m2-syn
syn for Macaulay2: a Rust crate that turns M2 code into a fully typed
syntax tree, lets you walk and rewrite it, and prints it back out. The
language server is built on it.
- Typed tree: a
SourceFileofCells, and each construct is its own type (Expr::Lambda,Expr::If, …), so matching on it is checked by the compiler. - Round trip: an untouched file prints back byte for byte, comments included.
Visit,VisitMut,Fold: override the node you care about, the rest is walked for you.quote_m2!/parse_quote_m2!: write M2 code with$(value)interpolation instead of gluing strings.
#![allow(unused)]
fn main() {
use m2_syn::nodes::Symbol;
use m2_syn::{ParsedFile, visit_mut::VisitMut};
struct Rename;
impl VisitMut for Rename {
fn visit_symbol_mut(&mut self, symbol: &mut Symbol) {
if symbol.text() == "left" {
symbol.set_text("renamed");
}
}
}
let file = ParsedFile::from_source("left + right")?.edit(|cst| {
Rename.visit_source_file_mut(cst);
});
assert_eq!(file.to_source(), "renamed+ right");
}
cargo add m2-syn
cargo run --example inspect -- file.m2 # in the repo: dump a file's tree
As a macro engine
The ProcMacro trait takes cells in and gives cells out, and with quote_m2! the output is
written as M2. Right now these macros run from Rust, not from inside M2; for macros you call
from M2 code, there’s ProceduralMacros.
The API is still moving between minor versions.