如何使用clang API解析函数指针的typedef以获取函数指针名称? [英] How can I parse a typedef for a function pointer using clang API to get the function pointer name?

查看:1013
本文介绍了如何使用clang API解析函数指针的typedef以获取函数指针名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用clang C API构建一个用于C ++代码的解析器。解析器将处理一个头文件并为其生成一个定义和缺失符号的列表(它忽略包含指令,因此它将严格解析头的内容)。我的问题是,如果我有一个 typedef 为一个函数指针,接受一个未定义类型的参数,如:

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);

AST作为typedef解析 SOME_TYPE funcPtrName 。如果我用 int 替换 SOME_UNDEF_TYPE ,它会正确解析 funcPtrName

the AST parses SOME_TYPE as the typedef instead of funcPtrName. If I replace SOME_UNDEF_TYPE with int, it parses funcPtrName correctly.

我想我可以使用 clang_tokenize 获取游标的所有标记,并手动获取函数指针名称,但是在指向typedef的游标上调用 clang_getCursorExtent 无法正常工作(返回的范围为0,0)。

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?

推荐答案

我已经设法解决这个问题,翻译单元中的所有令牌并将其传递给访问者函数。当我到达 CXCursor_TypedefDecl 游标时,我在令牌列表中搜索<​​code> typedef 名称,然后检查下一个令牌是。如果是这样,请等待 * 之后的第一个令牌,这将是函数指针的名称

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.

以下是一些示例代码:

   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 };
   }

这篇关于如何使用clang API解析函数指针的typedef以获取函数指针名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆