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
24using namespace clang::ast_type_traits;
25
26namespace clang {
27namespace ast_matchers {
28namespace dynamic {
29namespace {
30
31using internal::MatcherDescriptor;
32
33typedef llvm::StringMap<const MatcherDescriptor *> ConstructorMap;
34class RegistryMaps {
35public:
36  RegistryMaps();
37  ~RegistryMaps();
38
39  const ConstructorMap &constructors() const { return Constructors; }
40
41private:
42  void registerMatcher(StringRef MatcherName, MatcherDescriptor *Callback);
43  ConstructorMap Constructors;
44};
45
46void 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.
73RegistryMaps::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(asmStmt);
105  REGISTER_MATCHER(asString);
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(callExpr);
115  REGISTER_MATCHER(caseStmt);
116  REGISTER_MATCHER(castExpr);
117  REGISTER_MATCHER(catchStmt);
118  REGISTER_MATCHER(characterLiteral);
119  REGISTER_MATCHER(classTemplateDecl);
120  REGISTER_MATCHER(classTemplateSpecializationDecl);
121  REGISTER_MATCHER(complexType);
122  REGISTER_MATCHER(compoundLiteralExpr);
123  REGISTER_MATCHER(compoundStmt);
124  REGISTER_MATCHER(conditionalOperator);
125  REGISTER_MATCHER(constantArrayType);
126  REGISTER_MATCHER(constCastExpr);
127  REGISTER_MATCHER(constructExpr);
128  REGISTER_MATCHER(constructorDecl);
129  REGISTER_MATCHER(containsDeclaration);
130  REGISTER_MATCHER(continueStmt);
131  REGISTER_MATCHER(cStyleCastExpr);
132  REGISTER_MATCHER(ctorInitializer);
133  REGISTER_MATCHER(CUDAKernelCallExpr);
134  REGISTER_MATCHER(decl);
135  REGISTER_MATCHER(declaratorDecl);
136  REGISTER_MATCHER(declCountIs);
137  REGISTER_MATCHER(declRefExpr);
138  REGISTER_MATCHER(declStmt);
139  REGISTER_MATCHER(defaultArgExpr);
140  REGISTER_MATCHER(defaultStmt);
141  REGISTER_MATCHER(deleteExpr);
142  REGISTER_MATCHER(dependentSizedArrayType);
143  REGISTER_MATCHER(destructorDecl);
144  REGISTER_MATCHER(doStmt);
145  REGISTER_MATCHER(dynamicCastExpr);
146  REGISTER_MATCHER(eachOf);
147  REGISTER_MATCHER(elaboratedType);
148  REGISTER_MATCHER(enumConstantDecl);
149  REGISTER_MATCHER(enumDecl);
150  REGISTER_MATCHER(equalsBoundNode);
151  REGISTER_MATCHER(equalsIntegralValue);
152  REGISTER_MATCHER(explicitCastExpr);
153  REGISTER_MATCHER(expr);
154  REGISTER_MATCHER(exprWithCleanups);
155  REGISTER_MATCHER(fieldDecl);
156  REGISTER_MATCHER(floatLiteral);
157  REGISTER_MATCHER(forEach);
158  REGISTER_MATCHER(forEachConstructorInitializer);
159  REGISTER_MATCHER(forEachDescendant);
160  REGISTER_MATCHER(forEachSwitchCase);
161  REGISTER_MATCHER(forField);
162  REGISTER_MATCHER(forRangeStmt);
163  REGISTER_MATCHER(forStmt);
164  REGISTER_MATCHER(friendDecl);
165  REGISTER_MATCHER(functionalCastExpr);
166  REGISTER_MATCHER(functionDecl);
167  REGISTER_MATCHER(functionTemplateDecl);
168  REGISTER_MATCHER(functionType);
169  REGISTER_MATCHER(gotoStmt);
170  REGISTER_MATCHER(has);
171  REGISTER_MATCHER(hasAncestor);
172  REGISTER_MATCHER(hasAnyArgument);
173  REGISTER_MATCHER(hasAnyConstructorInitializer);
174  REGISTER_MATCHER(hasAnyParameter);
175  REGISTER_MATCHER(hasAnySubstatement);
176  REGISTER_MATCHER(hasAnyTemplateArgument);
177  REGISTER_MATCHER(hasAnyUsingShadowDecl);
178  REGISTER_MATCHER(hasArgument);
179  REGISTER_MATCHER(hasArgumentOfType);
180  REGISTER_MATCHER(hasAttr);
181  REGISTER_MATCHER(hasBase);
182  REGISTER_MATCHER(hasBody);
183  REGISTER_MATCHER(hasCanonicalType);
184  REGISTER_MATCHER(hasCaseConstant);
185  REGISTER_MATCHER(hasCondition);
186  REGISTER_MATCHER(hasConditionVariableStatement);
187  REGISTER_MATCHER(hasDeclaration);
188  REGISTER_MATCHER(hasDeclContext);
189  REGISTER_MATCHER(hasDeducedType);
190  REGISTER_MATCHER(hasDescendant);
191  REGISTER_MATCHER(hasDestinationType);
192  REGISTER_MATCHER(hasEitherOperand);
193  REGISTER_MATCHER(hasElementType);
194  REGISTER_MATCHER(hasElse);
195  REGISTER_MATCHER(hasFalseExpression);
196  REGISTER_MATCHER(hasGlobalStorage);
197  REGISTER_MATCHER(hasImplicitDestinationType);
198  REGISTER_MATCHER(hasIncrement);
199  REGISTER_MATCHER(hasIndex);
200  REGISTER_MATCHER(hasInitializer);
201  REGISTER_MATCHER(hasKeywordSelector);
202  REGISTER_MATCHER(hasLHS);
203  REGISTER_MATCHER(hasLocalQualifiers);
204  REGISTER_MATCHER(hasLocalStorage);
205  REGISTER_MATCHER(hasLoopInit);
206  REGISTER_MATCHER(hasLoopVariable);
207  REGISTER_MATCHER(hasMethod);
208  REGISTER_MATCHER(hasName);
209  REGISTER_MATCHER(hasNullSelector);
210  REGISTER_MATCHER(hasObjectExpression);
211  REGISTER_MATCHER(hasOperatorName);
212  REGISTER_MATCHER(hasOverloadedOperatorName);
213  REGISTER_MATCHER(hasParameter);
214  REGISTER_MATCHER(hasParent);
215  REGISTER_MATCHER(hasQualifier);
216  REGISTER_MATCHER(hasRangeInit);
217  REGISTER_MATCHER(hasReceiverType);
218  REGISTER_MATCHER(hasRHS);
219  REGISTER_MATCHER(hasSelector);
220  REGISTER_MATCHER(hasSingleDecl);
221  REGISTER_MATCHER(hasSize);
222  REGISTER_MATCHER(hasSizeExpr);
223  REGISTER_MATCHER(hasSourceExpression);
224  REGISTER_MATCHER(hasTargetDecl);
225  REGISTER_MATCHER(hasTemplateArgument);
226  REGISTER_MATCHER(hasThen);
227  REGISTER_MATCHER(hasTrueExpression);
228  REGISTER_MATCHER(hasTypeLoc);
229  REGISTER_MATCHER(hasUnaryOperand);
230  REGISTER_MATCHER(hasUnarySelector);
231  REGISTER_MATCHER(hasValueType);
232  REGISTER_MATCHER(ifStmt);
233  REGISTER_MATCHER(ignoringImpCasts);
234  REGISTER_MATCHER(ignoringParenCasts);
235  REGISTER_MATCHER(ignoringParenImpCasts);
236  REGISTER_MATCHER(implicitCastExpr);
237  REGISTER_MATCHER(incompleteArrayType);
238  REGISTER_MATCHER(initListExpr);
239  REGISTER_MATCHER(innerType);
240  REGISTER_MATCHER(integerLiteral);
241  REGISTER_MATCHER(isArrow);
242  REGISTER_MATCHER(isConst);
243  REGISTER_MATCHER(isConstQualified);
244  REGISTER_MATCHER(isDefinition);
245  REGISTER_MATCHER(isDeleted);
246  REGISTER_MATCHER(isExplicitTemplateSpecialization);
247  REGISTER_MATCHER(isExpr);
248  REGISTER_MATCHER(isExternC);
249  REGISTER_MATCHER(isImplicit);
250  REGISTER_MATCHER(isExpansionInFileMatching);
251  REGISTER_MATCHER(isExpansionInMainFile);
252  REGISTER_MATCHER(isInstantiated);
253  REGISTER_MATCHER(isExpansionInSystemHeader);
254  REGISTER_MATCHER(isInteger);
255  REGISTER_MATCHER(isIntegral);
256  REGISTER_MATCHER(isInTemplateInstantiation);
257  REGISTER_MATCHER(isListInitialization);
258  REGISTER_MATCHER(isOverride);
259  REGISTER_MATCHER(isPrivate);
260  REGISTER_MATCHER(isProtected);
261  REGISTER_MATCHER(isPublic);
262  REGISTER_MATCHER(isPure);
263  REGISTER_MATCHER(isTemplateInstantiation);
264  REGISTER_MATCHER(isVirtual);
265  REGISTER_MATCHER(isWritten);
266  REGISTER_MATCHER(labelStmt);
267  REGISTER_MATCHER(lambdaExpr);
268  REGISTER_MATCHER(lValueReferenceType);
269  REGISTER_MATCHER(matchesName);
270  REGISTER_MATCHER(matchesSelector);
271  REGISTER_MATCHER(materializeTemporaryExpr);
272  REGISTER_MATCHER(member);
273  REGISTER_MATCHER(memberCallExpr);
274  REGISTER_MATCHER(memberExpr);
275  REGISTER_MATCHER(memberPointerType);
276  REGISTER_MATCHER(methodDecl);
277  REGISTER_MATCHER(namedDecl);
278  REGISTER_MATCHER(namespaceDecl);
279  REGISTER_MATCHER(namesType);
280  REGISTER_MATCHER(nestedNameSpecifier);
281  REGISTER_MATCHER(nestedNameSpecifierLoc);
282  REGISTER_MATCHER(newExpr);
283  REGISTER_MATCHER(nullPtrLiteralExpr);
284  REGISTER_MATCHER(nullStmt);
285  REGISTER_MATCHER(numSelectorArgs);
286  REGISTER_MATCHER(ofClass);
287  REGISTER_MATCHER(objcMessageExpr);
288  REGISTER_MATCHER(on);
289  REGISTER_MATCHER(onImplicitObjectArgument);
290  REGISTER_MATCHER(operatorCallExpr);
291  REGISTER_MATCHER(parameterCountIs);
292  REGISTER_MATCHER(parenType);
293  REGISTER_MATCHER(parmVarDecl);
294  REGISTER_MATCHER(pointee);
295  REGISTER_MATCHER(pointerType);
296  REGISTER_MATCHER(qualType);
297  REGISTER_MATCHER(recordDecl);
298  REGISTER_MATCHER(recordType);
299  REGISTER_MATCHER(referenceType);
300  REGISTER_MATCHER(refersToDeclaration);
301  REGISTER_MATCHER(refersToIntegralType);
302  REGISTER_MATCHER(refersToType);
303  REGISTER_MATCHER(reinterpretCastExpr);
304  REGISTER_MATCHER(returns);
305  REGISTER_MATCHER(returnStmt);
306  REGISTER_MATCHER(rValueReferenceType);
307  REGISTER_MATCHER(sizeOfExpr);
308  REGISTER_MATCHER(specifiesNamespace);
309  REGISTER_MATCHER(specifiesType);
310  REGISTER_MATCHER(specifiesTypeLoc);
311  REGISTER_MATCHER(statementCountIs);
312  REGISTER_MATCHER(staticCastExpr);
313  REGISTER_MATCHER(stmt);
314  REGISTER_MATCHER(stringLiteral);
315  REGISTER_MATCHER(substNonTypeTemplateParmExpr);
316  REGISTER_MATCHER(switchCase);
317  REGISTER_MATCHER(switchStmt);
318  REGISTER_MATCHER(templateArgument);
319  REGISTER_MATCHER(templateArgumentCountIs);
320  REGISTER_MATCHER(templateSpecializationType);
321  REGISTER_MATCHER(temporaryObjectExpr);
322  REGISTER_MATCHER(thisExpr);
323  REGISTER_MATCHER(throughUsingDecl);
324  REGISTER_MATCHER(throwExpr);
325  REGISTER_MATCHER(to);
326  REGISTER_MATCHER(translationUnitDecl);
327  REGISTER_MATCHER(tryStmt);
328  REGISTER_MATCHER(type);
329  REGISTER_MATCHER(typedefDecl);
330  REGISTER_MATCHER(typedefType);
331  REGISTER_MATCHER(typeLoc);
332  REGISTER_MATCHER(unaryExprOrTypeTraitExpr);
333  REGISTER_MATCHER(unaryOperator);
334  REGISTER_MATCHER(unaryTransformType);
335  REGISTER_MATCHER(unless);
336  REGISTER_MATCHER(unresolvedConstructExpr);
337  REGISTER_MATCHER(unresolvedUsingValueDecl);
338  REGISTER_MATCHER(userDefinedLiteral);
339  REGISTER_MATCHER(usingDecl);
340  REGISTER_MATCHER(usingDirectiveDecl);
341  REGISTER_MATCHER(valueDecl);
342  REGISTER_MATCHER(varDecl);
343  REGISTER_MATCHER(variableArrayType);
344  REGISTER_MATCHER(voidType);
345  REGISTER_MATCHER(whileStmt);
346  REGISTER_MATCHER(withInitializer);
347}
348
349RegistryMaps::~RegistryMaps() {
350  for (ConstructorMap::iterator it = Constructors.begin(),
351                                end = Constructors.end();
352       it != end; ++it) {
353    delete it->second;
354  }
355}
356
357static llvm::ManagedStatic<RegistryMaps> RegistryData;
358
359} // anonymous namespace
360
361// static
362llvm::Optional<MatcherCtor> Registry::lookupMatcherCtor(StringRef MatcherName) {
363  ConstructorMap::const_iterator it =
364      RegistryData->constructors().find(MatcherName);
365  return it == RegistryData->constructors().end()
366             ? llvm::Optional<MatcherCtor>()
367             : it->second;
368}
369
370namespace {
371
372llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
373                              const std::set<ASTNodeKind> &KS) {
374  unsigned Count = 0;
375  for (std::set<ASTNodeKind>::const_iterator I = KS.begin(), E = KS.end();
376       I != E; ++I) {
377    if (I != KS.begin())
378      OS << "|";
379    if (Count++ == 3) {
380      OS << "...";
381      break;
382    }
383    OS << *I;
384  }
385  return OS;
386}
387
388}  // namespace
389
390std::vector<ArgKind> Registry::getAcceptedCompletionTypes(
391    ArrayRef<std::pair<MatcherCtor, unsigned>> Context) {
392  ASTNodeKind InitialTypes[] = {
393      ASTNodeKind::getFromNodeKind<Decl>(),
394      ASTNodeKind::getFromNodeKind<QualType>(),
395      ASTNodeKind::getFromNodeKind<Type>(),
396      ASTNodeKind::getFromNodeKind<Stmt>(),
397      ASTNodeKind::getFromNodeKind<NestedNameSpecifier>(),
398      ASTNodeKind::getFromNodeKind<NestedNameSpecifierLoc>(),
399      ASTNodeKind::getFromNodeKind<TypeLoc>()};
400
401  // Starting with the above seed of acceptable top-level matcher types, compute
402  // the acceptable type set for the argument indicated by each context element.
403  std::set<ArgKind> TypeSet(std::begin(InitialTypes), std::end(InitialTypes));
404  for (const auto &CtxEntry : Context) {
405    MatcherCtor Ctor = CtxEntry.first;
406    unsigned ArgNumber = CtxEntry.second;
407    std::vector<ArgKind> NextTypeSet;
408    for (const ArgKind &Kind : TypeSet) {
409      if (Kind.getArgKind() == Kind.AK_Matcher &&
410          Ctor->isConvertibleTo(Kind.getMatcherKind()) &&
411          (Ctor->isVariadic() || ArgNumber < Ctor->getNumArgs()))
412        Ctor->getArgKinds(Kind.getMatcherKind(), ArgNumber, NextTypeSet);
413    }
414    TypeSet.clear();
415    TypeSet.insert(NextTypeSet.begin(), NextTypeSet.end());
416  }
417  return std::vector<ArgKind>(TypeSet.begin(), TypeSet.end());
418}
419
420std::vector<MatcherCompletion>
421Registry::getMatcherCompletions(ArrayRef<ArgKind> AcceptedTypes) {
422  std::vector<MatcherCompletion> Completions;
423
424  // Search the registry for acceptable matchers.
425  for (ConstructorMap::const_iterator I = RegistryData->constructors().begin(),
426                                      E = RegistryData->constructors().end();
427       I != E; ++I) {
428    std::set<ASTNodeKind> RetKinds;
429    unsigned NumArgs = I->second->isVariadic() ? 1 : I->second->getNumArgs();
430    bool IsPolymorphic = I->second->isPolymorphic();
431    std::vector<std::vector<ArgKind>> ArgsKinds(NumArgs);
432    unsigned MaxSpecificity = 0;
433    for (const ArgKind& Kind : AcceptedTypes) {
434      if (Kind.getArgKind() != Kind.AK_Matcher)
435        continue;
436      unsigned Specificity;
437      ASTNodeKind LeastDerivedKind;
438      if (I->second->isConvertibleTo(Kind.getMatcherKind(), &Specificity,
439                                     &LeastDerivedKind)) {
440        if (MaxSpecificity < Specificity)
441          MaxSpecificity = Specificity;
442        RetKinds.insert(LeastDerivedKind);
443        for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
444          I->second->getArgKinds(Kind.getMatcherKind(), Arg, ArgsKinds[Arg]);
445        if (IsPolymorphic)
446          break;
447      }
448    }
449
450    if (!RetKinds.empty() && MaxSpecificity > 0) {
451      std::string Decl;
452      llvm::raw_string_ostream OS(Decl);
453
454      if (IsPolymorphic) {
455        OS << "Matcher<T> " << I->first() << "(Matcher<T>";
456      } else {
457        OS << "Matcher<" << RetKinds << "> " << I->first() << "(";
458        for (const std::vector<ArgKind> &Arg : ArgsKinds) {
459          if (&Arg != &ArgsKinds[0])
460            OS << ", ";
461
462          bool FirstArgKind = true;
463          std::set<ASTNodeKind> MatcherKinds;
464          // Two steps. First all non-matchers, then matchers only.
465          for (const ArgKind &AK : Arg) {
466            if (AK.getArgKind() == ArgKind::AK_Matcher) {
467              MatcherKinds.insert(AK.getMatcherKind());
468            } else {
469              if (!FirstArgKind) OS << "|";
470              FirstArgKind = false;
471              OS << AK.asString();
472            }
473          }
474          if (!MatcherKinds.empty()) {
475            if (!FirstArgKind) OS << "|";
476            OS << "Matcher<" << MatcherKinds << ">";
477          }
478        }
479      }
480      if (I->second->isVariadic())
481        OS << "...";
482      OS << ")";
483
484      std::string TypedText = I->first();
485      TypedText += "(";
486      if (ArgsKinds.empty())
487        TypedText += ")";
488      else if (ArgsKinds[0][0].getArgKind() == ArgKind::AK_String)
489        TypedText += "\"";
490
491      Completions.emplace_back(TypedText, OS.str(), MaxSpecificity);
492    }
493  }
494
495  return Completions;
496}
497
498// static
499VariantMatcher Registry::constructMatcher(MatcherCtor Ctor,
500                                          const SourceRange &NameRange,
501                                          ArrayRef<ParserValue> Args,
502                                          Diagnostics *Error) {
503  return Ctor->create(NameRange, Args, Error);
504}
505
506// static
507VariantMatcher Registry::constructBoundMatcher(MatcherCtor Ctor,
508                                               const SourceRange &NameRange,
509                                               StringRef BindID,
510                                               ArrayRef<ParserValue> Args,
511                                               Diagnostics *Error) {
512  VariantMatcher Out = constructMatcher(Ctor, NameRange, Args, Error);
513  if (Out.isNull()) return Out;
514
515  llvm::Optional<DynTypedMatcher> Result = Out.getSingleMatcher();
516  if (Result.hasValue()) {
517    llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID);
518    if (Bound.hasValue()) {
519      return VariantMatcher::SingleMatcher(*Bound);
520    }
521  }
522  Error->addError(NameRange, Error->ET_RegistryNotBindable);
523  return VariantMatcher();
524}
525
526}  // namespace dynamic
527}  // namespace ast_matchers
528}  // namespace clang
529