TextDiagnostic.cpp 49 KB

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