liveBook · Manning

Abstract syntax tree

As explained in Write Powerful Rust Macros

An abstract syntax tree is a hierarchical representation of a program's syntactic structure and relevant semantic elements.

An abstract syntax tree (AST) is a tree-like representation of the relevant structure in program code after parsing. For `1 + 11`, the `+` can be the root and the two number literals its branches. This structured form helps a compiler work with code, while spans retain links to original text for diagnostics. section 3.2

In Rust procedural macros, input arrives as a `TokenStream`, but parsing can turn that input into AST types such as `DeriveInput`. The AST can then supply parts of the input—such as a struct name—while also being emitted again through `ToTokens` when the original struct must remain in generated output. section 5.1.2

Use an AST when generated code depends on structure rather than token text:

  • Parse generated output with `syn::parse2` and inspect fields such as an identifier to test macro output structurally. section 6.3
  • Traverse a field type from `Type` through `TypePath`, `Path`, and `PathSegment` to identify `String` and generate different builder code. section 6.4.4

Inspecting a field type

A helper can match `Type::Path`, read the first path segment’s identifier, and compare it with `"String"`. That result determines whether generated builder code borrows and clones a string with `as_ref().expect(...).to_string()` or directly consumes another field value. section 6.4.4

Figure 6.4 A simplified drilling down from Field to PathSegment
figure

Follow the structural route from a field to the path segment that holds its type identifier. section 6.4.4

How Write Powerful Rust Macros covers it

How deep it goes
Demonstrates parsing, re-emitting, testing, and traversing AST nodes; defers compiler parsing internals.
Examples
Uses `1 + 11`, struct reconstruction, builder-output tests, and `String` versus `u8` fields.
What it assumes
Assumes familiarity with Rust testing and procedural-macro basics while motivating AST inspection through macro implementation.
What you can do after
Apply it via `syn` to inspect Rust declarations, verify generated output, and vary macro expansion by field type.
How it connects
Connects TokenStream, parsing, spans, DeriveInput, syn::parse2, Type, Path, and procedural macros.

Also explained in

Compare how 2 books explain abstract syntax tree →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.