20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/ConvertUTF.h"
24#include "llvm/Support/JSON.h"
25#include "llvm/Support/Path.h"
59 if (llvm::isAlnum(
C) || StringRef(
"-._~:@!$&'()*+,;=").
contains(
C))
60 return std::string(&
C, 1);
61 return "%" + llvm::toHex(StringRef(&
C, 1));
74 StringRef Root = sys::path::root_name(Filename);
75 if (Root.starts_with(
"//")) {
77 Ret += Root.drop_front(2).str();
78 }
else if (!Root.empty()) {
80 Ret += Twine(
"/" + Root).str();
83 auto Iter = sys::path::begin(Filename), End = sys::path::end(Filename);
84 assert(Iter != End &&
"Expected there to be a non-root path component.");
87 for (StringRef Component : llvm::make_range(++Iter, End)) {
91 if (Component ==
"\\")
99 for (
char C : Component) {
104 return std::string(Ret);
117 unsigned int TokenLen = 0) {
118 assert(!Loc.
isInvalid() &&
"invalid Loc when adjusting column position");
121 std::optional<MemoryBufferRef> Buf =
123 assert(Buf &&
"got an invalid buffer for the location's file");
124 assert(Buf->getBufferSize() >= (LocInfo.second + TokenLen) &&
125 "token extends past end of buffer?");
130 unsigned int Ret = 1;
131 while (
Off < (LocInfo.second + TokenLen)) {
132 Off += getNumBytesForUTF8(Buf->getBuffer()[
Off]);
144 return json::Object{{
"text",
Text.str()}};
156 if (BeginCharLoc == EndCharLoc) {
169 StringRef Message =
"") {
171 if (PhysicalLocation)
172 Ret[
"physicalLocation"] = std::move(*PhysicalLocation);
173 if (!Message.empty())
185 return "unimportant";
187 llvm_unreachable(
"Fully covered switch is not so fully covered");
201 llvm_unreachable(
"Potentially un-handled SarifResultLevel. "
202 "Is the switch not fully covered?");
208 return json::Object{{
"location", std::move(Location)},
213std::optional<json::Object>
217 assert(
R.isCharRange() &&
218 "Cannot create a physicalLocation from a token range!");
219 FullSourceLoc Start{
R.getBegin(), SourceMgr};
225 auto I = CurrentArtifacts.find(FileURI);
227 if (I == CurrentArtifacts.end()) {
229 const SarifArtifactLocation &Location =
235 auto StatusIter = CurrentArtifacts.insert({FileURI,
Artifact});
238 if (StatusIter.second)
239 I = StatusIter.first;
241 assert(I != CurrentArtifacts.end() &&
"Failed to insert new artifact");
242 const SarifArtifactLocation &Location = I->second.Location;
243 json::Object ArtifactLocationObject{{
"uri", Location.URI}};
244 if (Location.Index.has_value())
245 ArtifactLocationObject[
"index"] = *Location.Index;
246 return json::Object{{{
"artifactLocation", std::move(ArtifactLocationObject)},
250json::Object &SarifDocumentWriter::getCurrentTool() {
251 assert(!Closed &&
"SARIF Document is closed. "
252 "Need to call createRun() before using getcurrentTool!");
256 assert(!Runs.empty() &&
"There are no runs associated with the document!");
258 return *Runs.back().getAsObject()->get(
"tool")->getAsObject();
261void SarifDocumentWriter::reset() {
262 CurrentRules.clear();
263 CurrentArtifacts.clear();
275 assert(!Runs.empty() &&
"There are no runs associated with the document!");
278 json::Object &Tool = getCurrentTool();
280 for (
const SarifRule &R : CurrentRules) {
282 {
"enabled", R.DefaultConfiguration.Enabled},
284 {
"rank", R.DefaultConfiguration.Rank}};
288 {
"fullDescription", json::Object{{
"text", R.Description}}},
289 {
"defaultConfiguration", std::move(Config)}};
290 if (!R.HelpURI.empty())
291 Rule[
"helpUri"] = R.HelpURI;
292 if (!R.DeprecatedIds.empty())
293 Rule[
"deprecatedIds"] = json::Array(R.DeprecatedIds);
295 Rules.emplace_back(std::move(Rule));
297 json::Object &Driver = *Tool.getObject(
"driver");
298 Driver[
"rules"] = std::move(Rules);
301 json::Object &Run = getCurrentRun();
302 json::Array *Artifacts = Run.getArray(
"artifacts");
304 for (
const auto &[K,
V] : CurrentArtifacts)
305 Vec.emplace_back(K,
V);
307 llvm::sort(Vec, [](
const std::pair<StringRef, SarifArtifact> &L,
308 const std::pair<StringRef, SarifArtifact> &R) {
309 return L.second.Location.Index < R.second.Location.Index;
311 for (
const auto &[_, A] : Vec) {
312 json::Object Loc{{
"uri", A.Location.URI}};
313 if (A.Location.Index.has_value()) {
314 Loc[
"index"] =
static_cast<int64_t
>(*A.Location.Index);
316 json::Object Artifact;
317 Artifact[
"location"] = std::move(Loc);
318 if (A.Length.has_value())
319 Artifact[
"length"] =
static_cast<int64_t
>(*A.Length);
320 if (!A.Roles.empty())
321 Artifact[
"roles"] = json::Array(A.Roles);
322 if (!A.MimeType.empty())
323 Artifact[
"mimeType"] = A.MimeType;
324 if (A.Offset.has_value())
325 Artifact[
"offset"] = *A.Offset;
326 Artifacts->push_back(json::Value(std::move(Artifact)));
338 json::Object Ret{{
"locations", json::Array{}}};
340 for (
const auto &ThreadFlow : ThreadFlows) {
341 json::Object Loc =
createLocation(createPhysicalLocation(ThreadFlow.Range),
346 Ret[
"locations"] = std::move(Locs);
347 return json::Array{std::move(Ret)};
352 return json::Object{{
"threadFlows", createThreadFlows(ThreadFlows)}};
356 StringRef LongToolName,
357 StringRef ToolVersion,
358 StringRef InformationUri) {
365 json::Object Tool{{
"driver", json::Object{{
"name", ShortToolName},
366 {
"fullName", LongToolName},
367 {
"language",
"en-US"},
368 {
"version", ToolVersion},
369 {
"informationUri", InformationUri},
370 {
"rules", json::Array{}}}}};
371 json::Object TheRun{{
"tool", std::move(Tool)},
374 {
"columnKind",
"unicodeCodePoints"}};
375 Runs.emplace_back(std::move(TheRun));
378json::Object &SarifDocumentWriter::getCurrentRun() {
380 "SARIF Document is closed. "
381 "Can only getCurrentRun() if document is opened via createRun(), "
382 "create a run first");
386 assert(!Runs.empty() &&
"There are no runs associated with the document!");
387 return *Runs.back().getAsObject();
391 size_t Ret = CurrentRules.size();
392 CurrentRules.emplace_back(Rule);
397 size_t RuleIdx =
Result.RuleIdx;
398 assert(RuleIdx < CurrentRules.size() &&
399 "Trying to reference a rule that doesn't exist");
400 const SarifRule &Rule = CurrentRules[RuleIdx];
401 assert(Rule.DefaultConfiguration.Enabled &&
402 "Cannot add a result referencing a disabled Rule");
404 {
"ruleIndex",
static_cast<int64_t
>(RuleIdx)},
405 {
"ruleId", Rule.Id}};
407 if (!
Result.HostedViewerURI.empty()) {
408 Ret[
"hostedViewerUri"] =
Result.HostedViewerURI;
411 if (!
Result.Properties.empty()) {
412 json::Object Properties;
414 Properties[Key.str()] =
Value;
415 Ret[
"properties"] = std::move(Properties);
419 for (
const auto &Range :
Result.Locations)
420 if (std::optional<json::Object> PL = createPhysicalLocation(Range))
423 Ret[
"locations"] = std::move(Locs);
428 int64_t RelatedLocationId = 0;
429 for (
const auto &[Range, Message] :
Result.RelatedLocations) {
430 json::Object Loc =
createLocation(createPhysicalLocation(Range), Message);
433 Loc[
"id"] = RelatedLocationId++;
434 ReLocs.emplace_back(std::move(Loc));
438 Ret[
"relatedLocations"] = std::move(ReLocs);
440 if (!
Result.PartialFingerprints.empty()) {
441 json::Object fingerprints = {};
442 for (
auto &pair :
Result.PartialFingerprints) {
443 fingerprints[pair.first] = pair.second;
445 Ret[
"partialFingerprints"] = std::move(fingerprints);
448 if (!
Result.ThreadFlows.empty())
449 Ret[
"codeFlows"] = json::Array{createCodeFlow(
Result.ThreadFlows)};
452 Result.LevelOverride.value_or(Rule.DefaultConfiguration.Level));
454 json::Object &Run = getCurrentRun();
455 json::Array *Results = Run.getArray(
"results");
456 Results->emplace_back(std::move(Ret));
464 {
"$schema", SchemaURI},
465 {
"version", SchemaVersion},
468 Doc[
"runs"] = json::Array(Runs);
static StringRef importanceToStr(ThreadFlowImportance I)
static json::Object createMessage(StringRef Text)
static StringRef getFileName(FileEntryRef FE)
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 createTextRegion(const SourceManager &SM, const CharSourceRange &R)
static json::Object createLocation(std::optional< json::Object > &&PhysicalLocation, StringRef Message="")
static StringRef resultLevelToStr(SarifResultLevel R)
Defines clang::SarifDocumentWriter, clang::SarifRule, clang::SarifResult.
static bool contains(const std::set< tok::TokenKind > &Terminators, const Token &Tok)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
static SarifArtifactLocation create(llvm::StringRef URI)
static SarifArtifact create(const SarifArtifactLocation &Loc)
Represents a byte-granular source range.
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
const FileEntry & getFileEntry() const
StringRef getName() const
The name of this FileEntry.
StringRef tryGetRealPathName() const
A SourceLocation and its associated SourceManager.
FileIDAndOffset getDecomposedExpansionLoc() const
Decompose the underlying SourceLocation into a raw (FileID + Offset) pair, after walking through all ...
FullSourceLoc getExpansionLoc() const
OptionalFileEntryRef getFileEntryRef() const
unsigned getExpansionColumnNumber(bool *Invalid=nullptr) const
const SourceManager & getManager() const
unsigned getExpansionLineNumber(bool *Invalid=nullptr) const
void createRun(const llvm::StringRef ShortToolName, const llvm::StringRef LongToolName, const llvm::StringRef ToolVersion=CLANG_VERSION_STRING, const llvm::StringRef InformationUri="https://clang.llvm.org/docs/UsersManual.html")
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.
static std::string fileNameToURI(llvm::StringRef Filename)
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.
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)
PRESERVE_NONE bool Ret(InterpState &S)
std::variant< TUSummary, LUSummary, WPASuite > Artifact
Sum type returned by SerializationFormat::readArtifact, used when the caller does not know up-front w...
Top level wrappers for InstallAPI frontend operations.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
std::pair< FileID, unsigned > FileIDAndOffset
SarifResultLevel
The level of severity associated with a SarifResult.
@ Result
The result type of a method or function.
@ Off
Never emit colors regardless of the output stream.
Diagnostic wrappers for TextAPI types for error reporting.