1 //===--- Parser.cpp - Matcher expression parser -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Recursive parser implementation for the matcher expression grammar.
13 //===----------------------------------------------------------------------===//
15 #include "clang/ASTMatchers/Dynamic/Parser.h"
16 #include "clang/ASTMatchers/Dynamic/Registry.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Support/ManagedStatic.h"
25 namespace ast_matchers {
28 /// \brief Simple structure to hold information for one token from the parser.
29 struct Parser::TokenInfo {
30 /// \brief Different possible tokens.
44 /// \brief Some known identifiers.
45 static const char* const ID_Bind;
47 TokenInfo() : Text(), Kind(TK_Eof), Range(), Value() {}
55 const char* const Parser::TokenInfo::ID_Bind = "bind";
57 /// \brief Simple tokenizer for the parser.
58 class Parser::CodeTokenizer {
60 explicit CodeTokenizer(StringRef MatcherCode, Diagnostics *Error)
61 : Code(MatcherCode), StartOfLine(MatcherCode), Line(1), Error(Error),
62 CodeCompletionLocation(nullptr) {
63 NextToken = getNextToken();
66 CodeTokenizer(StringRef MatcherCode, Diagnostics *Error,
67 unsigned CodeCompletionOffset)
68 : Code(MatcherCode), StartOfLine(MatcherCode), Line(1), Error(Error),
69 CodeCompletionLocation(MatcherCode.data() + CodeCompletionOffset) {
70 NextToken = getNextToken();
73 /// \brief Returns but doesn't consume the next token.
74 const TokenInfo &peekNextToken() const { return NextToken; }
76 /// \brief Consumes and returns the next token.
77 TokenInfo consumeNextToken() {
78 TokenInfo ThisToken = NextToken;
79 NextToken = getNextToken();
83 TokenInfo::TokenKind nextTokenKind() const { return NextToken.Kind; }
86 TokenInfo getNextToken() {
89 Result.Range.Start = currentLocation();
91 if (CodeCompletionLocation && CodeCompletionLocation <= Code.data()) {
92 Result.Kind = TokenInfo::TK_CodeCompletion;
93 Result.Text = StringRef(CodeCompletionLocation, 0);
94 CodeCompletionLocation = nullptr;
99 Result.Kind = TokenInfo::TK_Eof;
106 Result.Kind = TokenInfo::TK_Comma;
107 Result.Text = Code.substr(0, 1);
108 Code = Code.drop_front();
111 Result.Kind = TokenInfo::TK_Period;
112 Result.Text = Code.substr(0, 1);
113 Code = Code.drop_front();
116 Result.Kind = TokenInfo::TK_OpenParen;
117 Result.Text = Code.substr(0, 1);
118 Code = Code.drop_front();
121 Result.Kind = TokenInfo::TK_CloseParen;
122 Result.Text = Code.substr(0, 1);
123 Code = Code.drop_front();
128 // Parse a string literal.
129 consumeStringLiteral(&Result);
132 case '0': case '1': case '2': case '3': case '4':
133 case '5': case '6': case '7': case '8': case '9':
134 // Parse an unsigned literal.
135 consumeUnsignedLiteral(&Result);
139 if (isAlphanumeric(Code[0])) {
140 // Parse an identifier
141 size_t TokenLength = 1;
143 // A code completion location in/immediately after an identifier will
144 // cause the portion of the identifier before the code completion
145 // location to become a code completion token.
146 if (CodeCompletionLocation == Code.data() + TokenLength) {
147 CodeCompletionLocation = nullptr;
148 Result.Kind = TokenInfo::TK_CodeCompletion;
149 Result.Text = Code.substr(0, TokenLength);
150 Code = Code.drop_front(TokenLength);
153 if (TokenLength == Code.size() || !isAlphanumeric(Code[TokenLength]))
157 Result.Kind = TokenInfo::TK_Ident;
158 Result.Text = Code.substr(0, TokenLength);
159 Code = Code.drop_front(TokenLength);
161 Result.Kind = TokenInfo::TK_InvalidChar;
162 Result.Text = Code.substr(0, 1);
163 Code = Code.drop_front(1);
168 Result.Range.End = currentLocation();
172 /// \brief Consume an unsigned literal.
173 void consumeUnsignedLiteral(TokenInfo *Result) {
175 if (Code.size() > 1) {
176 // Consume the 'x' or 'b' radix modifier, if present.
177 switch (toLowercase(Code[1])) {
178 case 'x': case 'b': Length = 2;
181 while (Length < Code.size() && isHexDigit(Code[Length]))
184 Result->Text = Code.substr(0, Length);
185 Code = Code.drop_front(Length);
188 if (!Result->Text.getAsInteger(0, Value)) {
189 Result->Kind = TokenInfo::TK_Literal;
190 Result->Value = Value;
193 Range.Start = Result->Range.Start;
194 Range.End = currentLocation();
195 Error->addError(Range, Error->ET_ParserUnsignedError) << Result->Text;
196 Result->Kind = TokenInfo::TK_Error;
200 /// \brief Consume a string literal.
202 /// \c Code must be positioned at the start of the literal (the opening
203 /// quote). Consumed until it finds the same closing quote character.
204 void consumeStringLiteral(TokenInfo *Result) {
205 bool InEscape = false;
206 const char Marker = Code[0];
207 for (size_t Length = 1, Size = Code.size(); Length != Size; ++Length) {
212 if (Code[Length] == '\\') {
216 if (Code[Length] == Marker) {
217 Result->Kind = TokenInfo::TK_Literal;
218 Result->Text = Code.substr(0, Length + 1);
219 Result->Value = Code.substr(1, Length - 1).str();
220 Code = Code.drop_front(Length + 1);
225 StringRef ErrorText = Code;
226 Code = Code.drop_front(Code.size());
228 Range.Start = Result->Range.Start;
229 Range.End = currentLocation();
230 Error->addError(Range, Error->ET_ParserStringError) << ErrorText;
231 Result->Kind = TokenInfo::TK_Error;
234 /// \brief Consume all leading whitespace from \c Code.
235 void consumeWhitespace() {
236 while (!Code.empty() && isWhitespace(Code[0])) {
237 if (Code[0] == '\n') {
239 StartOfLine = Code.drop_front();
241 Code = Code.drop_front();
245 SourceLocation currentLocation() {
246 SourceLocation Location;
247 Location.Line = Line;
248 Location.Column = Code.data() - StartOfLine.data() + 1;
253 StringRef StartOfLine;
257 const char *CodeCompletionLocation;
260 Parser::Sema::~Sema() {}
262 std::vector<ArgKind> Parser::Sema::getAcceptedCompletionTypes(
263 llvm::ArrayRef<std::pair<MatcherCtor, unsigned>> Context) {
264 return std::vector<ArgKind>();
267 std::vector<MatcherCompletion>
268 Parser::Sema::getMatcherCompletions(llvm::ArrayRef<ArgKind> AcceptedTypes) {
269 return std::vector<MatcherCompletion>();
272 struct Parser::ScopedContextEntry {
275 ScopedContextEntry(Parser *P, MatcherCtor C) : P(P) {
276 P->ContextStack.push_back(std::make_pair(C, 0u));
279 ~ScopedContextEntry() {
280 P->ContextStack.pop_back();
284 ++P->ContextStack.back().second;
288 /// \brief Parse expressions that start with an identifier.
290 /// This function can parse named values and matchers.
291 /// In case of failure it will try to determine the user's intent to give
292 /// an appropriate error message.
293 bool Parser::parseIdentifierPrefixImpl(VariantValue *Value) {
294 const TokenInfo NameToken = Tokenizer->consumeNextToken();
296 if (Tokenizer->nextTokenKind() != TokenInfo::TK_OpenParen) {
297 // Parse as a named value.
298 if (const VariantValue NamedValue =
299 NamedValues ? NamedValues->lookup(NameToken.Text)
304 // If the syntax is correct and the name is not a matcher either, report
305 // unknown named value.
306 if ((Tokenizer->nextTokenKind() == TokenInfo::TK_Comma ||
307 Tokenizer->nextTokenKind() == TokenInfo::TK_CloseParen ||
308 Tokenizer->nextTokenKind() == TokenInfo::TK_Eof) &&
309 !S->lookupMatcherCtor(NameToken.Text)) {
310 Error->addError(NameToken.Range, Error->ET_RegistryValueNotFound)
314 // Otherwise, fallback to the matcher parser.
317 // Parse as a matcher expression.
318 return parseMatcherExpressionImpl(NameToken, Value);
321 /// \brief Parse and validate a matcher expression.
322 /// \return \c true on success, in which case \c Value has the matcher parsed.
323 /// If the input is malformed, or some argument has an error, it
324 /// returns \c false.
325 bool Parser::parseMatcherExpressionImpl(const TokenInfo &NameToken,
326 VariantValue *Value) {
327 assert(NameToken.Kind == TokenInfo::TK_Ident);
328 const TokenInfo OpenToken = Tokenizer->consumeNextToken();
329 if (OpenToken.Kind != TokenInfo::TK_OpenParen) {
330 Error->addError(OpenToken.Range, Error->ET_ParserNoOpenParen)
335 llvm::Optional<MatcherCtor> Ctor = S->lookupMatcherCtor(NameToken.Text);
338 Error->addError(NameToken.Range, Error->ET_RegistryMatcherNotFound)
340 // Do not return here. We need to continue to give completion suggestions.
343 std::vector<ParserValue> Args;
347 ScopedContextEntry SCE(this, Ctor ? *Ctor : nullptr);
349 while (Tokenizer->nextTokenKind() != TokenInfo::TK_Eof) {
350 if (Tokenizer->nextTokenKind() == TokenInfo::TK_CloseParen) {
352 EndToken = Tokenizer->consumeNextToken();
355 if (Args.size() > 0) {
356 // We must find a , token to continue.
357 const TokenInfo CommaToken = Tokenizer->consumeNextToken();
358 if (CommaToken.Kind != TokenInfo::TK_Comma) {
359 Error->addError(CommaToken.Range, Error->ET_ParserNoComma)
365 Diagnostics::Context Ctx(Diagnostics::Context::MatcherArg, Error,
366 NameToken.Text, NameToken.Range,
368 ParserValue ArgValue;
369 ArgValue.Text = Tokenizer->peekNextToken().Text;
370 ArgValue.Range = Tokenizer->peekNextToken().Range;
371 if (!parseExpressionImpl(&ArgValue.Value)) {
375 Args.push_back(ArgValue);
380 if (EndToken.Kind == TokenInfo::TK_Eof) {
381 Error->addError(OpenToken.Range, Error->ET_ParserNoCloseParen);
386 if (Tokenizer->peekNextToken().Kind == TokenInfo::TK_Period) {
387 // Parse .bind("foo")
388 Tokenizer->consumeNextToken(); // consume the period.
389 const TokenInfo BindToken = Tokenizer->consumeNextToken();
390 if (BindToken.Kind == TokenInfo::TK_CodeCompletion) {
391 addCompletion(BindToken, MatcherCompletion("bind(\"", "bind", 1));
395 const TokenInfo OpenToken = Tokenizer->consumeNextToken();
396 const TokenInfo IDToken = Tokenizer->consumeNextToken();
397 const TokenInfo CloseToken = Tokenizer->consumeNextToken();
399 // TODO: We could use different error codes for each/some to be more
400 // explicit about the syntax error.
401 if (BindToken.Kind != TokenInfo::TK_Ident ||
402 BindToken.Text != TokenInfo::ID_Bind) {
403 Error->addError(BindToken.Range, Error->ET_ParserMalformedBindExpr);
406 if (OpenToken.Kind != TokenInfo::TK_OpenParen) {
407 Error->addError(OpenToken.Range, Error->ET_ParserMalformedBindExpr);
410 if (IDToken.Kind != TokenInfo::TK_Literal || !IDToken.Value.isString()) {
411 Error->addError(IDToken.Range, Error->ET_ParserMalformedBindExpr);
414 if (CloseToken.Kind != TokenInfo::TK_CloseParen) {
415 Error->addError(CloseToken.Range, Error->ET_ParserMalformedBindExpr);
418 BindID = IDToken.Value.getString();
424 // Merge the start and end infos.
425 Diagnostics::Context Ctx(Diagnostics::Context::ConstructMatcher, Error,
426 NameToken.Text, NameToken.Range);
427 SourceRange MatcherRange = NameToken.Range;
428 MatcherRange.End = EndToken.Range.End;
429 VariantMatcher Result = S->actOnMatcherExpression(
430 *Ctor, MatcherRange, BindID, Args, Error);
431 if (Result.isNull()) return false;
437 // If the prefix of this completion matches the completion token, add it to
438 // Completions minus the prefix.
439 void Parser::addCompletion(const TokenInfo &CompToken,
440 const MatcherCompletion& Completion) {
441 if (StringRef(Completion.TypedText).startswith(CompToken.Text) &&
442 Completion.Specificity > 0) {
443 Completions.emplace_back(Completion.TypedText.substr(CompToken.Text.size()),
444 Completion.MatcherDecl, Completion.Specificity);
448 std::vector<MatcherCompletion> Parser::getNamedValueCompletions(
449 ArrayRef<ArgKind> AcceptedTypes) {
450 if (!NamedValues) return std::vector<MatcherCompletion>();
451 std::vector<MatcherCompletion> Result;
452 for (const auto &Entry : *NamedValues) {
453 unsigned Specificity;
454 if (Entry.getValue().isConvertibleTo(AcceptedTypes, &Specificity)) {
456 (Entry.getValue().getTypeAsString() + " " + Entry.getKey()).str();
457 Result.emplace_back(Entry.getKey(), Decl, Specificity);
463 void Parser::addExpressionCompletions() {
464 const TokenInfo CompToken = Tokenizer->consumeNextToken();
465 assert(CompToken.Kind == TokenInfo::TK_CodeCompletion);
467 // We cannot complete code if there is an invalid element on the context
469 for (ContextStackTy::iterator I = ContextStack.begin(),
470 E = ContextStack.end();
476 auto AcceptedTypes = S->getAcceptedCompletionTypes(ContextStack);
477 for (const auto &Completion : S->getMatcherCompletions(AcceptedTypes)) {
478 addCompletion(CompToken, Completion);
481 for (const auto &Completion : getNamedValueCompletions(AcceptedTypes)) {
482 addCompletion(CompToken, Completion);
486 /// \brief Parse an <Expresssion>
487 bool Parser::parseExpressionImpl(VariantValue *Value) {
488 switch (Tokenizer->nextTokenKind()) {
489 case TokenInfo::TK_Literal:
490 *Value = Tokenizer->consumeNextToken().Value;
493 case TokenInfo::TK_Ident:
494 return parseIdentifierPrefixImpl(Value);
496 case TokenInfo::TK_CodeCompletion:
497 addExpressionCompletions();
500 case TokenInfo::TK_Eof:
501 Error->addError(Tokenizer->consumeNextToken().Range,
502 Error->ET_ParserNoCode);
505 case TokenInfo::TK_Error:
506 // This error was already reported by the tokenizer.
509 case TokenInfo::TK_OpenParen:
510 case TokenInfo::TK_CloseParen:
511 case TokenInfo::TK_Comma:
512 case TokenInfo::TK_Period:
513 case TokenInfo::TK_InvalidChar:
514 const TokenInfo Token = Tokenizer->consumeNextToken();
515 Error->addError(Token.Range, Error->ET_ParserInvalidToken) << Token.Text;
519 llvm_unreachable("Unknown token kind.");
522 static llvm::ManagedStatic<Parser::RegistrySema> DefaultRegistrySema;
524 Parser::Parser(CodeTokenizer *Tokenizer, Sema *S,
525 const NamedValueMap *NamedValues, Diagnostics *Error)
526 : Tokenizer(Tokenizer), S(S ? S : &*DefaultRegistrySema),
527 NamedValues(NamedValues), Error(Error) {}
529 Parser::RegistrySema::~RegistrySema() {}
531 llvm::Optional<MatcherCtor>
532 Parser::RegistrySema::lookupMatcherCtor(StringRef MatcherName) {
533 return Registry::lookupMatcherCtor(MatcherName);
536 VariantMatcher Parser::RegistrySema::actOnMatcherExpression(
537 MatcherCtor Ctor, const SourceRange &NameRange, StringRef BindID,
538 ArrayRef<ParserValue> Args, Diagnostics *Error) {
539 if (BindID.empty()) {
540 return Registry::constructMatcher(Ctor, NameRange, Args, Error);
542 return Registry::constructBoundMatcher(Ctor, NameRange, BindID, Args,
547 std::vector<ArgKind> Parser::RegistrySema::getAcceptedCompletionTypes(
548 ArrayRef<std::pair<MatcherCtor, unsigned>> Context) {
549 return Registry::getAcceptedCompletionTypes(Context);
552 std::vector<MatcherCompletion> Parser::RegistrySema::getMatcherCompletions(
553 ArrayRef<ArgKind> AcceptedTypes) {
554 return Registry::getMatcherCompletions(AcceptedTypes);
557 bool Parser::parseExpression(StringRef Code, Sema *S,
558 const NamedValueMap *NamedValues,
559 VariantValue *Value, Diagnostics *Error) {
560 CodeTokenizer Tokenizer(Code, Error);
561 if (!Parser(&Tokenizer, S, NamedValues, Error).parseExpressionImpl(Value))
563 if (Tokenizer.peekNextToken().Kind != TokenInfo::TK_Eof) {
564 Error->addError(Tokenizer.peekNextToken().Range,
565 Error->ET_ParserTrailingCode);
571 std::vector<MatcherCompletion>
572 Parser::completeExpression(StringRef Code, unsigned CompletionOffset, Sema *S,
573 const NamedValueMap *NamedValues) {
575 CodeTokenizer Tokenizer(Code, &Error, CompletionOffset);
576 Parser P(&Tokenizer, S, NamedValues, &Error);
578 P.parseExpressionImpl(&Dummy);
580 // Sort by specificity, then by name.
581 std::sort(P.Completions.begin(), P.Completions.end(),
582 [](const MatcherCompletion &A, const MatcherCompletion &B) {
583 if (A.Specificity != B.Specificity)
584 return A.Specificity > B.Specificity;
585 return A.TypedText < B.TypedText;
588 return P.Completions;
591 llvm::Optional<DynTypedMatcher>
592 Parser::parseMatcherExpression(StringRef Code, Sema *S,
593 const NamedValueMap *NamedValues,
594 Diagnostics *Error) {
596 if (!parseExpression(Code, S, NamedValues, &Value, Error))
597 return llvm::Optional<DynTypedMatcher>();
598 if (!Value.isMatcher()) {
599 Error->addError(SourceRange(), Error->ET_ParserNotAMatcher);
600 return llvm::Optional<DynTypedMatcher>();
602 llvm::Optional<DynTypedMatcher> Result =
603 Value.getMatcher().getSingleMatcher();
604 if (!Result.hasValue()) {
605 Error->addError(SourceRange(), Error->ET_ParserOverloadedType)
606 << Value.getTypeAsString();
611 } // namespace dynamic
612 } // namespace ast_matchers