rune/ast/
block.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use crate::ast::prelude::*;

#[test]
#[cfg(not(miri))]
fn ast_parse() {
    let expr = rt::<ast::ExprBlock>("{}");
    assert_eq!(expr.block.statements.len(), 0);

    let expr = rt::<ast::ExprBlock>("{ 42 }");
    assert_eq!(expr.block.statements.len(), 1);

    let block = rt::<ast::Block>("{ foo }");
    assert_eq!(block.statements.len(), 1);

    let block = rt::<ast::Block>("{ foo; }");
    assert_eq!(block.statements.len(), 1);

    let expr = rt::<ast::ExprBlock>("#[retry] { 42 }");
    assert_eq!(expr.block.statements.len(), 1);
    assert_eq!(expr.attributes.len(), 1);

    let block = rt::<ast::Block>(
        r#"
        {
            let foo = 42;
            let bar = "string";
            baz
        }
    "#,
    );

    assert_eq!(block.statements.len(), 3);

    let block = rt::<ast::EmptyBlock>(
        r#"
        let foo = 42;
        let bar = "string";
        baz
        "#,
    );

    assert_eq!(block.statements.len(), 3);
}

/// A block of statements.
///
/// * `{ (<stmt>)* }`.
#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Spanned)]
#[non_exhaustive]
pub struct Block {
    /// The close brace.
    pub open: T!['{'],
    /// Statements in the block.
    #[rune(iter)]
    pub statements: Vec<ast::Stmt>,
    /// The close brace.
    pub close: T!['}'],
    /// The unique identifier for the block expression.
    #[rune(skip)]
    pub(crate) id: ItemId,
}

impl Parse for Block {
    fn parse(parser: &mut Parser<'_>) -> Result<Self> {
        let mut statements = Vec::new();

        let open = parser.parse()?;

        while !parser.peek::<T!['}']>()? {
            statements.try_push(parser.parse()?)?;
        }

        let close = parser.parse()?;

        Ok(Self {
            open,
            statements,
            close,
            id: ItemId::ROOT,
        })
    }
}

/// A block of statements.
///
/// * `{ (<stmt>)* }`.
#[derive(Debug, TryClone, PartialEq, Eq, ToTokens)]
#[non_exhaustive]
pub struct EmptyBlock {
    /// Statements in the block.
    pub statements: Vec<ast::Stmt>,
    /// The unique identifier for the block expression.
    #[rune(skip)]
    pub(crate) id: ItemId,
}

impl Parse for EmptyBlock {
    fn parse(parser: &mut Parser<'_>) -> Result<Self> {
        let mut statements = Vec::new();

        while !parser.is_eof()? {
            statements.try_push(parser.parse()?)?;
        }

        Ok(Self {
            statements,
            id: ItemId::ROOT,
        })
    }
}