38AST_MATCHER(Decl, isFromStdNamespaceOrSystemHeader) {
39 if (
const auto *D = Node.getDeclContext()->getEnclosingNamespaceContext();
40 D && D->isStdNamespace())
42 if (Node.getLocation().isInvalid())
44 return Node.getASTContext().getSourceManager().isInSystemHeader(
54 if (
const std::optional<StringRef> Value =
55 Options.get(
"CommentIntegerLiterals")) {
56 if (
const std::optional<bool> Bool = llvm::yaml::parseBool(*Value))
57 return *Bool ? IntegerLiteralKind::All : IntegerLiteralKind::None;
59 if (!Value->getAsInteger(10, Number))
60 return Number != 0 ? IntegerLiteralKind::All : IntegerLiteralKind::None;
62 return Options.get(
"CommentIntegerLiterals", IntegerLiteralKind::None);
68 StrictMode(Options.get(
"StrictMode", false)),
69 IgnoreMacros(Options.get(
"IgnoreMacros", true)),
70 IgnoreSingleArgument(Options.get(
"IgnoreSingleArgument", false)),
71 CommentAnonymousInitLists(
72 Options.get(
"CommentAnonymousInitLists", false)),
73 CommentBoolLiterals(Options.get(
"CommentBoolLiterals", false)),
74 CommentCharacterLiterals(Options.get(
"CommentCharacterLiterals", false)),
75 CommentFloatLiterals(Options.get(
"CommentFloatLiterals", false)),
76 CommentNullPtrs(Options.get(
"CommentNullPtrs", false)),
77 CommentParenthesizedTemporaries(
78 Options.get(
"CommentParenthesizedTemporaries", false)),
79 CommentStringLiterals(Options.get(
"CommentStringLiterals", false)),
80 CommentTypedInitLists(Options.get(
"CommentTypedInitLists", false)),
81 CommentUserDefinedLiterals(
82 Options.get(
"CommentUserDefinedLiterals", false)),
83 IgnoredParameterNames(
utils::options::parseStringList(
84 Options.get(
"IgnoredParameterNames",
""))),
86 NullPtrMacros(
utils::options::parseStringList(
87 Options.get(
"NullPtrMacros",
"NULL"))),
88 BoolLiteralMacros(
utils::options::parseStringList(
89 Options.get(
"BoolLiteralMacros",
"true;false"))),
90 IdentRE(
"^(/\\* *)([_A-Za-z][_A-Za-z0-9]*)( *= *\\*/)$") {
91 for (
const StringRef Name : IgnoredParameterNames) {
92 llvm::Regex Regex(Name);
93 if (!Regex.isValid()) {
94 configurationDiag(
"Invalid regular expression '%0' in "
95 "IgnoredParameterNames")
99 IgnoredParameterNameRegexes.push_back(std::move(Regex));
104 Options.store(Opts,
"StrictMode", StrictMode);
105 Options.store(Opts,
"IgnoreMacros", IgnoreMacros);
106 Options.store(Opts,
"IgnoreSingleArgument", IgnoreSingleArgument);
107 Options.store(Opts,
"CommentAnonymousInitLists", CommentAnonymousInitLists);
108 Options.store(Opts,
"CommentBoolLiterals", CommentBoolLiterals);
109 Options.store(Opts,
"CommentCharacterLiterals", CommentCharacterLiterals);
110 Options.store(Opts,
"CommentFloatLiterals", CommentFloatLiterals);
111 Options.store(Opts,
"CommentIntegerLiterals", CommentIntegerLiterals);
112 Options.store(Opts,
"CommentNullPtrs", CommentNullPtrs);
113 Options.store(Opts,
"CommentParenthesizedTemporaries",
114 CommentParenthesizedTemporaries);
115 Options.store(Opts,
"CommentStringLiterals", CommentStringLiterals);
116 Options.store(Opts,
"CommentTypedInitLists", CommentTypedInitLists);
117 Options.store(Opts,
"CommentUserDefinedLiterals", CommentUserDefinedLiterals);
118 Options.store(Opts,
"IgnoredParameterNames",
120 Options.store(Opts,
"NullPtrMacros",
122 Options.store(Opts,
"BoolLiteralMacros",
128 callExpr(unless(cxxOperatorCallExpr()), unless(userDefinedLiteral()),
132 unless(hasDeclaration(functionDecl(
133 hasAnyName(
"NewCallback",
"NewPermanentCallback")))),
138 unless(hasDeclaration(isFromStdNamespaceOrSystemHeader())))
141 Finder->addMatcher(cxxConstructExpr(unless(hasDeclaration(
142 isFromStdNamespaceOrSystemHeader())))
148 SourceLocation Loc) {
149 std::vector<CommentToken> Comments;
150 while (Loc.isValid()) {
152 Loc, Ctx->getSourceManager(), Ctx->getLangOpts(),
154 if (!Tok || Tok->isNot(tok::comment))
156 Loc = Tok->getLocation();
159 Lexer::getSourceText(CharSourceRange::getCharRange(
160 Loc, Loc.getLocWithOffset(Tok->getLength())),
161 Ctx->getSourceManager(), Ctx->getLangOpts()),
167template <
typename NamedDeclRange>
169 StringRef TargetName) {
170 const std::string ArgNameLowerStr =
ArgName.lower();
171 const StringRef ArgNameLower = ArgNameLowerStr;
173 const unsigned UpperBound = ((
ArgName.size() + 2) / 3) + 1;
174 const unsigned ThisED =
175 ArgNameLower.edit_distance(TargetName.lower(),
177 if (ThisED >= UpperBound)
180 return llvm::all_of(Candidates, [&](
const auto &Candidate) {
181 const IdentifierInfo *II = Candidate->getIdentifier();
186 if (II->getName() == TargetName)
189 const unsigned Threshold = 2;
193 const unsigned OtherED = ArgNameLower.edit_distance(
194 II->getName().lower(),
195 true, ThisED + Threshold);
196 return OtherED >= ThisED + Threshold;
200static bool sameName(StringRef InComment, StringRef InDecl,
bool StrictMode) {
202 return InComment == InDecl;
203 InComment = InComment.trim(
'_');
204 InDecl = InDecl.trim(
'_');
206 return InComment.compare_insensitive(InDecl) == 0;
210 return Expect !=
nullptr && Expect->getLocation().isMacroID() &&
211 Expect->getNameInfo().getName().isIdentifier() &&
212 Expect->getName().starts_with(
"gmock_");
215 const CXXMethodDecl *Expect) {
217 return Mock !=
nullptr && Mock->getNextDeclInContext() == Expect &&
218 Mock->getNumParams() == Expect->getNumParams() &&
219 Mock->getLocation().isMacroID() &&
220 Mock->getNameInfo().getName().isIdentifier() &&
221 Mock->getName() == Expect->getName().substr(strlen(
"gmock_"));
231 const DeclContext *Ctx = Method->getDeclContext();
232 if (Ctx ==
nullptr || !Ctx->isRecord())
234 for (
const auto *D : Ctx->decls()) {
235 if (D->getNextDeclInContext() == Method) {
236 const auto *Previous = dyn_cast<CXXMethodDecl>(D);
242 if (
const auto *Next =
243 dyn_cast_or_null<CXXMethodDecl>(Method->getNextDeclInContext());
256 if (
const auto *Method = dyn_cast<CXXMethodDecl>(Func)) {
260 if (MockedMethod->size_overridden_methods() > 0)
261 return *MockedMethod->begin_overridden_methods();
270enum class InitListKind {
279 Arg = Arg->IgnoreUnlessSpelledInSource();
281 if (
const auto *StdInit = dyn_cast<CXXStdInitializerListExpr>(Arg))
282 Arg = StdInit->getSubExpr()->IgnoreUnlessSpelledInSource();
284 if (isa<InitListExpr>(Arg))
285 return InitListKind::Anonymous;
287 if (
const auto *Ctor = dyn_cast<CXXConstructExpr>(Arg)) {
288 if (!Ctor->isListInitialization())
289 return InitListKind::None;
291 if (isa<CXXTemporaryObjectExpr>(Ctor))
292 return InitListKind::Typed;
295 return InitListKind::Anonymous;
300 if (
const auto *FuncCast = dyn_cast<CXXFunctionalCastExpr>(Arg)) {
301 const Expr *SubExpr = FuncCast->getSubExpr()->IgnoreImplicit();
302 if (FuncCast->isListInitialization() ||
303 isa<CXXStdInitializerListExpr>(SubExpr))
304 return InitListKind::Typed;
307 return InitListKind::None;
316 const SourceManager &SM,
317 const LangOptions &LangOpts) {
318 const CharSourceRange Range = Lexer::makeFileCharRange(
319 CharSourceRange::getTokenRange(Arg->getBeginLoc(), CloseLoc), SM,
321 const SourceLocation ArgLoc =
322 SM.getExpansionLoc(SM.getTopMacroCallerLoc(Arg->getBeginLoc()));
323 if (Range.isInvalid() || Range.getBegin() != ArgLoc)
329 Arg = Arg->IgnoreUnlessSpelledInSource();
330 if (
const auto *TempObject = dyn_cast<CXXTemporaryObjectExpr>(Arg))
331 return !TempObject->isListInitialization();
334 const auto *FuncCast = dyn_cast<CXXFunctionalCastExpr>(Arg);
336 isa<CXXParenListInitExpr>(FuncCast->getSubExpr()->IgnoreImplicit());
341ArgumentCommentCheck::CommentKind
342ArgumentCommentCheck::shouldAddComment(
const Expr *Arg,
343 const ASTContext &Ctx)
const {
344 const SourceManager &SM = Ctx.getSourceManager();
350 Arg = Arg->IgnoreImplicit();
353 const auto *IntegerLit = dyn_cast<IntegerLiteral>(Arg);
354 const bool IsZero = IntegerLit && IntegerLit->getValue().isZero();
355 if (
const auto *UO = dyn_cast<UnaryOperator>(Arg))
356 Arg = UO->getSubExpr()->IgnoreImplicit();
363 if (SM.getTopMacroCallerLoc(Arg->getExprLoc()).isMacroID()) {
364 const StringRef MacroName =
365 Lexer::getSourceText(CharSourceRange::getTokenRange(
366 SM.getTopMacroCallerLoc(Arg->getBeginLoc()),
367 SM.getTopMacroCallerLoc(Arg->getEndLoc())),
368 SM, Ctx.getLangOpts());
369 if ((CommentNullPtrs && llvm::is_contained(NullPtrMacros, MacroName)) ||
370 (CommentBoolLiterals &&
371 llvm::is_contained(BoolLiteralMacros, MacroName)))
372 return CommentKind::Literal;
373 return CommentKind::None;
376 if ((CommentAnonymousInitLists && Kind == InitListKind::Anonymous) ||
377 (CommentTypedInitLists && Kind == InitListKind::Typed) ||
378 (CommentParenthesizedTemporaries && IsParenthesizedTemporary)) {
379 return CommentKind::NonLiteral;
382 const bool CommentInteger =
383 CommentIntegerLiterals == IntegerLiteralKind::All ||
384 (CommentIntegerLiterals == IntegerLiteralKind::ZeroOnly && IsZero);
385 if ((CommentBoolLiterals && isa<CXXBoolLiteralExpr>(Arg)) ||
386 (CommentInteger && isa<IntegerLiteral>(Arg)) ||
387 (CommentFloatLiterals && isa<FloatingLiteral>(Arg)) ||
388 (CommentUserDefinedLiterals && isa<UserDefinedLiteral>(Arg)) ||
389 (CommentCharacterLiterals && isa<CharacterLiteral>(Arg)) ||
390 (CommentStringLiterals && isa<StringLiteral>(Arg)) ||
391 (CommentNullPtrs && isa<CXXNullPtrLiteralExpr>(Arg))) {
392 return CommentKind::Literal;
395 return CommentKind::None;
398void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx,
399 const FunctionDecl *OriginalCallee,
400 SourceLocation ArgBeginLoc,
401 SourceLocation CloseLoc,
402 llvm::ArrayRef<const Expr *> Args) {
403 const FunctionDecl *Callee =
resolveMocks(OriginalCallee);
407 Callee = Callee->getFirstDecl();
408 if (
const auto *Ctor = dyn_cast<CXXConstructorDecl>(Callee);
409 Ctor && Ctor->isInheritingConstructor()) {
410 if (
const auto *BaseCtor = Ctor->getInheritedConstructor().getConstructor())
411 Callee = BaseCtor->getFirstDecl();
413 const unsigned NumArgs =
414 std::min<unsigned>(Args.size(), Callee->getNumParams());
415 if ((NumArgs == 0) || (IgnoreSingleArgument && NumArgs == 1))
418 const SourceManager &SM = Ctx->getSourceManager();
422 const bool AddMissingComments = !IgnoreMacros || CloseLoc.isFileID();
424 const auto MakeFileCharRange = [Ctx](SourceLocation Begin,
425 SourceLocation End) {
426 return Lexer::makeFileCharRange(CharSourceRange::getCharRange(Begin, End),
427 Ctx->getSourceManager(),
431 for (
unsigned I = 0; I < NumArgs; ++I) {
432 const ParmVarDecl *PVD = Callee->getParamDecl(I);
433 const IdentifierInfo *II = PVD->getIdentifier();
434 if (!II || llvm::any_of(IgnoredParameterNameRegexes,
435 [II](
const llvm::Regex &Regex) {
436 return Regex.match(II->getName());
443 if (FunctionDecl *Template = Callee->getTemplateInstantiationPattern();
444 Template && (Template->getNumParams() <= I ||
445 Template->getParamDecl(I)->isParameterPack()))
448 const CharSourceRange BeforeArgument =
449 MakeFileCharRange(ArgBeginLoc, Args[I]->getBeginLoc());
450 ArgBeginLoc = Args[I]->getEndLoc();
452 std::vector<CommentToken> Comments;
453 if (BeforeArgument.isValid()) {
455 BeforeArgument, Ctx->getSourceManager(), Ctx->getLangOpts());
460 const CharSourceRange ArgsRange =
461 MakeFileCharRange(Args[I]->getBeginLoc(), Args[I]->getBeginLoc());
465 for (
const auto &Comment : Comments) {
466 SmallVector<StringRef, 2> Matches;
467 if (IdentRE.match(Comment.Text, &Matches) &&
468 !
sameName(Matches[2], II->getName(), StrictMode)) {
470 const DiagnosticBuilder Diag =
471 diag(Comment.Loc,
"argument name '%0' in comment does not "
472 "match parameter name %1")
474 if (
isLikelyTypo(Callee->parameters(), Matches[2], II->getName())) {
475 Diag << FixItHint::CreateReplacement(
477 llvm::Twine(Matches[1] + II->getName() + Matches[3]).str());
480 diag(PVD->getLocation(),
"%0 declared here", DiagnosticIDs::Note) << II;
481 if (OriginalCallee != Callee) {
482 diag(OriginalCallee->getLocation(),
483 "actual callee (%0) is declared here", DiagnosticIDs::Note)
491 if (!AddMissingComments || !Comments.empty())
493 const SourceLocation ArgLoc =
495 if (ArgLoc.isInvalid())
497 const CommentKind Kind = shouldAddComment(Args[I], *Ctx);
498 if (Kind != CommentKind::None) {
499 SmallString<32> ArgComment;
500 llvm::Twine(llvm::Twine(
"/*") + II->getName() +
"=*/")
501 .toStringRef(ArgComment);
502 const DiagnosticBuilder Diag =
503 diag(ArgLoc,
"argument comment missing for %select{literal argument|"
505 << (Kind == CommentKind::Literal ? 0 : 1) << II
506 << FixItHint::CreateInsertion(ArgLoc, ArgComment);
512 const auto *E = Result.Nodes.getNodeAs<Expr>(
"expr");
513 if (
const auto *Call = dyn_cast<CallExpr>(E)) {
514 const FunctionDecl *Callee = Call->getDirectCallee();
518 checkCallArgs(Result.Context, Callee, Call->getCallee()->getEndLoc(),
520 llvm::ArrayRef(Call->getArgs(), Call->getNumArgs()));
522 const auto *Construct = cast<CXXConstructExpr>(E);
523 if (Construct->getNumArgs() > 0 &&
524 Construct->getArg(0)->getSourceRange() == Construct->getSourceRange()) {
529 Result.Context, Construct->getConstructor(),
530 Construct->getParenOrBraceRange().getBegin(), Construct->getEndLoc(),
531 llvm::ArrayRef(Construct->getArgs(), Construct->getNumArgs()));