blob: c6ebdcaf9a8fa572bb6f77661fafdfc1aebad5fa [file] [log] [blame]
Chandler Carrutha3028852011-10-15 23:43:53 +00001//===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chandler Carrutha3028852011-10-15 23:43:53 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "clang/Frontend/TextDiagnostic.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000010#include "clang/Basic/CharInfo.h"
Douglas Gregor811db4e2012-10-23 22:26:28 +000011#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000012#include "clang/Basic/FileManager.h"
13#include "clang/Basic/SourceManager.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000014#include "clang/Lex/Lexer.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000015#include "llvm/ADT/SmallString.h"
Seth Cantrell99e2fa82012-04-18 02:44:46 +000016#include "llvm/ADT/StringExtras.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000017#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "llvm/Support/ErrorHandling.h"
19#include "llvm/Support/Locale.h"
Hans Wennborgb30f4372016-08-26 15:45:36 +000020#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "llvm/Support/raw_ostream.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000022#include <algorithm>
Seth Cantrell99e2fa82012-04-18 02:44:46 +000023
Chandler Carrutha3028852011-10-15 23:43:53 +000024using namespace clang;
25
26static const enum raw_ostream::Colors noteColor =
27 raw_ostream::BLACK;
Tobias Grosser74160242014-02-28 09:11:08 +000028static const enum raw_ostream::Colors remarkColor =
29 raw_ostream::BLUE;
Chandler Carrutha3028852011-10-15 23:43:53 +000030static const enum raw_ostream::Colors fixitColor =
31 raw_ostream::GREEN;
32static const enum raw_ostream::Colors caretColor =
33 raw_ostream::GREEN;
34static const enum raw_ostream::Colors warningColor =
35 raw_ostream::MAGENTA;
Richard Trieu91844232012-06-26 18:18:47 +000036static const enum raw_ostream::Colors templateColor =
37 raw_ostream::CYAN;
Chandler Carrutha3028852011-10-15 23:43:53 +000038static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
39static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
40// Used for changing only the bold attribute.
41static const enum raw_ostream::Colors savedColor =
42 raw_ostream::SAVEDCOLOR;
43
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Add highlights to differences in template strings.
Richard Trieu91844232012-06-26 18:18:47 +000045static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
Richard Trieua71f0de2012-06-28 22:39:03 +000046 bool &Normal, bool Bold) {
Benjamin Kramerfce09f12012-10-18 20:09:54 +000047 while (1) {
48 size_t Pos = Str.find(ToggleHighlight);
49 OS << Str.slice(0, Pos);
50 if (Pos == StringRef::npos)
51 break;
52
53 Str = Str.substr(Pos + 1);
54 if (Normal)
55 OS.changeColor(templateColor, true);
56 else {
57 OS.resetColor();
58 if (Bold)
59 OS.changeColor(savedColor, true);
Richard Trieu91844232012-06-26 18:18:47 +000060 }
Benjamin Kramerfce09f12012-10-18 20:09:54 +000061 Normal = !Normal;
62 }
Richard Trieu91844232012-06-26 18:18:47 +000063}
64
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000065/// Number of spaces to indent when word-wrapping.
Chandler Carrutha3028852011-10-15 23:43:53 +000066const unsigned WordWrapIndentation = 6;
67
Benjamin Kramer556ab5e2012-05-01 14:34:11 +000068static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +000069 int bytes = 0;
70 while (0<i) {
71 if (SourceLine[--i]=='\t')
72 break;
73 ++bytes;
74 }
75 return bytes;
76}
77
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000078/// returns a printable representation of first item from input range
Seth Cantrell99e2fa82012-04-18 02:44:46 +000079///
80/// This function returns a printable representation of the next item in a line
81/// of source. If the next byte begins a valid and printable character, that
82/// character is returned along with 'true'.
83///
84/// Otherwise, if the next byte begins a valid, but unprintable character, a
85/// printable, escaped representation of the character is returned, along with
86/// 'false'. Otherwise a printable, escaped representation of the next byte
87/// is returned along with 'false'.
88///
89/// \note The index is updated to be used with a subsequent call to
90/// printableTextForNextCharacter.
91///
92/// \param SourceLine The line of source
93/// \param i Pointer to byte index,
94/// \param TabStop used to expand tabs
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000095/// \return pair(printable text, 'true' iff original text was printable)
Seth Cantrell99e2fa82012-04-18 02:44:46 +000096///
Benjamin Kramer556ab5e2012-05-01 14:34:11 +000097static std::pair<SmallString<16>, bool>
Seth Cantrell99e2fa82012-04-18 02:44:46 +000098printableTextForNextCharacter(StringRef SourceLine, size_t *i,
99 unsigned TabStop) {
100 assert(i && "i must not be null");
101 assert(*i<SourceLine.size() && "must point to a valid index");
Fangrui Song6907ce22018-07-30 19:24:48 +0000102
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000103 if (SourceLine[*i]=='\t') {
104 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
105 "Invalid -ftabstop value");
106 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
107 unsigned NumSpaces = TabStop - col%TabStop;
108 assert(0 < NumSpaces && NumSpaces <= TabStop
109 && "Invalid computation of space amt");
110 ++(*i);
111
112 SmallString<16> expandedTab;
113 expandedTab.assign(NumSpaces, ' ');
114 return std::make_pair(expandedTab, true);
115 }
116
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000117 unsigned char const *begin, *end;
118 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
Seth Cantrell29394162012-10-30 06:13:50 +0000119 end = begin + (SourceLine.size() - *i);
Fangrui Song6907ce22018-07-30 19:24:48 +0000120
Justin Lebar90910552016-09-30 00:38:45 +0000121 if (llvm::isLegalUTF8Sequence(begin, end)) {
122 llvm::UTF32 c;
123 llvm::UTF32 *cptr = &c;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000124 unsigned char const *original_begin = begin;
Justin Lebar90910552016-09-30 00:38:45 +0000125 unsigned char const *cp_end =
126 begin + llvm::getNumBytesForUTF8(SourceLine[*i]);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000127
Justin Lebar90910552016-09-30 00:38:45 +0000128 llvm::ConversionResult res = llvm::ConvertUTF8toUTF32(
129 &begin, cp_end, &cptr, cptr + 1, llvm::strictConversion);
Matt Beaumont-Gay69e227b2012-04-18 17:25:16 +0000130 (void)res;
Justin Lebar90910552016-09-30 00:38:45 +0000131 assert(llvm::conversionOK == res);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000132 assert(0 < begin-original_begin
133 && "we must be further along in the string now");
134 *i += begin-original_begin;
135
136 if (!llvm::sys::locale::isPrint(c)) {
137 // If next character is valid UTF-8, but not printable
138 SmallString<16> expandedCP("<U+>");
139 while (c) {
140 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
141 c/=16;
142 }
143 while (expandedCP.size() < 8)
144 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
145 return std::make_pair(expandedCP, false);
146 }
147
148 // If next character is valid UTF-8, and printable
149 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
150
151 }
152
153 // If next byte is not valid UTF-8 (and therefore not printable)
154 SmallString<16> expandedByte("<XX>");
155 unsigned char byte = SourceLine[*i];
156 expandedByte[1] = llvm::hexdigit(byte / 16);
157 expandedByte[2] = llvm::hexdigit(byte % 16);
158 ++(*i);
159 return std::make_pair(expandedByte, false);
160}
161
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000162static void expandTabs(std::string &SourceLine, unsigned TabStop) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000163 size_t i = SourceLine.size();
164 while (i>0) {
165 i--;
166 if (SourceLine[i]!='\t')
167 continue;
168 size_t tmp_i = i;
169 std::pair<SmallString<16>,bool> res
170 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
171 SourceLine.replace(i, 1, res.first.c_str());
172 }
173}
174
175/// This function takes a raw source line and produces a mapping from the bytes
176/// of the printable representation of the line to the columns those printable
177/// characters will appear at (numbering the first column as 0).
178///
Logan Chien968a21d2014-12-20 08:51:22 +0000179/// If a byte 'i' corresponds to multiple columns (e.g. the byte contains a tab
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000180/// character) then the array will map that byte to the first column the
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000181/// tab appears at and the next value in the map will have been incremented
182/// more than once.
183///
184/// If a byte is the first in a sequence of bytes that together map to a single
185/// entity in the output, then the array will map that byte to the appropriate
186/// column while the subsequent bytes will be -1.
187///
188/// The last element in the array does not correspond to any byte in the input
189/// and instead is the number of columns needed to display the source
190///
191/// example: (given a tabstop of 8)
192///
193/// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
194///
James Dennettf347d932012-06-22 05:33:23 +0000195/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000196/// display)
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000197static void byteToColumn(StringRef SourceLine, unsigned TabStop,
198 SmallVectorImpl<int> &out) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000199 out.clear();
200
201 if (SourceLine.empty()) {
202 out.resize(1u,0);
203 return;
204 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000205
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000206 out.resize(SourceLine.size()+1, -1);
207
208 int columns = 0;
209 size_t i = 0;
210 while (i<SourceLine.size()) {
211 out[i] = columns;
212 std::pair<SmallString<16>,bool> res
213 = printableTextForNextCharacter(SourceLine, &i, TabStop);
214 columns += llvm::sys::locale::columnWidth(res.first);
215 }
216 out.back() = columns;
217}
218
219/// This function takes a raw source line and produces a mapping from columns
220/// to the byte of the source line that produced the character displaying at
221/// that column. This is the inverse of the mapping produced by byteToColumn()
222///
223/// The last element in the array is the number of bytes in the source string
224///
225/// example: (given a tabstop of 8)
226///
227/// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
228///
James Dennettf347d932012-06-22 05:33:23 +0000229/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000230/// display)
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000231static void columnToByte(StringRef SourceLine, unsigned TabStop,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000232 SmallVectorImpl<int> &out) {
233 out.clear();
234
235 if (SourceLine.empty()) {
236 out.resize(1u, 0);
237 return;
238 }
239
240 int columns = 0;
241 size_t i = 0;
242 while (i<SourceLine.size()) {
243 out.resize(columns+1, -1);
244 out.back() = i;
245 std::pair<SmallString<16>,bool> res
246 = printableTextForNextCharacter(SourceLine, &i, TabStop);
247 columns += llvm::sys::locale::columnWidth(res.first);
248 }
249 out.resize(columns+1, -1);
250 out.back() = i;
251}
252
Benjamin Kramer2a812282012-12-01 20:58:01 +0000253namespace {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000254struct SourceColumnMap {
255 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
256 : m_SourceLine(SourceLine) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000257
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000258 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
259 ::columnToByte(SourceLine, TabStop, m_columnToByte);
Fangrui Song6907ce22018-07-30 19:24:48 +0000260
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000261 assert(m_byteToColumn.size()==SourceLine.size()+1);
262 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
263 assert(m_byteToColumn.size()
264 == static_cast<unsigned>(m_columnToByte.back()+1));
265 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
266 == m_columnToByte.size());
267 }
268 int columns() const { return m_byteToColumn.back(); }
269 int bytes() const { return m_columnToByte.back(); }
Richard Smithfab4b1a2012-09-13 18:37:50 +0000270
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000271 /// Map a byte to the column which it is at the start of, or return -1
Richard Smithfab4b1a2012-09-13 18:37:50 +0000272 /// if it is not at the start of a column (for a UTF-8 trailing byte).
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000273 int byteToColumn(int n) const {
274 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
275 return m_byteToColumn[n];
276 }
Richard Smithfab4b1a2012-09-13 18:37:50 +0000277
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000278 /// Map a byte to the first column which contains it.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000279 int byteToContainingColumn(int N) const {
280 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
281 while (m_byteToColumn[N] == -1)
282 --N;
283 return m_byteToColumn[N];
284 }
285
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000286 /// Map a column to the byte which starts the column, or return -1 if
Richard Smithfab4b1a2012-09-13 18:37:50 +0000287 /// the column the second or subsequent column of an expanded tab or similar
288 /// multi-column entity.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000289 int columnToByte(int n) const {
290 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
291 return m_columnToByte[n];
292 }
Richard Smithfab4b1a2012-09-13 18:37:50 +0000293
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000294 /// Map from a byte index to the next byte which starts a column.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000295 int startOfNextColumn(int N) const {
Logan Chiend3d385d2015-01-08 13:19:07 +0000296 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size() - 1));
Richard Smithfab4b1a2012-09-13 18:37:50 +0000297 while (byteToColumn(++N) == -1) {}
298 return N;
299 }
300
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000301 /// Map from a byte index to the previous byte which starts a column.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000302 int startOfPreviousColumn(int N) const {
Logan Chiend3d385d2015-01-08 13:19:07 +0000303 assert(0 < N && N < static_cast<int>(m_byteToColumn.size()));
Seth Cantrelld38c7082012-11-03 21:21:14 +0000304 while (byteToColumn(--N) == -1) {}
Richard Smithfab4b1a2012-09-13 18:37:50 +0000305 return N;
306 }
307
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000308 StringRef getSourceLine() const {
309 return m_SourceLine;
310 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000311
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000312private:
313 const std::string m_SourceLine;
314 SmallVector<int,200> m_byteToColumn;
315 SmallVector<int,200> m_columnToByte;
316};
Benjamin Kramer2a812282012-12-01 20:58:01 +0000317} // end anonymous namespace
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000318
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000319/// When the source code line we want to print is too long for
Chandler Carrutha3028852011-10-15 23:43:53 +0000320/// the terminal, select the "interesting" region.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000321static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carrutha3028852011-10-15 23:43:53 +0000322 std::string &CaretLine,
323 std::string &FixItInsertionLine,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000324 unsigned Columns,
325 const SourceColumnMap &map) {
Logan Chiend3d385d2015-01-08 13:19:07 +0000326 unsigned CaretColumns = CaretLine.size();
327 unsigned FixItColumns = llvm::sys::locale::columnWidth(FixItInsertionLine);
328 unsigned MaxColumns = std::max(static_cast<unsigned>(map.columns()),
329 std::max(CaretColumns, FixItColumns));
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000330 // if the number of columns is less than the desired number we're done
331 if (MaxColumns <= Columns)
332 return;
333
Jordan Rosee2fad6d2013-06-07 17:16:01 +0000334 // No special characters are allowed in CaretLine.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000335 assert(CaretLine.end() ==
Fangrui Song75e74e02019-03-31 08:48:19 +0000336 llvm::find_if(CaretLine, [](char c) { return c < ' ' || '~' < c; }));
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000337
Chandler Carrutha3028852011-10-15 23:43:53 +0000338 // Find the slice that we need to display the full caret line
339 // correctly.
340 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
341 for (; CaretStart != CaretEnd; ++CaretStart)
Jordan Rosea7d03842013-02-08 22:30:41 +0000342 if (!isWhitespace(CaretLine[CaretStart]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000343 break;
344
345 for (; CaretEnd != CaretStart; --CaretEnd)
Jordan Rosea7d03842013-02-08 22:30:41 +0000346 if (!isWhitespace(CaretLine[CaretEnd - 1]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000347 break;
348
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000349 // caret has already been inserted into CaretLine so the above whitespace
350 // check is guaranteed to include the caret
Chandler Carrutha3028852011-10-15 23:43:53 +0000351
352 // If we have a fix-it line, make sure the slice includes all of the
353 // fix-it information.
354 if (!FixItInsertionLine.empty()) {
355 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
356 for (; FixItStart != FixItEnd; ++FixItStart)
Jordan Rosea7d03842013-02-08 22:30:41 +0000357 if (!isWhitespace(FixItInsertionLine[FixItStart]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000358 break;
359
360 for (; FixItEnd != FixItStart; --FixItEnd)
Jordan Rosea7d03842013-02-08 22:30:41 +0000361 if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000362 break;
363
Jordan Rosee2fad6d2013-06-07 17:16:01 +0000364 // We can safely use the byte offset FixItStart as the column offset
365 // because the characters up until FixItStart are all ASCII whitespace
366 // characters.
367 unsigned FixItStartCol = FixItStart;
368 unsigned FixItEndCol
369 = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
370
371 CaretStart = std::min(FixItStartCol, CaretStart);
372 CaretEnd = std::max(FixItEndCol, CaretEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000373 }
374
Seth Cantrellac6fb8f2012-05-24 05:14:44 +0000375 // CaretEnd may have been set at the middle of a character
376 // If it's not at a character's first column then advance it past the current
377 // character.
378 while (static_cast<int>(CaretEnd) < map.columns() &&
379 -1 == map.columnToByte(CaretEnd))
380 ++CaretEnd;
381
382 assert((static_cast<int>(CaretStart) > map.columns() ||
383 -1!=map.columnToByte(CaretStart)) &&
384 "CaretStart must not point to a column in the middle of a source"
385 " line character");
386 assert((static_cast<int>(CaretEnd) > map.columns() ||
387 -1!=map.columnToByte(CaretEnd)) &&
388 "CaretEnd must not point to a column in the middle of a source line"
389 " character");
390
Chandler Carrutha3028852011-10-15 23:43:53 +0000391 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
392 // parts of the caret line. While this slice is smaller than the
393 // number of columns we have, try to grow the slice to encompass
394 // more context.
395
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000396 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
397 map.columns()));
398 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
399 map.columns()));
400
401 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
402 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
403
404 char const *front_ellipse = " ...";
405 char const *front_space = " ";
406 char const *back_ellipse = "...";
407 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
Chandler Carrutha3028852011-10-15 23:43:53 +0000408
409 unsigned TargetColumns = Columns;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000410 // Give us extra room for the ellipses
411 // and any of the caret line that extends past the source
412 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
413 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
414
415 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000416 bool ExpandedRegion = false;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000417
418 if (SourceStart>0) {
Seth Cantrell6292e5b82012-11-03 21:21:17 +0000419 unsigned NewStart = map.startOfPreviousColumn(SourceStart);
Chandler Carrutha3028852011-10-15 23:43:53 +0000420
421 // Skip over any whitespace we see here; we're looking for
422 // another bit of interesting text.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000423 // FIXME: Detect non-ASCII whitespace characters too.
Jordan Rosea7d03842013-02-08 22:30:41 +0000424 while (NewStart && isWhitespace(SourceLine[NewStart]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000425 NewStart = map.startOfPreviousColumn(NewStart);
Chandler Carrutha3028852011-10-15 23:43:53 +0000426
427 // Skip over this bit of "interesting" text.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000428 while (NewStart) {
429 unsigned Prev = map.startOfPreviousColumn(NewStart);
Jordan Rosea7d03842013-02-08 22:30:41 +0000430 if (isWhitespace(SourceLine[Prev]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000431 break;
432 NewStart = Prev;
433 }
Chandler Carrutha3028852011-10-15 23:43:53 +0000434
Richard Smithfab4b1a2012-09-13 18:37:50 +0000435 assert(map.byteToColumn(NewStart) != -1);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000436 unsigned NewColumns = map.byteToColumn(SourceEnd) -
437 map.byteToColumn(NewStart);
438 if (NewColumns <= TargetColumns) {
439 SourceStart = NewStart;
Chandler Carrutha3028852011-10-15 23:43:53 +0000440 ExpandedRegion = true;
441 }
442 }
443
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000444 if (SourceEnd<SourceLine.size()) {
Seth Cantrell6292e5b82012-11-03 21:21:17 +0000445 unsigned NewEnd = map.startOfNextColumn(SourceEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000446
447 // Skip over any whitespace we see here; we're looking for
448 // another bit of interesting text.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000449 // FIXME: Detect non-ASCII whitespace characters too.
Jordan Rosea7d03842013-02-08 22:30:41 +0000450 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000451 NewEnd = map.startOfNextColumn(NewEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000452
453 // Skip over this bit of "interesting" text.
Jordan Rosea7d03842013-02-08 22:30:41 +0000454 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000455 NewEnd = map.startOfNextColumn(NewEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000456
Richard Smithfab4b1a2012-09-13 18:37:50 +0000457 assert(map.byteToColumn(NewEnd) != -1);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000458 unsigned NewColumns = map.byteToColumn(NewEnd) -
459 map.byteToColumn(SourceStart);
460 if (NewColumns <= TargetColumns) {
461 SourceEnd = NewEnd;
Chandler Carrutha3028852011-10-15 23:43:53 +0000462 ExpandedRegion = true;
463 }
464 }
465
466 if (!ExpandedRegion)
467 break;
468 }
469
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000470 CaretStart = map.byteToColumn(SourceStart);
471 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
472
Chandler Carrutha3028852011-10-15 23:43:53 +0000473 // [CaretStart, CaretEnd) is the slice we want. Update the various
474 // output lines to show only this slice, with two-space padding
475 // before the lines so that it looks nicer.
Chandler Carrutha3028852011-10-15 23:43:53 +0000476
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000477 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
478 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
479 assert(SourceStart <= SourceEnd);
480 assert(CaretStart <= CaretEnd);
481
482 unsigned BackColumnsRemoved
483 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
484 unsigned FrontColumnsRemoved = CaretStart;
485 unsigned ColumnsKept = CaretEnd-CaretStart;
486
487 // We checked up front that the line needed truncation
488 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
489
Logan Chien968a21d2014-12-20 08:51:22 +0000490 // The line needs some truncation, and we'd prefer to keep the front
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000491 // if possible, so remove the back
Seth Cantrell40f87b12012-11-03 23:56:43 +0000492 if (BackColumnsRemoved > strlen(back_ellipse))
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000493 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
494
495 // If that's enough then we're done
496 if (FrontColumnsRemoved+ColumnsKept <= Columns)
497 return;
498
499 // Otherwise remove the front as well
Seth Cantrell40f87b12012-11-03 23:56:43 +0000500 if (FrontColumnsRemoved > strlen(front_ellipse)) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000501 SourceLine.replace(0, SourceStart, front_ellipse);
502 CaretLine.replace(0, CaretStart, front_space);
503 if (!FixItInsertionLine.empty())
504 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carrutha3028852011-10-15 23:43:53 +0000505 }
506}
507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508/// Skip over whitespace in the string, starting at the given
Chandler Carrutha3028852011-10-15 23:43:53 +0000509/// index.
510///
511/// \returns The index of the first non-whitespace character that is
512/// greater than or equal to Idx or, if no such character exists,
513/// returns the end of the string.
514static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000515 while (Idx < Length && isWhitespace(Str[Idx]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000516 ++Idx;
517 return Idx;
518}
519
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520/// If the given character is the start of some kind of
Chandler Carrutha3028852011-10-15 23:43:53 +0000521/// balanced punctuation (e.g., quotes or parentheses), return the
522/// character that will terminate the punctuation.
523///
524/// \returns The ending punctuation character, if any, or the NULL
525/// character if the input character does not start any punctuation.
526static inline char findMatchingPunctuation(char c) {
527 switch (c) {
528 case '\'': return '\'';
529 case '`': return '\'';
530 case '"': return '"';
531 case '(': return ')';
532 case '[': return ']';
533 case '{': return '}';
534 default: break;
535 }
536
537 return 0;
538}
539
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000540/// Find the end of the word starting at the given offset
Chandler Carrutha3028852011-10-15 23:43:53 +0000541/// within a string.
542///
543/// \returns the index pointing one character past the end of the
544/// word.
545static unsigned findEndOfWord(unsigned Start, StringRef Str,
546 unsigned Length, unsigned Column,
547 unsigned Columns) {
548 assert(Start < Str.size() && "Invalid start position!");
549 unsigned End = Start + 1;
550
551 // If we are already at the end of the string, take that as the word.
552 if (End == Str.size())
553 return End;
554
555 // Determine if the start of the string is actually opening
556 // punctuation, e.g., a quote or parentheses.
557 char EndPunct = findMatchingPunctuation(Str[Start]);
558 if (!EndPunct) {
559 // This is a normal word. Just find the first space character.
Jordan Rosea7d03842013-02-08 22:30:41 +0000560 while (End < Length && !isWhitespace(Str[End]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000561 ++End;
562 return End;
563 }
564
565 // We have the start of a balanced punctuation sequence (quotes,
566 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000567 SmallString<16> PunctuationEndStack;
Chandler Carrutha3028852011-10-15 23:43:53 +0000568 PunctuationEndStack.push_back(EndPunct);
569 while (End < Length && !PunctuationEndStack.empty()) {
570 if (Str[End] == PunctuationEndStack.back())
571 PunctuationEndStack.pop_back();
572 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
573 PunctuationEndStack.push_back(SubEndPunct);
574
575 ++End;
576 }
577
578 // Find the first space character after the punctuation ended.
Jordan Rosea7d03842013-02-08 22:30:41 +0000579 while (End < Length && !isWhitespace(Str[End]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000580 ++End;
581
582 unsigned PunctWordLength = End - Start;
583 if (// If the word fits on this line
584 Column + PunctWordLength <= Columns ||
585 // ... or the word is "short enough" to take up the next line
586 // without too much ugly white space
587 PunctWordLength < Columns/3)
588 return End; // Take the whole thing as a single "word".
589
590 // The whole quoted/parenthesized string is too long to print as a
591 // single "word". Instead, find the "word" that starts just after
592 // the punctuation and use that end-point instead. This will recurse
593 // until it finds something small enough to consider a word.
594 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
595}
596
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000597/// Print the given string to a stream, word-wrapping it to
Chandler Carrutha3028852011-10-15 23:43:53 +0000598/// some number of columns in the process.
599///
600/// \param OS the stream to which the word-wrapping string will be
601/// emitted.
602/// \param Str the string to word-wrap and output.
603/// \param Columns the number of columns to word-wrap to.
604/// \param Column the column number at which the first character of \p
605/// Str will be printed. This will be non-zero when part of the first
606/// line has already been printed.
Richard Trieua71f0de2012-06-28 22:39:03 +0000607/// \param Bold if the current text should be bold
Chandler Carrutha3028852011-10-15 23:43:53 +0000608/// \param Indentation the number of spaces to indent any lines beyond
609/// the first line.
610/// \returns true if word-wrapping was required, or false if the
611/// string fit on the first line.
612static bool printWordWrapped(raw_ostream &OS, StringRef Str,
613 unsigned Columns,
614 unsigned Column = 0,
Richard Trieua71f0de2012-06-28 22:39:03 +0000615 bool Bold = false,
Chandler Carrutha3028852011-10-15 23:43:53 +0000616 unsigned Indentation = WordWrapIndentation) {
617 const unsigned Length = std::min(Str.find('\n'), Str.size());
Richard Trieu91844232012-06-26 18:18:47 +0000618 bool TextNormal = true;
Chandler Carrutha3028852011-10-15 23:43:53 +0000619
620 // The string used to indent each line.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000621 SmallString<16> IndentStr;
Chandler Carrutha3028852011-10-15 23:43:53 +0000622 IndentStr.assign(Indentation, ' ');
623 bool Wrapped = false;
624 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
625 WordStart = WordEnd) {
626 // Find the beginning of the next word.
627 WordStart = skipWhitespace(WordStart, Str, Length);
628 if (WordStart == Length)
629 break;
630
631 // Find the end of this word.
632 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
633
634 // Does this word fit on the current line?
635 unsigned WordLength = WordEnd - WordStart;
636 if (Column + WordLength < Columns) {
637 // This word fits on the current line; print it there.
638 if (WordStart) {
639 OS << ' ';
640 Column += 1;
641 }
Richard Trieu91844232012-06-26 18:18:47 +0000642 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieua71f0de2012-06-28 22:39:03 +0000643 TextNormal, Bold);
Chandler Carrutha3028852011-10-15 23:43:53 +0000644 Column += WordLength;
645 continue;
646 }
647
648 // This word does not fit on the current line, so wrap to the next
649 // line.
650 OS << '\n';
651 OS.write(&IndentStr[0], Indentation);
Richard Trieu91844232012-06-26 18:18:47 +0000652 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieua71f0de2012-06-28 22:39:03 +0000653 TextNormal, Bold);
Chandler Carrutha3028852011-10-15 23:43:53 +0000654 Column = Indentation + WordLength;
655 Wrapped = true;
656 }
657
658 // Append any remaning text from the message with its existing formatting.
Richard Trieua71f0de2012-06-28 22:39:03 +0000659 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
Richard Trieu91844232012-06-26 18:18:47 +0000660
661 assert(TextNormal && "Text highlighted at end of diagnostic message.");
Chandler Carrutha3028852011-10-15 23:43:53 +0000662
663 return Wrapped;
664}
665
666TextDiagnostic::TextDiagnostic(raw_ostream &OS,
Chandler Carrutha3028852011-10-15 23:43:53 +0000667 const LangOptions &LangOpts,
Douglas Gregor811db4e2012-10-23 22:26:28 +0000668 DiagnosticOptions *DiagOpts)
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000669 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000670
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000671TextDiagnostic::~TextDiagnostic() {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000672
Christof Doumafb4a0452017-06-27 09:50:38 +0000673void TextDiagnostic::emitDiagnosticMessage(
674 FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level,
675 StringRef Message, ArrayRef<clang::CharSourceRange> Ranges,
676 DiagOrStoredDiag D) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000677 uint64_t StartOfLocationInfo = OS.tell();
678
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000679 // Emit the location of this particular diagnostic.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000680 if (Loc.isValid())
Christof Doumafb4a0452017-06-27 09:50:38 +0000681 emitDiagnosticLoc(Loc, PLoc, Level, Ranges);
682
Douglas Gregor811db4e2012-10-23 22:26:28 +0000683 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +0000684 OS.resetColor();
Fangrui Song6907ce22018-07-30 19:24:48 +0000685
Hans Wennborgf4aee182013-09-24 00:08:55 +0000686 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors,
687 DiagOpts->CLFallbackMode);
Alp Tokera68ad102014-06-21 23:31:52 +0000688 printDiagnosticMessage(OS,
689 /*IsSupplemental*/ Level == DiagnosticsEngine::Note,
690 Message, OS.tell() - StartOfLocationInfo,
Douglas Gregor811db4e2012-10-23 22:26:28 +0000691 DiagOpts->MessageLength, DiagOpts->ShowColors);
Chandler Carrutha3028852011-10-15 23:43:53 +0000692}
693
Chandler Carruth07c346d2011-10-15 23:48:02 +0000694/*static*/ void
695TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
696 DiagnosticsEngine::Level Level,
Hans Wennborgf4aee182013-09-24 00:08:55 +0000697 bool ShowColors,
698 bool CLFallbackMode) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000699 if (ShowColors) {
700 // Print diagnostic category in bold and color
701 switch (Level) {
702 case DiagnosticsEngine::Ignored:
703 llvm_unreachable("Invalid diagnostic type");
704 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
Tobias Grosser74160242014-02-28 09:11:08 +0000705 case DiagnosticsEngine::Remark: OS.changeColor(remarkColor, true); break;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000706 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
707 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
708 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
709 }
710 }
711
712 switch (Level) {
713 case DiagnosticsEngine::Ignored:
714 llvm_unreachable("Invalid diagnostic type");
Hans Wennborgf4aee182013-09-24 00:08:55 +0000715 case DiagnosticsEngine::Note: OS << "note"; break;
Tobias Grosser74160242014-02-28 09:11:08 +0000716 case DiagnosticsEngine::Remark: OS << "remark"; break;
Hans Wennborgf4aee182013-09-24 00:08:55 +0000717 case DiagnosticsEngine::Warning: OS << "warning"; break;
718 case DiagnosticsEngine::Error: OS << "error"; break;
719 case DiagnosticsEngine::Fatal: OS << "fatal error"; break;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000720 }
721
Hans Wennborgf4aee182013-09-24 00:08:55 +0000722 // In clang-cl /fallback mode, print diagnostics as "error(clang):". This
723 // makes it more clear whether a message is coming from clang or cl.exe,
724 // and it prevents MSBuild from concluding that the build failed just because
725 // there is an "error:" in the output.
726 if (CLFallbackMode)
727 OS << "(clang)";
728
729 OS << ": ";
730
Chandler Carruth07c346d2011-10-15 23:48:02 +0000731 if (ShowColors)
732 OS.resetColor();
733}
734
Alp Tokera68ad102014-06-21 23:31:52 +0000735/*static*/
736void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
737 bool IsSupplemental,
738 StringRef Message,
739 unsigned CurrentColumn,
740 unsigned Columns, bool ShowColors) {
Richard Trieua71f0de2012-06-28 22:39:03 +0000741 bool Bold = false;
Alp Tokera68ad102014-06-21 23:31:52 +0000742 if (ShowColors && !IsSupplemental) {
743 // Print primary diagnostic messages in bold and without color, to visually
744 // indicate the transition from continuation notes and other output.
745 OS.changeColor(savedColor, true);
746 Bold = true;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000747 }
748
749 if (Columns)
Richard Trieua71f0de2012-06-28 22:39:03 +0000750 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
David Blaikie9e55d742012-06-28 21:46:07 +0000751 else {
752 bool Normal = true;
Richard Trieua71f0de2012-06-28 22:39:03 +0000753 applyTemplateHighlighting(OS, Message, Normal, Bold);
David Blaikie9e55d742012-06-28 21:46:07 +0000754 assert(Normal && "Formatting should have returned to normal");
755 }
Chandler Carruth07c346d2011-10-15 23:48:02 +0000756
757 if (ShowColors)
758 OS.resetColor();
759 OS << '\n';
760}
761
Hans Wennborgb30f4372016-08-26 15:45:36 +0000762void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
763 SmallVector<char, 128> AbsoluteFilename;
764 if (DiagOpts->AbsolutePath) {
765 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
766 llvm::sys::path::parent_path(Filename));
767 if (Dir) {
768 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
769 llvm::sys::path::append(AbsoluteFilename, DirName,
770 llvm::sys::path::filename(Filename));
771 Filename = StringRef(AbsoluteFilename.data(), AbsoluteFilename.size());
772 }
773 }
774
775 OS << Filename;
776}
777
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000778/// Print out the file/line/column information and include trace.
Chandler Carruth07c346d2011-10-15 23:48:02 +0000779///
780/// This method handlen the emission of the diagnostic location information.
781/// This includes extracting as much location information as is present for
782/// the diagnostic and printing it, as well as any include stack or source
783/// ranges necessary.
Christof Doumafb4a0452017-06-27 09:50:38 +0000784void TextDiagnostic::emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc,
Chandler Carruth07c346d2011-10-15 23:48:02 +0000785 DiagnosticsEngine::Level Level,
Christof Doumafb4a0452017-06-27 09:50:38 +0000786 ArrayRef<CharSourceRange> Ranges) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000787 if (PLoc.isInvalid()) {
788 // At least print the file name if available:
Christof Doumafb4a0452017-06-27 09:50:38 +0000789 FileID FID = Loc.getFileID();
Yaron Keren8b563662015-10-03 10:46:20 +0000790 if (FID.isValid()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000791 const FileEntry *FE = Loc.getFileEntry();
Ben Langmuirc8a71462014-02-27 17:23:33 +0000792 if (FE && FE->isValid()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000793 emitFilename(FE->getName(), Loc.getManager());
Chandler Carruth07c346d2011-10-15 23:48:02 +0000794 OS << ": ";
795 }
796 }
797 return;
798 }
799 unsigned LineNo = PLoc.getLine();
800
Douglas Gregor811db4e2012-10-23 22:26:28 +0000801 if (!DiagOpts->ShowLocation)
Chandler Carruth07c346d2011-10-15 23:48:02 +0000802 return;
803
Douglas Gregor811db4e2012-10-23 22:26:28 +0000804 if (DiagOpts->ShowColors)
Chandler Carruth07c346d2011-10-15 23:48:02 +0000805 OS.changeColor(savedColor, true);
806
Christof Doumafb4a0452017-06-27 09:50:38 +0000807 emitFilename(PLoc.getFilename(), Loc.getManager());
Douglas Gregor79591782012-10-23 23:11:23 +0000808 switch (DiagOpts->getFormat()) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000809 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
David Majnemer8ab003a2015-02-02 19:30:52 +0000810 case DiagnosticOptions::MSVC: OS << '(' << LineNo; break;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000811 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
812 }
813
Douglas Gregor811db4e2012-10-23 22:26:28 +0000814 if (DiagOpts->ShowColumn)
Chandler Carruth07c346d2011-10-15 23:48:02 +0000815 // Compute the column number.
816 if (unsigned ColNo = PLoc.getColumn()) {
David Majnemer8ab003a2015-02-02 19:30:52 +0000817 if (DiagOpts->getFormat() == DiagnosticOptions::MSVC) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000818 OS << ',';
Yunzhong Gao820c6872014-03-07 00:23:36 +0000819 // Visual Studio 2010 or earlier expects column number to be off by one
Saleem Abdulrasoolc68237b2014-07-16 03:13:50 +0000820 if (LangOpts.MSCompatibilityVersion &&
David Majnemerb710a932015-05-11 03:57:49 +0000821 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2012))
Yunzhong Gao820c6872014-03-07 00:23:36 +0000822 ColNo--;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000823 } else
824 OS << ':';
825 OS << ColNo;
826 }
Douglas Gregor79591782012-10-23 23:11:23 +0000827 switch (DiagOpts->getFormat()) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000828 case DiagnosticOptions::Clang:
829 case DiagnosticOptions::Vi: OS << ':'; break;
Nico Weberfbe3adf2016-03-23 22:57:55 +0000830 case DiagnosticOptions::MSVC:
831 // MSVC2013 and before print 'file(4) : error'. MSVC2015 gets rid of the
832 // space and prints 'file(4): error'.
833 OS << ')';
834 if (LangOpts.MSCompatibilityVersion &&
835 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
836 OS << ' ';
Hans Wennborg27a78852019-02-19 16:58:25 +0000837 OS << ':';
Nico Weberfbe3adf2016-03-23 22:57:55 +0000838 break;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000839 }
840
Douglas Gregor811db4e2012-10-23 22:26:28 +0000841 if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000842 FileID CaretFileID = Loc.getExpansionLoc().getFileID();
Chandler Carruth07c346d2011-10-15 23:48:02 +0000843 bool PrintedRange = false;
844
845 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
846 RE = Ranges.end();
847 RI != RE; ++RI) {
848 // Ignore invalid ranges.
849 if (!RI->isValid()) continue;
850
Richard Smithb5f81712018-04-30 05:25:48 +0000851 auto &SM = Loc.getManager();
852 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
853 CharSourceRange ERange = SM.getExpansionRange(RI->getEnd());
854 SourceLocation E = ERange.getEnd();
855 bool IsTokenRange = ERange.isTokenRange();
Chandler Carruth07c346d2011-10-15 23:48:02 +0000856
Richard Smithb5f81712018-04-30 05:25:48 +0000857 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
858 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
Chandler Carruth07c346d2011-10-15 23:48:02 +0000859
860 // If the start or end of the range is in another file, just discard
861 // it.
862 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
863 continue;
864
865 // Add in the length of the token, so that we cover multi-char
866 // tokens.
867 unsigned TokSize = 0;
Richard Smithb5f81712018-04-30 05:25:48 +0000868 if (IsTokenRange)
869 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
Chandler Carruth07c346d2011-10-15 23:48:02 +0000870
Richard Smithb5f81712018-04-30 05:25:48 +0000871 FullSourceLoc BF(B, SM), EF(E, SM);
872 OS << '{'
873 << BF.getLineNumber() << ':' << BF.getColumnNumber() << '-'
874 << EF.getLineNumber() << ':' << (EF.getColumnNumber() + TokSize)
875 << '}';
Chandler Carruth07c346d2011-10-15 23:48:02 +0000876 PrintedRange = true;
877 }
878
879 if (PrintedRange)
880 OS << ':';
881 }
882 OS << ' ';
883}
884
Christof Doumafb4a0452017-06-27 09:50:38 +0000885void TextDiagnostic::emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) {
Richard Smith41e66292016-04-28 18:26:32 +0000886 if (DiagOpts->ShowLocation && PLoc.isValid())
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000887 OS << "In file included from " << PLoc.getFilename() << ':'
888 << PLoc.getLine() << ":\n";
889 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000890 OS << "In included file:\n";
Chandler Carrutha3028852011-10-15 23:43:53 +0000891}
892
Christof Doumafb4a0452017-06-27 09:50:38 +0000893void TextDiagnostic::emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc,
894 StringRef ModuleName) {
Richard Smith41e66292016-04-28 18:26:32 +0000895 if (DiagOpts->ShowLocation && PLoc.isValid())
Douglas Gregor22103e32012-11-30 21:58:49 +0000896 OS << "In module '" << ModuleName << "' imported from "
897 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
898 else
Richard Smitha24ff552015-08-11 00:05:21 +0000899 OS << "In module '" << ModuleName << "':\n";
Douglas Gregor22103e32012-11-30 21:58:49 +0000900}
901
Christof Doumafb4a0452017-06-27 09:50:38 +0000902void TextDiagnostic::emitBuildingModuleLocation(FullSourceLoc Loc,
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000903 PresumedLoc PLoc,
Christof Doumafb4a0452017-06-27 09:50:38 +0000904 StringRef ModuleName) {
Richard Smith41e66292016-04-28 18:26:32 +0000905 if (DiagOpts->ShowLocation && PLoc.isValid())
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000906 OS << "While building module '" << ModuleName << "' imported from "
907 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
908 else
909 OS << "While building module '" << ModuleName << "':\n";
910}
911
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000912/// Find the suitable set of lines to show to include a set of ranges.
Richard Smith0c7d4d7e2017-05-22 23:51:40 +0000913static llvm::Optional<std::pair<unsigned, unsigned>>
914findLinesForRange(const CharSourceRange &R, FileID FID,
915 const SourceManager &SM) {
916 if (!R.isValid()) return None;
917
918 SourceLocation Begin = R.getBegin();
919 SourceLocation End = R.getEnd();
920 if (SM.getFileID(Begin) != FID || SM.getFileID(End) != FID)
921 return None;
922
923 return std::make_pair(SM.getExpansionLineNumber(Begin),
924 SM.getExpansionLineNumber(End));
925}
926
927/// Add as much of range B into range A as possible without exceeding a maximum
928/// size of MaxRange. Ranges are inclusive.
Benjamin Kramer674d5792017-05-26 20:08:24 +0000929static std::pair<unsigned, unsigned>
930maybeAddRange(std::pair<unsigned, unsigned> A, std::pair<unsigned, unsigned> B,
931 unsigned MaxRange) {
Richard Smith0c7d4d7e2017-05-22 23:51:40 +0000932 // If A is already the maximum size, we're done.
933 unsigned Slack = MaxRange - (A.second - A.first + 1);
934 if (Slack == 0)
935 return A;
936
937 // Easy case: merge succeeds within MaxRange.
938 unsigned Min = std::min(A.first, B.first);
939 unsigned Max = std::max(A.second, B.second);
940 if (Max - Min + 1 <= MaxRange)
941 return {Min, Max};
942
943 // If we can't reach B from A within MaxRange, there's nothing to do.
944 // Don't add lines to the range that contain nothing interesting.
945 if ((B.first > A.first && B.first - A.first + 1 > MaxRange) ||
946 (B.second < A.second && A.second - B.second + 1 > MaxRange))
947 return A;
948
949 // Otherwise, expand A towards B to produce a range of size MaxRange. We
950 // attempt to expand by the same amount in both directions if B strictly
951 // contains A.
952
953 // Expand downwards by up to half the available amount, then upwards as
954 // much as possible, then downwards as much as possible.
955 A.second = std::min(A.second + (Slack + 1) / 2, Max);
956 Slack = MaxRange - (A.second - A.first + 1);
957 A.first = std::max(Min + Slack, A.first) - Slack;
958 A.second = std::min(A.first + MaxRange - 1, Max);
959 return A;
960}
961
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000962/// Highlight a SourceRange (with ~'s) for any characters on LineNo.
Benjamin Kramer2a812282012-12-01 20:58:01 +0000963static void highlightRange(const CharSourceRange &R,
964 unsigned LineNo, FileID FID,
965 const SourceColumnMap &map,
966 std::string &CaretLine,
967 const SourceManager &SM,
968 const LangOptions &LangOpts) {
969 if (!R.isValid()) return;
970
971 SourceLocation Begin = R.getBegin();
972 SourceLocation End = R.getEnd();
973
974 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
975 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
976 return; // No intersection.
977
978 unsigned EndLineNo = SM.getExpansionLineNumber(End);
979 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
980 return; // No intersection.
981
982 // Compute the column number of the start.
983 unsigned StartColNo = 0;
984 if (StartLineNo == LineNo) {
985 StartColNo = SM.getExpansionColumnNumber(Begin);
986 if (StartColNo) --StartColNo; // Zero base the col #.
987 }
988
989 // Compute the column number of the end.
990 unsigned EndColNo = map.getSourceLine().size();
991 if (EndLineNo == LineNo) {
992 EndColNo = SM.getExpansionColumnNumber(End);
993 if (EndColNo) {
994 --EndColNo; // Zero base the col #.
995
996 // Add in the length of the token, so that we cover multi-char tokens if
997 // this is a token range.
998 if (R.isTokenRange())
999 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1000 } else {
1001 EndColNo = CaretLine.size();
1002 }
1003 }
1004
1005 assert(StartColNo <= EndColNo && "Invalid range!");
1006
1007 // Check that a token range does not highlight only whitespace.
1008 if (R.isTokenRange()) {
1009 // Pick the first non-whitespace column.
1010 while (StartColNo < map.getSourceLine().size() &&
1011 (map.getSourceLine()[StartColNo] == ' ' ||
1012 map.getSourceLine()[StartColNo] == '\t'))
1013 StartColNo = map.startOfNextColumn(StartColNo);
1014
1015 // Pick the last non-whitespace column.
1016 if (EndColNo > map.getSourceLine().size())
1017 EndColNo = map.getSourceLine().size();
Ted Kremenek90d7fa12013-03-15 23:09:37 +00001018 while (EndColNo &&
Benjamin Kramer2a812282012-12-01 20:58:01 +00001019 (map.getSourceLine()[EndColNo-1] == ' ' ||
1020 map.getSourceLine()[EndColNo-1] == '\t'))
1021 EndColNo = map.startOfPreviousColumn(EndColNo);
1022
1023 // If the start/end passed each other, then we are trying to highlight a
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001024 // range that just exists in whitespace. That most likely means we have
1025 // a multi-line highlighting range that covers a blank line.
1026 if (StartColNo > EndColNo) {
1027 assert(StartLineNo != EndLineNo && "trying to highlight whitespace");
1028 StartColNo = EndColNo;
1029 }
Benjamin Kramer2a812282012-12-01 20:58:01 +00001030 }
1031
1032 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
1033 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
1034
1035 // Fill the range with ~'s.
1036 StartColNo = map.byteToContainingColumn(StartColNo);
1037 EndColNo = map.byteToContainingColumn(EndColNo);
1038
1039 assert(StartColNo <= EndColNo && "Invalid range!");
1040 if (CaretLine.size() < EndColNo)
1041 CaretLine.resize(EndColNo,' ');
1042 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
1043}
1044
Chih-Hung Hsieh322e8c22017-07-12 16:25:40 +00001045static std::string buildFixItInsertionLine(FileID FID,
1046 unsigned LineNo,
Benjamin Kramer2a812282012-12-01 20:58:01 +00001047 const SourceColumnMap &map,
1048 ArrayRef<FixItHint> Hints,
1049 const SourceManager &SM,
1050 const DiagnosticOptions *DiagOpts) {
1051 std::string FixItInsertionLine;
1052 if (Hints.empty() || !DiagOpts->ShowFixits)
1053 return FixItInsertionLine;
1054 unsigned PrevHintEndCol = 0;
1055
1056 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1057 I != E; ++I) {
1058 if (!I->CodeToInsert.empty()) {
1059 // We have an insertion hint. Determine whether the inserted
1060 // code contains no newlines and is on the same line as the caret.
1061 std::pair<FileID, unsigned> HintLocInfo
1062 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chih-Hung Hsieh322e8c22017-07-12 16:25:40 +00001063 if (FID == HintLocInfo.first &&
1064 LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
Benjamin Kramer2a812282012-12-01 20:58:01 +00001065 StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
1066 // Insert the new code into the line just below the code
1067 // that the user wrote.
1068 // Note: When modifying this function, be very careful about what is a
1069 // "column" (printed width, platform-dependent) and what is a
1070 // "byte offset" (SourceManager "column").
1071 unsigned HintByteOffset
1072 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1073
1074 // The hint must start inside the source or right at the end
1075 assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
1076 unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
1077
1078 // If we inserted a long previous hint, push this one forwards, and add
1079 // an extra space to show that this is not part of the previous
1080 // completion. This is sort of the best we can do when two hints appear
1081 // to overlap.
1082 //
1083 // Note that if this hint is located immediately after the previous
1084 // hint, no space will be added, since the location is more important.
1085 if (HintCol < PrevHintEndCol)
1086 HintCol = PrevHintEndCol + 1;
1087
Benjamin Kramer2a812282012-12-01 20:58:01 +00001088 // This should NOT use HintByteOffset, because the source might have
1089 // Unicode characters in earlier columns.
Jordan Rosee2fad6d2013-06-07 17:16:01 +00001090 unsigned NewFixItLineSize = FixItInsertionLine.size() +
1091 (HintCol - PrevHintEndCol) + I->CodeToInsert.size();
1092 if (NewFixItLineSize > FixItInsertionLine.size())
1093 FixItInsertionLine.resize(NewFixItLineSize, ' ');
Benjamin Kramer2a812282012-12-01 20:58:01 +00001094
1095 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Jordan Rosee2fad6d2013-06-07 17:16:01 +00001096 FixItInsertionLine.end() - I->CodeToInsert.size());
Benjamin Kramer2a812282012-12-01 20:58:01 +00001097
Jordan Rosee2fad6d2013-06-07 17:16:01 +00001098 PrevHintEndCol =
1099 HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
Benjamin Kramer2a812282012-12-01 20:58:01 +00001100 }
1101 }
1102 }
1103
1104 expandTabs(FixItInsertionLine, DiagOpts->TabStop);
1105
1106 return FixItInsertionLine;
1107}
1108
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001109/// Emit a code snippet and caret line.
Chandler Carrutha3028852011-10-15 23:43:53 +00001110///
1111/// This routine emits a single line's code snippet and caret line..
1112///
1113/// \param Loc The location for the caret.
1114/// \param Ranges The underlined ranges for this code snippet.
1115/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthab4c1da2011-10-15 23:54:09 +00001116void TextDiagnostic::emitSnippetAndCaret(
Christof Doumafb4a0452017-06-27 09:50:38 +00001117 FullSourceLoc Loc, DiagnosticsEngine::Level Level,
1118 SmallVectorImpl<CharSourceRange> &Ranges, ArrayRef<FixItHint> Hints) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +00001119 assert(Loc.isValid() && "must have a valid source location here");
Chandler Carrutha3028852011-10-15 23:43:53 +00001120 assert(Loc.isFileID() && "must have a file location here");
1121
Chandler Carruthdc2f2572011-10-16 07:20:28 +00001122 // If caret diagnostics are enabled and we have location, we want to
1123 // emit the caret. However, we only do this if the location moved
1124 // from the last diagnostic, if the last diagnostic was a note that
1125 // was part of a different warning or error diagnostic, or if the
1126 // diagnostic has ranges. We don't want to emit the same caret
1127 // multiple times if one loc has multiple diagnostics.
Douglas Gregor811db4e2012-10-23 22:26:28 +00001128 if (!DiagOpts->ShowCarets)
Chandler Carruthdc2f2572011-10-16 07:20:28 +00001129 return;
1130 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
1131 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
1132 return;
1133
Chandler Carrutha3028852011-10-15 23:43:53 +00001134 // Decompose the location into a FID/Offset pair.
Christof Doumafb4a0452017-06-27 09:50:38 +00001135 std::pair<FileID, unsigned> LocInfo = Loc.getDecomposedLoc();
Chandler Carrutha3028852011-10-15 23:43:53 +00001136 FileID FID = LocInfo.first;
Christof Doumafb4a0452017-06-27 09:50:38 +00001137 const SourceManager &SM = Loc.getManager();
Chandler Carrutha3028852011-10-15 23:43:53 +00001138
1139 // Get information about the buffer it points into.
1140 bool Invalid = false;
Christof Doumafb4a0452017-06-27 09:50:38 +00001141 StringRef BufData = Loc.getBufferData(&Invalid);
Chandler Carrutha3028852011-10-15 23:43:53 +00001142 if (Invalid)
1143 return;
1144
Christof Doumafb4a0452017-06-27 09:50:38 +00001145 unsigned CaretLineNo = Loc.getLineNumber();
1146 unsigned CaretColNo = Loc.getColumnNumber();
David Majnemer38a3dbd2016-02-17 22:37:45 +00001147
Jordan Rose2da0d1c2013-01-30 21:41:07 +00001148 // Arbitrarily stop showing snippets when the line is too long.
Benjamin Kramerd408de62013-04-23 14:42:47 +00001149 static const size_t MaxLineLengthToPrint = 4096;
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001150 if (CaretColNo > MaxLineLengthToPrint)
Jordan Rose2da0d1c2013-01-30 21:41:07 +00001151 return;
Chandler Carrutha3028852011-10-15 23:43:53 +00001152
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001153 // Find the set of lines to include.
1154 const unsigned MaxLines = DiagOpts->SnippetLineLimit;
1155 std::pair<unsigned, unsigned> Lines = {CaretLineNo, CaretLineNo};
Chandler Carrutha3028852011-10-15 23:43:53 +00001156 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
1157 E = Ranges.end();
1158 I != E; ++I)
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001159 if (auto OptionalRange = findLinesForRange(*I, FID, SM))
1160 Lines = maybeAddRange(Lines, *OptionalRange, MaxLines);
Chandler Carrutha3028852011-10-15 23:43:53 +00001161
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001162 for (unsigned LineNo = Lines.first; LineNo != Lines.second + 1; ++LineNo) {
1163 const char *BufStart = BufData.data();
1164 const char *BufEnd = BufStart + BufData.size();
Chandler Carrutha3028852011-10-15 23:43:53 +00001165
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001166 // Rewind from the current position to the start of the line.
1167 const char *LineStart =
1168 BufStart +
1169 SM.getDecomposedLoc(SM.translateLineCol(FID, LineNo, 1)).second;
1170 if (LineStart == BufEnd)
1171 break;
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001172
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001173 // Compute the line end.
1174 const char *LineEnd = LineStart;
1175 while (*LineEnd != '\n' && *LineEnd != '\r' && LineEnd != BufEnd)
1176 ++LineEnd;
Chandler Carrutha3028852011-10-15 23:43:53 +00001177
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001178 // Arbitrarily stop showing snippets when the line is too long.
1179 // FIXME: Don't print any lines in this case.
1180 if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
1181 return;
Chandler Carrutha3028852011-10-15 23:43:53 +00001182
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001183 // Trim trailing null-bytes.
1184 StringRef Line(LineStart, LineEnd - LineStart);
1185 while (!Line.empty() && Line.back() == '\0' &&
1186 (LineNo != CaretLineNo || Line.size() > CaretColNo))
1187 Line = Line.drop_back();
Chandler Carrutha3028852011-10-15 23:43:53 +00001188
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001189 // Copy the line of code into an std::string for ease of manipulation.
1190 std::string SourceLine(Line.begin(), Line.end());
Chandler Carrutha3028852011-10-15 23:43:53 +00001191
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001192 // Build the byte to column map.
1193 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
Chandler Carrutha3028852011-10-15 23:43:53 +00001194
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001195 // Create a line for the caret that is filled with spaces that is the same
1196 // number of columns as the line of source code.
1197 std::string CaretLine(sourceColMap.columns(), ' ');
1198
1199 // Highlight all of the characters covered by Ranges with ~ characters.
1200 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
1201 E = Ranges.end();
1202 I != E; ++I)
1203 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
1204
1205 // Next, insert the caret itself.
1206 if (CaretLineNo == LineNo) {
1207 CaretColNo = sourceColMap.byteToContainingColumn(CaretColNo - 1);
1208 if (CaretLine.size() < CaretColNo + 1)
1209 CaretLine.resize(CaretColNo + 1, ' ');
1210 CaretLine[CaretColNo] = '^';
1211 }
1212
1213 std::string FixItInsertionLine = buildFixItInsertionLine(
Chih-Hung Hsieh322e8c22017-07-12 16:25:40 +00001214 FID, LineNo, sourceColMap, Hints, SM, DiagOpts.get());
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001215
1216 // If the source line is too long for our terminal, select only the
1217 // "interesting" source region within that line.
1218 unsigned Columns = DiagOpts->MessageLength;
1219 if (Columns)
1220 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
1221 Columns, sourceColMap);
1222
1223 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
1224 // to produce easily machine parsable output. Add a space before the
1225 // source line and the caret to make it trivial to tell the main diagnostic
1226 // line from what the user is intended to see.
1227 if (DiagOpts->ShowSourceRanges) {
1228 SourceLine = ' ' + SourceLine;
1229 CaretLine = ' ' + CaretLine;
1230 }
1231
1232 // Finally, remove any blank spaces from the end of CaretLine.
Benjamin Kramer4e382f92017-05-23 20:48:21 +00001233 while (!CaretLine.empty() && CaretLine[CaretLine.size() - 1] == ' ')
Richard Smith0c7d4d7e2017-05-22 23:51:40 +00001234 CaretLine.erase(CaretLine.end() - 1);
1235
1236 // Emit what we have computed.
1237 emitSnippet(SourceLine);
1238
1239 if (!CaretLine.empty()) {
1240 if (DiagOpts->ShowColors)
1241 OS.changeColor(caretColor, true);
1242 OS << CaretLine << '\n';
1243 if (DiagOpts->ShowColors)
1244 OS.resetColor();
1245 }
1246
1247 if (!FixItInsertionLine.empty()) {
1248 if (DiagOpts->ShowColors)
1249 // Print fixit line in color
1250 OS.changeColor(fixitColor, false);
1251 if (DiagOpts->ShowSourceRanges)
1252 OS << ' ';
1253 OS << FixItInsertionLine << '\n';
1254 if (DiagOpts->ShowColors)
1255 OS.resetColor();
1256 }
Chandler Carrutha3028852011-10-15 23:43:53 +00001257 }
1258
1259 // Print out any parseable fixit information requested by the options.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001260 emitParseableFixits(Hints, SM);
Chandler Carrutha3028852011-10-15 23:43:53 +00001261}
1262
Benjamin Kramer556ab5e2012-05-01 14:34:11 +00001263void TextDiagnostic::emitSnippet(StringRef line) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001264 if (line.empty())
1265 return;
1266
1267 size_t i = 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00001268
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001269 std::string to_print;
1270 bool print_reversed = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001271
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001272 while (i<line.size()) {
1273 std::pair<SmallString<16>,bool> res
Douglas Gregor811db4e2012-10-23 22:26:28 +00001274 = printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001275 bool was_printable = res.second;
Fangrui Song6907ce22018-07-30 19:24:48 +00001276
Douglas Gregor811db4e2012-10-23 22:26:28 +00001277 if (DiagOpts->ShowColors && was_printable == print_reversed) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001278 if (print_reversed)
1279 OS.reverseColor();
1280 OS << to_print;
1281 to_print.clear();
Douglas Gregor811db4e2012-10-23 22:26:28 +00001282 if (DiagOpts->ShowColors)
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001283 OS.resetColor();
1284 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001285
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001286 print_reversed = !was_printable;
1287 to_print += res.first.str();
1288 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001289
Douglas Gregor811db4e2012-10-23 22:26:28 +00001290 if (print_reversed && DiagOpts->ShowColors)
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001291 OS.reverseColor();
1292 OS << to_print;
Douglas Gregor811db4e2012-10-23 22:26:28 +00001293 if (print_reversed && DiagOpts->ShowColors)
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001294 OS.resetColor();
Fangrui Song6907ce22018-07-30 19:24:48 +00001295
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001296 OS << '\n';
1297}
1298
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001299void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1300 const SourceManager &SM) {
Douglas Gregor811db4e2012-10-23 22:26:28 +00001301 if (!DiagOpts->ShowParseableFixits)
Chandler Carrutha3028852011-10-15 23:43:53 +00001302 return;
1303
1304 // We follow FixItRewriter's example in not (yet) handling
1305 // fix-its in macros.
1306 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1307 I != E; ++I) {
1308 if (I->RemoveRange.isInvalid() ||
1309 I->RemoveRange.getBegin().isMacroID() ||
1310 I->RemoveRange.getEnd().isMacroID())
1311 return;
1312 }
1313
1314 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1315 I != E; ++I) {
1316 SourceLocation BLoc = I->RemoveRange.getBegin();
1317 SourceLocation ELoc = I->RemoveRange.getEnd();
1318
1319 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1320 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1321
1322 // Adjust for token ranges.
1323 if (I->RemoveRange.isTokenRange())
1324 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1325
1326 // We specifically do not do word-wrapping or tab-expansion here,
1327 // because this is supposed to be easy to parse.
1328 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1329 if (PLoc.isInvalid())
1330 break;
1331
1332 OS << "fix-it:\"";
1333 OS.write_escaped(PLoc.getFilename());
1334 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1335 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1336 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1337 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1338 << "}:\"";
1339 OS.write_escaped(I->CodeToInsert);
1340 OS << "\"\n";
1341 }
1342}