pub fn syntax_fmt<'e, E>(elem: &'e E) -> SyntaxDisplay<'static, 'e, (), E>Expand description
Formats a syntax tree.
Returns a SyntaxDisplay wrapper that implements Display, allowing it to be
used with format!, println!, and other formatting macros.
By default, uses () as the state. Chain with .state() or .state_mut() to provide
custom state. Chain with .pretty() to enable pretty printing mode and .indent() to
customize the indentation string (default is four spaces).
§Arguments
elem- The syntax tree to format
§Examples
use syntaxfmt::{SyntaxFmt, syntax_fmt};
#[derive(SyntaxFmt)]
struct Expr<'src> {
#[syntax(pre = ["(", "( "], suf = [")", " )"])]
value: &'src str,
}
let expr = Expr { value: "42" };
assert_eq!(format!("{}", syntax_fmt(&expr)), "(42)");
assert_eq!(format!("{}", syntax_fmt(&expr).pretty()), "( 42 )");§With custom state
use syntaxfmt::{Mode, SyntaxFmt, SyntaxFormatter, syntax_fmt};
struct Counter {
count: usize,
}
impl Counter {
pub fn next(&mut self) -> usize {
let count = self.count;
self.count += 1;
count
}
}
struct Item;
impl SyntaxFmt<Counter> for Item {
fn syntax_fmt(&self, f: &mut SyntaxFormatter<Counter>) -> std::fmt::Result {
let count = f.state_mut().next();
if f.mode() == Mode::Pretty {
write!(f, "pretty_item_{}", count)
} else {
write!(f, "item_{}", count)
}
}
}
let mut state = Counter { count: 0 };
let item = Item;
assert_eq!(format!("{}", syntax_fmt(&item).state_mut(&mut state)), "item_0");
assert_eq!(state.count, 1);
assert_eq!(format!("{}", syntax_fmt(&item).state_mut(&mut state).pretty()), "pretty_item_1");
assert_eq!(state.count, 2);Examples found in repository?
examples/comprehensive.rs (line 146)
117fn main() {
118 // Create example AST
119 let func = Function {
120 name: "calculate",
121 params: vec![
122 Parameter { name: "x", ty: Some("i32") },
123 Parameter { name: "y", ty: Some("i32") },
124 ],
125 return_type: Some("i32"),
126 body: Block {
127 statements: vec![
128 Statement::Expr(Expr::Call(FunctionCall {
129 name: "println",
130 args: vec![Expr::Literal(42)],
131 })),
132 Statement::Return {
133 value: Some(Expr::Binary {
134 left: Box::new(Expr::Literal(1)),
135 op: "+",
136 right: Box::new(Expr::Literal(2)),
137 }),
138 },
139 ],
140 },
141 };
142
143 let config = TypeConfig { show_types: true };
144
145 println!("Normal - with types:");
146 println!("{}", syntax_fmt(&func).state(&config));
147 println!();
148
149 println!("Pretty - with types:");
150 println!("{}", syntax_fmt(&func).state(&config).pretty());
151 println!();
152
153 let config_no_types = TypeConfig { show_types: false };
154
155 println!("Normal - without types:");
156 println!("{}", syntax_fmt(&func).state(&config_no_types));
157 println!();
158
159 println!("Pretty - without types:");
160 println!("{}", syntax_fmt(&func).state(&config_no_types).pretty());
161}