Fix issue with bitwise and precedence.
[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/ADT/OwningPtr.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Support/system_error.h"
22 using namespace llvm;
23
24 namespace {
25   struct LineNoCacheTy {
26     int LastQueryBufferID;
27     const char *LastQuery;
28     unsigned LineNoOfQuery;
29   };
30 }
31
32 static LineNoCacheTy *getCache(void *Ptr) {
33   return (LineNoCacheTy*)Ptr;
34 }
35
36
37 SourceMgr::~SourceMgr() {
38   // Delete the line # cache if allocated.
39   if (LineNoCacheTy *Cache = getCache(LineNoCache))
40     delete Cache;
41
42   while (!Buffers.empty()) {
43     delete Buffers.back().Buffer;
44     Buffers.pop_back();
45   }
46 }
47
48 /// AddIncludeFile - Search for a file with the specified name in the current
49 /// directory or in one of the IncludeDirs.  If no file is found, this returns
50 /// ~0, otherwise it returns the buffer ID of the stacked file.
51 unsigned SourceMgr::AddIncludeFile(const std::string &Filename,
52                                    SMLoc IncludeLoc,
53                                    std::string &IncludedFile) {
54   OwningPtr<MemoryBuffer> NewBuf;
55   IncludedFile = Filename;
56   MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
57
58   // If the file didn't exist directly, see if it's in an include path.
59   for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
60     IncludedFile = IncludeDirectories[i] + "/" + Filename;
61     MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
62   }
63
64   if (NewBuf == 0) return ~0U;
65
66   return AddNewSourceBuffer(NewBuf.take(), IncludeLoc);
67 }
68
69
70 /// FindBufferContainingLoc - Return the ID of the buffer containing the
71 /// specified location, returning -1 if not found.
72 int SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
73   for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
74     if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
75         // Use <= here so that a pointer to the null at the end of the buffer
76         // is included as part of the buffer.
77         Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
78       return i;
79   return -1;
80 }
81
82 /// FindLineNumber - Find the line number for the specified location in the
83 /// specified file.  This is not a fast method.
84 unsigned SourceMgr::FindLineNumber(SMLoc Loc, int BufferID) const {
85   if (BufferID == -1) BufferID = FindBufferContainingLoc(Loc);
86   assert(BufferID != -1 && "Invalid Location!");
87
88   MemoryBuffer *Buff = getBufferInfo(BufferID).Buffer;
89
90   // Count the number of \n's between the start of the file and the specified
91   // location.
92   unsigned LineNo = 1;
93
94   const char *Ptr = Buff->getBufferStart();
95
96   // If we have a line number cache, and if the query is to a later point in the
97   // same file, start searching from the last query location.  This optimizes
98   // for the case when multiple diagnostics come out of one file in order.
99   if (LineNoCacheTy *Cache = getCache(LineNoCache))
100     if (Cache->LastQueryBufferID == BufferID &&
101         Cache->LastQuery <= Loc.getPointer()) {
102       Ptr = Cache->LastQuery;
103       LineNo = Cache->LineNoOfQuery;
104     }
105
106   // Scan for the location being queried, keeping track of the number of lines
107   // we see.
108   for (; SMLoc::getFromPointer(Ptr) != Loc; ++Ptr)
109     if (*Ptr == '\n') ++LineNo;
110
111
112   // Allocate the line number cache if it doesn't exist.
113   if (LineNoCache == 0)
114     LineNoCache = new LineNoCacheTy();
115
116   // Update the line # cache.
117   LineNoCacheTy &Cache = *getCache(LineNoCache);
118   Cache.LastQueryBufferID = BufferID;
119   Cache.LastQuery = Ptr;
120   Cache.LineNoOfQuery = LineNo;
121   return LineNo;
122 }
123
124 void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
125   if (IncludeLoc == SMLoc()) return;  // Top of stack.
126
127   int CurBuf = FindBufferContainingLoc(IncludeLoc);
128   assert(CurBuf != -1 && "Invalid or unspecified location!");
129
130   PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
131
132   OS << "Included from "
133      << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
134      << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
135 }
136
137
138 /// GetMessage - Return an SMDiagnostic at the specified location with the
139 /// specified string.
140 ///
141 /// @param Type - If non-null, the kind of message (e.g., "error") which is
142 /// prefixed to the message.
143 SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
144                                    const Twine &Msg,
145                                    ArrayRef<SMRange> Ranges) const {
146
147   // First thing to do: find the current buffer containing the specified
148   // location.
149   int CurBuf = FindBufferContainingLoc(Loc);
150   assert(CurBuf != -1 && "Invalid or unspecified location!");
151
152   MemoryBuffer *CurMB = getBufferInfo(CurBuf).Buffer;
153
154   // Scan backward to find the start of the line.
155   const char *LineStart = Loc.getPointer();
156   while (LineStart != CurMB->getBufferStart() &&
157          LineStart[-1] != '\n' && LineStart[-1] != '\r')
158     --LineStart;
159
160   // Get the end of the line.
161   const char *LineEnd = Loc.getPointer();
162   while (LineEnd != CurMB->getBufferEnd() &&
163          LineEnd[0] != '\n' && LineEnd[0] != '\r')
164     ++LineEnd;
165   std::string LineStr(LineStart, LineEnd);
166
167   // Convert any ranges to column ranges that only intersect the line of the
168   // location.
169   SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
170   for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
171     SMRange R = Ranges[i];
172     if (!R.isValid()) continue;
173     
174     // If the line doesn't contain any part of the range, then ignore it.
175     if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
176       continue;
177    
178     // Ignore pieces of the range that go onto other lines.
179     if (R.Start.getPointer() < LineStart)
180       R.Start = SMLoc::getFromPointer(LineStart);
181     if (R.End.getPointer() > LineEnd)
182       R.End = SMLoc::getFromPointer(LineEnd);
183     
184     // Translate from SMLoc ranges to column ranges.
185     ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart,
186                                        R.End.getPointer()-LineStart));
187   }
188   
189   return SMDiagnostic(*this, Loc,
190                       CurMB->getBufferIdentifier(), FindLineNumber(Loc, CurBuf),
191                       Loc.getPointer()-LineStart, Kind, Msg.str(),
192                       LineStr, ColRanges);
193 }
194
195 void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
196                              const Twine &Msg, ArrayRef<SMRange> Ranges) const {
197   SMDiagnostic Diagnostic = GetMessage(Loc, Kind, Msg, Ranges);
198   
199   // Report the message with the diagnostic handler if present.
200   if (DiagHandler) {
201     DiagHandler(Diagnostic, DiagContext);
202     return;
203   }
204
205   raw_ostream &OS = errs();
206
207   int CurBuf = FindBufferContainingLoc(Loc);
208   assert(CurBuf != -1 && "Invalid or unspecified location!");
209   PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
210
211   Diagnostic.print(0, OS);
212 }
213
214 //===----------------------------------------------------------------------===//
215 // SMDiagnostic Implementation
216 //===----------------------------------------------------------------------===//
217
218 SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, const std::string &FN,
219                            int Line, int Col, SourceMgr::DiagKind Kind,
220                            const std::string &Msg,
221                            const std::string &LineStr,
222                            ArrayRef<std::pair<unsigned,unsigned> > Ranges)
223   : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Kind(Kind),
224     Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()) {
225 }
226
227
228 void SMDiagnostic::print(const char *ProgName, raw_ostream &S) const {
229   if (ProgName && ProgName[0])
230     S << ProgName << ": ";
231
232   if (!Filename.empty()) {
233     if (Filename == "-")
234       S << "<stdin>";
235     else
236       S << Filename;
237
238     if (LineNo != -1) {
239       S << ':' << LineNo;
240       if (ColumnNo != -1)
241         S << ':' << (ColumnNo+1);
242     }
243     S << ": ";
244   }
245
246   switch (Kind) {
247   case SourceMgr::DK_Error: S << "error: "; break;
248   case SourceMgr::DK_Warning: S << "warning: "; break;
249   case SourceMgr::DK_Note: S << "note: "; break;
250   }
251   
252   S << Message << '\n';
253
254   if (LineNo == -1 || ColumnNo == -1)
255     return;
256
257   // Build the line with the caret and ranges.
258   std::string CaretLine(LineContents.size()+1, ' ');
259   
260   // Expand any ranges.
261   for (unsigned r = 0, e = Ranges.size(); r != e; ++r) {
262     std::pair<unsigned, unsigned> R = Ranges[r];
263     for (unsigned i = R.first,
264          e = std::min(R.second, (unsigned)LineContents.size())+1; i != e; ++i)
265       CaretLine[i] = '~';
266   }
267     
268   // Finally, plop on the caret.
269   if (unsigned(ColumnNo) <= LineContents.size())
270     CaretLine[ColumnNo] = '^';
271   else 
272     CaretLine[LineContents.size()] = '^';
273   
274   // ... and remove trailing whitespace so the output doesn't wrap for it.  We
275   // know that the line isn't completely empty because it has the caret in it at
276   // least.
277   CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
278   
279   // Print out the source line one character at a time, so we can expand tabs.
280   for (unsigned i = 0, e = LineContents.size(), OutCol = 0; i != e; ++i) {
281     if (LineContents[i] != '\t') {
282       S << LineContents[i];
283       ++OutCol;
284       continue;
285     }
286     
287     // If we have a tab, emit at least one space, then round up to 8 columns.
288     do {
289       S << ' ';
290       ++OutCol;
291     } while (OutCol & 7);
292   }
293   S << '\n';
294
295   // Print out the caret line, matching tabs in the source line.
296   for (unsigned i = 0, e = CaretLine.size(), OutCol = 0; i != e; ++i) {
297     if (i >= LineContents.size() || LineContents[i] != '\t') {
298       S << CaretLine[i];
299       ++OutCol;
300       continue;
301     }
302     
303     // Okay, we have a tab.  Insert the appropriate number of characters.
304     do {
305       S << CaretLine[i];
306       ++OutCol;
307     } while (OutCol & 7);
308   }
309   
310   S << '\n';
311 }
312
313