parser.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. use crate::{pkg_length::PkgLength, AmlContext, AmlError, DebugVerbosity};
  2. use alloc::vec::Vec;
  3. use core::marker::PhantomData;
  4. use log::trace;
  5. /// This is the number of spaces added to indent a scope when printing parser debug messages.
  6. pub const INDENT_PER_SCOPE: usize = 2;
  7. impl AmlContext {
  8. /// This is used by the parser to provide debug comments about the current object, which are indented to the
  9. /// correct level for the current object. We most often need to print these comments from `map_with_context`s,
  10. /// so it's most convenient to have this method on `AmlContext`.
  11. pub(crate) fn comment(&self, verbosity: DebugVerbosity, message: &str) {
  12. if verbosity <= self.debug_verbosity {
  13. log::trace!("{:indent$}{}", "", message, indent = self.scope_indent);
  14. }
  15. }
  16. }
  17. pub type ParseResult<'a, 'c, R> =
  18. Result<(&'a [u8], &'c mut AmlContext, R), (&'a [u8], &'c mut AmlContext, AmlError)>;
  19. pub trait Parser<'a, 'c, R>: Sized
  20. where
  21. 'c: 'a,
  22. {
  23. fn parse(&self, input: &'a [u8], context: &'c mut AmlContext) -> ParseResult<'a, 'c, R>;
  24. fn map<F, A>(self, map_fn: F) -> Map<'a, 'c, Self, F, R, A>
  25. where
  26. F: Fn(R) -> Result<A, AmlError>,
  27. {
  28. Map { parser: self, map_fn, _phantom: PhantomData }
  29. }
  30. fn map_with_context<F, A>(self, map_fn: F) -> MapWithContext<'a, 'c, Self, F, R, A>
  31. where
  32. F: Fn(R, &'c mut AmlContext) -> (Result<A, AmlError>, &'c mut AmlContext),
  33. {
  34. MapWithContext { parser: self, map_fn, _phantom: PhantomData }
  35. }
  36. fn discard_result(self) -> DiscardResult<'a, 'c, Self, R> {
  37. DiscardResult { parser: self, _phantom: PhantomData }
  38. }
  39. /// Try parsing with `self`. If it succeeds, return its result. If it returns `AmlError::WrongParser`, try
  40. /// parsing with `other`, returning the result of that parser in all cases. Other errors from the first
  41. /// parser are propagated without attempting the second parser. To chain more than two parsers using
  42. /// `or`, see the `choice!` macro.
  43. fn or<OtherParser>(self, other: OtherParser) -> Or<'a, 'c, Self, OtherParser, R>
  44. where
  45. OtherParser: Parser<'a, 'c, R>,
  46. {
  47. Or { p1: self, p2: other, _phantom: PhantomData }
  48. }
  49. fn then<NextParser, NextR>(self, next: NextParser) -> Then<'a, 'c, Self, NextParser, R, NextR>
  50. where
  51. NextParser: Parser<'a, 'c, NextR>,
  52. {
  53. Then { p1: self, p2: next, _phantom: PhantomData }
  54. }
  55. /// `feed` takes a function that takes the result of this parser (`self`) and creates another
  56. /// parser, which is then used to parse the next part of the stream. This sounds convoluted,
  57. /// but is useful for when the next parser's behaviour depends on a property of the result of
  58. /// the first (e.g. the first parser might parse a length `n`, and the second parser then
  59. /// consumes `n` bytes).
  60. fn feed<F, P2, R2>(self, producer_fn: F) -> Feed<'a, 'c, Self, P2, F, R, R2>
  61. where
  62. P2: Parser<'a, 'c, R2>,
  63. F: Fn(R) -> P2,
  64. {
  65. Feed { parser: self, producer_fn, _phantom: PhantomData }
  66. }
  67. }
  68. impl<'a, 'c, F, R> Parser<'a, 'c, R> for F
  69. where
  70. 'c: 'a,
  71. F: Fn(&'a [u8], &'c mut AmlContext) -> ParseResult<'a, 'c, R>,
  72. {
  73. fn parse(&self, input: &'a [u8], context: &'c mut AmlContext) -> ParseResult<'a, 'c, R> {
  74. self(input, context)
  75. }
  76. }
  77. /// The identity parser - returns the stream and context unchanged. Useful for producing parsers
  78. /// that produce a result without parsing anything by doing: `id().map(|()| Ok(foo))`.
  79. pub fn id<'a, 'c>() -> impl Parser<'a, 'c, ()>
  80. where
  81. 'c: 'a,
  82. {
  83. move |input: &'a [u8], context: &'c mut AmlContext| Ok((input, context, ()))
  84. }
  85. pub fn take<'a, 'c>() -> impl Parser<'a, 'c, u8>
  86. where
  87. 'c: 'a,
  88. {
  89. move |input: &'a [u8], context: &'c mut AmlContext| match input.first() {
  90. Some(&byte) => Ok((&input[1..], context, byte)),
  91. None => Err((input, context, AmlError::UnexpectedEndOfStream)),
  92. }
  93. }
  94. pub fn take_u16<'a, 'c>() -> impl Parser<'a, 'c, u16>
  95. where
  96. 'c: 'a,
  97. {
  98. move |input: &'a [u8], context: &'c mut AmlContext| {
  99. if input.len() < 2 {
  100. return Err((input, context, AmlError::UnexpectedEndOfStream));
  101. }
  102. Ok((&input[2..], context, input[0] as u16 + ((input[1] as u16) << 8)))
  103. }
  104. }
  105. pub fn take_u32<'a, 'c>() -> impl Parser<'a, 'c, u32>
  106. where
  107. 'c: 'a,
  108. {
  109. move |input: &'a [u8], context: &'c mut AmlContext| {
  110. if input.len() < 4 {
  111. return Err((input, context, AmlError::UnexpectedEndOfStream));
  112. }
  113. Ok((
  114. &input[4..],
  115. context,
  116. input[0] as u32 + ((input[1] as u32) << 8) + ((input[2] as u32) << 16) + ((input[3] as u32) << 24),
  117. ))
  118. }
  119. }
  120. pub fn take_u64<'a, 'c>() -> impl Parser<'a, 'c, u64>
  121. where
  122. 'c: 'a,
  123. {
  124. move |input: &'a [u8], context: &'c mut AmlContext| {
  125. if input.len() < 8 {
  126. return Err((input, context, AmlError::UnexpectedEndOfStream));
  127. }
  128. Ok((
  129. &input[8..],
  130. context,
  131. input[0] as u64
  132. + ((input[1] as u64) << 8)
  133. + ((input[2] as u64) << 16)
  134. + ((input[3] as u64) << 24)
  135. + ((input[4] as u64) << 32)
  136. + ((input[5] as u64) << 40)
  137. + ((input[6] as u64) << 48)
  138. + ((input[7] as u64) << 56),
  139. ))
  140. }
  141. }
  142. pub fn take_n<'a, 'c>(n: u32) -> impl Parser<'a, 'c, &'a [u8]>
  143. where
  144. 'c: 'a,
  145. {
  146. move |input: &'a [u8], context| {
  147. if (input.len() as u32) < n {
  148. return Err((input, context, AmlError::UnexpectedEndOfStream));
  149. }
  150. let (result, new_input) = input.split_at(n as usize);
  151. Ok((new_input, context, result))
  152. }
  153. }
  154. pub fn take_to_end_of_pkglength<'a, 'c>(length: PkgLength) -> impl Parser<'a, 'c, &'a [u8]>
  155. where
  156. 'c: 'a,
  157. {
  158. move |input: &'a [u8], context| {
  159. let bytes_to_take = (input.len() as u32) - length.end_offset;
  160. take_n(bytes_to_take).parse(input, context)
  161. }
  162. }
  163. pub fn n_of<'a, 'c, P, R>(parser: P, n: usize) -> impl Parser<'a, 'c, Vec<R>>
  164. where
  165. 'c: 'a,
  166. P: Parser<'a, 'c, R>,
  167. {
  168. // TODO: can we write this more nicely?
  169. move |mut input, mut context| {
  170. let mut results = Vec::with_capacity(n);
  171. for _ in 0..n {
  172. let (new_input, new_context, result) = match parser.parse(input, context) {
  173. Ok((input, context, result)) => (input, context, result),
  174. Err((_, context, err)) => return Err((input, context, err)),
  175. };
  176. results.push(result);
  177. input = new_input;
  178. context = new_context;
  179. }
  180. Ok((input, context, results))
  181. }
  182. }
  183. pub fn take_while<'a, 'c, P, R>(parser: P) -> impl Parser<'a, 'c, usize>
  184. where
  185. 'c: 'a,
  186. P: Parser<'a, 'c, R>,
  187. {
  188. move |mut input: &'a [u8], mut context: &'c mut AmlContext| {
  189. let mut num_passed = 0;
  190. loop {
  191. match parser.parse(input, context) {
  192. Ok((new_input, new_context, _)) => {
  193. input = new_input;
  194. context = new_context;
  195. num_passed += 1;
  196. }
  197. Err((_, context, AmlError::WrongParser)) => return Ok((input, context, num_passed)),
  198. Err((_, context, err)) => return Err((input, context, err)),
  199. }
  200. }
  201. }
  202. }
  203. pub fn consume<'a, 'c, F>(condition: F) -> impl Parser<'a, 'c, u8>
  204. where
  205. 'c: 'a,
  206. F: Fn(u8) -> bool,
  207. {
  208. move |input: &'a [u8], context: &'c mut AmlContext| match input.first() {
  209. Some(&byte) if condition(byte) => Ok((&input[1..], context, byte)),
  210. Some(&byte) => Err((input, context, AmlError::UnexpectedByte(byte))),
  211. None => Err((input, context, AmlError::UnexpectedEndOfStream)),
  212. }
  213. }
  214. pub fn comment_scope<'a, 'c, P, R>(
  215. verbosity: DebugVerbosity,
  216. scope_name: &'a str,
  217. parser: P,
  218. ) -> impl Parser<'a, 'c, R>
  219. where
  220. 'c: 'a,
  221. R: core::fmt::Debug,
  222. P: Parser<'a, 'c, R>,
  223. {
  224. move |input, context: &'c mut AmlContext| {
  225. if verbosity <= context.debug_verbosity {
  226. trace!("{:indent$}--> {}", "", scope_name, indent = context.scope_indent);
  227. context.scope_indent += INDENT_PER_SCOPE;
  228. }
  229. // Return if the parse fails, so we don't print the tail. Makes it easier to debug.
  230. let (new_input, context, result) = parser.parse(input, context)?;
  231. if verbosity <= context.debug_verbosity {
  232. context.scope_indent -= INDENT_PER_SCOPE;
  233. trace!("{:indent$}<-- {}", "", scope_name, indent = context.scope_indent);
  234. }
  235. Ok((new_input, context, result))
  236. }
  237. }
  238. pub struct Or<'a, 'c, P1, P2, R>
  239. where
  240. 'c: 'a,
  241. P1: Parser<'a, 'c, R>,
  242. P2: Parser<'a, 'c, R>,
  243. {
  244. p1: P1,
  245. p2: P2,
  246. _phantom: PhantomData<(&'a R, &'c ())>,
  247. }
  248. impl<'a, 'c, P1, P2, R> Parser<'a, 'c, R> for Or<'a, 'c, P1, P2, R>
  249. where
  250. 'c: 'a,
  251. P1: Parser<'a, 'c, R>,
  252. P2: Parser<'a, 'c, R>,
  253. {
  254. fn parse(&self, input: &'a [u8], context: &'c mut AmlContext) -> ParseResult<'a, 'c, R> {
  255. match self.p1.parse(input, context) {
  256. Ok(parse_result) => Ok(parse_result),
  257. Err((_, context, AmlError::WrongParser)) => self.p2.parse(input, context),
  258. Err((_, context, err)) => Err((input, context, err)),
  259. }
  260. }
  261. }
  262. pub struct Map<'a, 'c, P, F, R, A>
  263. where
  264. 'c: 'a,
  265. P: Parser<'a, 'c, R>,
  266. F: Fn(R) -> Result<A, AmlError>,
  267. {
  268. parser: P,
  269. map_fn: F,
  270. _phantom: PhantomData<(&'a (R, A), &'c ())>,
  271. }
  272. impl<'a, 'c, P, F, R, A> Parser<'a, 'c, A> for Map<'a, 'c, P, F, R, A>
  273. where
  274. 'c: 'a,
  275. P: Parser<'a, 'c, R>,
  276. F: Fn(R) -> Result<A, AmlError>,
  277. {
  278. fn parse(&self, input: &'a [u8], context: &'c mut AmlContext) -> ParseResult<'a, 'c, A> {
  279. match self.parser.parse(input, context) {
  280. Ok((new_input, context, result)) => match (self.map_fn)(result) {
  281. Ok(result_value) => Ok((new_input, context, result_value)),
  282. Err(err) => Err((input, context, err)),
  283. },
  284. Err(result) => Err(result),
  285. }
  286. }
  287. }
  288. pub struct MapWithContext<'a, 'c, P, F, R, A>
  289. where
  290. 'c: 'a,
  291. P: Parser<'a, 'c, R>,
  292. F: Fn(R, &'c mut AmlContext) -> (Result<A, AmlError>, &'c mut AmlContext),
  293. {
  294. parser: P,
  295. map_fn: F,
  296. _phantom: PhantomData<(&'a (R, A), &'c ())>,
  297. }
  298. impl<'a, 'c, P, F, R, A> Parser<'a, 'c, A> for MapWithContext<'a, 'c, P, F, R, A>
  299. where
  300. 'c: 'a,
  301. P: Parser<'a, 'c, R>,
  302. F: Fn(R, &'c mut AmlContext) -> (Result<A, AmlError>, &'c mut AmlContext),
  303. {
  304. fn parse(&self, input: &'a [u8], context: &'c mut AmlContext) -> ParseResult<'a, 'c, A> {
  305. match self.parser.parse(input, context) {
  306. Ok((new_input, context, result)) => match (self.map_fn)(result, context) {
  307. (Ok(result_value), context) => Ok((new_input, context, result_value)),
  308. (Err(err), context) => Err((input, context, err)),
  309. },
  310. Err(result) => Err(result),
  311. }
  312. }
  313. }
  314. pub struct DiscardResult<'a, 'c, P, R>
  315. where
  316. 'c: 'a,
  317. P: Parser<'a, 'c, R>,
  318. {
  319. parser: P,
  320. _phantom: PhantomData<(&'a R, &'c ())>,
  321. }
  322. impl<'a, 'c, P, R> Parser<'a, 'c, ()> for DiscardResult<'a, 'c, P, R>
  323. where
  324. 'c: 'a,
  325. P: Parser<'a, 'c, R>,
  326. {
  327. fn parse(&self, input: &'a [u8], context: &'c mut AmlContext) -> ParseResult<'a, 'c, ()> {
  328. self.parser.parse(input, context).map(|(new_input, new_context, _)| (new_input, new_context, ()))
  329. }
  330. }
  331. pub struct Then<'a, 'c, P1, P2, R1, R2>
  332. where
  333. 'c: 'a,
  334. P1: Parser<'a, 'c, R1>,
  335. P2: Parser<'a, 'c, R2>,
  336. {
  337. p1: P1,
  338. p2: P2,
  339. _phantom: PhantomData<(&'a (R1, R2), &'c ())>,
  340. }
  341. impl<'a, 'c, P1, P2, R1, R2> Parser<'a, 'c, (R1, R2)> for Then<'a, 'c, P1, P2, R1, R2>
  342. where
  343. 'c: 'a,
  344. P1: Parser<'a, 'c, R1>,
  345. P2: Parser<'a, 'c, R2>,
  346. {
  347. fn parse(&self, input: &'a [u8], context: &'c mut AmlContext) -> ParseResult<'a, 'c, (R1, R2)> {
  348. self.p1.parse(input, context).and_then(|(next_input, context, result_a)| {
  349. self.p2
  350. .parse(next_input, context)
  351. .map(|(final_input, context, result_b)| (final_input, context, (result_a, result_b)))
  352. })
  353. }
  354. }
  355. pub struct Feed<'a, 'c, P1, P2, F, R1, R2>
  356. where
  357. 'c: 'a,
  358. P1: Parser<'a, 'c, R1>,
  359. P2: Parser<'a, 'c, R2>,
  360. F: Fn(R1) -> P2,
  361. {
  362. parser: P1,
  363. producer_fn: F,
  364. _phantom: PhantomData<(&'a (R1, R2), &'c ())>,
  365. }
  366. impl<'a, 'c, P1, P2, F, R1, R2> Parser<'a, 'c, R2> for Feed<'a, 'c, P1, P2, F, R1, R2>
  367. where
  368. 'c: 'a,
  369. P1: Parser<'a, 'c, R1>,
  370. P2: Parser<'a, 'c, R2>,
  371. F: Fn(R1) -> P2,
  372. {
  373. fn parse(&self, input: &'a [u8], context: &'c mut AmlContext) -> ParseResult<'a, 'c, R2> {
  374. let (input, context, first_result) = self.parser.parse(input, context)?;
  375. // We can now produce the second parser, and parse using that.
  376. let second_parser = (self.producer_fn)(first_result);
  377. second_parser.parse(input, context)
  378. }
  379. }
  380. /// Takes a number of parsers, and tries to apply each one to the input in order. Returns the
  381. /// result of the first one that succeeds, or fails if all of them fail.
  382. pub(crate) macro choice {
  383. () => {
  384. id().map(|()| Err(AmlError::WrongParser))
  385. },
  386. ($first_parser: expr) => {
  387. $first_parser
  388. .or(id().map(|()| Err(AmlError::WrongParser)))
  389. },
  390. ($first_parser: expr, $($other_parser: expr),*) => {
  391. $first_parser
  392. $(
  393. .or($other_parser)
  394. )*
  395. .or(id().map(|()| Err(AmlError::WrongParser)))
  396. }
  397. }
  398. /// This encapsulates an unfortunate hack we sometimes need to use, where the type checker gets
  399. /// caught in an infinite loop of parser types. This occurs when an object can indirectly contain
  400. /// itself, and so the parser type will contain its own type. This works by breaking the cycle of
  401. /// `impl Parser` chains that build up, by effectively creating a "concrete" closure type.
  402. ///
  403. /// You can try using this hack if you are writing a parser and end up with an error of the form:
  404. /// `error[E0275]: overflow evaluating the requirement 'impl Parser<{a type}>'
  405. /// help: consider adding a a '#![recursion_limit="128"] attribute to your crate`
  406. /// Note: Increasing the recursion limit will not fix the issue, as the cycle will just continue
  407. /// until you either hit the new recursion limit or `rustc` overflows its stack.
  408. pub(crate) macro make_parser_concrete($parser: expr) {
  409. |input, context| ($parser).parse(input, context)
  410. }
  411. /// Helper macro for use within `map_with_context` as an alternative to "trying" an expression.
  412. ///
  413. /// ### Example
  414. /// Problem: `expr?` won't work because the expected return type is `(Result<R, AmlError>, &mut AmlContext)`
  415. /// Solution: use `try_with_context!(context, expr)` instead.
  416. pub(crate) macro try_with_context($context: expr, $expr: expr) {
  417. match $expr {
  418. Ok(result) => result,
  419. Err(err) => return (Err(err), $context),
  420. }
  421. }
  422. #[cfg(test)]
  423. mod tests {
  424. use super::*;
  425. use crate::{test_utils::*, DebugVerbosity};
  426. #[test]
  427. fn test_take_n() {
  428. let mut context = AmlContext::new(false, DebugVerbosity::None);
  429. check_err!(take_n(1).parse(&[], &mut context), AmlError::UnexpectedEndOfStream, &[]);
  430. check_err!(take_n(2).parse(&[0xf5], &mut context), AmlError::UnexpectedEndOfStream, &[0xf5]);
  431. check_ok!(take_n(1).parse(&[0xff], &mut context), &[0xff], &[]);
  432. check_ok!(take_n(1).parse(&[0xff, 0xf8], &mut context), &[0xff], &[0xf8]);
  433. check_ok!(take_n(2).parse(&[0xff, 0xf8], &mut context), &[0xff, 0xf8], &[]);
  434. }
  435. #[test]
  436. fn test_take_ux() {
  437. let mut context = AmlContext::new(false, DebugVerbosity::None);
  438. check_err!(take_u16().parse(&[0x34], &mut context), AmlError::UnexpectedEndOfStream, &[0x34]);
  439. check_ok!(take_u16().parse(&[0x34, 0x12], &mut context), 0x1234, &[]);
  440. check_err!(take_u32().parse(&[0x34, 0x12], &mut context), AmlError::UnexpectedEndOfStream, &[0x34, 0x12]);
  441. check_ok!(take_u32().parse(&[0x34, 0x12, 0xf4, 0xc3, 0x3e], &mut context), 0xc3f41234, &[0x3e]);
  442. check_err!(take_u64().parse(&[0x34], &mut context), AmlError::UnexpectedEndOfStream, &[0x34]);
  443. check_ok!(
  444. take_u64().parse(&[0x34, 0x12, 0x35, 0x76, 0xd4, 0x43, 0xa3, 0xb6, 0xff, 0x00], &mut context),
  445. 0xb6a343d476351234,
  446. &[0xff, 0x00]
  447. );
  448. }
  449. }