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