Fix whitespace.
[oota-llvm.git] / lib / Support / SourceMgr.cpp
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/ADT/Twine.h"
17 #include "llvm/Support/SourceMgr.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/Support/system_error.h"
21 using namespace llvm;
22
23 namespace {
24   struct LineNoCacheTy {
25     int LastQueryBufferID;
26     const char *LastQuery;
27     unsigned LineNoOfQuery;
28   };
29 }
30
31 static LineNoCacheTy *getCache(void *Ptr) {
32   return (LineNoCacheTy*)Ptr;
33 }
34
35
36 SourceMgr::~SourceMgr() {
37   // Delete the line # cache if allocated.
38   if (LineNoCacheTy *Cache = getCache(LineNoCache))
39     delete Cache;
40
41   while (!Buffers.empty()) {
42     delete Buffers.back().Buffer;
43     Buffers.pop_back();
44   }
45 }
46
47 /// AddIncludeFile - Search for a file with the specified name in the current
48 /// directory or in one of the IncludeDirs.  If no file is found, this returns
49 /// ~0, otherwise it returns the buffer ID of the stacked file.
50 unsigned SourceMgr::AddIncludeFile(const std::string &Filename,
51                                    SMLoc IncludeLoc) {
52   error_code ec;
53   MemoryBuffer *NewBuf = MemoryBuffer::getFile(Filename.c_str(), ec);
54
55   // If the file didn't exist directly, see if it's in an include path.
56   for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
57     std::string IncFile = IncludeDirectories[i] + "/" + Filename;
58     NewBuf = MemoryBuffer::getFile(IncFile.c_str(), ec);
59   }
60
61   if (NewBuf == 0) return ~0U;
62
63   return AddNewSourceBuffer(NewBuf, IncludeLoc);
64 }
65
66
67 /// FindBufferContainingLoc - Return the ID of the buffer containing the
68 /// specified location, returning -1 if not found.
69 int SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
70   for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
71     if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
72         // Use <= here so that a pointer to the null at the end of the buffer
73         // is included as part of the buffer.
74         Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
75       return i;
76   return -1;
77 }
78
79 /// FindLineNumber - Find the line number for the specified location in the
80 /// specified file.  This is not a fast method.
81 unsigned SourceMgr::FindLineNumber(SMLoc Loc, int BufferID) const {
82   if (BufferID == -1) BufferID = FindBufferContainingLoc(Loc);
83   assert(BufferID != -1 && "Invalid Location!");
84
85   MemoryBuffer *Buff = getBufferInfo(BufferID).Buffer;
86
87   // Count the number of \n's between the start of the file and the specified
88   // location.
89   unsigned LineNo = 1;
90
91   const char *Ptr = Buff->getBufferStart();
92
93   // If we have a line number cache, and if the query is to a later point in the
94   // same file, start searching from the last query location.  This optimizes
95   // for the case when multiple diagnostics come out of one file in order.
96   if (LineNoCacheTy *Cache = getCache(LineNoCache))
97     if (Cache->LastQueryBufferID == BufferID &&
98         Cache->LastQuery <= Loc.getPointer()) {
99       Ptr = Cache->LastQuery;
100       LineNo = Cache->LineNoOfQuery;
101     }
102
103   // Scan for the location being queried, keeping track of the number of lines
104   // we see.
105   for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
106     if (*Ptr == '\n') ++LineNo;
107
108
109   // Allocate the line number cache if it doesn't exist.
110   if (LineNoCache == 0)
111     LineNoCache = new LineNoCacheTy();
112
113   // Update the line # cache.
114   LineNoCacheTy &Cache = *getCache(LineNoCache);
115   Cache.LastQueryBufferID = BufferID;
116   Cache.LastQuery = Ptr;
117   Cache.LineNoOfQuery = LineNo;
118   return LineNo;
119 }
120
121 void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
122   if (IncludeLoc == SMLoc()) return;  // Top of stack.
123
124   int CurBuf = FindBufferContainingLoc(IncludeLoc);
125   assert(CurBuf != -1 && "Invalid or unspecified location!");
126
127   PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
128
129   OS << "Included from "
130      << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
131      << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
132 }
133
134
135 /// GetMessage - Return an SMDiagnostic at the specified location with the
136 /// specified string.
137 ///
138 /// @param Type - If non-null, the kind of message (e.g., "error") which is
139 /// prefixed to the message.
140 SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, const Twine &Msg,
141                                    const char *Type, bool ShowLine) const {
142
143   // First thing to do: find the current buffer containing the specified
144   // location.
145   int CurBuf = FindBufferContainingLoc(Loc);
146   assert(CurBuf != -1 && "Invalid or unspecified location!");
147
148   MemoryBuffer *CurMB = getBufferInfo(CurBuf).Buffer;
149
150   // Scan backward to find the start of the line.
151   const char *LineStart = Loc.getPointer();
152   while (LineStart != CurMB->getBufferStart() &&
153          LineStart[-1] != '\n' && LineStart[-1] != '\r')
154     --LineStart;
155
156   std::string LineStr;
157   if (ShowLine) {
158     // Get the end of the line.
159     const char *LineEnd = Loc.getPointer();
160     while (LineEnd != CurMB->getBufferEnd() &&
161            LineEnd[0] != '\n' && LineEnd[0] != '\r')
162       ++LineEnd;
163     LineStr = std::string(LineStart, LineEnd);
164   }
165
166   std::string PrintedMsg;
167   raw_string_ostream OS(PrintedMsg);
168   if (Type)
169     OS << Type << ": ";
170   OS << Msg;
171
172   return SMDiagnostic(*this, Loc,
173                       CurMB->getBufferIdentifier(), FindLineNumber(Loc, CurBuf),
174                       Loc.getPointer()-LineStart, OS.str(),
175                       LineStr, ShowLine);
176 }
177
178 void SourceMgr::PrintMessage(SMLoc Loc, const Twine &Msg,
179                              const char *Type, bool ShowLine) const {
180   // Report the message with the diagnostic handler if present.
181   if (DiagHandler) {
182     DiagHandler(GetMessage(Loc, Msg, Type, ShowLine), DiagContext);
183     return;
184   }
185
186   raw_ostream &OS = errs();
187
188   int CurBuf = FindBufferContainingLoc(Loc);
189   assert(CurBuf != -1 && "Invalid or unspecified location!");
190   PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
191
192   GetMessage(Loc, Msg, Type, ShowLine).Print(0, OS);
193 }
194
195 //===----------------------------------------------------------------------===//
196 // SMDiagnostic Implementation
197 //===----------------------------------------------------------------------===//
198
199 void SMDiagnostic::Print(const char *ProgName, raw_ostream &S) const {
200   if (ProgName && ProgName[0])
201     S << ProgName << ": ";
202
203   if (!Filename.empty()) {
204     if (Filename == "-")
205       S << "<stdin>";
206     else
207       S << Filename;
208
209     if (LineNo != -1) {
210       S << ':' << LineNo;
211       if (ColumnNo != -1)
212         S << ':' << (ColumnNo+1);
213     }
214     S << ": ";
215   }
216
217   S << Message << '\n';
218
219   if (LineNo != -1 && ColumnNo != -1 && ShowLine) {
220     S << LineContents << '\n';
221
222     // Print out spaces/tabs before the caret.
223     for (unsigned i = 0; i != unsigned(ColumnNo); ++i)
224       S << (LineContents[i] == '\t' ? '\t' : ' ');
225     S << "^\n";
226   }
227 }
228
229