llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT--> @llvm/pr-subscribers-clang-tidy Author: Daan De Meyer (daandemeyer) <details> <summary>Changes</summary> systemd wants a /*name=*/ comment on every argument that is passed as a bare NULL, 0, true or false, and proposes a libclang script to check it (https://github.com/systemd/systemd/pull/43725). bugprone-argument-comment can't do this for C code. It skips literals that come from a macro, and C spells NULL, and true and false before C23, with macros. It also skips calls in macro arguments such as assert_se(f(NULL)), and CommentIntegerLiterals flags every integer instead of only 0. Let's add an IgnoreMacros option. When it's false, the check also adds missing comments to calls in macro arguments. CommentNullPtrs and CommentBoolLiterals now match the macros in the new NullPtrMacros and BoolLiteralMacros options, which default to NULL, true and false. We also add a CommentZeroIntegerLiterals option for integer literals with the value zero, and an IgnoredParameterNames option to skip parameters with names like p or arg1 that don't help the reader. IgnoreMacros defaults to true, so existing configurations only get new warnings for NULL, and for true and false where they are macros. systemd's lint corresponds to: CheckOptions: bugprone-argument-comment.CommentBoolLiterals: true bugprone-argument-comment.CommentNullPtrs: true bugprone-argument-comment.CommentZeroIntegerLiterals: true bugprone-argument-comment.IgnoreMacros: false bugprone-argument-comment.IgnoredParameterNames: '^[a-z]$;^arg[0-9]*$;^__' --- Patch is 29.84 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/237623.diff 10 Files Affected: - (modified) clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp (+102-13) - (modified) clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.h (+8-2) - (modified) clang-tools-extra/docs/ReleaseNotes.md (+13) - (modified) clang-tools-extra/docs/clang-tidy/checks/bugprone/argument-comment.md (+58-4) - (added) clang-tools-extra/test/clang-tidy/checkers/bugprone/argument-comment-c.c (+52) - (added) clang-tools-extra/test/clang-tidy/checkers/bugprone/argument-comment-gnu98.cpp (+18) - (added) clang-tools-extra/test/clang-tidy/checkers/bugprone/argument-comment-ignored-parameter-names.cpp (+24) - (added) clang-tools-extra/test/clang-tidy/checkers/bugprone/argument-comment-macro-names.c (+31) - (added) clang-tools-extra/test/clang-tidy/checkers/bugprone/argument-comment-macros.cpp (+72) - (added) clang-tools-extra/test/clang-tidy/checkers/bugprone/argument-comment-zero-integer-literals.cpp (+23) ``````````diff diff --git a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp index 783944cd1a5a17..b8f90a3b89513c 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.cpp @@ -13,6 +13,7 @@ #include "clang/Lex/Token.h" #include "../utils/LexerUtils.h" +#include "../utils/OptionsUtils.h" using namespace clang::ast_matchers; @@ -35,6 +36,7 @@ ArgumentCommentCheck::ArgumentCommentCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), StrictMode(Options.get("StrictMode", false)), + IgnoreMacros(Options.get("IgnoreMacros", true)), IgnoreSingleArgument(Options.get("IgnoreSingleArgument", false)), CommentAnonymousInitLists( Options.get("CommentAnonymousInitLists", false)), @@ -49,10 +51,30 @@ ArgumentCommentCheck::ArgumentCommentCheck(StringRef Name, CommentTypedInitLists(Options.get("CommentTypedInitLists", false)), CommentUserDefinedLiterals( Options.get("CommentUserDefinedLiterals", false)), - IdentRE("^(/\\* *)([_A-Za-z][_A-Za-z0-9]*)( *= *\\*/)$") {} + CommentZeroIntegerLiterals( + Options.get("CommentZeroIntegerLiterals", false)), + NullPtrMacros(utils::options::parseStringList( + Options.get("NullPtrMacros", "NULL"))), + BoolLiteralMacros(utils::options::parseStringList( + Options.get("BoolLiteralMacros", "true;false"))), + IgnoredParameterNames(utils::options::parseStringList( + Options.get("IgnoredParameterNames", ""))), + IdentRE("^(/\\* *)([_A-Za-z][_A-Za-z0-9]*)( *= *\\*/)$") { + for (const StringRef Name : IgnoredParameterNames) { + llvm::Regex Regex(Name); + if (!Regex.isValid()) { + configurationDiag("Invalid regular expression '%0' in " + "IgnoredParameterNames") + << Name; + continue; + } + IgnoredParameterNameRegexes.push_back(std::move(Regex)); + } +} void ArgumentCommentCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "StrictMode", StrictMode); + Options.store(Opts, "IgnoreMacros", IgnoreMacros); Options.store(Opts, "IgnoreSingleArgument", IgnoreSingleArgument); Options.store(Opts, "CommentAnonymousInitLists", CommentAnonymousInitLists); Options.store(Opts, "CommentBoolLiterals", CommentBoolLiterals); @@ -65,6 +87,13 @@ void ArgumentCommentCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "CommentStringLiterals", CommentStringLiterals); Options.store(Opts, "CommentTypedInitLists", CommentTypedInitLists); Options.store(Opts, "CommentUserDefinedLiterals", CommentUserDefinedLiterals); + Options.store(Opts, "CommentZeroIntegerLiterals", CommentZeroIntegerLiterals); + Options.store(Opts, "NullPtrMacros", + utils::options::serializeStringList(NullPtrMacros)); + Options.store(Opts, "BoolLiteralMacros", + utils::options::serializeStringList(BoolLiteralMacros)); + Options.store(Opts, "IgnoredParameterNames", + utils::options::serializeStringList(IgnoredParameterNames)); } void ArgumentCommentCheck::registerMatchers(MatchFinder *Finder) { @@ -251,6 +280,24 @@ static InitListKind getInitListKind(const Expr *Arg) { return InitListKind::None; } +// Returns the file location of Arg. Returns an invalid location when Arg and +// the closing parenthesis of the call at CloseLoc don't map to one range of the +// file that starts at Arg. That happens when a macro body contains Arg or the +// closing parenthesis, or when Arg is in another macro argument than the +// closing parenthesis, such as the `0` in `f(ID(0))`. +static SourceLocation getWrittenArgLoc(const Expr *Arg, SourceLocation CloseLoc, + const SourceManager &SM, + const LangOptions &LangOpts) { + const CharSourceRange Range = Lexer::makeFileCharRange( + CharSourceRange::getTokenRange(Arg->getBeginLoc(), CloseLoc), SM, + LangOpts); + const SourceLocation ArgLoc = + SM.getExpansionLoc(SM.getTopMacroCallerLoc(Arg->getBeginLoc())); + if (Range.isInvalid() || Range.getBegin() != ArgLoc) + return {}; + return ArgLoc; +} + static bool isParenthesizedTemporary(const Expr *Arg) { Arg = Arg->IgnoreUnlessSpelledInSource(); if (const auto *TempObject = dyn_cast<CXXTemporaryObjectExpr>(Arg)) @@ -265,17 +312,40 @@ static bool isParenthesizedTemporary(const Expr *Arg) { // Given the argument type and the options determine if we should be adding an // argument comment and which diagnostic wording to use. ArgumentCommentCheck::CommentKind -ArgumentCommentCheck::shouldAddComment(const Expr *Arg) const { +ArgumentCommentCheck::shouldAddComment(const Expr *Arg, + const ASTContext &Ctx) const { + const SourceManager &SM = Ctx.getSourceManager(); const InitListKind Kind = getInitListKind(Arg); const bool IsParenthesizedTemporary = isParenthesizedTemporary(Arg); // Strip implicit wrappers so brace-init arguments bound to references still // look like list-initialization at this point. Arg = Arg->IgnoreImplicit(); + // Check for zero before stripping the unary operator, because `~0` and `!0` + // are not zero. + const auto *ZeroLiteral = dyn_cast<IntegerLiteral>(Arg); + if (ZeroLiteral && !ZeroLiteral->getValue().isZero()) + ZeroLiteral = nullptr; if (const auto *UO = dyn_cast<UnaryOperator>(Arg)) Arg = UO->getSubExpr()->IgnoreImplicit(); - if (Arg->getExprLoc().isMacroID()) + + // C spells the null pointer constant with the macro `NULL`, and the boolean + // constants before C23 with the macros `true` and `false`. The options + // NullPtrMacros and BoolLiteralMacros contain `NULL`, `true` and `false` by + // default. Other macros, such as `MAX_SIZE`, already name their value and + // need no comment. + if (SM.getTopMacroCallerLoc(Arg->getExprLoc()).isMacroID()) { + const StringRef MacroName = + Lexer::getSourceText(CharSourceRange::getTokenRange( + SM.getTopMacroCallerLoc(Arg->getBeginLoc()), + SM.getTopMacroCallerLoc(Arg->getEndLoc())), + SM, Ctx.getLangOpts()); + if ((CommentNullPtrs && llvm::is_contained(NullPtrMacros, MacroName)) || + (CommentBoolLiterals && + llvm::is_contained(BoolLiteralMacros, MacroName))) + return CommentKind::Literal; return CommentKind::None; + } if ((CommentAnonymousInitLists && Kind == InitListKind::Anonymous) || (CommentTypedInitLists && Kind == InitListKind::Typed) || @@ -285,6 +355,7 @@ ArgumentCommentCheck::shouldAddComment(const Expr *Arg) const { if ((CommentBoolLiterals && isa<CXXBoolLiteralExpr>(Arg)) || (CommentIntegerLiterals && isa<IntegerLiteral>(Arg)) || + (CommentZeroIntegerLiterals && ZeroLiteral) || (CommentFloatLiterals && isa<FloatingLiteral>(Arg)) || (CommentUserDefinedLiterals && isa<UserDefinedLiteral>(Arg)) || (CommentCharacterLiterals && isa<CharacterLiteral>(Arg)) || @@ -299,6 +370,7 @@ ArgumentCommentCheck::shouldAddComment(const Expr *Arg) const { void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, const FunctionDecl *OriginalCallee, SourceLocation ArgBeginLoc, + SourceLocation CloseLoc, llvm::ArrayRef<const Expr *> Args) { const FunctionDecl *Callee = resolveMocks(OriginalCallee); if (!Callee) @@ -315,6 +387,12 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, if ((NumArgs == 0) || (IgnoreSingleArgument && NumArgs == 1)) return; + const SourceManager &SM = Ctx->getSourceManager(); + // A call whose closing parenthesis is a macro location is in a macro + // argument, such as `f(0)` in `ASSERT(f(0))`. getWrittenArgLoc() rejects + // calls in a macro body. + const bool AddMissingComments = !IgnoreMacros || CloseLoc.isFileID(); + const auto MakeFileCharRange = [Ctx](SourceLocation Begin, SourceLocation End) { return Lexer::makeFileCharRange(CharSourceRange::getCharRange(Begin, End), @@ -325,7 +403,10 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, for (unsigned I = 0; I < NumArgs; ++I) { const ParmVarDecl *PVD = Callee->getParamDecl(I); const IdentifierInfo *II = PVD->getIdentifier(); - if (!II) + if (!II || llvm::any_of(IgnoredParameterNameRegexes, + [II](const llvm::Regex &Regex) { + return Regex.match(II->getName()); + })) continue; // Don't warn on arguments for parameters instantiated from template // parameter packs. If we find more arguments than the template @@ -345,9 +426,11 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, Comments = utils::lexer::getTrailingCommentsInRange( BeforeArgument, Ctx->getSourceManager(), Ctx->getLangOpts()); } else { - // Fall back to parsing back from the start of the argument. + // Fall back to parsing back from the start of the argument. The range + // is empty because a range that ends inside a macro expansion, such as + // the `)` of `NULL`, has no file range. const CharSourceRange ArgsRange = - MakeFileCharRange(Args[I]->getBeginLoc(), Args[I]->getEndLoc()); + MakeFileCharRange(Args[I]->getBeginLoc(), Args[I]->getBeginLoc()); Comments = getCommentsBeforeLoc(Ctx, ArgsRange.getBegin()); } @@ -377,17 +460,22 @@ void ArgumentCommentCheck::checkCallArgs(ASTContext *Ctx, // If the argument comments are missing for configured argument kinds, add // them. - const CommentKind Kind = shouldAddComment(Args[I]); - if (Comments.empty() && Kind != CommentKind::None) { + if (!AddMissingComments || !Comments.empty()) + continue; + const SourceLocation ArgLoc = + getWrittenArgLoc(Args[I], CloseLoc, SM, Ctx->getLangOpts()); + if (ArgLoc.isInvalid()) + continue; + const CommentKind Kind = shouldAddComment(Args[I], *Ctx); + if (Kind != CommentKind::None) { SmallString<32> ArgComment; llvm::Twine(llvm::Twine("/*") + II->getName() + "=*/") .toStringRef(ArgComment); const DiagnosticBuilder Diag = - diag(Args[I]->getBeginLoc(), - "argument comment missing for %select{literal argument|" - "argument}0 %1") + diag(ArgLoc, "argument comment missing for %select{literal argument|" + "argument}0 %1") << (Kind == CommentKind::Literal ? 0 : 1) << II - << FixItHint::CreateInsertion(Args[I]->getBeginLoc(), ArgComment); + << FixItHint::CreateInsertion(ArgLoc, ArgComment); } } } @@ -400,6 +488,7 @@ void ArgumentCommentCheck::check(const MatchFinder::MatchResult &Result) { return; checkCallArgs(Result.Context, Callee, Call->getCallee()->getEndLoc(), + Call->getEndLoc(), llvm::ArrayRef(Call->getArgs(), Call->getNumArgs())); } else { const auto *Construct = cast<CXXConstructExpr>(E); @@ -410,7 +499,7 @@ void ArgumentCommentCheck::check(const MatchFinder::MatchResult &Result) { } checkCallArgs( Result.Context, Construct->getConstructor(), - Construct->getParenOrBraceRange().getBegin(), + Construct->getParenOrBraceRange().getBegin(), Construct->getEndLoc(), llvm::ArrayRef(Construct->getArgs(), Construct->getNumArgs())); } } diff --git a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.h b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.h index 3bed1ad4247e5b..143db4f6fd1c96 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.h +++ b/clang-tools-extra/clang-tidy/bugprone/ArgumentCommentCheck.h @@ -47,6 +47,7 @@ class ArgumentCommentCheck : public ClangTidyCheck { }; const unsigned StrictMode : 1; + const unsigned IgnoreMacros : 1; const unsigned IgnoreSingleArgument : 1; const unsigned CommentAnonymousInitLists : 1; const unsigned CommentBoolLiterals : 1; @@ -58,13 +59,18 @@ class ArgumentCommentCheck : public ClangTidyCheck { const unsigned CommentStringLiterals : 1; const unsigned CommentTypedInitLists : 1; const unsigned CommentUserDefinedLiterals : 1; + const unsigned CommentZeroIntegerLiterals : 1; + const std::vector<StringRef> NullPtrMacros; + const std::vector<StringRef> BoolLiteralMacros; + const std::vector<StringRef> IgnoredParameterNames; + std::vector<llvm::Regex> IgnoredParameterNameRegexes; llvm::Regex IdentRE; void checkCallArgs(ASTContext *Ctx, const FunctionDecl *Callee, - SourceLocation ArgBeginLoc, + SourceLocation ArgBeginLoc, SourceLocation CloseLoc, llvm::ArrayRef<const Expr *> Args); - CommentKind shouldAddComment(const Expr *Arg) const; + CommentKind shouldAddComment(const Expr *Arg, const ASTContext &Ctx) const; }; } // namespace clang::tidy::bugprone diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md index 679ca9ecbb4a39..c1ff3200312b00 100644 --- a/clang-tools-extra/docs/ReleaseNotes.md +++ b/clang-tools-extra/docs/ReleaseNotes.md @@ -184,6 +184,19 @@ infrastructure are described first, followed by tool-specific sections. #### Changes in existing checks +- Improved {doc}`bugprone-argument-comment + <clang-tidy/checks/bugprone/argument-comment>` check by adding the + {option}`IgnoreMacros` option. Set it to `false` to add missing comments to + calls in a macro argument, such as `ASSERT(f(0))`. {option}`CommentNullPtrs` + and {option}`CommentBoolLiterals` also match the `NULL`, `true` and `false` + macros, in C and C++. The {option}`NullPtrMacros` and + {option}`BoolLiteralMacros` options configure the macro names. The check also + compares comments before an argument that follows a multi-token macro, such + as `NULL`, with the parameter name. Added the + {option}`CommentZeroIntegerLiterals` option to only add missing comments to + integer literals with the value zero, and the {option}`IgnoredParameterNames` + option to skip parameters by name. + - Improved {doc}`bugprone-assignment-in-if-condition <clang-tidy/checks/bugprone/assignment-in-if-condition>` check by ignoring assignments inside GNU statement expressions unless they form the value of diff --git a/clang-tools-extra/docs/clang-tidy/checks/bugprone/argument-comment.md b/clang-tools-extra/docs/clang-tidy/checks/bugprone/argument-comment.md index 68f7a6eb7a260f..f10145ba7cce00 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/bugprone/argument-comment.md +++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/argument-comment.md @@ -29,10 +29,26 @@ underscores and case when comparing names -- otherwise they are taken into account. Default is `false`. ``` +```{option} IgnoreMacros +When `false`, the check also adds missing comments to calls in a macro +argument, such as `ASSERT(f(0))`. It never adds them to calls in a macro body, +or to arguments that you pass through another macro, such as `f(ID(0))`. The +check compares argument comments with parameter names regardless of this +option. Default is `true`. +``` + ```{option} IgnoreSingleArgument When `true`, the check will ignore the single argument. Default is `false`. ``` +```{option} IgnoredParameterNames +A semicolon-separated list of regular expressions for the parameter names that +the check skips. The check neither compares the argument comment of a matching +parameter nor adds a missing comment for it. A regular expression matches +anywhere in the name unless you anchor it. Use the option for names that say +nothing about the parameter, such as `^[a-z]$;^arg[0-9]*$`. Default is empty. +``` + ```{option} CommentAnonymousInitLists When `true`, the check will add argument comments in the format `/*ParameterName=*/` right before anonymous braced-init list arguments @@ -57,8 +73,8 @@ foo(/*Dims=*/{}); ```{option} CommentBoolLiterals When `true`, the check will add argument comments in the format -`/*ParameterName=*/` right before the boolean literal argument. -Default is `false`. +`/*ParameterName=*/` right before the boolean literal argument and the macros +in {option}`BoolLiteralMacros`. Default is `false`. ``` Before: @@ -145,8 +161,8 @@ foo(/*MeaningOfLife=*/42); ```{option} CommentNullPtrs When `true`, the check will add argument comments in the format -`/*ParameterName=*/` right before the nullptr literal argument. -Default is `false`. +`/*ParameterName=*/` right before the nullptr literal argument and the macros +in {option}`NullPtrMacros`. Default is `false`. ``` Before: @@ -272,3 +288,41 @@ double operator"" _km(long double); foo(/*Distance=*/402.0_km); ``` + +```{option} CommentZeroIntegerLiterals +When `true`, the check will add argument comments in the format +`/*ParameterName=*/` right before integer literal arguments with the value +zero, which often stands for "none" or "default". This option has no effect +when {option}`CommentIntegerLiterals` is `true`. Default is `false`. +``` + +Before: + +```c +int open_file(const char *Path, int Flags); + +open_file(Path, 0); +open_file(Path, 1); +``` + +After: + +```c +int open_file(const char *Path, int Flags); + +open_file(Path, /*Flags=*/0); +open_file(Path, 1); +``` + +```{option} NullPtrMacros +A semicolon-separated list of macros that {option}`CommentNullPtrs` treats like +`nullptr`. The check only matches an argument that is exactly one of these +macros. Default is `NULL`. +``` + +```{option} BoolLiteralMacros +A semicolon-separated list of macros that {option}`CommentBoolLiterals` treats +like boolean literals. The check only matches an argument that is exactly one +of these macros. Default is `true;false`, which covers `<stdbool.h>` in C +before C23 and in GNU C++98. +``` diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/argument-comment-c.c b/clang-tools-extra/test/clang-tidy/checkers/bugprone/argument-comment-c.c new file mode 100644 index 00000000000000..63119c2259518e --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/argument-comment-c.c @@ -0,0 +1,52 @@ +// RUN: %check_clang_tidy %s bugprone-argument-comment %t -- \ +// RUN: -config="{CheckOptions: { \ +// RUN: bugprone-argument-comment.CommentBoolLiterals: true, \ +// RUN: bugprone-argument-comment.CommentNullPtrs: true, \ +// RUN: bugprone-argument-comment.IgnoreMacros: false}}" -- + +#include <stdbool.h> +#include <stddef.h> + +#define CHECK(e) do { (void)(e); } while (0) +#define ID(x) x +#define MY_NULL NULL +#define MY_TRUE true +#define CALL_F f(NULL, true) + +int f(const char *path, bool force); +int h(const char *path, const char *root); + +void test(void) { + f(NULL, false); + // CHECK-MESSAGES: [[@LINE-1]]:5: warning: argument comment missing for literal argument 'path' [bugprone-argument-comment] + // CHECK-MESSAGES: [[@LINE-2]]:11: warning: argument comment missing for literal argument 'force' [bugprone-argument-comment] + // CHECK-FIXES: f(/*path=*/NULL, /*force=*/false); + f(/*path=*/NULL, /*force=*/false); + f(/* path= */ NULL, /* force= */ true); + + CHECK(f(NULL, true)); + // CHECK-MESSAGES: [[@LINE-1]]:11: warning: argument comment missing for literal argument 'path' [bugprone-argument-comment] + // CHECK-MESSAGES: [[@LINE-2]]:17: warning: argument comment missing for literal argument 'force' [bugprone-argument-comment] + // CHECK-FIXES: CHECK(f(/*path=*/NULL, /*force=*/true)); + CHECK(f(/*path=*/NULL, /*force=*/true)); + + h(NULL, NULL); + // CHECK-MESSAGES: [[@LINE-1]]:5: warning: argument comment missing for literal argument 'path' [bugprone-argument-comment] + // CHECK-MESSAGES: [[@LINE-2]]:11: warning: argument comment missing for literal argument 'root' [bugprone-argument-comment] + // CHECK-FIXES: h(/*path=*/NULL, /*root=*/NULL); + h(/*path=*/NULL, /*root=*/NULL); + CHECK(h(/* path= */ NULL, /* root= */ NULL)); + + h(NULL, /*rot=*/NULL); + //... [truncated] `````````` </details> https://github.com/llvm/llvm-project/pull/237623 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
