Reading — step 1 of 5
Read
~1 min readImplementation
Preserving Comments
Comments are formatter foes. AST drops them. CST keeps them.
Strategies:
Position-based:
- Each comment has a position (line, col).
- Associate with the AST node before/after based on lines.
Trailing vs leading:
- Leading comment:
# commentthennode. - Trailing comment:
node # comment.
python
When formatting:
python
Edge cases:
- Block comments inside expressions: hard. Some formatters punt and keep verbatim.
- Multi-line comments: indent properly.
- Comments separating logical groups: detect blank-line patterns.
- Disabling:
// prettier-ignoreskip the next node.
Doc strings (Python) and docstrings (other langs):
- Often preserved exactly (don't reflow).
- Some formatters detect and skip.
Embedded code in comments (jsdoc):
- Don't touch interior.
Best practice: use a CST-aware library. Don't roll your own comment association.
Real CSTs:
- libCST (Python): Python-specific, comment-aware.
- ts-morph (TypeScript): wraps TypeScript AST + lossless source.
- tree-sitter: language-agnostic.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…