TextDiagnostic.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. //===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
  2. //
  3. // 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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Frontend/TextDiagnostic.h"
  9. #include "clang/Basic/CharInfo.h"
  10. #include "clang/Basic/DiagnosticOptions.h"
  11. #include "clang/Basic/FileManager.h"
  12. #include "clang/Basic/SourceManager.h"
  13. #include "clang/Lex/Lexer.h"
  14. #include "llvm/ADT/SmallString.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/Support/ConvertUTF.h"
  17. #include "llvm/Support/ErrorHandling.h"
  18. #include "llvm/Support/Locale.h"
  19. #include "llvm/Support/Path.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #include <algorithm>
  22. using namespace clang;
  23. static const enum raw_ostream::Colors noteColor =
  24. raw_ostream::BLACK;
  25. static const enum raw_ostream::Colors remarkColor =
  26. raw_ostream::BLUE;
  27. static const enum raw_ostream::Colors fixitColor =
  28. raw_ostream::GREEN;
  29. static const enum raw_ostream::Colors caretColor =
  30. raw_ostream::GREEN;
  31. static const enum raw_ostream::Colors warningColor =
  32. raw_ostream::MAGENTA;
  33. static const enum raw_ostream::Colors templateColor =
  34. raw_ostream::CYAN;
  35. static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
  36. static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
  37. // Used for changing only the bold attribute.
  38. static const enum raw_ostream::Colors savedColor =
  39. raw_ostream::SAVEDCOLOR;
  40. /// Add highlights to differences in template strings.
  41. static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
  42. bool &Normal, bool Bold) {
  43. while (true) {
  44. size_t Pos = Str.find(ToggleHighlight);
  45. OS << Str.slice(0, Pos);
  46. if (Pos == StringRef::npos)
  47. break;
  48. Str = Str.substr(Pos + 1);
  49. if (Normal)
  50. OS.changeColor(templateColor, true);
  51. else {
  52. OS.resetColor();
  53. if (Bold)
  54. OS.changeColor(savedColor, true);
  55. }
  56. Normal = !Normal;
  57. }
  58. }
  59. /// Number of spaces to indent when word-wrapping.
  60. const unsigned WordWrapIndentation = 6;
  61. static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
  62. int bytes = 0;
  63. while (0<i) {
  64. if (SourceLine[--i]=='\t')
  65. break;
  66. ++bytes;
  67. }
  68. return bytes;
  69. }
  70. /// returns a printable representation of first item from input range
  71. ///
  72. /// This function returns a printable representation of the next item in a line
  73. /// of source. If the next byte begins a valid and printable character, that
  74. /// character is returned along with 'true'.
  75. ///
  76. /// Otherwise, if the next byte begins a valid, but unprintable character, a
  77. /// printable, escaped representation of the character is returned, along with
  78. /// 'false'. Otherwise a printable, escaped representation of the next byte
  79. /// is returned along with 'false'.
  80. ///
  81. /// \note The index is updated to be used with a subsequent call to
  82. /// printableTextForNextCharacter.
  83. ///
  84. /// \param SourceLine The line of source
  85. /// \param i Pointer to byte index,
  86. /// \param TabStop used to expand tabs
  87. /// \return pair(printable text, 'true' iff original text was printable)
  88. ///
  89. static std::pair<SmallString<16>, bool>
  90. printableTextForNextCharacter(StringRef SourceLine, size_t *i,
  91. unsigned TabStop) {
  92. assert(i && "i must not be null");
  93. assert(*i<SourceLine.size() && "must point to a valid index");
  94. if (SourceLine[*i]=='\t') {
  95. assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
  96. "Invalid -ftabstop value");
  97. unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
  98. unsigned NumSpaces = TabStop - col%TabStop;
  99. assert(0 < NumSpaces && NumSpaces <= TabStop
  100. && "Invalid computation of space amt");
  101. ++(*i);
  102. SmallString<16> expandedTab;
  103. expandedTab.assign(NumSpaces, ' ');
  104. return std::make_pair(expandedTab, true);
  105. }
  106. unsigned char const *begin, *end;
  107. begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
  108. end = begin + (SourceLine.size() - *i);
  109. if (llvm::isLegalUTF8Sequence(begin, end)) {
  110. llvm::UTF32 c;
  111. llvm::UTF32 *cptr = &c;
  112. unsigned char const *original_begin = begin;
  113. unsigned char const *cp_end =
  114. begin + llvm::getNumBytesForUTF8(SourceLine[*i]);
  115. llvm::ConversionResult res = llvm::ConvertUTF8toUTF32(
  116. &begin, cp_end, &cptr, cptr + 1, llvm::strictConversion);
  117. (void)res;
  118. assert(llvm::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 multiple 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. /// 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. /// 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. /// 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. /// 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_byteToColumn.size() - 1));
  265. while (byteToColumn(++N) == -1) {}
  266. return N;
  267. }
  268. /// 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_byteToColumn.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. /// 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 CaretColumns = CaretLine.size();
  291. unsigned FixItColumns = llvm::sys::locale::columnWidth(FixItInsertionLine);
  292. unsigned MaxColumns = std::max(static_cast<unsigned>(map.columns()),
  293. std::max(CaretColumns, FixItColumns));
  294. // if the number of columns is less than the desired number we're done
  295. if (MaxColumns <= Columns)
  296. return;
  297. // No special characters are allowed in CaretLine.
  298. assert(CaretLine.end() ==
  299. llvm::find_if(CaretLine, [](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 truncation, 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. /// 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. /// 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. /// 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. /// 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 TextDiagnostic::emitDiagnosticMessage(
  583. FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level,
  584. StringRef Message, ArrayRef<clang::CharSourceRange> Ranges,
  585. DiagOrStoredDiag D) {
  586. uint64_t StartOfLocationInfo = OS.tell();
  587. // Emit the location of this particular diagnostic.
  588. if (Loc.isValid())
  589. emitDiagnosticLoc(Loc, PLoc, Level, Ranges);
  590. if (DiagOpts->ShowColors)
  591. OS.resetColor();
  592. if (DiagOpts->ShowLevel)
  593. printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
  594. printDiagnosticMessage(OS,
  595. /*IsSupplemental*/ Level == DiagnosticsEngine::Note,
  596. Message, OS.tell() - StartOfLocationInfo,
  597. DiagOpts->MessageLength, DiagOpts->ShowColors);
  598. }
  599. /*static*/ void
  600. TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
  601. DiagnosticsEngine::Level Level,
  602. bool ShowColors) {
  603. if (ShowColors) {
  604. // Print diagnostic category in bold and color
  605. switch (Level) {
  606. case DiagnosticsEngine::Ignored:
  607. llvm_unreachable("Invalid diagnostic type");
  608. case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
  609. case DiagnosticsEngine::Remark: OS.changeColor(remarkColor, true); break;
  610. case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
  611. case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
  612. case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
  613. }
  614. }
  615. switch (Level) {
  616. case DiagnosticsEngine::Ignored:
  617. llvm_unreachable("Invalid diagnostic type");
  618. case DiagnosticsEngine::Note: OS << "note: "; break;
  619. case DiagnosticsEngine::Remark: OS << "remark: "; break;
  620. case DiagnosticsEngine::Warning: OS << "warning: "; break;
  621. case DiagnosticsEngine::Error: OS << "error: "; break;
  622. case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
  623. }
  624. if (ShowColors)
  625. OS.resetColor();
  626. }
  627. /*static*/
  628. void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
  629. bool IsSupplemental,
  630. StringRef Message,
  631. unsigned CurrentColumn,
  632. unsigned Columns, bool ShowColors) {
  633. bool Bold = false;
  634. if (ShowColors && !IsSupplemental) {
  635. // Print primary diagnostic messages in bold and without color, to visually
  636. // indicate the transition from continuation notes and other output.
  637. OS.changeColor(savedColor, true);
  638. Bold = true;
  639. }
  640. if (Columns)
  641. printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
  642. else {
  643. bool Normal = true;
  644. applyTemplateHighlighting(OS, Message, Normal, Bold);
  645. assert(Normal && "Formatting should have returned to normal");
  646. }
  647. if (ShowColors)
  648. OS.resetColor();
  649. OS << '\n';
  650. }
  651. void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
  652. #ifdef _WIN32
  653. SmallString<4096> TmpFilename;
  654. #endif
  655. if (DiagOpts->AbsolutePath) {
  656. auto File = SM.getFileManager().getFile(Filename);
  657. if (File) {
  658. // We want to print a simplified absolute path, i. e. without "dots".
  659. //
  660. // The hardest part here are the paths like "<part1>/<link>/../<part2>".
  661. // On Unix-like systems, we cannot just collapse "<link>/..", because
  662. // paths are resolved sequentially, and, thereby, the path
  663. // "<part1>/<part2>" may point to a different location. That is why
  664. // we use FileManager::getCanonicalName(), which expands all indirections
  665. // with llvm::sys::fs::real_path() and caches the result.
  666. //
  667. // On the other hand, it would be better to preserve as much of the
  668. // original path as possible, because that helps a user to recognize it.
  669. // real_path() expands all links, which sometimes too much. Luckily,
  670. // on Windows we can just use llvm::sys::path::remove_dots(), because,
  671. // on that system, both aforementioned paths point to the same place.
  672. #ifdef _WIN32
  673. TmpFilename = (*File)->getName();
  674. llvm::sys::fs::make_absolute(TmpFilename);
  675. llvm::sys::path::native(TmpFilename);
  676. llvm::sys::path::remove_dots(TmpFilename, /* remove_dot_dot */ true);
  677. Filename = StringRef(TmpFilename.data(), TmpFilename.size());
  678. #else
  679. Filename = SM.getFileManager().getCanonicalName(*File);
  680. #endif
  681. }
  682. }
  683. OS << Filename;
  684. }
  685. /// Print out the file/line/column information and include trace.
  686. ///
  687. /// This method handlen the emission of the diagnostic location information.
  688. /// This includes extracting as much location information as is present for
  689. /// the diagnostic and printing it, as well as any include stack or source
  690. /// ranges necessary.
  691. void TextDiagnostic::emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc,
  692. DiagnosticsEngine::Level Level,
  693. ArrayRef<CharSourceRange> Ranges) {
  694. if (PLoc.isInvalid()) {
  695. // At least print the file name if available:
  696. FileID FID = Loc.getFileID();
  697. if (FID.isValid()) {
  698. const FileEntry *FE = Loc.getFileEntry();
  699. if (FE && FE->isValid()) {
  700. emitFilename(FE->getName(), Loc.getManager());
  701. OS << ": ";
  702. }
  703. }
  704. return;
  705. }
  706. unsigned LineNo = PLoc.getLine();
  707. if (!DiagOpts->ShowLocation)
  708. return;
  709. if (DiagOpts->ShowColors)
  710. OS.changeColor(savedColor, true);
  711. emitFilename(PLoc.getFilename(), Loc.getManager());
  712. switch (DiagOpts->getFormat()) {
  713. case DiagnosticOptions::Clang:
  714. if (DiagOpts->ShowLine)
  715. OS << ':' << LineNo;
  716. break;
  717. case DiagnosticOptions::MSVC: OS << '(' << LineNo; break;
  718. case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
  719. }
  720. if (DiagOpts->ShowColumn)
  721. // Compute the column number.
  722. if (unsigned ColNo = PLoc.getColumn()) {
  723. if (DiagOpts->getFormat() == DiagnosticOptions::MSVC) {
  724. OS << ',';
  725. // Visual Studio 2010 or earlier expects column number to be off by one
  726. if (LangOpts.MSCompatibilityVersion &&
  727. !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2012))
  728. ColNo--;
  729. } else
  730. OS << ':';
  731. OS << ColNo;
  732. }
  733. switch (DiagOpts->getFormat()) {
  734. case DiagnosticOptions::Clang:
  735. case DiagnosticOptions::Vi: OS << ':'; break;
  736. case DiagnosticOptions::MSVC:
  737. // MSVC2013 and before print 'file(4) : error'. MSVC2015 gets rid of the
  738. // space and prints 'file(4): error'.
  739. OS << ')';
  740. if (LangOpts.MSCompatibilityVersion &&
  741. !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
  742. OS << ' ';
  743. OS << ':';
  744. break;
  745. }
  746. if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
  747. FileID CaretFileID = Loc.getExpansionLoc().getFileID();
  748. bool PrintedRange = false;
  749. for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
  750. RE = Ranges.end();
  751. RI != RE; ++RI) {
  752. // Ignore invalid ranges.
  753. if (!RI->isValid()) continue;
  754. auto &SM = Loc.getManager();
  755. SourceLocation B = SM.getExpansionLoc(RI->getBegin());
  756. CharSourceRange ERange = SM.getExpansionRange(RI->getEnd());
  757. SourceLocation E = ERange.getEnd();
  758. bool IsTokenRange = ERange.isTokenRange();
  759. std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
  760. std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
  761. // If the start or end of the range is in another file, just discard
  762. // it.
  763. if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
  764. continue;
  765. // Add in the length of the token, so that we cover multi-char
  766. // tokens.
  767. unsigned TokSize = 0;
  768. if (IsTokenRange)
  769. TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
  770. FullSourceLoc BF(B, SM), EF(E, SM);
  771. OS << '{'
  772. << BF.getLineNumber() << ':' << BF.getColumnNumber() << '-'
  773. << EF.getLineNumber() << ':' << (EF.getColumnNumber() + TokSize)
  774. << '}';
  775. PrintedRange = true;
  776. }
  777. if (PrintedRange)
  778. OS << ':';
  779. }
  780. OS << ' ';
  781. }
  782. void TextDiagnostic::emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) {
  783. if (DiagOpts->ShowLocation && PLoc.isValid())
  784. OS << "In file included from " << PLoc.getFilename() << ':'
  785. << PLoc.getLine() << ":\n";
  786. else
  787. OS << "In included file:\n";
  788. }
  789. void TextDiagnostic::emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc,
  790. StringRef ModuleName) {
  791. if (DiagOpts->ShowLocation && PLoc.isValid())
  792. OS << "In module '" << ModuleName << "' imported from "
  793. << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
  794. else
  795. OS << "In module '" << ModuleName << "':\n";
  796. }
  797. void TextDiagnostic::emitBuildingModuleLocation(FullSourceLoc Loc,
  798. PresumedLoc PLoc,
  799. StringRef ModuleName) {
  800. if (DiagOpts->ShowLocation && PLoc.isValid())
  801. OS << "While building module '" << ModuleName << "' imported from "
  802. << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
  803. else
  804. OS << "While building module '" << ModuleName << "':\n";
  805. }
  806. /// Find the suitable set of lines to show to include a set of ranges.
  807. static llvm::Optional<std::pair<unsigned, unsigned>>
  808. findLinesForRange(const CharSourceRange &R, FileID FID,
  809. const SourceManager &SM) {
  810. if (!R.isValid()) return None;
  811. SourceLocation Begin = R.getBegin();
  812. SourceLocation End = R.getEnd();
  813. if (SM.getFileID(Begin) != FID || SM.getFileID(End) != FID)
  814. return None;
  815. return std::make_pair(SM.getExpansionLineNumber(Begin),
  816. SM.getExpansionLineNumber(End));
  817. }
  818. /// Add as much of range B into range A as possible without exceeding a maximum
  819. /// size of MaxRange. Ranges are inclusive.
  820. static std::pair<unsigned, unsigned>
  821. maybeAddRange(std::pair<unsigned, unsigned> A, std::pair<unsigned, unsigned> B,
  822. unsigned MaxRange) {
  823. // If A is already the maximum size, we're done.
  824. unsigned Slack = MaxRange - (A.second - A.first + 1);
  825. if (Slack == 0)
  826. return A;
  827. // Easy case: merge succeeds within MaxRange.
  828. unsigned Min = std::min(A.first, B.first);
  829. unsigned Max = std::max(A.second, B.second);
  830. if (Max - Min + 1 <= MaxRange)
  831. return {Min, Max};
  832. // If we can't reach B from A within MaxRange, there's nothing to do.
  833. // Don't add lines to the range that contain nothing interesting.
  834. if ((B.first > A.first && B.first - A.first + 1 > MaxRange) ||
  835. (B.second < A.second && A.second - B.second + 1 > MaxRange))
  836. return A;
  837. // Otherwise, expand A towards B to produce a range of size MaxRange. We
  838. // attempt to expand by the same amount in both directions if B strictly
  839. // contains A.
  840. // Expand downwards by up to half the available amount, then upwards as
  841. // much as possible, then downwards as much as possible.
  842. A.second = std::min(A.second + (Slack + 1) / 2, Max);
  843. Slack = MaxRange - (A.second - A.first + 1);
  844. A.first = std::max(Min + Slack, A.first) - Slack;
  845. A.second = std::min(A.first + MaxRange - 1, Max);
  846. return A;
  847. }
  848. /// Highlight a SourceRange (with ~'s) for any characters on LineNo.
  849. static void highlightRange(const CharSourceRange &R,
  850. unsigned LineNo, FileID FID,
  851. const SourceColumnMap &map,
  852. std::string &CaretLine,
  853. const SourceManager &SM,
  854. const LangOptions &LangOpts) {
  855. if (!R.isValid()) return;
  856. SourceLocation Begin = R.getBegin();
  857. SourceLocation End = R.getEnd();
  858. unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
  859. if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
  860. return; // No intersection.
  861. unsigned EndLineNo = SM.getExpansionLineNumber(End);
  862. if (EndLineNo < LineNo || SM.getFileID(End) != FID)
  863. return; // No intersection.
  864. // Compute the column number of the start.
  865. unsigned StartColNo = 0;
  866. if (StartLineNo == LineNo) {
  867. StartColNo = SM.getExpansionColumnNumber(Begin);
  868. if (StartColNo) --StartColNo; // Zero base the col #.
  869. }
  870. // Compute the column number of the end.
  871. unsigned EndColNo = map.getSourceLine().size();
  872. if (EndLineNo == LineNo) {
  873. EndColNo = SM.getExpansionColumnNumber(End);
  874. if (EndColNo) {
  875. --EndColNo; // Zero base the col #.
  876. // Add in the length of the token, so that we cover multi-char tokens if
  877. // this is a token range.
  878. if (R.isTokenRange())
  879. EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
  880. } else {
  881. EndColNo = CaretLine.size();
  882. }
  883. }
  884. assert(StartColNo <= EndColNo && "Invalid range!");
  885. // Check that a token range does not highlight only whitespace.
  886. if (R.isTokenRange()) {
  887. // Pick the first non-whitespace column.
  888. while (StartColNo < map.getSourceLine().size() &&
  889. (map.getSourceLine()[StartColNo] == ' ' ||
  890. map.getSourceLine()[StartColNo] == '\t'))
  891. StartColNo = map.startOfNextColumn(StartColNo);
  892. // Pick the last non-whitespace column.
  893. if (EndColNo > map.getSourceLine().size())
  894. EndColNo = map.getSourceLine().size();
  895. while (EndColNo &&
  896. (map.getSourceLine()[EndColNo-1] == ' ' ||
  897. map.getSourceLine()[EndColNo-1] == '\t'))
  898. EndColNo = map.startOfPreviousColumn(EndColNo);
  899. // If the start/end passed each other, then we are trying to highlight a
  900. // range that just exists in whitespace. That most likely means we have
  901. // a multi-line highlighting range that covers a blank line.
  902. if (StartColNo > EndColNo) {
  903. assert(StartLineNo != EndLineNo && "trying to highlight whitespace");
  904. StartColNo = EndColNo;
  905. }
  906. }
  907. assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
  908. assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
  909. // Fill the range with ~'s.
  910. StartColNo = map.byteToContainingColumn(StartColNo);
  911. EndColNo = map.byteToContainingColumn(EndColNo);
  912. assert(StartColNo <= EndColNo && "Invalid range!");
  913. if (CaretLine.size() < EndColNo)
  914. CaretLine.resize(EndColNo,' ');
  915. std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
  916. }
  917. static std::string buildFixItInsertionLine(FileID FID,
  918. unsigned LineNo,
  919. const SourceColumnMap &map,
  920. ArrayRef<FixItHint> Hints,
  921. const SourceManager &SM,
  922. const DiagnosticOptions *DiagOpts) {
  923. std::string FixItInsertionLine;
  924. if (Hints.empty() || !DiagOpts->ShowFixits)
  925. return FixItInsertionLine;
  926. unsigned PrevHintEndCol = 0;
  927. for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
  928. I != E; ++I) {
  929. if (!I->CodeToInsert.empty()) {
  930. // We have an insertion hint. Determine whether the inserted
  931. // code contains no newlines and is on the same line as the caret.
  932. std::pair<FileID, unsigned> HintLocInfo
  933. = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
  934. if (FID == HintLocInfo.first &&
  935. LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
  936. StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
  937. // Insert the new code into the line just below the code
  938. // that the user wrote.
  939. // Note: When modifying this function, be very careful about what is a
  940. // "column" (printed width, platform-dependent) and what is a
  941. // "byte offset" (SourceManager "column").
  942. unsigned HintByteOffset
  943. = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
  944. // The hint must start inside the source or right at the end
  945. assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
  946. unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
  947. // If we inserted a long previous hint, push this one forwards, and add
  948. // an extra space to show that this is not part of the previous
  949. // completion. This is sort of the best we can do when two hints appear
  950. // to overlap.
  951. //
  952. // Note that if this hint is located immediately after the previous
  953. // hint, no space will be added, since the location is more important.
  954. if (HintCol < PrevHintEndCol)
  955. HintCol = PrevHintEndCol + 1;
  956. // This should NOT use HintByteOffset, because the source might have
  957. // Unicode characters in earlier columns.
  958. unsigned NewFixItLineSize = FixItInsertionLine.size() +
  959. (HintCol - PrevHintEndCol) + I->CodeToInsert.size();
  960. if (NewFixItLineSize > FixItInsertionLine.size())
  961. FixItInsertionLine.resize(NewFixItLineSize, ' ');
  962. std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
  963. FixItInsertionLine.end() - I->CodeToInsert.size());
  964. PrevHintEndCol =
  965. HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
  966. }
  967. }
  968. }
  969. expandTabs(FixItInsertionLine, DiagOpts->TabStop);
  970. return FixItInsertionLine;
  971. }
  972. /// Emit a code snippet and caret line.
  973. ///
  974. /// This routine emits a single line's code snippet and caret line..
  975. ///
  976. /// \param Loc The location for the caret.
  977. /// \param Ranges The underlined ranges for this code snippet.
  978. /// \param Hints The FixIt hints active for this diagnostic.
  979. void TextDiagnostic::emitSnippetAndCaret(
  980. FullSourceLoc Loc, DiagnosticsEngine::Level Level,
  981. SmallVectorImpl<CharSourceRange> &Ranges, ArrayRef<FixItHint> Hints) {
  982. assert(Loc.isValid() && "must have a valid source location here");
  983. assert(Loc.isFileID() && "must have a file location here");
  984. // If caret diagnostics are enabled and we have location, we want to
  985. // emit the caret. However, we only do this if the location moved
  986. // from the last diagnostic, if the last diagnostic was a note that
  987. // was part of a different warning or error diagnostic, or if the
  988. // diagnostic has ranges. We don't want to emit the same caret
  989. // multiple times if one loc has multiple diagnostics.
  990. if (!DiagOpts->ShowCarets)
  991. return;
  992. if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
  993. (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
  994. return;
  995. // Decompose the location into a FID/Offset pair.
  996. std::pair<FileID, unsigned> LocInfo = Loc.getDecomposedLoc();
  997. FileID FID = LocInfo.first;
  998. const SourceManager &SM = Loc.getManager();
  999. // Get information about the buffer it points into.
  1000. bool Invalid = false;
  1001. StringRef BufData = Loc.getBufferData(&Invalid);
  1002. if (Invalid)
  1003. return;
  1004. unsigned CaretLineNo = Loc.getLineNumber();
  1005. unsigned CaretColNo = Loc.getColumnNumber();
  1006. // Arbitrarily stop showing snippets when the line is too long.
  1007. static const size_t MaxLineLengthToPrint = 4096;
  1008. if (CaretColNo > MaxLineLengthToPrint)
  1009. return;
  1010. // Find the set of lines to include.
  1011. const unsigned MaxLines = DiagOpts->SnippetLineLimit;
  1012. std::pair<unsigned, unsigned> Lines = {CaretLineNo, CaretLineNo};
  1013. for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
  1014. E = Ranges.end();
  1015. I != E; ++I)
  1016. if (auto OptionalRange = findLinesForRange(*I, FID, SM))
  1017. Lines = maybeAddRange(Lines, *OptionalRange, MaxLines);
  1018. for (unsigned LineNo = Lines.first; LineNo != Lines.second + 1; ++LineNo) {
  1019. const char *BufStart = BufData.data();
  1020. const char *BufEnd = BufStart + BufData.size();
  1021. // Rewind from the current position to the start of the line.
  1022. const char *LineStart =
  1023. BufStart +
  1024. SM.getDecomposedLoc(SM.translateLineCol(FID, LineNo, 1)).second;
  1025. if (LineStart == BufEnd)
  1026. break;
  1027. // Compute the line end.
  1028. const char *LineEnd = LineStart;
  1029. while (*LineEnd != '\n' && *LineEnd != '\r' && LineEnd != BufEnd)
  1030. ++LineEnd;
  1031. // Arbitrarily stop showing snippets when the line is too long.
  1032. // FIXME: Don't print any lines in this case.
  1033. if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
  1034. return;
  1035. // Trim trailing null-bytes.
  1036. StringRef Line(LineStart, LineEnd - LineStart);
  1037. while (!Line.empty() && Line.back() == '\0' &&
  1038. (LineNo != CaretLineNo || Line.size() > CaretColNo))
  1039. Line = Line.drop_back();
  1040. // Copy the line of code into an std::string for ease of manipulation.
  1041. std::string SourceLine(Line.begin(), Line.end());
  1042. // Build the byte to column map.
  1043. const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
  1044. // Create a line for the caret that is filled with spaces that is the same
  1045. // number of columns as the line of source code.
  1046. std::string CaretLine(sourceColMap.columns(), ' ');
  1047. // Highlight all of the characters covered by Ranges with ~ characters.
  1048. for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
  1049. E = Ranges.end();
  1050. I != E; ++I)
  1051. highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
  1052. // Next, insert the caret itself.
  1053. if (CaretLineNo == LineNo) {
  1054. CaretColNo = sourceColMap.byteToContainingColumn(CaretColNo - 1);
  1055. if (CaretLine.size() < CaretColNo + 1)
  1056. CaretLine.resize(CaretColNo + 1, ' ');
  1057. CaretLine[CaretColNo] = '^';
  1058. }
  1059. std::string FixItInsertionLine = buildFixItInsertionLine(
  1060. FID, LineNo, sourceColMap, Hints, SM, DiagOpts.get());
  1061. // If the source line is too long for our terminal, select only the
  1062. // "interesting" source region within that line.
  1063. unsigned Columns = DiagOpts->MessageLength;
  1064. if (Columns)
  1065. selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
  1066. Columns, sourceColMap);
  1067. // If we are in -fdiagnostics-print-source-range-info mode, we are trying
  1068. // to produce easily machine parsable output. Add a space before the
  1069. // source line and the caret to make it trivial to tell the main diagnostic
  1070. // line from what the user is intended to see.
  1071. if (DiagOpts->ShowSourceRanges) {
  1072. SourceLine = ' ' + SourceLine;
  1073. CaretLine = ' ' + CaretLine;
  1074. }
  1075. // Finally, remove any blank spaces from the end of CaretLine.
  1076. while (!CaretLine.empty() && CaretLine[CaretLine.size() - 1] == ' ')
  1077. CaretLine.erase(CaretLine.end() - 1);
  1078. // Emit what we have computed.
  1079. emitSnippet(SourceLine);
  1080. if (!CaretLine.empty()) {
  1081. if (DiagOpts->ShowColors)
  1082. OS.changeColor(caretColor, true);
  1083. OS << CaretLine << '\n';
  1084. if (DiagOpts->ShowColors)
  1085. OS.resetColor();
  1086. }
  1087. if (!FixItInsertionLine.empty()) {
  1088. if (DiagOpts->ShowColors)
  1089. // Print fixit line in color
  1090. OS.changeColor(fixitColor, false);
  1091. if (DiagOpts->ShowSourceRanges)
  1092. OS << ' ';
  1093. OS << FixItInsertionLine << '\n';
  1094. if (DiagOpts->ShowColors)
  1095. OS.resetColor();
  1096. }
  1097. }
  1098. // Print out any parseable fixit information requested by the options.
  1099. emitParseableFixits(Hints, SM);
  1100. }
  1101. void TextDiagnostic::emitSnippet(StringRef line) {
  1102. if (line.empty())
  1103. return;
  1104. size_t i = 0;
  1105. std::string to_print;
  1106. bool print_reversed = false;
  1107. while (i<line.size()) {
  1108. std::pair<SmallString<16>,bool> res
  1109. = printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
  1110. bool was_printable = res.second;
  1111. if (DiagOpts->ShowColors && was_printable == print_reversed) {
  1112. if (print_reversed)
  1113. OS.reverseColor();
  1114. OS << to_print;
  1115. to_print.clear();
  1116. if (DiagOpts->ShowColors)
  1117. OS.resetColor();
  1118. }
  1119. print_reversed = !was_printable;
  1120. to_print += res.first.str();
  1121. }
  1122. if (print_reversed && DiagOpts->ShowColors)
  1123. OS.reverseColor();
  1124. OS << to_print;
  1125. if (print_reversed && DiagOpts->ShowColors)
  1126. OS.resetColor();
  1127. OS << '\n';
  1128. }
  1129. void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
  1130. const SourceManager &SM) {
  1131. if (!DiagOpts->ShowParseableFixits)
  1132. return;
  1133. // We follow FixItRewriter's example in not (yet) handling
  1134. // fix-its in macros.
  1135. for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
  1136. I != E; ++I) {
  1137. if (I->RemoveRange.isInvalid() ||
  1138. I->RemoveRange.getBegin().isMacroID() ||
  1139. I->RemoveRange.getEnd().isMacroID())
  1140. return;
  1141. }
  1142. for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
  1143. I != E; ++I) {
  1144. SourceLocation BLoc = I->RemoveRange.getBegin();
  1145. SourceLocation ELoc = I->RemoveRange.getEnd();
  1146. std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
  1147. std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
  1148. // Adjust for token ranges.
  1149. if (I->RemoveRange.isTokenRange())
  1150. EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
  1151. // We specifically do not do word-wrapping or tab-expansion here,
  1152. // because this is supposed to be easy to parse.
  1153. PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
  1154. if (PLoc.isInvalid())
  1155. break;
  1156. OS << "fix-it:\"";
  1157. OS.write_escaped(PLoc.getFilename());
  1158. OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
  1159. << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
  1160. << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
  1161. << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
  1162. << "}:\"";
  1163. OS.write_escaped(I->CodeToInsert);
  1164. OS << "\"\n";
  1165. }
  1166. }