LLVM API Documentation

SourceMgr.cpp

Go to the documentation of this file.
00001 //===- SourceMgr.cpp - Manager for Simple Source Buffers & Diagnostics ----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the SourceMgr class.  This class is used as a simple
00011 // substrate for diagnostics, #include handling, and other low level things for
00012 // simple parsers.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Support/SourceMgr.h"
00017 #include "llvm/Support/MemoryBuffer.h"
00018 #include "llvm/Support/raw_ostream.h"
00019 using namespace llvm;
00020 
00021 namespace {
00022   struct LineNoCacheTy {
00023     int LastQueryBufferID;
00024     const char *LastQuery;
00025     unsigned LineNoOfQuery;
00026   };
00027 }
00028 
00029 static LineNoCacheTy *getCache(void *Ptr) {
00030   return (LineNoCacheTy*)Ptr;
00031 }
00032 
00033 
00034 SourceMgr::~SourceMgr() {
00035   // Delete the line # cache if allocated.
00036   if (LineNoCacheTy *Cache = getCache(LineNoCache))
00037     delete Cache;
00038     
00039   while (!Buffers.empty()) {
00040     delete Buffers.back().Buffer;
00041     Buffers.pop_back();
00042   }
00043 }
00044 
00045 /// AddIncludeFile - Search for a file with the specified name in the current
00046 /// directory or in one of the IncludeDirs.  If no file is found, this returns
00047 /// ~0, otherwise it returns the buffer ID of the stacked file.
00048 unsigned SourceMgr::AddIncludeFile(const std::string &Filename,
00049                                    SMLoc IncludeLoc) {
00050   
00051   MemoryBuffer *NewBuf = MemoryBuffer::getFile(Filename.c_str());
00052 
00053   // If the file didn't exist directly, see if it's in an include path.
00054   for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
00055     std::string IncFile = IncludeDirectories[i] + "/" + Filename;
00056     NewBuf = MemoryBuffer::getFile(IncFile.c_str());
00057   }
00058  
00059   if (NewBuf == 0) return ~0U;
00060 
00061   return AddNewSourceBuffer(NewBuf, IncludeLoc);
00062 }
00063 
00064 
00065 /// FindBufferContainingLoc - Return the ID of the buffer containing the
00066 /// specified location, returning -1 if not found.
00067 int SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
00068   for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
00069     if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
00070         // Use <= here so that a pointer to the null at the end of the buffer
00071         // is included as part of the buffer.
00072         Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
00073       return i;
00074   return -1;
00075 }
00076 
00077 /// FindLineNumber - Find the line number for the specified location in the
00078 /// specified file.  This is not a fast method.
00079 unsigned SourceMgr::FindLineNumber(SMLoc Loc, int BufferID) const {
00080   if (BufferID == -1) BufferID = FindBufferContainingLoc(Loc);
00081   assert(BufferID != -1 && "Invalid Location!");
00082   
00083   MemoryBuffer *Buff = getBufferInfo(BufferID).Buffer;
00084   
00085   // Count the number of \n's between the start of the file and the specified
00086   // location.
00087   unsigned LineNo = 1;
00088   
00089   const char *Ptr = Buff->getBufferStart();
00090 
00091   // If we have a line number cache, and if the query is to a later point in the
00092   // same file, start searching from the last query location.  This optimizes
00093   // for the case when multiple diagnostics come out of one file in order.
00094   if (LineNoCacheTy *Cache = getCache(LineNoCache))
00095     if (Cache->LastQueryBufferID == BufferID && 
00096         Cache->LastQuery <= Loc.getPointer()) {
00097       Ptr = Cache->LastQuery;
00098       LineNo = Cache->LineNoOfQuery;
00099     }
00100 
00101   // Scan for the location being queried, keeping track of the number of lines
00102   // we see.
00103   for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
00104     if (*Ptr == '\n') ++LineNo;
00105   
00106   
00107   // Allocate the line number cache if it doesn't exist.
00108   if (LineNoCache == 0)
00109     LineNoCache = new LineNoCacheTy();
00110   
00111   // Update the line # cache.
00112   LineNoCacheTy &Cache = *getCache(LineNoCache);
00113   Cache.LastQueryBufferID = BufferID;
00114   Cache.LastQuery = Ptr;
00115   Cache.LineNoOfQuery = LineNo;
00116   return LineNo;
00117 }
00118 
00119 void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
00120   if (IncludeLoc == SMLoc()) return;  // Top of stack.
00121   
00122   int CurBuf = FindBufferContainingLoc(IncludeLoc);
00123   assert(CurBuf != -1 && "Invalid or unspecified location!");
00124 
00125   PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
00126   
00127   OS << "Included from "
00128      << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
00129      << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
00130 }
00131 
00132 
00133 /// GetMessage - Return an SMDiagnostic at the specified location with the
00134 /// specified string.
00135 ///
00136 /// @param Type - If non-null, the kind of message (e.g., "error") which is
00137 /// prefixed to the message.
00138 SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, const std::string &Msg,
00139                                    const char *Type) const {
00140   
00141   // First thing to do: find the current buffer containing the specified
00142   // location.
00143   int CurBuf = FindBufferContainingLoc(Loc);
00144   assert(CurBuf != -1 && "Invalid or unspecified location!");
00145   
00146   MemoryBuffer *CurMB = getBufferInfo(CurBuf).Buffer;
00147   
00148   
00149   // Scan backward to find the start of the line.
00150   const char *LineStart = Loc.getPointer();
00151   while (LineStart != CurMB->getBufferStart() && 
00152          LineStart[-1] != '\n' && LineStart[-1] != '\r')
00153     --LineStart;
00154   // Get the end of the line.
00155   const char *LineEnd = Loc.getPointer();
00156   while (LineEnd != CurMB->getBufferEnd() && 
00157          LineEnd[0] != '\n' && LineEnd[0] != '\r')
00158     ++LineEnd;
00159   
00160   std::string PrintedMsg;
00161   if (Type) {
00162     PrintedMsg = Type;
00163     PrintedMsg += ": ";
00164   }
00165   PrintedMsg += Msg;
00166   
00167   // Print out the line.
00168   return SMDiagnostic(CurMB->getBufferIdentifier(), FindLineNumber(Loc, CurBuf),
00169                       Loc.getPointer()-LineStart, PrintedMsg,
00170                       std::string(LineStart, LineEnd));
00171 }
00172 
00173 void SourceMgr::PrintMessage(SMLoc Loc, const std::string &Msg, 
00174                              const char *Type) const {
00175   raw_ostream &OS = errs();
00176 
00177   int CurBuf = FindBufferContainingLoc(Loc);
00178   assert(CurBuf != -1 && "Invalid or unspecified location!");
00179   PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
00180 
00181   GetMessage(Loc, Msg, Type).Print(0, OS);
00182 }
00183 
00184 //===----------------------------------------------------------------------===//
00185 // SMDiagnostic Implementation
00186 //===----------------------------------------------------------------------===//
00187 
00188 void SMDiagnostic::Print(const char *ProgName, raw_ostream &S) {
00189   if (ProgName && ProgName[0])
00190     S << ProgName << ": ";
00191 
00192   if (Filename == "-")
00193     S << "<stdin>";
00194   else
00195     S << Filename;
00196   
00197   if (LineNo != -1) {
00198     S << ':' << LineNo;
00199     if (ColumnNo != -1)
00200       S << ':' << (ColumnNo+1);
00201   }
00202   
00203   S << ": " << Message << '\n';
00204   
00205   if (LineNo != -1 && ColumnNo != -1) {
00206     S << LineContents << '\n';
00207     
00208     // Print out spaces/tabs before the caret.
00209     for (unsigned i = 0; i != unsigned(ColumnNo); ++i)
00210       S << (LineContents[i] == '\t' ? '\t' : ' ');
00211     S << "^\n";
00212   }
00213 }
00214 
00215