rune/ast/
file.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
use crate::ast::prelude::*;

#[test]
#[cfg(not(miri))]
fn ast_parse() {
    rt::<ast::File>(
        r#"
        use foo;
        ///
        fn foo() {
            42
        }
        ///
        use bar;
        ///
        fn bar(a, b) {
            a
        }
        "#,
    );

    rt::<ast::File>(
        r#"
        use http;

        fn main() {
            let client = http::client();
            let response = client.get("https://google.com");
            let text = response.text();
        }
        "#,
    );

    rt::<ast::File>(
        r#"
        // NB: Attributes are currently rejected by the compiler
        #![feature(attributes)]

        fn main() {}
        "#,
    );

    let file = rt_with::<ast::File>(
        r#"#!rune run

        fn main() {}
        "#,
        true,
    );

    assert!(file.shebang.is_some());
}

/// A rune file.
#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, OptionSpanned)]
#[non_exhaustive]
pub struct File {
    /// Top-level shebang.
    #[rune(iter)]
    pub shebang: Option<Shebang>,
    /// Top level "Outer" `#![...]` attributes for the file
    #[rune(iter)]
    pub attributes: Vec<ast::Attribute>,
    /// All the declarations in a file.
    #[rune(iter)]
    pub items: Vec<(ast::Item, Option<T![;]>)>,
}

impl Parse for File {
    fn parse(p: &mut Parser<'_>) -> Result<Self> {
        let shebang = p.parse()?;

        let mut attributes = try_vec![];

        // only allow outer attributes at the top of a file
        while p.peek::<ast::attribute::OuterAttribute>()? {
            attributes.try_push(p.parse()?)?;
        }

        let mut items = Vec::new();

        let mut item_attributes = p.parse()?;
        let mut item_visibility = p.parse()?;
        let mut path = p.parse::<Option<ast::Path>>()?;

        while path.is_some() || ast::Item::peek_as_item(p.peeker()) {
            let item: ast::Item =
                ast::Item::parse_with_meta_path(p, item_attributes, item_visibility, path.take())?;

            let semi_colon = if item.needs_semi_colon() || p.peek::<T![;]>()? {
                Some(p.parse::<T![;]>()?)
            } else {
                None
            };

            items.try_push((item, semi_colon))?;
            item_attributes = p.parse()?;
            item_visibility = p.parse()?;
            path = p.parse()?;
        }

        // meta without items. maybe use different error kind?
        if let Some(span) = item_attributes.option_span() {
            return Err(compile::Error::unsupported(span, "attributes"));
        }

        if let Some(span) = item_visibility.option_span() {
            return Err(compile::Error::unsupported(span, "visibility"));
        }

        Ok(Self {
            shebang,
            attributes,
            items,
        })
    }
}

/// The shebang of a file.
#[derive(Debug, TryClone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Shebang {
    /// The span of the shebang.
    pub span: Span,
    /// The source of the shebang.
    pub source: ast::LitSource,
}

impl Peek for Shebang {
    fn peek(p: &mut Peeker<'_>) -> bool {
        matches!(p.nth(0), K![#!(..)])
    }
}

impl Parse for Shebang {
    fn parse(p: &mut Parser<'_>) -> Result<Self> {
        let token = p.next()?;

        match token.kind {
            K![#!(source)] => Ok(Self {
                span: token.span,
                source,
            }),
            _ => Err(compile::Error::expected(token, Expectation::Shebang)),
        }
    }
}

impl Spanned for Shebang {
    fn span(&self) -> Span {
        self.span
    }
}

impl ToTokens for Shebang {
    fn to_tokens(
        &self,
        _: &mut MacroContext<'_, '_, '_>,
        stream: &mut TokenStream,
    ) -> alloc::Result<()> {
        stream.push(ast::Token {
            span: self.span,
            kind: ast::Kind::Shebang(self.source),
        })
    }
}