forked from facebook/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSourceErrorManager.cpp
More file actions
576 lines (503 loc) · 16.7 KB
/
SourceErrorManager.cpp
File metadata and controls
576 lines (503 loc) · 16.7 KB
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "hermes/Support/SourceErrorManager.h"
#include "hermes/Support/UTF8.h"
#include "llvh/ADT/DenseMap.h"
#include "llvh/Support/raw_ostream.h"
namespace hermes {
static const char sTooManyErrors[] = "too many errors emitted";
SourceErrorManager::ICoordTranslator::~ICoordTranslator() = default;
SourceErrorManager::SourceErrorManager()
: warningStatuses_((unsigned)Warning::_NumWarnings, true),
warningsAreErrors_((unsigned)Warning::_NumWarnings, false) {
sm_.setDiagHandler(SourceErrorManager::printDiagnostic, this);
}
void SourceErrorManager::BufferedMessage::addNote(
std::vector<MessageData> &bufferedNotes,
DiagKind dk,
SMLoc loc,
SMRange sm,
std::string &&msg) {
bufferedNotes.emplace_back(dk, loc, sm, std::move(msg));
if (!noteCount_)
firstNote_ = bufferedNotes.size() - 1;
++noteCount_;
}
llvh::iterator_range<const SourceErrorManager::MessageData *>
SourceErrorManager::BufferedMessage::notes(
const std::vector<MessageData> &bufferedNotes) const {
if (!noteCount_)
return {nullptr, nullptr};
return {
bufferedNotes.data() + firstNote_,
bufferedNotes.data() + firstNote_ + noteCount_};
}
void SourceErrorManager::enableBuffering() {
++bufferingEnabled_;
assert(bufferingEnabled_ != 0 && "unsigned counter overflow");
}
void SourceErrorManager::disableBuffering() {
assert(bufferingEnabled_ != 0 && "unsigned counter underflow");
if (--bufferingEnabled_ != 0)
return;
// Sort all messages.
std::sort(
bufferedMessages_.begin(),
bufferedMessages_.end(),
[](const BufferedMessage &a, const BufferedMessage &b) {
// Make sure the "too many errors" message is always last.
if (a.dk == DK_Error && !a.loc.isValid() && a.msg == sTooManyErrors)
return false;
if (b.dk == DK_Error && !b.loc.isValid() && b.msg == sTooManyErrors)
return true;
return a.loc.getPointer() < b.loc.getPointer();
});
// Print them.
for (const auto &bm : bufferedMessages_) {
doPrintMessage(bm.dk, bm.loc, bm.sm, bm.msg);
for (const auto ¬e : bm.notes(bufferedNotes_))
doPrintMessage(note.dk, note.loc, note.sm, note.msg);
}
// Clean the buffer.
bufferedMessages_.clear();
bufferedNotes_.clear();
}
unsigned SourceErrorManager::addNewSourceBuffer(
std::unique_ptr<llvh::MemoryBuffer> f) {
unsigned bufId = sm_.AddNewSourceBuffer(std::move(f), SMLoc{});
assert(
!isVirtualBufferId(bufId) && "unexpected virtual buf id from SourceMgr");
return bufId;
}
/// Add a source buffer which maps to a filename. It doesn't contain any
/// source and the only operation that can be performed on that buffer is to
/// obtain the filename.
unsigned SourceErrorManager::addNewVirtualSourceBuffer(
llvh::StringRef fileName) {
return indexToVirtualBufferId(virtualBufferNames_.insert(fileName));
}
llvh::StringRef SourceErrorManager::getBufferFileName(unsigned bufId) const {
if (isVirtualBufferId(bufId))
return virtualBufferNames_[virtualBufferIdToIndex(bufId)];
else
return sm_.getMemoryBuffer(bufId)->getBufferIdentifier();
}
void SourceErrorManager::dumpCoords(
llvh::raw_ostream &OS,
const SourceCoords &coords) {
if (coords.isValid()) {
OS << getSourceUrl(coords.bufId) << ":" << coords.line << "," << coords.col;
} else {
OS << "none:0,0";
}
}
void SourceErrorManager::dumpCoords(llvh::raw_ostream &OS, SMLoc loc) {
SourceCoords coords;
findBufferLineAndLoc(loc, coords);
dumpCoords(OS, coords);
}
void SourceErrorManager::countAndGenMessage(
DiagKind dk,
SMLoc loc,
SMRange sm,
const Twine &msg) {
++messageCount_[dk];
doGenMessage(dk, loc, sm, msg);
if (LLVM_UNLIKELY(dk == DK_Error && messageCount_[DK_Error] == errorLimit_)) {
errorLimitReached_ = true;
doGenMessage(DK_Error, {}, {}, sTooManyErrors);
}
}
void SourceErrorManager::doGenMessage(
hermes::SourceErrorManager::DiagKind dk,
llvh::SMLoc loc,
llvh::SMRange sm,
llvh::Twine const &msg) {
if (bufferingEnabled_) {
// If this message is a note, try to associate it with the last message.
// Note that theoretically the first buffered message could be a note, so
// we play it safe here (even though it should never happen).
if (dk == DK_Note && !bufferedMessages_.empty()) {
bufferedMessages_.back().addNote(bufferedNotes_, dk, loc, sm, msg.str());
} else {
bufferedMessages_.emplace_back(dk, loc, sm, msg.str());
}
} else {
doPrintMessage(dk, loc, sm, msg);
}
}
void SourceErrorManager::doPrintMessage(
DiagKind dk,
SMLoc loc,
SMRange sm,
const Twine &msg) {
sm_.PrintMessage(
loc,
static_cast<llvh::SourceMgr::DiagKind>(dk),
msg,
sm.isValid() ? llvh::ArrayRef<SMRange>(sm)
: llvh::ArrayRef<SMRange>(llvh::None),
llvh::None,
outputOptions_.showColors);
}
void SourceErrorManager::message(
hermes::SourceErrorManager::DiagKind dk,
llvh::SMLoc loc,
llvh::SMRange sm,
llvh::Twine const &msg,
hermes::Warning w,
Subsystem subsystem) {
assert(dk <= DK_Note);
if (suppressMessages_) {
if (*suppressMessages_ == Subsystem::Unspecified) {
return;
}
if (subsystem == *suppressMessages_) {
return;
}
}
// Suppress all messages once the error limit has been reached.
if (LLVM_UNLIKELY(errorLimitReached_))
return;
if (dk == DK_Warning && !isWarningEnabled(w)) {
lastMessageSuppressed_ = true;
return;
}
// Automatically suppress notes if the last message was suppressed.
if (dk == DK_Note && lastMessageSuppressed_)
return;
lastMessageSuppressed_ = false;
/// Optionally upgrade warnings into errors.
if (dk == DK_Warning && isWarningAnError(w)) {
dk = DK_Error;
}
assert(static_cast<unsigned>(dk) < kMessageCountSize && "bounds check");
if (externalMessageBuffer_) {
externalMessageBuffer_->addMessage(dk, loc, sm, msg);
return;
}
countAndGenMessage(dk, loc, sm, msg);
}
void SourceErrorManager::message(
DiagKind dk,
SMLoc loc,
SMRange sm,
const Twine &msg,
Subsystem subsystem) {
message(dk, loc, sm, msg, Warning::NoWarning, subsystem);
}
void SourceErrorManager::message(
DiagKind dk,
SMRange sm,
const Twine &msg,
Subsystem subsystem) {
message(dk, sm.Start, sm, msg, subsystem);
}
void SourceErrorManager::message(
DiagKind dk,
SMLoc loc,
const Twine &msg,
Subsystem subsystem) {
message(dk, loc, SMRange{}, msg, subsystem);
}
/// Make sure the location doesn't point to \r or in the middle of a utf-8
/// sequence.
static inline SMLoc adjustSourceLocation(
const llvh::MemoryBuffer *buf,
SMLoc loc) {
const char *ptr = loc.getPointer();
// In the very unlikely case that `loc` points to a '\r', we skip backwards
// until we find another character, while being careful not to fall off the
// beginning of the buffer.
if (LLVM_UNLIKELY(*ptr == '\r') ||
LLVM_UNLIKELY(isUTF8ContinuationByte(*ptr))) {
const char *bufStart = buf->getBufferStart();
do {
if (LLVM_UNLIKELY(ptr == bufStart)) {
// This is highly unlikely but theoretically possible. There were only
// '\r' between `loc` and the start of the buffer.
break;
}
--ptr;
} while (*ptr == '\r' || isUTF8ContinuationByte(*ptr));
}
return SMLoc::getFromPointer(ptr);
}
bool SourceErrorManager::findBufferLineAndLoc(SMLoc loc, SourceCoords &result) {
if (!loc.isValid()) {
result.bufId = 0;
return false;
}
result.bufId = sm_.FindBufferContainingLoc(loc);
if (!result.bufId)
return false;
// Adjust the source location if necessary.
loc = adjustSourceLocation(sm_.getMemoryBuffer(result.bufId), loc);
auto lineCol = sm_.getLineAndColumn(loc, result.bufId);
result.line = lineCol.first;
result.col = lineCol.second;
return true;
}
bool SourceErrorManager::findBufferLineAndLoc(
llvh::SMLoc loc,
hermes::SourceErrorManager::SourceCoords &result,
bool translate) {
if (!findBufferLineAndLoc(loc, result))
return false;
if (translate && translator_)
translator_->translate(result);
return true;
}
uint32_t SourceErrorManager::findBufferIdForLoc(SMLoc loc) const {
return sm_.FindBufferContainingLoc(loc);
}
const llvh::MemoryBuffer *SourceErrorManager::findBufferForLoc(
SMLoc loc) const {
uint32_t bufID = findBufferIdForLoc(loc);
if (bufID == 0) {
return nullptr;
}
return sm_.getMemoryBuffer(bufID);
}
SMLoc SourceErrorManager::findSMLocFromCoords(SourceCoords coords) {
if (!coords.isValid())
return {};
// TODO: optimize this with caching, etc.
auto *buffer = getSourceBuffer(coords.bufId);
if (!buffer)
return {};
const char *cur = buffer->getBufferStart();
const char *end = buffer->getBufferEnd();
// Loop until we find the line or we reach EOF.
unsigned lineNumber = 1;
const char *lineEnd;
while ((lineEnd = (const char *)std::memchr(cur, '\n', end - cur)) !=
nullptr &&
lineNumber != coords.line) {
++lineNumber;
cur = lineEnd + 1;
}
// If we didn't find LF, the end of the buffer is the end of the line.
if (!lineEnd)
lineEnd = end;
// The last line we found is [cur..lineEnd) and its number is lineNumber.
// Is it the right one?
if (lineNumber != coords.line)
return {};
// Trim a CR at start and end to account for all crazy line endings.
if (cur != lineEnd && *cur == '\r')
++cur;
if (cur != lineEnd && *(lineEnd - 1) == '\r')
--lineEnd;
// Special case for empty line.
if (cur == lineEnd) {
// Column 1 or 0 in an empty line should work.
if (coords.col <= 1)
return SMLoc::getFromPointer(cur);
return {};
}
// Check for presence of UTF-8.
bool utf8 = false;
for (const char *p = cur; p != lineEnd; ++p) {
if (LLVM_UNLIKELY(*p & 0x80)) {
utf8 = true;
break;
}
}
// ASCII is easy - just add the offset.
if (LLVM_LIKELY(!utf8)) {
// Is the column in range?
if (coords.col > (size_t)(lineEnd - cur))
return {};
return SMLoc::getFromPointer(cur + coords.col - 1);
}
// Scan for the column while accounting for multi-byte characters.
unsigned column = 0;
for (; cur != lineEnd; ++cur) {
// Skip continuation bytes.
if (isUTF8ContinuationByte(*cur))
continue;
if (++column == coords.col)
return SMLoc::getFromPointer(cur);
}
return {};
}
/// Given an SMDiagnostic, return {sourceLine, caretLine}, respecting the error
/// output options
std::pair<std::string, std::string> SourceErrorManager::buildSourceAndCaretLine(
const llvh::SMDiagnostic &diag,
SourceErrorOutputOptions opts) {
// Decode our source line to UTF-32
// Ignore errors (UTF-8 errors will become replacement character)
// Don't try to decode past embedded nulls
// Map from narrow byte to column as we go
std::vector<uint32_t> narrowByteToColumn;
std::u32string sourceLine;
std::string narrowSourceLine = diag.getLineContents();
const char *cursor = narrowSourceLine.c_str();
while (*cursor) {
const char *prev = cursor;
sourceLine.push_back(decodeUTF8<true>(cursor, [](const llvh::Twine &) {}));
while (prev++ < cursor) {
narrowByteToColumn.push_back(sourceLine.size() - 1);
}
}
const size_t numColumns = sourceLine.size();
// Widening helper
auto widenColumn = [&](unsigned narrowColumn) -> unsigned {
return narrowColumn < narrowByteToColumn.size()
? narrowByteToColumn[narrowColumn]
: numColumns;
};
// Widen the caret column and ranges using our map
// Ranges are of the form [first, last)
assert(diag.getColumnNo() >= 0);
const size_t columnNo = widenColumn(diag.getColumnNo());
std::vector<std::pair<unsigned, unsigned>> ranges;
for (const auto &r : diag.getRanges()) {
ranges.emplace_back(widenColumn(r.first), widenColumn(r.second));
}
// Build the line with the caret and ranges.
std::string caretLine(numColumns + 1, ' ');
for (const auto &range : ranges) {
if (range.first < caretLine.size()) {
std::fill(
&caretLine[range.first],
&caretLine[std::min((size_t)range.second, caretLine.size())],
'~');
}
}
caretLine[std::min(size_t(columnNo), numColumns)] = '^';
caretLine.erase(caretLine.find_last_not_of(' ') + 1);
// Expand tabs to spaces in both the source and caret line
const size_t tabStop = SourceErrorOutputOptions::TabStop;
for (size_t pos = sourceLine.find('\t'); pos < sourceLine.size();
pos = sourceLine.find('\t', pos)) {
size_t expandCount = tabStop - (pos % tabStop);
sourceLine.replace(pos, 1, expandCount, ' ');
if (pos < caretLine.size()) {
// Reuse the character in the caretLine, so that tabs in tildes expand to
// more tildes
caretLine.replace(pos, 1, expandCount, caretLine[pos]);
}
pos += expandCount;
}
// Trim the lines to respect preferredMaxErrorWidth
// "Focus" around the caret, and any range intersecting it
// Note ranges are of the form [start, end) and not [start, length)
int focusStart = columnNo;
int focusLength = 1;
for (const auto &r : ranges) {
if (r.first <= size_t(columnNo) && size_t(columnNo) < r.second) {
focusStart = r.first;
focusLength = r.second - r.first;
break;
}
}
size_t desiredLineLength = std::max(
opts.preferredMaxErrorWidth,
focusLength + SourceErrorOutputOptions::MinimumSourceContext);
if (sourceLine.size() > desiredLineLength) {
int focusCenter = focusStart + focusLength / 2;
int leftTrimAmount = focusCenter - desiredLineLength / 2;
if (leftTrimAmount > 0) {
caretLine.erase(0, leftTrimAmount);
sourceLine.erase(0, leftTrimAmount);
std::fill(sourceLine.begin(), sourceLine.begin() + 3, '.');
}
if (sourceLine.size() > desiredLineLength) {
// Trim on the right
caretLine.erase(std::min(caretLine.size(), desiredLineLength));
sourceLine.erase(desiredLineLength);
std::fill(sourceLine.end() - 3, sourceLine.end(), '.');
}
}
// Convert sourceLine back to narrow
narrowSourceLine.clear();
for (uint32_t c : sourceLine) {
char buffer[UTF8CodepointMaxBytes] = {};
char *buffCursor = buffer;
encodeUTF8(buffCursor, c);
narrowSourceLine.append(buffer, buffCursor);
}
return {std::move(narrowSourceLine), std::move(caretLine)};
}
void SourceErrorManager::printDiagnostic(
const llvh::SMDiagnostic &diag,
void *ctx) {
using llvh::raw_ostream;
const SourceErrorManager *self = static_cast<SourceErrorManager *>(ctx);
const SourceErrorOutputOptions opts = self->outputOptions_;
auto &S = llvh::errs();
llvh::StringRef filename = diag.getFilename();
int lineNo = diag.getLineNo();
int columnNo = diag.getColumnNo();
// Helpers to conditionally set or reset a color
auto changeColor = [&](raw_ostream::Colors color) {
if (opts.showColors)
S.changeColor(color, true);
};
auto resetColor = [&]() {
if (opts.showColors)
S.resetColor();
};
changeColor(raw_ostream::SAVEDCOLOR);
if (!filename.empty()) {
S << (filename == "-" ? "<stdin>" : filename);
if (lineNo != -1) {
S << ':' << lineNo;
if (columnNo != -1)
S << ':' << (columnNo + 1);
}
S << ": ";
}
switch (diag.getKind()) {
case llvh::SourceMgr::DK_Error:
changeColor(raw_ostream::RED);
S << "error: ";
break;
case llvh::SourceMgr::DK_Warning:
changeColor(raw_ostream::MAGENTA);
S << "warning: ";
break;
case llvh::SourceMgr::DK_Note:
changeColor(raw_ostream::BLACK);
S << "note: ";
break;
case llvh::SourceMgr::DK_Remark:
changeColor(raw_ostream::BLACK);
S << "remark: ";
break;
}
resetColor();
changeColor(raw_ostream::SAVEDCOLOR);
S << diag.getMessage() << '\n';
resetColor();
if (lineNo == -1 || columnNo == -1)
return;
std::string sourceLine;
std::string caretLine;
std::tie(sourceLine, caretLine) = buildSourceAndCaretLine(diag, opts);
// Check for non-ASCII characters, which may have a width > 1
// If we find them, don't try to show the caret line
// TODO: bravely teach buildSourceAndCaretLine to use wcwidth(), lifting this
// restriction
bool showCaret = isAllASCII(sourceLine.begin(), sourceLine.end());
S << sourceLine << '\n';
if (showCaret) {
changeColor(raw_ostream::GREEN);
S << caretLine << '\n';
resetColor();
}
}
SMLoc SourceErrorManager::convertEndToLocation(SMRange range) {
// If the range is empty, return the starting point.
if (range.Start == range.End)
return range.Start;
return SMLoc::getFromPointer(range.End.getPointer() - 1);
}
} // namespace hermes