syntax_rs/
macros.rs

1#[macro_export]
2macro_rules! simple_tok {
3    ($ident:ident, $str:literal) => {
4        #[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
5        struct $ident;
6
7        impl $crate::parse::Parse for $ident {
8            fn parse(stream: &mut $crate::parse::ParseStream) -> $crate::Result<$ident> {
9                match stream.cur().peek_n($str.len()) {
10                    Some(array) => {
11                        if array == $str {
12                            // TODO: This can be optimized
13                            stream.cur().advance_n($str.len());
14                            Ok($ident)
15                        } else {
16                            Err($crate::concat_all!("Expected `", $str, "`."))
17                        }
18                    }
19                    None => Err($crate::concat_all!("Found EOF but expected `", $str, "`.")),
20                }
21            }
22        }
23    };
24}
25
26#[macro_export]
27macro_rules! spanned_field {
28    ($field:ident,$name:ident) => {
29        impl $crate::Spanned for $name {
30            fn span(&self) -> $crate::Span {
31                self.$field
32            }
33
34            fn span_ref_mut(&mut self) -> &mut $crate::Span {
35                &mut self.$field
36            }
37        }
38    };
39}
40
41#[macro_export]
42macro_rules! simple_tok_spanned {
43    ($ident:ident, $str:literal) => {
44        cfg_if::cfg_if! {
45            if #[cfg(feature = "span")] {
46                #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
47                struct $ident {
48                    span: $crate::Span
49                }
50                $crate::spanned_field!(span,$ident);
51
52                impl $crate::parse::Parse for $ident {
53                    fn parse(stream: &mut $crate::parse::ParseStream) -> $crate::Result<$ident> {
54                        let index = stream.cur().index();
55                        match stream.cur().peek_n($str.len()) {
56                            Some(array) => if array == $str {
57                                stream.cur().advance_n($str.len());
58                                Ok($ident { span: $crate::Span { begin: index, end: stream.cur().index() } })
59                            } else {
60                                Err($crate::concat_all!("Expected `", $str, "`."))
61                            },
62                            None => Err($crate::concat_all!("Found EOF but expected `", $str, "`.")),
63                        }
64                    }
65                }
66            } else {
67                $crate::simple_tok!($ident,$str);
68            }
69        }
70    };
71}
72
73#[macro_export]
74macro_rules! concat_all {
75    ($val:literal,$($rest:literal),+) => {
76        concat!($val, $crate::concat_all!($($rest),+))
77    };
78    ($single:literal) => {
79        $single
80    };
81}