20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringExtras.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) || StringRef(
"-._~:@!$&'()*+,;=").
contains(
C))
61 return std::string(&
C, 1);
62 return "%" + llvm::toHex(StringRef(&
C, 1));
75 StringRef Root = sys::path::root_name(
Filename);
76 if (Root.starts_with(
"//")) {
78 Ret += Root.drop_front(2).str();
79 }
else if (!Root.empty()) {
81 Ret += Twine(
"/" + Root).str();
85 assert(
Iter != End &&
"Expected there to be a non-root path component.");
88 for (StringRef Component : llvm::make_range(++
Iter, End)) {
92 if (Component ==
"\\")
100 for (
char C : Component) {
105 return std::string(Ret);
118 unsigned int TokenLen = 0) {
119 assert(!
Loc.
isInvalid() &&
"invalid Loc when adjusting column position");
121 std::pair<FileID, unsigned> LocInfo =
Loc.getDecomposedExpansionLoc();
122 std::optional<MemoryBufferRef> Buf =
123 Loc.getManager().getBufferOrNone(LocInfo.first);
124 assert(Buf &&
"got an invalid buffer for the location's file");
125 assert(Buf->getBufferSize() >= (LocInfo.second + TokenLen) &&
126 "token extends past end of buffer?");
130 unsigned int Off = LocInfo.second - (
Loc.getExpansionColumnNumber() - 1);
131 unsigned int Ret = 1;
132 while (Off < (LocInfo.second + TokenLen)) {
133 Off += getNumBytesForUTF8(Buf->getBuffer()[Off]);
145 return json::Object{{
"text",
Text.str()}};
154 json::Object Region{{
"startLine", BeginCharLoc.getExpansionLineNumber()},
157 if (BeginCharLoc == EndCharLoc) {
160 Region[
"endLine"] = EndCharLoc.getExpansionLineNumber();
167 StringRef Message =
"") {
168 json::Object Ret{{
"physicalLocation", std::move(PhysicalLocation)}};
169 if (!Message.empty())
176 case ThreadFlowImportance::Important:
178 case ThreadFlowImportance::Essential:
180 case ThreadFlowImportance::Unimportant:
181 return "unimportant";
183 llvm_unreachable(
"Fully covered switch is not so fully covered");
188 case SarifResultLevel::None:
190 case SarifResultLevel::Note:
192 case SarifResultLevel::Warning:
194 case SarifResultLevel::Error:
197 llvm_unreachable(
"Potentially un-handled SarifResultLevel. "
198 "Is the switch not fully covered?");
204 return json::Object{{
"location", std::move(Location)},
212 "Cannot create a physicalLocation from invalid SourceRange!");
214 "Cannot create a physicalLocation from a token range!");
217 assert(FE &&
"Diagnostic does not exist within a valid file!");
220 auto I = CurrentArtifacts.find(FileURI);
222 if (I == CurrentArtifacts.end()) {
225 SarifArtifactLocation::create(FileURI).
setIndex(Idx);
226 const SarifArtifact &Artifact = SarifArtifact::create(Location)
230 auto StatusIter = CurrentArtifacts.insert({FileURI, Artifact});
233 if (StatusIter.second)
234 I = StatusIter.first;
236 assert(I != CurrentArtifacts.end() &&
"Failed to insert new artifact");
238 json::Object ArtifactLocationObject{{
"uri", Location.URI}};
239 if (Location.Index.has_value())
240 ArtifactLocationObject[
"index"] = *Location.Index;
241 return json::Object{{{
"artifactLocation", std::move(ArtifactLocationObject)},
245json::Object &SarifDocumentWriter::getCurrentTool() {
246 assert(!Closed &&
"SARIF Document is closed. "
247 "Need to call createRun() before using getcurrentTool!");
251 assert(!Runs.empty() &&
"There are no runs associated with the document!");
253 return *Runs.back().getAsObject()->get(
"tool")->getAsObject();
256void SarifDocumentWriter::reset() {
257 CurrentRules.clear();
258 CurrentArtifacts.clear();
270 assert(!Runs.empty() &&
"There are no runs associated with the document!");
273 json::Object &Tool = getCurrentTool();
275 for (
const SarifRule &R : CurrentRules) {
277 {
"enabled", R.DefaultConfiguration.Enabled},
279 {
"rank", R.DefaultConfiguration.Rank}};
283 {
"fullDescription", json::Object{{
"text", R.Description}}},
284 {
"defaultConfiguration", std::move(Config)}};
285 if (!R.HelpURI.empty())
286 Rule[
"helpUri"] = R.HelpURI;
287 Rules.emplace_back(std::move(Rule));
289 json::Object &Driver = *Tool.getObject(
"driver");
290 Driver[
"rules"] = std::move(Rules);
293 json::Object &Run = getCurrentRun();
294 json::Array *Artifacts = Run.getArray(
"artifacts");
296 for (
const auto &[K,
V] : CurrentArtifacts)
297 Vec.emplace_back(K,
V);
298 llvm::sort(Vec, llvm::less_first());
299 for (
const auto &[_, A] : Vec) {
300 json::Object
Loc{{
"uri", A.Location.URI}};
301 if (A.Location.Index.has_value()) {
302 Loc[
"index"] =
static_cast<int64_t
>(*A.Location.Index);
304 json::Object Artifact;
305 Artifact[
"location"] = std::move(
Loc);
306 if (A.Length.has_value())
307 Artifact[
"length"] =
static_cast<int64_t
>(*A.Length);
308 if (!A.Roles.empty())
309 Artifact[
"roles"] = json::Array(A.Roles);
310 if (!A.MimeType.empty())
311 Artifact[
"mimeType"] = A.MimeType;
312 if (A.Offset.has_value())
313 Artifact[
"offset"] = *A.Offset;
314 Artifacts->push_back(json::Value(std::move(Artifact)));
326 json::Object Ret{{
"locations", json::Array{}}};
329 json::Object PLoc = createPhysicalLocation(
ThreadFlow.Range);
334 Ret[
"locations"] = std::move(Locs);
335 return json::Array{std::move(Ret)};
340 return json::Object{{
"threadFlows", createThreadFlows(ThreadFlows)}};
344 StringRef LongToolName,
345 StringRef ToolVersion) {
354 json::Object{{
"name", ShortToolName},
355 {
"fullName", LongToolName},
356 {
"language",
"en-US"},
357 {
"version", ToolVersion},
359 "https://clang.llvm.org/docs/UsersManual.html"}}}};
360 json::Object TheRun{{
"tool", std::move(Tool)},
363 {
"columnKind",
"unicodeCodePoints"}};
364 Runs.emplace_back(std::move(TheRun));
367json::Object &SarifDocumentWriter::getCurrentRun() {
369 "SARIF Document is closed. "
370 "Can only getCurrentRun() if document is opened via createRun(), "
371 "create a run first");
375 assert(!Runs.empty() &&
"There are no runs associated with the document!");
376 return *Runs.back().getAsObject();
380 size_t Ret = CurrentRules.size();
381 CurrentRules.emplace_back(Rule);
386 size_t RuleIdx =
Result.RuleIdx;
387 assert(RuleIdx < CurrentRules.size() &&
388 "Trying to reference a rule that doesn't exist");
389 const SarifRule &Rule = CurrentRules[RuleIdx];
390 assert(Rule.DefaultConfiguration.Enabled &&
391 "Cannot add a result referencing a disabled Rule");
393 {
"ruleIndex",
static_cast<int64_t
>(RuleIdx)},
394 {
"ruleId", Rule.Id}};
395 if (!
Result.Locations.empty()) {
400 Ret[
"locations"] = std::move(Locs);
402 if (!
Result.ThreadFlows.empty())
403 Ret[
"codeFlows"] = json::Array{createCodeFlow(
Result.ThreadFlows)};
406 Result.LevelOverride.value_or(Rule.DefaultConfiguration.Level));
408 json::Object &Run = getCurrentRun();
409 json::Array *Results = Run.getArray(
"results");
410 Results->emplace_back(std::move(Ret));
418 {
"$schema", SchemaURI},
419 {
"version", SchemaVersion},
422 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 createLocation(json::Object &&PhysicalLocation, StringRef Message="")
static json::Object createTextRegion(const SourceManager &SM, const CharSourceRange &R)
static std::string fileNameToURI(StringRef Filename)
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.
Represents a character-granular source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
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.
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.
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)
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
SarifResultLevel
The level of severity associated with a SarifResult.
@ Result
The result type of a method or function.
Diagnostic wrappers for TextAPI types for error reporting.