clang-tools 20.0.0git
QueryParser.cpp
Go to the documentation of this file.
1//===---- QueryParser.cpp - clang-query command parser --------------------===//
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 "QueryParser.h"
10#include "Query.h"
11#include "QuerySession.h"
12#include "clang/ASTMatchers/Dynamic/Parser.h"
13#include "clang/Basic/CharInfo.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/StringSwitch.h"
16#include <optional>
17#include <set>
18
19using namespace llvm;
20using namespace clang::ast_matchers::dynamic;
21
22namespace clang {
23namespace query {
24
25// Lex any amount of whitespace followed by a "word" (any sequence of
26// non-whitespace characters) from the start of region [Begin,End). If no word
27// is found before End, return StringRef(). Begin is adjusted to exclude the
28// lexed region.
29StringRef QueryParser::lexWord() {
30 // Don't trim newlines.
31 Line = Line.ltrim(" \t\v\f\r");
32
33 if (Line.empty())
34 // Even though the Line is empty, it contains a pointer and
35 // a (zero) length. The pointer is used in the LexOrCompleteWord
36 // code completion.
37 return Line;
38
39 StringRef Word;
40 if (Line.front() == '#')
41 Word = Line.substr(0, 1);
42 else
43 Word = Line.take_until(isWhitespace);
44
45 Line = Line.drop_front(Word.size());
46 return Word;
47}
48
49// This is the StringSwitch-alike used by lexOrCompleteWord below. See that
50// function for details.
51template <typename T> struct QueryParser::LexOrCompleteWord {
52 StringRef Word;
53 StringSwitch<T> Switch;
54
56 // Set to the completion point offset in Word, or StringRef::npos if
57 // completion point not in Word.
59
60 // Lexes a word and stores it in Word. Returns a LexOrCompleteWord<T> object
61 // that can be used like a llvm::StringSwitch<T>, but adds cases as possible
62 // completions if the lexed word contains the completion point.
63 LexOrCompleteWord(QueryParser *P, StringRef &OutWord)
64 : Word(P->lexWord()), Switch(Word), P(P),
65 WordCompletionPos(StringRef::npos) {
66 OutWord = Word;
67 if (P->CompletionPos && P->CompletionPos <= Word.data() + Word.size()) {
68 if (P->CompletionPos < Word.data())
70 else
71 WordCompletionPos = P->CompletionPos - Word.data();
72 }
73 }
74
75 LexOrCompleteWord &Case(llvm::StringLiteral CaseStr, const T &Value,
76 bool IsCompletion = true) {
77
78 if (WordCompletionPos == StringRef::npos)
79 Switch.Case(CaseStr, Value);
80 else if (CaseStr.size() != 0 && IsCompletion && WordCompletionPos <= CaseStr.size() &&
81 CaseStr.substr(0, WordCompletionPos) ==
82 Word.substr(0, WordCompletionPos))
83 P->Completions.push_back(LineEditor::Completion(
84 (CaseStr.substr(WordCompletionPos) + " ").str(),
85 std::string(CaseStr)));
86 return *this;
87 }
88
89 T Default(T Value) { return Switch.Default(Value); }
90};
91
92QueryRef QueryParser::parseSetBool(bool QuerySession::*Var) {
93 StringRef ValStr;
94 unsigned Value = LexOrCompleteWord<unsigned>(this, ValStr)
95 .Case("false", 0)
96 .Case("true", 1)
97 .Default(~0u);
98 if (Value == ~0u) {
99 return new InvalidQuery("expected 'true' or 'false', got '" + ValStr + "'");
100 }
101 return new SetQuery<bool>(Var, Value);
102}
103
104template <typename QueryType> QueryRef QueryParser::parseSetOutputKind() {
105 StringRef ValStr;
106 unsigned OutKind = LexOrCompleteWord<unsigned>(this, ValStr)
107 .Case("diag", OK_Diag)
108 .Case("print", OK_Print)
109 .Case("detailed-ast", OK_DetailedAST)
110 .Case("dump", OK_DetailedAST)
111 .Default(~0u);
112 if (OutKind == ~0u) {
113 return new InvalidQuery("expected 'diag', 'print', 'detailed-ast' or "
114 "'dump', got '" +
115 ValStr + "'");
116 }
117
118 switch (OutKind) {
119 case OK_DetailedAST:
120 return new QueryType(&QuerySession::DetailedASTOutput);
121 case OK_Diag:
122 return new QueryType(&QuerySession::DiagOutput);
123 case OK_Print:
124 return new QueryType(&QuerySession::PrintOutput);
125 }
126
127 llvm_unreachable("Invalid output kind");
128}
129
130QueryRef QueryParser::parseSetTraversalKind(TraversalKind QuerySession::*Var) {
131 StringRef ValStr;
132 unsigned Value =
133 LexOrCompleteWord<unsigned>(this, ValStr)
134 .Case("AsIs", TK_AsIs)
135 .Case("IgnoreUnlessSpelledInSource", TK_IgnoreUnlessSpelledInSource)
136 .Default(~0u);
137 if (Value == ~0u) {
138 return new InvalidQuery("expected traversal kind, got '" + ValStr + "'");
139 }
140 return new SetQuery<TraversalKind>(Var, static_cast<TraversalKind>(Value));
141}
142
143QueryRef QueryParser::endQuery(QueryRef Q) {
144 StringRef Extra = Line;
145 StringRef ExtraTrimmed = Extra.ltrim(" \t\v\f\r");
146
147 if (ExtraTrimmed.starts_with('\n') || ExtraTrimmed.starts_with("\r\n"))
148 Q->RemainingContent = Extra;
149 else {
150 StringRef TrailingWord = lexWord();
151 if (TrailingWord.starts_with('#')) {
152 Line = Line.drop_until([](char c) { return c == '\n'; });
153 Line = Line.drop_while([](char c) { return c == '\n'; });
154 return endQuery(Q);
155 }
156 if (!TrailingWord.empty()) {
157 return new InvalidQuery("unexpected extra input: '" + Extra + "'");
158 }
159 }
160 return Q;
161}
162
163namespace {
164
165enum ParsedQueryKind {
166 PQK_Invalid,
167 PQK_Comment,
168 PQK_NoOp,
169 PQK_Help,
170 PQK_Let,
171 PQK_Match,
172 PQK_Set,
173 PQK_Unlet,
174 PQK_Quit,
175 PQK_Enable,
176 PQK_Disable,
177 PQK_File
178};
179
180enum ParsedQueryVariable {
181 PQV_Invalid,
182 PQV_Output,
183 PQV_BindRoot,
184 PQV_PrintMatcher,
185 PQV_Traversal
186};
187
188QueryRef makeInvalidQueryFromDiagnostics(const Diagnostics &Diag) {
189 std::string ErrStr;
190 llvm::raw_string_ostream OS(ErrStr);
191 Diag.printToStreamFull(OS);
192 return new InvalidQuery(OS.str());
193}
194
195} // namespace
196
197QueryRef QueryParser::completeMatcherExpression() {
198 std::vector<MatcherCompletion> Comps = Parser::completeExpression(
199 Line, CompletionPos - Line.begin(), nullptr, &QS.NamedValues);
200 for (auto I = Comps.begin(), E = Comps.end(); I != E; ++I) {
201 Completions.push_back(LineEditor::Completion(I->TypedText, I->MatcherDecl));
202 }
203 return QueryRef();
204}
205
206QueryRef QueryParser::doParse() {
207 StringRef CommandStr;
208 ParsedQueryKind QKind = LexOrCompleteWord<ParsedQueryKind>(this, CommandStr)
209 .Case("", PQK_NoOp)
210 .Case("#", PQK_Comment, /*IsCompletion=*/false)
211 .Case("help", PQK_Help)
212 .Case("l", PQK_Let, /*IsCompletion=*/false)
213 .Case("let", PQK_Let)
214 .Case("m", PQK_Match, /*IsCompletion=*/false)
215 .Case("match", PQK_Match)
216 .Case("q", PQK_Quit, /*IsCompletion=*/false)
217 .Case("quit", PQK_Quit)
218 .Case("set", PQK_Set)
219 .Case("enable", PQK_Enable)
220 .Case("disable", PQK_Disable)
221 .Case("unlet", PQK_Unlet)
222 .Case("f", PQK_File, /*IsCompletion=*/false)
223 .Case("file", PQK_File)
224 .Default(PQK_Invalid);
225
226 switch (QKind) {
227 case PQK_Comment:
228 case PQK_NoOp:
229 Line = Line.drop_until([](char c) { return c == '\n'; });
230 Line = Line.drop_while([](char c) { return c == '\n'; });
231 if (Line.empty())
232 return new NoOpQuery;
233 return doParse();
234
235 case PQK_Help:
236 return endQuery(new HelpQuery);
237
238 case PQK_Quit:
239 return endQuery(new QuitQuery);
240
241 case PQK_Let: {
242 StringRef Name = lexWord();
243
244 if (Name.empty())
245 return new InvalidQuery("expected variable name");
246
247 if (CompletionPos)
248 return completeMatcherExpression();
249
250 Diagnostics Diag;
251 ast_matchers::dynamic::VariantValue Value;
252 if (!Parser::parseExpression(Line, nullptr, &QS.NamedValues, &Value,
253 &Diag)) {
254 return makeInvalidQueryFromDiagnostics(Diag);
255 }
256
257 auto *Q = new LetQuery(Name, Value);
258 Q->RemainingContent = Line;
259 return Q;
260 }
261
262 case PQK_Match: {
263 if (CompletionPos)
264 return completeMatcherExpression();
265
266 Diagnostics Diag;
267 auto MatcherSource = Line.ltrim();
268 auto OrigMatcherSource = MatcherSource;
269 std::optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(
270 MatcherSource, nullptr, &QS.NamedValues, &Diag);
271 if (!Matcher) {
272 return makeInvalidQueryFromDiagnostics(Diag);
273 }
274 auto ActualSource = OrigMatcherSource.slice(0, OrigMatcherSource.size() -
275 MatcherSource.size());
276 auto *Q = new MatchQuery(ActualSource, *Matcher);
277 Q->RemainingContent = MatcherSource;
278 return Q;
279 }
280
281 case PQK_Set: {
282 StringRef VarStr;
283 ParsedQueryVariable Var =
284 LexOrCompleteWord<ParsedQueryVariable>(this, VarStr)
285 .Case("output", PQV_Output)
286 .Case("bind-root", PQV_BindRoot)
287 .Case("print-matcher", PQV_PrintMatcher)
288 .Case("traversal", PQV_Traversal)
289 .Default(PQV_Invalid);
290 if (VarStr.empty())
291 return new InvalidQuery("expected variable name");
292 if (Var == PQV_Invalid)
293 return new InvalidQuery("unknown variable: '" + VarStr + "'");
294
295 QueryRef Q;
296 switch (Var) {
297 case PQV_Output:
298 Q = parseSetOutputKind<SetExclusiveOutputQuery>();
299 break;
300 case PQV_BindRoot:
301 Q = parseSetBool(&QuerySession::BindRoot);
302 break;
303 case PQV_PrintMatcher:
304 Q = parseSetBool(&QuerySession::PrintMatcher);
305 break;
306 case PQV_Traversal:
307 Q = parseSetTraversalKind(&QuerySession::TK);
308 break;
309 case PQV_Invalid:
310 llvm_unreachable("Invalid query kind");
311 }
312
313 return endQuery(Q);
314 }
315 case PQK_Enable:
316 case PQK_Disable: {
317 StringRef VarStr;
318 ParsedQueryVariable Var =
319 LexOrCompleteWord<ParsedQueryVariable>(this, VarStr)
320 .Case("output", PQV_Output)
321 .Default(PQV_Invalid);
322 if (VarStr.empty())
323 return new InvalidQuery("expected variable name");
324 if (Var == PQV_Invalid)
325 return new InvalidQuery("unknown variable: '" + VarStr + "'");
326
327 QueryRef Q;
328
329 if (QKind == PQK_Enable)
330 Q = parseSetOutputKind<EnableOutputQuery>();
331 else if (QKind == PQK_Disable)
332 Q = parseSetOutputKind<DisableOutputQuery>();
333 else
334 llvm_unreachable("Invalid query kind");
335 return endQuery(Q);
336 }
337
338 case PQK_Unlet: {
339 StringRef Name = lexWord();
340
341 if (Name.empty())
342 return new InvalidQuery("expected variable name");
343
344 return endQuery(new LetQuery(Name, VariantValue()));
345 }
346
347 case PQK_File:
348 return new FileQuery(Line);
349
350 case PQK_Invalid:
351 return new InvalidQuery("unknown command: " + CommandStr);
352 }
353
354 llvm_unreachable("Invalid query kind");
355}
356
358 return QueryParser(Line, QS).doParse();
359}
360
361std::vector<LineEditor::Completion>
362QueryParser::complete(StringRef Line, size_t Pos, const QuerySession &QS) {
363 QueryParser P(Line, QS);
364 P.CompletionPos = Line.data() + Pos;
365
366 P.doParse();
367 return P.Completions;
368}
369
370} // namespace query
371} // namespace clang
const Expr * E
llvm::SmallString< 256U > Name
std::string Word
size_t Pos
WantDiagnostics Diagnostics
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:160
static QueryRef parse(StringRef Line, const QuerySession &QS)
Parse Line as a query.
static std::vector< llvm::LineEditor::Completion > complete(StringRef Line, size_t Pos, const QuerySession &QS)
Compute a list of completions for Line assuming a cursor at.
Represents the state for a particular clang-query session.
Definition: QuerySession.h:24
llvm::StringMap< ast_matchers::dynamic::VariantValue > NamedValues
Definition: QuerySession.h:42
llvm::IntrusiveRefCntPtr< Query > QueryRef
Definition: Query.h:52
@ OK_Diag
Definition: Query.h:20
@ OK_Print
Definition: Query.h:20
@ OK_DetailedAST
Definition: Query.h:20
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Some operations such as code completion produce a set of candidates.
Any query which resulted in a parse error. The error message is in ErrStr.
Definition: Query.h:55
LexOrCompleteWord & Case(llvm::StringLiteral CaseStr, const T &Value, bool IsCompletion=true)
Definition: QueryParser.cpp:75
LexOrCompleteWord(QueryParser *P, StringRef &OutWord)
Definition: QueryParser.cpp:63