cas_parser/parser/token/
pair.rs

1use crate::{
2    parser::{
3        token::{
4            CloseParen,
5            OpenParen,
6            CloseCurly,
7            OpenCurly,
8            CloseSquare,
9            OpenSquare,
10        },
11        Parse,
12    },
13    tokenizer::TokenKind,
14};
15
16/// A trait for token kinds that have a logical pairing with another token kind. Only tokens that
17/// implement [`Pair`] can be used with the [`Surrounded`] helper.
18///
19/// This includes tokens like parentheses, square brackets, and curly braces.
20///
21/// [`Surrounded`]: crate::parser::ast::helper::surrounded::Surrounded
22pub trait Pair {
23    /// The type of the opening token, defined in the [`token`] module.
24    ///
25    /// [`token`]: crate::parser::token
26    type Open<'source>: Parse<'source>;
27
28    /// The type of the closing token, defined in the [`token`] module.
29    ///
30    /// [`token`]: crate::parser::token
31    type Close<'source>: Parse<'source>;
32
33    /// The corresponding opening [`TokenKind`].
34    const OPEN: TokenKind;
35
36    /// The corresponding closing [`TokenKind`].
37    const CLOSE: TokenKind;
38}
39
40/// Generates implementations of [`Pair`] for each pair of token kinds.
41macro_rules! pairs {
42    ($($open:ident $close:ident),* $(,)?) => {
43        $(
44            impl Pair for $open<'_> {
45                type Open<'source> = $open<'source>;
46                type Close<'source> = $close<'source>;
47                const OPEN: TokenKind = TokenKind::$open;
48                const CLOSE: TokenKind = TokenKind::$close;
49            }
50
51            impl Pair for $close<'_> {
52                type Open<'source> = $open<'source>;
53                type Close<'source> = $close<'source>;
54                const OPEN: TokenKind = TokenKind::$open;
55                const CLOSE: TokenKind = TokenKind::$close;
56            }
57        )*
58    }
59}
60
61pairs!(
62    OpenParen CloseParen,
63    OpenCurly CloseCurly,
64    OpenSquare CloseSquare,
65);