parser.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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.parse(input, context).map(|(new_input, new_context, _)| (new_input, new_context, ()))
  299. }
  300. }
  301. pub struct Then<'a, 'c, P1, P2, R1, R2>
  302. where
  303. 'c: 'a,
  304. P1: Parser<'a, 'c, R1>,
  305. P2: Parser<'a, 'c, R2>,
  306. {
  307. p1: P1,
  308. p2: P2,
  309. _phantom: PhantomData<(&'a (R1, R2), &'c ())>,
  310. }
  311. impl<'a, 'c, P1, P2, R1, R2> Parser<'a, 'c, (R1, R2)> for Then<'a, 'c, P1, P2, R1, R2>
  312. where
  313. 'c: 'a,
  314. P1: Parser<'a, 'c, R1>,
  315. P2: Parser<'a, 'c, R2>,
  316. {
  317. fn parse(&self, input: &'a [u8], context: &'c mut AmlContext) -> ParseResult<'a, 'c, (R1, R2)> {
  318. self.p1.parse(input, context).and_then(|(next_input, context, result_a)| {
  319. self.p2
  320. .parse(next_input, context)
  321. .map(|(final_input, context, result_b)| (final_input, context, (result_a, result_b)))
  322. })
  323. }
  324. }
  325. pub struct Feed<'a, 'c, P1, P2, F, R1, R2>
  326. where
  327. 'c: 'a,
  328. P1: Parser<'a, 'c, R1>,
  329. P2: Parser<'a, 'c, R2>,
  330. F: Fn(R1) -> P2,
  331. {
  332. parser: P1,
  333. producer_fn: F,
  334. _phantom: PhantomData<(&'a (R1, R2), &'c ())>,
  335. }
  336. impl<'a, 'c, P1, P2, F, R1, R2> Parser<'a, 'c, R2> for Feed<'a, 'c, P1, P2, F, R1, R2>
  337. where
  338. 'c: 'a,
  339. P1: Parser<'a, 'c, R1>,
  340. P2: Parser<'a, 'c, R2>,
  341. F: Fn(R1) -> P2,
  342. {
  343. fn parse(&self, input: &'a [u8], context: &'c mut AmlContext) -> ParseResult<'a, 'c, R2> {
  344. let (input, context, first_result) = self.parser.parse(input, context)?;
  345. // We can now produce the second parser, and parse using that.
  346. let second_parser = (self.producer_fn)(first_result);
  347. second_parser.parse(input, context)
  348. }
  349. }
  350. pub(crate) fn emit_no_parsers_could_parse<'a, 'c, R>() -> impl Parser<'a, 'c, R>
  351. where
  352. 'c: 'a,
  353. {
  354. |input: &'a [u8], context| Err((input, context, AmlError::NoParsersCouldParse))
  355. }
  356. /// Takes a number of parsers, and tries to apply each one to the input in order. Returns the
  357. /// result of the first one that succeeds, or fails if all of them fail.
  358. pub(crate) macro choice {
  359. ($first_parser: expr) => {
  360. $first_parser
  361. .or(emit_no_parsers_could_parse())
  362. },
  363. ($first_parser: expr, $($other_parser: expr),*) => {
  364. $first_parser
  365. $(
  366. .or($other_parser)
  367. )*
  368. .or(emit_no_parsers_could_parse())
  369. }
  370. }
  371. /// This encapsulates an unfortunate hack we sometimes need to use, where the type checker gets
  372. /// caught in an infinite loop of parser types. This occurs when an object can indirectly contain
  373. /// itself, and so the parser type will contain its own type. This works by breaking the cycle of
  374. /// `impl Parser` chains that build up, by effectively creating a "concrete" closure type.
  375. ///
  376. /// You can try using this hack if you are writing a parser and end up with an error of the form:
  377. /// `error[E0275]: overflow evaluating the requirement 'impl Parser<{a type}>'
  378. /// help: consider adding a a '#![recursion_limit="128"] attribute to your crate`
  379. /// Note: Increasing the recursion limit will not fix the issue, as the cycle will just continue
  380. /// until you either hit the new recursion limit or `rustc` overflows its stack.
  381. pub(crate) macro make_parser_concrete($parser: expr) {
  382. |input, context| ($parser).parse(input, context)
  383. }
  384. #[cfg(test)]
  385. mod tests {
  386. use super::*;
  387. use crate::test_utils::*;
  388. #[test]
  389. fn test_take_n() {
  390. let mut context = AmlContext::new();
  391. check_err!(take_n(1).parse(&[], &mut context), AmlError::UnexpectedEndOfStream, &[]);
  392. check_err!(take_n(2).parse(&[0xf5], &mut context), AmlError::UnexpectedEndOfStream, &[0xf5]);
  393. check_ok!(take_n(1).parse(&[0xff], &mut context), &[0xff], &[]);
  394. check_ok!(take_n(1).parse(&[0xff, 0xf8], &mut context), &[0xff], &[0xf8]);
  395. check_ok!(take_n(2).parse(&[0xff, 0xf8], &mut context), &[0xff, 0xf8], &[]);
  396. }
  397. #[test]
  398. fn test_take_ux() {
  399. let mut context = AmlContext::new();
  400. check_err!(take_u16().parse(&[0x34], &mut context), AmlError::UnexpectedEndOfStream, &[0x34]);
  401. check_ok!(take_u16().parse(&[0x34, 0x12], &mut context), 0x1234, &[]);
  402. check_err!(
  403. take_u32().parse(&[0x34, 0x12], &mut context),
  404. AmlError::UnexpectedEndOfStream,
  405. &[0x34, 0x12]
  406. );
  407. check_ok!(take_u32().parse(&[0x34, 0x12, 0xf4, 0xc3, 0x3e], &mut context), 0xc3f41234, &[0x3e]);
  408. check_err!(take_u64().parse(&[0x34], &mut context), AmlError::UnexpectedEndOfStream, &[0x34]);
  409. check_ok!(
  410. take_u64().parse(&[0x34, 0x12, 0x35, 0x76, 0xd4, 0x43, 0xa3, 0xb6, 0xff, 0x00], &mut context),
  411. 0xb6a343d476351234,
  412. &[0xff, 0x00]
  413. );
  414. }
  415. }