TextDiagnostic.cpp 48 KB

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