1 //===--- MagicNumbersCheck.cpp - clang-tidy-------------------------------===// 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 // A checker for magic numbers: integer or floating point literals embedded 10 // in the code, outside the definition of a constant or an enumeration. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "MagicNumbersCheck.h" 15 #include "../utils/OptionsUtils.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/ASTMatchers/ASTMatchFinder.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include <algorithm> 20 21 using namespace clang::ast_matchers; 22 using namespace clang::ast_type_traits; 23 24 namespace clang { 25 26 static bool isUsedToInitializeAConstant(const MatchFinder::MatchResult &Result, 27 const DynTypedNode &Node) { 28 29 const auto *AsDecl = Node.get<DeclaratorDecl>(); 30 if (AsDecl) { 31 if (AsDecl->getType().isConstQualified()) 32 return true; 33 34 return AsDecl->isImplicit(); 35 } 36 37 if (Node.get<EnumConstantDecl>() != nullptr) 38 return true; 39 40 return llvm::any_of(Result.Context->getParents(Node), 41 [&Result](const DynTypedNode &Parent) { 42 return isUsedToInitializeAConstant(Result, Parent); 43 }); 44 } 45 46 static bool isUsedToDefineABitField(const MatchFinder::MatchResult &Result, 47 const DynTypedNode &Node) { 48 const auto *AsFieldDecl = Node.get<FieldDecl>(); 49 if (AsFieldDecl && AsFieldDecl->isBitField()) 50 return true; 51 52 return llvm::any_of(Result.Context->getParents(Node), 53 [&Result](const DynTypedNode &Parent) { 54 return isUsedToDefineABitField(Result, Parent); 55 }); 56 } 57 58 namespace tidy { 59 namespace readability { 60 61 const char DefaultIgnoredIntegerValues[] = "1;2;3;4;"; 62 const char DefaultIgnoredFloatingPointValues[] = "1.0;100.0;"; 63 64 MagicNumbersCheck::MagicNumbersCheck(StringRef Name, ClangTidyContext *Context) 65 : ClangTidyCheck(Name, Context), 66 IgnoreAllFloatingPointValues( 67 Options.get("IgnoreAllFloatingPointValues", false)), 68 IgnoreBitFieldsWidths(Options.get("IgnoreBitFieldsWidths", true)), 69 IgnorePowersOf2IntegerValues( 70 Options.get("IgnorePowersOf2IntegerValues", false)) { 71 // Process the set of ignored integer values. 72 const std::vector<std::string> IgnoredIntegerValuesInput = 73 utils::options::parseStringList( 74 Options.get("IgnoredIntegerValues", DefaultIgnoredIntegerValues)); 75 IgnoredIntegerValues.resize(IgnoredIntegerValuesInput.size()); 76 llvm::transform(IgnoredIntegerValuesInput, IgnoredIntegerValues.begin(), 77 [](const std::string &Value) { return std::stoll(Value); }); 78 llvm::sort(IgnoredIntegerValues); 79 80 if (!IgnoreAllFloatingPointValues) { 81 // Process the set of ignored floating point values. 82 const std::vector<std::string> IgnoredFloatingPointValuesInput = 83 utils::options::parseStringList(Options.get( 84 "IgnoredFloatingPointValues", DefaultIgnoredFloatingPointValues)); 85 IgnoredFloatingPointValues.reserve(IgnoredFloatingPointValuesInput.size()); 86 IgnoredDoublePointValues.reserve(IgnoredFloatingPointValuesInput.size()); 87 for (const auto &InputValue : IgnoredFloatingPointValuesInput) { 88 llvm::APFloat FloatValue(llvm::APFloat::IEEEsingle()); 89 FloatValue.convertFromString(InputValue, DefaultRoundingMode); 90 IgnoredFloatingPointValues.push_back(FloatValue.convertToFloat()); 91 92 llvm::APFloat DoubleValue(llvm::APFloat::IEEEdouble()); 93 DoubleValue.convertFromString(InputValue, DefaultRoundingMode); 94 IgnoredDoublePointValues.push_back(DoubleValue.convertToDouble()); 95 } 96 llvm::sort(IgnoredFloatingPointValues.begin(), 97 IgnoredFloatingPointValues.end()); 98 llvm::sort(IgnoredDoublePointValues.begin(), 99 IgnoredDoublePointValues.end()); 100 } 101 } 102 103 void MagicNumbersCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { 104 Options.store(Opts, "IgnoredIntegerValues", DefaultIgnoredIntegerValues); 105 Options.store(Opts, "IgnoredFloatingPointValues", 106 DefaultIgnoredFloatingPointValues); 107 } 108 109 void MagicNumbersCheck::registerMatchers(MatchFinder *Finder) { 110 Finder->addMatcher(integerLiteral().bind("integer"), this); 111 if (!IgnoreAllFloatingPointValues) 112 Finder->addMatcher(floatLiteral().bind("float"), this); 113 } 114 115 void MagicNumbersCheck::check(const MatchFinder::MatchResult &Result) { 116 checkBoundMatch<IntegerLiteral>(Result, "integer"); 117 checkBoundMatch<FloatingLiteral>(Result, "float"); 118 } 119 120 bool MagicNumbersCheck::isConstant(const MatchFinder::MatchResult &Result, 121 const Expr &ExprResult) const { 122 return llvm::any_of( 123 Result.Context->getParents(ExprResult), 124 [&Result](const DynTypedNode &Parent) { 125 if (isUsedToInitializeAConstant(Result, Parent)) 126 return true; 127 128 // Ignore this instance, because this match reports the location 129 // where the template is defined, not where it is instantiated. 130 if (Parent.get<SubstNonTypeTemplateParmExpr>()) 131 return true; 132 133 // Don't warn on string user defined literals: 134 // std::string s = "Hello World"s; 135 if (const auto *UDL = Parent.get<UserDefinedLiteral>()) 136 if (UDL->getLiteralOperatorKind() == UserDefinedLiteral::LOK_String) 137 return true; 138 139 return false; 140 }); 141 } 142 143 bool MagicNumbersCheck::isIgnoredValue(const IntegerLiteral *Literal) const { 144 const llvm::APInt IntValue = Literal->getValue(); 145 const int64_t Value = IntValue.getZExtValue(); 146 if (Value == 0) 147 return true; 148 149 if (IgnorePowersOf2IntegerValues && IntValue.isPowerOf2()) 150 return true; 151 152 return std::binary_search(IgnoredIntegerValues.begin(), 153 IgnoredIntegerValues.end(), Value); 154 } 155 156 bool MagicNumbersCheck::isIgnoredValue(const FloatingLiteral *Literal) const { 157 const llvm::APFloat FloatValue = Literal->getValue(); 158 if (FloatValue.isZero()) 159 return true; 160 161 if (&FloatValue.getSemantics() == &llvm::APFloat::IEEEsingle()) { 162 const float Value = FloatValue.convertToFloat(); 163 return std::binary_search(IgnoredFloatingPointValues.begin(), 164 IgnoredFloatingPointValues.end(), Value); 165 } 166 167 if (&FloatValue.getSemantics() == &llvm::APFloat::IEEEdouble()) { 168 const double Value = FloatValue.convertToDouble(); 169 return std::binary_search(IgnoredDoublePointValues.begin(), 170 IgnoredDoublePointValues.end(), Value); 171 } 172 173 return false; 174 } 175 176 bool MagicNumbersCheck::isSyntheticValue(const SourceManager *SourceManager, 177 const IntegerLiteral *Literal) const { 178 const std::pair<FileID, unsigned> FileOffset = 179 SourceManager->getDecomposedLoc(Literal->getLocation()); 180 if (FileOffset.first.isInvalid()) 181 return false; 182 183 const StringRef BufferIdentifier = 184 SourceManager->getBuffer(FileOffset.first)->getBufferIdentifier(); 185 186 return BufferIdentifier.empty(); 187 } 188 189 bool MagicNumbersCheck::isBitFieldWidth( 190 const clang::ast_matchers::MatchFinder::MatchResult &Result, 191 const IntegerLiteral &Literal) const { 192 return IgnoreBitFieldsWidths && 193 llvm::any_of(Result.Context->getParents(Literal), 194 [&Result](const DynTypedNode &Parent) { 195 return isUsedToDefineABitField(Result, Parent); 196 }); 197 } 198 199 } // namespace readability 200 } // namespace tidy 201 } // namespace clang 202