• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- Registry.cpp - Matcher registry -------------------------===//
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 /// \file
11 /// \brief Registry map populated at static initialization time.
12 ///
13 //===------------------------------------------------------------===//
14 
15 #include "clang/ASTMatchers/Dynamic/Registry.h"
16 #include "Marshallers.h"
17 #include "clang/ASTMatchers/ASTMatchers.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include <set>
23 #include <utility>
24 
25 using namespace clang::ast_type_traits;
26 
27 namespace clang {
28 namespace ast_matchers {
29 namespace dynamic {
30 namespace {
31 
32 using internal::MatcherDescriptor;
33 
34 typedef llvm::StringMap<const MatcherDescriptor *> ConstructorMap;
35 class RegistryMaps {
36 public:
37   RegistryMaps();
38   ~RegistryMaps();
39 
constructors() const40   const ConstructorMap &constructors() const { return Constructors; }
41 
42 private:
43   void registerMatcher(StringRef MatcherName, MatcherDescriptor *Callback);
44   ConstructorMap Constructors;
45 };
46 
registerMatcher(StringRef MatcherName,MatcherDescriptor * Callback)47 void RegistryMaps::registerMatcher(StringRef MatcherName,
48                                    MatcherDescriptor *Callback) {
49   assert(Constructors.find(MatcherName) == Constructors.end());
50   Constructors[MatcherName] = Callback;
51 }
52 
53 #define REGISTER_MATCHER(name)                                                 \
54   registerMatcher(#name, internal::makeMatcherAutoMarshall(                    \
55                              ::clang::ast_matchers::name, #name));
56 
57 #define SPECIFIC_MATCHER_OVERLOAD(name, Id)                                    \
58   static_cast< ::clang::ast_matchers::name##_Type##Id>(                        \
59       ::clang::ast_matchers::name)
60 
61 #define REGISTER_OVERLOADED_2(name)                                            \
62   do {                                                                         \
63     MatcherDescriptor *Callbacks[] = {                                         \
64       internal::makeMatcherAutoMarshall(SPECIFIC_MATCHER_OVERLOAD(name, 0),    \
65                                         #name),                                \
66       internal::makeMatcherAutoMarshall(SPECIFIC_MATCHER_OVERLOAD(name, 1),    \
67                                         #name)                                 \
68     };                                                                         \
69     registerMatcher(#name,                                                     \
70                     new internal::OverloadedMatcherDescriptor(Callbacks));     \
71   } while (0)
72 
73 /// \brief Generate a registry map with all the known matchers.
RegistryMaps()74 RegistryMaps::RegistryMaps() {
75   // TODO: Here is the list of the missing matchers, grouped by reason.
76   //
77   // Need Variant/Parser fixes:
78   // ofKind
79   //
80   // Polymorphic + argument overload:
81   // findAll
82   //
83   // Other:
84   // equals
85   // equalsNode
86 
87   REGISTER_OVERLOADED_2(callee);
88   REGISTER_OVERLOADED_2(hasPrefix);
89   REGISTER_OVERLOADED_2(hasType);
90   REGISTER_OVERLOADED_2(isDerivedFrom);
91   REGISTER_OVERLOADED_2(isSameOrDerivedFrom);
92   REGISTER_OVERLOADED_2(loc);
93   REGISTER_OVERLOADED_2(pointsTo);
94   REGISTER_OVERLOADED_2(references);
95   REGISTER_OVERLOADED_2(thisPointerType);
96 
97   REGISTER_MATCHER(accessSpecDecl);
98   REGISTER_MATCHER(addrLabelExpr);
99   REGISTER_MATCHER(alignOfExpr);
100   REGISTER_MATCHER(allOf);
101   REGISTER_MATCHER(anyOf);
102   REGISTER_MATCHER(anything);
103   REGISTER_MATCHER(argumentCountIs);
104   REGISTER_MATCHER(arraySubscriptExpr);
105   REGISTER_MATCHER(arrayType);
106   REGISTER_MATCHER(asmStmt);
107   REGISTER_MATCHER(asString);
108   REGISTER_MATCHER(atomicExpr);
109   REGISTER_MATCHER(atomicType);
110   REGISTER_MATCHER(autoType);
111   REGISTER_MATCHER(binaryOperator);
112   REGISTER_MATCHER(binaryConditionalOperator);
113   REGISTER_MATCHER(blockPointerType);
114   REGISTER_MATCHER(booleanType);
115   REGISTER_MATCHER(breakStmt);
116   REGISTER_MATCHER(builtinType);
117   REGISTER_MATCHER(callExpr);
118   REGISTER_MATCHER(caseStmt);
119   REGISTER_MATCHER(castExpr);
120   REGISTER_MATCHER(characterLiteral);
121   REGISTER_MATCHER(classTemplateDecl);
122   REGISTER_MATCHER(classTemplateSpecializationDecl);
123   REGISTER_MATCHER(complexType);
124   REGISTER_MATCHER(compoundLiteralExpr);
125   REGISTER_MATCHER(compoundStmt);
126   REGISTER_MATCHER(conditionalOperator);
127   REGISTER_MATCHER(constantArrayType);
128   REGISTER_MATCHER(containsDeclaration);
129   REGISTER_MATCHER(continueStmt);
130   REGISTER_MATCHER(cStyleCastExpr);
131   REGISTER_MATCHER(cudaKernelCallExpr);
132   REGISTER_MATCHER(cxxBindTemporaryExpr);
133   REGISTER_MATCHER(cxxBoolLiteral);
134   REGISTER_MATCHER(cxxCatchStmt);
135   REGISTER_MATCHER(cxxConstCastExpr);
136   REGISTER_MATCHER(cxxConstructExpr);
137   REGISTER_MATCHER(cxxConstructorDecl);
138   REGISTER_MATCHER(cxxConversionDecl);
139   REGISTER_MATCHER(cxxCtorInitializer);
140   REGISTER_MATCHER(cxxDefaultArgExpr);
141   REGISTER_MATCHER(cxxDeleteExpr);
142   REGISTER_MATCHER(cxxDestructorDecl);
143   REGISTER_MATCHER(cxxDynamicCastExpr);
144   REGISTER_MATCHER(cxxForRangeStmt);
145   REGISTER_MATCHER(cxxFunctionalCastExpr);
146   REGISTER_MATCHER(cxxMemberCallExpr);
147   REGISTER_MATCHER(cxxMethodDecl);
148   REGISTER_MATCHER(cxxNewExpr);
149   REGISTER_MATCHER(cxxNullPtrLiteralExpr);
150   REGISTER_MATCHER(cxxOperatorCallExpr);
151   REGISTER_MATCHER(cxxRecordDecl);
152   REGISTER_MATCHER(cxxReinterpretCastExpr);
153   REGISTER_MATCHER(cxxStaticCastExpr);
154   REGISTER_MATCHER(cxxTemporaryObjectExpr);
155   REGISTER_MATCHER(cxxThisExpr);
156   REGISTER_MATCHER(cxxThrowExpr);
157   REGISTER_MATCHER(cxxTryStmt);
158   REGISTER_MATCHER(cxxUnresolvedConstructExpr);
159   REGISTER_MATCHER(decayedType);
160   REGISTER_MATCHER(decl);
161   REGISTER_MATCHER(declaratorDecl);
162   REGISTER_MATCHER(declCountIs);
163   REGISTER_MATCHER(declRefExpr);
164   REGISTER_MATCHER(declStmt);
165   REGISTER_MATCHER(defaultStmt);
166   REGISTER_MATCHER(dependentSizedArrayType);
167   REGISTER_MATCHER(designatedInitExpr);
168   REGISTER_MATCHER(designatorCountIs);
169   REGISTER_MATCHER(doStmt);
170   REGISTER_MATCHER(eachOf);
171   REGISTER_MATCHER(elaboratedType);
172   REGISTER_MATCHER(enumConstantDecl);
173   REGISTER_MATCHER(enumDecl);
174   REGISTER_MATCHER(enumType);
175   REGISTER_MATCHER(equalsBoundNode);
176   REGISTER_MATCHER(equalsIntegralValue);
177   REGISTER_MATCHER(explicitCastExpr);
178   REGISTER_MATCHER(expr);
179   REGISTER_MATCHER(exprWithCleanups);
180   REGISTER_MATCHER(fieldDecl);
181   REGISTER_MATCHER(floatLiteral);
182   REGISTER_MATCHER(forEach);
183   REGISTER_MATCHER(forEachArgumentWithParam);
184   REGISTER_MATCHER(forEachConstructorInitializer);
185   REGISTER_MATCHER(forEachDescendant);
186   REGISTER_MATCHER(forEachSwitchCase);
187   REGISTER_MATCHER(forField);
188   REGISTER_MATCHER(forFunction);
189   REGISTER_MATCHER(forStmt);
190   REGISTER_MATCHER(friendDecl);
191   REGISTER_MATCHER(functionDecl);
192   REGISTER_MATCHER(functionProtoType);
193   REGISTER_MATCHER(functionTemplateDecl);
194   REGISTER_MATCHER(functionType);
195   REGISTER_MATCHER(gnuNullExpr);
196   REGISTER_MATCHER(gotoStmt);
197   REGISTER_MATCHER(has);
198   REGISTER_MATCHER(hasAncestor);
199   REGISTER_MATCHER(hasAnyArgument);
200   REGISTER_MATCHER(hasAnyConstructorInitializer);
201   REGISTER_MATCHER(hasAnyName);
202   REGISTER_MATCHER(hasAnyParameter);
203   REGISTER_MATCHER(hasAnySubstatement);
204   REGISTER_MATCHER(hasAnyTemplateArgument);
205   REGISTER_MATCHER(hasAnyUsingShadowDecl);
206   REGISTER_MATCHER(hasArgument);
207   REGISTER_MATCHER(hasArgumentOfType);
208   REGISTER_MATCHER(hasAttr);
209   REGISTER_MATCHER(hasAutomaticStorageDuration);
210   REGISTER_MATCHER(hasBase);
211   REGISTER_MATCHER(hasBitWidth);
212   REGISTER_MATCHER(hasBody);
213   REGISTER_MATCHER(hasCanonicalType);
214   REGISTER_MATCHER(hasCaseConstant);
215   REGISTER_MATCHER(hasCastKind);
216   REGISTER_MATCHER(hasCondition);
217   REGISTER_MATCHER(hasConditionVariableStatement);
218   REGISTER_MATCHER(hasDecayedType);
219   REGISTER_MATCHER(hasDeclaration);
220   REGISTER_MATCHER(hasDeclContext);
221   REGISTER_MATCHER(hasDeducedType);
222   REGISTER_MATCHER(hasDescendant);
223   REGISTER_MATCHER(hasDestinationType);
224   REGISTER_MATCHER(hasDynamicExceptionSpec);
225   REGISTER_MATCHER(hasEitherOperand);
226   REGISTER_MATCHER(hasElementType);
227   REGISTER_MATCHER(hasElse);
228   REGISTER_MATCHER(hasFalseExpression);
229   REGISTER_MATCHER(hasGlobalStorage);
230   REGISTER_MATCHER(hasImplicitDestinationType);
231   REGISTER_MATCHER(hasIncrement);
232   REGISTER_MATCHER(hasIndex);
233   REGISTER_MATCHER(hasInitializer);
234   REGISTER_MATCHER(hasKeywordSelector);
235   REGISTER_MATCHER(hasLHS);
236   REGISTER_MATCHER(hasLocalQualifiers);
237   REGISTER_MATCHER(hasLocalStorage);
238   REGISTER_MATCHER(hasLoopInit);
239   REGISTER_MATCHER(hasLoopVariable);
240   REGISTER_MATCHER(hasMethod);
241   REGISTER_MATCHER(hasName);
242   REGISTER_MATCHER(hasNullSelector);
243   REGISTER_MATCHER(hasObjectExpression);
244   REGISTER_MATCHER(hasOperatorName);
245   REGISTER_MATCHER(hasOverloadedOperatorName);
246   REGISTER_MATCHER(hasParameter);
247   REGISTER_MATCHER(hasParent);
248   REGISTER_MATCHER(hasQualifier);
249   REGISTER_MATCHER(hasRangeInit);
250   REGISTER_MATCHER(hasReceiverType);
251   REGISTER_MATCHER(hasReturnValue);
252   REGISTER_MATCHER(hasRHS);
253   REGISTER_MATCHER(hasSelector);
254   REGISTER_MATCHER(hasSingleDecl);
255   REGISTER_MATCHER(hasSize);
256   REGISTER_MATCHER(hasSizeExpr);
257   REGISTER_MATCHER(hasSourceExpression);
258   REGISTER_MATCHER(hasStaticStorageDuration);
259   REGISTER_MATCHER(hasSyntacticForm);
260   REGISTER_MATCHER(hasTargetDecl);
261   REGISTER_MATCHER(hasTemplateArgument);
262   REGISTER_MATCHER(hasThen);
263   REGISTER_MATCHER(hasThreadStorageDuration);
264   REGISTER_MATCHER(hasTrueExpression);
265   REGISTER_MATCHER(hasTypeLoc);
266   REGISTER_MATCHER(hasUnaryOperand);
267   REGISTER_MATCHER(hasUnarySelector);
268   REGISTER_MATCHER(hasValueType);
269   REGISTER_MATCHER(ifStmt);
270   REGISTER_MATCHER(ignoringImplicit);
271   REGISTER_MATCHER(ignoringImpCasts);
272   REGISTER_MATCHER(ignoringParenCasts);
273   REGISTER_MATCHER(ignoringParenImpCasts);
274   REGISTER_MATCHER(ignoringParens);
275   REGISTER_MATCHER(implicitCastExpr);
276   REGISTER_MATCHER(implicitValueInitExpr);
277   REGISTER_MATCHER(incompleteArrayType);
278   REGISTER_MATCHER(initListExpr);
279   REGISTER_MATCHER(injectedClassNameType);
280   REGISTER_MATCHER(innerType);
281   REGISTER_MATCHER(integerLiteral);
282   REGISTER_MATCHER(isAnonymous);
283   REGISTER_MATCHER(isAnyCharacter);
284   REGISTER_MATCHER(isAnyPointer);
285   REGISTER_MATCHER(isArrow);
286   REGISTER_MATCHER(isBaseInitializer);
287   REGISTER_MATCHER(isBitField);
288   REGISTER_MATCHER(isCatchAll);
289   REGISTER_MATCHER(isClass);
290   REGISTER_MATCHER(isConst);
291   REGISTER_MATCHER(isConstQualified);
292   REGISTER_MATCHER(isCopyAssignmentOperator);
293   REGISTER_MATCHER(isCopyConstructor);
294   REGISTER_MATCHER(isDefaultConstructor);
295   REGISTER_MATCHER(isDefaulted);
296   REGISTER_MATCHER(isDefinition);
297   REGISTER_MATCHER(isDeleted);
298   REGISTER_MATCHER(isExceptionVariable);
299   REGISTER_MATCHER(isExplicit);
300   REGISTER_MATCHER(isExplicitTemplateSpecialization);
301   REGISTER_MATCHER(isExpr);
302   REGISTER_MATCHER(isExternC);
303   REGISTER_MATCHER(isFinal);
304   REGISTER_MATCHER(isInline);
305   REGISTER_MATCHER(isImplicit);
306   REGISTER_MATCHER(isExpansionInFileMatching);
307   REGISTER_MATCHER(isExpansionInMainFile);
308   REGISTER_MATCHER(isInstantiated);
309   REGISTER_MATCHER(isExpansionInSystemHeader);
310   REGISTER_MATCHER(isInteger);
311   REGISTER_MATCHER(isIntegral);
312   REGISTER_MATCHER(isInTemplateInstantiation);
313   REGISTER_MATCHER(isLambda);
314   REGISTER_MATCHER(isListInitialization);
315   REGISTER_MATCHER(isMemberInitializer);
316   REGISTER_MATCHER(isMoveAssignmentOperator);
317   REGISTER_MATCHER(isMoveConstructor);
318   REGISTER_MATCHER(isNoThrow);
319   REGISTER_MATCHER(isOverride);
320   REGISTER_MATCHER(isPrivate);
321   REGISTER_MATCHER(isProtected);
322   REGISTER_MATCHER(isPublic);
323   REGISTER_MATCHER(isPure);
324   REGISTER_MATCHER(isSignedInteger);
325   REGISTER_MATCHER(isStruct);
326   REGISTER_MATCHER(isTemplateInstantiation);
327   REGISTER_MATCHER(isUnion);
328   REGISTER_MATCHER(isUnsignedInteger);
329   REGISTER_MATCHER(isVariadic);
330   REGISTER_MATCHER(isVirtual);
331   REGISTER_MATCHER(isVirtualAsWritten);
332   REGISTER_MATCHER(isVolatileQualified);
333   REGISTER_MATCHER(isWritten);
334   REGISTER_MATCHER(labelDecl);
335   REGISTER_MATCHER(labelStmt);
336   REGISTER_MATCHER(lambdaExpr);
337   REGISTER_MATCHER(lValueReferenceType);
338   REGISTER_MATCHER(matchesName);
339   REGISTER_MATCHER(matchesSelector);
340   REGISTER_MATCHER(materializeTemporaryExpr);
341   REGISTER_MATCHER(member);
342   REGISTER_MATCHER(memberExpr);
343   REGISTER_MATCHER(memberPointerType);
344   REGISTER_MATCHER(namedDecl);
345   REGISTER_MATCHER(namespaceAliasDecl);
346   REGISTER_MATCHER(namespaceDecl);
347   REGISTER_MATCHER(namesType);
348   REGISTER_MATCHER(nestedNameSpecifier);
349   REGISTER_MATCHER(nestedNameSpecifierLoc);
350   REGISTER_MATCHER(nullPointerConstant);
351   REGISTER_MATCHER(nullStmt);
352   REGISTER_MATCHER(numSelectorArgs);
353   REGISTER_MATCHER(ofClass);
354   REGISTER_MATCHER(objcInterfaceDecl);
355   REGISTER_MATCHER(objcMessageExpr);
356   REGISTER_MATCHER(objcObjectPointerType);
357   REGISTER_MATCHER(on);
358   REGISTER_MATCHER(onImplicitObjectArgument);
359   REGISTER_MATCHER(opaqueValueExpr);
360   REGISTER_MATCHER(parameterCountIs);
361   REGISTER_MATCHER(parenExpr);
362   REGISTER_MATCHER(parenListExpr);
363   REGISTER_MATCHER(parenType);
364   REGISTER_MATCHER(parmVarDecl);
365   REGISTER_MATCHER(pointee);
366   REGISTER_MATCHER(pointerType);
367   REGISTER_MATCHER(predefinedExpr);
368   REGISTER_MATCHER(qualType);
369   REGISTER_MATCHER(realFloatingPointType);
370   REGISTER_MATCHER(recordDecl);
371   REGISTER_MATCHER(recordType);
372   REGISTER_MATCHER(referenceType);
373   REGISTER_MATCHER(refersToDeclaration);
374   REGISTER_MATCHER(refersToIntegralType);
375   REGISTER_MATCHER(refersToType);
376   REGISTER_MATCHER(requiresZeroInitialization);
377   REGISTER_MATCHER(returns);
378   REGISTER_MATCHER(returnStmt);
379   REGISTER_MATCHER(rValueReferenceType);
380   REGISTER_MATCHER(sizeOfExpr);
381   REGISTER_MATCHER(specifiesNamespace);
382   REGISTER_MATCHER(specifiesType);
383   REGISTER_MATCHER(specifiesTypeLoc);
384   REGISTER_MATCHER(statementCountIs);
385   REGISTER_MATCHER(staticAssertDecl);
386   REGISTER_MATCHER(stmt);
387   REGISTER_MATCHER(stmtExpr);
388   REGISTER_MATCHER(stringLiteral);
389   REGISTER_MATCHER(substNonTypeTemplateParmExpr);
390   REGISTER_MATCHER(substTemplateTypeParmType);
391   REGISTER_MATCHER(switchCase);
392   REGISTER_MATCHER(switchStmt);
393   REGISTER_MATCHER(templateArgument);
394   REGISTER_MATCHER(templateArgumentCountIs);
395   REGISTER_MATCHER(templateSpecializationType);
396   REGISTER_MATCHER(templateTypeParmType);
397   REGISTER_MATCHER(throughUsingDecl);
398   REGISTER_MATCHER(to);
399   REGISTER_MATCHER(translationUnitDecl);
400   REGISTER_MATCHER(type);
401   REGISTER_MATCHER(typedefDecl);
402   REGISTER_MATCHER(typedefNameDecl);
403   REGISTER_MATCHER(typedefType);
404   REGISTER_MATCHER(typeAliasDecl);
405   REGISTER_MATCHER(typeLoc);
406   REGISTER_MATCHER(unaryExprOrTypeTraitExpr);
407   REGISTER_MATCHER(unaryOperator);
408   REGISTER_MATCHER(unaryTransformType);
409   REGISTER_MATCHER(unless);
410   REGISTER_MATCHER(unresolvedLookupExpr);
411   REGISTER_MATCHER(unresolvedUsingTypenameDecl);
412   REGISTER_MATCHER(unresolvedUsingValueDecl);
413   REGISTER_MATCHER(userDefinedLiteral);
414   REGISTER_MATCHER(usingDecl);
415   REGISTER_MATCHER(usingDirectiveDecl);
416   REGISTER_MATCHER(valueDecl);
417   REGISTER_MATCHER(varDecl);
418   REGISTER_MATCHER(variableArrayType);
419   REGISTER_MATCHER(voidType);
420   REGISTER_MATCHER(whileStmt);
421   REGISTER_MATCHER(withInitializer);
422 }
423 
~RegistryMaps()424 RegistryMaps::~RegistryMaps() {
425   llvm::DeleteContainerSeconds(Constructors);
426 }
427 
428 static llvm::ManagedStatic<RegistryMaps> RegistryData;
429 
430 } // anonymous namespace
431 
432 // static
lookupMatcherCtor(StringRef MatcherName)433 llvm::Optional<MatcherCtor> Registry::lookupMatcherCtor(StringRef MatcherName) {
434   ConstructorMap::const_iterator it =
435       RegistryData->constructors().find(MatcherName);
436   return it == RegistryData->constructors().end()
437              ? llvm::Optional<MatcherCtor>()
438              : it->second;
439 }
440 
441 namespace {
442 
operator <<(llvm::raw_ostream & OS,const std::set<ASTNodeKind> & KS)443 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
444                               const std::set<ASTNodeKind> &KS) {
445   unsigned Count = 0;
446   for (std::set<ASTNodeKind>::const_iterator I = KS.begin(), E = KS.end();
447        I != E; ++I) {
448     if (I != KS.begin())
449       OS << "|";
450     if (Count++ == 3) {
451       OS << "...";
452       break;
453     }
454     OS << *I;
455   }
456   return OS;
457 }
458 
459 }  // namespace
460 
getAcceptedCompletionTypes(ArrayRef<std::pair<MatcherCtor,unsigned>> Context)461 std::vector<ArgKind> Registry::getAcceptedCompletionTypes(
462     ArrayRef<std::pair<MatcherCtor, unsigned>> Context) {
463   ASTNodeKind InitialTypes[] = {
464       ASTNodeKind::getFromNodeKind<Decl>(),
465       ASTNodeKind::getFromNodeKind<QualType>(),
466       ASTNodeKind::getFromNodeKind<Type>(),
467       ASTNodeKind::getFromNodeKind<Stmt>(),
468       ASTNodeKind::getFromNodeKind<NestedNameSpecifier>(),
469       ASTNodeKind::getFromNodeKind<NestedNameSpecifierLoc>(),
470       ASTNodeKind::getFromNodeKind<TypeLoc>()};
471 
472   // Starting with the above seed of acceptable top-level matcher types, compute
473   // the acceptable type set for the argument indicated by each context element.
474   std::set<ArgKind> TypeSet(std::begin(InitialTypes), std::end(InitialTypes));
475   for (const auto &CtxEntry : Context) {
476     MatcherCtor Ctor = CtxEntry.first;
477     unsigned ArgNumber = CtxEntry.second;
478     std::vector<ArgKind> NextTypeSet;
479     for (const ArgKind &Kind : TypeSet) {
480       if (Kind.getArgKind() == Kind.AK_Matcher &&
481           Ctor->isConvertibleTo(Kind.getMatcherKind()) &&
482           (Ctor->isVariadic() || ArgNumber < Ctor->getNumArgs()))
483         Ctor->getArgKinds(Kind.getMatcherKind(), ArgNumber, NextTypeSet);
484     }
485     TypeSet.clear();
486     TypeSet.insert(NextTypeSet.begin(), NextTypeSet.end());
487   }
488   return std::vector<ArgKind>(TypeSet.begin(), TypeSet.end());
489 }
490 
491 std::vector<MatcherCompletion>
getMatcherCompletions(ArrayRef<ArgKind> AcceptedTypes)492 Registry::getMatcherCompletions(ArrayRef<ArgKind> AcceptedTypes) {
493   std::vector<MatcherCompletion> Completions;
494 
495   // Search the registry for acceptable matchers.
496   for (const auto &M : RegistryData->constructors()) {
497     const auto *Matcher = M.getValue();
498     StringRef Name = M.getKey();
499 
500     std::set<ASTNodeKind> RetKinds;
501     unsigned NumArgs = Matcher->isVariadic() ? 1 : Matcher->getNumArgs();
502     bool IsPolymorphic = Matcher->isPolymorphic();
503     std::vector<std::vector<ArgKind>> ArgsKinds(NumArgs);
504     unsigned MaxSpecificity = 0;
505     for (const ArgKind& Kind : AcceptedTypes) {
506       if (Kind.getArgKind() != Kind.AK_Matcher)
507         continue;
508       unsigned Specificity;
509       ASTNodeKind LeastDerivedKind;
510       if (Matcher->isConvertibleTo(Kind.getMatcherKind(), &Specificity,
511                                    &LeastDerivedKind)) {
512         if (MaxSpecificity < Specificity)
513           MaxSpecificity = Specificity;
514         RetKinds.insert(LeastDerivedKind);
515         for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
516           Matcher->getArgKinds(Kind.getMatcherKind(), Arg, ArgsKinds[Arg]);
517         if (IsPolymorphic)
518           break;
519       }
520     }
521 
522     if (!RetKinds.empty() && MaxSpecificity > 0) {
523       std::string Decl;
524       llvm::raw_string_ostream OS(Decl);
525 
526       if (IsPolymorphic) {
527         OS << "Matcher<T> " << Name << "(Matcher<T>";
528       } else {
529         OS << "Matcher<" << RetKinds << "> " << Name << "(";
530         for (const std::vector<ArgKind> &Arg : ArgsKinds) {
531           if (&Arg != &ArgsKinds[0])
532             OS << ", ";
533 
534           bool FirstArgKind = true;
535           std::set<ASTNodeKind> MatcherKinds;
536           // Two steps. First all non-matchers, then matchers only.
537           for (const ArgKind &AK : Arg) {
538             if (AK.getArgKind() == ArgKind::AK_Matcher) {
539               MatcherKinds.insert(AK.getMatcherKind());
540             } else {
541               if (!FirstArgKind) OS << "|";
542               FirstArgKind = false;
543               OS << AK.asString();
544             }
545           }
546           if (!MatcherKinds.empty()) {
547             if (!FirstArgKind) OS << "|";
548             OS << "Matcher<" << MatcherKinds << ">";
549           }
550         }
551       }
552       if (Matcher->isVariadic())
553         OS << "...";
554       OS << ")";
555 
556       std::string TypedText = Name;
557       TypedText += "(";
558       if (ArgsKinds.empty())
559         TypedText += ")";
560       else if (ArgsKinds[0][0].getArgKind() == ArgKind::AK_String)
561         TypedText += "\"";
562 
563       Completions.emplace_back(TypedText, OS.str(), MaxSpecificity);
564     }
565   }
566 
567   return Completions;
568 }
569 
570 // static
constructMatcher(MatcherCtor Ctor,SourceRange NameRange,ArrayRef<ParserValue> Args,Diagnostics * Error)571 VariantMatcher Registry::constructMatcher(MatcherCtor Ctor,
572                                           SourceRange NameRange,
573                                           ArrayRef<ParserValue> Args,
574                                           Diagnostics *Error) {
575   return Ctor->create(NameRange, Args, Error);
576 }
577 
578 // static
constructBoundMatcher(MatcherCtor Ctor,SourceRange NameRange,StringRef BindID,ArrayRef<ParserValue> Args,Diagnostics * Error)579 VariantMatcher Registry::constructBoundMatcher(MatcherCtor Ctor,
580                                                SourceRange NameRange,
581                                                StringRef BindID,
582                                                ArrayRef<ParserValue> Args,
583                                                Diagnostics *Error) {
584   VariantMatcher Out = constructMatcher(Ctor, NameRange, Args, Error);
585   if (Out.isNull()) return Out;
586 
587   llvm::Optional<DynTypedMatcher> Result = Out.getSingleMatcher();
588   if (Result.hasValue()) {
589     llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID);
590     if (Bound.hasValue()) {
591       return VariantMatcher::SingleMatcher(*Bound);
592     }
593   }
594   Error->addError(NameRange, Error->ET_RegistryNotBindable);
595   return VariantMatcher();
596 }
597 
598 }  // namespace dynamic
599 }  // namespace ast_matchers
600 }  // namespace clang
601