parser.rs 15 KB

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