rune/compile/
attrs.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use core::marker::PhantomData;

use crate as rune;
use crate::alloc::prelude::*;
use crate::alloc::{Vec, VecDeque};
use crate::ast;
use crate::ast::{LitStr, Spanned};
use crate::compile::{self, ErrorKind};
use crate::parse::{self, Parse, Resolve, ResolveContext};

/// Helper for parsing internal attributes.
pub(crate) struct Parser {
    /// Collection of attributes that have been used.
    unused: VecDeque<usize>,
    /// Attributes which were missed during the last parse.
    missed: Vec<usize>,
}

impl Parser {
    /// Construct a new attributes parser.
    pub(crate) fn new(attributes: &[ast::Attribute]) -> compile::Result<Self> {
        Ok(Self {
            unused: attributes
                .iter()
                .enumerate()
                .map(|(i, _)| i)
                .try_collect()?,
            missed: Vec::new(),
        })
    }

    /// Try to parse and collect all attributes of a given type.
    ///
    /// The returned Vec may be empty.
    pub(crate) fn parse_all<'this, 'a, T>(
        &'this mut self,
        cx: ResolveContext<'this>,
        attributes: &'a [ast::Attribute],
    ) -> compile::Result<ParseAll<'this, 'a, T>>
    where
        T: Attribute + Parse,
    {
        for index in self.missed.drain(..) {
            self.unused.try_push_back(index)?;
        }

        Ok(ParseAll {
            outer: self,
            attributes,
            cx,
            _marker: PhantomData,
        })
    }

    /// Try to parse a unique attribute with the given type.
    ///
    /// Returns the parsed element and the span it was parsed from if
    /// successful.
    pub(crate) fn try_parse<'a, T>(
        &mut self,
        cx: ResolveContext<'_>,
        attributes: &'a [ast::Attribute],
    ) -> compile::Result<Option<(&'a ast::Attribute, T)>>
    where
        T: Attribute + Parse,
    {
        let mut vec = self.parse_all::<T>(cx, attributes)?;
        let first = vec.next();
        let second = vec.next();

        match (first, second) {
            (None, _) => Ok(None),
            (Some(first), None) => Ok(Some(first?)),
            (Some(first), _) => Err(compile::Error::new(
                first?.0,
                ErrorKind::MultipleMatchingAttributes { name: T::PATH },
            )),
        }
    }

    /// Get the span of the first remaining attribute.
    pub(crate) fn remaining<'a>(
        &'a self,
        attributes: &'a [ast::Attribute],
    ) -> impl Iterator<Item = &'a ast::Attribute> + 'a {
        self.unused
            .iter()
            .chain(self.missed.iter())
            .flat_map(|&n| attributes.get(n))
    }
}

pub(crate) struct ParseAll<'this, 'a, T> {
    outer: &'this mut Parser,
    attributes: &'a [ast::Attribute],
    cx: ResolveContext<'this>,
    _marker: PhantomData<T>,
}

impl<'a, T> Iterator for ParseAll<'_, 'a, T>
where
    T: Attribute + Parse,
{
    type Item = compile::Result<(&'a ast::Attribute, T)>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let index = self.outer.unused.pop_front()?;

            let Some(a) = self.attributes.get(index) else {
                if let Err(error) = self.outer.missed.try_push(index) {
                    return Some(Err(error.into()));
                }

                continue;
            };

            let Some(ident) = a.path.try_as_ident() else {
                if let Err(error) = self.outer.missed.try_push(index) {
                    return Some(Err(error.into()));
                }

                continue;
            };

            let ident = match ident.resolve(self.cx) {
                Ok(ident) => ident,
                Err(e) => {
                    return Some(Err(e));
                }
            };

            if ident != T::PATH {
                if let Err(error) = self.outer.missed.try_push(index) {
                    return Some(Err(error.into()));
                }

                continue;
            }

            let mut parser = parse::Parser::from_token_stream(&a.input, a.span());

            let item = match parser.parse::<T>() {
                Ok(item) => item,
                Err(e) => {
                    return Some(Err(e));
                }
            };

            if let Err(e) = parser.eof() {
                return Some(Err(e));
            }

            return Some(Ok((a, item)));
        }
    }
}

pub(crate) trait Attribute {
    const PATH: &'static str;
}

#[derive(Default)]
pub(crate) struct BuiltInArgs {
    pub(crate) literal: bool,
}

#[derive(Parse)]
pub(crate) struct BuiltIn {
    /// Arguments to this built-in.
    pub args: Option<ast::Parenthesized<ast::Ident, T![,]>>,
}

impl BuiltIn {
    /// Parse built-in arguments.
    pub(crate) fn args(&self, cx: ResolveContext<'_>) -> compile::Result<BuiltInArgs> {
        let mut out = BuiltInArgs::default();

        if let Some(args) = &self.args {
            for (ident, _) in args {
                match ident.resolve(cx)? {
                    "literal" => {
                        out.literal = true;
                    }
                    _ => {
                        return Err(compile::Error::msg(ident, "unsupported attribute"));
                    }
                }
            }
        }

        Ok(out)
    }
}

impl Attribute for BuiltIn {
    /// Must match the specified name.
    const PATH: &'static str = "builtin";
}

/// NB: at this point we don't support attributes beyond the empty `#[test]`.
#[derive(Parse)]
pub(crate) struct Test {}

impl Attribute for Test {
    /// Must match the specified name.
    const PATH: &'static str = "test";
}

/// NB: at this point we don't support attributes beyond the empty `#[bench]`.
#[derive(Parse)]
pub(crate) struct Bench {}

impl Attribute for Bench {
    /// Must match the specified name.
    const PATH: &'static str = "bench";
}

#[derive(Parse)]
pub(crate) struct Doc {
    /// The `=` token.
    #[allow(dead_code)]
    pub eq_token: T![=],
    /// The doc string.
    pub doc_string: LitStr,
}

impl Attribute for Doc {
    /// Must match the specified name.
    const PATH: &'static str = "doc";
}