scalameta / scalameta

Library to read, analyze, transform and generate Scala programs
http://scalameta.org/
BSD 3-Clause "New" or "Revised" License
1.11k stars 223 forks source link

Add Ast node(s) representing comments #3372

Open hamnis opened 11 months ago

hamnis commented 11 months ago

Sometimes it is very useful to be able to add comments to generated code when using scalameta. Currently this is not possible.

val instances: List[Stat] = cases.map(c => q"""
           // ${c.comment}
           case object ${c.name.termName} extends $init""")

/*
can't unquote into single-line comments
          ${c.comment}
*/

This is the same with multi-line comments.

tgodzik commented 11 months ago

Thanks for raising this! As mentioned on discord there was a previous discussion at https://github.com/scalameta/scalameta/issues/1137#issuecomment-338427505

It seems that having comments in quasiquotes is most problematic, we could do attachements or special AST nodes that woul pretty print correctly.

steinybot commented 3 months ago

Even just the AST nodes would be nice. Right now we can only get/create the Tokens but I haven't found a way to combine it with a Tree in any meaningful way.

There is claim in the docs that:

Scalameta trees are lossless...

Which is not true. The Tokens are lossless but Trees are not. You can be mislead into beleiving that they are lossless if you parse the source and immediately print it but that is just because of a shortcut that returns the origin text if the origin or dialect haven't changed. The comment in scala.meta.internal.prettyprinters.TreeSyntax#apply sums it up:

    // NOTE: This is the current state of the art of smart prettyprinting.
    // If we prettyprint a tree that's just been parsed with the same dialect,
    // then we retain formatting. Otherwise, we don't, even in the tiniest.
    // I expect to improve on this in the nearest future, because we had it much better until recently.