| 1 | //===--- UseStdPrintCheck.cpp - clang-tidy-----------------------*- C++ -*-===// |
| 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 | |
| 9 | #include "UseStdPrintCheck.h" |
| 10 | #include "../utils/FormatStringConverter.h" |
| 11 | #include "../utils/Matchers.h" |
| 12 | #include "../utils/OptionsUtils.h" |
| 13 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| 14 | #include "clang/Lex/Lexer.h" |
| 15 | |
| 16 | using namespace clang::ast_matchers; |
| 17 | |
| 18 | namespace clang::tidy::modernize { |
| 19 | |
| 20 | namespace { |
| 21 | AST_MATCHER(StringLiteral, isOrdinary) { return Node.isOrdinary(); } |
| 22 | } // namespace |
| 23 | |
| 24 | UseStdPrintCheck::UseStdPrintCheck(StringRef Name, ClangTidyContext *Context) |
| 25 | : ClangTidyCheck(Name, Context), PP(nullptr), |
| 26 | StrictMode(Options.getLocalOrGlobal(LocalName: "StrictMode" , Default: false)), |
| 27 | PrintfLikeFunctions(utils::options::parseStringList( |
| 28 | Option: Options.get(LocalName: "PrintfLikeFunctions" , Default: "" ))), |
| 29 | FprintfLikeFunctions(utils::options::parseStringList( |
| 30 | Option: Options.get(LocalName: "FprintfLikeFunctions" , Default: "" ))), |
| 31 | ReplacementPrintFunction( |
| 32 | Options.get(LocalName: "ReplacementPrintFunction" , Default: "std::print" )), |
| 33 | ReplacementPrintlnFunction( |
| 34 | Options.get(LocalName: "ReplacementPrintlnFunction" , Default: "std::println" )), |
| 35 | IncludeInserter(Options.getLocalOrGlobal(LocalName: "IncludeStyle" , |
| 36 | Default: utils::IncludeSorter::IS_LLVM), |
| 37 | areDiagsSelfContained()), |
| 38 | MaybeHeaderToInclude(Options.get(LocalName: "PrintHeader" )) { |
| 39 | |
| 40 | if (PrintfLikeFunctions.empty() && FprintfLikeFunctions.empty()) { |
| 41 | PrintfLikeFunctions.emplace_back(args: "::printf" ); |
| 42 | PrintfLikeFunctions.emplace_back(args: "absl::PrintF" ); |
| 43 | FprintfLikeFunctions.emplace_back(args: "::fprintf" ); |
| 44 | FprintfLikeFunctions.emplace_back(args: "absl::FPrintF" ); |
| 45 | } |
| 46 | |
| 47 | if (!MaybeHeaderToInclude && (ReplacementPrintFunction == "std::print" || |
| 48 | ReplacementPrintlnFunction == "std::println" )) |
| 49 | MaybeHeaderToInclude = "<print>" ; |
| 50 | } |
| 51 | |
| 52 | void UseStdPrintCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { |
| 53 | using utils::options::serializeStringList; |
| 54 | Options.store(Options&: Opts, LocalName: "StrictMode" , Value: StrictMode); |
| 55 | Options.store(Options&: Opts, LocalName: "PrintfLikeFunctions" , |
| 56 | Value: serializeStringList(Strings: PrintfLikeFunctions)); |
| 57 | Options.store(Options&: Opts, LocalName: "FprintfLikeFunctions" , |
| 58 | Value: serializeStringList(Strings: FprintfLikeFunctions)); |
| 59 | Options.store(Options&: Opts, LocalName: "ReplacementPrintFunction" , Value: ReplacementPrintFunction); |
| 60 | Options.store(Options&: Opts, LocalName: "ReplacementPrintlnFunction" , Value: ReplacementPrintlnFunction); |
| 61 | Options.store(Options&: Opts, LocalName: "IncludeStyle" , Value: IncludeInserter.getStyle()); |
| 62 | if (MaybeHeaderToInclude) |
| 63 | Options.store(Options&: Opts, LocalName: "PrintHeader" , Value: *MaybeHeaderToInclude); |
| 64 | } |
| 65 | |
| 66 | void UseStdPrintCheck::registerPPCallbacks(const SourceManager &SM, |
| 67 | Preprocessor *PP, |
| 68 | Preprocessor *ModuleExpanderPP) { |
| 69 | IncludeInserter.registerPreprocessor(PP); |
| 70 | this->PP = PP; |
| 71 | } |
| 72 | |
| 73 | static clang::ast_matchers::StatementMatcher |
| 74 | unusedReturnValue(clang::ast_matchers::StatementMatcher MatchedCallExpr) { |
| 75 | auto UnusedInCompoundStmt = |
| 76 | compoundStmt(forEach(MatchedCallExpr), |
| 77 | // The checker can't currently differentiate between the |
| 78 | // return statement and other statements inside GNU statement |
| 79 | // expressions, so disable the checker inside them to avoid |
| 80 | // false positives. |
| 81 | unless(hasParent(stmtExpr()))); |
| 82 | auto UnusedInIfStmt = |
| 83 | ifStmt(eachOf(hasThen(InnerMatcher: MatchedCallExpr), hasElse(InnerMatcher: MatchedCallExpr))); |
| 84 | auto UnusedInWhileStmt = whileStmt(hasBody(InnerMatcher: MatchedCallExpr)); |
| 85 | auto UnusedInDoStmt = doStmt(hasBody(InnerMatcher: MatchedCallExpr)); |
| 86 | auto UnusedInForStmt = |
| 87 | forStmt(eachOf(hasLoopInit(InnerMatcher: MatchedCallExpr), |
| 88 | hasIncrement(InnerMatcher: MatchedCallExpr), hasBody(InnerMatcher: MatchedCallExpr))); |
| 89 | auto UnusedInRangeForStmt = cxxForRangeStmt(hasBody(InnerMatcher: MatchedCallExpr)); |
| 90 | auto UnusedInCaseStmt = switchCase(forEach(MatchedCallExpr)); |
| 91 | |
| 92 | return stmt(anyOf(UnusedInCompoundStmt, UnusedInIfStmt, UnusedInWhileStmt, |
| 93 | UnusedInDoStmt, UnusedInForStmt, UnusedInRangeForStmt, |
| 94 | UnusedInCaseStmt)); |
| 95 | } |
| 96 | |
| 97 | void UseStdPrintCheck::registerMatchers(MatchFinder *Finder) { |
| 98 | if (!PrintfLikeFunctions.empty()) |
| 99 | Finder->addMatcher( |
| 100 | NodeMatch: unusedReturnValue( |
| 101 | MatchedCallExpr: callExpr(argumentCountAtLeast(N: 1), |
| 102 | hasArgument(N: 0, InnerMatcher: stringLiteral(isOrdinary())), |
| 103 | callee(InnerMatcher: functionDecl(matchers::matchesAnyListedName( |
| 104 | NameList: PrintfLikeFunctions)) |
| 105 | .bind(ID: "func_decl" ))) |
| 106 | .bind(ID: "printf" )), |
| 107 | Action: this); |
| 108 | |
| 109 | if (!FprintfLikeFunctions.empty()) |
| 110 | Finder->addMatcher( |
| 111 | NodeMatch: unusedReturnValue( |
| 112 | MatchedCallExpr: callExpr(argumentCountAtLeast(N: 2), |
| 113 | hasArgument(N: 1, InnerMatcher: stringLiteral(isOrdinary())), |
| 114 | callee(InnerMatcher: functionDecl(matchers::matchesAnyListedName( |
| 115 | NameList: FprintfLikeFunctions)) |
| 116 | .bind(ID: "func_decl" ))) |
| 117 | .bind(ID: "fprintf" )), |
| 118 | Action: this); |
| 119 | } |
| 120 | |
| 121 | void UseStdPrintCheck::check(const MatchFinder::MatchResult &Result) { |
| 122 | unsigned FormatArgOffset = 0; |
| 123 | const auto *OldFunction = Result.Nodes.getNodeAs<FunctionDecl>(ID: "func_decl" ); |
| 124 | const auto *Printf = Result.Nodes.getNodeAs<CallExpr>(ID: "printf" ); |
| 125 | if (!Printf) { |
| 126 | Printf = Result.Nodes.getNodeAs<CallExpr>(ID: "fprintf" ); |
| 127 | FormatArgOffset = 1; |
| 128 | } |
| 129 | |
| 130 | utils::FormatStringConverter::Configuration ConverterConfig; |
| 131 | ConverterConfig.StrictMode = StrictMode; |
| 132 | ConverterConfig.AllowTrailingNewlineRemoval = true; |
| 133 | assert(PP && "Preprocessor should be set by registerPPCallbacks" ); |
| 134 | utils::FormatStringConverter Converter( |
| 135 | Result.Context, Printf, FormatArgOffset, ConverterConfig, getLangOpts(), |
| 136 | *Result.SourceManager, *PP); |
| 137 | const Expr *PrintfCall = Printf->getCallee(); |
| 138 | const StringRef ReplacementFunction = Converter.usePrintNewlineFunction() |
| 139 | ? ReplacementPrintlnFunction |
| 140 | : ReplacementPrintFunction; |
| 141 | if (!Converter.canApply()) { |
| 142 | diag(PrintfCall->getBeginLoc(), |
| 143 | "unable to use '%0' instead of %1 because %2" ) |
| 144 | << PrintfCall->getSourceRange() << ReplacementFunction |
| 145 | << OldFunction->getIdentifier() |
| 146 | << Converter.conversionNotPossibleReason(); |
| 147 | return; |
| 148 | } |
| 149 | |
| 150 | DiagnosticBuilder Diag = |
| 151 | diag(PrintfCall->getBeginLoc(), "use '%0' instead of %1" ) |
| 152 | << ReplacementFunction << OldFunction->getIdentifier(); |
| 153 | |
| 154 | Diag << FixItHint::CreateReplacement( |
| 155 | CharSourceRange::getTokenRange(PrintfCall->getExprLoc(), |
| 156 | PrintfCall->getEndLoc()), |
| 157 | ReplacementFunction); |
| 158 | Converter.applyFixes(Diag, SM&: *Result.SourceManager); |
| 159 | |
| 160 | if (MaybeHeaderToInclude) |
| 161 | Diag << IncludeInserter.createIncludeInsertion( |
| 162 | FileID: Result.Context->getSourceManager().getFileID(PrintfCall->getBeginLoc()), |
| 163 | Header: *MaybeHeaderToInclude); |
| 164 | } |
| 165 | |
| 166 | } // namespace clang::tidy::modernize |
| 167 | |