miniblog.

← Back to all posts
4
ASTs typically discard comments, and that's usually what you want. The only time (AFAICS) that preserving comments is useful is for writing a code formatter. Could you write a formatter in terms of a list of lexemes? A CST is a non-trivial bit of code for one use case.

4 Comments

@wilfredh I’ve worked on a simple language describing data structures to code-generate implementations in different target languages. We had to keep comments in the AST to include them in the output - it’s similar to a code formatter, but not quite the same
@wilfredh Well you almost certainly want to build some structure as part of processing the list in order to be able to format it, at which point you're rewriting at least *some* of the parser. My attempts to operate on lists of tokens have usually been frustrating before we even get to the matter of comments. If the question is "can you write a formatter without having to embed comments into the AST", the answer might be yes. I think Dart uses a syntax tree with enough positioning information to reconstruct the trivia spans without actually embedding the comments into the syntax tree. Then it might be easy enough to design your syntax tree without spending a ton of complexity on trivia handling. But comments are useful for other tooling too. In particular, doc-comments can be surfaced in the IDE. If you're an aftermarket typechecker, then there's a good chance that you're interested in comments to inform semantics. You could consider "comments in the CST" as an escape hatch for the case that your language doesn't support attaching metadata to arbitrary syntax nodes (although it's still paying a considerable cost now for potential benefit later).
@wilfredh in my work on #GRASP that's a very delicate point, because I essentially want to operate on CST. Another quite big example is syntax-case macros in Scheme, that manipulate syntax objects (which are CST nodes). While they don't exactly preserve comments, they preserve line information, making comments recoverable. (Also, you'd typically want to preserve line information at all levels down to assembly)