Bug Summary

File:clang/lib/Format/SortJavaScriptImports.cpp
Warning:line 389, column 17
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SortJavaScriptImports.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Format -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Format -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-26-234817-15343-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Format/SortJavaScriptImports.cpp

/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Format/SortJavaScriptImports.cpp

1//===--- SortJavaScriptImports.cpp - Sort ES6 Imports -----------*- C++ -*-===//
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///
9/// \file
10/// This file implements a sort operation for JavaScript ES6 imports.
11///
12//===----------------------------------------------------------------------===//
13
14#include "SortJavaScriptImports.h"
15#include "TokenAnalyzer.h"
16#include "TokenAnnotator.h"
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/DiagnosticOptions.h"
19#include "clang/Basic/LLVM.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TokenKinds.h"
23#include "clang/Format/Format.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/Support/Debug.h"
27#include <algorithm>
28#include <string>
29
30#define DEBUG_TYPE"format-formatter" "format-formatter"
31
32namespace clang {
33namespace format {
34
35class FormatTokenLexer;
36
37using clang::format::FormatStyle;
38
39// An imported symbol in a JavaScript ES6 import/export, possibly aliased.
40struct JsImportedSymbol {
41 StringRef Symbol;
42 StringRef Alias;
43 SourceRange Range;
44
45 bool operator==(const JsImportedSymbol &RHS) const {
46 // Ignore Range for comparison, it is only used to stitch code together,
47 // but imports at different code locations are still conceptually the same.
48 return Symbol == RHS.Symbol && Alias == RHS.Alias;
49 }
50};
51
52// An ES6 module reference.
53//
54// ES6 implements a module system, where individual modules (~= source files)
55// can reference other modules, either importing symbols from them, or exporting
56// symbols from them:
57// import {foo} from 'foo';
58// export {foo};
59// export {bar} from 'bar';
60//
61// `export`s with URLs are syntactic sugar for an import of the symbol from the
62// URL, followed by an export of the symbol, allowing this code to treat both
63// statements more or less identically, with the exception being that `export`s
64// are sorted last.
65//
66// imports and exports support individual symbols, but also a wildcard syntax:
67// import * as prefix from 'foo';
68// export * from 'bar';
69//
70// This struct represents both exports and imports to build up the information
71// required for sorting module references.
72struct JsModuleReference {
73 bool FormattingOff = false;
74 bool IsExport = false;
75 // Module references are sorted into these categories, in order.
76 enum ReferenceCategory {
77 SIDE_EFFECT, // "import 'something';"
78 ABSOLUTE, // from 'something'
79 RELATIVE_PARENT, // from '../*'
80 RELATIVE, // from './*'
81 };
82 ReferenceCategory Category = ReferenceCategory::SIDE_EFFECT;
83 // The URL imported, e.g. `import .. from 'url';`. Empty for `export {a, b};`.
84 StringRef URL;
85 // Prefix from "import * as prefix". Empty for symbol imports and `export *`.
86 // Implies an empty names list.
87 StringRef Prefix;
88 // Default import from "import DefaultName from '...';".
89 StringRef DefaultImport;
90 // Symbols from `import {SymbolA, SymbolB, ...} from ...;`.
91 SmallVector<JsImportedSymbol, 1> Symbols;
92 // Whether some symbols were merged into this one. Controls if the module
93 // reference needs re-formatting.
94 bool SymbolsMerged = false;
95 // The source location just after { and just before } in the import.
96 // Extracted eagerly to allow modification of Symbols later on.
97 SourceLocation SymbolsStart, SymbolsEnd;
98 // Textual position of the import/export, including preceding and trailing
99 // comments.
100 SourceRange Range;
101};
102
103bool operator<(const JsModuleReference &LHS, const JsModuleReference &RHS) {
104 if (LHS.IsExport != RHS.IsExport)
105 return LHS.IsExport < RHS.IsExport;
106 if (LHS.Category != RHS.Category)
107 return LHS.Category < RHS.Category;
108 if (LHS.Category == JsModuleReference::ReferenceCategory::SIDE_EFFECT)
109 // Side effect imports might be ordering sensitive. Consider them equal so
110 // that they maintain their relative order in the stable sort below.
111 // This retains transitivity because LHS.Category == RHS.Category here.
112 return false;
113 // Empty URLs sort *last* (for export {...};).
114 if (LHS.URL.empty() != RHS.URL.empty())
115 return LHS.URL.empty() < RHS.URL.empty();
116 if (int Res = LHS.URL.compare_insensitive(RHS.URL))
117 return Res < 0;
118 // '*' imports (with prefix) sort before {a, b, ...} imports.
119 if (LHS.Prefix.empty() != RHS.Prefix.empty())
120 return LHS.Prefix.empty() < RHS.Prefix.empty();
121 if (LHS.Prefix != RHS.Prefix)
122 return LHS.Prefix > RHS.Prefix;
123 return false;
124}
125
126// JavaScriptImportSorter sorts JavaScript ES6 imports and exports. It is
127// implemented as a TokenAnalyzer because ES6 imports have substantial syntactic
128// structure, making it messy to sort them using regular expressions.
129class JavaScriptImportSorter : public TokenAnalyzer {
130public:
131 JavaScriptImportSorter(const Environment &Env, const FormatStyle &Style)
132 : TokenAnalyzer(Env, Style),
133 FileContents(Env.getSourceManager().getBufferData(Env.getFileID())) {}
134
135 std::pair<tooling::Replacements, unsigned>
136 analyze(TokenAnnotator &Annotator,
137 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
138 FormatTokenLexer &Tokens) override {
139 tooling::Replacements Result;
140 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
141
142 const AdditionalKeywords &Keywords = Tokens.getKeywords();
143 SmallVector<JsModuleReference, 16> References;
144 AnnotatedLine *FirstNonImportLine;
145 std::tie(References, FirstNonImportLine) =
146 parseModuleReferences(Keywords, AnnotatedLines);
1
Calling 'JavaScriptImportSorter::parseModuleReferences'
147
148 if (References.empty())
149 return {Result, 0};
150
151 // The text range of all parsed imports, to be replaced later.
152 SourceRange InsertionPoint = References[0].Range;
153 InsertionPoint.setEnd(References[References.size() - 1].Range.getEnd());
154
155 References = sortModuleReferences(References);
156
157 std::string ReferencesText;
158 for (unsigned I = 0, E = References.size(); I != E; ++I) {
159 JsModuleReference Reference = References[I];
160 appendReference(ReferencesText, Reference);
161 if (I + 1 < E) {
162 // Insert breaks between imports and exports.
163 ReferencesText += "\n";
164 // Separate imports groups with two line breaks, but keep all exports
165 // in a single group.
166 if (!Reference.IsExport &&
167 (Reference.IsExport != References[I + 1].IsExport ||
168 Reference.Category != References[I + 1].Category))
169 ReferencesText += "\n";
170 }
171 }
172 llvm::StringRef PreviousText = getSourceText(InsertionPoint);
173 if (ReferencesText == PreviousText)
174 return {Result, 0};
175
176 // The loop above might collapse previously existing line breaks between
177 // import blocks, and thus shrink the file. SortIncludes must not shrink
178 // overall source length as there is currently no re-calculation of ranges
179 // after applying source sorting.
180 // This loop just backfills trailing spaces after the imports, which are
181 // harmless and will be stripped by the subsequent formatting pass.
182 // FIXME: A better long term fix is to re-calculate Ranges after sorting.
183 unsigned PreviousSize = PreviousText.size();
184 while (ReferencesText.size() < PreviousSize) {
185 ReferencesText += " ";
186 }
187
188 // Separate references from the main code body of the file.
189 if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2 &&
190 !(FirstNonImportLine->First->is(tok::comment) &&
191 FirstNonImportLine->First->TokenText.trim() == "// clang-format on"))
192 ReferencesText += "\n";
193
194 LLVM_DEBUG(llvm::dbgs() << "Replacing imports:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { llvm::dbgs() << "Replacing imports:\n"
<< PreviousText << "\nwith:\n" << ReferencesText
<< "\n"; } } while (false)
195 << PreviousText << "\nwith:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { llvm::dbgs() << "Replacing imports:\n"
<< PreviousText << "\nwith:\n" << ReferencesText
<< "\n"; } } while (false)
196 << ReferencesText << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { llvm::dbgs() << "Replacing imports:\n"
<< PreviousText << "\nwith:\n" << ReferencesText
<< "\n"; } } while (false)
;
197 auto Err = Result.add(tooling::Replacement(
198 Env.getSourceManager(), CharSourceRange::getCharRange(InsertionPoint),
199 ReferencesText));
200 // FIXME: better error handling. For now, just print error message and skip
201 // the replacement for the release version.
202 if (Err) {
203 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
204 assert(false)(static_cast <bool> (false) ? void (0) : __assert_fail (
"false", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/Format/SortJavaScriptImports.cpp"
, 204, __extension__ __PRETTY_FUNCTION__))
;
205 }
206
207 return {Result, 0};
208 }
209
210private:
211 FormatToken *Current;
212 FormatToken *LineEnd;
213
214 FormatToken invalidToken;
215
216 StringRef FileContents;
217
218 void skipComments() { Current = skipComments(Current); }
219
220 FormatToken *skipComments(FormatToken *Tok) {
221 while (Tok && Tok->is(tok::comment))
222 Tok = Tok->Next;
223 return Tok;
224 }
225
226 void nextToken() {
227 Current = Current->Next;
228 skipComments();
229 if (!Current || Current == LineEnd->Next) {
230 // Set the current token to an invalid token, so that further parsing on
231 // this line fails.
232 invalidToken.Tok.setKind(tok::unknown);
233 Current = &invalidToken;
234 }
235 }
236
237 StringRef getSourceText(SourceRange Range) {
238 return getSourceText(Range.getBegin(), Range.getEnd());
239 }
240
241 StringRef getSourceText(SourceLocation Begin, SourceLocation End) {
242 const SourceManager &SM = Env.getSourceManager();
243 return FileContents.substr(SM.getFileOffset(Begin),
244 SM.getFileOffset(End) - SM.getFileOffset(Begin));
245 }
246
247 // Sorts the given module references.
248 // Imports can have formatting disabled (FormattingOff), so the code below
249 // skips runs of "no-formatting" module references, and sorts/merges the
250 // references that have formatting enabled in individual chunks.
251 SmallVector<JsModuleReference, 16>
252 sortModuleReferences(const SmallVector<JsModuleReference, 16> &References) {
253 // Sort module references.
254 // Imports can have formatting disabled (FormattingOff), so the code below
255 // skips runs of "no-formatting" module references, and sorts other
256 // references per group.
257 const auto *Start = References.begin();
258 SmallVector<JsModuleReference, 16> ReferencesSorted;
259 while (Start != References.end()) {
260 while (Start != References.end() && Start->FormattingOff) {
261 // Skip over all imports w/ disabled formatting.
262 ReferencesSorted.push_back(*Start);
263 Start++;
264 }
265 SmallVector<JsModuleReference, 16> SortChunk;
266 while (Start != References.end() && !Start->FormattingOff) {
267 // Skip over all imports w/ disabled formatting.
268 SortChunk.push_back(*Start);
269 Start++;
270 }
271 llvm::stable_sort(SortChunk);
272 mergeModuleReferences(SortChunk);
273 ReferencesSorted.insert(ReferencesSorted.end(), SortChunk.begin(),
274 SortChunk.end());
275 }
276 return ReferencesSorted;
277 }
278
279 // Merge module references.
280 // After sorting, find all references that import named symbols from the
281 // same URL and merge their names. E.g.
282 // import {X} from 'a';
283 // import {Y} from 'a';
284 // should be rewritten to:
285 // import {X, Y} from 'a';
286 // Note: this modifies the passed in ``References`` vector (by removing no
287 // longer needed references).
288 void mergeModuleReferences(SmallVector<JsModuleReference, 16> &References) {
289 if (References.empty())
290 return;
291 JsModuleReference *PreviousReference = References.begin();
292 auto *Reference = std::next(References.begin());
293 while (Reference != References.end()) {
294 // Skip:
295 // import 'foo';
296 // import * as foo from 'foo'; on either previous or this.
297 // import Default from 'foo'; on either previous or this.
298 // mismatching
299 if (Reference->Category == JsModuleReference::SIDE_EFFECT ||
300 PreviousReference->Category == JsModuleReference::SIDE_EFFECT ||
301 Reference->IsExport != PreviousReference->IsExport ||
302 !PreviousReference->Prefix.empty() || !Reference->Prefix.empty() ||
303 !PreviousReference->DefaultImport.empty() ||
304 !Reference->DefaultImport.empty() || Reference->Symbols.empty() ||
305 PreviousReference->URL != Reference->URL) {
306 PreviousReference = Reference;
307 ++Reference;
308 continue;
309 }
310 // Merge symbols from identical imports.
311 PreviousReference->Symbols.append(Reference->Symbols);
312 PreviousReference->SymbolsMerged = true;
313 // Remove the merged import.
314 Reference = References.erase(Reference);
315 }
316 }
317
318 // Appends ``Reference`` to ``Buffer``.
319 void appendReference(std::string &Buffer, JsModuleReference &Reference) {
320 if (Reference.FormattingOff) {
321 Buffer +=
322 getSourceText(Reference.Range.getBegin(), Reference.Range.getEnd());
323 return;
324 }
325 // Sort the individual symbols within the import.
326 // E.g. `import {b, a} from 'x';` -> `import {a, b} from 'x';`
327 SmallVector<JsImportedSymbol, 1> Symbols = Reference.Symbols;
328 llvm::stable_sort(
329 Symbols, [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) {
330 return LHS.Symbol.compare_insensitive(RHS.Symbol) < 0;
331 });
332 if (!Reference.SymbolsMerged && Symbols == Reference.Symbols) {
333 // Symbols didn't change, just emit the entire module reference.
334 StringRef ReferenceStmt = getSourceText(Reference.Range);
335 Buffer += ReferenceStmt;
336 return;
337 }
338 // Stitch together the module reference start...
339 Buffer += getSourceText(Reference.Range.getBegin(), Reference.SymbolsStart);
340 // ... then the references in order ...
341 for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) {
342 if (I != Symbols.begin())
343 Buffer += ",";
344 Buffer += getSourceText(I->Range);
345 }
346 // ... followed by the module reference end.
347 Buffer += getSourceText(Reference.SymbolsEnd, Reference.Range.getEnd());
348 }
349
350 // Parses module references in the given lines. Returns the module references,
351 // and a pointer to the first "main code" line if that is adjacent to the
352 // affected lines of module references, nullptr otherwise.
353 std::pair<SmallVector<JsModuleReference, 16>, AnnotatedLine *>
354 parseModuleReferences(const AdditionalKeywords &Keywords,
355 SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
356 SmallVector<JsModuleReference, 16> References;
357 SourceLocation Start;
358 AnnotatedLine *FirstNonImportLine = nullptr;
359 bool AnyImportAffected = false;
360 bool FormattingOff = false;
361 for (auto *Line : AnnotatedLines) {
2
Assuming '__begin2' is not equal to '__end2'
362 Current = Line->First;
363 LineEnd = Line->Last;
364 // clang-format comments toggle formatting on/off.
365 // This is tracked in FormattingOff here and on JsModuleReference.
366 while (Current && Current->is(tok::comment)) {
3
Assuming field 'Current' is null
367 StringRef CommentText = Current->TokenText.trim();
368 if (CommentText == "// clang-format off") {
369 FormattingOff = true;
370 } else if (CommentText == "// clang-format on") {
371 FormattingOff = false;
372 // Special case: consider a trailing "clang-format on" line to be part
373 // of the module reference, so that it gets moved around together with
374 // it (as opposed to the next module reference, which might get sorted
375 // around).
376 if (!References.empty()) {
377 References.back().Range.setEnd(Current->Tok.getEndLoc());
378 Start = Current->Tok.getEndLoc().getLocWithOffset(1);
379 }
380 }
381 // Handle all clang-format comments on a line, e.g. for an empty block.
382 Current = Current->Next;
383 }
384 skipComments();
385 if (Start.isInvalid() || References.empty())
4
Calling 'SourceLocation::isInvalid'
6
Returning from 'SourceLocation::isInvalid'
386 // After the first file level comment, consider line comments to be part
387 // of the import that immediately follows them by using the previously
388 // set Start.
389 Start = Line->First->Tok.getLocation();
7
Called C++ object pointer is null
390 if (!Current) {
391 // Only comments on this line. Could be the first non-import line.
392 FirstNonImportLine = Line;
393 continue;
394 }
395 JsModuleReference Reference;
396 Reference.FormattingOff = FormattingOff;
397 Reference.Range.setBegin(Start);
398 if (!parseModuleReference(Keywords, Reference)) {
399 if (!FirstNonImportLine)
400 FirstNonImportLine = Line; // if no comment before.
401 break;
402 }
403 FirstNonImportLine = nullptr;
404 AnyImportAffected = AnyImportAffected || Line->Affected;
405 Reference.Range.setEnd(LineEnd->Tok.getEndLoc());
406 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
407 llvm::dbgs() << "JsModuleReference: {"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
408 << "formatting_off: " << Reference.FormattingOffdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
409 << ", is_export: " << Reference.IsExportdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
410 << ", cat: " << Reference.Categorydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
411 << ", url: " << Reference.URLdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
412 << ", prefix: " << Reference.Prefix;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
413 for (size_t I = 0; I < Reference.Symbols.size(); ++I)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
414 llvm::dbgs() << ", " << Reference.Symbols[I].Symbol << " as "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
415 << Reference.Symbols[I].Alias;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
416 llvm::dbgs() << ", text: " << getSourceText(Reference.Range);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
417 llvm::dbgs() << "}\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
418 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { llvm::dbgs() << "JsModuleReference: {"
<< "formatting_off: " << Reference.FormattingOff
<< ", is_export: " << Reference.IsExport <<
", cat: " << Reference.Category << ", url: " <<
Reference.URL << ", prefix: " << Reference.Prefix
; for (size_t I = 0; I < Reference.Symbols.size(); ++I) llvm
::dbgs() << ", " << Reference.Symbols[I].Symbol <<
" as " << Reference.Symbols[I].Alias; llvm::dbgs() <<
", text: " << getSourceText(Reference.Range); llvm::dbgs
() << "}\n"; }; } } while (false)
;
419 References.push_back(Reference);
420 Start = SourceLocation();
421 }
422 // Sort imports if any import line was affected.
423 if (!AnyImportAffected)
424 References.clear();
425 return std::make_pair(References, FirstNonImportLine);
426 }
427
428 // Parses a JavaScript/ECMAScript 6 module reference.
429 // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules
430 // for grammar EBNF (production ModuleItem).
431 bool parseModuleReference(const AdditionalKeywords &Keywords,
432 JsModuleReference &Reference) {
433 if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export))
434 return false;
435 Reference.IsExport = Current->is(tok::kw_export);
436
437 nextToken();
438 if (Current->isStringLiteral() && !Reference.IsExport) {
439 // "import 'side-effect';"
440 Reference.Category = JsModuleReference::ReferenceCategory::SIDE_EFFECT;
441 Reference.URL =
442 Current->TokenText.substr(1, Current->TokenText.size() - 2);
443 return true;
444 }
445
446 if (!parseModuleBindings(Keywords, Reference))
447 return false;
448
449 if (Current->is(Keywords.kw_from)) {
450 // imports have a 'from' clause, exports might not.
451 nextToken();
452 if (!Current->isStringLiteral())
453 return false;
454 // URL = TokenText without the quotes.
455 Reference.URL =
456 Current->TokenText.substr(1, Current->TokenText.size() - 2);
457 if (Reference.URL.startswith(".."))
458 Reference.Category =
459 JsModuleReference::ReferenceCategory::RELATIVE_PARENT;
460 else if (Reference.URL.startswith("."))
461 Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
462 else
463 Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE;
464 } else {
465 // w/o URL groups with "empty".
466 Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE;
467 }
468 return true;
469 }
470
471 bool parseModuleBindings(const AdditionalKeywords &Keywords,
472 JsModuleReference &Reference) {
473 if (parseStarBinding(Keywords, Reference))
474 return true;
475 return parseNamedBindings(Keywords, Reference);
476 }
477
478 bool parseStarBinding(const AdditionalKeywords &Keywords,
479 JsModuleReference &Reference) {
480 // * as prefix from '...';
481 if (Current->isNot(tok::star))
482 return false;
483 nextToken();
484 if (Current->isNot(Keywords.kw_as))
485 return false;
486 nextToken();
487 if (Current->isNot(tok::identifier))
488 return false;
489 Reference.Prefix = Current->TokenText;
490 nextToken();
491 return true;
492 }
493
494 bool parseNamedBindings(const AdditionalKeywords &Keywords,
495 JsModuleReference &Reference) {
496 // eat a potential "import X, " prefix.
497 if (Current->is(tok::identifier)) {
498 Reference.DefaultImport = Current->TokenText;
499 nextToken();
500 if (Current->is(Keywords.kw_from))
501 return true;
502 if (Current->isNot(tok::comma))
503 return false;
504 nextToken(); // eat comma.
505 }
506 if (Current->isNot(tok::l_brace))
507 return false;
508
509 // {sym as alias, sym2 as ...} from '...';
510 Reference.SymbolsStart = Current->Tok.getEndLoc();
511 while (Current->isNot(tok::r_brace)) {
512 nextToken();
513 if (Current->is(tok::r_brace))
514 break;
515 if (!Current->isOneOf(tok::identifier, tok::kw_default))
516 return false;
517
518 JsImportedSymbol Symbol;
519 Symbol.Symbol = Current->TokenText;
520 // Make sure to include any preceding comments.
521 Symbol.Range.setBegin(
522 Current->getPreviousNonComment()->Next->WhitespaceRange.getBegin());
523 nextToken();
524
525 if (Current->is(Keywords.kw_as)) {
526 nextToken();
527 if (!Current->isOneOf(tok::identifier, tok::kw_default))
528 return false;
529 Symbol.Alias = Current->TokenText;
530 nextToken();
531 }
532 Symbol.Range.setEnd(Current->Tok.getLocation());
533 Reference.Symbols.push_back(Symbol);
534
535 if (!Current->isOneOf(tok::r_brace, tok::comma))
536 return false;
537 }
538 Reference.SymbolsEnd = Current->Tok.getLocation();
539 // For named imports with a trailing comma ("import {X,}"), consider the
540 // comma to be the end of the import list, so that it doesn't get removed.
541 if (Current->Previous->is(tok::comma))
542 Reference.SymbolsEnd = Current->Previous->Tok.getLocation();
543 nextToken(); // consume r_brace
544 return true;
545 }
546};
547
548tooling::Replacements sortJavaScriptImports(const FormatStyle &Style,
549 StringRef Code,
550 ArrayRef<tooling::Range> Ranges,
551 StringRef FileName) {
552 // FIXME: Cursor support.
553 return JavaScriptImportSorter(Environment(Code, FileName, Ranges), Style)
554 .process()
555 .first;
556}
557
558} // end namespace format
559} // end namespace clang

/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h

1//===- SourceLocation.h - Compact identifier for Source Files ---*- C++ -*-===//
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//
9/// \file
10/// Defines the clang::SourceLocation class and associated facilities.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_BASIC_SOURCELOCATION_H
15#define LLVM_CLANG_BASIC_SOURCELOCATION_H
16
17#include "clang/Basic/LLVM.h"
18#include "llvm/ADT/StringRef.h"
19#include <cassert>
20#include <cstdint>
21#include <string>
22#include <utility>
23
24namespace llvm {
25
26template <typename T> struct DenseMapInfo;
27
28class FoldingSetNodeID;
29template <typename T> struct FoldingSetTrait;
30
31} // namespace llvm
32
33namespace clang {
34
35class SourceManager;
36
37/// An opaque identifier used by SourceManager which refers to a
38/// source file (MemoryBuffer) along with its \#include path and \#line data.
39///
40class FileID {
41 /// A mostly-opaque identifier, where 0 is "invalid", >0 is
42 /// this module, and <-1 is something loaded from another module.
43 int ID = 0;
44
45public:
46 bool isValid() const { return ID != 0; }
47 bool isInvalid() const { return ID == 0; }
48
49 bool operator==(const FileID &RHS) const { return ID == RHS.ID; }
50 bool operator<(const FileID &RHS) const { return ID < RHS.ID; }
51 bool operator<=(const FileID &RHS) const { return ID <= RHS.ID; }
52 bool operator!=(const FileID &RHS) const { return !(*this == RHS); }
53 bool operator>(const FileID &RHS) const { return RHS < *this; }
54 bool operator>=(const FileID &RHS) const { return RHS <= *this; }
55
56 static FileID getSentinel() { return get(-1); }
57 unsigned getHashValue() const { return static_cast<unsigned>(ID); }
58
59private:
60 friend class ASTWriter;
61 friend class ASTReader;
62 friend class SourceManager;
63
64 static FileID get(int V) {
65 FileID F;
66 F.ID = V;
67 return F;
68 }
69
70 int getOpaqueValue() const { return ID; }
71};
72
73/// Encodes a location in the source. The SourceManager can decode this
74/// to get at the full include stack, line and column information.
75///
76/// Technically, a source location is simply an offset into the manager's view
77/// of the input source, which is all input buffers (including macro
78/// expansions) concatenated in an effectively arbitrary order. The manager
79/// actually maintains two blocks of input buffers. One, starting at offset
80/// 0 and growing upwards, contains all buffers from this module. The other,
81/// starting at the highest possible offset and growing downwards, contains
82/// buffers of loaded modules.
83///
84/// In addition, one bit of SourceLocation is used for quick access to the
85/// information whether the location is in a file or a macro expansion.
86///
87/// It is important that this type remains small. It is currently 32 bits wide.
88class SourceLocation {
89 friend class ASTReader;
90 friend class ASTWriter;
91 friend class SourceManager;
92 friend struct llvm::FoldingSetTrait<SourceLocation>;
93
94public:
95 using UIntTy = uint32_t;
96 using IntTy = int32_t;
97
98private:
99 UIntTy ID = 0;
100
101 enum : UIntTy { MacroIDBit = 1ULL << (8 * sizeof(UIntTy) - 1) };
102
103public:
104 bool isFileID() const { return (ID & MacroIDBit) == 0; }
105 bool isMacroID() const { return (ID & MacroIDBit) != 0; }
106
107 /// Return true if this is a valid SourceLocation object.
108 ///
109 /// Invalid SourceLocations are often used when events have no corresponding
110 /// location in the source (e.g. a diagnostic is required for a command line
111 /// option).
112 bool isValid() const { return ID != 0; }
113 bool isInvalid() const { return ID == 0; }
5
Returning the value 1, which participates in a condition later
114
115private:
116 /// Return the offset into the manager's global input view.
117 UIntTy getOffset() const { return ID & ~MacroIDBit; }
118
119 static SourceLocation getFileLoc(UIntTy ID) {
120 assert((ID & MacroIDBit) == 0 && "Ran out of source locations!")(static_cast <bool> ((ID & MacroIDBit) == 0 &&
"Ran out of source locations!") ? void (0) : __assert_fail (
"(ID & MacroIDBit) == 0 && \"Ran out of source locations!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 120, __extension__ __PRETTY_FUNCTION__))
;
121 SourceLocation L;
122 L.ID = ID;
123 return L;
124 }
125
126 static SourceLocation getMacroLoc(UIntTy ID) {
127 assert((ID & MacroIDBit) == 0 && "Ran out of source locations!")(static_cast <bool> ((ID & MacroIDBit) == 0 &&
"Ran out of source locations!") ? void (0) : __assert_fail (
"(ID & MacroIDBit) == 0 && \"Ran out of source locations!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 127, __extension__ __PRETTY_FUNCTION__))
;
128 SourceLocation L;
129 L.ID = MacroIDBit | ID;
130 return L;
131 }
132
133public:
134 /// Return a source location with the specified offset from this
135 /// SourceLocation.
136 SourceLocation getLocWithOffset(IntTy Offset) const {
137 assert(((getOffset()+Offset) & MacroIDBit) == 0 && "offset overflow")(static_cast <bool> (((getOffset()+Offset) & MacroIDBit
) == 0 && "offset overflow") ? void (0) : __assert_fail
("((getOffset()+Offset) & MacroIDBit) == 0 && \"offset overflow\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 137, __extension__ __PRETTY_FUNCTION__))
;
138 SourceLocation L;
139 L.ID = ID+Offset;
140 return L;
141 }
142
143 /// When a SourceLocation itself cannot be used, this returns
144 /// an (opaque) 32-bit integer encoding for it.
145 ///
146 /// This should only be passed to SourceLocation::getFromRawEncoding, it
147 /// should not be inspected directly.
148 UIntTy getRawEncoding() const { return ID; }
149
150 /// Turn a raw encoding of a SourceLocation object into
151 /// a real SourceLocation.
152 ///
153 /// \see getRawEncoding.
154 static SourceLocation getFromRawEncoding(UIntTy Encoding) {
155 SourceLocation X;
156 X.ID = Encoding;
157 return X;
158 }
159
160 /// When a SourceLocation itself cannot be used, this returns
161 /// an (opaque) pointer encoding for it.
162 ///
163 /// This should only be passed to SourceLocation::getFromPtrEncoding, it
164 /// should not be inspected directly.
165 void* getPtrEncoding() const {
166 // Double cast to avoid a warning "cast to pointer from integer of different
167 // size".
168 return (void*)(uintptr_t)getRawEncoding();
169 }
170
171 /// Turn a pointer encoding of a SourceLocation object back
172 /// into a real SourceLocation.
173 static SourceLocation getFromPtrEncoding(const void *Encoding) {
174 return getFromRawEncoding((SourceLocation::UIntTy)(uintptr_t)Encoding);
175 }
176
177 static bool isPairOfFileLocations(SourceLocation Start, SourceLocation End) {
178 return Start.isValid() && Start.isFileID() && End.isValid() &&
179 End.isFileID();
180 }
181
182 unsigned getHashValue() const;
183 void print(raw_ostream &OS, const SourceManager &SM) const;
184 std::string printToString(const SourceManager &SM) const;
185 void dump(const SourceManager &SM) const;
186};
187
188inline bool operator==(const SourceLocation &LHS, const SourceLocation &RHS) {
189 return LHS.getRawEncoding() == RHS.getRawEncoding();
190}
191
192inline bool operator!=(const SourceLocation &LHS, const SourceLocation &RHS) {
193 return !(LHS == RHS);
194}
195
196// Ordering is meaningful only if LHS and RHS have the same FileID!
197// Otherwise use SourceManager::isBeforeInTranslationUnit().
198inline bool operator<(const SourceLocation &LHS, const SourceLocation &RHS) {
199 return LHS.getRawEncoding() < RHS.getRawEncoding();
200}
201inline bool operator>(const SourceLocation &LHS, const SourceLocation &RHS) {
202 return LHS.getRawEncoding() > RHS.getRawEncoding();
203}
204inline bool operator<=(const SourceLocation &LHS, const SourceLocation &RHS) {
205 return LHS.getRawEncoding() <= RHS.getRawEncoding();
206}
207inline bool operator>=(const SourceLocation &LHS, const SourceLocation &RHS) {
208 return LHS.getRawEncoding() >= RHS.getRawEncoding();
209}
210
211/// A trivial tuple used to represent a source range.
212class SourceRange {
213 SourceLocation B;
214 SourceLocation E;
215
216public:
217 SourceRange() = default;
218 SourceRange(SourceLocation loc) : B(loc), E(loc) {}
219 SourceRange(SourceLocation begin, SourceLocation end) : B(begin), E(end) {}
220
221 SourceLocation getBegin() const { return B; }
222 SourceLocation getEnd() const { return E; }
223
224 void setBegin(SourceLocation b) { B = b; }
225 void setEnd(SourceLocation e) { E = e; }
226
227 bool isValid() const { return B.isValid() && E.isValid(); }
228 bool isInvalid() const { return !isValid(); }
229
230 bool operator==(const SourceRange &X) const {
231 return B == X.B && E == X.E;
232 }
233
234 bool operator!=(const SourceRange &X) const {
235 return B != X.B || E != X.E;
236 }
237
238 // Returns true iff other is wholly contained within this range.
239 bool fullyContains(const SourceRange &other) const {
240 return B <= other.B && E >= other.E;
241 }
242
243 void print(raw_ostream &OS, const SourceManager &SM) const;
244 std::string printToString(const SourceManager &SM) const;
245 void dump(const SourceManager &SM) const;
246};
247
248/// Represents a character-granular source range.
249///
250/// The underlying SourceRange can either specify the starting/ending character
251/// of the range, or it can specify the start of the range and the start of the
252/// last token of the range (a "token range"). In the token range case, the
253/// size of the last token must be measured to determine the actual end of the
254/// range.
255class CharSourceRange {
256 SourceRange Range;
257 bool IsTokenRange = false;
258
259public:
260 CharSourceRange() = default;
261 CharSourceRange(SourceRange R, bool ITR) : Range(R), IsTokenRange(ITR) {}
262
263 static CharSourceRange getTokenRange(SourceRange R) {
264 return CharSourceRange(R, true);
265 }
266
267 static CharSourceRange getCharRange(SourceRange R) {
268 return CharSourceRange(R, false);
269 }
270
271 static CharSourceRange getTokenRange(SourceLocation B, SourceLocation E) {
272 return getTokenRange(SourceRange(B, E));
273 }
274
275 static CharSourceRange getCharRange(SourceLocation B, SourceLocation E) {
276 return getCharRange(SourceRange(B, E));
277 }
278
279 /// Return true if the end of this range specifies the start of
280 /// the last token. Return false if the end of this range specifies the last
281 /// character in the range.
282 bool isTokenRange() const { return IsTokenRange; }
283 bool isCharRange() const { return !IsTokenRange; }
284
285 SourceLocation getBegin() const { return Range.getBegin(); }
286 SourceLocation getEnd() const { return Range.getEnd(); }
287 SourceRange getAsRange() const { return Range; }
288
289 void setBegin(SourceLocation b) { Range.setBegin(b); }
290 void setEnd(SourceLocation e) { Range.setEnd(e); }
291 void setTokenRange(bool TR) { IsTokenRange = TR; }
292
293 bool isValid() const { return Range.isValid(); }
294 bool isInvalid() const { return !isValid(); }
295};
296
297/// Represents an unpacked "presumed" location which can be presented
298/// to the user.
299///
300/// A 'presumed' location can be modified by \#line and GNU line marker
301/// directives and is always the expansion point of a normal location.
302///
303/// You can get a PresumedLoc from a SourceLocation with SourceManager.
304class PresumedLoc {
305 const char *Filename = nullptr;
306 FileID ID;
307 unsigned Line, Col;
308 SourceLocation IncludeLoc;
309
310public:
311 PresumedLoc() = default;
312 PresumedLoc(const char *FN, FileID FID, unsigned Ln, unsigned Co,
313 SourceLocation IL)
314 : Filename(FN), ID(FID), Line(Ln), Col(Co), IncludeLoc(IL) {}
315
316 /// Return true if this object is invalid or uninitialized.
317 ///
318 /// This occurs when created with invalid source locations or when walking
319 /// off the top of a \#include stack.
320 bool isInvalid() const { return Filename == nullptr; }
321 bool isValid() const { return Filename != nullptr; }
322
323 /// Return the presumed filename of this location.
324 ///
325 /// This can be affected by \#line etc.
326 const char *getFilename() const {
327 assert(isValid())(static_cast <bool> (isValid()) ? void (0) : __assert_fail
("isValid()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 327, __extension__ __PRETTY_FUNCTION__))
;
328 return Filename;
329 }
330
331 FileID getFileID() const {
332 assert(isValid())(static_cast <bool> (isValid()) ? void (0) : __assert_fail
("isValid()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 332, __extension__ __PRETTY_FUNCTION__))
;
333 return ID;
334 }
335
336 /// Return the presumed line number of this location.
337 ///
338 /// This can be affected by \#line etc.
339 unsigned getLine() const {
340 assert(isValid())(static_cast <bool> (isValid()) ? void (0) : __assert_fail
("isValid()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 340, __extension__ __PRETTY_FUNCTION__))
;
341 return Line;
342 }
343
344 /// Return the presumed column number of this location.
345 ///
346 /// This cannot be affected by \#line, but is packaged here for convenience.
347 unsigned getColumn() const {
348 assert(isValid())(static_cast <bool> (isValid()) ? void (0) : __assert_fail
("isValid()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 348, __extension__ __PRETTY_FUNCTION__))
;
349 return Col;
350 }
351
352 /// Return the presumed include location of this location.
353 ///
354 /// This can be affected by GNU linemarker directives.
355 SourceLocation getIncludeLoc() const {
356 assert(isValid())(static_cast <bool> (isValid()) ? void (0) : __assert_fail
("isValid()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 356, __extension__ __PRETTY_FUNCTION__))
;
357 return IncludeLoc;
358 }
359};
360
361class FileEntry;
362
363/// A SourceLocation and its associated SourceManager.
364///
365/// This is useful for argument passing to functions that expect both objects.
366///
367/// This class does not guarantee the presence of either the SourceManager or
368/// a valid SourceLocation. Clients should use `isValid()` and `hasManager()`
369/// before calling the member functions.
370class FullSourceLoc : public SourceLocation {
371 const SourceManager *SrcMgr = nullptr;
372
373public:
374 /// Creates a FullSourceLoc where isValid() returns \c false.
375 FullSourceLoc() = default;
376
377 explicit FullSourceLoc(SourceLocation Loc, const SourceManager &SM)
378 : SourceLocation(Loc), SrcMgr(&SM) {}
379
380 /// Checks whether the SourceManager is present.
381 bool hasManager() const { return SrcMgr != nullptr; }
382
383 /// \pre hasManager()
384 const SourceManager &getManager() const {
385 assert(SrcMgr && "SourceManager is NULL.")(static_cast <bool> (SrcMgr && "SourceManager is NULL."
) ? void (0) : __assert_fail ("SrcMgr && \"SourceManager is NULL.\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 385, __extension__ __PRETTY_FUNCTION__))
;
386 return *SrcMgr;
387 }
388
389 FileID getFileID() const;
390
391 FullSourceLoc getExpansionLoc() const;
392 FullSourceLoc getSpellingLoc() const;
393 FullSourceLoc getFileLoc() const;
394 PresumedLoc getPresumedLoc(bool UseLineDirectives = true) const;
395 bool isMacroArgExpansion(FullSourceLoc *StartLoc = nullptr) const;
396 FullSourceLoc getImmediateMacroCallerLoc() const;
397 std::pair<FullSourceLoc, StringRef> getModuleImportLoc() const;
398 unsigned getFileOffset() const;
399
400 unsigned getExpansionLineNumber(bool *Invalid = nullptr) const;
401 unsigned getExpansionColumnNumber(bool *Invalid = nullptr) const;
402
403 unsigned getSpellingLineNumber(bool *Invalid = nullptr) const;
404 unsigned getSpellingColumnNumber(bool *Invalid = nullptr) const;
405
406 const char *getCharacterData(bool *Invalid = nullptr) const;
407
408 unsigned getLineNumber(bool *Invalid = nullptr) const;
409 unsigned getColumnNumber(bool *Invalid = nullptr) const;
410
411 const FileEntry *getFileEntry() const;
412
413 /// Return a StringRef to the source buffer data for the
414 /// specified FileID.
415 StringRef getBufferData(bool *Invalid = nullptr) const;
416
417 /// Decompose the specified location into a raw FileID + Offset pair.
418 ///
419 /// The first element is the FileID, the second is the offset from the
420 /// start of the buffer of the location.
421 std::pair<FileID, unsigned> getDecomposedLoc() const;
422
423 bool isInSystemHeader() const;
424
425 /// Determines the order of 2 source locations in the translation unit.
426 ///
427 /// \returns true if this source location comes before 'Loc', false otherwise.
428 bool isBeforeInTranslationUnitThan(SourceLocation Loc) const;
429
430 /// Determines the order of 2 source locations in the translation unit.
431 ///
432 /// \returns true if this source location comes before 'Loc', false otherwise.
433 bool isBeforeInTranslationUnitThan(FullSourceLoc Loc) const {
434 assert(Loc.isValid())(static_cast <bool> (Loc.isValid()) ? void (0) : __assert_fail
("Loc.isValid()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 434, __extension__ __PRETTY_FUNCTION__))
;
435 assert(SrcMgr == Loc.SrcMgr && "Loc comes from another SourceManager!")(static_cast <bool> (SrcMgr == Loc.SrcMgr && "Loc comes from another SourceManager!"
) ? void (0) : __assert_fail ("SrcMgr == Loc.SrcMgr && \"Loc comes from another SourceManager!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include/clang/Basic/SourceLocation.h"
, 435, __extension__ __PRETTY_FUNCTION__))
;
436 return isBeforeInTranslationUnitThan((SourceLocation)Loc);
437 }
438
439 /// Comparison function class, useful for sorting FullSourceLocs.
440 struct BeforeThanCompare {
441 bool operator()(const FullSourceLoc& lhs, const FullSourceLoc& rhs) const {
442 return lhs.isBeforeInTranslationUnitThan(rhs);
443 }
444 };
445
446 /// Prints information about this FullSourceLoc to stderr.
447 ///
448 /// This is useful for debugging.
449 void dump() const;
450
451 friend bool
452 operator==(const FullSourceLoc &LHS, const FullSourceLoc &RHS) {
453 return LHS.getRawEncoding() == RHS.getRawEncoding() &&
454 LHS.SrcMgr == RHS.SrcMgr;
455 }
456
457 friend bool
458 operator!=(const FullSourceLoc &LHS, const FullSourceLoc &RHS) {
459 return !(LHS == RHS);
460 }
461};
462
463} // namespace clang
464
465namespace llvm {
466
467 /// Define DenseMapInfo so that FileID's can be used as keys in DenseMap and
468 /// DenseSets.
469 template <>
470 struct DenseMapInfo<clang::FileID> {
471 static clang::FileID getEmptyKey() {
472 return {};
473 }
474
475 static clang::FileID getTombstoneKey() {
476 return clang::FileID::getSentinel();
477 }
478
479 static unsigned getHashValue(clang::FileID S) {
480 return S.getHashValue();
481 }
482
483 static bool isEqual(clang::FileID LHS, clang::FileID RHS) {
484 return LHS == RHS;
485 }
486 };
487
488 /// Define DenseMapInfo so that SourceLocation's can be used as keys in
489 /// DenseMap and DenseSet. This trait class is eqivalent to
490 /// DenseMapInfo<unsigned> which uses SourceLocation::ID is used as a key.
491 template <> struct DenseMapInfo<clang::SourceLocation> {
492 static clang::SourceLocation getEmptyKey() {
493 constexpr clang::SourceLocation::UIntTy Zero = 0;
494 return clang::SourceLocation::getFromRawEncoding(~Zero);
495 }
496
497 static clang::SourceLocation getTombstoneKey() {
498 constexpr clang::SourceLocation::UIntTy Zero = 0;
499 return clang::SourceLocation::getFromRawEncoding(~Zero - 1);
500 }
501
502 static unsigned getHashValue(clang::SourceLocation Loc) {
503 return Loc.getHashValue();
504 }
505
506 static bool isEqual(clang::SourceLocation LHS, clang::SourceLocation RHS) {
507 return LHS == RHS;
508 }
509 };
510
511 // Allow calling FoldingSetNodeID::Add with SourceLocation object as parameter
512 template <> struct FoldingSetTrait<clang::SourceLocation> {
513 static void Profile(const clang::SourceLocation &X, FoldingSetNodeID &ID);
514 };
515
516} // namespace llvm
517
518#endif // LLVM_CLANG_BASIC_SOURCELOCATION_H