Reading — step 1 of 5
Read
~1 min readImplementation
AST-Based Formatting
Modern formatters parse → AST → format → output.
python
Each AST node type has its formatting rule. Trees compose: a binary op containing function calls renders both correctly.
Comments are tricky:
- AST drops them.
- Need: associate each comment with a "next" or "prev" AST node.
- During formatting, emit comments adjacent to their node.
Most formatters use CST (concrete syntax tree) instead, retaining comments + whitespace info.
Tree-sitter produces CST. Many newer formatters use it.
Pros of AST formatting:
- Robust: works regardless of input formatting.
- Can refactor: convert function expression to declaration, etc.
Cons:
- Loses original details (formatting hints, comment alignment).
- Bug in parser → formatter dies.
Hybrid: AST for the "real" code; preserve trivia (whitespace, comments) verbatim.
Example: prettier in JavaScript:
- Uses ESTree-style AST.
- Special-case comments: leading vs trailing.
- Preserves choice of
'vs"in strings (configurable).
Black: AST-based. Strict: removes optional parens, normalizes everything.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…