使用clang获取类中的方法列表

Kon*_*ine 10 c++ parsing clang code-inspection outliner

在常见的IDE(选择一个)中,您经常会有一个大纲视图,显示特定类的方法列表.

假设我有一个C++接口类IFoo.h,如下所示:

#ifndef IFOO_H_
#define IFOO_H_
class IFoo { 
    public:
        virtual ~IFoo() {}
        virtual void bar() = 0;
};
#endif
Run Code Online (Sandbox Code Playgroud)

如何(以编程方式)我可以IFoo.h使用clang库获取上面文件的IDE大纲列表?对于第一次启动,如果我可以获得函数名称列表将会有所帮助.

我特意打算使用clang,所以任何关于如何用clang分析我的头文件的帮助都会非常感激.

同时我将在这里看一下clang教程:https://github.com/loarabia/Clang-tutorial

在此先感谢您的帮助.

Kon*_*ine 14

我浏览了这个教程http://clang.llvm.org/docs/LibASTMatchersTutorial.html,发现了一些非常有用的东西,这就是我提出的:

我不得不重新命名我的文件IFoo.h,以IFoo.hpp作为CXX被检测,而不是C代码.

我不得不调用我的程序-x c++将我的IFoo.h文件识别为C++代码而不是C代码(clang *.h默认将文件解释为C:

~/Development/llvm-build/bin/mytool ~/IFoo.h -- -x c++
Run Code Online (Sandbox Code Playgroud)

这是我从提供的类转储所有虚函数的代码:

// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/ASTMatchers/ASTMatchers.h"
// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"

#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

#include <cstdio>

using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;

DeclarationMatcher methodMatcher = methodDecl(isVirtual()).bind("methods");

class MethodPrinter : public MatchFinder::MatchCallback {
public :
  virtual void run(const MatchFinder::MatchResult &Result) {
    if (const CXXMethodDecl *md = Result.Nodes.getNodeAs<clang::CXXMethodDecl>("methods")) {    
      md->dump();
    }
  }
};

// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);

// A help message for this specific tool can be added afterwards.
static cl::extrahelp MoreHelp("\nMore help text...");

int main(int argc, const char **argv) {    
  cl::OptionCategory cat("myname", "mydescription");
  CommonOptionsParser optionsParser(argc, argv, cat, 0);    

  ClangTool tool(optionsParser.getCompilations(), optionsParser.getSourcePathList());

  MethodPrinter printer;
  MatchFinder finder;
  finder.addMatcher(methodMatcher, &printer);
  return tool.run(newFrontendActionFactory(&finder));
}
Run Code Online (Sandbox Code Playgroud)

传递IFoo.h文件时,输出如下所示:

CXXDestructorDecl 0x1709c30 <~/IFoo.h:5:3, col:20> ~IFoo 'void (void)' virtual
`-CompoundStmt 0x1758128 <col:19, col:20>
CXXMethodDecl 0x1757e60 <~/IFoo.h:6:3, col:24> bar 'void (void)' virtual pure
Run Code Online (Sandbox Code Playgroud)