10 #include "clang/AST/ASTContext.h" 11 #include "clang/ASTMatchers/ASTMatchFinder.h" 12 #include "clang/Lex/Lexer.h" 22 IgnoreDestructors(Options.get(
"IgnoreDestructors", false)),
23 OverrideSpelling(Options.get(
"OverrideSpelling",
"override")),
24 FinalSpelling(Options.get(
"FinalSpelling",
"final")) {}
27 Options.
store(Opts,
"IgnoreDestructors", IgnoreDestructors);
28 Options.
store(Opts,
"OverrideSpelling", OverrideSpelling);
37 if (IgnoreDestructors)
39 cxxMethodDecl(isOverride(), unless(cxxDestructorDecl())).bind(
"method"),
42 Finder->addMatcher(cxxMethodDecl(isOverride()).bind(
"method"),
this);
47 static SmallVector<Token, 16>
49 const SourceManager &Sources = *Result.SourceManager;
50 std::pair<FileID, unsigned> LocInfo =
51 Sources.getDecomposedLoc(Range.getBegin());
52 StringRef File = Sources.getBufferData(LocInfo.first);
53 const char *TokenBegin = File.data() + LocInfo.second;
54 Lexer RawLexer(Sources.getLocForStartOfFile(LocInfo.first),
55 Result.Context->getLangOpts(), File.begin(), TokenBegin,
57 SmallVector<Token, 16>
Tokens;
60 while (!RawLexer.LexFromRawLexer(Tok)) {
61 if ((Tok.is(tok::semi) || Tok.is(tok::l_brace)) && NestedParens == 0)
63 if (Sources.isBeforeInTranslationUnit(Range.getEnd(), Tok.getLocation()))
65 if (Tok.is(tok::l_paren))
67 else if (Tok.is(tok::r_paren))
69 if (Tok.is(tok::raw_identifier)) {
70 IdentifierInfo &
Info = Result.Context->Idents.get(StringRef(
71 Sources.getCharacterData(Tok.getLocation()), Tok.getLength()));
72 Tok.setIdentifierInfo(&Info);
73 Tok.setKind(Info.getTokenID());
75 Tokens.push_back(Tok);
80 static StringRef
GetText(
const Token &Tok,
const SourceManager &Sources) {
81 return StringRef(Sources.getCharacterData(Tok.getLocation()),
86 const auto *Method = Result.Nodes.getNodeAs<FunctionDecl>(
"method");
87 const SourceManager &Sources = *Result.SourceManager;
89 ASTContext &Context = *Result.Context;
91 assert(Method !=
nullptr);
92 if (Method->getInstantiatedFromMemberFunction() !=
nullptr)
93 Method = Method->getInstantiatedFromMemberFunction();
95 if (Method->isImplicit() || Method->getLocation().isMacroID() ||
96 Method->isOutOfLine())
99 bool HasVirtual = Method->isVirtualAsWritten();
100 bool HasOverride = Method->getAttr<OverrideAttr>();
101 bool HasFinal = Method->getAttr<FinalAttr>();
103 bool OnlyVirtualSpecified = HasVirtual && !HasOverride && !HasFinal;
104 unsigned KeywordCount = HasVirtual + HasOverride + HasFinal;
106 if (!OnlyVirtualSpecified && KeywordCount == 1)
110 if (OnlyVirtualSpecified) {
111 Message =
"prefer using '%0' or (rarely) '%1' instead of 'virtual'";
112 }
else if (KeywordCount == 0) {
113 Message =
"annotate this function with '%0' or (rarely) '%1'";
115 StringRef Redundant =
116 HasVirtual ? (HasOverride && HasFinal ?
"'virtual' and '%0' are" 119 StringRef Correct = HasFinal ?
"'%1'" :
"'%0'";
121 Message = (llvm::Twine(Redundant) +
122 " redundant since the function is already declared " + Correct)
127 << OverrideSpelling << FinalSpelling;
129 CharSourceRange FileRange = Lexer::makeFileCharRange(
133 if (!FileRange.isValid())
142 if (!HasFinal && !HasOverride) {
143 SourceLocation InsertLoc;
144 std::string ReplacementText = OverrideSpelling +
" ";
145 SourceLocation MethodLoc = Method->getLocation();
147 for (Token T : Tokens) {
148 if (T.is(tok::kw___attribute) &&
149 !Sources.isBeforeInTranslationUnit(T.getLocation(), MethodLoc)) {
150 InsertLoc = T.getLocation();
155 if (Method->hasAttrs()) {
156 for (
const clang::Attr *A : Method->getAttrs()) {
157 if (!A->isImplicit() && !A->isInherited()) {
159 Sources.getExpansionLoc(A->getRange().getBegin());
160 if ((!InsertLoc.isValid() ||
161 Sources.isBeforeInTranslationUnit(Loc, InsertLoc)) &&
162 !Sources.isBeforeInTranslationUnit(Loc, MethodLoc))
168 if (InsertLoc.isInvalid() && Method->doesThisDeclarationHaveABody() &&
169 Method->getBody() && !Method->isDefaulted()) {
174 ReplacementText =
" " + OverrideSpelling;
175 auto LastTokenIter = std::prev(Tokens.end());
178 if (LastTokenIter->is(tok::kw_try))
179 LastTokenIter = std::prev(LastTokenIter);
180 InsertLoc = LastTokenIter->getEndLoc();
183 if (!InsertLoc.isValid()) {
187 if (Tokens.size() > 2 &&
188 (
GetText(Tokens.back(), Sources) ==
"0" ||
189 Tokens.back().is(tok::kw_default) ||
190 Tokens.back().is(tok::kw_delete)) &&
191 GetText(Tokens[Tokens.size() - 2], Sources) ==
"=") {
192 InsertLoc = Tokens[Tokens.size() - 2].getLocation();
194 if ((Tokens[Tokens.size() - 2].getFlags() & Token::LeadingSpace) == 0)
195 ReplacementText =
" " + OverrideSpelling +
" ";
196 }
else if (
GetText(Tokens.back(), Sources) ==
"ABSTRACT")
197 InsertLoc = Tokens.back().getLocation();
200 if (!InsertLoc.isValid()) {
201 InsertLoc = FileRange.getEnd();
202 ReplacementText =
" " + OverrideSpelling;
207 if (OverrideSpelling !=
"override" &&
208 !Context.Idents.get(OverrideSpelling).hasMacroDefinition())
211 Diag << FixItHint::CreateInsertion(InsertLoc, ReplacementText);
214 if (HasFinal && HasOverride) {
215 SourceLocation OverrideLoc = Method->getAttr<OverrideAttr>()->getLocation();
216 Diag << FixItHint::CreateRemoval(
221 for (Token Tok : Tokens) {
222 if (Tok.is(tok::kw_virtual)) {
224 Tok.getLocation(), Tok.getLocation()));
SourceLocation Loc
'#' location in the include directive
constexpr llvm::StringLiteral Message
Base class for all clang-tidy checks.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
const LangOptions & getLangOpts() const
Returns the language options from the context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
static constexpr llvm::StringLiteral Name
std::map< std::string, std::string > OptionMap
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
static StringRef GetText(const Token &Tok, const SourceManager &Sources)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
CharSourceRange Range
SourceRange for the file name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
static SmallVector< Token, 16 > ParseTokens(CharSourceRange Range, const MatchFinder::MatchResult &Result)
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.