LCOV - code coverage report
Current view: top level - lib/Support - SourceMgr.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 200 221 90.5 %
Date: 2017-09-14 15:23:50 Functions: 14 14 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- SourceMgr.cpp - Manager for Simple Source Buffers & Diagnostics ----===//
       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             : // This file implements the SourceMgr class.  This class is used as a simple
      11             : // substrate for diagnostics, #include handling, and other low level things for
      12             : // simple parsers.
      13             : //
      14             : //===----------------------------------------------------------------------===//
      15             : 
      16             : #include "llvm/Support/SourceMgr.h"
      17             : #include "llvm/ADT/ArrayRef.h"
      18             : #include "llvm/ADT/STLExtras.h"
      19             : #include "llvm/ADT/SmallVector.h"
      20             : #include "llvm/ADT/StringRef.h"
      21             : #include "llvm/ADT/Twine.h"
      22             : #include "llvm/Support/ErrorOr.h"
      23             : #include "llvm/Support/Locale.h"
      24             : #include "llvm/Support/MemoryBuffer.h"
      25             : #include "llvm/Support/Path.h"
      26             : #include "llvm/Support/SMLoc.h"
      27             : #include "llvm/Support/raw_ostream.h"
      28             : #include <algorithm>
      29             : #include <cassert>
      30             : #include <cstddef>
      31             : #include <memory>
      32             : #include <string>
      33             : #include <utility>
      34             : 
      35             : using namespace llvm;
      36             : 
      37             : static const size_t TabStop = 8;
      38             : 
      39             : namespace {
      40             : 
      41             :   struct LineNoCacheTy {
      42             :     const char *LastQuery;
      43             :     unsigned LastQueryBufferID;
      44             :     unsigned LineNoOfQuery;
      45             :   };
      46             : 
      47             : } // end anonymous namespace
      48             : 
      49             : static LineNoCacheTy *getCache(void *Ptr) {
      50             :   return (LineNoCacheTy*)Ptr;
      51             : }
      52             : 
      53      174906 : SourceMgr::~SourceMgr() {
      54       87453 :   delete getCache(LineNoCache);
      55       87453 : }
      56             : 
      57        6405 : unsigned SourceMgr::AddIncludeFile(const std::string &Filename,
      58             :                                    SMLoc IncludeLoc,
      59             :                                    std::string &IncludedFile) {
      60        6405 :   IncludedFile = Filename;
      61             :   ErrorOr<std::unique_ptr<MemoryBuffer>> NewBufOrErr =
      62       12810 :     MemoryBuffer::getFile(IncludedFile);
      63             : 
      64             :   // If the file didn't exist directly, see if it's in an include path.
      65       38225 :   for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBufOrErr;
      66             :        ++i) {
      67        9656 :     IncludedFile =
      68       48280 :         IncludeDirectories[i] + sys::path::get_separator().data() + Filename;
      69       28968 :     NewBufOrErr = MemoryBuffer::getFile(IncludedFile);
      70             :   }
      71             : 
      72        6405 :   if (!NewBufOrErr)
      73             :     return 0;
      74             : 
      75       19215 :   return AddNewSourceBuffer(std::move(*NewBufOrErr), IncludeLoc);
      76             : }
      77             : 
      78      145372 : unsigned SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
      79      389786 :   for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
      80      763063 :     if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
      81             :         // Use <= here so that a pointer to the null at the end of the buffer
      82             :         // is included as part of the buffer.
      83      257942 :         Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
      84      112322 :       return i + 1;
      85             :   return 0;
      86             : }
      87             : 
      88             : std::pair<unsigned, unsigned>
      89       36801 : SourceMgr::getLineAndColumn(SMLoc Loc, unsigned BufferID) const {
      90       36801 :   if (!BufferID)
      91          92 :     BufferID = FindBufferContainingLoc(Loc);
      92             :   assert(BufferID && "Invalid Location!");
      93             : 
      94       36801 :   const MemoryBuffer *Buff = getMemoryBuffer(BufferID);
      95             : 
      96             :   // Count the number of \n's between the start of the file and the specified
      97             :   // location.
      98       36801 :   unsigned LineNo = 1;
      99             : 
     100       36801 :   const char *BufStart = Buff->getBufferStart();
     101       36801 :   const char *Ptr = BufStart;
     102             : 
     103             :   // If we have a line number cache, and if the query is to a later point in the
     104             :   // same file, start searching from the last query location.  This optimizes
     105             :   // for the case when multiple diagnostics come out of one file in order.
     106       36801 :   if (LineNoCacheTy *Cache = getCache(LineNoCache))
     107       69402 :     if (Cache->LastQueryBufferID == BufferID &&
     108       34484 :         Cache->LastQuery <= Loc.getPointer()) {
     109       34295 :       Ptr = Cache->LastQuery;
     110       34295 :       LineNo = Cache->LineNoOfQuery;
     111             :     }
     112             : 
     113             :   // Scan for the location being queried, keeping track of the number of lines
     114             :   // we see.
     115    18085105 :   for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
     116     9024152 :     if (*Ptr == '\n') ++LineNo;
     117             : 
     118             :   // Allocate the line number cache if it doesn't exist.
     119       36801 :   if (!LineNoCache)
     120        1883 :     LineNoCache = new LineNoCacheTy();
     121             : 
     122             :   // Update the line # cache.
     123       36801 :   LineNoCacheTy &Cache = *getCache(LineNoCache);
     124       36801 :   Cache.LastQueryBufferID = BufferID;
     125       36801 :   Cache.LastQuery = Ptr;
     126       36801 :   Cache.LineNoOfQuery = LineNo;
     127             :   
     128      110403 :   size_t NewlineOffs = StringRef(BufStart, Ptr-BufStart).find_last_of("\n\r");
     129       36801 :   if (NewlineOffs == StringRef::npos) NewlineOffs = ~(size_t)0;
     130      110403 :   return std::make_pair(LineNo, Ptr-BufStart-NewlineOffs);
     131             : }
     132             : 
     133        3222 : void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
     134        6444 :   if (IncludeLoc == SMLoc()) return;  // Top of stack.
     135             : 
     136           0 :   unsigned CurBuf = FindBufferContainingLoc(IncludeLoc);
     137             :   assert(CurBuf && "Invalid or unspecified location!");
     138             : 
     139           0 :   PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
     140             : 
     141           0 :   OS << "Included from "
     142           0 :      << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
     143           0 :      << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
     144             : }
     145             : 
     146       36590 : SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
     147             :                                    const Twine &Msg,
     148             :                                    ArrayRef<SMRange> Ranges,
     149             :                                    ArrayRef<SMFixIt> FixIts) const {
     150             :   // First thing to do: find the current buffer containing the specified
     151             :   // location to pull out the source line.
     152       73180 :   SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
     153       36590 :   std::pair<unsigned, unsigned> LineAndCol;
     154       36590 :   StringRef BufferID = "<unknown>";
     155       73180 :   std::string LineStr;
     156             :   
     157       36590 :   if (Loc.isValid()) {
     158       36527 :     unsigned CurBuf = FindBufferContainingLoc(Loc);
     159             :     assert(CurBuf && "Invalid or unspecified location!");
     160             : 
     161       36527 :     const MemoryBuffer *CurMB = getMemoryBuffer(CurBuf);
     162       36527 :     BufferID = CurMB->getBufferIdentifier();
     163             :     
     164             :     // Scan backward to find the start of the line.
     165       36527 :     const char *LineStart = Loc.getPointer();
     166       36527 :     const char *BufStart = CurMB->getBufferStart();
     167      920405 :     while (LineStart != BufStart && LineStart[-1] != '\n' &&
     168             :            LineStart[-1] != '\r')
     169      441939 :       --LineStart;
     170             : 
     171             :     // Get the end of the line.
     172       36527 :     const char *LineEnd = Loc.getPointer();
     173       36527 :     const char *BufEnd = CurMB->getBufferEnd();
     174     1931673 :     while (LineEnd != BufEnd && LineEnd[0] != '\n' && LineEnd[0] != '\r')
     175      947573 :       ++LineEnd;
     176      146108 :     LineStr = std::string(LineStart, LineEnd);
     177             : 
     178             :     // Convert any ranges to column ranges that only intersect the line of the
     179             :     // location.
     180       69282 :     for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
     181       65510 :       SMRange R = Ranges[i];
     182       32755 :       if (!R.isValid()) continue;
     183             :       
     184             :       // If the line doesn't contain any part of the range, then ignore it.
     185         347 :       if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
     186           0 :         continue;
     187             :      
     188             :       // Ignore pieces of the range that go onto other lines.
     189         347 :       if (R.Start.getPointer() < LineStart)
     190           0 :         R.Start = SMLoc::getFromPointer(LineStart);
     191         347 :       if (R.End.getPointer() > LineEnd)
     192          10 :         R.End = SMLoc::getFromPointer(LineEnd);
     193             :       
     194             :       // Translate from SMLoc ranges to column ranges.
     195             :       // FIXME: Handle multibyte characters.
     196        1041 :       ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart,
     197         347 :                                          R.End.getPointer()-LineStart));
     198             :     }
     199             : 
     200       73054 :     LineAndCol = getLineAndColumn(Loc, CurBuf);
     201             :   }
     202             :     
     203             :   return SMDiagnostic(*this, Loc, BufferID, LineAndCol.first,
     204      109770 :                       LineAndCol.second-1, Kind, Msg.str(),
     205      219540 :                       LineStr, ColRanges, FixIts);
     206             : }
     207             : 
     208       36280 : void SourceMgr::PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
     209             :                              bool ShowColors) const {
     210             :   // Report the message with the diagnostic handler if present.
     211       36280 :   if (DiagHandler) {
     212       33095 :     DiagHandler(Diagnostic, DiagContext);
     213       33095 :     return;
     214             :   }
     215             : 
     216        3185 :   if (Diagnostic.getLoc().isValid()) {
     217        3185 :     unsigned CurBuf = FindBufferContainingLoc(Diagnostic.getLoc());
     218             :     assert(CurBuf && "Invalid or unspecified location!");
     219        3185 :     PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
     220             :   }
     221             : 
     222        3185 :   Diagnostic.print(nullptr, OS, ShowColors);
     223             : }
     224             : 
     225       36280 : void SourceMgr::PrintMessage(raw_ostream &OS, SMLoc Loc,
     226             :                              SourceMgr::DiagKind Kind,
     227             :                              const Twine &Msg, ArrayRef<SMRange> Ranges,
     228             :                              ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
     229       36280 :   PrintMessage(OS, GetMessage(Loc, Kind, Msg, Ranges, FixIts), ShowColors);
     230       36280 : }
     231             : 
     232       36268 : void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
     233             :                              const Twine &Msg, ArrayRef<SMRange> Ranges,
     234             :                              ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
     235       36268 :   PrintMessage(errs(), Loc, Kind, Msg, Ranges, FixIts, ShowColors);
     236       36268 : }
     237             : 
     238             : //===----------------------------------------------------------------------===//
     239             : // SMDiagnostic Implementation
     240             : //===----------------------------------------------------------------------===//
     241             : 
     242       36725 : SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN,
     243             :                            int Line, int Col, SourceMgr::DiagKind Kind,
     244             :                            StringRef Msg, StringRef LineStr,
     245             :                            ArrayRef<std::pair<unsigned,unsigned>> Ranges,
     246       36725 :                            ArrayRef<SMFixIt> Hints)
     247             :   : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Kind(Kind),
     248             :     Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()),
     249      257075 :     FixIts(Hints.begin(), Hints.end()) {
     250      146900 :   std::sort(FixIts.begin(), FixIts.end());
     251       36725 : }
     252             : 
     253       36438 : static void buildFixItLine(std::string &CaretLine, std::string &FixItLine,
     254             :                            ArrayRef<SMFixIt> FixIts, ArrayRef<char> SourceLine){
     255       36438 :   if (FixIts.empty())
     256             :     return;
     257             : 
     258          29 :   const char *LineStart = SourceLine.begin();
     259          29 :   const char *LineEnd = SourceLine.end();
     260             : 
     261          29 :   size_t PrevHintEndCol = 0;
     262             : 
     263          87 :   for (ArrayRef<SMFixIt>::iterator I = FixIts.begin(), E = FixIts.end();
     264          58 :        I != E; ++I) {
     265             :     // If the fixit contains a newline or tab, ignore it.
     266          58 :     if (I->getText().find_first_of("\n\r\t") != StringRef::npos)
     267           0 :       continue;
     268             : 
     269          29 :     SMRange R = I->getRange();
     270             : 
     271             :     // If the line doesn't contain any part of the range, then ignore it.
     272          29 :     if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
     273           0 :       continue;
     274             : 
     275             :     // Translate from SMLoc to column.
     276             :     // Ignore pieces of the range that go onto other lines.
     277             :     // FIXME: Handle multibyte characters in the source line.
     278             :     unsigned FirstCol;
     279          29 :     if (R.Start.getPointer() < LineStart)
     280             :       FirstCol = 0;
     281             :     else
     282          28 :       FirstCol = R.Start.getPointer() - LineStart;
     283             : 
     284             :     // If we inserted a long previous hint, push this one forwards, and add
     285             :     // an extra space to show that this is not part of the previous
     286             :     // completion. This is sort of the best we can do when two hints appear
     287             :     // to overlap.
     288             :     //
     289             :     // Note that if this hint is located immediately after the previous
     290             :     // hint, no space will be added, since the location is more important.
     291          29 :     unsigned HintCol = FirstCol;
     292          29 :     if (HintCol < PrevHintEndCol)
     293           0 :       HintCol = PrevHintEndCol + 1;
     294             : 
     295             :     // FIXME: This assertion is intended to catch unintended use of multibyte
     296             :     // characters in fixits. If we decide to do this, we'll have to track
     297             :     // separate byte widths for the source and fixit lines.
     298             :     assert((size_t)sys::locale::columnWidth(I->getText()) ==
     299             :            I->getText().size());
     300             : 
     301             :     // This relies on one byte per column in our fixit hints.
     302          29 :     unsigned LastColumnModified = HintCol + I->getText().size();
     303          29 :     if (LastColumnModified > FixItLine.size())
     304          29 :       FixItLine.resize(LastColumnModified, ' ');
     305             : 
     306          87 :     std::copy(I->getText().begin(), I->getText().end(),
     307         145 :               FixItLine.begin() + HintCol);
     308             : 
     309          29 :     PrevHintEndCol = LastColumnModified;
     310             : 
     311             :     // For replacements, mark the removal range with '~'.
     312             :     // FIXME: Handle multibyte characters in the source line.
     313             :     unsigned LastCol;
     314          29 :     if (R.End.getPointer() >= LineEnd)
     315           2 :       LastCol = LineEnd - LineStart;
     316             :     else
     317          27 :       LastCol = R.End.getPointer() - LineStart;
     318             : 
     319          87 :     std::fill(&CaretLine[FirstCol], &CaretLine[LastCol], '~');
     320             :   }
     321             : }
     322             : 
     323       36442 : static void printSourceLine(raw_ostream &S, StringRef LineContents) {
     324             :   // Print out the source line one character at a time, so we can expand tabs.
     325     1459668 :   for (unsigned i = 0, e = LineContents.size(), OutCol = 0; i != e; ++i) {
     326     4139623 :     if (LineContents[i] != '\t') {
     327     2732110 :       S << LineContents[i];
     328     1366055 :       ++OutCol;
     329     1366055 :       continue;
     330             :     }
     331             : 
     332             :     // If we have a tab, emit at least one space, then round up to 8 columns.
     333             :     do {
     334      121342 :       S << ' ';
     335      121342 :       ++OutCol;
     336      121342 :     } while ((OutCol % TabStop) != 0);
     337             :   }
     338       36442 :   S << '\n';
     339       36442 : }
     340             : 
     341     1386399 : static bool isNonASCII(char c) {
     342     1386399 :   return c & 0x80;
     343             : }
     344             : 
     345       36510 : void SMDiagnostic::print(const char *ProgName, raw_ostream &S, bool ShowColors,
     346             :                          bool ShowKindLabel) const {
     347             :   // Display colors only if OS supports colors.
     348       36510 :   ShowColors &= S.has_colors();
     349             : 
     350       36510 :   if (ShowColors)
     351           0 :     S.changeColor(raw_ostream::SAVEDCOLOR, true);
     352             : 
     353       36510 :   if (ProgName && ProgName[0])
     354         193 :     S << ProgName << ": ";
     355             : 
     356       73020 :   if (!Filename.empty()) {
     357       72912 :     if (Filename == "-")
     358           0 :       S << "<stdin>";
     359             :     else
     360       36456 :       S << Filename;
     361             : 
     362       36456 :     if (LineNo != -1) {
     363       72902 :       S << ':' << LineNo;
     364       36451 :       if (ColumnNo != -1)
     365       36388 :         S << ':' << (ColumnNo+1);
     366             :     }
     367       36456 :     S << ": ";
     368             :   }
     369             : 
     370       36510 :   if (ShowKindLabel) {
     371       36398 :     switch (Kind) {
     372       30504 :     case SourceMgr::DK_Error:
     373       30504 :       if (ShowColors)
     374           0 :         S.changeColor(raw_ostream::RED, true);
     375       30504 :       S << "error: ";
     376       30504 :       break;
     377        5312 :     case SourceMgr::DK_Warning:
     378        5312 :       if (ShowColors)
     379           0 :         S.changeColor(raw_ostream::MAGENTA, true);
     380        5312 :       S << "warning: ";
     381        5312 :       break;
     382         582 :     case SourceMgr::DK_Note:
     383         582 :       if (ShowColors)
     384           0 :         S.changeColor(raw_ostream::BLACK, true);
     385         582 :       S << "note: ";
     386         582 :       break;
     387             :     }
     388             : 
     389       36398 :     if (ShowColors) {
     390           0 :       S.resetColor();
     391           0 :       S.changeColor(raw_ostream::SAVEDCOLOR, true);
     392             :     }
     393             :   }
     394             : 
     395      109530 :   S << Message << '\n';
     396             : 
     397       36510 :   if (ShowColors)
     398           0 :     S.resetColor();
     399             : 
     400       36510 :   if (LineNo == -1 || ColumnNo == -1)
     401       36481 :     return;
     402             : 
     403             :   // FIXME: If there are multibyte or multi-column characters in the source, all
     404             :   // our ranges will be wrong. To do this properly, we'll need a byte-to-column
     405             :   // map like Clang's TextDiagnostic. For now, we'll just handle tabs by
     406             :   // expanding them later, and bail out rather than show incorrect ranges and
     407             :   // misaligned fixits for any other odd characters.
     408      145768 :   if (find_if(LineContents, isNonASCII) != LineContents.end()) {
     409           8 :     printSourceLine(S, LineContents);
     410           4 :     return;
     411             :   }
     412       36438 :   size_t NumColumns = LineContents.size();
     413             : 
     414             :   // Build the line with the caret and ranges.
     415      109343 :   std::string CaretLine(NumColumns+1, ' ');
     416             :   
     417             :   // Expand any ranges.
     418       73155 :   for (unsigned r = 0, e = Ranges.size(); r != e; ++r) {
     419         558 :     std::pair<unsigned, unsigned> R = Ranges[r];
     420         837 :     std::fill(&CaretLine[R.first],
     421        1116 :               &CaretLine[std::min((size_t)R.second, CaretLine.size())],
     422             :               '~');
     423             :   }
     424             : 
     425             :   // Add any fix-its.
     426             :   // FIXME: Find the beginning of the line properly for multibyte characters.
     427       36467 :   std::string FixItInsertionLine;
     428      145752 :   buildFixItLine(CaretLine, FixItInsertionLine, FixIts,
     429       72876 :                  makeArrayRef(Loc.getPointer() - ColumnNo,
     430             :                               LineContents.size()));
     431             : 
     432             :   // Finally, plop on the caret.
     433       36438 :   if (unsigned(ColumnNo) <= NumColumns)
     434       72876 :     CaretLine[ColumnNo] = '^';
     435             :   else 
     436           0 :     CaretLine[NumColumns] = '^';
     437             :   
     438             :   // ... and remove trailing whitespace so the output doesn't wrap for it.  We
     439             :   // know that the line isn't completely empty because it has the caret in it at
     440             :   // least.
     441       36438 :   CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
     442             :   
     443       72876 :   printSourceLine(S, LineContents);
     444             : 
     445       36438 :   if (ShowColors)
     446           0 :     S.changeColor(raw_ostream::GREEN, true);
     447             : 
     448             :   // Print out the caret line, matching tabs in the source line.
     449      514240 :   for (unsigned i = 0, e = CaretLine.size(), OutCol = 0; i != e; ++i) {
     450     1413875 :     if (i >= LineContents.size() || LineContents[i] != '\t') {
     451     1375818 :       S << CaretLine[i];
     452      458606 :       ++OutCol;
     453      458606 :       continue;
     454             :     }
     455             :     
     456             :     // Okay, we have a tab.  Insert the appropriate number of characters.
     457             :     do {
     458      351183 :       S << CaretLine[i];
     459      117061 :       ++OutCol;
     460      117061 :     } while ((OutCol % TabStop) != 0);
     461             :   }
     462       36438 :   S << '\n';
     463             : 
     464       36438 :   if (ShowColors)
     465           0 :     S.resetColor();
     466             : 
     467             :   // Print out the replacement line, matching tabs in the source line.
     468       36438 :   if (FixItInsertionLine.empty())
     469       36409 :     return;
     470             :   
     471        1843 :   for (size_t i = 0, e = FixItInsertionLine.size(), OutCol = 0; i < e; ++i) {
     472        2703 :     if (i >= LineContents.size() || LineContents[i] != '\t') {
     473        1780 :       S << FixItInsertionLine[i];
     474         890 :       ++OutCol;
     475         890 :       continue;
     476             :     }
     477             : 
     478             :     // Okay, we have a tab.  Insert the appropriate number of characters.
     479             :     do {
     480         142 :       S << FixItInsertionLine[i];
     481             :       // FIXME: This is trying not to break up replacements, but then to re-sync
     482             :       // with the tabs between replacements. This will fail, though, if two
     483             :       // fix-it replacements are exactly adjacent, or if a fix-it contains a
     484             :       // space. Really we should be precomputing column widths, which we'll
     485             :       // need anyway for multibyte chars.
     486          71 :       if (FixItInsertionLine[i] != ' ')
     487          11 :         ++i;
     488          71 :       ++OutCol;
     489          71 :     } while (((OutCol % TabStop) != 0) && i != e);
     490             :   }
     491          29 :   S << '\n';
     492             : }

Generated by: LCOV version 1.13