11#include "clang/AST/CXXInheritance.h"
12#include "clang/AST/RecursiveASTVisitor.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include "clang/Basic/CharInfo.h"
15#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Lex/PPCallbacks.h"
17#include "clang/Lex/Preprocessor.h"
18#include "llvm/ADT/DenseMapInfo.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/ScopeExit.h"
23#define DEBUG_TYPE "clang-tidy"
35 return DenseMapInfo<clang::SourceLocation>::getHashValue(Val.first) +
36 DenseMapInfo<StringRef>::getHashValue(Val.second);
51 llvm::PointerIntPair<const NamedDecl *, 1, bool> Data;
54 explicit NameLookup(
const NamedDecl *ND) : Data(ND, false) {}
55 explicit NameLookup(std::nullopt_t) : Data(nullptr, true) {}
56 explicit NameLookup(std::nullptr_t) : Data(nullptr, false) {}
57 NameLookup() : NameLookup(nullptr) {}
59 bool hasMultipleResolutions()
const {
return Data.getInt(); }
60 const NamedDecl *getDecl()
const {
61 assert(!hasMultipleResolutions() &&
"Found multiple decls");
62 return Data.getPointer();
64 operator bool()
const {
return !hasMultipleResolutions(); }
65 const NamedDecl *operator*()
const {
return getDecl(); }
70static const NamedDecl *
findDecl(
const RecordDecl &RecDecl,
72 for (
const Decl *D : RecDecl.decls()) {
73 if (
const auto *ND = dyn_cast<NamedDecl>(D)) {
74 if (ND->getDeclName().isIdentifier() && ND->getName() == DeclName)
85 if (Method->size_overridden_methods() != 1)
89 Method = *Method->begin_overridden_methods();
90 assert(Method &&
"Overridden method shouldn't be null");
91 const unsigned NumOverrides = Method->size_overridden_methods();
92 if (NumOverrides == 0)
100 return !Decl->getIdentifier() || Decl->getName().empty();
104 const auto *Canonical = cast<NamedDecl>(ND->getCanonicalDecl());
108 if (
const auto *Method = dyn_cast<CXXMethodDecl>(ND)) {
110 Canonical = cast<NamedDecl>(Overridden->getCanonicalDecl());
111 else if (
const FunctionTemplateDecl *Primary = Method->getPrimaryTemplate())
112 if (
const FunctionDecl *TemplatedDecl = Primary->getTemplatedDecl())
113 Canonical = cast<NamedDecl>(TemplatedDecl->getCanonicalDecl());
131 bool AggressiveTemplateLookup,
133 if (!Parent.hasDefinition())
134 return NameLookup(
nullptr);
136 const auto *Definition = Parent.getDefinition();
137 if (!Visited.insert(Definition).second)
138 return NameLookup(
nullptr);
139 auto RemoveFromVisited =
140 llvm::scope_exit([&Visited, Definition] { Visited.erase(Definition); });
142 if (
const NamedDecl *InClassRef =
findDecl(Parent, DeclName))
143 return NameLookup(InClassRef);
144 const NamedDecl *Found =
nullptr;
146 for (
const CXXBaseSpecifier Base : Parent.bases()) {
147 const auto *Record = Base.getType()->getAsCXXRecordDecl();
148 if (!Record && AggressiveTemplateLookup) {
149 if (
const auto *TST =
150 Base.getType()->getAs<TemplateSpecializationType>()) {
151 if (
const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(
152 TST->getTemplateName().getAsTemplateDecl()))
153 Record = TD->getTemplatedDecl();
159 AggressiveTemplateLookup, Visited)) {
168 return NameLookup(std::nullopt);
171 return NameLookup(Found);
177class RenamerClangTidyCheckPPCallbacks :
public PPCallbacks {
179 RenamerClangTidyCheckPPCallbacks(
const SourceManager &SM,
180 RenamerClangTidyCheck *Check)
181 : SM(SM), Check(Check) {}
184 void MacroDefined(
const Token &MacroNameTok,
185 const MacroDirective *
MD)
override {
186 const MacroInfo *Info =
MD->getMacroInfo();
187 if (Info->isBuiltinMacro())
189 if (SM.isWrittenInBuiltinFile(MacroNameTok.getLocation()))
191 if (SM.isWrittenInCommandLineFile(MacroNameTok.getLocation()))
193 if (SM.isInSystemHeader(MacroNameTok.getLocation()))
195 Check->checkMacro(MacroNameTok, Info, SM);
199 void MacroExpands(
const Token &MacroNameTok,
const MacroDefinition &
MD,
201 const MacroArgs * )
override {
202 Check->expandMacro(MacroNameTok,
MD.getMacroInfo(), SM);
206 const SourceManager &SM;
207 RenamerClangTidyCheck *Check;
210class RenamerClangTidyVisitor
211 :
public RecursiveASTVisitor<RenamerClangTidyVisitor> {
213 RenamerClangTidyVisitor(RenamerClangTidyCheck *Check,
const SourceManager &SM,
214 bool AggressiveDependentMemberLookup)
215 : Check(Check), SM(SM),
216 AggressiveDependentMemberLookup(AggressiveDependentMemberLookup) {}
218 bool shouldVisitTemplateInstantiations()
const {
return true; }
220 bool shouldVisitImplicitCode()
const {
return false; }
222 bool VisitCXXConstructorDecl(CXXConstructorDecl *Decl) {
223 if (Decl->isImplicit())
225 Check->addUsage(Decl->getParent(), Decl->getNameInfo().getSourceRange(),
228 for (
const auto *Init : Decl->inits()) {
229 if (!Init->isWritten() || Init->isInClassMemberInitializer())
231 if (
const FieldDecl *FD = Init->getAnyMember())
232 Check->addUsage(FD, SourceRange(Init->getMemberLocation()), SM);
240 bool VisitCXXDestructorDecl(CXXDestructorDecl *Decl) {
241 if (Decl->isImplicit())
243 SourceRange Range = Decl->getNameInfo().getSourceRange();
244 if (Range.getBegin().isInvalid())
249 Range.setBegin(CharSourceRange::getTokenRange(Range).getEnd());
250 Check->addUsage(Decl->getParent(), Range, SM);
254 bool VisitUsingDecl(UsingDecl *Decl) {
255 for (
const auto *Shadow : Decl->shadows())
256 Check->addUsage(Shadow->getTargetDecl(),
257 Decl->getNameInfo().getSourceRange(), SM);
261 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *Decl) {
262 Check->addUsage(Decl->getNominatedNamespaceAsWritten(),
263 Decl->getIdentLocation(), SM);
267 bool VisitNamedDecl(NamedDecl *Decl) {
268 const SourceRange UsageRange =
269 DeclarationNameInfo(Decl->getDeclName(), Decl->getLocation())
271 Check->addUsage(Decl, UsageRange, SM);
275 bool VisitDeclRefExpr(DeclRefExpr *DeclRef) {
276 const SourceRange Range = DeclRef->getNameInfo().getSourceRange();
277 Check->addUsage(DeclRef->getDecl(), Range, SM);
281 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc Loc) {
282 if (
const NestedNameSpecifier Spec = Loc.getNestedNameSpecifier();
283 Spec.getKind() == NestedNameSpecifier::Kind::Namespace) {
284 if (
const auto *Decl =
285 dyn_cast<NamespaceDecl>(Spec.getAsNamespaceAndPrefix().Namespace))
286 Check->addUsage(Decl, Loc.getLocalSourceRange(), SM);
289 using Base = RecursiveASTVisitor<RenamerClangTidyVisitor>;
290 return Base::TraverseNestedNameSpecifierLoc(Loc);
293 bool VisitMemberExpr(MemberExpr *MemberRef) {
294 const SourceRange Range = MemberRef->getMemberNameInfo().getSourceRange();
295 Check->addUsage(MemberRef->getMemberDecl(), Range, SM);
300 VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *DepMemberRef) {
301 const QualType BaseType =
302 DepMemberRef->isArrow() ? DepMemberRef->getBaseType()->getPointeeType()
303 : DepMemberRef->getBaseType();
304 if (BaseType.isNull())
306 const CXXRecordDecl *Base = BaseType.getTypePtr()->getAsCXXRecordDecl();
309 const DeclarationName DeclName =
310 DepMemberRef->getMemberNameInfo().getName();
311 if (!DeclName.isIdentifier())
313 const StringRef
DependentName = DeclName.getAsIdentifierInfo()->getName();
317 *Base, DependentName, AggressiveDependentMemberLookup, Visited)) {
319 Check->addUsage(*Resolved,
320 DepMemberRef->getMemberNameInfo().getSourceRange(), SM);
326 bool VisitTypedefTypeLoc(
const TypedefTypeLoc &Loc) {
327 Check->addUsage(Loc.getDecl(), Loc.getNameLoc(), SM);
331 bool VisitTagTypeLoc(
const TagTypeLoc &Loc) {
332 Check->addUsage(Loc.getDecl(), Loc.getNameLoc(), SM);
336 bool VisitUnresolvedUsingTypeLoc(
const UnresolvedUsingTypeLoc &Loc) {
337 Check->addUsage(Loc.getDecl(), Loc.getNameLoc(), SM);
341 bool VisitTemplateTypeParmTypeLoc(
const TemplateTypeParmTypeLoc &Loc) {
342 Check->addUsage(Loc.getDecl(), Loc.getNameLoc(), SM);
347 VisitTemplateSpecializationTypeLoc(
const TemplateSpecializationTypeLoc &Loc) {
348 const TemplateDecl *Decl =
349 Loc.getTypePtr()->getTemplateName().getAsTemplateDecl(
354 if (
const auto *ClassDecl = dyn_cast<TemplateDecl>(Decl))
355 if (
const NamedDecl *TemplDecl = ClassDecl->getTemplatedDecl())
356 Check->addUsage(TemplDecl, Loc.getTemplateNameLoc(), SM);
361 bool VisitDesignatedInitExpr(DesignatedInitExpr *Expr) {
362 for (
const DesignatedInitExpr::Designator &D : Expr->designators()) {
363 if (!
D.isFieldDesignator())
365 const FieldDecl *FD =
D.getFieldDecl();
368 const IdentifierInfo *II = FD->getIdentifier();
371 const SourceRange FixLocation{
D.getFieldLoc(),
D.getFieldLoc()};
372 Check->addUsage(FD, FixLocation, SM);
379 RenamerClangTidyCheck *Check;
380 const SourceManager &SM;
381 const bool AggressiveDependentMemberLookup;
389 AggressiveDependentMemberLookup(
390 Options.get(
"AggressiveDependentMemberLookup", false)) {}
394 Options.store(Opts,
"AggressiveDependentMemberLookup",
395 AggressiveDependentMemberLookup);
399 Finder->addMatcher(translationUnitDecl(),
this);
403 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
404 ModuleExpanderPP->addPPCallbacks(
405 std::make_unique<RenamerClangTidyCheckPPCallbacks>(SM,
this));
408std::pair<RenamerClangTidyCheck::NamingCheckFailureMap::iterator, bool>
411 SourceRange UsageRange,
const SourceManager &SourceMgr) {
413 if (UsageRange.isInvalid())
414 return {NamingCheckFailures.end(),
false};
419 SourceLocation FixLocation = UsageRange.getBegin();
420 FixLocation = SourceMgr.getSpellingLoc(FixLocation);
421 if (FixLocation.isInvalid())
422 return {NamingCheckFailures.end(),
false};
425 if (SourceMgr.isInSystemHeader(FixLocation))
426 return {NamingCheckFailures.end(),
false};
428 auto EmplaceResult = NamingCheckFailures.try_emplace(FailureId);
433 if (!Failure.RawUsageLocs.insert(FixLocation).second)
434 return EmplaceResult;
437 return EmplaceResult;
439 if (SourceMgr.isWrittenInScratchSpace(FixLocation))
445 return EmplaceResult;
449 SourceRange UsageRange,
450 const SourceManager &SourceMgr) {
451 if (SourceMgr.isInSystemHeader(Decl->getLocation()))
459 if (isa<ClassTemplateSpecializationDecl>(Decl))
469 std::optional<FailureInfo> MaybeFailure =
475 FailureDecl->getName());
477 auto [FailureIter, NewFailure] =
addUsage(FailureId, UsageRange, SourceMgr);
479 if (FailureIter == NamingCheckFailures.end()) {
490 Failure.Info = std::move(*MaybeFailure);
493 if (!Failure.shouldFix())
495 const IdentifierTable &Idents = FailureDecl->getASTContext().Idents;
496 auto CheckNewIdentifier = Idents.find(Failure.Info.Fixup);
497 if (CheckNewIdentifier != Idents.end()) {
498 const IdentifierInfo *Ident = CheckNewIdentifier->second;
499 if (Ident->isKeyword(getLangOpts()))
501 else if (Ident->hasMacroDefinition())
503 }
else if (!isValidAsciiIdentifier(Failure.Info.Fixup)) {
509 if (!Result.SourceManager) {
515 RenamerClangTidyVisitor Visitor(
this, *Result.SourceManager,
516 AggressiveDependentMemberLookup);
517 Visitor.TraverseAST(*Result.Context);
522 const SourceManager &SourceMgr) {
523 std::optional<FailureInfo> MaybeFailure =
528 const StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
531 const SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
533 if (!isValidAsciiIdentifier(Info.Fixup))
536 Failure.Info = std::move(Info);
542 const SourceManager &SourceMgr) {
543 const StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
546 auto Failure = NamingCheckFailures.find(ID);
547 if (Failure == NamingCheckFailures.end())
550 const SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());
556 const std::string &Fixup) {
559 return "; cannot be fixed automatically";
566 return "; cannot be fixed because '" + Fixup +
567 "' would conflict with a keyword";
570 return "; cannot be fixed because '" + Fixup +
571 "' would conflict with a macro definition";
572 llvm_unreachable(
"invalid ShouldFixStatus");
576 for (
const auto &Pair : NamingCheckFailures) {
580 if (Failure.Info.KindName.empty())
583 if (Failure.shouldNotify()) {
585 auto Diag = diag(Decl.first,
587 Failure.Info.Fixup));
590 if (Failure.shouldFix()) {
591 for (
const auto &Loc : Failure.RawUsageLocs) {
602 Diag << FixItHint::CreateReplacement(SourceRange(Loc),
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for MD output.")
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) final
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) final
std::pair< SourceLocation, StringRef > NamingCheckId
void onEndOfTranslationUnit() final
virtual DiagInfo getDiagInfo(const NamingCheckId &ID, const NamingCheckFailure &Failure) const =0
Overridden by derived classes, returns a description of the diagnostic that should be emitted for the...
void expandMacro(const Token &MacroNameTok, const MacroInfo *MI, const SourceManager &SourceMgr)
Add a usage of a macro if it already has a violation.
void registerMatchers(ast_matchers::MatchFinder *Finder) final
Derived classes should not implement any matching logic themselves; this class will do the matching a...
RenamerClangTidyCheck(StringRef CheckName, ClangTidyContext *Context)
ShouldFixStatus
This enum will be used in select of the diagnostic message.
@ IgnoreFailureThreshold
Values pass this threshold will be ignored completely i.e no message, no fixup.
@ ConflictsWithMacroDefinition
The fixup will conflict with a macro definition, so we can't fix it automatically.
@ ConflictsWithKeyword
The fixup will conflict with a language keyword, so we can't fix it automatically.
@ InsideMacro
If the identifier was used or declared within a macro we won't offer a fixup for safety reasons.
@ FixInvalidIdentifier
The fixup results in an identifier that is not a valid c/c++ identifier.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Derived classes that override this function should call this method from the overridden method.
virtual std::optional< FailureInfo > getMacroFailureInfo(const Token &MacroNameTok, const SourceManager &SM) const =0
Overridden by derived classes, returns information about if and how a macro failed the check.
void addUsage(const NamedDecl *Decl, SourceRange Range, const SourceManager &SourceMgr)
virtual std::optional< FailureInfo > getDeclFailureInfo(const NamedDecl *Decl, const SourceManager &SM) const =0
Overridden by derived classes, returns information about if and how a Decl failed the check.
void checkMacro(const Token &MacroNameTok, const MacroInfo *MI, const SourceManager &SourceMgr)
Check Macros for style violations.
~RenamerClangTidyCheck() override
bool rangeCanBeFixed(SourceRange Range, const SourceManager *SM)
static std::string getDiagnosticSuffix(const RenamerClangTidyCheck::ShouldFixStatus FixStatus, const std::string &Fixup)
llvm::SmallPtrSet< const CXXRecordDecl *, 4 > RecursionProtectionSet
static const CXXMethodDecl * getOverrideMethod(const CXXMethodDecl *Method)
Returns the function that Method is overriding.
static NameLookup findDeclInBases(const CXXRecordDecl &Parent, StringRef DeclName, bool AggressiveTemplateLookup, RecursionProtectionSet &Visited)
Returns a decl matching the DeclName in Parent or one of its base classes.
static const NamedDecl * getFailureForNamedDecl(const NamedDecl *ND)
static const NamedDecl * findDecl(const RecordDecl &RecDecl, StringRef DeclName)
static bool hasNoName(const NamedDecl *Decl)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Some operations such as code completion produce a set of candidates.
llvm::StringMap< ClangTidyValue > OptionMap
Represents customized diagnostic text and how arguments should be applied.
llvm::unique_function< void(DiagnosticBuilder &)> ApplyArgs
Information describing a failed check.
Holds an identifier name check failure, tracking the kind of the identifier, its possible fixup and t...
static bool isEqual(const NamingCheckId &LHS, const NamingCheckId &RHS)
static unsigned getHashValue(NamingCheckId Val)
clang::tidy::RenamerClangTidyCheck::NamingCheckId NamingCheckId