xref: /llvm-project/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp (revision c01d3fbe0f29836890abb16bc834ce9950bdb3ea)
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 
15 #include "clang/Frontend/FrontendPluginRegistry.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/AST.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "clang/Frontend/FrontendActions.h"
21 using namespace clang;
22 
23 namespace {
24 
25 class PrintFunctionsConsumer : public ASTConsumer {
26 public:
27   virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
28     for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) {
29       const Decl *D = *i;
30       if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
31         llvm::errs() << "top-level-decl: \"" << ND->getNameAsString() << "\"\n";
32     }
33 
34     return true;
35   }
36 };
37 
38 class PrintFunctionNamesAction : public PluginASTAction {
39 protected:
40   ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
41     return new PrintFunctionsConsumer();
42   }
43 
44   bool ParseArgs(const CompilerInstance &CI,
45                  const std::vector<std::string>& args) {
46     for (unsigned i = 0, e = args.size(); i != e; ++i) {
47       llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n";
48 
49       // Example error handling.
50       if (args[i] == "-an-error") {
51         DiagnosticsEngine &D = CI.getDiagnostics();
52         unsigned DiagID = D.getCustomDiagID(
53           DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
54         D.Report(DiagID);
55         return false;
56       }
57     }
58     if (args.size() && args[0] == "help")
59       PrintHelp(llvm::errs());
60 
61     return true;
62   }
63   void PrintHelp(llvm::raw_ostream& ros) {
64     ros << "Help for PrintFunctionNames plugin goes here\n";
65   }
66 
67 };
68 
69 }
70 
71 static FrontendPluginRegistry::Add<SyntaxOnlyAction>
72 X("print-fns", "print function names");
73