Is there a way to check if a function is virtual or not from the Eclipse CDT's AST?
I tried to perform this kind of check by using a visitor on the ICPPASTFunctionDeclarator node. It has the following methods: isOverride(), isPureVirtual(), isFinal(), etc. Something like isVirtual() is missing.
The C++ grammar has some oddities. One of them is that the function declarator production only covers the part of a function declaration starting from the function name (technically, it also includes any pointer operators from the function return type which precede the function name), and ending at the end of the function declaration (or the start of the function body).
The function's return type (again, except for pointer operators) and other specifiers that go at the beginning of the declaration (including virtual
) are part of a sibling node called the decl-specifier.
So, if your starting point is a function declarator, you have to navigate to the decl-specifier via its parent. The parent can be either a simple declaration (in case of a function declaration without a body) or a function definition (declaration with body), and you have to check for each case.
Once you have the decl-specifier, you can check for virtual using ICPPASTDeclSpecifier.isVirtual()
.
In code:
// declarator is your ICPPASTFunctionDeclarator
ICPPASTDeclSpecifier declSpec = null;
if (declarator.getParent() instanceof IASTSimpleDeclaration) {
declSpec = (ICPPASTDeclSpecifier) ((IASTSimpleDeclaration) declarator.getParent()).getDeclSpecifier();
} else if (declarator.getParent() instanceof IASTFunctionDefinition) {
declSpec = (ICPPASTDeclSpecifier) ((IASTFunctionDefinition) declarator.getParent()).getDeclSpecifier();
}
if (declSpec != null) {
boolean isVirtual = declSpec.isVirtual();
}
Finally, note that what the above tells you is whether the virtual
keyword appears in the function's declaration.
A function can be virtual without the virtual
keyword appearing in its declaration, if it's a function in a derived class overriding a virtual function in a base class.
If what you really want to know is whether the function is virtual, even if the virtual
keyword is not used, that's more involved. I don't think there's an easy way to do it using CDT's public APIs, but it gets easier if you're willing to use internal APIs. Let me know if you're interested in that, I can provide more details.