20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/Support/ConvertUTF.h"
25#include "llvm/Support/JSON.h"
26#include "llvm/Support/Path.h"
60 if (llvm::isAlnum(
C) ||
61 StringRef::npos != StringRef(
"-._~:@!$&'()*+,;=").find(
C))
62 return std::string(&
C, 1);
63 return "%" + llvm::toHex(StringRef(&
C, 1));
76 StringRef Root = sys::path::root_name(
Filename);
77 if (Root.startswith(
"//")) {
79 Ret += Root.drop_front(2).str();
80 }
else if (!Root.empty()) {
82 Ret += Twine(
"/" + Root).str();
86 assert(Iter != End &&
"Expected there to be a non-root path component.");
89 std::for_each(++Iter, End, [&Ret](StringRef Component) {
93 if (Component ==
"\\")
101 for (
char C : Component) {
106 return std::string(Ret);
119 unsigned int TokenLen = 0) {
120 assert(!Loc.
isInvalid() &&
"invalid Loc when adjusting column position");
123 std::optional<MemoryBufferRef> Buf =
125 assert(Buf &&
"got an invalid buffer for the location's file");
126 assert(Buf->getBufferSize() >= (LocInfo.second + TokenLen) &&
127 "token extends past end of buffer?");
132 unsigned int Ret = 1;
133 while (Off < (LocInfo.second + TokenLen)) {
134 Off += getNumBytesForUTF8(Buf->getBuffer()[Off]);
146 return json::Object{{
"text",
Text.str()}};
155 json::Object Region{{
"startLine", BeginCharLoc.getExpansionLineNumber()},
158 if (BeginCharLoc == EndCharLoc) {
161 Region[
"endLine"] = EndCharLoc.getExpansionLineNumber();
168 StringRef Message =
"") {
169 json::Object Ret{{
"physicalLocation", std::move(PhysicalLocation)}};
170 if (!Message.empty())
177 case ThreadFlowImportance::Important:
179 case ThreadFlowImportance::Essential:
181 case ThreadFlowImportance::Unimportant:
182 return "unimportant";
184 llvm_unreachable(
"Fully covered switch is not so fully covered");
189 case SarifResultLevel::None:
191 case SarifResultLevel::Note:
193 case SarifResultLevel::Warning:
195 case SarifResultLevel::Error:
198 llvm_unreachable(
"Potentially un-handled SarifResultLevel. "
199 "Is the switch not fully covered?");
205 return json::Object{{
"location", std::move(Location)},
213 "Cannot create a physicalLocation from invalid SourceRange!");
215 "Cannot create a physicalLocation from a token range!");
217 const FileEntry *FE = Start.getExpansionLoc().getFileEntry();
218 assert(FE !=
nullptr &&
"Diagnostic does not exist within a valid file!");
221 auto I = CurrentArtifacts.find(FileURI);
223 if (I == CurrentArtifacts.end()) {
224 uint32_t Idx =
static_cast<uint32_t
>(CurrentArtifacts.size());
226 SarifArtifactLocation::create(FileURI).
setIndex(Idx);
227 const SarifArtifact &Artifact = SarifArtifact::create(Location)
231 auto StatusIter = CurrentArtifacts.insert({FileURI, Artifact});
234 if (StatusIter.second)
235 I = StatusIter.first;
237 assert(I != CurrentArtifacts.end() &&
"Failed to insert new artifact");
239 json::Object ArtifactLocationObject{{
"uri", Location.URI}};
240 if (Location.Index.has_value())
241 ArtifactLocationObject[
"index"] = *Location.Index;
242 return json::Object{{{
"artifactLocation", std::move(ArtifactLocationObject)},
246json::Object &SarifDocumentWriter::getCurrentTool() {
247 assert(!Closed &&
"SARIF Document is closed. "
248 "Need to call createRun() before using getcurrentTool!");
252 assert(!Runs.empty() &&
"There are no runs associated with the document!");
254 return *Runs.back().getAsObject()->get(
"tool")->getAsObject();
257void SarifDocumentWriter::reset() {
258 CurrentRules.clear();
259 CurrentArtifacts.clear();
271 assert(!Runs.empty() &&
"There are no runs associated with the document!");
274 json::Object &Tool = getCurrentTool();
276 for (
const SarifRule &R : CurrentRules) {
278 {
"enabled", R.DefaultConfiguration.Enabled},
280 {
"rank", R.DefaultConfiguration.Rank}};
284 {
"fullDescription", json::Object{{
"text", R.Description}}},
285 {
"defaultConfiguration", std::move(Config)}};
286 if (!R.HelpURI.empty())
287 Rule[
"helpUri"] = R.HelpURI;
288 Rules.emplace_back(std::move(Rule));
290 json::Object &Driver = *Tool.getObject(
"driver");
291 Driver[
"rules"] = std::move(Rules);
294 json::Object &Run = getCurrentRun();
295 json::Array *Artifacts = Run.getArray(
"artifacts");
296 for (
const auto &Pair : CurrentArtifacts) {
298 json::Object Loc{{
"uri", A.Location.URI}};
299 if (A.Location.Index.has_value()) {
300 Loc[
"index"] =
static_cast<int64_t
>(*A.Location.Index);
302 json::Object Artifact;
303 Artifact[
"location"] = std::move(Loc);
304 if (A.Length.has_value())
305 Artifact[
"length"] =
static_cast<int64_t
>(*A.Length);
306 if (!A.Roles.empty())
307 Artifact[
"roles"] = json::Array(A.Roles);
308 if (!A.MimeType.empty())
309 Artifact[
"mimeType"] = A.MimeType;
310 if (A.Offset.has_value())
311 Artifact[
"offset"] = *A.Offset;
312 Artifacts->push_back(json::Value(std::move(Artifact)));
324 json::Object Ret{{
"locations", json::Array{}}};
327 json::Object PLoc = createPhysicalLocation(
ThreadFlow.Range);
332 Ret[
"locations"] = std::move(Locs);
333 return json::Array{std::move(Ret)};
338 return json::Object{{
"threadFlows", createThreadFlows(ThreadFlows)}};
342 StringRef LongToolName,
343 StringRef ToolVersion) {
352 json::Object{{
"name", ShortToolName},
353 {
"fullName", LongToolName},
354 {
"language",
"en-US"},
355 {
"version", ToolVersion},
357 "https://clang.llvm.org/docs/UsersManual.html"}}}};
358 json::Object TheRun{{
"tool", std::move(Tool)},
361 {
"columnKind",
"unicodeCodePoints"}};
362 Runs.emplace_back(std::move(TheRun));
365json::Object &SarifDocumentWriter::getCurrentRun() {
367 "SARIF Document is closed. "
368 "Can only getCurrentRun() if document is opened via createRun(), "
369 "create a run first");
373 assert(!Runs.empty() &&
"There are no runs associated with the document!");
374 return *Runs.back().getAsObject();
378 size_t Ret = CurrentRules.size();
379 CurrentRules.emplace_back(Rule);
384 size_t RuleIdx =
Result.RuleIdx;
385 assert(RuleIdx < CurrentRules.size() &&
386 "Trying to reference a rule that doesn't exist");
387 const SarifRule &Rule = CurrentRules[RuleIdx];
388 assert(Rule.DefaultConfiguration.Enabled &&
389 "Cannot add a result referencing a disabled Rule");
391 {
"ruleIndex",
static_cast<int64_t
>(RuleIdx)},
392 {
"ruleId", Rule.Id}};
393 if (!
Result.Locations.empty()) {
395 for (
auto &Range :
Result.Locations) {
398 Ret[
"locations"] = std::move(Locs);
400 if (!
Result.ThreadFlows.empty())
401 Ret[
"codeFlows"] = json::Array{createCodeFlow(
Result.ThreadFlows)};
404 Result.LevelOverride.value_or(Rule.DefaultConfiguration.Level));
406 json::Object &Run = getCurrentRun();
407 json::Array *Results = Run.getArray(
"results");
408 Results->emplace_back(std::move(Ret));
416 {
"$schema", SchemaURI},
417 {
"version", SchemaVersion},
420 Doc[
"runs"] = json::Array(Runs);
static StringRef importanceToStr(ThreadFlowImportance I)
json::Object createMessage(StringRef Text)
static unsigned int adjustColumnPos(FullSourceLoc Loc, unsigned int TokenLen=0)
Calculate the column position expressed in the number of UTF-8 code points from column start to the s...
static std::string percentEncodeURICharacter(char C)
static json::Object createThreadFlowLocation(json::Object &&Location, const ThreadFlowImportance &Importance)
static json::Object createLocation(json::Object &&PhysicalLocation, StringRef Message="")
static json::Object createTextRegion(const SourceManager &SM, const CharSourceRange &R)
static std::string fileNameToURI(StringRef Filename)
static StringRef getFileName(const FileEntry &FE)
static StringRef resultLevelToStr(SarifResultLevel R)
Defines clang::SarifDocumentWriter, clang::SarifRule, clang::SarifResult.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Represents a character-granular source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Cached information about one file (either on disk or in the virtual file system).
StringRef tryGetRealPathName() const
StringRef getName() const
A SourceLocation and its associated SourceManager.
std::pair< FileID, unsigned > getDecomposedExpansionLoc() const
Decompose the underlying SourceLocation into a raw (FileID + Offset) pair, after walking through all ...
unsigned getExpansionColumnNumber(bool *Invalid=nullptr) const
const SourceManager & getManager() const
void createRun(const llvm::StringRef ShortToolName, const llvm::StringRef LongToolName, const llvm::StringRef ToolVersion=CLANG_VERSION_STRING)
Create a new run with which any upcoming analysis will be associated.
size_t createRule(const SarifRule &Rule)
Associate the given rule with the current run.
llvm::json::Object createDocument()
Return the SARIF document in its current state.
void endRun()
If there is a current run, end it.
void appendResult(const SarifResult &SarifResult)
Append a new result to the currently in-flight run.
A SARIF result (also called a "reporting item") is a unit of output produced when one of the tool's r...
A SARIF rule (reportingDescriptor object) contains information that describes a reporting item genera...
This class handles loading and caching of source files into memory.
std::optional< llvm::MemoryBufferRef > getBufferOrNone(FileID FID, SourceLocation Loc=SourceLocation()) const
Return the buffer for the specified FileID.
A thread flow is a sequence of code locations that specify a possible path through a single thread of...
SarifArtifactLocation setIndex(uint32_t Idx)
Since every clang artifact MUST have a location (there being no nested artifacts),...
SarifArtifact setMimeType(llvm::StringRef ArtifactMimeType)
SarifArtifact setRoles(std::initializer_list< llvm::StringRef > ArtifactRoles)
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
SarifResultLevel
The level of severity associated with a SarifResult.
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
YAML serialization mapping.