rune

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§

Macros§

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

Structs§

Enums§

Traits§