-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSourceLoc.cpp
326 lines (282 loc) · 11 KB
/
SourceLoc.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//===--- SourceLoc.cpp - SourceLoc and SourceRange implementations --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/SourceLoc.h"
#include "swift/Basic/SourceManager.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
void SourceManager::verifyAllBuffers() const {
llvm::PrettyStackTraceString backtrace{
"Checking that all source buffers are still valid"
};
// FIXME: This depends on the buffer IDs chosen by llvm::SourceMgr.
LLVM_ATTRIBUTE_USED static char arbitraryTotal = 0;
for (unsigned i = 1, e = LLVMSourceMgr.getNumBuffers(); i <= e; ++i) {
auto *buffer = LLVMSourceMgr.getMemoryBuffer(i);
if (buffer->getBufferSize() == 0)
continue;
arbitraryTotal += buffer->getBufferStart()[0];
arbitraryTotal += buffer->getBufferEnd()[-1];
}
}
SourceLoc SourceManager::getCodeCompletionLoc() const {
return getLocForBufferStart(CodeCompletionBufferID)
.getAdvancedLoc(CodeCompletionOffset);
}
unsigned
SourceManager::addNewSourceBuffer(std::unique_ptr<llvm::MemoryBuffer> Buffer) {
assert(Buffer);
StringRef BufIdentifier = Buffer->getBufferIdentifier();
auto ID = LLVMSourceMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
BufIdentIDMap[BufIdentifier] = ID;
return ID;
}
unsigned SourceManager::addMemBufferCopy(llvm::MemoryBuffer *Buffer) {
return addMemBufferCopy(Buffer->getBuffer(), Buffer->getBufferIdentifier());
}
unsigned SourceManager::addMemBufferCopy(StringRef InputData,
StringRef BufIdentifier) {
auto Buffer = std::unique_ptr<llvm::MemoryBuffer>(
llvm::MemoryBuffer::getMemBufferCopy(InputData, BufIdentifier));
return addNewSourceBuffer(std::move(Buffer));
}
bool SourceManager::openVirtualFile(SourceLoc loc, StringRef name,
int lineOffset) {
CharSourceRange fullRange = getRangeForBuffer(findBufferContainingLoc(loc));
SourceLoc end;
auto nextRangeIter = VirtualFiles.upper_bound(loc.Value.getPointer());
if (nextRangeIter != VirtualFiles.end() &&
fullRange.contains(nextRangeIter->second.Range.getStart())) {
const VirtualFile &existingFile = nextRangeIter->second;
if (existingFile.Range.getStart() == loc) {
assert(existingFile.Name == name);
assert(existingFile.LineOffset == lineOffset);
return false;
}
assert(!existingFile.Range.contains(loc) &&
"must close current open file first");
end = nextRangeIter->second.Range.getStart();
} else {
end = fullRange.getEnd();
}
CharSourceRange range = CharSourceRange(*this, loc, end);
VirtualFiles[end.Value.getPointer()] = { range, name, lineOffset };
CachedVFile = {nullptr, nullptr};
return true;
}
void SourceManager::closeVirtualFile(SourceLoc end) {
auto *virtualFile = const_cast<VirtualFile *>(getVirtualFile(end));
if (!virtualFile) {
#ifndef NDEBUG
unsigned bufferID = findBufferContainingLoc(end);
CharSourceRange fullRange = getRangeForBuffer(bufferID);
assert((fullRange.getByteLength() == 0 ||
getVirtualFile(end.getAdvancedLoc(-1))) &&
"no open virtual file for this location");
assert(fullRange.getEnd() == end);
#endif
return;
}
CachedVFile = {nullptr, nullptr};
CharSourceRange oldRange = virtualFile->Range;
virtualFile->Range = CharSourceRange(*this, virtualFile->Range.getStart(),
end);
VirtualFiles[end.Value.getPointer()] = std::move(*virtualFile);
bool existed = VirtualFiles.erase(oldRange.getEnd().Value.getPointer());
assert(existed);
(void)existed;
}
const SourceManager::VirtualFile *
SourceManager::getVirtualFile(SourceLoc Loc) const {
const char *p = Loc.Value.getPointer();
if (CachedVFile.first == p)
return CachedVFile.second;
// Returns the first element that is >p.
auto VFileIt = VirtualFiles.upper_bound(p);
if (VFileIt != VirtualFiles.end() && VFileIt->second.Range.contains(Loc)) {
CachedVFile = { p, &VFileIt->second };
return CachedVFile.second;
}
return nullptr;
}
Optional<unsigned> SourceManager::getIDForBufferIdentifier(
StringRef BufIdentifier) {
auto It = BufIdentIDMap.find(BufIdentifier);
if (It == BufIdentIDMap.end())
return None;
return It->second;
}
StringRef SourceManager::getIdentifierForBuffer(unsigned bufferID) const {
auto *buffer = LLVMSourceMgr.getMemoryBuffer(bufferID);
assert(buffer && "invalid buffer ID");
return buffer->getBufferIdentifier();
}
CharSourceRange SourceManager::getRangeForBuffer(unsigned bufferID) const {
auto *buffer = LLVMSourceMgr.getMemoryBuffer(bufferID);
SourceLoc start{llvm::SMLoc::getFromPointer(buffer->getBufferStart())};
return CharSourceRange(start, buffer->getBufferSize());
}
unsigned SourceManager::getLocOffsetInBuffer(SourceLoc Loc,
unsigned BufferID) const {
assert(Loc.isValid() && "location should be valid");
auto *Buffer = LLVMSourceMgr.getMemoryBuffer(BufferID);
assert(Loc.Value.getPointer() >= Buffer->getBuffer().begin() &&
Loc.Value.getPointer() <= Buffer->getBuffer().end() &&
"Location is not from the specified buffer");
return Loc.Value.getPointer() - Buffer->getBuffer().begin();
}
unsigned SourceManager::getByteDistance(SourceLoc Start, SourceLoc End) const {
assert(Start.isValid() && "start location should be valid");
assert(End.isValid() && "end location should be valid");
#ifndef NDEBUG
unsigned BufferID = findBufferContainingLoc(Start);
auto *Buffer = LLVMSourceMgr.getMemoryBuffer(BufferID);
assert(End.Value.getPointer() >= Buffer->getBuffer().begin() &&
End.Value.getPointer() <= Buffer->getBuffer().end() &&
"End location is not from the same buffer");
#endif
// When we have a rope buffer, could be implemented in terms of
// getLocOffsetInBuffer().
return End.Value.getPointer() - Start.Value.getPointer();
}
StringRef SourceManager::getEntireTextForBuffer(unsigned BufferID) const {
return LLVMSourceMgr.getMemoryBuffer(BufferID)->getBuffer();
}
StringRef SourceManager::extractText(CharSourceRange Range,
Optional<unsigned> BufferID) const {
assert(Range.isValid() && "range should be valid");
if (!BufferID)
BufferID = findBufferContainingLoc(Range.getStart());
StringRef Buffer = LLVMSourceMgr.getMemoryBuffer(*BufferID)->getBuffer();
return Buffer.substr(getLocOffsetInBuffer(Range.getStart(), *BufferID),
Range.getByteLength());
}
unsigned SourceManager::findBufferContainingLoc(SourceLoc Loc) const {
assert(Loc.isValid());
// Search the buffers back-to front, so later alias buffers are
// visited first.
auto less_equal = std::less_equal<const char *>();
for (unsigned i = LLVMSourceMgr.getNumBuffers(), e = 1; i >= e; --i) {
auto Buf = LLVMSourceMgr.getMemoryBuffer(i);
if (less_equal(Buf->getBufferStart(), Loc.Value.getPointer()) &&
// Use <= here so that a pointer to the null at the end of the buffer
// is included as part of the buffer.
less_equal(Loc.Value.getPointer(), Buf->getBufferEnd()))
return i;
}
llvm_unreachable("no buffer containing location found");
}
void SourceRange::widen(SourceRange Other) {
if (Other.Start.Value.getPointer() < Start.Value.getPointer())
Start = Other.Start;
if (Other.End.Value.getPointer() > End.Value.getPointer())
End = Other.End;
}
void SourceLoc::printLineAndColumn(raw_ostream &OS,
const SourceManager &SM) const {
if (isInvalid()) {
OS << "<invalid loc>";
return;
}
auto LineAndCol = SM.getLineAndColumn(*this);
OS << "line:" << LineAndCol.first << ':' << LineAndCol.second;
}
void SourceLoc::print(raw_ostream &OS, const SourceManager &SM,
unsigned &LastBufferID) const {
if (isInvalid()) {
OS << "<invalid loc>";
return;
}
unsigned BufferID = SM.findBufferContainingLoc(*this);
if (BufferID != LastBufferID) {
OS << SM.getIdentifierForBuffer(BufferID);
LastBufferID = BufferID;
} else {
OS << "line";
}
auto LineAndCol = SM.getLineAndColumn(*this, BufferID);
OS << ':' << LineAndCol.first << ':' << LineAndCol.second;
}
void SourceLoc::dump(const SourceManager &SM) const {
print(llvm::errs(), SM);
}
void SourceRange::print(raw_ostream &OS, const SourceManager &SM,
unsigned &LastBufferID, bool PrintText) const {
// FIXME: CharSourceRange is a half-open character-based range, while
// SourceRange is a closed token-based range, so this conversion omits the
// last token in the range. Unfortunately, we can't actually get to the end
// of the token without using the Lex library, which would be a layering
// violation. This is still better than nothing.
CharSourceRange(SM, Start, End).print(OS, SM, LastBufferID, PrintText);
}
void SourceRange::dump(const SourceManager &SM) const {
print(llvm::errs(), SM);
}
CharSourceRange::CharSourceRange(const SourceManager &SM, SourceLoc Start,
SourceLoc End)
: Start(Start) {
assert(Start.isValid() == End.isValid() &&
"Start and end should either both be valid or both be invalid!");
if (Start.isValid())
ByteLength = SM.getByteDistance(Start, End);
}
void CharSourceRange::print(raw_ostream &OS, const SourceManager &SM,
unsigned &LastBufferID, bool PrintText) const {
OS << '[';
Start.print(OS, SM, LastBufferID);
OS << " - ";
getEnd().print(OS, SM, LastBufferID);
OS << ']';
if (Start.isInvalid() || getEnd().isInvalid())
return;
if (PrintText) {
OS << " RangeText=\""
<< StringRef(Start.Value.getPointer(),
getEnd().Value.getPointer() - Start.Value.getPointer() + 1)
<< '"';
}
}
void CharSourceRange::dump(const SourceManager &SM) const {
print(llvm::errs(), SM);
}
llvm::Optional<unsigned> SourceManager::resolveFromLineCol(unsigned BufferId,
unsigned Line,
unsigned Col) const {
if (Line == 0 || Col == 0) {
return None;
}
auto InputBuf = getLLVMSourceMgr().getMemoryBuffer(BufferId);
const char *Ptr = InputBuf->getBufferStart();
const char *End = InputBuf->getBufferEnd();
const char *LineStart = Ptr;
for (; Ptr < End; ++Ptr) {
if (*Ptr == '\n') {
--Line;
if (Line == 0)
break;
LineStart = Ptr+1;
}
}
if (Line != 0) {
return None;
}
Ptr = LineStart;
for (; Ptr < End; ++Ptr) {
--Col;
if (Col == 0)
return Ptr - InputBuf->getBufferStart();
if (*Ptr == '\n')
break;
}
return None;
}