PrintFunctionNames.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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/ASTConsumer.h"
  16. #include "clang/AST/AST.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. virtual void HandleTopLevelDecl(DeclGroupRef DG) {
  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. }
  30. };
  31. class PrintFunctionNamesAction : public PluginASTAction {
  32. protected:
  33. ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
  34. return new PrintFunctionsConsumer();
  35. }
  36. bool ParseArgs(const CompilerInstance &CI,
  37. const std::vector<std::string>& args) {
  38. for (unsigned i = 0, e = args.size(); i != e; ++i) {
  39. llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n";
  40. // Example error handling.
  41. if (args[i] == "-an-error") {
  42. DiagnosticsEngine &D = CI.getDiagnostics();
  43. unsigned DiagID = D.getCustomDiagID(
  44. DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
  45. D.Report(DiagID);
  46. return false;
  47. }
  48. }
  49. if (args.size() && args[0] == "help")
  50. PrintHelp(llvm::errs());
  51. return true;
  52. }
  53. void PrintHelp(llvm::raw_ostream& ros) {
  54. ros << "Help for PrintFunctionNames plugin goes here\n";
  55. }
  56. };
  57. }
  58. static FrontendPluginRegistry::Add<PrintFunctionNamesAction>
  59. X("print-fns", "print function names");