Best way to add comments at the top of a bal file by modifying syntax tree? #40365
Replies: 2 comments
-
looping @sameerajayasoma @rdulmina @IMS94 @malinthar @hasithaa |
Beta Was this translation helpful? Give feedback.
-
Generic Syntax Tree Modification for Adding Leading CommentsI came across your scenario about generically modifying a Ballerina syntax tree (ST) to inject leading comments at the start of a file. Since I couldn’t find an existing solution, I crafted one myself. Below, I’m sharing my approach, an analysis of challenges I encountered, and some suggestions for potential API enhancements. Hope this helps! SolutionHere’s a working test case (paste it into
Output
This solution works generically, regardless of the file’s structure, unlike specific cases (e.g., modifying an import declaration). Observations and Challenges1. No Public API for First TokenThe internal 2. Why
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Playing around with modifying the syntax tree after a while. :) Today I encountered the scenario mentioned in the title. (Raised by @kalaiyarasiganeshalingam) As I couldn't find an already written similar code, thought of writing one myself.
One way of modifying ST is by knowing the internal structure. e.g. If we know the first line is an import declaration.
We could simply modify it by,
However, when the structure is unknown (generic scenario), I had to write one new method (
Token firstToken(Node node)
) and aTokenReplacer
by extending theTreeModifier
.My code is as follows (can run it by copying it to
SyntaxTreeModifierTest.java
class),firstToken()
) to get the first token of a givenSTNode
. However, no API to achieve the same in the external tree. So had to writeToken firstToken(Node node)
method. Should we add such API?syntaxTree.replaceNode()
returns a new syntax with the root being that token. I'm not sure why. So I ended up writing aTokenReplacer
to achieve the token replacement in the syntax tree.Want to make sure if the above is the best way to achieve it?
Beta Was this translation helpful? Give feedback.
All reactions