• 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/StringMap.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include <set>
22 #include <utility>
23 
24 using namespace clang::ast_type_traits;
25 
26 namespace clang {
27 namespace ast_matchers {
28 namespace dynamic {
29 namespace {
30 
31 using internal::MatcherDescriptor;
32 
33 typedef llvm::StringMap<const MatcherDescriptor *> ConstructorMap;
34 class RegistryMaps {
35 public:
36   RegistryMaps();
37   ~RegistryMaps();
38 
constructors() const39   const ConstructorMap &constructors() const { return Constructors; }
40 
41 private:
42   void registerMatcher(StringRef MatcherName, MatcherDescriptor *Callback);
43   ConstructorMap Constructors;
44 };
45 
registerMatcher(StringRef MatcherName,MatcherDescriptor * Callback)46 void RegistryMaps::registerMatcher(StringRef MatcherName,
47                                    MatcherDescriptor *Callback) {
48   assert(Constructors.find(MatcherName) == Constructors.end());
49   Constructors[MatcherName] = Callback;
50 }
51 
52 #define REGISTER_MATCHER(name)                                                 \
53   registerMatcher(#name, internal::makeMatcherAutoMarshall(                    \
54                              ::clang::ast_matchers::name, #name));
55 
56 #define SPECIFIC_MATCHER_OVERLOAD(name, Id)                                    \
57   static_cast< ::clang::ast_matchers::name##_Type##Id>(                        \
58       ::clang::ast_matchers::name)
59 
60 #define REGISTER_OVERLOADED_2(name)                                            \
61   do {                                                                         \
62     MatcherDescriptor *Callbacks[] = {                                         \
63       internal::makeMatcherAutoMarshall(SPECIFIC_MATCHER_OVERLOAD(name, 0),    \
64                                         #name),                                \
65       internal::makeMatcherAutoMarshall(SPECIFIC_MATCHER_OVERLOAD(name, 1),    \
66                                         #name)                                 \
67     };                                                                         \
68     registerMatcher(#name,                                                     \
69                     new internal::OverloadedMatcherDescriptor(Callbacks));     \
70   } while (0)
71 
72 /// \brief Generate a registry map with all the known matchers.
RegistryMaps()73 RegistryMaps::RegistryMaps() {
74   // TODO: Here is the list of the missing matchers, grouped by reason.
75   //
76   // Need Variant/Parser fixes:
77   // ofKind
78   //
79   // Polymorphic + argument overload:
80   // findAll
81   //
82   // Other:
83   // equals
84   // equalsNode
85 
86   REGISTER_OVERLOADED_2(callee);
87   REGISTER_OVERLOADED_2(hasPrefix);
88   REGISTER_OVERLOADED_2(hasType);
89   REGISTER_OVERLOADED_2(isDerivedFrom);
90   REGISTER_OVERLOADED_2(isSameOrDerivedFrom);
91   REGISTER_OVERLOADED_2(loc);
92   REGISTER_OVERLOADED_2(pointsTo);
93   REGISTER_OVERLOADED_2(references);
94   REGISTER_OVERLOADED_2(thisPointerType);
95 
96   REGISTER_MATCHER(accessSpecDecl);
97   REGISTER_MATCHER(alignOfExpr);
98   REGISTER_MATCHER(allOf);
99   REGISTER_MATCHER(anyOf);
100   REGISTER_MATCHER(anything);
101   REGISTER_MATCHER(argumentCountIs);
102   REGISTER_MATCHER(arraySubscriptExpr);
103   REGISTER_MATCHER(arrayType);
104   REGISTER_MATCHER(asString);
105   REGISTER_MATCHER(asmStmt);
106   REGISTER_MATCHER(atomicType);
107   REGISTER_MATCHER(autoType);
108   REGISTER_MATCHER(binaryOperator);
109   REGISTER_MATCHER(bindTemporaryExpr);
110   REGISTER_MATCHER(blockPointerType);
111   REGISTER_MATCHER(boolLiteral);
112   REGISTER_MATCHER(breakStmt);
113   REGISTER_MATCHER(builtinType);
114   REGISTER_MATCHER(cStyleCastExpr);
115   REGISTER_MATCHER(callExpr);
116   REGISTER_MATCHER(caseStmt);
117   REGISTER_MATCHER(castExpr);
118   REGISTER_MATCHER(catchStmt);
119   REGISTER_MATCHER(characterLiteral);
120   REGISTER_MATCHER(classTemplateDecl);
121   REGISTER_MATCHER(classTemplateSpecializationDecl);
122   REGISTER_MATCHER(complexType);
123   REGISTER_MATCHER(compoundLiteralExpr);
124   REGISTER_MATCHER(compoundStmt);
125   REGISTER_MATCHER(conditionalOperator);
126   REGISTER_MATCHER(constCastExpr);
127   REGISTER_MATCHER(constantArrayType);
128   REGISTER_MATCHER(constructExpr);
129   REGISTER_MATCHER(constructorDecl);
130   REGISTER_MATCHER(containsDeclaration);
131   REGISTER_MATCHER(continueStmt);
132   REGISTER_MATCHER(ctorInitializer);
133   REGISTER_MATCHER(decl);
134   REGISTER_MATCHER(declCountIs);
135   REGISTER_MATCHER(declRefExpr);
136   REGISTER_MATCHER(declStmt);
137   REGISTER_MATCHER(declaratorDecl);
138   REGISTER_MATCHER(defaultArgExpr);
139   REGISTER_MATCHER(defaultStmt);
140   REGISTER_MATCHER(deleteExpr);
141   REGISTER_MATCHER(dependentSizedArrayType);
142   REGISTER_MATCHER(destructorDecl);
143   REGISTER_MATCHER(doStmt);
144   REGISTER_MATCHER(dynamicCastExpr);
145   REGISTER_MATCHER(eachOf);
146   REGISTER_MATCHER(elaboratedType);
147   REGISTER_MATCHER(enumConstantDecl);
148   REGISTER_MATCHER(enumDecl);
149   REGISTER_MATCHER(equalsBoundNode);
150   REGISTER_MATCHER(explicitCastExpr);
151   REGISTER_MATCHER(expr);
152   REGISTER_MATCHER(exprWithCleanups);
153   REGISTER_MATCHER(fieldDecl);
154   REGISTER_MATCHER(floatLiteral);
155   REGISTER_MATCHER(forEach);
156   REGISTER_MATCHER(forEachConstructorInitializer);
157   REGISTER_MATCHER(forEachDescendant);
158   REGISTER_MATCHER(forEachSwitchCase);
159   REGISTER_MATCHER(forField);
160   REGISTER_MATCHER(forRangeStmt);
161   REGISTER_MATCHER(forStmt);
162   REGISTER_MATCHER(friendDecl);
163   REGISTER_MATCHER(functionDecl);
164   REGISTER_MATCHER(functionTemplateDecl);
165   REGISTER_MATCHER(functionType);
166   REGISTER_MATCHER(functionalCastExpr);
167   REGISTER_MATCHER(gotoStmt);
168   REGISTER_MATCHER(has);
169   REGISTER_MATCHER(hasAncestor);
170   REGISTER_MATCHER(hasAnyArgument);
171   REGISTER_MATCHER(hasAnyConstructorInitializer);
172   REGISTER_MATCHER(hasAnyParameter);
173   REGISTER_MATCHER(hasAnySubstatement);
174   REGISTER_MATCHER(hasAnyTemplateArgument);
175   REGISTER_MATCHER(hasAnyUsingShadowDecl);
176   REGISTER_MATCHER(hasArgument);
177   REGISTER_MATCHER(hasArgumentOfType);
178   REGISTER_MATCHER(hasBase);
179   REGISTER_MATCHER(hasBody);
180   REGISTER_MATCHER(hasCanonicalType);
181   REGISTER_MATCHER(hasCaseConstant);
182   REGISTER_MATCHER(hasCondition);
183   REGISTER_MATCHER(hasConditionVariableStatement);
184   REGISTER_MATCHER(hasDeclContext);
185   REGISTER_MATCHER(hasDeclaration);
186   REGISTER_MATCHER(hasDeducedType);
187   REGISTER_MATCHER(hasDescendant);
188   REGISTER_MATCHER(hasDestinationType);
189   REGISTER_MATCHER(hasEitherOperand);
190   REGISTER_MATCHER(hasElementType);
191   REGISTER_MATCHER(hasFalseExpression);
192   REGISTER_MATCHER(hasGlobalStorage);
193   REGISTER_MATCHER(hasImplicitDestinationType);
194   REGISTER_MATCHER(hasIncrement);
195   REGISTER_MATCHER(hasIndex);
196   REGISTER_MATCHER(hasInitializer);
197   REGISTER_MATCHER(hasLHS);
198   REGISTER_MATCHER(hasLocalQualifiers);
199   REGISTER_MATCHER(hasLocalStorage);
200   REGISTER_MATCHER(hasLoopInit);
201   REGISTER_MATCHER(hasMethod);
202   REGISTER_MATCHER(hasName);
203   REGISTER_MATCHER(hasObjectExpression);
204   REGISTER_MATCHER(hasOperatorName);
205   REGISTER_MATCHER(hasOverloadedOperatorName);
206   REGISTER_MATCHER(hasParameter);
207   REGISTER_MATCHER(hasParent);
208   REGISTER_MATCHER(hasQualifier);
209   REGISTER_MATCHER(hasRHS);
210   REGISTER_MATCHER(hasSingleDecl);
211   REGISTER_MATCHER(hasSize);
212   REGISTER_MATCHER(hasSizeExpr);
213   REGISTER_MATCHER(hasSourceExpression);
214   REGISTER_MATCHER(hasTargetDecl);
215   REGISTER_MATCHER(hasTemplateArgument);
216   REGISTER_MATCHER(hasTrueExpression);
217   REGISTER_MATCHER(hasTypeLoc);
218   REGISTER_MATCHER(hasUnaryOperand);
219   REGISTER_MATCHER(hasValueType);
220   REGISTER_MATCHER(ifStmt);
221   REGISTER_MATCHER(ignoringImpCasts);
222   REGISTER_MATCHER(ignoringParenCasts);
223   REGISTER_MATCHER(ignoringParenImpCasts);
224   REGISTER_MATCHER(implicitCastExpr);
225   REGISTER_MATCHER(incompleteArrayType);
226   REGISTER_MATCHER(initListExpr);
227   REGISTER_MATCHER(innerType);
228   REGISTER_MATCHER(integerLiteral);
229   REGISTER_MATCHER(isArrow);
230   REGISTER_MATCHER(isConst);
231   REGISTER_MATCHER(isConstQualified);
232   REGISTER_MATCHER(isDefinition);
233   REGISTER_MATCHER(isExplicitTemplateSpecialization);
234   REGISTER_MATCHER(isExpr);
235   REGISTER_MATCHER(isExternC);
236   REGISTER_MATCHER(isImplicit);
237   REGISTER_MATCHER(isInteger);
238   REGISTER_MATCHER(isListInitialization);
239   REGISTER_MATCHER(isOverride);
240   REGISTER_MATCHER(isPrivate);
241   REGISTER_MATCHER(isProtected);
242   REGISTER_MATCHER(isPublic);
243   REGISTER_MATCHER(isTemplateInstantiation);
244   REGISTER_MATCHER(isVirtual);
245   REGISTER_MATCHER(isWritten);
246   REGISTER_MATCHER(lValueReferenceType);
247   REGISTER_MATCHER(labelStmt);
248   REGISTER_MATCHER(lambdaExpr);
249   REGISTER_MATCHER(matchesName);
250   REGISTER_MATCHER(materializeTemporaryExpr);
251   REGISTER_MATCHER(member);
252   REGISTER_MATCHER(memberCallExpr);
253   REGISTER_MATCHER(memberExpr);
254   REGISTER_MATCHER(memberPointerType);
255   REGISTER_MATCHER(methodDecl);
256   REGISTER_MATCHER(namedDecl);
257   REGISTER_MATCHER(namesType);
258   REGISTER_MATCHER(namespaceDecl);
259   REGISTER_MATCHER(nestedNameSpecifier);
260   REGISTER_MATCHER(nestedNameSpecifierLoc);
261   REGISTER_MATCHER(newExpr);
262   REGISTER_MATCHER(nullPtrLiteralExpr);
263   REGISTER_MATCHER(nullStmt);
264   REGISTER_MATCHER(ofClass);
265   REGISTER_MATCHER(on);
266   REGISTER_MATCHER(onImplicitObjectArgument);
267   REGISTER_MATCHER(operatorCallExpr);
268   REGISTER_MATCHER(parameterCountIs);
269   REGISTER_MATCHER(parenType);
270   REGISTER_MATCHER(parmVarDecl);
271   REGISTER_MATCHER(pointee);
272   REGISTER_MATCHER(pointerType);
273   REGISTER_MATCHER(qualType);
274   REGISTER_MATCHER(rValueReferenceType);
275   REGISTER_MATCHER(recordDecl);
276   REGISTER_MATCHER(recordType);
277   REGISTER_MATCHER(referenceType);
278   REGISTER_MATCHER(refersToDeclaration);
279   REGISTER_MATCHER(refersToType);
280   REGISTER_MATCHER(reinterpretCastExpr);
281   REGISTER_MATCHER(returnStmt);
282   REGISTER_MATCHER(returns);
283   REGISTER_MATCHER(sizeOfExpr);
284   REGISTER_MATCHER(specifiesNamespace);
285   REGISTER_MATCHER(specifiesType);
286   REGISTER_MATCHER(specifiesTypeLoc);
287   REGISTER_MATCHER(statementCountIs);
288   REGISTER_MATCHER(staticCastExpr);
289   REGISTER_MATCHER(stmt);
290   REGISTER_MATCHER(stringLiteral);
291   REGISTER_MATCHER(switchCase);
292   REGISTER_MATCHER(switchStmt);
293   REGISTER_MATCHER(templateSpecializationType);
294   REGISTER_MATCHER(temporaryObjectExpr);
295   REGISTER_MATCHER(thisExpr);
296   REGISTER_MATCHER(throughUsingDecl);
297   REGISTER_MATCHER(throwExpr);
298   REGISTER_MATCHER(to);
299   REGISTER_MATCHER(tryStmt);
300   REGISTER_MATCHER(type);
301   REGISTER_MATCHER(typeLoc);
302   REGISTER_MATCHER(typedefType);
303   REGISTER_MATCHER(unaryExprOrTypeTraitExpr);
304   REGISTER_MATCHER(unaryOperator);
305   REGISTER_MATCHER(unaryTransformType);
306   REGISTER_MATCHER(unless);
307   REGISTER_MATCHER(unresolvedConstructExpr);
308   REGISTER_MATCHER(unresolvedUsingValueDecl);
309   REGISTER_MATCHER(userDefinedLiteral);
310   REGISTER_MATCHER(usingDecl);
311   REGISTER_MATCHER(varDecl);
312   REGISTER_MATCHER(variableArrayType);
313   REGISTER_MATCHER(whileStmt);
314   REGISTER_MATCHER(withInitializer);
315 }
316 
~RegistryMaps()317 RegistryMaps::~RegistryMaps() {
318   for (ConstructorMap::iterator it = Constructors.begin(),
319                                 end = Constructors.end();
320        it != end; ++it) {
321     delete it->second;
322   }
323 }
324 
325 static llvm::ManagedStatic<RegistryMaps> RegistryData;
326 
327 } // anonymous namespace
328 
329 // static
lookupMatcherCtor(StringRef MatcherName)330 llvm::Optional<MatcherCtor> Registry::lookupMatcherCtor(StringRef MatcherName) {
331   ConstructorMap::const_iterator it =
332       RegistryData->constructors().find(MatcherName);
333   return it == RegistryData->constructors().end()
334              ? llvm::Optional<MatcherCtor>()
335              : it->second;
336 }
337 
338 namespace {
339 
operator <<(llvm::raw_ostream & OS,const std::set<ASTNodeKind> & KS)340 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
341                               const std::set<ASTNodeKind> &KS) {
342   unsigned Count = 0;
343   for (std::set<ASTNodeKind>::const_iterator I = KS.begin(), E = KS.end();
344        I != E; ++I) {
345     if (I != KS.begin())
346       OS << "|";
347     if (Count++ == 3) {
348       OS << "...";
349       break;
350     }
351     OS << *I;
352   }
353   return OS;
354 }
355 
356 struct ReverseSpecificityThenName {
operator ()clang::ast_matchers::dynamic::__anon4f7dd02e0211::ReverseSpecificityThenName357   bool operator()(const std::pair<unsigned, std::string> &A,
358                   const std::pair<unsigned, std::string> &B) const {
359     return A.first > B.first || (A.first == B.first && A.second < B.second);
360   }
361 };
362 
363 }
364 
getCompletions(ArrayRef<std::pair<MatcherCtor,unsigned>> Context)365 std::vector<MatcherCompletion> Registry::getCompletions(
366     ArrayRef<std::pair<MatcherCtor, unsigned> > Context) {
367   ASTNodeKind InitialTypes[] = {
368     ASTNodeKind::getFromNodeKind<Decl>(),
369     ASTNodeKind::getFromNodeKind<QualType>(),
370     ASTNodeKind::getFromNodeKind<Type>(),
371     ASTNodeKind::getFromNodeKind<Stmt>(),
372     ASTNodeKind::getFromNodeKind<NestedNameSpecifier>(),
373     ASTNodeKind::getFromNodeKind<NestedNameSpecifierLoc>(),
374     ASTNodeKind::getFromNodeKind<TypeLoc>()
375   };
376   ArrayRef<ASTNodeKind> InitialTypesRef(InitialTypes);
377 
378   // Starting with the above seed of acceptable top-level matcher types, compute
379   // the acceptable type set for the argument indicated by each context element.
380   std::set<ASTNodeKind> TypeSet(InitialTypesRef.begin(), InitialTypesRef.end());
381   for (ArrayRef<std::pair<MatcherCtor, unsigned> >::iterator
382            CtxI = Context.begin(),
383            CtxE = Context.end();
384        CtxI != CtxE; ++CtxI) {
385     std::vector<internal::ArgKind> NextTypeSet;
386     for (std::set<ASTNodeKind>::iterator I = TypeSet.begin(), E = TypeSet.end();
387          I != E; ++I) {
388       if (CtxI->first->isConvertibleTo(*I) &&
389           (CtxI->first->isVariadic() ||
390            CtxI->second < CtxI->first->getNumArgs()))
391         CtxI->first->getArgKinds(*I, CtxI->second, NextTypeSet);
392     }
393     TypeSet.clear();
394     for (std::vector<internal::ArgKind>::iterator I = NextTypeSet.begin(),
395                                                   E = NextTypeSet.end();
396          I != E; ++I) {
397       if (I->getArgKind() == internal::ArgKind::AK_Matcher)
398         TypeSet.insert(I->getMatcherKind());
399     }
400   }
401 
402   typedef std::map<std::pair<unsigned, std::string>, MatcherCompletion,
403                    ReverseSpecificityThenName> CompletionsTy;
404   CompletionsTy Completions;
405 
406   // TypeSet now contains the list of acceptable types for the argument we are
407   // completing.  Search the registry for acceptable matchers.
408   for (ConstructorMap::const_iterator I = RegistryData->constructors().begin(),
409                                       E = RegistryData->constructors().end();
410        I != E; ++I) {
411     std::set<ASTNodeKind> RetKinds;
412     unsigned NumArgs = I->second->isVariadic() ? 1 : I->second->getNumArgs();
413     bool IsPolymorphic = I->second->isPolymorphic();
414     std::vector<std::vector<internal::ArgKind> > ArgsKinds(NumArgs);
415     unsigned MaxSpecificity = 0;
416     for (std::set<ASTNodeKind>::iterator TI = TypeSet.begin(),
417                                          TE = TypeSet.end();
418          TI != TE; ++TI) {
419       unsigned Specificity;
420       ASTNodeKind LeastDerivedKind;
421       if (I->second->isConvertibleTo(*TI, &Specificity, &LeastDerivedKind)) {
422         if (MaxSpecificity < Specificity)
423           MaxSpecificity = Specificity;
424         RetKinds.insert(LeastDerivedKind);
425         for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
426           I->second->getArgKinds(*TI, Arg, ArgsKinds[Arg]);
427         if (IsPolymorphic)
428           break;
429       }
430     }
431 
432     if (!RetKinds.empty() && MaxSpecificity > 0) {
433       std::string Decl;
434       llvm::raw_string_ostream OS(Decl);
435 
436       if (IsPolymorphic) {
437         OS << "Matcher<T> " << I->first() << "(Matcher<T>";
438       } else {
439         OS << "Matcher<" << RetKinds << "> " << I->first() << "(";
440         for (std::vector<std::vector<internal::ArgKind> >::iterator
441                  KI = ArgsKinds.begin(),
442                  KE = ArgsKinds.end();
443              KI != KE; ++KI) {
444           if (KI != ArgsKinds.begin())
445             OS << ", ";
446           // This currently assumes that a matcher may not overload a
447           // non-matcher, and all non-matcher overloads have identical
448           // arguments.
449           if ((*KI)[0].getArgKind() == internal::ArgKind::AK_Matcher) {
450             std::set<ASTNodeKind> MatcherKinds;
451             std::transform(
452                 KI->begin(), KI->end(),
453                 std::inserter(MatcherKinds, MatcherKinds.end()),
454                 std::mem_fun_ref(&internal::ArgKind::getMatcherKind));
455             OS << "Matcher<" << MatcherKinds << ">";
456           } else {
457             OS << (*KI)[0].asString();
458           }
459         }
460       }
461       if (I->second->isVariadic())
462         OS << "...";
463       OS << ")";
464 
465       std::string TypedText = I->first();
466       TypedText += "(";
467       if (ArgsKinds.empty())
468         TypedText += ")";
469       else if (ArgsKinds[0][0].getArgKind() == internal::ArgKind::AK_String)
470         TypedText += "\"";
471 
472       Completions[std::make_pair(MaxSpecificity, I->first())] =
473           MatcherCompletion(TypedText, OS.str());
474     }
475   }
476 
477   std::vector<MatcherCompletion> RetVal;
478   for (CompletionsTy::iterator I = Completions.begin(), E = Completions.end();
479        I != E; ++I)
480     RetVal.push_back(I->second);
481   return RetVal;
482 }
483 
484 // static
constructMatcher(MatcherCtor Ctor,const SourceRange & NameRange,ArrayRef<ParserValue> Args,Diagnostics * Error)485 VariantMatcher Registry::constructMatcher(MatcherCtor Ctor,
486                                           const SourceRange &NameRange,
487                                           ArrayRef<ParserValue> Args,
488                                           Diagnostics *Error) {
489   return Ctor->create(NameRange, Args, Error);
490 }
491 
492 // static
constructBoundMatcher(MatcherCtor Ctor,const SourceRange & NameRange,StringRef BindID,ArrayRef<ParserValue> Args,Diagnostics * Error)493 VariantMatcher Registry::constructBoundMatcher(MatcherCtor Ctor,
494                                                const SourceRange &NameRange,
495                                                StringRef BindID,
496                                                ArrayRef<ParserValue> Args,
497                                                Diagnostics *Error) {
498   VariantMatcher Out = constructMatcher(Ctor, NameRange, Args, Error);
499   if (Out.isNull()) return Out;
500 
501   llvm::Optional<DynTypedMatcher> Result = Out.getSingleMatcher();
502   if (Result.hasValue()) {
503     llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID);
504     if (Bound.hasValue()) {
505       return VariantMatcher::SingleMatcher(*Bound);
506     }
507   }
508   Error->addError(NameRange, Error->ET_RegistryNotBindable);
509   return VariantMatcher();
510 }
511 
512 }  // namespace dynamic
513 }  // namespace ast_matchers
514 }  // namespace clang
515