PrintFunctionNames.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //===- PrintFunctionNames.cpp ---------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Example clang plugin which simply prints the names of all the top-level decls
  11. // in the input file.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Frontend/FrontendPluginRegistry.h"
  15. #include "clang/AST/AST.h"
  16. #include "clang/AST/ASTConsumer.h"
  17. #include "clang/Frontend/CompilerInstance.h"
  18. #include "llvm/Support/raw_ostream.h"
  19. using namespace clang;
  20. namespace {
  21. class PrintFunctionsConsumer : public ASTConsumer {
  22. public:
  23. bool HandleTopLevelDecl(DeclGroupRef DG) override {
  24. for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) {
  25. const Decl *D = *i;
  26. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  27. llvm::errs() << "top-level-decl: \"" << ND->getNameAsString() << "\"\n";
  28. }
  29. return true;
  30. }
  31. };
  32. class PrintFunctionNamesAction : public PluginASTAction {
  33. protected:
  34. std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
  35. llvm::StringRef) override {
  36. return llvm::make_unique<PrintFunctionsConsumer>();
  37. }
  38. bool ParseArgs(const CompilerInstance &CI,
  39. const std::vector<std::string> &args) override {
  40. for (unsigned i = 0, e = args.size(); i != e; ++i) {
  41. llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n";
  42. // Example error handling.
  43. if (args[i] == "-an-error") {
  44. DiagnosticsEngine &D = CI.getDiagnostics();
  45. unsigned DiagID = D.getCustomDiagID(DiagnosticsEngine::Error,
  46. "invalid argument '%0'");
  47. D.Report(DiagID) << args[i];
  48. return false;
  49. }
  50. }
  51. if (!args.empty() && args[0] == "help")
  52. PrintHelp(llvm::errs());
  53. return true;
  54. }
  55. void PrintHelp(llvm::raw_ostream& ros) {
  56. ros << "Help for PrintFunctionNames plugin goes here\n";
  57. }
  58. };
  59. }
  60. static FrontendPluginRegistry::Add<PrintFunctionNamesAction>
  61. X("print-fns", "print function names");