clang-tools 24.0.0git
ArgumentCommentCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Lex/Lexer.h"
13#include "clang/Lex/Token.h"
14
15#include "../utils/LexerUtils.h"
17
18using namespace clang::ast_matchers;
19
21
23namespace {
24AST_MATCHER(Decl, isFromStdNamespaceOrSystemHeader) {
25 if (const auto *D = Node.getDeclContext()->getEnclosingNamespaceContext();
26 D && D->isStdNamespace())
27 return true;
28 if (Node.getLocation().isInvalid())
29 return false;
30 return Node.getASTContext().getSourceManager().isInSystemHeader(
31 Node.getLocation());
32}
33} // namespace
34
36 ClangTidyContext *Context)
37 : ClangTidyCheck(Name, Context),
38 StrictMode(Options.get("StrictMode", false)),
39 IgnoreSingleArgument(Options.get("IgnoreSingleArgument", false)),
40 CommentAnonymousInitLists(
41 Options.get("CommentAnonymousInitLists", false)),
42 CommentBoolLiterals(Options.get("CommentBoolLiterals", false)),
43 CommentCharacterLiterals(Options.get("CommentCharacterLiterals", false)),
44 CommentFloatLiterals(Options.get("CommentFloatLiterals", false)),
45 CommentIntegerLiterals(Options.get("CommentIntegerLiterals", false)),
46 CommentNullPtrs(Options.get("CommentNullPtrs", false)),
47 CommentParenthesizedTemporaries(
48 Options.get("CommentParenthesizedTemporaries", false)),
49 CommentStringLiterals(Options.get("CommentStringLiterals", false)),
50 CommentTypedInitLists(Options.get("CommentTypedInitLists", false)),
51 CommentUserDefinedLiterals(
52 Options.get("CommentUserDefinedLiterals", false)),
53 IgnoredParameterNames(utils::options::parseStringList(
54 Options.get("IgnoredParameterNames", ""))),
55 IdentRE("^(/\\* *)([_A-Za-z][_A-Za-z0-9]*)( *= *\\*/)$") {
56 for (const StringRef Name : IgnoredParameterNames) {
57 llvm::Regex Regex(Name);
58 if (!Regex.isValid()) {
59 configurationDiag("Invalid regular expression '%0' in "
60 "IgnoredParameterNames")
61 << Name;
62 continue;
63 }
64 IgnoredParameterNameRegexes.push_back(std::move(Regex));
65 }
66}
67
69 Options.store(Opts, "StrictMode", StrictMode);
70 Options.store(Opts, "IgnoreSingleArgument", IgnoreSingleArgument);
71 Options.store(Opts, "CommentAnonymousInitLists", CommentAnonymousInitLists);
72 Options.store(Opts, "CommentBoolLiterals", CommentBoolLiterals);
73 Options.store(Opts, "CommentCharacterLiterals", CommentCharacterLiterals);
74 Options.store(Opts, "CommentFloatLiterals", CommentFloatLiterals);
75 Options.store(Opts, "CommentIntegerLiterals", CommentIntegerLiterals);
76 Options.store(Opts, "CommentNullPtrs", CommentNullPtrs);
77 Options.store(Opts, "CommentParenthesizedTemporaries",
78 CommentParenthesizedTemporaries);
79 Options.store(Opts, "CommentStringLiterals", CommentStringLiterals);
80 Options.store(Opts, "CommentTypedInitLists", CommentTypedInitLists);
81 Options.store(Opts, "CommentUserDefinedLiterals", CommentUserDefinedLiterals);
82 Options.store(Opts, "IgnoredParameterNames",
83 utils::options::serializeStringList(IgnoredParameterNames));
84}
85
86void ArgumentCommentCheck::registerMatchers(MatchFinder *Finder) {
87 Finder->addMatcher(
88 callExpr(unless(cxxOperatorCallExpr()), unless(userDefinedLiteral()),
89 // NewCallback's arguments relate to the pointed function,
90 // don't check them against NewCallback's parameter names.
91 // FIXME: Make this configurable.
92 unless(hasDeclaration(functionDecl(
93 hasAnyName("NewCallback", "NewPermanentCallback")))),
94 // Ignore APIs from the standard library, since their names are
95 // not specified by the standard, and standard library
96 // implementations in practice have to use reserved names to
97 // avoid conflicts with same-named macros.
98 unless(hasDeclaration(isFromStdNamespaceOrSystemHeader())))
99 .bind("expr"),
100 this);
101 Finder->addMatcher(cxxConstructExpr(unless(hasDeclaration(
102 isFromStdNamespaceOrSystemHeader())))
103 .bind("expr"),
104 this);
105}
106
107static std::vector<CommentToken> getCommentsBeforeLoc(ASTContext *Ctx,
108 SourceLocation Loc) {
109 std::vector<CommentToken> Comments;
110 while (Loc.isValid()) {
111 const std::optional<Token> Tok = utils::lexer::getPreviousToken(
112 Loc, Ctx->getSourceManager(), Ctx->getLangOpts(),
113 /*SkipComments=*/false);
114 if (!Tok || Tok->isNot(tok::comment))
115 break;
116 Loc = Tok->getLocation();
117 Comments.emplace_back(CommentToken{
118 Loc,
119 Lexer::getSourceText(CharSourceRange::getCharRange(
120 Loc, Loc.getLocWithOffset(Tok->getLength())),
121 Ctx->getSourceManager(), Ctx->getLangOpts()),
122 });
123 }
124 return Comments;
125}
126
127template <typename NamedDeclRange>
128static bool isLikelyTypo(const NamedDeclRange &Candidates, StringRef ArgName,
129 StringRef TargetName) {
130 const std::string ArgNameLowerStr = ArgName.lower();
131 const StringRef ArgNameLower = ArgNameLowerStr;
132 // The threshold is arbitrary.
133 const unsigned UpperBound = ((ArgName.size() + 2) / 3) + 1;
134 const unsigned ThisED =
135 ArgNameLower.edit_distance(TargetName.lower(),
136 /*AllowReplacements=*/true, UpperBound);
137 if (ThisED >= UpperBound)
138 return false;
139
140 return llvm::all_of(Candidates, [&](const auto &Candidate) {
141 const IdentifierInfo *II = Candidate->getIdentifier();
142 if (!II)
143 return true;
144
145 // Skip the target itself.
146 if (II->getName() == TargetName)
147 return true;
148
149 const unsigned Threshold = 2;
150 // Other candidates must be an edit distance at least Threshold more away
151 // from this candidate. This gives us greater confidence that this is a
152 // typo of this candidate and not one with a similar name.
153 const unsigned OtherED = ArgNameLower.edit_distance(
154 II->getName().lower(),
155 /*AllowReplacements=*/true, ThisED + Threshold);
156 return OtherED >= ThisED + Threshold;
157 });
158}
159
160static bool sameName(StringRef InComment, StringRef InDecl, bool StrictMode) {
161 if (StrictMode)
162 return InComment == InDecl;
163 InComment = InComment.trim('_');
164 InDecl = InDecl.trim('_');
165 // FIXME: compare_insensitive only works for ASCII.
166 return InComment.compare_insensitive(InDecl) == 0;
167}
168
169static bool looksLikeExpectMethod(const CXXMethodDecl *Expect) {
170 return Expect != nullptr && Expect->getLocation().isMacroID() &&
171 Expect->getNameInfo().getName().isIdentifier() &&
172 Expect->getName().starts_with("gmock_");
173}
174static bool areMockAndExpectMethods(const CXXMethodDecl *Mock,
175 const CXXMethodDecl *Expect) {
176 assert(looksLikeExpectMethod(Expect));
177 return Mock != nullptr && Mock->getNextDeclInContext() == Expect &&
178 Mock->getNumParams() == Expect->getNumParams() &&
179 Mock->getLocation().isMacroID() &&
180 Mock->getNameInfo().getName().isIdentifier() &&
181 Mock->getName() == Expect->getName().substr(strlen("gmock_"));
182}
183
184// This uses implementation details of MOCK_METHODx_ macros: for each mocked
185// method M it defines M() with appropriate signature and a method used to set
186// up expectations - gmock_M() - with each argument's type changed the
187// corresponding matcher. This function returns M when given either M or
188// gmock_M.
189static const CXXMethodDecl *findMockedMethod(const CXXMethodDecl *Method) {
190 if (looksLikeExpectMethod(Method)) {
191 const DeclContext *Ctx = Method->getDeclContext();
192 if (Ctx == nullptr || !Ctx->isRecord())
193 return nullptr;
194 for (const auto *D : Ctx->decls()) {
195 if (D->getNextDeclInContext() == Method) {
196 const auto *Previous = dyn_cast<CXXMethodDecl>(D);
197 return areMockAndExpectMethods(Previous, Method) ? Previous : nullptr;
198 }
199 }
200 return nullptr;
201 }
202 if (const auto *Next =
203 dyn_cast_or_null<CXXMethodDecl>(Method->getNextDeclInContext());
204 Next && looksLikeExpectMethod(Next) &&
205 areMockAndExpectMethods(Method, Next))
206 return Method;
207
208 return nullptr;
209}
210
211// For gmock expectation builder method (the target of the call generated by
212// `EXPECT_CALL(obj, Method(...))`) tries to find the real method being mocked
213// (returns nullptr, if the mock method doesn't override anything). For other
214// functions returns the function itself.
215static const FunctionDecl *resolveMocks(const FunctionDecl *Func) {
216 if (const auto *Method = dyn_cast<CXXMethodDecl>(Func)) {
217 if (const auto *MockedMethod = findMockedMethod(Method)) {
218 // If mocked method overrides the real one, we can use its parameter
219 // names, otherwise we're out of luck.
220 if (MockedMethod->size_overridden_methods() > 0)
221 return *MockedMethod->begin_overridden_methods();
222 return nullptr;
223 }
224 }
225 return Func;
226}
227
228namespace {
229
230enum class InitListKind {
231 None,
232 Anonymous,
233 Typed,
234};
235
236} // namespace
237
238static InitListKind getInitListKind(const Expr *Arg) {
239 Arg = Arg->IgnoreUnlessSpelledInSource();
240
241 if (const auto *StdInit = dyn_cast<CXXStdInitializerListExpr>(Arg))
242 Arg = StdInit->getSubExpr()->IgnoreUnlessSpelledInSource();
243
244 if (isa<InitListExpr>(Arg))
245 return InitListKind::Anonymous;
246
247 if (const auto *Ctor = dyn_cast<CXXConstructExpr>(Arg)) {
248 if (!Ctor->isListInitialization())
249 return InitListKind::None;
250 // CXXTemporaryObjectExpr corresponds to explicit Type{...} syntax.
251 if (isa<CXXTemporaryObjectExpr>(Ctor))
252 return InitListKind::Typed;
253 // Other list-initialized constructions (for example '{}') have no
254 // explicit type at the call site.
255 return InitListKind::Anonymous;
256 }
257
258 // std::initializer_list<T>{...} is represented as a functional cast whose
259 // subexpression carries the list-initialization spelling.
260 if (const auto *FuncCast = dyn_cast<CXXFunctionalCastExpr>(Arg)) {
261 const Expr *SubExpr = FuncCast->getSubExpr()->IgnoreImplicit();
262 if (FuncCast->isListInitialization() ||
263 isa<CXXStdInitializerListExpr>(SubExpr))
264 return InitListKind::Typed;
265 }
266
267 return InitListKind::None;
268}
269
270static bool isParenthesizedTemporary(const Expr *Arg) {
271 Arg = Arg->IgnoreUnlessSpelledInSource();
272 if (const auto *TempObject = dyn_cast<CXXTemporaryObjectExpr>(Arg))
273 return !TempObject->isListInitialization();
274 // CXXFunctionalCastExpr with CXXParenListInitExpr corresponds to explicit
275 // Type(...) aggregate temporary initialization syntax.
276 const auto *FuncCast = dyn_cast<CXXFunctionalCastExpr>(Arg);
277 return FuncCast &&
278 isa<CXXParenListInitExpr>(FuncCast->getSubExpr()->IgnoreImplicit());
279}
280
281// Given the argument type and the options determine if we should be adding an
282// argument comment and which diagnostic wording to use.
283ArgumentCommentCheck::CommentKind
284ArgumentCommentCheck::shouldAddComment(const Expr *Arg) const {
285 const InitListKind Kind = getInitListKind(Arg);
286 const bool IsParenthesizedTemporary = isParenthesizedTemporary(Arg);
287
288 // Strip implicit wrappers so brace-init arguments bound to references still
289 // look like list-initialization at this point.
290 Arg = Arg->IgnoreImplicit();
291 if (const auto *UO = dyn_cast<UnaryOperator>(Arg))
292 Arg = UO->getSubExpr()->IgnoreImplicit();
293 if (Arg->getExprLoc().isMacroID())
294 return CommentKind::None;
295
296 if ((CommentAnonymousInitLists && Kind == InitListKind::Anonymous) ||
297 (CommentTypedInitLists && Kind == InitListKind::Typed) ||
298 (CommentParenthesizedTemporaries && IsParenthesizedTemporary)) {
299 return CommentKind::NonLiteral;
300 }
301
302 if ((CommentBoolLiterals && isa<CXXBoolLiteralExpr>(Arg)) ||
303 (CommentIntegerLiterals && isa<IntegerLiteral>(Arg)) ||
304 (CommentFloatLiterals && isa<FloatingLiteral>(Arg)) ||
305 (CommentUserDefinedLiterals && isa<UserDefinedLiteral>(Arg)) ||
306 (CommentCharacterLiterals && isa<CharacterLiteral>(Arg)) ||
307 (CommentStringLiterals && isa<StringLiteral>(Arg)) ||
308 (CommentNullPtrs && isa<CXXNullPtrLiteralExpr>(Arg))) {
309 return CommentKind::Literal;
310 }
311
312 return CommentKind::None;
313}
314
315void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx,
316 const FunctionDecl *OriginalCallee,
317 SourceLocation ArgBeginLoc,
318 llvm::ArrayRef<const Expr *> Args) {
319 const FunctionDecl *Callee = resolveMocks(OriginalCallee);
320 if (!Callee)
321 return;
322
323 Callee = Callee->getFirstDecl();
324 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Callee);
325 Ctor && Ctor->isInheritingConstructor()) {
326 if (const auto *BaseCtor = Ctor->getInheritedConstructor().getConstructor())
327 Callee = BaseCtor->getFirstDecl();
328 }
329 const unsigned NumArgs =
330 std::min<unsigned>(Args.size(), Callee->getNumParams());
331 if ((NumArgs == 0) || (IgnoreSingleArgument && NumArgs == 1))
332 return;
333
334 const auto MakeFileCharRange = [Ctx](SourceLocation Begin,
335 SourceLocation End) {
336 return Lexer::makeFileCharRange(CharSourceRange::getCharRange(Begin, End),
337 Ctx->getSourceManager(),
338 Ctx->getLangOpts());
339 };
340
341 for (unsigned I = 0; I < NumArgs; ++I) {
342 const ParmVarDecl *PVD = Callee->getParamDecl(I);
343 const IdentifierInfo *II = PVD->getIdentifier();
344 if (!II || llvm::any_of(IgnoredParameterNameRegexes,
345 [II](const llvm::Regex &Regex) {
346 return Regex.match(II->getName());
347 }))
348 continue;
349 // Don't warn on arguments for parameters instantiated from template
350 // parameter packs. If we find more arguments than the template
351 // definition has, it also means that they correspond to a parameter
352 // pack.
353 if (FunctionDecl *Template = Callee->getTemplateInstantiationPattern();
354 Template && (Template->getNumParams() <= I ||
355 Template->getParamDecl(I)->isParameterPack()))
356 continue;
357
358 const CharSourceRange BeforeArgument =
359 MakeFileCharRange(ArgBeginLoc, Args[I]->getBeginLoc());
360 ArgBeginLoc = Args[I]->getEndLoc();
361
362 std::vector<CommentToken> Comments;
363 if (BeforeArgument.isValid()) {
365 BeforeArgument, Ctx->getSourceManager(), Ctx->getLangOpts());
366 } else {
367 // Fall back to parsing back from the start of the argument.
368 const CharSourceRange ArgsRange =
369 MakeFileCharRange(Args[I]->getBeginLoc(), Args[I]->getEndLoc());
370 Comments = getCommentsBeforeLoc(Ctx, ArgsRange.getBegin());
371 }
372
373 for (const auto &Comment : Comments) {
374 SmallVector<StringRef, 2> Matches;
375 if (IdentRE.match(Comment.Text, &Matches) &&
376 !sameName(Matches[2], II->getName(), StrictMode)) {
377 {
378 const DiagnosticBuilder Diag =
379 diag(Comment.Loc, "argument name '%0' in comment does not "
380 "match parameter name %1")
381 << Matches[2] << II;
382 if (isLikelyTypo(Callee->parameters(), Matches[2], II->getName())) {
383 Diag << FixItHint::CreateReplacement(
384 Comment.Loc,
385 llvm::Twine(Matches[1] + II->getName() + Matches[3]).str());
386 }
387 }
388 diag(PVD->getLocation(), "%0 declared here", DiagnosticIDs::Note) << II;
389 if (OriginalCallee != Callee) {
390 diag(OriginalCallee->getLocation(),
391 "actual callee (%0) is declared here", DiagnosticIDs::Note)
392 << OriginalCallee;
393 }
394 }
395 }
396
397 // If the argument comments are missing for configured argument kinds, add
398 // them.
399 const CommentKind Kind = shouldAddComment(Args[I]);
400 if (Comments.empty() && Kind != CommentKind::None) {
401 SmallString<32> ArgComment;
402 llvm::Twine(llvm::Twine("/*") + II->getName() + "=*/")
403 .toStringRef(ArgComment);
404 const DiagnosticBuilder Diag =
405 diag(Args[I]->getBeginLoc(),
406 "argument comment missing for %select{literal argument|"
407 "argument}0 %1")
408 << (Kind == CommentKind::Literal ? 0 : 1) << II
409 << FixItHint::CreateInsertion(Args[I]->getBeginLoc(), ArgComment);
410 }
411 }
412}
413
414void ArgumentCommentCheck::check(const MatchFinder::MatchResult &Result) {
415 const auto *E = Result.Nodes.getNodeAs<Expr>("expr");
416 if (const auto *Call = dyn_cast<CallExpr>(E)) {
417 const FunctionDecl *Callee = Call->getDirectCallee();
418 if (!Callee)
419 return;
420
421 checkCallArgs(Result.Context, Callee, Call->getCallee()->getEndLoc(),
422 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
423 } else {
424 const auto *Construct = cast<CXXConstructExpr>(E);
425 if (Construct->getNumArgs() > 0 &&
426 Construct->getArg(0)->getSourceRange() == Construct->getSourceRange()) {
427 // Ignore implicit construction.
428 return;
429 }
430 checkCallArgs(
431 Result.Context, Construct->getConstructor(),
432 Construct->getParenOrBraceRange().getBegin(),
433 llvm::ArrayRef(Construct->getArgs(), Construct->getNumArgs()));
434 }
435}
436
437} // namespace clang::tidy::bugprone
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
ArgumentCommentCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static InitListKind getInitListKind(const Expr *Arg)
static bool sameName(StringRef InComment, StringRef InDecl, bool StrictMode)
static bool isParenthesizedTemporary(const Expr *Arg)
static bool isLikelyTypo(const NamedDeclRange &Candidates, StringRef ArgName, StringRef TargetName)
static bool looksLikeExpectMethod(const CXXMethodDecl *Expect)
static const CXXMethodDecl * findMockedMethod(const CXXMethodDecl *Method)
static const FunctionDecl * resolveMocks(const FunctionDecl *Func)
static std::vector< CommentToken > getCommentsBeforeLoc(ASTContext *Ctx, SourceLocation Loc)
static bool areMockAndExpectMethods(const CXXMethodDecl *Mock, const CXXMethodDecl *Expect)
std::optional< Token > getPreviousToken(SourceLocation Location, const SourceManager &SM, const LangOptions &LangOpts, bool SkipComments)
Returns previous token or std::nullopt if not found.
std::vector< CommentToken > getTrailingCommentsInRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Returns comment tokens found in the given range. If a non-comment token is encountered,...
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap
static constexpr const char ArgName[]