parser.rs 15 KB

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