ruast
This crate provides a formattable & modifiable Rust AST.
```rust use ruast::*;
let mut krate = Crate::new(); let def = Fn::main( None, Block::from(Path::single("println").maccall(vec![Token::lit("Hello, world!")])), ); krate.additem(def); println!("{krate}"); krate.dump("test.rs")?; krate.removeitembyid("main"); assert!(krate.isempty()); ```
This is equivalent to:
```rust use ruast::*;
let mut krate = Crate::new(); krate.additem(Fn { ident: "main".tostring(), generics: vec![], fndecl: FnDecl::new(vec![], None), body: Some(Block::from( Stmt::Expr(Expr::new(MacCall { path: Path::single("println!"), args: DelimArgs::from(vec![Token::lit("Hello, world!")]), })), )), }); println!("{krate}"); krate.dump("test.rs")?; krate.removeitembyid("main"); assert!(krate.is_empty()); ```
```rust use ruast::*;
let mut krate = Crate::new(); let def = StructDef::empty("Foo") .withfield(FieldDef::inherited("foo", Type::from("u32"))) .withfield(FieldDef::inherited("bar", Type::from("u32"))); krate.additem(def); let imp = Impl::empty("Foo") .withitem(Fn::emptymethod("test", Pat::refself())); krate.add_item(imp); println!("{krate}"); ```
```rust use ruast::*;
let mut krate = Crate::new(); let def = EnumDef::empty("Foo") .withvariant(Variant::empty("Bar")) .withvariant(Variant::tuple("Baz", vec![FieldDef::anonymous("u32")])); krate.additem(def); let imp = Impl::empty("Foo") .withitem(Fn::emptymethod("test", Pat::refself())); krate.add_item(imp); println!("{krate}"); ```
proc_macro2::TokenStream
By enabling a feature tokenize
, you can convert ruast
ASTs to proc_macro2::TokenStream
.
You can build ASTs systematically without using syn
or quote
macros.
```rust use ruast::*;
let mut krate = Crate::new(); let def = Fn::main( None, Block::from(Path::single("println").maccall(vec![Token::lit("Hello, world!")])), ); krate.additem(def); let tokens = krate.totokenstream(); println!("{krate}"); println!("{tokens}"); ```
The Rust project has a submodule called rustc_ast
that defines an AST, but it is not published on crates.io and requires a huge build of rust
itself. Also, rustc_ast
is not designed for third parties to build ASTs by hand.
There is a codegen
crate for Rust code generation, but this crate has not been maintained for some time and only supports basic syntax elements.
There is also a syn
crate that can parse proc_macro::TokenStream
into an AST, but its AST elements don't implement Display
trait and are not designed for direct construction & modification.
The goal of this project is to provide a simple and portable Rust AST building/Rust code generation library.
This library is not directly related to the Rust compiler AST, and ASTs built with this library cannot be directly given as input to the compiler.
This project is licensed under either of Apache license version 2.0 or MIT license at your option.