rune/ast/
mod.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//! Abstract syntax trees for the Rune language.
//!
//! These are primarily made available for use in macros, where the input to the
//! macro needs to be parsed so that it can be processed.
//!
//! Below we define a macro capable of taking identifiers like `hello`, and
//! turning them into literal strings like `"hello"`.
//!
//! ```
//! use rune::{Context, FromValue, Module, Vm};
//! use rune::ast;
//! use rune::compile;
//! use rune::macros::{quote, MacroContext, TokenStream};
//! use rune::parse::Parser;
//! use rune::alloc::prelude::*;
//!
//! use std::sync::Arc;
//!
//! #[rune::macro_]
//! fn ident_to_string(cx: &mut MacroContext<'_, '_, '_>, stream: &TokenStream) -> compile::Result<TokenStream> {
//!     let mut p = Parser::from_token_stream(stream, cx.input_span());
//!     let ident = p.parse_all::<ast::Ident>()?;
//!     let ident = cx.resolve(ident)?.try_to_owned()?;
//!     let string = cx.lit(&ident)?;
//!     Ok(quote!(#string).into_token_stream(cx)?)
//! }
//!
//! let mut m = Module::new();
//! m.macro_meta(ident_to_string)?;
//!
//! let mut context = Context::new();
//! context.install(m)?;
//!
//! let runtime = Arc::new(context.runtime()?);
//!
//! let mut sources = rune::sources! {
//!     entry => {
//!         pub fn main() {
//!             ident_to_string!(hello)
//!         }
//!     }
//! };
//!
//! let unit = rune::prepare(&mut sources)
//!     .with_context(&context)
//!     .build()?;
//!
//! let unit = Arc::new(unit);
//!
//! let mut vm = Vm::new(runtime, unit);
//! let value = vm.call(["main"], ())?;
//! let value: String = rune::from_value(value)?;
//!
//! assert_eq!(value, "hello");
//! # Ok::<_, rune::support::Error>(())
//! ```

use crate as rune;
use crate::alloc::prelude::*;
use crate::macros::{MacroContext, ToTokens, TokenStream};
use crate::parse::{Parse, Parser, Peek};

#[cfg(test)]
mod testing;

#[macro_use]
/// Generated modules.
mod generated;
pub use self::generated::*;

macro_rules! expr_parse {
    ($ty:ident, $local:ty, $expected:literal) => {
        impl $crate::parse::Parse for $local {
            fn parse(p: &mut $crate::parse::Parser<'_>) -> $crate::compile::Result<Self> {
                let t = p.tok_at(0)?;

                match $crate::ast::Expr::parse(p)? {
                    $crate::ast::Expr::$ty(expr) => Ok(expr),
                    _ => Err($crate::compile::Error::expected(t, $expected)),
                }
            }
        }
    };
}

macro_rules! item_parse {
    ($ty:ident, $local:ty, $expected:literal) => {
        impl $crate::parse::Parse for $local {
            fn parse(p: &mut $crate::parse::Parser<'_>) -> $crate::compile::Result<Self> {
                let t = p.tok_at(0)?;

                match $crate::ast::Item::parse(p)? {
                    $crate::ast::Item::$ty(item) => Ok(item),
                    _ => Err($crate::compile::Error::expected(t, $expected)),
                }
            }
        }
    };
}

#[cfg(test)]
mod tests;

mod attribute;
mod block;
mod condition;
mod expr;
mod expr_assign;
mod expr_await;
mod expr_binary;
mod expr_block;
mod expr_break;
mod expr_call;
mod expr_closure;
mod expr_continue;
mod expr_empty;
mod expr_field_access;
mod expr_for;
mod expr_group;
mod expr_if;
mod expr_index;
mod expr_let;
mod expr_lit;
mod expr_loop;
mod expr_match;
mod expr_object;
mod expr_range;
mod expr_return;
mod expr_select;
mod expr_try;
mod expr_tuple;
mod expr_unary;
mod expr_vec;
mod expr_while;
mod expr_yield;
mod fields;
mod file;
mod fn_arg;
mod grouped;
mod ident;
mod item;
mod item_const;
mod item_enum;
mod item_fn;
mod item_impl;
mod item_mod;
mod item_struct;
mod item_use;
mod label;
mod lit;
mod lit_bool;
mod lit_byte;
mod lit_byte_str;
mod lit_char;
mod lit_number;
mod lit_str;
mod local;
mod macro_call;
mod macro_utils;
mod pat;
mod path;
mod prelude;
mod span;
pub(crate) mod spanned;
mod stmt;
mod to_ast;
mod token;
pub(super) mod unescape;
mod utils;
mod vis;

pub use self::attribute::{AttrStyle, Attribute};
pub use self::block::{Block, EmptyBlock};
pub use self::condition::Condition;
pub use self::expr::Expr;
pub use self::expr_assign::ExprAssign;
pub use self::expr_await::ExprAwait;
pub use self::expr_binary::{BinOp, ExprBinary};
pub use self::expr_block::ExprBlock;
pub use self::expr_break::ExprBreak;
pub use self::expr_call::ExprCall;
pub use self::expr_closure::{ExprClosure, ExprClosureArgs};
pub use self::expr_continue::ExprContinue;
pub use self::expr_empty::ExprEmpty;
pub use self::expr_field_access::{ExprField, ExprFieldAccess};
pub use self::expr_for::ExprFor;
pub use self::expr_group::ExprGroup;
pub use self::expr_if::{ExprElse, ExprElseIf, ExprIf};
pub use self::expr_index::ExprIndex;
pub use self::expr_let::ExprLet;
pub use self::expr_lit::ExprLit;
pub use self::expr_loop::ExprLoop;
pub use self::expr_match::{ExprMatch, ExprMatchBranch};
pub use self::expr_object::{ExprObject, FieldAssign, ObjectIdent, ObjectKey};
pub use self::expr_range::{ExprRange, ExprRangeLimits};
pub use self::expr_return::ExprReturn;
pub use self::expr_select::{ExprDefaultBranch, ExprSelect, ExprSelectBranch, ExprSelectPatBranch};
pub use self::expr_try::ExprTry;
pub use self::expr_tuple::ExprTuple;
pub use self::expr_unary::{ExprUnary, UnOp};
pub use self::expr_vec::ExprVec;
pub use self::expr_while::ExprWhile;
pub use self::expr_yield::ExprYield;
pub use self::fields::Fields;
pub use self::file::{File, Shebang};
pub use self::fn_arg::FnArg;
pub use self::grouped::{AngleBracketed, Braced, Bracketed, Parenthesized};
pub use self::ident::Ident;
pub use self::item::Item;
pub use self::item_const::ItemConst;
pub use self::item_enum::{ItemEnum, ItemVariant};
pub use self::item_fn::ItemFn;
pub use self::item_impl::ItemImpl;
pub use self::item_mod::{ItemInlineBody, ItemMod, ItemModBody};
pub use self::item_struct::{Field, ItemStruct};
pub use self::item_use::{ItemUse, ItemUsePath, ItemUseSegment};
pub use self::label::Label;
pub use self::lit::Lit;
pub use self::lit_bool::LitBool;
pub use self::lit_byte::LitByte;
pub use self::lit_byte_str::LitByteStr;
pub use self::lit_char::LitChar;
pub use self::lit_number::LitNumber;
pub use self::lit_str::LitStr;
pub use self::local::Local;
pub use self::macro_call::MacroCall;
pub use self::macro_utils::{EqValue, Group};
pub use self::pat::{
    Pat, PatBinding, PatIgnore, PatLit, PatObject, PatPath, PatRest, PatTuple, PatVec,
};
pub use self::path::{Path, PathKind, PathSegment, PathSegmentExpr};
use self::prelude::*;
pub use self::span::{ByteIndex, Span};
pub use self::spanned::{OptionSpanned, Spanned};
pub use self::stmt::{ItemOrExpr, Stmt, StmtSemi, StmtSortKey};
pub(crate) use self::to_ast::ToAst;
pub use self::token::{
    BuiltIn, CopySource, Delimiter, LitSource, Number, NumberBase, NumberSize, NumberSource,
    NumberSuffix, NumberText, NumberValue, StrSource, StrText, Token,
};
pub use self::vis::Visibility;

macro_rules! decl_tokens {
    ($(($parser:ident, $name:expr, $doc:expr, $($kind:tt)*),)*) => {
        $(
            #[doc = $doc]
            #[derive(Debug, TryClone, Clone, Copy, PartialEq, Eq)]
            #[try_clone(copy)]
            pub struct $parser {
                /// Associated token.
                pub span: Span,
            }

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

            impl OptionSpanned for $parser {
                fn option_span(&self) -> Option<Span> {
                    Some(self.span)
                }
            }

            impl Parse for $parser {
                fn parse(parser: &mut Parser<'_>) -> $crate::compile::Result<Self> {
                    let t = parser.next()?;

                    match t.kind {
                        $($kind)* => Ok(Self { span: t.span }),
                        _ => Err($crate::compile::Error::expected(t, $name)),
                    }
                }
            }

            impl Peek for $parser {
                fn peek(p: &mut $crate::parse::Peeker<'_>) -> bool {
                    matches!(p.nth(0), $($kind)*)
                }
            }

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

decl_tokens! {
    (CloseBrace, "a closing brace `}`", "closing brace", Kind::Close(Delimiter::Brace)),
    (CloseBracket, "a closing bracket `]`", "closing bracket", Kind::Close(Delimiter::Bracket)),
    (CloseParen, "a closing parenthesis `)`", "closing parenthesis", Kind::Close(Delimiter::Parenthesis)),
    (CloseEmpty, "an empty closing marker", "closing marker", Kind::Close(Delimiter::Empty)),
    (OpenBrace, "an opening brace `{`", "opening brace", Kind::Open(Delimiter::Brace)),
    (OpenBracket, "an open bracket `[`", "opening bracket", Kind::Open(Delimiter::Bracket)),
    (OpenParen, "an opening parenthesis `(`", "opening parenthesis", Kind::Open(Delimiter::Parenthesis)),
    (OpenEmpty, "an empty opening marker", "opening marker", Kind::Open(Delimiter::Empty)),
}

/// The composite `is not` operation.
#[derive(Debug, TryClone, Clone, Copy, PartialEq, Eq, Hash, ToTokens, Spanned)]
#[try_clone(copy)]
#[non_exhaustive]
pub struct IsNot {
    /// The `is` token.
    pub is: Is,
    /// The `not` token.
    pub not: Not,
}