问题
I am currently building a parser for C++ code using the clang C API. The parser will process a header file and generate a list of defined and missing symbols for it (it ignores include directives, so it will parse strictly the contents of the header). My problem is, if I have a typedef for a function pointer which takes an argument of an undefined type, such as:
typedef SOME_TYPE (* funcPtrName)(SOME_UNDEF_TYPE x);
the AST parses SOME_TYPE as the typedef instead of funcPtrName. If I replace SOME_UNDEF_TYPE with int, it parses funcPtrName correctly.
I thought I could use clang_tokenize to get all the tokens for the cursor and manually get the function pointer name, but calling clang_getCursorExtent on the cursor pointing to the typedef does not work correctly (the range returned is 0,0).
Do you know any way around this issue?
回答1:
I did manage to work around the issue by building a list of all the tokens in the translation unit and passing that over to the visitor function. When I reached the CXCursor_TypedefDecl cursor, I searched for the typedef name in the tokens list and then checked if the next token is (. If so, look forward to the first token after *, which will be the name of the function pointer.
Here is some sample code:
std::string symbol = clang_getCString(clang_getCursorSpelling(Cursor));
...
case CXCursor_TypedefDecl:
{
auto finder = std::find(tokens.begin(), tokens.end(), symbol);
if (*(finder + 1) == "(")
{
auto next = std::find(finder, parserData->tokens.end(), "*") + 1;
symbol = *next;
}
symbolData[symbol] = SymbolInfo{ cursorKind, fileName };
}
来源:https://stackoverflow.com/questions/24054433/how-can-i-parse-a-typedef-for-a-function-pointer-using-clang-api-to-get-the-func