Skip to main content

rune/ast/
mod.rs

1//! Abstract syntax trees for the Rune language.
2//!
3//! These are primarily made available for use in macros, where the input to the
4//! macro needs to be parsed so that it can be processed.
5//!
6//! Below we define a macro capable of taking identifiers like `hello`, and
7//! turning them into literal strings like `"hello"`.
8//!
9//! ```
10//! use rune::{Context, FromValue, Module, Vm};
11//! use rune::ast;
12//! use rune::compile;
13//! use rune::macros::{quote, MacroContext, TokenStream};
14//! use rune::parse::Parser;
15//! use rune::alloc::prelude::*;
16//! use rune::sync::Arc;
17//!
18//! #[rune::macro_]
19//! fn ident_to_string(cx: &mut MacroContext<'_, '_, '_>, stream: &TokenStream) -> compile::Result<TokenStream> {
20//!     let mut p = Parser::from_token_stream(stream, cx.input_span());
21//!     let ident = p.parse_all::<ast::Ident>()?;
22//!     let ident = cx.resolve(ident)?.try_to_owned()?;
23//!     let string = cx.lit(&ident)?;
24//!     Ok(quote!(#string).into_token_stream(cx)?)
25//! }
26//!
27//! let mut m = Module::new();
28//! m.macro_meta(ident_to_string)?;
29//!
30//! let mut context = Context::new();
31//! context.install(m)?;
32//!
33//! let runtime = Arc::try_new(context.runtime()?)?;
34//!
35//! let mut sources = rune::sources! {
36//!     entry => {
37//!         pub fn main() {
38//!             ident_to_string!(hello)
39//!         }
40//!     }
41//! };
42//!
43//! let unit = rune::prepare(&mut sources)
44//!     .with_context(&context)
45//!     .build()?;
46//!
47//! let unit = Arc::try_new(unit)?;
48//!
49//! let mut vm = Vm::new(runtime, unit);
50//! let value = vm.call(["main"], ())?;
51//! let value: String = rune::from_value(value)?;
52//!
53//! assert_eq!(value, "hello");
54//! # Ok::<_, rune::support::Error>(())
55//! ```
56
57use crate as rune;
58use crate::alloc::prelude::*;
59use crate::macros::{MacroContext, ToTokens, TokenStream};
60use crate::parse::{Parse, Parser, Peek};
61
62#[cfg(test)]
63mod testing;
64
65#[macro_use]
66/// Generated modules.
67mod generated;
68pub use self::generated::*;
69
70macro_rules! expr_parse {
71    ($ty:ident, $local:ty, $expected:literal) => {
72        impl $crate::parse::Parse for $local {
73            fn parse(p: &mut $crate::parse::Parser<'_>) -> $crate::compile::Result<Self> {
74                let t = p.tok_at(0)?;
75
76                match $crate::ast::Expr::parse(p)? {
77                    $crate::ast::Expr::$ty(expr) => Ok(expr),
78                    _ => Err($crate::compile::Error::expected(t, $expected)),
79                }
80            }
81        }
82    };
83}
84
85macro_rules! item_parse {
86    ($ty:ident, $local:ty, $expected:literal) => {
87        impl $crate::parse::Parse for $local {
88            fn parse(p: &mut $crate::parse::Parser<'_>) -> $crate::compile::Result<Self> {
89                let t = p.tok_at(0)?;
90
91                match $crate::ast::Item::parse(p)? {
92                    $crate::ast::Item::$ty(item) => Ok(item),
93                    _ => Err($crate::compile::Error::expected(t, $expected)),
94                }
95            }
96        }
97    };
98}
99
100#[cfg(test)]
101mod tests;
102
103mod attribute;
104mod block;
105mod condition;
106mod expr;
107mod expr_assign;
108mod expr_await;
109mod expr_binary;
110mod expr_block;
111mod expr_break;
112mod expr_call;
113mod expr_closure;
114mod expr_continue;
115mod expr_empty;
116mod expr_field_access;
117mod expr_for;
118mod expr_group;
119mod expr_if;
120mod expr_index;
121mod expr_let;
122mod expr_lit;
123mod expr_loop;
124mod expr_match;
125mod expr_object;
126mod expr_range;
127mod expr_return;
128mod expr_select;
129mod expr_try;
130mod expr_tuple;
131mod expr_unary;
132mod expr_vec;
133mod expr_while;
134mod expr_yield;
135mod fields;
136mod file;
137mod fn_arg;
138mod grouped;
139mod ident;
140mod item;
141mod item_const;
142mod item_enum;
143mod item_fn;
144mod item_impl;
145mod item_mod;
146mod item_static;
147mod item_struct;
148mod item_use;
149mod label;
150mod lit;
151mod lit_bool;
152mod lit_byte;
153mod lit_byte_str;
154mod lit_char;
155mod lit_number;
156mod lit_str;
157mod local;
158mod macro_call;
159mod macro_utils;
160mod pat;
161mod path;
162mod prelude;
163mod rn_type;
164mod span;
165pub(crate) mod spanned;
166mod stmt;
167mod to_ast;
168mod token;
169pub(super) mod unescape;
170mod utils;
171mod vis;
172
173pub use self::attribute::{AttrStyle, Attribute};
174pub use self::block::{Block, EmptyBlock};
175pub use self::condition::Condition;
176pub use self::expr::Expr;
177pub use self::expr_assign::ExprAssign;
178pub use self::expr_await::ExprAwait;
179pub use self::expr_binary::{BinOp, ExprBinary};
180pub use self::expr_block::ExprBlock;
181pub use self::expr_break::ExprBreak;
182pub use self::expr_call::ExprCall;
183pub use self::expr_closure::{ExprClosure, ExprClosureArgs};
184pub use self::expr_continue::ExprContinue;
185pub use self::expr_empty::ExprEmpty;
186pub use self::expr_field_access::{ExprField, ExprFieldAccess};
187pub use self::expr_for::ExprFor;
188pub use self::expr_group::ExprGroup;
189pub use self::expr_if::{ExprElse, ExprElseIf, ExprIf};
190pub use self::expr_index::ExprIndex;
191pub use self::expr_let::ExprLet;
192pub use self::expr_lit::ExprLit;
193pub use self::expr_loop::ExprLoop;
194pub use self::expr_match::{ExprMatch, ExprMatchBranch};
195pub use self::expr_object::{ExprObject, FieldAssign, ObjectIdent, ObjectKey};
196pub use self::expr_range::{ExprRange, ExprRangeLimits};
197pub use self::expr_return::ExprReturn;
198pub use self::expr_select::{ExprDefaultBranch, ExprSelect, ExprSelectBranch, ExprSelectPatBranch};
199pub use self::expr_try::ExprTry;
200pub use self::expr_tuple::ExprTuple;
201pub use self::expr_unary::{ExprUnary, UnOp};
202pub use self::expr_vec::ExprVec;
203pub use self::expr_while::ExprWhile;
204pub use self::expr_yield::ExprYield;
205pub use self::fields::Fields;
206pub use self::file::{File, Shebang};
207pub use self::fn_arg::FnArg;
208pub use self::grouped::{AngleBracketed, Braced, Bracketed, Parenthesized};
209pub use self::ident::Ident;
210pub use self::item::Item;
211pub use self::item_const::ItemConst;
212pub use self::item_enum::{ItemEnum, ItemVariant};
213pub use self::item_fn::ItemFn;
214pub use self::item_impl::ItemImpl;
215pub use self::item_mod::{ItemInlineBody, ItemMod, ItemModBody};
216pub use self::item_static::{ItemStatic, ItemStaticInit};
217pub use self::item_struct::{Field, ItemStruct};
218pub use self::item_use::{ItemUse, ItemUsePath, ItemUseSegment};
219pub use self::label::Label;
220pub use self::lit::Lit;
221pub use self::lit_bool::LitBool;
222pub use self::lit_byte::LitByte;
223pub use self::lit_byte_str::LitByteStr;
224pub use self::lit_char::LitChar;
225pub use self::lit_number::LitNumber;
226pub use self::lit_str::LitStr;
227pub use self::local::Local;
228pub use self::macro_call::MacroCall;
229pub use self::macro_utils::{EqValue, Group};
230pub use self::pat::{
231    Pat, PatBinding, PatIgnore, PatLit, PatObject, PatPath, PatRest, PatTuple, PatVec,
232};
233pub use self::path::{Path, PathKind, PathSegment, PathSegmentExpr};
234use self::prelude::*;
235pub use self::rn_type::Type;
236pub use self::span::{ByteIndex, Span};
237pub use self::spanned::{OptionSpanned, Spanned};
238pub use self::stmt::{ItemOrExpr, Stmt, StmtSemi, StmtSortKey};
239pub(crate) use self::to_ast::ToAst;
240pub use self::token::{
241    BuiltIn, CopySource, Delimiter, LitSource, Number, NumberBase, NumberSize, NumberSource,
242    NumberSuffix, NumberText, NumberValue, StrSource, StrText, Token,
243};
244pub use self::vis::Visibility;
245
246macro_rules! decl_tokens {
247    ($(($parser:ident, $name:expr, $doc:expr, $($kind:tt)*),)*) => {
248        $(
249            #[doc = $doc]
250            #[derive(Debug, TryClone, Clone, Copy, PartialEq, Eq)]
251            #[try_clone(copy)]
252            pub struct $parser {
253                /// Associated token.
254                pub span: Span,
255            }
256
257            impl Spanned for $parser {
258                fn span(&self) -> Span {
259                    self.span
260                }
261            }
262
263            impl OptionSpanned for $parser {
264                fn option_span(&self) -> Option<Span> {
265                    Some(self.span)
266                }
267            }
268
269            impl Parse for $parser {
270                fn parse(parser: &mut Parser<'_>) -> $crate::compile::Result<Self> {
271                    let t = parser.next()?;
272
273                    match t.kind {
274                        $($kind)* => Ok(Self { span: t.span }),
275                        _ => Err($crate::compile::Error::expected(t, $name)),
276                    }
277                }
278            }
279
280            impl Peek for $parser {
281                fn peek(p: &mut $crate::parse::Peeker<'_>) -> bool {
282                    matches!(p.nth(0), $($kind)*)
283                }
284            }
285
286            impl ToTokens for $parser {
287                fn to_tokens(&self, _: &mut MacroContext<'_, '_, '_>, stream: &mut TokenStream) -> alloc::Result<()> {
288                    stream.push(Token { span: self.span, kind: $($kind)* })
289                }
290            }
291        )*
292    }
293}
294
295decl_tokens! {
296    (CloseBrace, "a closing brace `}`", "closing brace", Kind::Close(Delimiter::Brace)),
297    (CloseBracket, "a closing bracket `]`", "closing bracket", Kind::Close(Delimiter::Bracket)),
298    (CloseParen, "a closing parenthesis `)`", "closing parenthesis", Kind::Close(Delimiter::Parenthesis)),
299    (CloseEmpty, "an empty closing marker", "closing marker", Kind::Close(Delimiter::Empty)),
300    (OpenBrace, "an opening brace `{`", "opening brace", Kind::Open(Delimiter::Brace)),
301    (OpenBracket, "an open bracket `[`", "opening bracket", Kind::Open(Delimiter::Bracket)),
302    (OpenParen, "an opening parenthesis `(`", "opening parenthesis", Kind::Open(Delimiter::Parenthesis)),
303    (OpenEmpty, "an empty opening marker", "opening marker", Kind::Open(Delimiter::Empty)),
304}
305
306/// The composite `is not` operation.
307#[derive(Debug, TryClone, Clone, Copy, PartialEq, Eq, Hash, ToTokens, Spanned)]
308#[try_clone(copy)]
309#[non_exhaustive]
310pub struct IsNot {
311    /// The `is` token.
312    pub is: Is,
313    /// The `not` token.
314    pub not: Not,
315}