css_parse/traits/
parse.rs

1use crate::{Parser, Peek, Result};
2use bumpalo::collections::Vec;
3
4/// This trait allows AST nodes to construct themselves from a mutable [Parser] instance.
5///
6/// Nodes that implement this trait are entitled to consume any number of [Cursors][crate::Cursor] from [Parser] in
7/// order to construct themselves. They may also consume some amount of tokens and still return an [Err] - there is no
8/// need to try and reset the [Parser] state on failure ([Parser::try_parse()] exists for this reason).
9///
10/// When wanting to parse child nodes, implementations should _not_ call [Parse::parse()] directly. Instead - call
11/// [`Parser::parse<T>()`]. Other convenience methods such as [`Parser::parse_if_peek<T>()`] and [`Parser::try_parse<T>()`]
12/// exist.
13///
14/// Any node implementing [Parse::parse()] gets [Parse::try_parse()] for free. It's unlikely that nodes can come up with
15/// a more efficient algorithm than the provided one, so it is not worth re-implementing [Parse::try_parse()].
16///
17/// If a Node can construct itself from a single [Cursor][crate::Cursor] it should implement
18/// [Peek][crate::Peek] and [Parse], where [Parse::parse()] calls [Parser::next()] and constructs from the cursor.
19pub trait Parse<'a>: Sized {
20	fn parse(p: &mut Parser<'a>) -> Result<Self>;
21
22	fn try_parse(p: &mut Parser<'a>) -> Result<Self> {
23		let checkpoint = p.checkpoint();
24		Self::parse(p).inspect_err(|_| p.rewind(checkpoint))
25	}
26}
27
28impl<'a, T> Parse<'a> for Option<T>
29where
30	T: Peek<'a> + Parse<'a>,
31{
32	fn parse(p: &mut Parser<'a>) -> Result<Self> {
33		p.parse_if_peek::<T>()
34	}
35}
36
37impl<'a, T> Parse<'a> for Vec<'a, T>
38where
39	T: Peek<'a> + Parse<'a>,
40{
41	fn parse(p: &mut Parser<'a>) -> Result<Self> {
42		let mut vec = Vec::new_in(p.bump());
43		while let Some(item) = p.parse_if_peek::<T>()? {
44			vec.push(item);
45		}
46		Ok(vec)
47	}
48}
49
50macro_rules! impl_tuple {
51    ($($T:ident),*) => {
52        impl<'a, $($T),*> Parse<'a> for ($($T),*)
53        where
54            $($T: Parse<'a>),*
55        {
56            #[allow(non_snake_case)]
57            #[allow(unused)]
58            fn parse(p: &mut Parser<'a>) -> Result<Self> {
59                $(let $T = p.parse::<$T>()?;)*
60                Ok(($($T),*))
61            }
62        }
63    };
64}
65
66impl_tuple!(A, B);
67impl_tuple!(A, B, C);
68impl_tuple!(A, B, C, D);
69impl_tuple!(A, B, C, D, E);
70impl_tuple!(A, B, C, D, E, F);
71impl_tuple!(A, B, C, D, E, F, G);
72impl_tuple!(A, B, C, D, E, F, G, H);
73impl_tuple!(A, B, C, D, E, F, G, H, I);
74impl_tuple!(A, B, C, D, E, F, G, H, I, J);
75impl_tuple!(A, B, C, D, E, F, G, H, I, J, K);
76impl_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);