Abstract Syntax Tree (AST)¶
The AST is implemented as a tree of structs that represent parsed Forge code. The structs are written by hand which has the advantage of quicker implementation and better optimization, but it also means that code consistency needs to be maintained manually. Make sure to follow these guidelines when adding new structs.
Code map¶
All of the code is defined in crates/forge-core/src/ast/*
. It's split up into files by concern:
structs.rs
: Where the structs themselves are defined.traits.rs
: The traits that the structs must implement to provide shared functionality.impls.rs
: The implementations of the traits intraits.rs
for the structs instructs.rs
. This code can be hard to read and repetitive, so it's put in a separate file so keep the other two files more readable.
Adding a new AST node type¶
This is an example struct definition in structs.rs
:
#[derive(Debug, Clone, Serialize)]
pub struct ExprCall<'sctx> {
#[serde(rename = "sourceRange")]
pub source_range: Option<SourceRange<'sctx>>,
pub callee: Box<Expr<'sctx>>,
pub args: Vec<Expr<'sctx>>,
}
impl<'ctx> IsNode<'ctx> for ExprCall<'ctx> {}
Let's go through it step by step.
All of them must implement the Debug
, Clone
, and Serialize
traits. These can be automatically derived:
#[derive(Debug, Clone, Serialize)]
Then the struct needs to contain some standard attributes. Right now the only one is source_range
, but this may expand in the future:
#[serde(rename = "sourceRange")]
pub source_range: Option<SourceRange<'sctx>>,
Todo
This page needs to be expanded.