rune/ast/
macro_utils.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use super::prelude::*;
use super::Eq;

/// An `= ...` e.g. inside an attribute `#[doc = ...]`.
///
/// To get unparsed tokens use `EqValue<TokenStream>`.
#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Parse, Spanned)]
#[try_clone(bound = {T: TryClone})]
pub struct EqValue<T> {
    /// The `=` token.
    pub eq: Eq,
    /// The remainder.
    pub value: T,
}

/// Parses `[{( ... )}]` ensuring that the delimiter is balanced.
#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Spanned)]
pub struct Group {
    /// The opening delimiter.
    pub open: ast::Token,
    /// The content between the delimiters.
    #[rune(iter)]
    pub content: TokenStream,
    /// The closing delimiter.
    pub close: ast::Token,
}

impl Parse for Group {
    fn parse(parser: &mut Parser<'_>) -> compile::Result<Self> {
        let mut level = 1;
        let open = parser.next()?;

        let delim = match open.kind {
            ast::Kind::Open(delim) => delim,
            _ => {
                return Err(compile::Error::expected(open, Expectation::OpenDelimiter));
            }
        };

        let close;

        let mut stream = Vec::new();

        loop {
            let token = parser.next()?;

            match token.kind {
                ast::Kind::Open(..) => level += 1,
                ast::Kind::Close(actual) => {
                    level -= 1;

                    if level == 0 {
                        if actual != delim {
                            return Err(compile::Error::new(
                                open,
                                ErrorKind::ExpectedMacroCloseDelimiter {
                                    actual: token.kind,
                                    expected: ast::Kind::Close(delim),
                                },
                            ));
                        }

                        close = token;
                        break;
                    }
                }
                _ => (),
            }

            stream.try_push(token)?;
        }

        Ok(Self {
            open,
            content: TokenStream::from(stream),
            close,
        })
    }
}