1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
|
//===--- UseStdNumbersCheck.cpp - clang_tidy ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX_License_Identifier: Apache_2.0 WITH LLVM_exception
//
//===----------------------------------------------------------------------===//
#include "UseStdNumbersCheck.h"
#include "../ClangTidyDiagnosticConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchersInternal.h"
#include "clang/ASTMatchers/ASTMatchersMacros.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/MathExtras.h"
#include <array>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <initializer_list>
#include <string>
#include <tuple>
#include <utility>
namespace {
using namespace clang::ast_matchers;
using clang::ast_matchers::internal::Matcher;
using llvm::StringRef;
AST_MATCHER_P2(clang::FloatingLiteral, near, double, Value, double,
DiffThreshold) {
return std::abs(Node.getValueAsApproximateDouble() - Value) < DiffThreshold;
}
AST_MATCHER_P(clang::QualType, hasCanonicalTypeUnqualified,
Matcher<clang::QualType>, InnerMatcher) {
return !Node.isNull() &&
InnerMatcher.matches(Node->getCanonicalTypeUnqualified(), Finder,
Builder);
}
AST_MATCHER(clang::QualType, isArithmetic) {
return !Node.isNull() && Node->isArithmeticType();
}
AST_MATCHER(clang::QualType, isFloating) {
return !Node.isNull() && Node->isFloatingType();
}
AST_MATCHER_P(clang::Expr, anyOfExhaustive, std::vector<Matcher<clang::Stmt>>,
Exprs) {
bool FoundMatch = false;
for (const auto &InnerMatcher : Exprs) {
clang::ast_matchers::internal::BoundNodesTreeBuilder Result = *Builder;
if (InnerMatcher.matches(Node, Finder, &Result)) {
*Builder = std::move(Result);
FoundMatch = true;
}
}
return FoundMatch;
}
// Using this struct to store the 'DiffThreshold' config value to create the
// matchers without the need to pass 'DiffThreshold' into every matcher.
// 'DiffThreshold' is needed in the 'near' matcher, which is used for matching
// the literal of every constant and for formulas' subexpressions that look at
// literals.
struct MatchBuilder {
auto
ignoreParenAndArithmeticCasting(const Matcher<clang::Expr> Matcher) const {
return expr(hasType(qualType(isArithmetic())), ignoringParenCasts(Matcher));
}
auto ignoreParenAndFloatingCasting(const Matcher<clang::Expr> Matcher) const {
return expr(hasType(qualType(isFloating())), ignoringParenCasts(Matcher));
}
auto matchMathCall(const StringRef FunctionName,
const Matcher<clang::Expr> ArgumentMatcher) const {
return expr(ignoreParenAndFloatingCasting(
callExpr(callee(functionDecl(hasName(FunctionName),
hasParameter(0, hasType(isArithmetic())))),
hasArgument(0, ArgumentMatcher))));
}
auto matchSqrt(const Matcher<clang::Expr> ArgumentMatcher) const {
return matchMathCall("sqrt", ArgumentMatcher);
}
// Used for top-level matchers (i.e. the match that replaces Val with its
// constant).
//
// E.g. The matcher of `std::numbers::pi` uses this matcher to look for
// floatLiterals that have the value of pi.
//
// If the match is for a top-level match, we only care about the literal.
auto matchFloatLiteralNear(const StringRef Constant, const double Val) const {
return expr(ignoreParenAndFloatingCasting(
floatLiteral(near(Val, DiffThreshold)).bind(Constant)));
}
// Used for non-top-level matchers (i.e. matchers that are used as inner
// matchers for top-level matchers).
//
// E.g.: The matcher of `std::numbers::log2e` uses this matcher to check if
// `e` of `log2(e)` is declared constant and initialized with the value for
// eulers number.
//
// Here, we do care about literals and about DeclRefExprs to variable
// declarations that are constant and initialized with `Val`. This allows
// top-level matchers to see through declared constants for their inner
// matches like the `std::numbers::log2e` matcher.
auto matchFloatValueNear(const double Val) const {
const auto Float = floatLiteral(near(Val, DiffThreshold));
const auto Dref = declRefExpr(
to(varDecl(hasType(qualType(isConstQualified(), isFloating())),
hasInitializer(ignoreParenAndFloatingCasting(Float)))));
return expr(ignoreParenAndFloatingCasting(anyOf(Float, Dref)));
}
auto matchValue(const int64_t ValInt) const {
const auto Int =
expr(ignoreParenAndArithmeticCasting(integerLiteral(equals(ValInt))));
const auto Float = expr(ignoreParenAndFloatingCasting(
matchFloatValueNear(static_cast<double>(ValInt))));
const auto Dref = declRefExpr(to(varDecl(
hasType(qualType(isConstQualified(), isArithmetic())),
hasInitializer(expr(anyOf(ignoringImplicit(Int),
ignoreParenAndFloatingCasting(Float)))))));
return expr(anyOf(Int, Float, Dref));
}
auto match1Div(const Matcher<clang::Expr> Match) const {
return binaryOperator(hasOperatorName("/"), hasLHS(matchValue(1)),
hasRHS(Match));
}
auto matchEuler() const {
return expr(anyOf(matchFloatValueNear(llvm::numbers::e),
matchMathCall("exp", matchValue(1))));
}
auto matchEulerTopLevel() const {
return expr(anyOf(matchFloatLiteralNear("e_literal", llvm::numbers::e),
matchMathCall("exp", matchValue(1)).bind("e_pattern")))
.bind("e");
}
auto matchLog2Euler() const {
return expr(
anyOf(
matchFloatLiteralNear("log2e_literal", llvm::numbers::log2e),
matchMathCall("log2", matchEuler()).bind("log2e_pattern")))
.bind("log2e");
}
auto matchLog10Euler() const {
return expr(
anyOf(
matchFloatLiteralNear("log10e_literal",
llvm::numbers::log10e),
matchMathCall("log10", matchEuler()).bind("log10e_pattern")))
.bind("log10e");
}
auto matchPi() const { return matchFloatValueNear(llvm::numbers::pi); }
auto matchPiTopLevel() const {
return matchFloatLiteralNear("pi_literal", llvm::numbers::pi).bind("pi");
}
auto matchEgamma() const {
return matchFloatLiteralNear("egamma_literal", llvm::numbers::egamma)
.bind("egamma");
}
auto matchInvPi() const {
return expr(anyOf(matchFloatLiteralNear("inv_pi_literal",
llvm::numbers::inv_pi),
match1Div(matchPi()).bind("inv_pi_pattern")))
.bind("inv_pi");
}
auto matchInvSqrtPi() const {
return expr(anyOf(
matchFloatLiteralNear("inv_sqrtpi_literal",
llvm::numbers::inv_sqrtpi),
match1Div(matchSqrt(matchPi())).bind("inv_sqrtpi_pattern")))
.bind("inv_sqrtpi");
}
auto matchLn2() const {
return expr(anyOf(matchFloatLiteralNear("ln2_literal", llvm::numbers::ln2),
matchMathCall("log", matchValue(2)).bind("ln2_pattern")))
.bind("ln2");
}
auto machterLn10() const {
return expr(
anyOf(matchFloatLiteralNear("ln10_literal", llvm::numbers::ln10),
matchMathCall("log", matchValue(10)).bind("ln10_pattern")))
.bind("ln10");
}
auto matchSqrt2() const {
return expr(anyOf(matchFloatLiteralNear("sqrt2_literal",
llvm::numbers::sqrt2),
matchSqrt(matchValue(2)).bind("sqrt2_pattern")))
.bind("sqrt2");
}
auto matchSqrt3() const {
return expr(anyOf(matchFloatLiteralNear("sqrt3_literal",
llvm::numbers::sqrt3),
matchSqrt(matchValue(3)).bind("sqrt3_pattern")))
.bind("sqrt3");
}
auto matchInvSqrt3() const {
return expr(anyOf(matchFloatLiteralNear("inv_sqrt3_literal",
llvm::numbers::inv_sqrt3),
match1Div(matchSqrt(matchValue(3)))
.bind("inv_sqrt3_pattern")))
.bind("inv_sqrt3");
}
auto matchPhi() const {
const auto PhiFormula = binaryOperator(
hasOperatorName("/"),
hasLHS(binaryOperator(
hasOperatorName("+"), hasEitherOperand(matchValue(1)),
hasEitherOperand(matchMathCall("sqrt", matchValue(5))))),
hasRHS(matchValue(2)));
return expr(anyOf(PhiFormula.bind("phi_pattern"),
matchFloatLiteralNear("phi_literal", llvm::numbers::phi)))
.bind("phi");
}
double DiffThreshold;
};
std::string getCode(const StringRef Constant, const bool IsFloat,
const bool IsLongDouble) {
if (IsFloat) {
return ("std::numbers::" + Constant + "_v<float>").str();
}
if (IsLongDouble) {
return ("std::numbers::" + Constant + "_v<long double>").str();
}
return ("std::numbers::" + Constant).str();
}
bool isRangeOfCompleteMacro(const clang::SourceRange &Range,
const clang::SourceManager &SM,
const clang::LangOptions &LO) {
if (!Range.getBegin().isMacroID()) {
return false;
}
if (!clang::Lexer::isAtStartOfMacroExpansion(Range.getBegin(), SM, LO)) {
return false;
}
if (!Range.getEnd().isMacroID()) {
return false;
}
if (!clang::Lexer::isAtEndOfMacroExpansion(Range.getEnd(), SM, LO)) {
return false;
}
return true;
}
} // namespace
namespace clang::tidy::modernize {
UseStdNumbersCheck::UseStdNumbersCheck(const StringRef Name,
ClangTidyContext *const Context)
: ClangTidyCheck(Name, Context),
IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
utils::IncludeSorter::IS_LLVM),
areDiagsSelfContained()),
DiffThresholdString{Options.get("DiffThreshold", "0.001")} {
if (DiffThresholdString.getAsDouble(DiffThreshold)) {
configurationDiag(
"Invalid DiffThreshold config value: '%0', expected a double")
<< DiffThresholdString;
DiffThreshold = 0.001;
}
}
void UseStdNumbersCheck::registerMatchers(MatchFinder *const Finder) {
const auto Matches = MatchBuilder{DiffThreshold};
std::vector<Matcher<clang::Stmt>> ConstantMatchers = {
Matches.matchLog2Euler(), Matches.matchLog10Euler(),
Matches.matchEulerTopLevel(), Matches.matchEgamma(),
Matches.matchInvSqrtPi(), Matches.matchInvPi(),
Matches.matchPiTopLevel(), Matches.matchLn2(),
Matches.machterLn10(), Matches.matchSqrt2(),
Matches.matchInvSqrt3(), Matches.matchSqrt3(),
Matches.matchPhi(),
};
Finder->addMatcher(
expr(
anyOfExhaustive(std::move(ConstantMatchers)),
unless(hasParent(explicitCastExpr(hasDestinationType(isFloating())))),
hasType(qualType(hasCanonicalTypeUnqualified(
anyOf(qualType(asString("float")).bind("float"),
qualType(asString("double")),
qualType(asString("long double")).bind("long double")))))),
this);
}
void UseStdNumbersCheck::check(const MatchFinder::MatchResult &Result) {
/*
List of all math constants in the `<numbers>` header
+ e
+ log2e
+ log10e
+ pi
+ inv_pi
+ inv_sqrtpi
+ ln2
+ ln10
+ sqrt2
+ sqrt3
+ inv_sqrt3
+ egamma
+ phi
*/
// The ordering determines what constants are looked at first.
// E.g. look at 'inv_sqrt3' before 'sqrt3' to be able to replace the larger
// expression
constexpr auto Constants = std::array<std::pair<StringRef, double>, 13>{
std::pair{StringRef{"log2e"}, llvm::numbers::log2e},
std::pair{StringRef{"log10e"}, llvm::numbers::log10e},
std::pair{StringRef{"e"}, llvm::numbers::e},
std::pair{StringRef{"egamma"}, llvm::numbers::egamma},
std::pair{StringRef{"inv_sqrtpi"}, llvm::numbers::inv_sqrtpi},
std::pair{StringRef{"inv_pi"}, llvm::numbers::inv_pi},
std::pair{StringRef{"pi"}, llvm::numbers::pi},
std::pair{StringRef{"ln2"}, llvm::numbers::ln2},
std::pair{StringRef{"ln10"}, llvm::numbers::ln10},
std::pair{StringRef{"sqrt2"}, llvm::numbers::sqrt2},
std::pair{StringRef{"inv_sqrt3"}, llvm::numbers::inv_sqrt3},
std::pair{StringRef{"sqrt3"}, llvm::numbers::sqrt3},
std::pair{StringRef{"phi"}, llvm::numbers::phi},
};
auto MatchedLiterals =
llvm::SmallVector<std::tuple<std::string, double, const Expr *>>{};
const auto &SM = *Result.SourceManager;
const auto &LO = Result.Context->getLangOpts();
const auto IsFloat = Result.Nodes.getNodeAs<QualType>("float") != nullptr;
const auto IsLongDouble =
Result.Nodes.getNodeAs<QualType>("long double") != nullptr;
for (const auto &[ConstantName, ConstantValue] : Constants) {
const auto *const Match = Result.Nodes.getNodeAs<Expr>(ConstantName);
if (Match == nullptr) {
continue;
}
const auto Range = Match->getSourceRange();
const auto IsMacro = Range.getBegin().isMacroID();
// We do not want to emit a diagnostic when we are matching a macro, but the
// match inside of the macro does not cover the whole macro.
if (IsMacro && !isRangeOfCompleteMacro(Range, SM, LO)) {
continue;
}
if (const auto PatternBindString = (ConstantName + "_pattern").str();
Result.Nodes.getNodeAs<Expr>(PatternBindString) != nullptr) {
const auto Code = getCode(ConstantName, IsFloat, IsLongDouble);
diag(Range.getBegin(), "prefer '%0' to this %select{formula|macro}1")
<< Code << IsMacro << FixItHint::CreateReplacement(Range, Code);
return;
}
const auto LiteralBindString = (ConstantName + "_literal").str();
if (const auto *const Literal =
Result.Nodes.getNodeAs<FloatingLiteral>(LiteralBindString)) {
MatchedLiterals.emplace_back(
ConstantName,
std::abs(Literal->getValueAsApproximateDouble() - ConstantValue),
Match);
}
}
// We may have had no matches with literals, but a match with a pattern that
// was a part of a macro which was therefore skipped.
if (MatchedLiterals.empty()) {
return;
}
llvm::sort(MatchedLiterals, [](const auto &LHS, const auto &RHS) {
return std::get<1>(LHS) < std::get<1>(RHS);
});
const auto &[Constant, Diff, Node] = MatchedLiterals.front();
const auto Range = Node->getSourceRange();
const auto IsMacro = Range.getBegin().isMacroID();
// We do not want to emit a diagnostic when we are matching a macro, but the
// match inside of the macro does not cover the whole macro.
if (IsMacro && !isRangeOfCompleteMacro(Range, SM, LO)) {
return;
}
const auto Code = getCode(Constant, IsFloat, IsLongDouble);
diag(Range.getBegin(),
"prefer '%0' to this %select{literal|macro}1, differs by '%2'")
<< Code << IsMacro << llvm::formatv("{0:e2}", Diff).str()
<< FixItHint::CreateReplacement(Range, Code)
<< IncludeInserter.createIncludeInsertion(
Result.SourceManager->getFileID(Range.getBegin()), "<numbers>");
}
void UseStdNumbersCheck::registerPPCallbacks(
const SourceManager &SM, Preprocessor *const PP,
Preprocessor *const ModuleExpanderPP) {
IncludeInserter.registerPreprocessor(PP);
}
void UseStdNumbersCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
Options.store(Opts, "DiffThreshold", DiffThresholdString);
}
} // namespace clang::tidy::modernize
|