[PATCH] D49114: [clang-tidy] Add a check for "magic numbers"

Florin Iucha via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Sat Jul 28 18:27:36 PDT 2018


0x8000-0000 added a comment.

Not trying to be difficult here - I have attempted to implement the straight-forward check.

Added this to the MagicNumbersCheck::MagicNumbersCheck constructor:

  +  // process set of ignored floating point values
  +  const std::vector<std::string> IgnoredFloatingPointValuesInput =
  +      utils::options::parseStringList(Options.get(
  +          "IgnoredFloatingPointValues", DefaultIgnoredFloatingPointValues));
  +  IgnoredFloatingPointValues.reserve(IgnoredFloatingPointValuesInput.size());
  +  for (const auto &InputValue : IgnoredFloatingPointValuesInput) {
  +    llvm::APFloat FloatValue(llvm::APFloat::IEEEdouble());
  +    FloatValue.convertFromString(InputValue, DefaultRoundingMode);
  +    const double Value = FloatValue.convertToDouble();
  +    IgnoredFloatingPointValues.push_back(Value);
  +  }
  +  llvm::sort(IgnoredFloatingPointValues.begin(),
  +             IgnoredFloatingPointValues.end());

and changed isIgnoredValue(const FloatingLiteral *Literal) like this:

   bool MagicNumbersCheck::isIgnoredValue(const FloatingLiteral *Literal) const {
  -  llvm::APFloat FloatValue = Literal->getValue();
  -  return FloatValue.isZero();
  +  const llvm::APFloat FloatValue = Literal->getValue();
  +  double Value;
  +  if (&FloatValue.getSemantics() == &llvm::APFloat::IEEEdouble()) {
  +    Value = FloatValue.convertToDouble();
  +  } else if (&FloatValue.getSemantics() == &llvm::APFloat::IEEEsingle()) {
  +    Value = static_cast<double>(FloatValue.convertToFloat());
  +  } else
  +    return false;
  +
  +  return std::binary_search(IgnoredFloatingPointValues.begin(),
  +                            IgnoredFloatingPointValues.end(), Value);
   }

When running under the debugger and printing various values, it seems that 3.14 read as double and converted to double prints as 3.1399999999999997, while 3.14f read as float and cast to double prints as 3.1400001049041748

I will parse the IgnoredFloatingPointValues twice and store the results in two arrays, one of doubles and one of floats.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49114





More information about the cfe-commits mailing list