1 //===---- Query.cpp - clang-query query -----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Query.h"
10 #include "QuerySession.h"
11 #include "clang/AST/ASTDumper.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Frontend/ASTUnit.h"
14 #include "clang/Frontend/TextDiagnostic.h"
15 #include "llvm/Support/raw_ostream.h"
16 
17 using namespace clang::ast_matchers;
18 using namespace clang::ast_matchers::dynamic;
19 
20 namespace clang {
21 namespace query {
22 
23 Query::~Query() {}
24 
25 bool InvalidQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
26   OS << ErrStr << "\n";
27   return false;
28 }
29 
30 bool NoOpQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
31   return true;
32 }
33 
34 bool HelpQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
35   OS << "Available commands:\n\n"
36         "  match MATCHER, m MATCHER          "
37         "Match the loaded ASTs against the given matcher.\n"
38         "  let NAME MATCHER, l NAME MATCHER  "
39         "Give a matcher expression a name, to be used later\n"
40         "                                    "
41         "as part of other expressions.\n"
42         "  set bind-root (true|false)        "
43         "Set whether to bind the root matcher to \"root\".\n"
44         "  set print-matcher (true|false)    "
45         "Set whether to print the current matcher,\n"
46         "  set traversal <kind>              "
47         "Set traversal kind of clang-query session. Available kinds are:\n"
48         "    AsIs                            "
49         "Print and match the AST as clang sees it.  This mode is the "
50         "default.\n"
51         "    IgnoreUnlessSpelledInSource     "
52         "Omit AST nodes unless spelled in the source.\n"
53         "  set output <feature>              "
54         "Set whether to output only <feature> content.\n"
55         "  enable output <feature>           "
56         "Enable <feature> content non-exclusively.\n"
57         "  disable output <feature>          "
58         "Disable <feature> content non-exclusively.\n"
59         "  quit, q                           "
60         "Terminates the query session.\n\n"
61         "Several commands accept a <feature> parameter. The available features "
62         "are:\n\n"
63         "  print                             "
64         "Pretty-print bound nodes.\n"
65         "  diag                              "
66         "Diagnostic location for bound nodes.\n"
67         "  detailed-ast                      "
68         "Detailed AST output for bound nodes.\n"
69         "  dump                              "
70         "Detailed AST output for bound nodes (alias of detailed-ast).\n\n";
71   return true;
72 }
73 
74 bool QuitQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
75   QS.Terminate = true;
76   return true;
77 }
78 
79 namespace {
80 
81 struct CollectBoundNodes : MatchFinder::MatchCallback {
82   std::vector<BoundNodes> &Bindings;
83   CollectBoundNodes(std::vector<BoundNodes> &Bindings) : Bindings(Bindings) {}
84   void run(const MatchFinder::MatchResult &Result) override {
85     Bindings.push_back(Result.Nodes);
86   }
87 };
88 
89 } // namespace
90 
91 bool MatchQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
92   unsigned MatchCount = 0;
93 
94   for (auto &AST : QS.ASTs) {
95     MatchFinder Finder;
96     std::vector<BoundNodes> Matches;
97     DynTypedMatcher MaybeBoundMatcher = Matcher;
98     if (QS.BindRoot) {
99       llvm::Optional<DynTypedMatcher> M = Matcher.tryBind("root");
100       if (M)
101         MaybeBoundMatcher = *M;
102     }
103     CollectBoundNodes Collect(Matches);
104     if (!Finder.addDynamicMatcher(MaybeBoundMatcher, &Collect)) {
105       OS << "Not a valid top-level matcher.\n";
106       return false;
107     }
108 
109     AST->getASTContext().getParentMapContext().setTraversalKind(QS.TK);
110     Finder.matchAST(AST->getASTContext());
111 
112     if (QS.PrintMatcher) {
113       SmallVector<StringRef, 4> Lines;
114       Source.split(Lines, "\n");
115       auto FirstLine = Lines[0];
116       Lines.erase(Lines.begin(), Lines.begin() + 1);
117       while (!Lines.empty() && Lines.back().empty()) {
118         Lines.resize(Lines.size() - 1);
119       }
120       unsigned MaxLength = FirstLine.size();
121       std::string PrefixText = "Matcher: ";
122       OS << "\n  " << PrefixText << FirstLine;
123 
124       for (auto Line : Lines) {
125         OS << "\n" << std::string(PrefixText.size() + 2, ' ') << Line;
126         MaxLength = std::max<int>(MaxLength, Line.rtrim().size());
127       }
128 
129       OS << "\n"
130          << "  " << std::string(PrefixText.size() + MaxLength, '=') << "\n\n";
131     }
132 
133     for (auto MI = Matches.begin(), ME = Matches.end(); MI != ME; ++MI) {
134       OS << "\nMatch #" << ++MatchCount << ":\n\n";
135 
136       for (auto BI = MI->getMap().begin(), BE = MI->getMap().end(); BI != BE;
137            ++BI) {
138         if (QS.DiagOutput) {
139           clang::SourceRange R = BI->second.getSourceRange();
140           if (R.isValid()) {
141             TextDiagnostic TD(OS, AST->getASTContext().getLangOpts(),
142                               &AST->getDiagnostics().getDiagnosticOptions());
143             TD.emitDiagnostic(
144                 FullSourceLoc(R.getBegin(), AST->getSourceManager()),
145                 DiagnosticsEngine::Note, "\"" + BI->first + "\" binds here",
146                 CharSourceRange::getTokenRange(R), None);
147           }
148         }
149         if (QS.PrintOutput) {
150           OS << "Binding for \"" << BI->first << "\":\n";
151           BI->second.print(OS, AST->getASTContext().getPrintingPolicy());
152           OS << "\n";
153         }
154         if (QS.DetailedASTOutput) {
155           OS << "Binding for \"" << BI->first << "\":\n";
156           const ASTContext &Ctx = AST->getASTContext();
157           ASTDumper Dumper(OS, Ctx, AST->getDiagnostics().getShowColors());
158           Dumper.SetTraversalKind(QS.TK);
159           Dumper.Visit(BI->second);
160           OS << "\n";
161         }
162       }
163 
164       if (MI->getMap().empty())
165         OS << "No bindings.\n";
166     }
167   }
168 
169   OS << MatchCount << (MatchCount == 1 ? " match.\n" : " matches.\n");
170   return true;
171 }
172 
173 bool LetQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
174   if (Value) {
175     QS.NamedValues[Name] = Value;
176   } else {
177     QS.NamedValues.erase(Name);
178   }
179   return true;
180 }
181 
182 #ifndef _MSC_VER
183 const QueryKind SetQueryKind<bool>::value;
184 const QueryKind SetQueryKind<OutputKind>::value;
185 #endif
186 
187 } // namespace query
188 } // namespace clang
189