parser.rs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. use crate::AmlError;
  2. use alloc::vec::Vec;
  3. use core::marker::PhantomData;
  4. use log::trace;
  5. pub type ParseResult<'a, R> = Result<(&'a [u8], R), (&'a [u8], AmlError)>;
  6. pub trait Parser<'a, R>: Sized {
  7. fn parse(&self, input: &'a [u8]) -> ParseResult<'a, R>;
  8. fn map<F, A>(self, map_fn: F) -> Map<'a, Self, F, R, A>
  9. where
  10. F: Fn(R) -> A,
  11. {
  12. Map { parser: self, map_fn, _phantom: PhantomData }
  13. }
  14. fn discard_result(self) -> DiscardResult<'a, Self, R> {
  15. DiscardResult { parser: self, _phantom: PhantomData }
  16. }
  17. /// Try parsing with `self`. If it fails, try parsing with `other`, returning the result of the
  18. /// first of the two parsers to succeed. To `or` multiple parsers ergonomically, see the
  19. /// `choice!` macro.
  20. fn or<OtherParser>(self, other: OtherParser) -> Or<'a, Self, OtherParser, R>
  21. where
  22. OtherParser: Parser<'a, R>,
  23. {
  24. Or { p1: self, p2: other, _phantom: PhantomData }
  25. }
  26. fn then<NextParser, NextR>(self, next: NextParser) -> Then<'a, Self, NextParser, R, NextR>
  27. where
  28. NextParser: Parser<'a, NextR>,
  29. {
  30. Then { p1: self, p2: next, _phantom: PhantomData }
  31. }
  32. /// `feed` takes a function that takes the result of this parser (`self`) and creates another
  33. /// parser, which is then used to parse the next part of the stream. This sounds convoluted,
  34. /// but is useful for when the next parser's behaviour depends on a property of the result of
  35. /// the first (e.g. the first parser might parse a length `n`, and the second parser then
  36. /// consumes `n` bytes).
  37. fn feed<F, P2, R2>(self, producer_fn: F) -> Feed<'a, Self, P2, F, R, R2>
  38. where
  39. P2: Parser<'a, R2>,
  40. F: Fn(R) -> P2,
  41. {
  42. Feed { parser: self, producer_fn, _phantom: PhantomData }
  43. }
  44. }
  45. impl<'a, F, R> Parser<'a, R> for F
  46. where
  47. F: Fn(&'a [u8]) -> ParseResult<'a, R>,
  48. {
  49. fn parse(&self, input: &'a [u8]) -> ParseResult<'a, R> {
  50. self(input)
  51. }
  52. }
  53. pub fn take<'a>() -> impl Parser<'a, u8> {
  54. move |input: &'a [u8]| match input.first() {
  55. Some(&byte) => Ok((&input[1..], byte)),
  56. None => Err((input, AmlError::UnexpectedEndOfStream)),
  57. }
  58. }
  59. pub fn take_u16<'a>() -> impl Parser<'a, u16> {
  60. move |input: &'a [u8]| {
  61. if input.len() < 2 {
  62. return Err((input, AmlError::UnexpectedEndOfStream));
  63. }
  64. Ok((&input[2..], input[0] as u16 + ((input[1] as u16) << 8)))
  65. }
  66. }
  67. pub fn take_u32<'a>() -> impl Parser<'a, u32> {
  68. move |input: &'a [u8]| {
  69. if input.len() < 4 {
  70. return Err((input, AmlError::UnexpectedEndOfStream));
  71. }
  72. Ok((
  73. &input[4..],
  74. input[0] as u32
  75. + ((input[1] as u32) << 8)
  76. + ((input[2] as u32) << 16)
  77. + ((input[3] as u32) << 24),
  78. ))
  79. }
  80. }
  81. pub fn take_u64<'a>() -> impl Parser<'a, u64> {
  82. move |input: &'a [u8]| {
  83. if input.len() < 8 {
  84. return Err((input, AmlError::UnexpectedEndOfStream));
  85. }
  86. Ok((
  87. &input[8..],
  88. input[0] as u64
  89. + ((input[1] as u64) << 8)
  90. + ((input[2] as u64) << 16)
  91. + ((input[3] as u64) << 24)
  92. + ((input[4] as u64) << 32)
  93. + ((input[5] as u64) << 40)
  94. + ((input[6] as u64) << 48)
  95. + ((input[7] as u64) << 56),
  96. ))
  97. }
  98. }
  99. pub fn take_n<'a>(n: usize) -> impl Parser<'a, &'a [u8]> {
  100. move |input: &'a [u8]| {
  101. if input.len() < n {
  102. return Err((input, AmlError::UnexpectedEndOfStream));
  103. }
  104. let (result, new_input) = input.split_at(n);
  105. Ok((new_input, result))
  106. }
  107. }
  108. // TODO: can we use const generics (e.g. [R; N]) to avoid allocating?
  109. pub fn n_of<'a, P, R>(parser: P, n: usize) -> impl Parser<'a, Vec<R>>
  110. where
  111. P: Parser<'a, R>,
  112. {
  113. move |input| {
  114. let mut results = Vec::with_capacity(n);
  115. let mut new_input = input;
  116. for _ in 0..n {
  117. let (after_input, result) = match parser.parse(new_input) {
  118. Ok((input, result)) => (input, result),
  119. Err((_, err)) => return Err((input, err)),
  120. };
  121. results.push(result);
  122. new_input = after_input;
  123. }
  124. Ok((new_input, results))
  125. }
  126. }
  127. pub fn consume<'a, F>(condition: F) -> impl Parser<'a, u8>
  128. where
  129. F: Fn(u8) -> bool,
  130. {
  131. move |input: &'a [u8]| match input.first() {
  132. Some(&byte) if condition(byte) => Ok((&input[1..], byte)),
  133. Some(&byte) => Err((input, AmlError::UnexpectedByte(byte))),
  134. None => Err((input, AmlError::UnexpectedEndOfStream)),
  135. }
  136. }
  137. pub fn comment_scope<'a, P, R>(scope_name: &'a str, parser: P) -> impl Parser<'a, R>
  138. where
  139. R: core::fmt::Debug,
  140. P: Parser<'a, R>,
  141. {
  142. move |input| {
  143. trace!("--> {}", scope_name);
  144. // Return if the parse fails, so we don't print the tail. Makes it easier to debug.
  145. let (new_input, result) = parser.parse(input)?;
  146. trace!("<-- {}({:?})", scope_name, result);
  147. Ok((new_input, result))
  148. }
  149. }
  150. pub struct Or<'a, P1, P2, R>
  151. where
  152. P1: Parser<'a, R>,
  153. P2: Parser<'a, R>,
  154. {
  155. p1: P1,
  156. p2: P2,
  157. _phantom: PhantomData<&'a R>,
  158. }
  159. impl<'a, P1, P2, R> Parser<'a, R> for Or<'a, P1, P2, R>
  160. where
  161. P1: Parser<'a, R>,
  162. P2: Parser<'a, R>,
  163. {
  164. fn parse(&self, input: &'a [u8]) -> ParseResult<'a, R> {
  165. match self.p1.parse(input) {
  166. Ok(result) => return Ok(result),
  167. Err(_) => (),
  168. }
  169. self.p2.parse(input)
  170. }
  171. }
  172. pub struct Map<'a, P, F, R, A>
  173. where
  174. P: Parser<'a, R>,
  175. F: Fn(R) -> A,
  176. {
  177. parser: P,
  178. map_fn: F,
  179. _phantom: PhantomData<&'a (R, A)>,
  180. }
  181. impl<'a, P, F, R, A> Parser<'a, A> for Map<'a, P, F, R, A>
  182. where
  183. P: Parser<'a, R>,
  184. F: Fn(R) -> A,
  185. {
  186. fn parse(&self, input: &'a [u8]) -> ParseResult<'a, A> {
  187. self.parser.parse(input).map(|(new_input, result)| (new_input, (self.map_fn)(result)))
  188. }
  189. }
  190. pub struct DiscardResult<'a, P, R>
  191. where
  192. P: Parser<'a, R>,
  193. {
  194. parser: P,
  195. _phantom: PhantomData<&'a R>,
  196. }
  197. impl<'a, P, R> Parser<'a, ()> for DiscardResult<'a, P, R>
  198. where
  199. P: Parser<'a, R>,
  200. {
  201. fn parse(&self, input: &'a [u8]) -> ParseResult<'a, ()> {
  202. self.parser.parse(input).map(|(new_input, _)| (new_input, ()))
  203. }
  204. }
  205. pub struct Then<'a, P1, P2, R1, R2>
  206. where
  207. P1: Parser<'a, R1>,
  208. P2: Parser<'a, R2>,
  209. {
  210. p1: P1,
  211. p2: P2,
  212. _phantom: PhantomData<&'a (R1, R2)>,
  213. }
  214. impl<'a, P1, P2, R1, R2> Parser<'a, (R1, R2)> for Then<'a, P1, P2, R1, R2>
  215. where
  216. P1: Parser<'a, R1>,
  217. P2: Parser<'a, R2>,
  218. {
  219. fn parse(&self, input: &'a [u8]) -> ParseResult<'a, (R1, R2)> {
  220. self.p1.parse(input).and_then(|(next_input, result_a)| {
  221. self.p2
  222. .parse(next_input)
  223. .map(|(final_input, result_b)| (final_input, (result_a, result_b)))
  224. })
  225. }
  226. }
  227. pub struct Feed<'a, P1, P2, F, R1, R2>
  228. where
  229. P1: Parser<'a, R1>,
  230. P2: Parser<'a, R2>,
  231. F: Fn(R1) -> P2,
  232. {
  233. parser: P1,
  234. producer_fn: F,
  235. _phantom: PhantomData<&'a (R1, R2)>,
  236. }
  237. impl<'a, P1, P2, F, R1, R2> Parser<'a, R2> for Feed<'a, P1, P2, F, R1, R2>
  238. where
  239. P1: Parser<'a, R1>,
  240. P2: Parser<'a, R2>,
  241. F: Fn(R1) -> P2,
  242. {
  243. fn parse(&self, input: &'a [u8]) -> ParseResult<'a, R2> {
  244. let (input, first_result) = self.parser.parse(input)?;
  245. // We can now produce the second parser, and parse using that.
  246. let second_parser = (self.producer_fn)(first_result);
  247. second_parser.parse(input)
  248. }
  249. }
  250. /// Takes a number of parsers, and tries to apply each one to the input in order. Returns the
  251. /// result of the first one that succeeds, or fails if all of them fail.
  252. pub macro choice {
  253. ($first_parser: expr) => {
  254. $first_parser
  255. },
  256. ($first_parser: expr, $($other_parser: expr),*) => {
  257. $first_parser
  258. $(
  259. .or($other_parser)
  260. )*
  261. }
  262. }
  263. #[cfg(test)]
  264. mod tests {
  265. use super::*;
  266. use crate::test_utils::*;
  267. #[test]
  268. fn test_take_n() {
  269. check_err!(take_n(1).parse(&[]), AmlError::UnexpectedEndOfStream, &[]);
  270. check_err!(take_n(2).parse(&[0xf5]), AmlError::UnexpectedEndOfStream, &[0xf5]);
  271. check_ok!(take_n(1).parse(&[0xff]), &[0xff], &[]);
  272. check_ok!(take_n(1).parse(&[0xff, 0xf8]), &[0xff], &[0xf8]);
  273. check_ok!(take_n(2).parse(&[0xff, 0xf8]), &[0xff, 0xf8], &[]);
  274. }
  275. #[test]
  276. fn test_take_ux() {
  277. check_err!(take_u16().parse(&[0x34]), AmlError::UnexpectedEndOfStream, &[0x34]);
  278. check_ok!(take_u16().parse(&[0x34, 0x12]), 0x1234, &[]);
  279. check_err!(take_u32().parse(&[0x34, 0x12]), AmlError::UnexpectedEndOfStream, &[0x34, 0x12]);
  280. check_ok!(take_u32().parse(&[0x34, 0x12, 0xf4, 0xc3, 0x3e]), 0xc3f41234, &[0x3e]);
  281. check_err!(take_u64().parse(&[0x34]), AmlError::UnexpectedEndOfStream, &[0x34]);
  282. check_ok!(
  283. take_u64().parse(&[0x34, 0x12, 0x35, 0x76, 0xd4, 0x43, 0xa3, 0xb6, 0xff, 0x00]),
  284. 0xb6a343d476351234,
  285. &[0xff, 0x00]
  286. );
  287. }
  288. }