Module ast

Source
Expand description

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");

Re-exports§

pub use self::spanned::OptionSpanned;
pub use self::spanned::Spanned;

Macros§

K
Helper macro to reference a specific token kind, or short sequence of kinds.
T
Helper macro to reference a specific token.

Structs§

Abstract
The abstract keyword.
AlignOf
The alignof keyword.
Amp
&.
AmpAmp
&&.
AmpEq
&=.
AngleBracketed
Parse something bracketed, that is separated by <(T, S?)*>.
Arrow
->.
As
The as keyword.
Async
The async keyword.
At
@.
Attribute
Attributes like:
Await
The await keyword.
Bang
!.
BangEq
!=.
Become
The become keyword.
Block
A block of statements.
Braced
Parse something braced, that is separated by {(T, S?)*}.
Bracketed
Parse something bracketed, that is separated by [(T, S?)*].
Break
The break keyword.
ByteIndex
A single index in a Span, like the start or ending index.
Caret
^.
CaretEq
^=.
CloseBrace
closing brace
CloseBracket
closing bracket
CloseEmpty
closing marker
CloseParen
closing parenthesis
Colon
:.
ColonColon
::.
Comma
,.
Const
The const keyword.
Continue
The continue keyword.
Crate
The crate keyword.
Dash
-.
DashEq
-=.
Default
The default keyword.
Div
/.
Do
The do keyword.
Dollar
$.
Dot
..
DotDot
...
DotDotEq
..=.
Else
The else keyword.
EmptyBlock
A block of statements.
Enum
The enum keyword.
Eq
=.
EqEq
==.
EqValue
An = ... e.g. inside an attribute #[doc = ...].
ExprAssign
An assign expression.
ExprAwait
An await expression.
ExprBinary
A binary expression.
ExprBlock
A block expression.
ExprBreak
A break expression.
ExprCall
A call expression.
ExprClosure
A closure expression.
ExprContinue
A continue statement.
ExprDefaultBranch
A single selection branch.
ExprElse
An else branch of an if expression.
ExprElseIf
An else branch of an if expression.
ExprEmpty
A prioritized expression group without delimiters <expr>.
ExprFieldAccess
A field access.
ExprFor
A for loop over an iterator.
ExprGroup
A prioritized expression group.
ExprIf
A conditional if expression.
ExprIndex
An index get operation.
ExprLet
A let expression.
ExprLit
A literal expression. With the addition of being able to receive attributes, this is identical to ast::Lit.
ExprLoop
A loop expression.
ExprMatch
A match expression.
ExprMatchBranch
A match branch.
ExprObject
An object expression.
ExprRange
A range expression.
ExprReturn
A return expression.
ExprSelect
A select expression that selects over a collection of futures.
ExprSelectPatBranch
A single selection branch.
ExprTry
A try expression.
ExprTuple
An expression to construct a literal tuple.
ExprUnary
A unary expression.
ExprVec
A literal vector.
ExprWhile
A while loop.
ExprYield
A yield expression to return a value from a generator.
Extern
The extern keyword.
False
The false keyword.
Field
A field as part of a struct or a tuple body.
FieldAssign
A single field assignment in an object expression.
File
A rune file.
Final
The final keyword.
Fn
The fn keyword.
For
The for keyword.
Group
Parses [{( ... )}] ensuring that the delimiter is balanced.
Gt
>.
GtEq
>=.
GtGt
>>.
GtGtEq
>>=.
Ident
An identifier, like foo or Hello.
If
The if keyword.
Impl
The impl keyword.
In
The in keyword.
Is
The is keyword.
IsNot
The composite is not operation.
ItemConst
A const declaration.
ItemEnum
An enum item.
ItemFn
A function item.
ItemImpl
An impl item.
ItemInlineBody
A module declaration.
ItemMod
A module item.
ItemStruct
A struct item.
ItemUse
A use item.
ItemUsePath
A single use declaration path.
ItemVariant
An enum variant.
Label
A label, like 'foo.
Let
The let keyword.
LitBool
The boolean literal.
LitByte
A byte literal.
LitByteStr
A string literal.
LitChar
A character literal.
LitNumber
A number literal.
LitStr
A string literal.
Local
A local variable declaration.
Loop
The loop keyword.
Lt
<.
LtEq
<=.
LtLt
<<.
LtLtEq
<<=.
Macro
The macro keyword.
MacroCall
A macro call.
Match
The match keyword.
Mod
The mod keyword.
Move
The move keyword.
Mut
The mut keyword.
Not
The not keyword.
Number
A resolved number literal.
NumberText
Configuration of a text number.
OffsetOf
The offsetof keyword.
OpenBrace
opening brace
OpenBracket
opening bracket
OpenEmpty
opening marker
OpenParen
opening parenthesis
Override
The override keyword.
Parenthesized
Parse something parenthesis, that is separated by ((T, S?)*).
PatBinding
An object item.
PatIgnore
An ignore pattern.
PatLit
A literal pattern.
PatObject
An object pattern.
PatPath
A path pattern.
PatRest
The rest pattern .. and associated attributes.
PatTuple
A tuple pattern.
PatVec
An array pattern.
Path
A path, where each element is separated by a ::.
PathSegmentExpr
Used to parse an expression without supporting an immediate binary expression.
Perc
%.
PercEq
%=.
Pipe
|.
PipeEq
|=`.
PipePipe
||.
Plus
+.
PlusEq
+=.
Pound
#.
Priv
The priv keyword.
Proc
The proc keyword.
Pub
The pub keyword.
Pure
The pure keyword.
QuestionMark
?.
Ref
The ref keyword.
Return
The return keyword.
Rocket
=>.
Select
The select keyword.
SelfType
The Self keyword.
SelfValue
The self keyword.
SemiColon
;.
Shebang
The shebang of a file.
SizeOf
The sizeof keyword.
SlashEq
/=.
Span
A span corresponding to a range in the source file being parsed.
Star
*.
StarEq
*=.
Static
The static keyword.
StmtSemi
A semi-terminated expression.
StrText
Configuration for a literal string.
Struct
The struct keyword.
Super
The super keyword.
Tilde
~.
Token
A single token encountered during parsing.
True
The true keyword.
TypeOf
The typeof keyword.
Underscore
_.
Unsafe
The unsafe keyword.
Use
The use keyword.
Virtual
The virtual keyword.
While
The while keyword.
Yield
The yield keyword.

Enums§

AttrStyle
Whether or not the attribute is an outer #! or inner # attribute
BinOp
A binary operation.
BuiltIn
A built-in identifiers that do not have a source.
Condition
The condition in an if statement.
CopySource
The source of an item that implements Copy.
Delimiter
A delimiter, {, {, or [.
Expr
A rune expression.
ExprClosureArgs
Representation of closure arguments.
ExprField
The field being accessed.
ExprRangeLimits
The limits of the specified range.
ExprSelectBranch
A single selection branch.
Fields
An item body declaration.
FnArg
A single argument in a closure.
Item
A declaration.
ItemModBody
An item body.
ItemOrExpr
Parsing an item or an expression.
ItemUseSegment
A use component.
Kind
The kind of the token.
Lit
A literal value,
LitSource
The kind of the identifier.
NumberBase
The kind of a number literal.
NumberSize
The literal size of a number.
NumberSource
The source of a number.
NumberSuffix
The suffix of a number.
NumberValue
The value of a number literal.
ObjectIdent
A literal object identifier.
ObjectKey
Possible literal object keys.
Pat
A pattern match.
PathKind
An identified path kind.
PathSegment
Part of a :: separated path.
Stmt
A statement within a block.
StmtSortKey
Key used to stort a statement into its processing order.
StrSource
The source of the literal string. This need to be treated separately from LitSource because it might encompass special things like quoting and escaping.
Type
A type, used for static typing.
UnOp
A unary operation.
Visibility
Visibility level restricted to some path.

Traits§

OptionSpanned
Types for which we can optionally get a span.
Spanned
Types for which we can get a span.