24AST_MATCHER(Decl, isFromStdNamespaceOrSystemHeader) {
25 if (
const auto *D = Node.getDeclContext()->getEnclosingNamespaceContext();
26 D && D->isStdNamespace())
28 if (Node.getLocation().isInvalid())
30 return Node.getASTContext().getSourceManager().isInSystemHeader(
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")
64 IgnoredParameterNameRegexes.push_back(std::move(Regex));
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",
88 callExpr(unless(cxxOperatorCallExpr()), unless(userDefinedLiteral()),
92 unless(hasDeclaration(functionDecl(
93 hasAnyName(
"NewCallback",
"NewPermanentCallback")))),
98 unless(hasDeclaration(isFromStdNamespaceOrSystemHeader())))
101 Finder->addMatcher(cxxConstructExpr(unless(hasDeclaration(
102 isFromStdNamespaceOrSystemHeader())))
108 SourceLocation Loc) {
109 std::vector<CommentToken> Comments;
110 while (Loc.isValid()) {
112 Loc, Ctx->getSourceManager(), Ctx->getLangOpts(),
114 if (!Tok || Tok->isNot(tok::comment))
116 Loc = Tok->getLocation();
119 Lexer::getSourceText(CharSourceRange::getCharRange(
120 Loc, Loc.getLocWithOffset(Tok->getLength())),
121 Ctx->getSourceManager(), Ctx->getLangOpts()),
127template <
typename NamedDeclRange>
129 StringRef TargetName) {
130 const std::string ArgNameLowerStr =
ArgName.lower();
131 const StringRef ArgNameLower = ArgNameLowerStr;
133 const unsigned UpperBound = ((
ArgName.size() + 2) / 3) + 1;
134 const unsigned ThisED =
135 ArgNameLower.edit_distance(TargetName.lower(),
137 if (ThisED >= UpperBound)
140 return llvm::all_of(Candidates, [&](
const auto &Candidate) {
141 const IdentifierInfo *II = Candidate->getIdentifier();
146 if (II->getName() == TargetName)
149 const unsigned Threshold = 2;
153 const unsigned OtherED = ArgNameLower.edit_distance(
154 II->getName().lower(),
155 true, ThisED + Threshold);
156 return OtherED >= ThisED + Threshold;
160static bool sameName(StringRef InComment, StringRef InDecl,
bool StrictMode) {
162 return InComment == InDecl;
163 InComment = InComment.trim(
'_');
164 InDecl = InDecl.trim(
'_');
166 return InComment.compare_insensitive(InDecl) == 0;
170 return Expect !=
nullptr && Expect->getLocation().isMacroID() &&
171 Expect->getNameInfo().getName().isIdentifier() &&
172 Expect->getName().starts_with(
"gmock_");
175 const CXXMethodDecl *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_"));
191 const DeclContext *Ctx = Method->getDeclContext();
192 if (Ctx ==
nullptr || !Ctx->isRecord())
194 for (
const auto *D : Ctx->decls()) {
195 if (D->getNextDeclInContext() == Method) {
196 const auto *Previous = dyn_cast<CXXMethodDecl>(D);
202 if (
const auto *Next =
203 dyn_cast_or_null<CXXMethodDecl>(Method->getNextDeclInContext());
216 if (
const auto *Method = dyn_cast<CXXMethodDecl>(Func)) {
220 if (MockedMethod->size_overridden_methods() > 0)
221 return *MockedMethod->begin_overridden_methods();
230enum class InitListKind {
239 Arg = Arg->IgnoreUnlessSpelledInSource();
241 if (
const auto *StdInit = dyn_cast<CXXStdInitializerListExpr>(Arg))
242 Arg = StdInit->getSubExpr()->IgnoreUnlessSpelledInSource();
244 if (isa<InitListExpr>(Arg))
245 return InitListKind::Anonymous;
247 if (
const auto *Ctor = dyn_cast<CXXConstructExpr>(Arg)) {
248 if (!Ctor->isListInitialization())
249 return InitListKind::None;
251 if (isa<CXXTemporaryObjectExpr>(Ctor))
252 return InitListKind::Typed;
255 return InitListKind::Anonymous;
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;
267 return InitListKind::None;
271 Arg = Arg->IgnoreUnlessSpelledInSource();
272 if (
const auto *TempObject = dyn_cast<CXXTemporaryObjectExpr>(Arg))
273 return !TempObject->isListInitialization();
276 const auto *FuncCast = dyn_cast<CXXFunctionalCastExpr>(Arg);
278 isa<CXXParenListInitExpr>(FuncCast->getSubExpr()->IgnoreImplicit());
283ArgumentCommentCheck::CommentKind
284ArgumentCommentCheck::shouldAddComment(
const Expr *Arg)
const {
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;
296 if ((CommentAnonymousInitLists && Kind == InitListKind::Anonymous) ||
297 (CommentTypedInitLists && Kind == InitListKind::Typed) ||
298 (CommentParenthesizedTemporaries && IsParenthesizedTemporary)) {
299 return CommentKind::NonLiteral;
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;
312 return CommentKind::None;
315void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx,
316 const FunctionDecl *OriginalCallee,
317 SourceLocation ArgBeginLoc,
318 llvm::ArrayRef<const Expr *> Args) {
319 const FunctionDecl *Callee =
resolveMocks(OriginalCallee);
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();
329 const unsigned NumArgs =
330 std::min<unsigned>(Args.size(), Callee->getNumParams());
331 if ((NumArgs == 0) || (IgnoreSingleArgument && NumArgs == 1))
334 const auto MakeFileCharRange = [Ctx](SourceLocation Begin,
335 SourceLocation End) {
336 return Lexer::makeFileCharRange(CharSourceRange::getCharRange(Begin, End),
337 Ctx->getSourceManager(),
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());
353 if (FunctionDecl *Template = Callee->getTemplateInstantiationPattern();
354 Template && (Template->getNumParams() <= I ||
355 Template->getParamDecl(I)->isParameterPack()))
358 const CharSourceRange BeforeArgument =
359 MakeFileCharRange(ArgBeginLoc, Args[I]->getBeginLoc());
360 ArgBeginLoc = Args[I]->getEndLoc();
362 std::vector<CommentToken> Comments;
363 if (BeforeArgument.isValid()) {
365 BeforeArgument, Ctx->getSourceManager(), Ctx->getLangOpts());
368 const CharSourceRange ArgsRange =
369 MakeFileCharRange(Args[I]->getBeginLoc(), Args[I]->getEndLoc());
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)) {
378 const DiagnosticBuilder Diag =
379 diag(Comment.Loc,
"argument name '%0' in comment does not "
380 "match parameter name %1")
382 if (
isLikelyTypo(Callee->parameters(), Matches[2], II->getName())) {
383 Diag << FixItHint::CreateReplacement(
385 llvm::Twine(Matches[1] + II->getName() + Matches[3]).str());
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)
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|"
408 << (Kind == CommentKind::Literal ? 0 : 1) << II
409 << FixItHint::CreateInsertion(Args[I]->getBeginLoc(), ArgComment);
415 const auto *E = Result.Nodes.getNodeAs<Expr>(
"expr");
416 if (
const auto *Call = dyn_cast<CallExpr>(E)) {
417 const FunctionDecl *Callee = Call->getDirectCallee();
421 checkCallArgs(Result.Context, Callee, Call->getCallee()->getEndLoc(),
422 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
424 const auto *Construct = cast<CXXConstructExpr>(E);
425 if (Construct->getNumArgs() > 0 &&
426 Construct->getArg(0)->getSourceRange() == Construct->getSourceRange()) {
431 Result.Context, Construct->getConstructor(),
432 Construct->getParenOrBraceRange().getBegin(),
433 llvm::ArrayRef(Construct->getArgs(), Construct->getNumArgs()));
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.