1 //===- Registry.cpp - Matcher registry ------------------------------------===//
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 /// \file
10 /// Registry map populated at static initialization time.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/ASTMatchers/Dynamic/Registry.h"
15 #include "Marshallers.h"
16 #include "clang/AST/ASTTypeTraits.h"
17 #include "clang/ASTMatchers/ASTMatchers.h"
18 #include "clang/ASTMatchers/Dynamic/Diagnostics.h"
19 #include "clang/ASTMatchers/Dynamic/VariantValue.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <cassert>
27 #include <iterator>
28 #include <memory>
29 #include <set>
30 #include <string>
31 #include <utility>
32 #include <vector>
33 
34 namespace clang {
35 namespace ast_matchers {
36 namespace dynamic {
37 
38 namespace {
39 
40 using internal::MatcherDescriptor;
41 
42 using ConstructorMap =
43     llvm::StringMap<std::unique_ptr<const MatcherDescriptor>>;
44 
45 class RegistryMaps {
46 public:
47   RegistryMaps();
48   ~RegistryMaps();
49 
constructors() const50   const ConstructorMap &constructors() const { return Constructors; }
51 
52 private:
53   void registerMatcher(StringRef MatcherName,
54                        std::unique_ptr<MatcherDescriptor> Callback);
55 
56   ConstructorMap Constructors;
57 };
58 
59 } // namespace
60 
registerMatcher(StringRef MatcherName,std::unique_ptr<MatcherDescriptor> Callback)61 void RegistryMaps::registerMatcher(
62     StringRef MatcherName, std::unique_ptr<MatcherDescriptor> Callback) {
63   assert(Constructors.find(MatcherName) == Constructors.end());
64   Constructors[MatcherName] = std::move(Callback);
65 }
66 
67 #define REGISTER_MATCHER(name)                                                 \
68   registerMatcher(#name, internal::makeMatcherAutoMarshall(                    \
69                              ::clang::ast_matchers::name, #name));
70 
71 #define REGISTER_MATCHER_OVERLOAD(name)                                        \
72   registerMatcher(#name,                                                       \
73       std::make_unique<internal::OverloadedMatcherDescriptor>(name##Callbacks))
74 
75 #define SPECIFIC_MATCHER_OVERLOAD(name, Id)                                    \
76   static_cast<::clang::ast_matchers::name##_Type##Id>(                         \
77       ::clang::ast_matchers::name)
78 
79 #define MATCHER_OVERLOAD_ENTRY(name, Id)                                       \
80         internal::makeMatcherAutoMarshall(SPECIFIC_MATCHER_OVERLOAD(name, Id), \
81                                           #name)
82 
83 #define REGISTER_OVERLOADED_2(name)                                            \
84   do {                                                                         \
85     std::unique_ptr<MatcherDescriptor> name##Callbacks[] = {                   \
86         MATCHER_OVERLOAD_ENTRY(name, 0),                                       \
87         MATCHER_OVERLOAD_ENTRY(name, 1)};                                      \
88     REGISTER_MATCHER_OVERLOAD(name);                                           \
89   } while (false)
90 
91 #define REGISTER_REGEX_MATCHER(name)                                           \
92   registerMatcher(#name, internal::makeMatcherRegexMarshall(name, name))
93 
94 /// Generate a registry map with all the known matchers.
95 /// Please keep sorted alphabetically!
RegistryMaps()96 RegistryMaps::RegistryMaps() {
97   // TODO: Here is the list of the missing matchers, grouped by reason.
98   //
99   // Polymorphic + argument overload:
100   // findAll
101   //
102   // Other:
103   // equalsNode
104 
105   registerMatcher("mapAnyOf",
106                   std::make_unique<internal::MapAnyOfBuilderDescriptor>());
107 
108   REGISTER_OVERLOADED_2(callee);
109   REGISTER_OVERLOADED_2(hasAnyCapture);
110   REGISTER_OVERLOADED_2(hasPrefix);
111   REGISTER_OVERLOADED_2(hasType);
112   REGISTER_OVERLOADED_2(ignoringParens);
113   REGISTER_OVERLOADED_2(isDerivedFrom);
114   REGISTER_OVERLOADED_2(isDirectlyDerivedFrom);
115   REGISTER_OVERLOADED_2(isSameOrDerivedFrom);
116   REGISTER_OVERLOADED_2(loc);
117   REGISTER_OVERLOADED_2(pointsTo);
118   REGISTER_OVERLOADED_2(references);
119   REGISTER_OVERLOADED_2(thisPointerType);
120 
121   std::unique_ptr<MatcherDescriptor> equalsCallbacks[] = {
122       MATCHER_OVERLOAD_ENTRY(equals, 0),
123       MATCHER_OVERLOAD_ENTRY(equals, 1),
124       MATCHER_OVERLOAD_ENTRY(equals, 2),
125   };
126   REGISTER_MATCHER_OVERLOAD(equals);
127 
128   REGISTER_REGEX_MATCHER(isExpansionInFileMatching);
129   REGISTER_REGEX_MATCHER(matchesName);
130   REGISTER_REGEX_MATCHER(matchesSelector);
131 
132   REGISTER_MATCHER(accessSpecDecl);
133   REGISTER_MATCHER(addrLabelExpr);
134   REGISTER_MATCHER(alignOfExpr);
135   REGISTER_MATCHER(allOf);
136   REGISTER_MATCHER(anyOf);
137   REGISTER_MATCHER(anything);
138   REGISTER_MATCHER(argumentCountIs);
139   REGISTER_MATCHER(arraySubscriptExpr);
140   REGISTER_MATCHER(arrayType);
141   REGISTER_MATCHER(asString);
142   REGISTER_MATCHER(asmStmt);
143   REGISTER_MATCHER(atomicExpr);
144   REGISTER_MATCHER(atomicType);
145   REGISTER_MATCHER(autoType);
146   REGISTER_MATCHER(autoreleasePoolStmt)
147   REGISTER_MATCHER(binaryConditionalOperator);
148   REGISTER_MATCHER(binaryOperator);
149   REGISTER_MATCHER(binaryOperation);
150   REGISTER_MATCHER(bindingDecl);
151   REGISTER_MATCHER(blockDecl);
152   REGISTER_MATCHER(blockExpr);
153   REGISTER_MATCHER(blockPointerType);
154   REGISTER_MATCHER(booleanType);
155   REGISTER_MATCHER(breakStmt);
156   REGISTER_MATCHER(builtinType);
157   REGISTER_MATCHER(cStyleCastExpr);
158   REGISTER_MATCHER(callExpr);
159   REGISTER_MATCHER(caseStmt);
160   REGISTER_MATCHER(castExpr);
161   REGISTER_MATCHER(characterLiteral);
162   REGISTER_MATCHER(chooseExpr);
163   REGISTER_MATCHER(classTemplateDecl);
164   REGISTER_MATCHER(classTemplatePartialSpecializationDecl);
165   REGISTER_MATCHER(classTemplateSpecializationDecl);
166   REGISTER_MATCHER(complexType);
167   REGISTER_MATCHER(compoundLiteralExpr);
168   REGISTER_MATCHER(compoundStmt);
169   REGISTER_MATCHER(coawaitExpr);
170   REGISTER_MATCHER(conditionalOperator);
171   REGISTER_MATCHER(constantArrayType);
172   REGISTER_MATCHER(constantExpr);
173   REGISTER_MATCHER(containsDeclaration);
174   REGISTER_MATCHER(continueStmt);
175   REGISTER_MATCHER(coreturnStmt);
176   REGISTER_MATCHER(coyieldExpr);
177   REGISTER_MATCHER(cudaKernelCallExpr);
178   REGISTER_MATCHER(cxxBaseSpecifier);
179   REGISTER_MATCHER(cxxBindTemporaryExpr);
180   REGISTER_MATCHER(cxxBoolLiteral);
181   REGISTER_MATCHER(cxxCatchStmt);
182   REGISTER_MATCHER(cxxConstCastExpr);
183   REGISTER_MATCHER(cxxConstructExpr);
184   REGISTER_MATCHER(cxxConstructorDecl);
185   REGISTER_MATCHER(cxxConversionDecl);
186   REGISTER_MATCHER(cxxCtorInitializer);
187   REGISTER_MATCHER(cxxDeductionGuideDecl);
188   REGISTER_MATCHER(cxxDefaultArgExpr);
189   REGISTER_MATCHER(cxxDeleteExpr);
190   REGISTER_MATCHER(cxxDependentScopeMemberExpr);
191   REGISTER_MATCHER(cxxDestructorDecl);
192   REGISTER_MATCHER(cxxDynamicCastExpr);
193   REGISTER_MATCHER(cxxForRangeStmt);
194   REGISTER_MATCHER(cxxFunctionalCastExpr);
195   REGISTER_MATCHER(cxxMemberCallExpr);
196   REGISTER_MATCHER(cxxMethodDecl);
197   REGISTER_MATCHER(cxxNewExpr);
198   REGISTER_MATCHER(cxxNoexceptExpr);
199   REGISTER_MATCHER(cxxNullPtrLiteralExpr);
200   REGISTER_MATCHER(cxxOperatorCallExpr);
201   REGISTER_MATCHER(cxxRecordDecl);
202   REGISTER_MATCHER(cxxReinterpretCastExpr);
203   REGISTER_MATCHER(cxxRewrittenBinaryOperator);
204   REGISTER_MATCHER(cxxStaticCastExpr);
205   REGISTER_MATCHER(cxxStdInitializerListExpr);
206   REGISTER_MATCHER(cxxTemporaryObjectExpr);
207   REGISTER_MATCHER(cxxThisExpr);
208   REGISTER_MATCHER(cxxThrowExpr);
209   REGISTER_MATCHER(cxxTryStmt);
210   REGISTER_MATCHER(cxxUnresolvedConstructExpr);
211   REGISTER_MATCHER(decayedType);
212   REGISTER_MATCHER(decl);
213   REGISTER_MATCHER(decompositionDecl);
214   REGISTER_MATCHER(declCountIs);
215   REGISTER_MATCHER(declRefExpr);
216   REGISTER_MATCHER(declStmt);
217   REGISTER_MATCHER(declaratorDecl);
218   REGISTER_MATCHER(decltypeType);
219   REGISTER_MATCHER(deducedTemplateSpecializationType);
220   REGISTER_MATCHER(defaultStmt);
221   REGISTER_MATCHER(dependentCoawaitExpr);
222   REGISTER_MATCHER(dependentSizedArrayType);
223   REGISTER_MATCHER(designatedInitExpr);
224   REGISTER_MATCHER(designatorCountIs);
225   REGISTER_MATCHER(doStmt);
226   REGISTER_MATCHER(eachOf);
227   REGISTER_MATCHER(elaboratedType);
228   REGISTER_MATCHER(enumConstantDecl);
229   REGISTER_MATCHER(enumDecl);
230   REGISTER_MATCHER(enumType);
231   REGISTER_MATCHER(equalsBoundNode);
232   REGISTER_MATCHER(equalsIntegralValue);
233   REGISTER_MATCHER(explicitCastExpr);
234   REGISTER_MATCHER(expr);
235   REGISTER_MATCHER(exprWithCleanups);
236   REGISTER_MATCHER(fieldDecl);
237   REGISTER_MATCHER(fixedPointLiteral);
238   REGISTER_MATCHER(floatLiteral);
239   REGISTER_MATCHER(forCallable);
240   REGISTER_MATCHER(forDecomposition);
241   REGISTER_MATCHER(forEach);
242   REGISTER_MATCHER(forEachArgumentWithParam);
243   REGISTER_MATCHER(forEachArgumentWithParamType);
244   REGISTER_MATCHER(forEachConstructorInitializer);
245   REGISTER_MATCHER(forEachDescendant);
246   REGISTER_MATCHER(forEachOverridden);
247   REGISTER_MATCHER(forEachSwitchCase);
248   REGISTER_MATCHER(forField);
249   REGISTER_MATCHER(forFunction);
250   REGISTER_MATCHER(forStmt);
251   REGISTER_MATCHER(friendDecl);
252   REGISTER_MATCHER(functionDecl);
253   REGISTER_MATCHER(functionProtoType);
254   REGISTER_MATCHER(functionTemplateDecl);
255   REGISTER_MATCHER(functionType);
256   REGISTER_MATCHER(genericSelectionExpr);
257   REGISTER_MATCHER(gnuNullExpr);
258   REGISTER_MATCHER(gotoStmt);
259   REGISTER_MATCHER(has);
260   REGISTER_MATCHER(hasAncestor);
261   REGISTER_MATCHER(hasAnyArgument);
262   REGISTER_MATCHER(hasAnyBase);
263   REGISTER_MATCHER(hasAnyBinding);
264   REGISTER_MATCHER(hasAnyBody);
265   REGISTER_MATCHER(hasAnyClause);
266   REGISTER_MATCHER(hasAnyConstructorInitializer);
267   REGISTER_MATCHER(hasAnyDeclaration);
268   REGISTER_MATCHER(hasAnyName);
269   REGISTER_MATCHER(hasAnyOperatorName);
270   REGISTER_MATCHER(hasAnyOverloadedOperatorName);
271   REGISTER_MATCHER(hasAnyParameter);
272   REGISTER_MATCHER(hasAnyPlacementArg);
273   REGISTER_MATCHER(hasAnySelector);
274   REGISTER_MATCHER(hasAnySubstatement);
275   REGISTER_MATCHER(hasAnyTemplateArgument);
276   REGISTER_MATCHER(hasAnyUsingShadowDecl);
277   REGISTER_MATCHER(hasArgument);
278   REGISTER_MATCHER(hasArgumentOfType);
279   REGISTER_MATCHER(hasArraySize);
280   REGISTER_MATCHER(hasAttr);
281   REGISTER_MATCHER(hasAutomaticStorageDuration);
282   REGISTER_MATCHER(hasBase);
283   REGISTER_MATCHER(hasBinding);
284   REGISTER_MATCHER(hasBitWidth);
285   REGISTER_MATCHER(hasBody);
286   REGISTER_MATCHER(hasCanonicalType);
287   REGISTER_MATCHER(hasCaseConstant);
288   REGISTER_MATCHER(hasCastKind);
289   REGISTER_MATCHER(hasCondition);
290   REGISTER_MATCHER(hasConditionVariableStatement);
291   REGISTER_MATCHER(hasDecayedType);
292   REGISTER_MATCHER(hasDeclContext);
293   REGISTER_MATCHER(hasDeclaration);
294   REGISTER_MATCHER(hasDeducedType);
295   REGISTER_MATCHER(hasDefaultArgument);
296   REGISTER_MATCHER(hasDefinition);
297   REGISTER_MATCHER(hasDescendant);
298   REGISTER_MATCHER(hasDestinationType);
299   REGISTER_MATCHER(hasDirectBase);
300   REGISTER_MATCHER(hasDynamicExceptionSpec);
301   REGISTER_MATCHER(hasEitherOperand);
302   REGISTER_MATCHER(hasElementType);
303   REGISTER_MATCHER(hasElse);
304   REGISTER_MATCHER(hasExplicitSpecifier);
305   REGISTER_MATCHER(hasExternalFormalLinkage);
306   REGISTER_MATCHER(hasFalseExpression);
307   REGISTER_MATCHER(hasGlobalStorage);
308   REGISTER_MATCHER(hasImplicitDestinationType);
309   REGISTER_MATCHER(hasInClassInitializer);
310   REGISTER_MATCHER(hasIncrement);
311   REGISTER_MATCHER(hasIndex);
312   REGISTER_MATCHER(hasInit);
313   REGISTER_MATCHER(hasInitializer);
314   REGISTER_MATCHER(hasInitStatement);
315   REGISTER_MATCHER(hasKeywordSelector);
316   REGISTER_MATCHER(hasLHS);
317   REGISTER_MATCHER(hasLocalQualifiers);
318   REGISTER_MATCHER(hasLocalStorage);
319   REGISTER_MATCHER(hasLoopInit);
320   REGISTER_MATCHER(hasLoopVariable);
321   REGISTER_MATCHER(hasMemberName);
322   REGISTER_MATCHER(hasMethod);
323   REGISTER_MATCHER(hasName);
324   REGISTER_MATCHER(hasNullSelector);
325   REGISTER_MATCHER(hasObjectExpression);
326   REGISTER_MATCHER(hasOperands);
327   REGISTER_MATCHER(hasOperatorName);
328   REGISTER_MATCHER(hasOverloadedOperatorName);
329   REGISTER_MATCHER(hasParameter);
330   REGISTER_MATCHER(hasParent);
331   REGISTER_MATCHER(hasQualifier);
332   REGISTER_MATCHER(hasRHS);
333   REGISTER_MATCHER(hasRangeInit);
334   REGISTER_MATCHER(hasReceiver);
335   REGISTER_MATCHER(hasReceiverType);
336   REGISTER_MATCHER(hasReplacementType);
337   REGISTER_MATCHER(hasReturnValue);
338   REGISTER_MATCHER(hasPlacementArg);
339   REGISTER_MATCHER(hasSelector);
340   REGISTER_MATCHER(hasSingleDecl);
341   REGISTER_MATCHER(hasSize);
342   REGISTER_MATCHER(hasSizeExpr);
343   REGISTER_MATCHER(hasSourceExpression);
344   REGISTER_MATCHER(hasSpecializedTemplate);
345   REGISTER_MATCHER(hasStaticStorageDuration);
346   REGISTER_MATCHER(hasStructuredBlock);
347   REGISTER_MATCHER(hasSyntacticForm);
348   REGISTER_MATCHER(hasTargetDecl);
349   REGISTER_MATCHER(hasTemplateArgument);
350   REGISTER_MATCHER(hasThen);
351   REGISTER_MATCHER(hasThreadStorageDuration);
352   REGISTER_MATCHER(hasTrailingReturn);
353   REGISTER_MATCHER(hasTrueExpression);
354   REGISTER_MATCHER(hasTypeLoc);
355   REGISTER_MATCHER(hasUnaryOperand);
356   REGISTER_MATCHER(hasUnarySelector);
357   REGISTER_MATCHER(hasUnderlyingDecl);
358   REGISTER_MATCHER(hasUnderlyingType);
359   REGISTER_MATCHER(hasUnqualifiedDesugaredType);
360   REGISTER_MATCHER(hasValueType);
361   REGISTER_MATCHER(ifStmt);
362   REGISTER_MATCHER(ignoringElidableConstructorCall);
363   REGISTER_MATCHER(ignoringImpCasts);
364   REGISTER_MATCHER(ignoringImplicit);
365   REGISTER_MATCHER(ignoringParenCasts);
366   REGISTER_MATCHER(ignoringParenImpCasts);
367   REGISTER_MATCHER(imaginaryLiteral);
368   REGISTER_MATCHER(implicitCastExpr);
369   REGISTER_MATCHER(implicitValueInitExpr);
370   REGISTER_MATCHER(incompleteArrayType);
371   REGISTER_MATCHER(indirectFieldDecl);
372   REGISTER_MATCHER(initListExpr);
373   REGISTER_MATCHER(injectedClassNameType);
374   REGISTER_MATCHER(innerType);
375   REGISTER_MATCHER(integerLiteral);
376   REGISTER_MATCHER(invocation);
377   REGISTER_MATCHER(isAllowedToContainClauseKind);
378   REGISTER_MATCHER(isAnonymous);
379   REGISTER_MATCHER(isAnyCharacter);
380   REGISTER_MATCHER(isAnyPointer);
381   REGISTER_MATCHER(isArray);
382   REGISTER_MATCHER(isArrow);
383   REGISTER_MATCHER(isAssignmentOperator);
384   REGISTER_MATCHER(isAtPosition);
385   REGISTER_MATCHER(isBaseInitializer);
386   REGISTER_MATCHER(isBitField);
387   REGISTER_MATCHER(isCatchAll);
388   REGISTER_MATCHER(isClass);
389   REGISTER_MATCHER(isClassMessage);
390   REGISTER_MATCHER(isClassMethod);
391   REGISTER_MATCHER(isComparisonOperator);
392   REGISTER_MATCHER(isConst);
393   REGISTER_MATCHER(isConstQualified);
394   REGISTER_MATCHER(isConstexpr);
395   REGISTER_MATCHER(isCopyAssignmentOperator);
396   REGISTER_MATCHER(isCopyConstructor);
397   REGISTER_MATCHER(isDefaultConstructor);
398   REGISTER_MATCHER(isDefaulted);
399   REGISTER_MATCHER(isDefinition);
400   REGISTER_MATCHER(isDelegatingConstructor);
401   REGISTER_MATCHER(isDeleted);
402   REGISTER_MATCHER(isEnum);
403   REGISTER_MATCHER(isExceptionVariable);
404   REGISTER_MATCHER(isExpandedFromMacro);
405   REGISTER_MATCHER(isExpansionInMainFile);
406   REGISTER_MATCHER(isExpansionInSystemHeader);
407   REGISTER_MATCHER(isExplicit);
408   REGISTER_MATCHER(isExplicitTemplateSpecialization);
409   REGISTER_MATCHER(isExpr);
410   REGISTER_MATCHER(isExternC);
411   REGISTER_MATCHER(isFinal);
412   REGISTER_MATCHER(isFirstPrivateKind);
413   REGISTER_MATCHER(isImplicit);
414   REGISTER_MATCHER(isInStdNamespace);
415   REGISTER_MATCHER(isInTemplateInstantiation);
416   REGISTER_MATCHER(isInline);
417   REGISTER_MATCHER(isInstanceMessage);
418   REGISTER_MATCHER(isInstanceMethod);
419   REGISTER_MATCHER(isInstantiated);
420   REGISTER_MATCHER(isInstantiationDependent);
421   REGISTER_MATCHER(isInteger);
422   REGISTER_MATCHER(isIntegral);
423   REGISTER_MATCHER(isLambda);
424   REGISTER_MATCHER(isListInitialization);
425   REGISTER_MATCHER(isMain);
426   REGISTER_MATCHER(isMemberInitializer);
427   REGISTER_MATCHER(isMoveAssignmentOperator);
428   REGISTER_MATCHER(isMoveConstructor);
429   REGISTER_MATCHER(isNoReturn);
430   REGISTER_MATCHER(isNoThrow);
431   REGISTER_MATCHER(isNoneKind);
432   REGISTER_MATCHER(isOverride);
433   REGISTER_MATCHER(isPrivate);
434   REGISTER_MATCHER(isProtected);
435   REGISTER_MATCHER(isPublic);
436   REGISTER_MATCHER(isPure);
437   REGISTER_MATCHER(isScoped);
438   REGISTER_MATCHER(isSharedKind);
439   REGISTER_MATCHER(isSignedInteger);
440   REGISTER_MATCHER(isStandaloneDirective);
441   REGISTER_MATCHER(isStaticLocal);
442   REGISTER_MATCHER(isStaticStorageClass);
443   REGISTER_MATCHER(isStruct);
444   REGISTER_MATCHER(isTemplateInstantiation);
445   REGISTER_MATCHER(isTypeDependent);
446   REGISTER_MATCHER(isUnion);
447   REGISTER_MATCHER(isUnsignedInteger);
448   REGISTER_MATCHER(isUserProvided);
449   REGISTER_MATCHER(isValueDependent);
450   REGISTER_MATCHER(isVariadic);
451   REGISTER_MATCHER(isVirtual);
452   REGISTER_MATCHER(isVirtualAsWritten);
453   REGISTER_MATCHER(isVolatileQualified);
454   REGISTER_MATCHER(isWeak);
455   REGISTER_MATCHER(isWritten);
456   REGISTER_MATCHER(lValueReferenceType);
457   REGISTER_MATCHER(labelDecl);
458   REGISTER_MATCHER(labelStmt);
459   REGISTER_MATCHER(lambdaExpr);
460   REGISTER_MATCHER(linkageSpecDecl);
461   REGISTER_MATCHER(materializeTemporaryExpr);
462   REGISTER_MATCHER(member);
463   REGISTER_MATCHER(memberExpr);
464   REGISTER_MATCHER(memberHasSameNameAsBoundNode);
465   REGISTER_MATCHER(memberPointerType);
466   REGISTER_MATCHER(namedDecl);
467   REGISTER_MATCHER(namesType);
468   REGISTER_MATCHER(namespaceAliasDecl);
469   REGISTER_MATCHER(namespaceDecl);
470   REGISTER_MATCHER(nestedNameSpecifier);
471   REGISTER_MATCHER(nestedNameSpecifierLoc);
472   REGISTER_MATCHER(nonTypeTemplateParmDecl);
473   REGISTER_MATCHER(nullPointerConstant);
474   REGISTER_MATCHER(nullStmt);
475   REGISTER_MATCHER(numSelectorArgs);
476   REGISTER_MATCHER(objcCatchStmt);
477   REGISTER_MATCHER(objcCategoryDecl);
478   REGISTER_MATCHER(objcCategoryImplDecl);
479   REGISTER_MATCHER(objcFinallyStmt);
480   REGISTER_MATCHER(objcImplementationDecl);
481   REGISTER_MATCHER(objcInterfaceDecl);
482   REGISTER_MATCHER(objcIvarDecl);
483   REGISTER_MATCHER(objcIvarRefExpr);
484   REGISTER_MATCHER(objcMessageExpr);
485   REGISTER_MATCHER(objcMethodDecl);
486   REGISTER_MATCHER(objcObjectPointerType);
487   REGISTER_MATCHER(objcPropertyDecl);
488   REGISTER_MATCHER(objcProtocolDecl);
489   REGISTER_MATCHER(objcThrowStmt);
490   REGISTER_MATCHER(objcTryStmt);
491   REGISTER_MATCHER(ofClass);
492   REGISTER_MATCHER(ofKind);
493   REGISTER_MATCHER(ompDefaultClause);
494   REGISTER_MATCHER(ompExecutableDirective);
495   REGISTER_MATCHER(on);
496   REGISTER_MATCHER(onImplicitObjectArgument);
497   REGISTER_MATCHER(opaqueValueExpr);
498   REGISTER_MATCHER(optionally);
499   REGISTER_MATCHER(parameterCountIs);
500   REGISTER_MATCHER(parenExpr);
501   REGISTER_MATCHER(parenListExpr);
502   REGISTER_MATCHER(parenType);
503   REGISTER_MATCHER(parmVarDecl);
504   REGISTER_MATCHER(pointee);
505   REGISTER_MATCHER(pointerType);
506   REGISTER_MATCHER(predefinedExpr);
507   REGISTER_MATCHER(qualType);
508   REGISTER_MATCHER(rValueReferenceType);
509   REGISTER_MATCHER(realFloatingPointType);
510   REGISTER_MATCHER(recordDecl);
511   REGISTER_MATCHER(recordType);
512   REGISTER_MATCHER(referenceType);
513   REGISTER_MATCHER(refersToDeclaration);
514   REGISTER_MATCHER(refersToIntegralType);
515   REGISTER_MATCHER(refersToTemplate);
516   REGISTER_MATCHER(refersToType);
517   REGISTER_MATCHER(requiresZeroInitialization);
518   REGISTER_MATCHER(returnStmt);
519   REGISTER_MATCHER(returns);
520   REGISTER_MATCHER(sizeOfExpr);
521   REGISTER_MATCHER(specifiesNamespace);
522   REGISTER_MATCHER(specifiesType);
523   REGISTER_MATCHER(specifiesTypeLoc);
524   REGISTER_MATCHER(statementCountIs);
525   REGISTER_MATCHER(staticAssertDecl);
526   REGISTER_MATCHER(stmt);
527   REGISTER_MATCHER(stmtExpr);
528   REGISTER_MATCHER(stringLiteral);
529   REGISTER_MATCHER(substNonTypeTemplateParmExpr);
530   REGISTER_MATCHER(substTemplateTypeParmType);
531   REGISTER_MATCHER(switchCase);
532   REGISTER_MATCHER(switchStmt);
533   REGISTER_MATCHER(tagDecl);
534   REGISTER_MATCHER(tagType);
535   REGISTER_MATCHER(templateArgument);
536   REGISTER_MATCHER(templateArgumentCountIs);
537   REGISTER_MATCHER(templateArgumentLoc);
538   REGISTER_MATCHER(templateName);
539   REGISTER_MATCHER(templateSpecializationType);
540   REGISTER_MATCHER(templateTemplateParmDecl);
541   REGISTER_MATCHER(templateTypeParmDecl);
542   REGISTER_MATCHER(templateTypeParmType);
543   REGISTER_MATCHER(throughUsingDecl);
544   REGISTER_MATCHER(to);
545   REGISTER_MATCHER(translationUnitDecl);
546   REGISTER_MATCHER(type);
547   REGISTER_MATCHER(typeAliasDecl);
548   REGISTER_MATCHER(typeAliasTemplateDecl);
549   REGISTER_MATCHER(typeLoc);
550   REGISTER_MATCHER(typedefDecl);
551   REGISTER_MATCHER(typedefNameDecl);
552   REGISTER_MATCHER(typedefType);
553   REGISTER_MATCHER(unaryExprOrTypeTraitExpr);
554   REGISTER_MATCHER(unaryOperator);
555   REGISTER_MATCHER(unaryTransformType);
556   REGISTER_MATCHER(unless);
557   REGISTER_MATCHER(unresolvedLookupExpr);
558   REGISTER_MATCHER(unresolvedMemberExpr);
559   REGISTER_MATCHER(unresolvedUsingTypenameDecl);
560   REGISTER_MATCHER(unresolvedUsingValueDecl);
561   REGISTER_MATCHER(userDefinedLiteral);
562   REGISTER_MATCHER(usesADL);
563   REGISTER_MATCHER(usingDecl);
564   REGISTER_MATCHER(usingEnumDecl);
565   REGISTER_MATCHER(usingDirectiveDecl);
566   REGISTER_MATCHER(valueDecl);
567   REGISTER_MATCHER(varDecl);
568   REGISTER_MATCHER(variableArrayType);
569   REGISTER_MATCHER(voidType);
570   REGISTER_MATCHER(whileStmt);
571   REGISTER_MATCHER(withInitializer);
572 }
573 
574 RegistryMaps::~RegistryMaps() = default;
575 
576 static llvm::ManagedStatic<RegistryMaps> RegistryData;
577 
nodeMatcherType(MatcherCtor Ctor)578 ASTNodeKind Registry::nodeMatcherType(MatcherCtor Ctor) {
579   return Ctor->nodeMatcherType();
580 }
581 
MatcherDescriptorPtr(MatcherDescriptor * Ptr)582 internal::MatcherDescriptorPtr::MatcherDescriptorPtr(MatcherDescriptor *Ptr)
583     : Ptr(Ptr) {}
584 
~MatcherDescriptorPtr()585 internal::MatcherDescriptorPtr::~MatcherDescriptorPtr() { delete Ptr; }
586 
isBuilderMatcher(MatcherCtor Ctor)587 bool Registry::isBuilderMatcher(MatcherCtor Ctor) {
588   return Ctor->isBuilderMatcher();
589 }
590 
591 internal::MatcherDescriptorPtr
buildMatcherCtor(MatcherCtor Ctor,SourceRange NameRange,ArrayRef<ParserValue> Args,Diagnostics * Error)592 Registry::buildMatcherCtor(MatcherCtor Ctor, SourceRange NameRange,
593                            ArrayRef<ParserValue> Args, Diagnostics *Error) {
594   return internal::MatcherDescriptorPtr(
595       Ctor->buildMatcherCtor(NameRange, Args, Error).release());
596 }
597 
598 // static
lookupMatcherCtor(StringRef MatcherName)599 llvm::Optional<MatcherCtor> Registry::lookupMatcherCtor(StringRef MatcherName) {
600   auto it = RegistryData->constructors().find(MatcherName);
601   return it == RegistryData->constructors().end()
602              ? llvm::Optional<MatcherCtor>()
603              : it->second.get();
604 }
605 
operator <<(llvm::raw_ostream & OS,const std::set<ASTNodeKind> & KS)606 static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
607                                      const std::set<ASTNodeKind> &KS) {
608   unsigned Count = 0;
609   for (std::set<ASTNodeKind>::const_iterator I = KS.begin(), E = KS.end();
610        I != E; ++I) {
611     if (I != KS.begin())
612       OS << "|";
613     if (Count++ == 3) {
614       OS << "...";
615       break;
616     }
617     OS << *I;
618   }
619   return OS;
620 }
621 
getAcceptedCompletionTypes(ArrayRef<std::pair<MatcherCtor,unsigned>> Context)622 std::vector<ArgKind> Registry::getAcceptedCompletionTypes(
623     ArrayRef<std::pair<MatcherCtor, unsigned>> Context) {
624   ASTNodeKind InitialTypes[] = {
625       ASTNodeKind::getFromNodeKind<Decl>(),
626       ASTNodeKind::getFromNodeKind<QualType>(),
627       ASTNodeKind::getFromNodeKind<Type>(),
628       ASTNodeKind::getFromNodeKind<Stmt>(),
629       ASTNodeKind::getFromNodeKind<NestedNameSpecifier>(),
630       ASTNodeKind::getFromNodeKind<NestedNameSpecifierLoc>(),
631       ASTNodeKind::getFromNodeKind<TypeLoc>()};
632 
633   // Starting with the above seed of acceptable top-level matcher types, compute
634   // the acceptable type set for the argument indicated by each context element.
635   std::set<ArgKind> TypeSet;
636   for (auto IT : InitialTypes) {
637     TypeSet.insert(ArgKind::MakeMatcherArg(IT));
638   }
639   for (const auto &CtxEntry : Context) {
640     MatcherCtor Ctor = CtxEntry.first;
641     unsigned ArgNumber = CtxEntry.second;
642     std::vector<ArgKind> NextTypeSet;
643     for (const ArgKind &Kind : TypeSet) {
644       if (Kind.getArgKind() == Kind.AK_Matcher &&
645           Ctor->isConvertibleTo(Kind.getMatcherKind()) &&
646           (Ctor->isVariadic() || ArgNumber < Ctor->getNumArgs()))
647         Ctor->getArgKinds(Kind.getMatcherKind(), ArgNumber, NextTypeSet);
648     }
649     TypeSet.clear();
650     TypeSet.insert(NextTypeSet.begin(), NextTypeSet.end());
651   }
652   return std::vector<ArgKind>(TypeSet.begin(), TypeSet.end());
653 }
654 
655 std::vector<MatcherCompletion>
getMatcherCompletions(ArrayRef<ArgKind> AcceptedTypes)656 Registry::getMatcherCompletions(ArrayRef<ArgKind> AcceptedTypes) {
657   std::vector<MatcherCompletion> Completions;
658 
659   // Search the registry for acceptable matchers.
660   for (const auto &M : RegistryData->constructors()) {
661     const MatcherDescriptor& Matcher = *M.getValue();
662     StringRef Name = M.getKey();
663 
664     std::set<ASTNodeKind> RetKinds;
665     unsigned NumArgs = Matcher.isVariadic() ? 1 : Matcher.getNumArgs();
666     bool IsPolymorphic = Matcher.isPolymorphic();
667     std::vector<std::vector<ArgKind>> ArgsKinds(NumArgs);
668     unsigned MaxSpecificity = 0;
669     bool NodeArgs = false;
670     for (const ArgKind& Kind : AcceptedTypes) {
671       if (Kind.getArgKind() != Kind.AK_Matcher &&
672           Kind.getArgKind() != Kind.AK_Node) {
673         continue;
674       }
675 
676       if (Kind.getArgKind() == Kind.AK_Node) {
677         NodeArgs = true;
678         unsigned Specificity;
679         ASTNodeKind LeastDerivedKind;
680         if (Matcher.isConvertibleTo(Kind.getNodeKind(), &Specificity,
681                                     &LeastDerivedKind)) {
682           if (MaxSpecificity < Specificity)
683             MaxSpecificity = Specificity;
684           RetKinds.insert(LeastDerivedKind);
685           for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
686             Matcher.getArgKinds(Kind.getNodeKind(), Arg, ArgsKinds[Arg]);
687           if (IsPolymorphic)
688             break;
689         }
690       } else {
691         unsigned Specificity;
692         ASTNodeKind LeastDerivedKind;
693         if (Matcher.isConvertibleTo(Kind.getMatcherKind(), &Specificity,
694                                     &LeastDerivedKind)) {
695           if (MaxSpecificity < Specificity)
696             MaxSpecificity = Specificity;
697           RetKinds.insert(LeastDerivedKind);
698           for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
699             Matcher.getArgKinds(Kind.getMatcherKind(), Arg, ArgsKinds[Arg]);
700           if (IsPolymorphic)
701             break;
702         }
703       }
704     }
705 
706     if (!RetKinds.empty() && MaxSpecificity > 0) {
707       std::string Decl;
708       llvm::raw_string_ostream OS(Decl);
709 
710       std::string TypedText = std::string(Name);
711 
712       if (NodeArgs) {
713         OS << Name;
714       } else {
715 
716         if (IsPolymorphic) {
717           OS << "Matcher<T> " << Name << "(Matcher<T>";
718         } else {
719           OS << "Matcher<" << RetKinds << "> " << Name << "(";
720           for (const std::vector<ArgKind> &Arg : ArgsKinds) {
721             if (&Arg != &ArgsKinds[0])
722               OS << ", ";
723 
724             bool FirstArgKind = true;
725             std::set<ASTNodeKind> MatcherKinds;
726             // Two steps. First all non-matchers, then matchers only.
727             for (const ArgKind &AK : Arg) {
728               if (AK.getArgKind() == ArgKind::AK_Matcher) {
729                 MatcherKinds.insert(AK.getMatcherKind());
730               } else {
731                 if (!FirstArgKind)
732                   OS << "|";
733                 FirstArgKind = false;
734                 OS << AK.asString();
735               }
736             }
737             if (!MatcherKinds.empty()) {
738               if (!FirstArgKind) OS << "|";
739               OS << "Matcher<" << MatcherKinds << ">";
740             }
741           }
742         }
743         if (Matcher.isVariadic())
744           OS << "...";
745         OS << ")";
746 
747         TypedText += "(";
748         if (ArgsKinds.empty())
749           TypedText += ")";
750         else if (ArgsKinds[0][0].getArgKind() == ArgKind::AK_String)
751           TypedText += "\"";
752       }
753 
754       Completions.emplace_back(TypedText, OS.str(), MaxSpecificity);
755     }
756   }
757 
758   return Completions;
759 }
760 
constructMatcher(MatcherCtor Ctor,SourceRange NameRange,ArrayRef<ParserValue> Args,Diagnostics * Error)761 VariantMatcher Registry::constructMatcher(MatcherCtor Ctor,
762                                           SourceRange NameRange,
763                                           ArrayRef<ParserValue> Args,
764                                           Diagnostics *Error) {
765   return Ctor->create(NameRange, Args, Error);
766 }
767 
constructBoundMatcher(MatcherCtor Ctor,SourceRange NameRange,StringRef BindID,ArrayRef<ParserValue> Args,Diagnostics * Error)768 VariantMatcher Registry::constructBoundMatcher(MatcherCtor Ctor,
769                                                SourceRange NameRange,
770                                                StringRef BindID,
771                                                ArrayRef<ParserValue> Args,
772                                                Diagnostics *Error) {
773   VariantMatcher Out = constructMatcher(Ctor, NameRange, Args, Error);
774   if (Out.isNull()) return Out;
775 
776   llvm::Optional<DynTypedMatcher> Result = Out.getSingleMatcher();
777   if (Result.hasValue()) {
778     llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID);
779     if (Bound.hasValue()) {
780       return VariantMatcher::SingleMatcher(*Bound);
781     }
782   }
783   Error->addError(NameRange, Error->ET_RegistryNotBindable);
784   return VariantMatcher();
785 }
786 
787 } // namespace dynamic
788 } // namespace ast_matchers
789 } // namespace clang
790