TextDiagnostic.cpp 45 KB

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