TextDiagnostic.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  1. //===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
  2. //
  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. #include "clang/Frontend/TextDiagnostic.h"
  10. #include "clang/Basic/CharInfo.h"
  11. #include "clang/Basic/DiagnosticOptions.h"
  12. #include "clang/Basic/FileManager.h"
  13. #include "clang/Basic/SourceManager.h"
  14. #include "clang/Lex/Lexer.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/Support/ConvertUTF.h"
  18. #include "llvm/Support/ErrorHandling.h"
  19. #include "llvm/Support/Locale.h"
  20. #include "llvm/Support/MemoryBuffer.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. #include <algorithm>
  23. using namespace clang;
  24. static const enum raw_ostream::Colors noteColor =
  25. raw_ostream::BLACK;
  26. static const enum raw_ostream::Colors remarkColor =
  27. raw_ostream::BLUE;
  28. static const enum raw_ostream::Colors fixitColor =
  29. raw_ostream::GREEN;
  30. static const enum raw_ostream::Colors caretColor =
  31. raw_ostream::GREEN;
  32. static const enum raw_ostream::Colors warningColor =
  33. raw_ostream::MAGENTA;
  34. static const enum raw_ostream::Colors templateColor =
  35. raw_ostream::CYAN;
  36. static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
  37. static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
  38. // Used for changing only the bold attribute.
  39. static const enum raw_ostream::Colors savedColor =
  40. raw_ostream::SAVEDCOLOR;
  41. /// \brief Add highlights to differences in template strings.
  42. static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
  43. bool &Normal, bool Bold) {
  44. while (1) {
  45. size_t Pos = Str.find(ToggleHighlight);
  46. OS << Str.slice(0, Pos);
  47. if (Pos == StringRef::npos)
  48. break;
  49. Str = Str.substr(Pos + 1);
  50. if (Normal)
  51. OS.changeColor(templateColor, true);
  52. else {
  53. OS.resetColor();
  54. if (Bold)
  55. OS.changeColor(savedColor, true);
  56. }
  57. Normal = !Normal;
  58. }
  59. }
  60. /// \brief Number of spaces to indent when word-wrapping.
  61. const unsigned WordWrapIndentation = 6;
  62. static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
  63. int bytes = 0;
  64. while (0<i) {
  65. if (SourceLine[--i]=='\t')
  66. break;
  67. ++bytes;
  68. }
  69. return bytes;
  70. }
  71. /// \brief returns a printable representation of first item from input range
  72. ///
  73. /// This function returns a printable representation of the next item in a line
  74. /// of source. If the next byte begins a valid and printable character, that
  75. /// character is returned along with 'true'.
  76. ///
  77. /// Otherwise, if the next byte begins a valid, but unprintable character, a
  78. /// printable, escaped representation of the character is returned, along with
  79. /// 'false'. Otherwise a printable, escaped representation of the next byte
  80. /// is returned along with 'false'.
  81. ///
  82. /// \note The index is updated to be used with a subsequent call to
  83. /// printableTextForNextCharacter.
  84. ///
  85. /// \param SourceLine The line of source
  86. /// \param i Pointer to byte index,
  87. /// \param TabStop used to expand tabs
  88. /// \return pair(printable text, 'true' iff original text was printable)
  89. ///
  90. static std::pair<SmallString<16>, bool>
  91. printableTextForNextCharacter(StringRef SourceLine, size_t *i,
  92. unsigned TabStop) {
  93. assert(i && "i must not be null");
  94. assert(*i<SourceLine.size() && "must point to a valid index");
  95. if (SourceLine[*i]=='\t') {
  96. assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
  97. "Invalid -ftabstop value");
  98. unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
  99. unsigned NumSpaces = TabStop - col%TabStop;
  100. assert(0 < NumSpaces && NumSpaces <= TabStop
  101. && "Invalid computation of space amt");
  102. ++(*i);
  103. SmallString<16> expandedTab;
  104. expandedTab.assign(NumSpaces, ' ');
  105. return std::make_pair(expandedTab, true);
  106. }
  107. unsigned char const *begin, *end;
  108. begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
  109. end = begin + (SourceLine.size() - *i);
  110. if (isLegalUTF8Sequence(begin, end)) {
  111. UTF32 c;
  112. UTF32 *cptr = &c;
  113. unsigned char const *original_begin = begin;
  114. unsigned char const *cp_end = begin+getNumBytesForUTF8(SourceLine[*i]);
  115. ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
  116. strictConversion);
  117. (void)res;
  118. assert(conversionOK==res);
  119. assert(0 < begin-original_begin
  120. && "we must be further along in the string now");
  121. *i += begin-original_begin;
  122. if (!llvm::sys::locale::isPrint(c)) {
  123. // If next character is valid UTF-8, but not printable
  124. SmallString<16> expandedCP("<U+>");
  125. while (c) {
  126. expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
  127. c/=16;
  128. }
  129. while (expandedCP.size() < 8)
  130. expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
  131. return std::make_pair(expandedCP, false);
  132. }
  133. // If next character is valid UTF-8, and printable
  134. return std::make_pair(SmallString<16>(original_begin, cp_end), true);
  135. }
  136. // If next byte is not valid UTF-8 (and therefore not printable)
  137. SmallString<16> expandedByte("<XX>");
  138. unsigned char byte = SourceLine[*i];
  139. expandedByte[1] = llvm::hexdigit(byte / 16);
  140. expandedByte[2] = llvm::hexdigit(byte % 16);
  141. ++(*i);
  142. return std::make_pair(expandedByte, false);
  143. }
  144. static void expandTabs(std::string &SourceLine, unsigned TabStop) {
  145. size_t i = SourceLine.size();
  146. while (i>0) {
  147. i--;
  148. if (SourceLine[i]!='\t')
  149. continue;
  150. size_t tmp_i = i;
  151. std::pair<SmallString<16>,bool> res
  152. = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
  153. SourceLine.replace(i, 1, res.first.c_str());
  154. }
  155. }
  156. /// This function takes a raw source line and produces a mapping from the bytes
  157. /// of the printable representation of the line to the columns those printable
  158. /// characters will appear at (numbering the first column as 0).
  159. ///
  160. /// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
  161. /// character) then the array will map that byte to the first column the
  162. /// tab appears at and the next value in the map will have been incremented
  163. /// more than once.
  164. ///
  165. /// If a byte is the first in a sequence of bytes that together map to a single
  166. /// entity in the output, then the array will map that byte to the appropriate
  167. /// column while the subsequent bytes will be -1.
  168. ///
  169. /// The last element in the array does not correspond to any byte in the input
  170. /// and instead is the number of columns needed to display the source
  171. ///
  172. /// example: (given a tabstop of 8)
  173. ///
  174. /// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
  175. ///
  176. /// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
  177. /// display)
  178. static void byteToColumn(StringRef SourceLine, unsigned TabStop,
  179. SmallVectorImpl<int> &out) {
  180. out.clear();
  181. if (SourceLine.empty()) {
  182. out.resize(1u,0);
  183. return;
  184. }
  185. out.resize(SourceLine.size()+1, -1);
  186. int columns = 0;
  187. size_t i = 0;
  188. while (i<SourceLine.size()) {
  189. out[i] = columns;
  190. std::pair<SmallString<16>,bool> res
  191. = printableTextForNextCharacter(SourceLine, &i, TabStop);
  192. columns += llvm::sys::locale::columnWidth(res.first);
  193. }
  194. out.back() = columns;
  195. }
  196. /// This function takes a raw source line and produces a mapping from columns
  197. /// to the byte of the source line that produced the character displaying at
  198. /// that column. This is the inverse of the mapping produced by byteToColumn()
  199. ///
  200. /// The last element in the array is the number of bytes in the source string
  201. ///
  202. /// example: (given a tabstop of 8)
  203. ///
  204. /// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
  205. ///
  206. /// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
  207. /// display)
  208. static void columnToByte(StringRef SourceLine, unsigned TabStop,
  209. SmallVectorImpl<int> &out) {
  210. out.clear();
  211. if (SourceLine.empty()) {
  212. out.resize(1u, 0);
  213. return;
  214. }
  215. int columns = 0;
  216. size_t i = 0;
  217. while (i<SourceLine.size()) {
  218. out.resize(columns+1, -1);
  219. out.back() = i;
  220. std::pair<SmallString<16>,bool> res
  221. = printableTextForNextCharacter(SourceLine, &i, TabStop);
  222. columns += llvm::sys::locale::columnWidth(res.first);
  223. }
  224. out.resize(columns+1, -1);
  225. out.back() = i;
  226. }
  227. namespace {
  228. struct SourceColumnMap {
  229. SourceColumnMap(StringRef SourceLine, unsigned TabStop)
  230. : m_SourceLine(SourceLine) {
  231. ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
  232. ::columnToByte(SourceLine, TabStop, m_columnToByte);
  233. assert(m_byteToColumn.size()==SourceLine.size()+1);
  234. assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
  235. assert(m_byteToColumn.size()
  236. == static_cast<unsigned>(m_columnToByte.back()+1));
  237. assert(static_cast<unsigned>(m_byteToColumn.back()+1)
  238. == m_columnToByte.size());
  239. }
  240. int columns() const { return m_byteToColumn.back(); }
  241. int bytes() const { return m_columnToByte.back(); }
  242. /// \brief Map a byte to the column which it is at the start of, or return -1
  243. /// if it is not at the start of a column (for a UTF-8 trailing byte).
  244. int byteToColumn(int n) const {
  245. assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
  246. return m_byteToColumn[n];
  247. }
  248. /// \brief Map a byte to the first column which contains it.
  249. int byteToContainingColumn(int N) const {
  250. assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
  251. while (m_byteToColumn[N] == -1)
  252. --N;
  253. return m_byteToColumn[N];
  254. }
  255. /// \brief Map a column to the byte which starts the column, or return -1 if
  256. /// the column the second or subsequent column of an expanded tab or similar
  257. /// multi-column entity.
  258. int columnToByte(int n) const {
  259. assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
  260. return m_columnToByte[n];
  261. }
  262. /// \brief Map from a byte index to the next byte which starts a column.
  263. int startOfNextColumn(int N) const {
  264. assert(0 <= N && N < static_cast<int>(m_columnToByte.size() - 1));
  265. while (byteToColumn(++N) == -1) {}
  266. return N;
  267. }
  268. /// \brief Map from a byte index to the previous byte which starts a column.
  269. int startOfPreviousColumn(int N) const {
  270. assert(0 < N && N < static_cast<int>(m_columnToByte.size()));
  271. while (byteToColumn(--N) == -1) {}
  272. return N;
  273. }
  274. StringRef getSourceLine() const {
  275. return m_SourceLine;
  276. }
  277. private:
  278. const std::string m_SourceLine;
  279. SmallVector<int,200> m_byteToColumn;
  280. SmallVector<int,200> m_columnToByte;
  281. };
  282. } // end anonymous namespace
  283. /// \brief When the source code line we want to print is too long for
  284. /// the terminal, select the "interesting" region.
  285. static void selectInterestingSourceRegion(std::string &SourceLine,
  286. std::string &CaretLine,
  287. std::string &FixItInsertionLine,
  288. unsigned Columns,
  289. const SourceColumnMap &map) {
  290. unsigned MaxColumns = std::max<unsigned>(map.columns(),
  291. std::max(CaretLine.size(),
  292. FixItInsertionLine.size()));
  293. // if the number of columns is less than the desired number we're done
  294. if (MaxColumns <= Columns)
  295. return;
  296. // No special characters are allowed in CaretLine.
  297. assert(CaretLine.end() ==
  298. std::find_if(CaretLine.begin(), CaretLine.end(),
  299. [](char c) { return c < ' ' || '~' < c; }));
  300. // Find the slice that we need to display the full caret line
  301. // correctly.
  302. unsigned CaretStart = 0, CaretEnd = CaretLine.size();
  303. for (; CaretStart != CaretEnd; ++CaretStart)
  304. if (!isWhitespace(CaretLine[CaretStart]))
  305. break;
  306. for (; CaretEnd != CaretStart; --CaretEnd)
  307. if (!isWhitespace(CaretLine[CaretEnd - 1]))
  308. break;
  309. // caret has already been inserted into CaretLine so the above whitespace
  310. // check is guaranteed to include the caret
  311. // If we have a fix-it line, make sure the slice includes all of the
  312. // fix-it information.
  313. if (!FixItInsertionLine.empty()) {
  314. unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
  315. for (; FixItStart != FixItEnd; ++FixItStart)
  316. if (!isWhitespace(FixItInsertionLine[FixItStart]))
  317. break;
  318. for (; FixItEnd != FixItStart; --FixItEnd)
  319. if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
  320. break;
  321. // We can safely use the byte offset FixItStart as the column offset
  322. // because the characters up until FixItStart are all ASCII whitespace
  323. // characters.
  324. unsigned FixItStartCol = FixItStart;
  325. unsigned FixItEndCol
  326. = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
  327. CaretStart = std::min(FixItStartCol, CaretStart);
  328. CaretEnd = std::max(FixItEndCol, CaretEnd);
  329. }
  330. // CaretEnd may have been set at the middle of a character
  331. // If it's not at a character's first column then advance it past the current
  332. // character.
  333. while (static_cast<int>(CaretEnd) < map.columns() &&
  334. -1 == map.columnToByte(CaretEnd))
  335. ++CaretEnd;
  336. assert((static_cast<int>(CaretStart) > map.columns() ||
  337. -1!=map.columnToByte(CaretStart)) &&
  338. "CaretStart must not point to a column in the middle of a source"
  339. " line character");
  340. assert((static_cast<int>(CaretEnd) > map.columns() ||
  341. -1!=map.columnToByte(CaretEnd)) &&
  342. "CaretEnd must not point to a column in the middle of a source line"
  343. " character");
  344. // CaretLine[CaretStart, CaretEnd) contains all of the interesting
  345. // parts of the caret line. While this slice is smaller than the
  346. // number of columns we have, try to grow the slice to encompass
  347. // more context.
  348. unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
  349. map.columns()));
  350. unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
  351. map.columns()));
  352. unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
  353. - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
  354. char const *front_ellipse = " ...";
  355. char const *front_space = " ";
  356. char const *back_ellipse = "...";
  357. unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
  358. unsigned TargetColumns = Columns;
  359. // Give us extra room for the ellipses
  360. // and any of the caret line that extends past the source
  361. if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
  362. TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
  363. while (SourceStart>0 || SourceEnd<SourceLine.size()) {
  364. bool ExpandedRegion = false;
  365. if (SourceStart>0) {
  366. unsigned NewStart = map.startOfPreviousColumn(SourceStart);
  367. // Skip over any whitespace we see here; we're looking for
  368. // another bit of interesting text.
  369. // FIXME: Detect non-ASCII whitespace characters too.
  370. while (NewStart && isWhitespace(SourceLine[NewStart]))
  371. NewStart = map.startOfPreviousColumn(NewStart);
  372. // Skip over this bit of "interesting" text.
  373. while (NewStart) {
  374. unsigned Prev = map.startOfPreviousColumn(NewStart);
  375. if (isWhitespace(SourceLine[Prev]))
  376. break;
  377. NewStart = Prev;
  378. }
  379. assert(map.byteToColumn(NewStart) != -1);
  380. unsigned NewColumns = map.byteToColumn(SourceEnd) -
  381. map.byteToColumn(NewStart);
  382. if (NewColumns <= TargetColumns) {
  383. SourceStart = NewStart;
  384. ExpandedRegion = true;
  385. }
  386. }
  387. if (SourceEnd<SourceLine.size()) {
  388. unsigned NewEnd = map.startOfNextColumn(SourceEnd);
  389. // Skip over any whitespace we see here; we're looking for
  390. // another bit of interesting text.
  391. // FIXME: Detect non-ASCII whitespace characters too.
  392. while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
  393. NewEnd = map.startOfNextColumn(NewEnd);
  394. // Skip over this bit of "interesting" text.
  395. while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
  396. NewEnd = map.startOfNextColumn(NewEnd);
  397. assert(map.byteToColumn(NewEnd) != -1);
  398. unsigned NewColumns = map.byteToColumn(NewEnd) -
  399. map.byteToColumn(SourceStart);
  400. if (NewColumns <= TargetColumns) {
  401. SourceEnd = NewEnd;
  402. ExpandedRegion = true;
  403. }
  404. }
  405. if (!ExpandedRegion)
  406. break;
  407. }
  408. CaretStart = map.byteToColumn(SourceStart);
  409. CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
  410. // [CaretStart, CaretEnd) is the slice we want. Update the various
  411. // output lines to show only this slice, with two-space padding
  412. // before the lines so that it looks nicer.
  413. assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
  414. SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
  415. assert(SourceStart <= SourceEnd);
  416. assert(CaretStart <= CaretEnd);
  417. unsigned BackColumnsRemoved
  418. = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
  419. unsigned FrontColumnsRemoved = CaretStart;
  420. unsigned ColumnsKept = CaretEnd-CaretStart;
  421. // We checked up front that the line needed truncation
  422. assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
  423. // The line needs some trunctiona, and we'd prefer to keep the front
  424. // if possible, so remove the back
  425. if (BackColumnsRemoved > strlen(back_ellipse))
  426. SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
  427. // If that's enough then we're done
  428. if (FrontColumnsRemoved+ColumnsKept <= Columns)
  429. return;
  430. // Otherwise remove the front as well
  431. if (FrontColumnsRemoved > strlen(front_ellipse)) {
  432. SourceLine.replace(0, SourceStart, front_ellipse);
  433. CaretLine.replace(0, CaretStart, front_space);
  434. if (!FixItInsertionLine.empty())
  435. FixItInsertionLine.replace(0, CaretStart, front_space);
  436. }
  437. }
  438. /// \brief Skip over whitespace in the string, starting at the given
  439. /// index.
  440. ///
  441. /// \returns The index of the first non-whitespace character that is
  442. /// greater than or equal to Idx or, if no such character exists,
  443. /// returns the end of the string.
  444. static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
  445. while (Idx < Length && isWhitespace(Str[Idx]))
  446. ++Idx;
  447. return Idx;
  448. }
  449. /// \brief If the given character is the start of some kind of
  450. /// balanced punctuation (e.g., quotes or parentheses), return the
  451. /// character that will terminate the punctuation.
  452. ///
  453. /// \returns The ending punctuation character, if any, or the NULL
  454. /// character if the input character does not start any punctuation.
  455. static inline char findMatchingPunctuation(char c) {
  456. switch (c) {
  457. case '\'': return '\'';
  458. case '`': return '\'';
  459. case '"': return '"';
  460. case '(': return ')';
  461. case '[': return ']';
  462. case '{': return '}';
  463. default: break;
  464. }
  465. return 0;
  466. }
  467. /// \brief Find the end of the word starting at the given offset
  468. /// within a string.
  469. ///
  470. /// \returns the index pointing one character past the end of the
  471. /// word.
  472. static unsigned findEndOfWord(unsigned Start, StringRef Str,
  473. unsigned Length, unsigned Column,
  474. unsigned Columns) {
  475. assert(Start < Str.size() && "Invalid start position!");
  476. unsigned End = Start + 1;
  477. // If we are already at the end of the string, take that as the word.
  478. if (End == Str.size())
  479. return End;
  480. // Determine if the start of the string is actually opening
  481. // punctuation, e.g., a quote or parentheses.
  482. char EndPunct = findMatchingPunctuation(Str[Start]);
  483. if (!EndPunct) {
  484. // This is a normal word. Just find the first space character.
  485. while (End < Length && !isWhitespace(Str[End]))
  486. ++End;
  487. return End;
  488. }
  489. // We have the start of a balanced punctuation sequence (quotes,
  490. // parentheses, etc.). Determine the full sequence is.
  491. SmallString<16> PunctuationEndStack;
  492. PunctuationEndStack.push_back(EndPunct);
  493. while (End < Length && !PunctuationEndStack.empty()) {
  494. if (Str[End] == PunctuationEndStack.back())
  495. PunctuationEndStack.pop_back();
  496. else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
  497. PunctuationEndStack.push_back(SubEndPunct);
  498. ++End;
  499. }
  500. // Find the first space character after the punctuation ended.
  501. while (End < Length && !isWhitespace(Str[End]))
  502. ++End;
  503. unsigned PunctWordLength = End - Start;
  504. if (// If the word fits on this line
  505. Column + PunctWordLength <= Columns ||
  506. // ... or the word is "short enough" to take up the next line
  507. // without too much ugly white space
  508. PunctWordLength < Columns/3)
  509. return End; // Take the whole thing as a single "word".
  510. // The whole quoted/parenthesized string is too long to print as a
  511. // single "word". Instead, find the "word" that starts just after
  512. // the punctuation and use that end-point instead. This will recurse
  513. // until it finds something small enough to consider a word.
  514. return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
  515. }
  516. /// \brief Print the given string to a stream, word-wrapping it to
  517. /// some number of columns in the process.
  518. ///
  519. /// \param OS the stream to which the word-wrapping string will be
  520. /// emitted.
  521. /// \param Str the string to word-wrap and output.
  522. /// \param Columns the number of columns to word-wrap to.
  523. /// \param Column the column number at which the first character of \p
  524. /// Str will be printed. This will be non-zero when part of the first
  525. /// line has already been printed.
  526. /// \param Bold if the current text should be bold
  527. /// \param Indentation the number of spaces to indent any lines beyond
  528. /// the first line.
  529. /// \returns true if word-wrapping was required, or false if the
  530. /// string fit on the first line.
  531. static bool printWordWrapped(raw_ostream &OS, StringRef Str,
  532. unsigned Columns,
  533. unsigned Column = 0,
  534. bool Bold = false,
  535. unsigned Indentation = WordWrapIndentation) {
  536. const unsigned Length = std::min(Str.find('\n'), Str.size());
  537. bool TextNormal = true;
  538. // The string used to indent each line.
  539. SmallString<16> IndentStr;
  540. IndentStr.assign(Indentation, ' ');
  541. bool Wrapped = false;
  542. for (unsigned WordStart = 0, WordEnd; WordStart < Length;
  543. WordStart = WordEnd) {
  544. // Find the beginning of the next word.
  545. WordStart = skipWhitespace(WordStart, Str, Length);
  546. if (WordStart == Length)
  547. break;
  548. // Find the end of this word.
  549. WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
  550. // Does this word fit on the current line?
  551. unsigned WordLength = WordEnd - WordStart;
  552. if (Column + WordLength < Columns) {
  553. // This word fits on the current line; print it there.
  554. if (WordStart) {
  555. OS << ' ';
  556. Column += 1;
  557. }
  558. applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
  559. TextNormal, Bold);
  560. Column += WordLength;
  561. continue;
  562. }
  563. // This word does not fit on the current line, so wrap to the next
  564. // line.
  565. OS << '\n';
  566. OS.write(&IndentStr[0], Indentation);
  567. applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
  568. TextNormal, Bold);
  569. Column = Indentation + WordLength;
  570. Wrapped = true;
  571. }
  572. // Append any remaning text from the message with its existing formatting.
  573. applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
  574. assert(TextNormal && "Text highlighted at end of diagnostic message.");
  575. return Wrapped;
  576. }
  577. TextDiagnostic::TextDiagnostic(raw_ostream &OS,
  578. const LangOptions &LangOpts,
  579. DiagnosticOptions *DiagOpts)
  580. : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
  581. TextDiagnostic::~TextDiagnostic() {}
  582. void
  583. TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
  584. PresumedLoc PLoc,
  585. DiagnosticsEngine::Level Level,
  586. StringRef Message,
  587. ArrayRef<clang::CharSourceRange> Ranges,
  588. const SourceManager *SM,
  589. DiagOrStoredDiag D) {
  590. uint64_t StartOfLocationInfo = OS.tell();
  591. // Emit the location of this particular diagnostic.
  592. if (Loc.isValid())
  593. emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
  594. if (DiagOpts->ShowColors)
  595. OS.resetColor();
  596. printDiagnosticLevel(OS, Level, DiagOpts->ShowColors,
  597. DiagOpts->CLFallbackMode);
  598. printDiagnosticMessage(OS,
  599. /*IsSupplemental*/ Level == DiagnosticsEngine::Note,
  600. Message, OS.tell() - StartOfLocationInfo,
  601. DiagOpts->MessageLength, DiagOpts->ShowColors);
  602. }
  603. /*static*/ void
  604. TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
  605. DiagnosticsEngine::Level Level,
  606. bool ShowColors,
  607. bool CLFallbackMode) {
  608. if (ShowColors) {
  609. // Print diagnostic category in bold and color
  610. switch (Level) {
  611. case DiagnosticsEngine::Ignored:
  612. llvm_unreachable("Invalid diagnostic type");
  613. case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
  614. case DiagnosticsEngine::Remark: OS.changeColor(remarkColor, true); break;
  615. case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
  616. case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
  617. case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
  618. }
  619. }
  620. switch (Level) {
  621. case DiagnosticsEngine::Ignored:
  622. llvm_unreachable("Invalid diagnostic type");
  623. case DiagnosticsEngine::Note: OS << "note"; break;
  624. case DiagnosticsEngine::Remark: OS << "remark"; break;
  625. case DiagnosticsEngine::Warning: OS << "warning"; break;
  626. case DiagnosticsEngine::Error: OS << "error"; break;
  627. case DiagnosticsEngine::Fatal: OS << "fatal error"; break;
  628. }
  629. // In clang-cl /fallback mode, print diagnostics as "error(clang):". This
  630. // makes it more clear whether a message is coming from clang or cl.exe,
  631. // and it prevents MSBuild from concluding that the build failed just because
  632. // there is an "error:" in the output.
  633. if (CLFallbackMode)
  634. OS << "(clang)";
  635. OS << ": ";
  636. if (ShowColors)
  637. OS.resetColor();
  638. }
  639. /*static*/
  640. void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
  641. bool IsSupplemental,
  642. StringRef Message,
  643. unsigned CurrentColumn,
  644. unsigned Columns, bool ShowColors) {
  645. bool Bold = false;
  646. if (ShowColors && !IsSupplemental) {
  647. // Print primary diagnostic messages in bold and without color, to visually
  648. // indicate the transition from continuation notes and other output.
  649. OS.changeColor(savedColor, true);
  650. Bold = true;
  651. }
  652. if (Columns)
  653. printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
  654. else {
  655. bool Normal = true;
  656. applyTemplateHighlighting(OS, Message, Normal, Bold);
  657. assert(Normal && "Formatting should have returned to normal");
  658. }
  659. if (ShowColors)
  660. OS.resetColor();
  661. OS << '\n';
  662. }
  663. /// \brief Print out the file/line/column information and include trace.
  664. ///
  665. /// This method handlen the emission of the diagnostic location information.
  666. /// This includes extracting as much location information as is present for
  667. /// the diagnostic and printing it, as well as any include stack or source
  668. /// ranges necessary.
  669. void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
  670. DiagnosticsEngine::Level Level,
  671. ArrayRef<CharSourceRange> Ranges,
  672. const SourceManager &SM) {
  673. if (PLoc.isInvalid()) {
  674. // At least print the file name if available:
  675. FileID FID = SM.getFileID(Loc);
  676. if (!FID.isInvalid()) {
  677. const FileEntry* FE = SM.getFileEntryForID(FID);
  678. if (FE && FE->isValid()) {
  679. OS << FE->getName();
  680. if (FE->isInPCH())
  681. OS << " (in PCH)";
  682. OS << ": ";
  683. }
  684. }
  685. return;
  686. }
  687. unsigned LineNo = PLoc.getLine();
  688. if (!DiagOpts->ShowLocation)
  689. return;
  690. if (DiagOpts->ShowColors)
  691. OS.changeColor(savedColor, true);
  692. OS << PLoc.getFilename();
  693. switch (DiagOpts->getFormat()) {
  694. case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
  695. case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
  696. case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
  697. }
  698. if (DiagOpts->ShowColumn)
  699. // Compute the column number.
  700. if (unsigned ColNo = PLoc.getColumn()) {
  701. if (DiagOpts->getFormat() == DiagnosticOptions::Msvc) {
  702. OS << ',';
  703. // Visual Studio 2010 or earlier expects column number to be off by one
  704. if (LangOpts.MSCompatibilityVersion &&
  705. LangOpts.MSCompatibilityVersion < 170000000)
  706. ColNo--;
  707. } else
  708. OS << ':';
  709. OS << ColNo;
  710. }
  711. switch (DiagOpts->getFormat()) {
  712. case DiagnosticOptions::Clang:
  713. case DiagnosticOptions::Vi: OS << ':'; break;
  714. case DiagnosticOptions::Msvc: OS << ") : "; break;
  715. }
  716. if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
  717. FileID CaretFileID =
  718. SM.getFileID(SM.getExpansionLoc(Loc));
  719. bool PrintedRange = false;
  720. for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
  721. RE = Ranges.end();
  722. RI != RE; ++RI) {
  723. // Ignore invalid ranges.
  724. if (!RI->isValid()) continue;
  725. SourceLocation B = SM.getExpansionLoc(RI->getBegin());
  726. SourceLocation E = SM.getExpansionLoc(RI->getEnd());
  727. // If the End location and the start location are the same and are a
  728. // macro location, then the range was something that came from a
  729. // macro expansion or _Pragma. If this is an object-like macro, the
  730. // best we can do is to highlight the range. If this is a
  731. // function-like macro, we'd also like to highlight the arguments.
  732. if (B == E && RI->getEnd().isMacroID())
  733. E = SM.getExpansionRange(RI->getEnd()).second;
  734. std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
  735. std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
  736. // If the start or end of the range is in another file, just discard
  737. // it.
  738. if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
  739. continue;
  740. // Add in the length of the token, so that we cover multi-char
  741. // tokens.
  742. unsigned TokSize = 0;
  743. if (RI->isTokenRange())
  744. TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
  745. OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
  746. << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
  747. << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
  748. << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
  749. << '}';
  750. PrintedRange = true;
  751. }
  752. if (PrintedRange)
  753. OS << ':';
  754. }
  755. OS << ' ';
  756. }
  757. void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
  758. PresumedLoc PLoc,
  759. const SourceManager &SM) {
  760. if (DiagOpts->ShowLocation)
  761. OS << "In file included from " << PLoc.getFilename() << ':'
  762. << PLoc.getLine() << ":\n";
  763. else
  764. OS << "In included file:\n";
  765. }
  766. void TextDiagnostic::emitImportLocation(SourceLocation Loc, PresumedLoc PLoc,
  767. StringRef ModuleName,
  768. const SourceManager &SM) {
  769. if (DiagOpts->ShowLocation)
  770. OS << "In module '" << ModuleName << "' imported from "
  771. << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
  772. else
  773. OS << "In module " << ModuleName << "':\n";
  774. }
  775. void TextDiagnostic::emitBuildingModuleLocation(SourceLocation Loc,
  776. PresumedLoc PLoc,
  777. StringRef ModuleName,
  778. const SourceManager &SM) {
  779. if (DiagOpts->ShowLocation && PLoc.getFilename())
  780. OS << "While building module '" << ModuleName << "' imported from "
  781. << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
  782. else
  783. OS << "While building module '" << ModuleName << "':\n";
  784. }
  785. /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
  786. static void highlightRange(const CharSourceRange &R,
  787. unsigned LineNo, FileID FID,
  788. const SourceColumnMap &map,
  789. std::string &CaretLine,
  790. const SourceManager &SM,
  791. const LangOptions &LangOpts) {
  792. if (!R.isValid()) return;
  793. SourceLocation Begin = R.getBegin();
  794. SourceLocation End = R.getEnd();
  795. unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
  796. if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
  797. return; // No intersection.
  798. unsigned EndLineNo = SM.getExpansionLineNumber(End);
  799. if (EndLineNo < LineNo || SM.getFileID(End) != FID)
  800. return; // No intersection.
  801. // Compute the column number of the start.
  802. unsigned StartColNo = 0;
  803. if (StartLineNo == LineNo) {
  804. StartColNo = SM.getExpansionColumnNumber(Begin);
  805. if (StartColNo) --StartColNo; // Zero base the col #.
  806. }
  807. // Compute the column number of the end.
  808. unsigned EndColNo = map.getSourceLine().size();
  809. if (EndLineNo == LineNo) {
  810. EndColNo = SM.getExpansionColumnNumber(End);
  811. if (EndColNo) {
  812. --EndColNo; // Zero base the col #.
  813. // Add in the length of the token, so that we cover multi-char tokens if
  814. // this is a token range.
  815. if (R.isTokenRange())
  816. EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
  817. } else {
  818. EndColNo = CaretLine.size();
  819. }
  820. }
  821. assert(StartColNo <= EndColNo && "Invalid range!");
  822. // Check that a token range does not highlight only whitespace.
  823. if (R.isTokenRange()) {
  824. // Pick the first non-whitespace column.
  825. while (StartColNo < map.getSourceLine().size() &&
  826. (map.getSourceLine()[StartColNo] == ' ' ||
  827. map.getSourceLine()[StartColNo] == '\t'))
  828. StartColNo = map.startOfNextColumn(StartColNo);
  829. // Pick the last non-whitespace column.
  830. if (EndColNo > map.getSourceLine().size())
  831. EndColNo = map.getSourceLine().size();
  832. while (EndColNo &&
  833. (map.getSourceLine()[EndColNo-1] == ' ' ||
  834. map.getSourceLine()[EndColNo-1] == '\t'))
  835. EndColNo = map.startOfPreviousColumn(EndColNo);
  836. // If the start/end passed each other, then we are trying to highlight a
  837. // range that just exists in whitespace, which must be some sort of other
  838. // bug.
  839. assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
  840. }
  841. assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
  842. assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
  843. // Fill the range with ~'s.
  844. StartColNo = map.byteToContainingColumn(StartColNo);
  845. EndColNo = map.byteToContainingColumn(EndColNo);
  846. assert(StartColNo <= EndColNo && "Invalid range!");
  847. if (CaretLine.size() < EndColNo)
  848. CaretLine.resize(EndColNo,' ');
  849. std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
  850. }
  851. static std::string buildFixItInsertionLine(unsigned LineNo,
  852. const SourceColumnMap &map,
  853. ArrayRef<FixItHint> Hints,
  854. const SourceManager &SM,
  855. const DiagnosticOptions *DiagOpts) {
  856. std::string FixItInsertionLine;
  857. if (Hints.empty() || !DiagOpts->ShowFixits)
  858. return FixItInsertionLine;
  859. unsigned PrevHintEndCol = 0;
  860. for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
  861. I != E; ++I) {
  862. if (!I->CodeToInsert.empty()) {
  863. // We have an insertion hint. Determine whether the inserted
  864. // code contains no newlines and is on the same line as the caret.
  865. std::pair<FileID, unsigned> HintLocInfo
  866. = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
  867. if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
  868. StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
  869. // Insert the new code into the line just below the code
  870. // that the user wrote.
  871. // Note: When modifying this function, be very careful about what is a
  872. // "column" (printed width, platform-dependent) and what is a
  873. // "byte offset" (SourceManager "column").
  874. unsigned HintByteOffset
  875. = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
  876. // The hint must start inside the source or right at the end
  877. assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
  878. unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
  879. // If we inserted a long previous hint, push this one forwards, and add
  880. // an extra space to show that this is not part of the previous
  881. // completion. This is sort of the best we can do when two hints appear
  882. // to overlap.
  883. //
  884. // Note that if this hint is located immediately after the previous
  885. // hint, no space will be added, since the location is more important.
  886. if (HintCol < PrevHintEndCol)
  887. HintCol = PrevHintEndCol + 1;
  888. // This should NOT use HintByteOffset, because the source might have
  889. // Unicode characters in earlier columns.
  890. unsigned NewFixItLineSize = FixItInsertionLine.size() +
  891. (HintCol - PrevHintEndCol) + I->CodeToInsert.size();
  892. if (NewFixItLineSize > FixItInsertionLine.size())
  893. FixItInsertionLine.resize(NewFixItLineSize, ' ');
  894. std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
  895. FixItInsertionLine.end() - I->CodeToInsert.size());
  896. PrevHintEndCol =
  897. HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
  898. } else {
  899. FixItInsertionLine.clear();
  900. break;
  901. }
  902. }
  903. }
  904. expandTabs(FixItInsertionLine, DiagOpts->TabStop);
  905. return FixItInsertionLine;
  906. }
  907. /// \brief Emit a code snippet and caret line.
  908. ///
  909. /// This routine emits a single line's code snippet and caret line..
  910. ///
  911. /// \param Loc The location for the caret.
  912. /// \param Ranges The underlined ranges for this code snippet.
  913. /// \param Hints The FixIt hints active for this diagnostic.
  914. void TextDiagnostic::emitSnippetAndCaret(
  915. SourceLocation Loc, DiagnosticsEngine::Level Level,
  916. SmallVectorImpl<CharSourceRange>& Ranges,
  917. ArrayRef<FixItHint> Hints,
  918. const SourceManager &SM) {
  919. assert(!Loc.isInvalid() && "must have a valid source location here");
  920. assert(Loc.isFileID() && "must have a file location here");
  921. // If caret diagnostics are enabled and we have location, we want to
  922. // emit the caret. However, we only do this if the location moved
  923. // from the last diagnostic, if the last diagnostic was a note that
  924. // was part of a different warning or error diagnostic, or if the
  925. // diagnostic has ranges. We don't want to emit the same caret
  926. // multiple times if one loc has multiple diagnostics.
  927. if (!DiagOpts->ShowCarets)
  928. return;
  929. if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
  930. (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
  931. return;
  932. // Decompose the location into a FID/Offset pair.
  933. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
  934. FileID FID = LocInfo.first;
  935. unsigned FileOffset = LocInfo.second;
  936. // Get information about the buffer it points into.
  937. bool Invalid = false;
  938. const char *BufStart = SM.getBufferData(FID, &Invalid).data();
  939. if (Invalid)
  940. return;
  941. unsigned LineNo = SM.getLineNumber(FID, FileOffset);
  942. unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
  943. // Arbitrarily stop showing snippets when the line is too long.
  944. static const size_t MaxLineLengthToPrint = 4096;
  945. if (ColNo > MaxLineLengthToPrint)
  946. return;
  947. // Rewind from the current position to the start of the line.
  948. const char *TokPtr = BufStart+FileOffset;
  949. const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
  950. // Compute the line end. Scan forward from the error position to the end of
  951. // the line.
  952. const char *LineEnd = TokPtr;
  953. while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
  954. ++LineEnd;
  955. // Arbitrarily stop showing snippets when the line is too long.
  956. if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
  957. return;
  958. // Copy the line of code into an std::string for ease of manipulation.
  959. std::string SourceLine(LineStart, LineEnd);
  960. // Create a line for the caret that is filled with spaces that is the same
  961. // length as the line of source code.
  962. std::string CaretLine(LineEnd-LineStart, ' ');
  963. const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
  964. // Highlight all of the characters covered by Ranges with ~ characters.
  965. for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
  966. E = Ranges.end();
  967. I != E; ++I)
  968. highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
  969. // Next, insert the caret itself.
  970. ColNo = sourceColMap.byteToContainingColumn(ColNo-1);
  971. if (CaretLine.size()<ColNo+1)
  972. CaretLine.resize(ColNo+1, ' ');
  973. CaretLine[ColNo] = '^';
  974. std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
  975. sourceColMap,
  976. Hints, SM,
  977. DiagOpts.get());
  978. // If the source line is too long for our terminal, select only the
  979. // "interesting" source region within that line.
  980. unsigned Columns = DiagOpts->MessageLength;
  981. if (Columns)
  982. selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
  983. Columns, sourceColMap);
  984. // If we are in -fdiagnostics-print-source-range-info mode, we are trying
  985. // to produce easily machine parsable output. Add a space before the
  986. // source line and the caret to make it trivial to tell the main diagnostic
  987. // line from what the user is intended to see.
  988. if (DiagOpts->ShowSourceRanges) {
  989. SourceLine = ' ' + SourceLine;
  990. CaretLine = ' ' + CaretLine;
  991. }
  992. // Finally, remove any blank spaces from the end of CaretLine.
  993. while (CaretLine[CaretLine.size()-1] == ' ')
  994. CaretLine.erase(CaretLine.end()-1);
  995. // Emit what we have computed.
  996. emitSnippet(SourceLine);
  997. if (DiagOpts->ShowColors)
  998. OS.changeColor(caretColor, true);
  999. OS << CaretLine << '\n';
  1000. if (DiagOpts->ShowColors)
  1001. OS.resetColor();
  1002. if (!FixItInsertionLine.empty()) {
  1003. if (DiagOpts->ShowColors)
  1004. // Print fixit line in color
  1005. OS.changeColor(fixitColor, false);
  1006. if (DiagOpts->ShowSourceRanges)
  1007. OS << ' ';
  1008. OS << FixItInsertionLine << '\n';
  1009. if (DiagOpts->ShowColors)
  1010. OS.resetColor();
  1011. }
  1012. // Print out any parseable fixit information requested by the options.
  1013. emitParseableFixits(Hints, SM);
  1014. }
  1015. void TextDiagnostic::emitSnippet(StringRef line) {
  1016. if (line.empty())
  1017. return;
  1018. size_t i = 0;
  1019. std::string to_print;
  1020. bool print_reversed = false;
  1021. while (i<line.size()) {
  1022. std::pair<SmallString<16>,bool> res
  1023. = printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
  1024. bool was_printable = res.second;
  1025. if (DiagOpts->ShowColors && was_printable == print_reversed) {
  1026. if (print_reversed)
  1027. OS.reverseColor();
  1028. OS << to_print;
  1029. to_print.clear();
  1030. if (DiagOpts->ShowColors)
  1031. OS.resetColor();
  1032. }
  1033. print_reversed = !was_printable;
  1034. to_print += res.first.str();
  1035. }
  1036. if (print_reversed && DiagOpts->ShowColors)
  1037. OS.reverseColor();
  1038. OS << to_print;
  1039. if (print_reversed && DiagOpts->ShowColors)
  1040. OS.resetColor();
  1041. OS << '\n';
  1042. }
  1043. void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
  1044. const SourceManager &SM) {
  1045. if (!DiagOpts->ShowParseableFixits)
  1046. return;
  1047. // We follow FixItRewriter's example in not (yet) handling
  1048. // fix-its in macros.
  1049. for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
  1050. I != E; ++I) {
  1051. if (I->RemoveRange.isInvalid() ||
  1052. I->RemoveRange.getBegin().isMacroID() ||
  1053. I->RemoveRange.getEnd().isMacroID())
  1054. return;
  1055. }
  1056. for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
  1057. I != E; ++I) {
  1058. SourceLocation BLoc = I->RemoveRange.getBegin();
  1059. SourceLocation ELoc = I->RemoveRange.getEnd();
  1060. std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
  1061. std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
  1062. // Adjust for token ranges.
  1063. if (I->RemoveRange.isTokenRange())
  1064. EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
  1065. // We specifically do not do word-wrapping or tab-expansion here,
  1066. // because this is supposed to be easy to parse.
  1067. PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
  1068. if (PLoc.isInvalid())
  1069. break;
  1070. OS << "fix-it:\"";
  1071. OS.write_escaped(PLoc.getFilename());
  1072. OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
  1073. << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
  1074. << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
  1075. << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
  1076. << "}:\"";
  1077. OS.write_escaped(I->CodeToInsert);
  1078. OS << "\"\n";
  1079. }
  1080. }