clang 24.0.0git
SARIFDiagnostic.cpp
Go to the documentation of this file.
1//===--------- SARIFDiagnostic.cpp - SARIF Diagnostic Formatting ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
13#include "clang/Basic/Sarif.h"
16#include "clang/Lex/Lexer.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/Support/ConvertUTF.h"
23#include "llvm/Support/ErrorHandling.h"
24#include "llvm/Support/ErrorOr.h"
25#include "llvm/Support/Locale.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/raw_ostream.h"
28#include <algorithm>
29#include <string>
30
31namespace clang {
32
33// SARIF reportingConfiguration.rank is given to each severity. Notes, remarks
34// and warnings keep the default -1.
35namespace rank {
36constexpr float Error = 50.0f;
37constexpr float Fatal = 100.0f;
38} // namespace rank
39
41 switch (level) {
43 llvm_unreachable("Invalid diagnostic type");
53 }
54 llvm_unreachable("Un-handled DiagnosticsEngine::Level occured.");
55}
56
61 getSarifResultLevel(Level));
62
63 if (Level == DiagnosticsEngine::Error)
64 Config = Config.setRank(rank::Error);
65 else if (Level == DiagnosticsEngine::Fatal)
66 Config = Config.setRank(rank::Fatal);
67
68 return Rule.setDefaultConfiguration(Config);
69}
70
75
76// FIXME(llvm-project/issues/57323): Refactor Diagnostic classes.
79 StringRef Message, ArrayRef<clang::CharSourceRange> Ranges,
81
82 const auto *Diag = dyn_cast_if_present<const Diagnostic *>(D);
83
84 if (!Diag)
85 return;
86
87 const auto &DiagnosticIDs = *(Diag->getDiags()->getDiagnosticIDs());
88 std::string StableID = DiagnosticIDs.getStableID(Diag->getID());
89 auto LegacyStableIDs = DiagnosticIDs.getLegacyStableIDs(Diag->getID());
90 SarifRule Rule =
91 SarifRule::create().setRuleId(StableID).setDeprecatedIds(LegacyStableIDs);
92
93 Rule = addDiagnosticLevelToRule(Rule, Level);
94
95 unsigned RuleIdx = Writer->createRule(Rule);
96
99
100 if (Loc.isValid())
101 Result = addLocationToResult(Result, Loc, PLoc, Ranges, *Diag);
102
103 for (auto &[RelLoc, RelPLoc] : RelatedLocationsCache)
104 Result = addRelatedLocationToResult(Result, RelLoc, RelPLoc);
105 RelatedLocationsCache.clear();
106
107 Writer->appendResult(Result);
108}
109
111 // We always emit include location before results, for example:
112 //
113 // In file included from ...
114 // In file included from ...
115 // error: ...
116 //
117 // At this time We cannot peek the SarifRule. But what we
118 // do is to push it into a cache and wait for next time
119 // \ref SARIFDiagnostic::emitDiagnosticMessage to pick it up.
120 RelatedLocationsCache.push_back({Loc, PLoc});
121}
122
124 StringRef ModuleName) {
125 RelatedLocationsCache.push_back({Loc, PLoc});
126}
127
128SarifResult SARIFDiagnostic::addLocationToResult(
131 auto Locations = getSarifLocation(Loc, PLoc, Ranges);
132 return Result.addLocations(Locations);
133}
134
135SarifResult SARIFDiagnostic::addRelatedLocationToResult(SarifResult Result,
136 FullSourceLoc Loc,
137 PresumedLoc PLoc) {
138 auto Locations = getSarifLocation(Loc, PLoc, {});
139 return Result.addRelatedLocations(Locations);
140}
141
143SARIFDiagnostic::getSarifLocation(FullSourceLoc Loc, PresumedLoc PLoc,
145 SmallVector<CharSourceRange> Locations = {};
146
147 if (PLoc.isInvalid()) {
148 // At least add the file name if available:
149 FileID FID = Loc.getFileID();
150 if (FID.isValid()) {
151 if (OptionalFileEntryRef FE = Loc.getFileEntryRef()) {
152 emitFilename(FE->getName(), Loc.getManager());
153 // FIXME(llvm-project/issues/57366): File-only locations
154 }
155 }
156 return {};
157 }
158
159 FileID CaretFileID = Loc.getExpansionLoc().getFileID();
160
161 auto &SM = Loc.getManager();
162 for (const CharSourceRange Range : Ranges) {
163 std::optional<CharSourceRange> FileRange =
164 getExpansionRangeInFile(Range, CaretFileID, SM);
165 if (!FileRange)
166 continue;
167
168 SourceLocation B = FileRange->getBegin();
169 SourceLocation E = FileRange->getEnd();
170
171 // Add in the length of the token, so that we cover multi-char
172 // tokens.
173 unsigned TokSize = 0;
174 if (FileRange->isTokenRange())
175 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
176
177 FullSourceLoc BF(B, SM), EF(E, SM);
178 SourceLocation BeginLoc = SM.translateLineCol(
179 BF.getFileID(), BF.getLineNumber(), BF.getColumnNumber());
180 SourceLocation EndLoc = SM.translateLineCol(
181 EF.getFileID(), EF.getLineNumber(), EF.getColumnNumber() + TokSize);
182
183 Locations.push_back(
184 CharSourceRange{SourceRange{BeginLoc, EndLoc}, /* ITR = */ false});
185 // FIXME: Additional ranges should use presumed location in both
186 // Text and SARIF diagnostics.
187 }
188
189 auto FID = PLoc.getFileID();
190 // Visual Studio 2010 or earlier expects column number to be off by one.
191 unsigned int ColNo = (LangOpts.MSCompatibilityVersion &&
192 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2012))
193 ? PLoc.getColumn() - 1
194 : PLoc.getColumn();
195 SourceLocation DiagLoc = SM.translateLineCol(FID, PLoc.getLine(), ColNo);
196
197 // FIXME(llvm-project/issues/57366): Properly process #line directives.
198 CharSourceRange Range = {SourceRange{DiagLoc, DiagLoc}, /* ITR = */ false};
199 if (Range.isValid())
200 Locations.push_back(std::move(Range));
201
202 return Locations;
203}
204
205llvm::StringRef SARIFDiagnostic::emitFilename(StringRef Filename,
206 const SourceManager &SM) {
207 if (DiagOpts.AbsolutePath) {
208 auto File = SM.getFileManager().getOptionalFileRef(Filename);
209 if (File) {
210 // We want to print a simplified absolute path, i. e. without "dots".
211 //
212 // The hardest part here are the paths like "<part1>/<link>/../<part2>".
213 // On Unix-like systems, we cannot just collapse "<link>/..", because
214 // paths are resolved sequentially, and, thereby, the path
215 // "<part1>/<part2>" may point to a different location. That is why
216 // we use FileManager::getCanonicalName(), which expands all indirections
217 // with llvm::sys::fs::real_path() and caches the result.
218 //
219 // On the other hand, it would be better to preserve as much of the
220 // original path as possible, because that helps a user to recognize it.
221 // real_path() expands all links, which is sometimes too much. Luckily,
222 // on Windows we can just use llvm::sys::path::remove_dots(), because,
223 // on that system, both aforementioned paths point to the same place.
224#ifdef _WIN32
225 SmallString<256> TmpFilename = File->getName();
226 SM.getFileManager().makeAbsolutePath(TmpFilename);
227 llvm::sys::path::native(TmpFilename);
228 llvm::sys::path::remove_dots(TmpFilename, /* remove_dot_dot */ true);
229 Filename = StringRef(TmpFilename.data(), TmpFilename.size());
230#else
231 Filename = SM.getFileManager().getCanonicalName(*File);
232#endif
233 }
234 }
235
236 return Filename;
237}
238
239/// Print out the file/line/column information and include trace.
240///
241/// This method handlen the emission of the diagnostic location information.
242/// This includes extracting as much location information as is present for
243/// the diagnostic and printing it, as well as any include stack or source
244/// ranges necessary.
248 assert(false && "Not implemented in SARIF mode");
249}
250
252 PresumedLoc PLoc,
253 StringRef ModuleName) {
254 assert(false && "Not implemented in SARIF mode");
255}
256} // namespace clang
Defines the clang::FileManager interface and associated types.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Defines clang::SarifDocumentWriter, clang::SarifRule, clang::SarifResult.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Used for handling and querying diagnostic IDs.
std::string getStableID(unsigned DiagID) const
Given a diagnostic ID, return the stable ID of the diagnostic.
llvm::SmallVector< StringRef, 4 > getLegacyStableIDs(unsigned DiagID) const
Given a diagnostic ID, return the previous stable IDs of the diagnostic.
Options for controlling the compiler diagnostics engine.
const LangOptions & LangOpts
DiagnosticOptions & DiagOpts
DiagnosticRenderer(const LangOptions &LangOpts, DiagnosticOptions &DiagOpts)
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:245
A SourceLocation and its associated SourceManager.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:509
Represents an unpacked "presumed" location which can be presented to the user.
SARIFDiagnostic(raw_ostream &OS, const LangOptions &LangOpts, DiagnosticOptions &DiagOpts, SarifDocumentWriter *Writer)
void emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) override
void emitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, StringRef Message, ArrayRef< CharSourceRange > Ranges, DiagOrStoredDiag D) override
void emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, ArrayRef< CharSourceRange > Ranges) override
Print out the file/line/column information and include trace.
void emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc, StringRef ModuleName) override
void emitBuildingModuleLocation(FullSourceLoc Loc, PresumedLoc PLoc, StringRef ModuleName) override
This class handles creating a valid SARIF document given various input attributes.
Definition Sarif.h:422
A SARIF Reporting Configuration (reportingConfiguration) object contains properties for a SarifRule t...
Definition Sarif.h:211
static SarifReportingConfiguration create()
Definition Sarif.h:221
SarifReportingConfiguration setLevel(SarifResultLevel TheLevel)
Definition Sarif.h:233
SarifReportingConfiguration setRank(float TheRank)
Definition Sarif.h:238
A SARIF result (also called a "reporting item") is a unit of output produced when one of the tool's r...
Definition Sarif.h:322
SarifResult setDiagnosticMessage(llvm::StringRef Message)
Definition Sarif.h:356
static SarifResult create(uint32_t RuleIdx)
Definition Sarif.h:344
A SARIF rule (reportingDescriptor object) contains information that describes a reporting item genera...
Definition Sarif.h:257
SarifRule setDeprecatedIds(llvm::ArrayRef< llvm::StringRef > RuleDeprecatedIds)
Definition Sarif.h:293
SarifRule setRuleId(llvm::StringRef RuleId)
Definition Sarif.h:277
static SarifRule create()
Definition Sarif.h:270
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
constexpr float Error
constexpr float Fatal
Top level wrappers for InstallAPI frontend operations.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
llvm::PointerUnion< const Diagnostic *, const StoredDiagnostic * > DiagOrStoredDiag
SarifResultLevel getSarifResultLevel(DiagnosticsEngine::Level level)
SarifResultLevel
The level of severity associated with a SarifResult.
Definition Sarif.h:165
@ Result
The result type of a method or function.
Definition TypeBase.h:906
SarifRule addDiagnosticLevelToRule(SarifRule Rule, DiagnosticsEngine::Level Level)
std::optional< CharSourceRange > getExpansionRangeInFile(CharSourceRange Range, FileID FID, const SourceManager &SM)
Maps both endpoints of Range to their macro expansion, so that the range can be shown to a user.