Skip to content

Commit 2f29ded

Browse files
authored
[analyzer] EnumCastOutOfRangeChecker: report the value (#74503)
...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.
1 parent e9e1c41 commit 2f29ded

File tree

2 files changed

+66
-59
lines changed

2 files changed

+66
-59
lines changed

clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,12 @@
2222
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
2323
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
2424
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
25+
#include "llvm/Support/FormatVariadic.h"
2526
#include <optional>
2627

2728
using namespace clang;
2829
using namespace ento;
30+
using llvm::formatv;
2931

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

90-
llvm::SmallString<128> Msg{"The value provided to the cast expression is "
91-
"not in the valid range of values for "};
92-
StringRef EnumName{E->getName()};
93-
if (EnumName.empty()) {
94-
Msg += "the enum";
95-
} else {
96-
Msg += '\'';
97-
Msg += EnumName;
98-
Msg += '\'';
92+
std::string ValueStr = "", NameStr = "the enum";
93+
94+
// Try to add details to the message:
95+
const auto ConcreteValue =
96+
C.getSVal(CE->getSubExpr()).getAs<nonloc::ConcreteInt>();
97+
if (ConcreteValue) {
98+
ValueStr = formatv(" '{0}'", ConcreteValue->getValue());
99+
}
100+
if (StringRef EnumName{E->getName()}; !EnumName.empty()) {
101+
NameStr = formatv("'{0}'", EnumName);
99102
}
100103

104+
std::string Msg = formatv("The value{0} provided to the cast expression is "
105+
"not in the valid range of values for {1}",
106+
ValueStr, NameStr);
107+
101108
auto BR = std::make_unique<PathSensitiveBugReport>(*EnumValueCastOutOfRange,
102109
Msg, N);
103110
bugreporter::trackExpressionValue(N, CE->getSubExpr(), *BR);

0 commit comments

Comments
 (0)