TextDiagnostic.cpp 45 KB

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