I'm trying to write a Prettier plugin and I've already got several pieces of the logic to rebuild the code from the AST and some bits of formatting working. However, right now I'm really having a hard time to make sense of how to handle comments, and I can't seem to figure out what I'm doing wrong.
The parser I'm using doesn't preserve comments, so I'm using a modified version of this state machine to extract and attach the comments manually.
My biggest issue is that while the comments are apparently correctly attached to the AST nodes as per core.js::attachComments(), said method also removes the comments array from the AST root node. However, later in comments.js::printCommentsSeparately() the code checks whether the passed in AST root has a comments array, and if not skips any printing logic.
In context that makes sense (in the "why try to print things that aren't there" way), but looking at the program flow that I've traced out so far I don't understand why this is happening or what I can do to make my comments stick and make it to the actual printing code. Right now all I get are "Comment xyz was not printed. Please report this error!" exceptions.
The call order I've been running through:
core.js::coreFormat()
> core.js::attachComments() // removes ast.comments
> ast-to-doc.js::printAstToDoc()
> ast-to-doc.js::mainPrint()
> ast-to-doc.js::mainPrintInternal()
> ast-to-doc.js::callPluginPrintFunction()
> comments.js::printComments()
> comments.js::printCommentsSeparately() // checks for ast.comments
What am I missing? The documentation for plugin development isn't exactly detailed, and I haven't found any helpful discussions or topics in my searches.