How to bind IASTComment to IASTDeclaration in CDT ASTParser
I am using CDT ASTParser to parse some content of a C / C ++ source file. Example:
//Docs for function min
int min(int a[], int n) {
//Comment here
}
int min1(){}
/*
Docs for function min2
*/
int min2(){}
Using ASTVisitor, I can parse the function definition list in code, but I don't know how to "link" the IASTComment above the definition code:
void handle(IASTTranslationUnit unit){
unit.accept(new ASTVisitor() {
{ shouldVisitDeclarations = true; }
@Override
public int visit(IASTDeclaration declaration) {
if (declaration instanceof IASTFunctionDefinition) {
IASTFunctionDefinition fnDefine =
(IASTFunctionDefinition) declaration;
IASTFunctionDeclarator fnDeclare = fnDefine.getDeclarator();
System.out.printf("Function: %s, type: %s, comment: %s\n",
fnDeclare.getName().getRawSignature(),
fnDefine.getDeclSpecifier().getRawSignature(),
"Somehow get the comment above function define???"
);
}
return PROCESS_SKIP;
}
@Override
public int visit(IASTComment comment) {
System.out.println("Comment: " + comment.getRawSignature());
return PROCESS_CONTINUE;
}
});
for (IASTComment cmt: unit.getComments())
System.out.println("Comment: " + cmt.getRawSignature());
}
The class visit(IASTComment comment)
in the ASTVisitor class has been deprecated and the method IASTTranslationUnit.getComments()
just returns a list of comments in the complete source file, there is no structure here.
So how do you get the IASTComment object that refers to the function definition (if any)?
source to share
You can use ASTCommenter.getCommentedNodeMap(IASTTranslationUnit)
in a package org.eclipse.cdt.internal.core.dom.rewrite.commenthandler
. The method returns a NodeCommentMap
, which displays the comments for the nodes in the AST. There are three types of comments that can be assigned to a node. In the example below, the declartion method is node:
//this is a leading comment
void method() //this is a trailing comment
//this is a freestanding comment
{
...
NodeCommentMap.getOffsetIncludingComments(IASTNode)
returns the offset of a node including its assigned leading comments. NodeCommentMap.getEndOffsetIncludingComments(IASTNode)
returns the offset of the end of the node, including the assigned trailing comments. The assigned independent comments must be handled by itself. You can get free comments using NodeCommentMap.getFreestandingCommentsForNode(IASTNode)
. At least I couldn't find the default approach in the cdt packages.
If you want to know more, it is advisable to read the documentation in the following classes:
-
org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.ASTCommenter
-
org.eclipse.cdt.core.parser.tests.rewrite.comenthandler.CommentHandlingTest
-
org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommenter
Note. Most of these packages / classes are internal.
source to share