Skip to content

Commit

Permalink
[analyzer] EnumCastOutOfRangeChecker: report the value (llvm#74503)
Browse files Browse the repository at this point in the history
...that is causing the bug report when it's converted to the enum type.
This commit only improves the diagnostics and does not affect the set of
reports.
  • Loading branch information
NagyDonat authored Dec 7, 2023
1 parent e9e1c41 commit 2f29ded
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 59 deletions.
25 changes: 16 additions & 9 deletions clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "llvm/Support/FormatVariadic.h"
#include <optional>

using namespace clang;
using namespace ento;
using llvm::formatv;

namespace {
// This evaluator checks two SVals for equality. The first SVal is provided via
Expand Down Expand Up @@ -87,17 +89,22 @@ void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C,
EnumValueCastOutOfRange.reset(
new BugType(this, "Enum cast out of range"));

llvm::SmallString<128> Msg{"The value provided to the cast expression is "
"not in the valid range of values for "};
StringRef EnumName{E->getName()};
if (EnumName.empty()) {
Msg += "the enum";
} else {
Msg += '\'';
Msg += EnumName;
Msg += '\'';
std::string ValueStr = "", NameStr = "the enum";

// Try to add details to the message:
const auto ConcreteValue =
C.getSVal(CE->getSubExpr()).getAs<nonloc::ConcreteInt>();
if (ConcreteValue) {
ValueStr = formatv(" '{0}'", ConcreteValue->getValue());
}
if (StringRef EnumName{E->getName()}; !EnumName.empty()) {
NameStr = formatv("'{0}'", EnumName);
}

std::string Msg = formatv("The value{0} provided to the cast expression is "
"not in the valid range of values for {1}",
ValueStr, NameStr);

auto BR = std::make_unique<PathSensitiveBugReport>(*EnumValueCastOutOfRange,
Msg, N);
bugreporter::trackExpressionValue(N, CE->getSubExpr(), *BR);
Expand Down
Loading

0 comments on commit 2f29ded

Please sign in to comment.