TextDiagnostic.cpp 49 KB

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