blob: a55ad881d01271490839974aea50b40152137ca8 [file] [log] [blame]
Chris Lattner1b30e1ac2009-06-21 03:36:54 +00001//===- SourceMgr.cpp - Manager for Simple Source Buffers & Diagnostics ----===//
Chris Lattner8db9bc72009-03-13 07:05:43 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner1b30e1ac2009-06-21 03:36:54 +000010// This file implements the SourceMgr class. This class is used as a simple
11// substrate for diagnostics, #include handling, and other low level things for
12// simple parsers.
Chris Lattner8db9bc72009-03-13 07:05:43 +000013//
14//===----------------------------------------------------------------------===//
15
Chandler Carruth6bda14b2017-06-06 11:49:48 +000016#include "llvm/Support/SourceMgr.h"
Eugene Zelenko454d0ce2017-02-15 22:17:02 +000017#include "llvm/ADT/ArrayRef.h"
David Majnemer562e8292016-08-12 00:18:03 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/ADT/SmallVector.h"
Eugene Zelenko454d0ce2017-02-15 22:17:02 +000020#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/Twine.h"
Eugene Zelenko454d0ce2017-02-15 22:17:02 +000022#include "llvm/Support/ErrorOr.h"
Jordan Roseefd8f802013-01-10 18:50:15 +000023#include "llvm/Support/Locale.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Support/MemoryBuffer.h"
Yaron Keren15217202014-05-16 13:16:30 +000025#include "llvm/Support/Path.h"
Eugene Zelenko454d0ce2017-02-15 22:17:02 +000026#include "llvm/Support/SMLoc.h"
Joel E. Denny3e665092018-10-24 21:46:42 +000027#include "llvm/Support/WithColor.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000028#include "llvm/Support/raw_ostream.h"
Eugene Zelenko454d0ce2017-02-15 22:17:02 +000029#include <algorithm>
30#include <cassert>
31#include <cstddef>
Graydon Hoare54fe2082018-04-07 00:44:02 +000032#include <limits>
Eugene Zelenko454d0ce2017-02-15 22:17:02 +000033#include <memory>
34#include <string>
35#include <utility>
36
Chris Lattner8db9bc72009-03-13 07:05:43 +000037using namespace llvm;
38
Jordan Roseefd8f802013-01-10 18:50:15 +000039static const size_t TabStop = 8;
40
Dmitri Gribenkoa5b27a72014-07-09 08:30:15 +000041unsigned SourceMgr::AddIncludeFile(const std::string &Filename,
42 SMLoc IncludeLoc,
43 std::string &IncludedFile) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +000044 IncludedFile = Filename;
Rafael Espindolaadf21f22014-07-06 17:43:13 +000045 ErrorOr<std::unique_ptr<MemoryBuffer>> NewBufOrErr =
Matt Arsenault6e863d12014-11-06 01:13:27 +000046 MemoryBuffer::getFile(IncludedFile);
Chris Lattner976af622009-06-21 05:06:04 +000047
48 // If the file didn't exist directly, see if it's in an include path.
Rafael Espindolaadf21f22014-07-06 17:43:13 +000049 for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBufOrErr;
50 ++i) {
51 IncludedFile =
52 IncludeDirectories[i] + sys::path::get_separator().data() + Filename;
Matt Arsenault6e863d12014-11-06 01:13:27 +000053 NewBufOrErr = MemoryBuffer::getFile(IncludedFile);
Chris Lattner976af622009-06-21 05:06:04 +000054 }
Mikhail Glushenkov84afae32010-01-27 10:13:11 +000055
Rafael Espindolaadf21f22014-07-06 17:43:13 +000056 if (!NewBufOrErr)
Alp Tokera55b95b2014-07-06 10:33:31 +000057 return 0;
Chris Lattner976af622009-06-21 05:06:04 +000058
David Blaikie1961f142014-08-21 20:44:56 +000059 return AddNewSourceBuffer(std::move(*NewBufOrErr), IncludeLoc);
Chris Lattner976af622009-06-21 05:06:04 +000060}
61
Alp Tokera55b95b2014-07-06 10:33:31 +000062unsigned SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
Chris Lattner8db9bc72009-03-13 07:05:43 +000063 for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
Chris Lattner87710ca2009-03-13 16:01:53 +000064 if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
Chris Lattner0f6dc782009-03-18 20:36:45 +000065 // Use <= here so that a pointer to the null at the end of the buffer
66 // is included as part of the buffer.
67 Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
Alp Tokera55b95b2014-07-06 10:33:31 +000068 return i + 1;
69 return 0;
Chris Lattner8db9bc72009-03-13 07:05:43 +000070}
71
Graydon Hoare54fe2082018-04-07 00:44:02 +000072template <typename T>
73unsigned SourceMgr::SrcBuffer::getLineNumber(const char *Ptr) const {
74
75 // Ensure OffsetCache is allocated and populated with offsets of all the
76 // '\n' bytes.
77 std::vector<T> *Offsets = nullptr;
78 if (OffsetCache.isNull()) {
79 Offsets = new std::vector<T>();
80 OffsetCache = Offsets;
81 size_t Sz = Buffer->getBufferSize();
82 assert(Sz <= std::numeric_limits<T>::max());
83 StringRef S = Buffer->getBuffer();
84 for (size_t N = 0; N < Sz; ++N) {
85 if (S[N] == '\n') {
86 Offsets->push_back(static_cast<T>(N));
87 }
88 }
89 } else {
90 Offsets = OffsetCache.get<std::vector<T> *>();
91 }
92
93 const char *BufStart = Buffer->getBufferStart();
94 assert(Ptr >= BufStart && Ptr <= Buffer->getBufferEnd());
95 ptrdiff_t PtrDiff = Ptr - BufStart;
96 assert(PtrDiff >= 0 && static_cast<size_t>(PtrDiff) <= std::numeric_limits<T>::max());
97 T PtrOffset = static_cast<T>(PtrDiff);
98
99 // std::lower_bound returns the first EOL offset that's not-less-than
100 // PtrOffset, meaning the EOL that _ends the line_ that PtrOffset is on
101 // (including if PtrOffset refers to the EOL itself). If there's no such
102 // EOL, returns end().
103 auto EOL = std::lower_bound(Offsets->begin(), Offsets->end(), PtrOffset);
104
105 // Lines count from 1, so add 1 to the distance from the 0th line.
106 return (1 + (EOL - Offsets->begin()));
107}
108
109SourceMgr::SrcBuffer::SrcBuffer(SourceMgr::SrcBuffer &&Other)
110 : Buffer(std::move(Other.Buffer)),
111 OffsetCache(Other.OffsetCache),
112 IncludeLoc(Other.IncludeLoc) {
113 Other.OffsetCache = nullptr;
114}
115
116SourceMgr::SrcBuffer::~SrcBuffer() {
117 if (!OffsetCache.isNull()) {
118 if (OffsetCache.is<std::vector<uint8_t>*>())
119 delete OffsetCache.get<std::vector<uint8_t>*>();
120 else if (OffsetCache.is<std::vector<uint16_t>*>())
121 delete OffsetCache.get<std::vector<uint16_t>*>();
122 else if (OffsetCache.is<std::vector<uint32_t>*>())
123 delete OffsetCache.get<std::vector<uint32_t>*>();
124 else
125 delete OffsetCache.get<std::vector<uint64_t>*>();
126 OffsetCache = nullptr;
127 }
128}
129
Chris Lattner9322ba82012-05-05 22:17:32 +0000130std::pair<unsigned, unsigned>
Alp Tokera55b95b2014-07-06 10:33:31 +0000131SourceMgr::getLineAndColumn(SMLoc Loc, unsigned BufferID) const {
132 if (!BufferID)
133 BufferID = FindBufferContainingLoc(Loc);
134 assert(BufferID && "Invalid Location!");
Mikhail Glushenkov84afae32010-01-27 10:13:11 +0000135
Graydon Hoare54fe2082018-04-07 00:44:02 +0000136 auto &SB = getBufferInfo(BufferID);
137 const char *Ptr = Loc.getPointer();
Mikhail Glushenkov84afae32010-01-27 10:13:11 +0000138
Graydon Hoare54fe2082018-04-07 00:44:02 +0000139 size_t Sz = SB.Buffer->getBufferSize();
Graydon Hoare54fe2082018-04-07 00:44:02 +0000140 unsigned LineNo;
141 if (Sz <= std::numeric_limits<uint8_t>::max())
142 LineNo = SB.getLineNumber<uint8_t>(Ptr);
143 else if (Sz <= std::numeric_limits<uint16_t>::max())
144 LineNo = SB.getLineNumber<uint16_t>(Ptr);
145 else if (Sz <= std::numeric_limits<uint32_t>::max())
146 LineNo = SB.getLineNumber<uint32_t>(Ptr);
147 else
148 LineNo = SB.getLineNumber<uint64_t>(Ptr);
Mikhail Glushenkov84afae32010-01-27 10:13:11 +0000149
Graydon Hoare54fe2082018-04-07 00:44:02 +0000150 const char *BufStart = SB.Buffer->getBufferStart();
Chris Lattner9322ba82012-05-05 22:17:32 +0000151 size_t NewlineOffs = StringRef(BufStart, Ptr-BufStart).find_last_of("\n\r");
Matt Beaumont-Gaya1b3b002012-05-07 18:12:42 +0000152 if (NewlineOffs == StringRef::npos) NewlineOffs = ~(size_t)0;
Chris Lattner9322ba82012-05-05 22:17:32 +0000153 return std::make_pair(LineNo, Ptr-BufStart-NewlineOffs);
Chris Lattner8db9bc72009-03-13 07:05:43 +0000154}
155
Chris Lattnercc64cc92009-07-02 22:24:20 +0000156void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
Chris Lattner526c8cb2009-06-21 03:39:35 +0000157 if (IncludeLoc == SMLoc()) return; // Top of stack.
Mikhail Glushenkov84afae32010-01-27 10:13:11 +0000158
Alp Tokera55b95b2014-07-06 10:33:31 +0000159 unsigned CurBuf = FindBufferContainingLoc(IncludeLoc);
160 assert(CurBuf && "Invalid or unspecified location!");
Chris Lattner8db9bc72009-03-13 07:05:43 +0000161
Chris Lattnercc64cc92009-07-02 22:24:20 +0000162 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
Mikhail Glushenkov84afae32010-01-27 10:13:11 +0000163
Chris Lattnercc64cc92009-07-02 22:24:20 +0000164 OS << "Included from "
165 << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
166 << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
Chris Lattner8db9bc72009-03-13 07:05:43 +0000167}
168
Chris Lattner03b80a42011-10-16 05:43:57 +0000169SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
Chris Lattner72845262011-10-16 05:47:55 +0000170 const Twine &Msg,
Jordan Roseefd8f802013-01-10 18:50:15 +0000171 ArrayRef<SMRange> Ranges,
172 ArrayRef<SMFixIt> FixIts) const {
Chris Lattner8db9bc72009-03-13 07:05:43 +0000173 // First thing to do: find the current buffer containing the specified
Chris Lattner854f3662012-05-06 16:20:49 +0000174 // location to pull out the source line.
Chris Lattnera3a06812011-10-16 04:47:35 +0000175 SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
Chris Lattner854f3662012-05-06 16:20:49 +0000176 std::pair<unsigned, unsigned> LineAndCol;
Mehdi Amini99d1b292016-10-01 16:38:28 +0000177 StringRef BufferID = "<unknown>";
Chris Lattner854f3662012-05-06 16:20:49 +0000178 std::string LineStr;
Fangrui Songf78650a2018-07-30 19:41:25 +0000179
Chris Lattner854f3662012-05-06 16:20:49 +0000180 if (Loc.isValid()) {
Alp Tokera55b95b2014-07-06 10:33:31 +0000181 unsigned CurBuf = FindBufferContainingLoc(Loc);
182 assert(CurBuf && "Invalid or unspecified location!");
Chris Lattner854f3662012-05-06 16:20:49 +0000183
Alp Toker7899d502014-06-25 00:41:15 +0000184 const MemoryBuffer *CurMB = getMemoryBuffer(CurBuf);
Chris Lattner854f3662012-05-06 16:20:49 +0000185 BufferID = CurMB->getBufferIdentifier();
Fangrui Songf78650a2018-07-30 19:41:25 +0000186
Chris Lattner854f3662012-05-06 16:20:49 +0000187 // Scan backward to find the start of the line.
188 const char *LineStart = Loc.getPointer();
189 const char *BufStart = CurMB->getBufferStart();
190 while (LineStart != BufStart && LineStart[-1] != '\n' &&
191 LineStart[-1] != '\r')
192 --LineStart;
193
194 // Get the end of the line.
195 const char *LineEnd = Loc.getPointer();
196 const char *BufEnd = CurMB->getBufferEnd();
197 while (LineEnd != BufEnd && LineEnd[0] != '\n' && LineEnd[0] != '\r')
198 ++LineEnd;
199 LineStr = std::string(LineStart, LineEnd);
200
201 // Convert any ranges to column ranges that only intersect the line of the
202 // location.
203 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
204 SMRange R = Ranges[i];
205 if (!R.isValid()) continue;
Fangrui Songf78650a2018-07-30 19:41:25 +0000206
Chris Lattner854f3662012-05-06 16:20:49 +0000207 // If the line doesn't contain any part of the range, then ignore it.
208 if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
209 continue;
Fangrui Songf78650a2018-07-30 19:41:25 +0000210
Chris Lattner854f3662012-05-06 16:20:49 +0000211 // Ignore pieces of the range that go onto other lines.
212 if (R.Start.getPointer() < LineStart)
213 R.Start = SMLoc::getFromPointer(LineStart);
214 if (R.End.getPointer() > LineEnd)
215 R.End = SMLoc::getFromPointer(LineEnd);
Fangrui Songf78650a2018-07-30 19:41:25 +0000216
Chris Lattner854f3662012-05-06 16:20:49 +0000217 // Translate from SMLoc ranges to column ranges.
Jordan Roseefd8f802013-01-10 18:50:15 +0000218 // FIXME: Handle multibyte characters.
Chris Lattner854f3662012-05-06 16:20:49 +0000219 ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart,
220 R.End.getPointer()-LineStart));
221 }
222
223 LineAndCol = getLineAndColumn(Loc, CurBuf);
224 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000225
Chris Lattner854f3662012-05-06 16:20:49 +0000226 return SMDiagnostic(*this, Loc, BufferID, LineAndCol.first,
Chris Lattner9322ba82012-05-05 22:17:32 +0000227 LineAndCol.second-1, Kind, Msg.str(),
Jordan Roseefd8f802013-01-10 18:50:15 +0000228 LineStr, ColRanges, FixIts);
Chris Lattner200e0752009-07-02 23:08:13 +0000229}
230
Jordan Rose57ffdb02014-06-17 02:15:40 +0000231void SourceMgr::PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
232 bool ShowColors) const {
Chris Lattner3c799812010-04-06 00:26:48 +0000233 // Report the message with the diagnostic handler if present.
234 if (DiagHandler) {
Chris Lattner03b80a42011-10-16 05:43:57 +0000235 DiagHandler(Diagnostic, DiagContext);
Chris Lattner3c799812010-04-06 00:26:48 +0000236 return;
237 }
Michael J. Spencerdb97c0b2010-12-09 17:37:32 +0000238
Jordan Rose57ffdb02014-06-17 02:15:40 +0000239 if (Diagnostic.getLoc().isValid()) {
Alp Tokera55b95b2014-07-06 10:33:31 +0000240 unsigned CurBuf = FindBufferContainingLoc(Diagnostic.getLoc());
241 assert(CurBuf && "Invalid or unspecified location!");
Chris Lattner854f3662012-05-06 16:20:49 +0000242 PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
243 }
Chris Lattner200e0752009-07-02 23:08:13 +0000244
Craig Topperc10719f2014-04-07 04:17:22 +0000245 Diagnostic.print(nullptr, OS, ShowColors);
Chris Lattner8db9bc72009-03-13 07:05:43 +0000246}
Chris Lattnercc64cc92009-07-02 22:24:20 +0000247
Jordan Rose57ffdb02014-06-17 02:15:40 +0000248void SourceMgr::PrintMessage(raw_ostream &OS, SMLoc Loc,
249 SourceMgr::DiagKind Kind,
250 const Twine &Msg, ArrayRef<SMRange> Ranges,
251 ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
252 PrintMessage(OS, GetMessage(Loc, Kind, Msg, Ranges, FixIts), ShowColors);
253}
254
Dmitri Gribenko8f944622013-09-27 21:09:25 +0000255void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
256 const Twine &Msg, ArrayRef<SMRange> Ranges,
257 ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
Eugene Zelenko454d0ce2017-02-15 22:17:02 +0000258 PrintMessage(errs(), Loc, Kind, Msg, Ranges, FixIts, ShowColors);
Dmitri Gribenko8f944622013-09-27 21:09:25 +0000259}
260
Chris Lattnercc64cc92009-07-02 22:24:20 +0000261//===----------------------------------------------------------------------===//
262// SMDiagnostic Implementation
263//===----------------------------------------------------------------------===//
264
Jordan Roseefd8f802013-01-10 18:50:15 +0000265SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN,
Chris Lattner03b80a42011-10-16 05:43:57 +0000266 int Line, int Col, SourceMgr::DiagKind Kind,
Jordan Roseefd8f802013-01-10 18:50:15 +0000267 StringRef Msg, StringRef LineStr,
Eugene Zelenko454d0ce2017-02-15 22:17:02 +0000268 ArrayRef<std::pair<unsigned,unsigned>> Ranges,
Jordan Roseefd8f802013-01-10 18:50:15 +0000269 ArrayRef<SMFixIt> Hints)
Chris Lattner03b80a42011-10-16 05:43:57 +0000270 : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Kind(Kind),
Jordan Roseefd8f802013-01-10 18:50:15 +0000271 Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()),
272 FixIts(Hints.begin(), Hints.end()) {
Fangrui Song0cac7262018-09-27 02:13:45 +0000273 llvm::sort(FixIts);
Chris Lattner03b80a42011-10-16 05:43:57 +0000274}
Chris Lattnera3a06812011-10-16 04:47:35 +0000275
Benjamin Kramer6ecb1e72013-02-15 12:30:38 +0000276static void buildFixItLine(std::string &CaretLine, std::string &FixItLine,
277 ArrayRef<SMFixIt> FixIts, ArrayRef<char> SourceLine){
Jordan Roseefd8f802013-01-10 18:50:15 +0000278 if (FixIts.empty())
279 return;
280
281 const char *LineStart = SourceLine.begin();
282 const char *LineEnd = SourceLine.end();
283
284 size_t PrevHintEndCol = 0;
285
286 for (ArrayRef<SMFixIt>::iterator I = FixIts.begin(), E = FixIts.end();
287 I != E; ++I) {
288 // If the fixit contains a newline or tab, ignore it.
289 if (I->getText().find_first_of("\n\r\t") != StringRef::npos)
290 continue;
291
292 SMRange R = I->getRange();
293
294 // If the line doesn't contain any part of the range, then ignore it.
295 if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
296 continue;
297
298 // Translate from SMLoc to column.
299 // Ignore pieces of the range that go onto other lines.
300 // FIXME: Handle multibyte characters in the source line.
301 unsigned FirstCol;
302 if (R.Start.getPointer() < LineStart)
303 FirstCol = 0;
304 else
305 FirstCol = R.Start.getPointer() - LineStart;
306
307 // If we inserted a long previous hint, push this one forwards, and add
308 // an extra space to show that this is not part of the previous
309 // completion. This is sort of the best we can do when two hints appear
310 // to overlap.
311 //
312 // Note that if this hint is located immediately after the previous
313 // hint, no space will be added, since the location is more important.
314 unsigned HintCol = FirstCol;
315 if (HintCol < PrevHintEndCol)
316 HintCol = PrevHintEndCol + 1;
317
318 // FIXME: This assertion is intended to catch unintended use of multibyte
319 // characters in fixits. If we decide to do this, we'll have to track
320 // separate byte widths for the source and fixit lines.
Eugene Zelenko454d0ce2017-02-15 22:17:02 +0000321 assert((size_t)sys::locale::columnWidth(I->getText()) ==
Jordan Roseefd8f802013-01-10 18:50:15 +0000322 I->getText().size());
323
324 // This relies on one byte per column in our fixit hints.
325 unsigned LastColumnModified = HintCol + I->getText().size();
326 if (LastColumnModified > FixItLine.size())
327 FixItLine.resize(LastColumnModified, ' ');
328
329 std::copy(I->getText().begin(), I->getText().end(),
330 FixItLine.begin() + HintCol);
331
332 PrevHintEndCol = LastColumnModified;
333
334 // For replacements, mark the removal range with '~'.
335 // FIXME: Handle multibyte characters in the source line.
336 unsigned LastCol;
337 if (R.End.getPointer() >= LineEnd)
338 LastCol = LineEnd - LineStart;
339 else
340 LastCol = R.End.getPointer() - LineStart;
341
342 std::fill(&CaretLine[FirstCol], &CaretLine[LastCol], '~');
343 }
344}
345
346static void printSourceLine(raw_ostream &S, StringRef LineContents) {
347 // Print out the source line one character at a time, so we can expand tabs.
348 for (unsigned i = 0, e = LineContents.size(), OutCol = 0; i != e; ++i) {
Reid Kleckner2b8c6922018-09-05 00:08:56 +0000349 size_t NextTab = LineContents.find('\t', i);
350 // If there were no tabs left, print the rest, we are done.
351 if (NextTab == StringRef::npos) {
352 S << LineContents.drop_front(i);
353 break;
Jordan Roseefd8f802013-01-10 18:50:15 +0000354 }
355
Reid Kleckner2b8c6922018-09-05 00:08:56 +0000356 // Otherwise, print from i to NextTab.
357 S << LineContents.slice(i, NextTab);
358 OutCol += NextTab - i;
359 i = NextTab;
360
Jordan Roseefd8f802013-01-10 18:50:15 +0000361 // If we have a tab, emit at least one space, then round up to 8 columns.
362 do {
363 S << ' ';
364 ++OutCol;
365 } while ((OutCol % TabStop) != 0);
366 }
367 S << '\n';
368}
Chris Lattnera3a06812011-10-16 04:47:35 +0000369
Jordan Roseceb1dbb2013-01-11 02:37:55 +0000370static bool isNonASCII(char c) {
371 return c & 0x80;
372}
373
Joel E. Denny3e665092018-10-24 21:46:42 +0000374void SMDiagnostic::print(const char *ProgName, raw_ostream &OS,
375 bool ShowColors, bool ShowKindLabel) const {
376 {
377 WithColor S(OS, raw_ostream::SAVEDCOLOR, true, false, !ShowColors);
Benjamin Kramerbb73d192012-04-18 19:04:15 +0000378
Joel E. Denny3e665092018-10-24 21:46:42 +0000379 if (ProgName && ProgName[0])
380 S << ProgName << ": ";
Benjamin Kramerbb73d192012-04-18 19:04:15 +0000381
Joel E. Denny3e665092018-10-24 21:46:42 +0000382 if (!Filename.empty()) {
383 if (Filename == "-")
384 S << "<stdin>";
385 else
386 S << Filename;
Chris Lattnercc64cc92009-07-02 22:24:20 +0000387
Joel E. Denny3e665092018-10-24 21:46:42 +0000388 if (LineNo != -1) {
389 S << ':' << LineNo;
390 if (ColumnNo != -1)
391 S << ':' << (ColumnNo + 1);
392 }
393 S << ": ";
Dan Gohman7c675902010-01-21 10:13:27 +0000394 }
Chris Lattnercc64cc92009-07-02 22:24:20 +0000395 }
Mikhail Glushenkov84afae32010-01-27 10:13:11 +0000396
Alex Lorenz735c47e2015-06-15 20:30:22 +0000397 if (ShowKindLabel) {
398 switch (Kind) {
399 case SourceMgr::DK_Error:
Joel E. Denny3e665092018-10-24 21:46:42 +0000400 WithColor::error(OS, "", !ShowColors);
Alex Lorenz735c47e2015-06-15 20:30:22 +0000401 break;
402 case SourceMgr::DK_Warning:
Joel E. Denny3e665092018-10-24 21:46:42 +0000403 WithColor::warning(OS, "", !ShowColors);
Alex Lorenz735c47e2015-06-15 20:30:22 +0000404 break;
405 case SourceMgr::DK_Note:
Joel E. Denny3e665092018-10-24 21:46:42 +0000406 WithColor::note(OS, "", !ShowColors);
Alex Lorenz735c47e2015-06-15 20:30:22 +0000407 break;
Adam Nemet01104ae2017-10-12 23:56:02 +0000408 case SourceMgr::DK_Remark:
Joel E. Denny3e665092018-10-24 21:46:42 +0000409 WithColor::remark(OS, "", !ShowColors);
Adam Nemet01104ae2017-10-12 23:56:02 +0000410 break;
Alex Lorenz735c47e2015-06-15 20:30:22 +0000411 }
Benjamin Kramerbb73d192012-04-18 19:04:15 +0000412 }
413
Joel E. Denny3e665092018-10-24 21:46:42 +0000414 WithColor(OS, raw_ostream::SAVEDCOLOR, true, false, !ShowColors)
415 << Message << '\n';
Benjamin Kramerbb73d192012-04-18 19:04:15 +0000416
Chris Lattner72845262011-10-16 05:47:55 +0000417 if (LineNo == -1 || ColumnNo == -1)
Chris Lattnera3a06812011-10-16 04:47:35 +0000418 return;
Mikhail Glushenkov84afae32010-01-27 10:13:11 +0000419
Jordan Roseceb1dbb2013-01-11 02:37:55 +0000420 // FIXME: If there are multibyte or multi-column characters in the source, all
421 // our ranges will be wrong. To do this properly, we'll need a byte-to-column
422 // map like Clang's TextDiagnostic. For now, we'll just handle tabs by
423 // expanding them later, and bail out rather than show incorrect ranges and
424 // misaligned fixits for any other odd characters.
David Majnemer562e8292016-08-12 00:18:03 +0000425 if (find_if(LineContents, isNonASCII) != LineContents.end()) {
Joel E. Denny3e665092018-10-24 21:46:42 +0000426 printSourceLine(OS, LineContents);
Jordan Roseefd8f802013-01-10 18:50:15 +0000427 return;
428 }
Jordan Roseceb1dbb2013-01-11 02:37:55 +0000429 size_t NumColumns = LineContents.size();
Jordan Roseefd8f802013-01-10 18:50:15 +0000430
Chris Lattnera3a06812011-10-16 04:47:35 +0000431 // Build the line with the caret and ranges.
Jordan Roseefd8f802013-01-10 18:50:15 +0000432 std::string CaretLine(NumColumns+1, ' ');
Fangrui Songf78650a2018-07-30 19:41:25 +0000433
Chris Lattnera3a06812011-10-16 04:47:35 +0000434 // Expand any ranges.
435 for (unsigned r = 0, e = Ranges.size(); r != e; ++r) {
436 std::pair<unsigned, unsigned> R = Ranges[r];
Jordan Roseefd8f802013-01-10 18:50:15 +0000437 std::fill(&CaretLine[R.first],
438 &CaretLine[std::min((size_t)R.second, CaretLine.size())],
439 '~');
Chris Lattnercc64cc92009-07-02 22:24:20 +0000440 }
Jordan Roseefd8f802013-01-10 18:50:15 +0000441
442 // Add any fix-its.
443 // FIXME: Find the beginning of the line properly for multibyte characters.
444 std::string FixItInsertionLine;
445 buildFixItLine(CaretLine, FixItInsertionLine, FixIts,
446 makeArrayRef(Loc.getPointer() - ColumnNo,
447 LineContents.size()));
448
Chris Lattnera3a06812011-10-16 04:47:35 +0000449 // Finally, plop on the caret.
Jordan Roseefd8f802013-01-10 18:50:15 +0000450 if (unsigned(ColumnNo) <= NumColumns)
Chris Lattnera3a06812011-10-16 04:47:35 +0000451 CaretLine[ColumnNo] = '^';
Fangrui Songf78650a2018-07-30 19:41:25 +0000452 else
Jordan Roseefd8f802013-01-10 18:50:15 +0000453 CaretLine[NumColumns] = '^';
Fangrui Songf78650a2018-07-30 19:41:25 +0000454
Chris Lattnera3a06812011-10-16 04:47:35 +0000455 // ... and remove trailing whitespace so the output doesn't wrap for it. We
456 // know that the line isn't completely empty because it has the caret in it at
457 // least.
458 CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
Fangrui Songf78650a2018-07-30 19:41:25 +0000459
Joel E. Denny3e665092018-10-24 21:46:42 +0000460 printSourceLine(OS, LineContents);
Chris Lattnera3a06812011-10-16 04:47:35 +0000461
Joel E. Denny3e665092018-10-24 21:46:42 +0000462 {
463 WithColor S(OS, raw_ostream::GREEN, true, false, !ShowColors);
Benjamin Kramerbb73d192012-04-18 19:04:15 +0000464
Joel E. Denny3e665092018-10-24 21:46:42 +0000465 // Print out the caret line, matching tabs in the source line.
466 for (unsigned i = 0, e = CaretLine.size(), OutCol = 0; i != e; ++i) {
467 if (i >= LineContents.size() || LineContents[i] != '\t') {
468 S << CaretLine[i];
469 ++OutCol;
470 continue;
471 }
472
473 // Okay, we have a tab. Insert the appropriate number of characters.
474 do {
475 S << CaretLine[i];
476 ++OutCol;
477 } while ((OutCol % TabStop) != 0);
Chris Lattnera3a06812011-10-16 04:47:35 +0000478 }
Joel E. Denny3e665092018-10-24 21:46:42 +0000479 S << '\n';
Chris Lattnera3a06812011-10-16 04:47:35 +0000480 }
Jordan Roseefd8f802013-01-10 18:50:15 +0000481
482 // Print out the replacement line, matching tabs in the source line.
483 if (FixItInsertionLine.empty())
484 return;
Fangrui Songf78650a2018-07-30 19:41:25 +0000485
Dmitri Gribenko78fe2ba2013-09-27 21:24:36 +0000486 for (size_t i = 0, e = FixItInsertionLine.size(), OutCol = 0; i < e; ++i) {
Jordan Roseefd8f802013-01-10 18:50:15 +0000487 if (i >= LineContents.size() || LineContents[i] != '\t') {
Joel E. Denny3e665092018-10-24 21:46:42 +0000488 OS << FixItInsertionLine[i];
Jordan Roseefd8f802013-01-10 18:50:15 +0000489 ++OutCol;
490 continue;
491 }
492
493 // Okay, we have a tab. Insert the appropriate number of characters.
494 do {
Joel E. Denny3e665092018-10-24 21:46:42 +0000495 OS << FixItInsertionLine[i];
Jordan Roseefd8f802013-01-10 18:50:15 +0000496 // FIXME: This is trying not to break up replacements, but then to re-sync
497 // with the tabs between replacements. This will fail, though, if two
498 // fix-it replacements are exactly adjacent, or if a fix-it contains a
499 // space. Really we should be precomputing column widths, which we'll
500 // need anyway for multibyte chars.
501 if (FixItInsertionLine[i] != ' ')
502 ++i;
503 ++OutCol;
504 } while (((OutCol % TabStop) != 0) && i != e);
505 }
Joel E. Denny3e665092018-10-24 21:46:42 +0000506 OS << '\n';
Chris Lattnercc64cc92009-07-02 22:24:20 +0000507}