abstract syntax tree - Remove LineComment in Java AST -
I am trying to delete a line comment from a Java file via AST. I read the document from a source file, make an AST parser (AST. JLS3) and later I make an example of a compilation unit and astrrit.
doctor = new document (theory); Parser = ATPPerser NEPERS (AST. JLS3); Parser.set ource (doc.get (). ToCharArray ()); Cu = (Compilation Unit) Parser. Cucket (null); AstRewrite = Astraite. Curate (QAATA.T.T.); Not quite anything yet, I'm able to add and remove fields. Now I am trying to remove comments from the unit with the following code:
@SuppressWarnings ("uncheck") final list & lt; Comment & gt; Comments = (list & lt; comment & gt;) cu.getCommentList (); Last Iterator & lt; Comment & gt; Comment = Comment =. While (CommentErter hasNext ()) {Last comment by curcomment = commentIter.next (); If (curcomment.isLineComment ()) {last line comment line comment = (line comment) curcomment; Line Comment.accept (new comment copyright field widget (cu, document.get (), astRewrite); }} The visitor should act and delete the comment here.
Expands the Public Category CommentFieldVisitor ASTVisitor {Final Collection UNIT cu; Last string source code; Last Asthrstrite astRewrite; Public CommentFieldVisitor (final compilation cu, last string source code, last aststright astRewrite) {this.cu = cu; This.sourceCode = sourceCode; This.astRewrite = astRewrite; } @ Override Public Boolean Visit (Last Line Comment Comment node) {int start = commentNode.getStartPosition (); Int end = start + commentNode.getLength (); Last String Comment = sourceCode.substring (start, end); Last String Field Comment = Config.INSTANCE.getTargetField Comment (); If (comment! = Null & amp; comment.Ageal Ignore Sees (field comment)) {System.out.println ("Remover Remark"); Claim AstRewrite! = Faucet: "Error: ASER recurrier is empty"; AstRewrite.remove (comment node, tap); } return false; }} I repeat all comments in the compilation unit, I make a visitor for every comment in the list. Check this visitor, if the content of the comment is equal to a pre-structured string, if it does, then it should be removed. Although I call
astRewrite.remove (commentNode, null); Let me always get a NPE from inside the extract method. AstRewrite and commentNode are defined (because the code to be extracted is reached.)
Do anyone have an idea, what am I doing wrong? Or how to remove such comments from AST?
I have managed this through a workaround that is comment .getStartPosition () < / Code> and comments .getLength () . I use these sources to remove my source code from the file and replace it with "". After that I need to recreate the AST tree with the modified source code. It's far from perfect, but I did not find an alternative solution
Comments
Post a Comment