Unbreak build with gcc 4.3: provide missed includes and silence most annoying warnings.
[oota-llvm.git] / utils / TableGen / TGLexer.cpp
1 //===- TGLexer.cpp - Lexer for TableGen -----------------------------------===//
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 // Implement the Lexer for TableGen.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TGLexer.h"
15 #include "llvm/Support/Streams.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include <ostream>
18 #include "llvm/Config/config.h"
19 #include <cctype>
20 #include <cstdlib>
21 #include <cstring>
22 using namespace llvm;
23
24 TGLexer::TGLexer(MemoryBuffer *StartBuf) : CurLineNo(1), CurBuf(StartBuf) {
25   CurPtr = CurBuf->getBufferStart();
26   TokStart = 0;
27 }
28
29 TGLexer::~TGLexer() {
30   while (!IncludeStack.empty()) {
31     delete IncludeStack.back().Buffer;
32     IncludeStack.pop_back();
33   }
34   delete CurBuf;
35 }
36
37 /// ReturnError - Set the error to the specified string at the specified
38 /// location.  This is defined to always return tgtok::Error.
39 tgtok::TokKind TGLexer::ReturnError(const char *Loc, const std::string &Msg) {
40   PrintError(Loc, Msg);
41   return tgtok::Error;
42 }
43
44 void TGLexer::PrintIncludeStack(std::ostream &OS) const {
45   for (unsigned i = 0, e = IncludeStack.size(); i != e; ++i)
46     OS << "Included from " << IncludeStack[i].Buffer->getBufferIdentifier()
47        << ":" << IncludeStack[i].LineNo << ":\n";
48   OS << "Parsing " << CurBuf->getBufferIdentifier() << ":"
49      << CurLineNo << ": ";
50 }
51
52 /// PrintError - Print the error at the specified location.
53 void TGLexer::PrintError(const char *ErrorLoc,  const std::string &Msg) const {
54   PrintIncludeStack(*cerr.stream());
55   cerr << Msg << "\n";
56   assert(ErrorLoc && "Location not specified!");
57   
58   // Scan backward to find the start of the line.
59   const char *LineStart = ErrorLoc;
60   while (LineStart != CurBuf->getBufferStart() && 
61          LineStart[-1] != '\n' && LineStart[-1] != '\r')
62     --LineStart;
63   // Get the end of the line.
64   const char *LineEnd = ErrorLoc;
65   while (LineEnd != CurBuf->getBufferEnd() && 
66          LineEnd[0] != '\n' && LineEnd[0] != '\r')
67     ++LineEnd;
68   // Print out the line.
69   cerr << std::string(LineStart, LineEnd) << "\n";
70   // Print out spaces before the carat.
71   for (const char *Pos = LineStart; Pos != ErrorLoc; ++Pos)
72     cerr << (*Pos == '\t' ? '\t' : ' ');
73   cerr << "^\n";
74 }
75
76 int TGLexer::getNextChar() {
77   char CurChar = *CurPtr++;
78   switch (CurChar) {
79   default:
80     return (unsigned char)CurChar;
81   case 0:
82     // A nul character in the stream is either the end of the current buffer or
83     // a random nul in the file.  Disambiguate that here.
84     if (CurPtr-1 != CurBuf->getBufferEnd())
85       return 0;  // Just whitespace.
86     
87     // If this is the end of an included file, pop the parent file off the
88     // include stack.
89     if (!IncludeStack.empty()) {
90       delete CurBuf;
91       CurBuf = IncludeStack.back().Buffer;
92       CurLineNo = IncludeStack.back().LineNo;
93       CurPtr = IncludeStack.back().CurPtr;
94       IncludeStack.pop_back();
95       return getNextChar();
96     }
97     
98     // Otherwise, return end of file.
99     --CurPtr;  // Another call to lex will return EOF again.  
100     return EOF;
101   case '\n':
102   case '\r':
103     // Handle the newline character by ignoring it and incrementing the line
104     // count.  However, be careful about 'dos style' files with \n\r in them.
105     // Only treat a \n\r or \r\n as a single line.
106     if ((*CurPtr == '\n' || (*CurPtr == '\r')) &&
107         *CurPtr != CurChar)
108       ++CurPtr;  // Eat the two char newline sequence.
109       
110     ++CurLineNo;
111     return '\n';
112   }  
113 }
114
115 tgtok::TokKind TGLexer::LexToken() {
116   TokStart = CurPtr;
117   // This always consumes at least one character.
118   int CurChar = getNextChar();
119
120   switch (CurChar) {
121   default:
122     // Handle letters: [a-zA-Z_]
123     if (isalpha(CurChar) || CurChar == '_')
124       return LexIdentifier();
125       
126     // Unknown character, emit an error.
127     return ReturnError(TokStart, "Unexpected character");
128   case EOF: return tgtok::Eof;
129   case ':': return tgtok::colon;
130   case ';': return tgtok::semi;
131   case '.': return tgtok::period;
132   case ',': return tgtok::comma;
133   case '<': return tgtok::less;
134   case '>': return tgtok::greater;
135   case ']': return tgtok::r_square;
136   case '{': return tgtok::l_brace;
137   case '}': return tgtok::r_brace;
138   case '(': return tgtok::l_paren;
139   case ')': return tgtok::r_paren;
140   case '=': return tgtok::equal;
141   case '?': return tgtok::question;
142       
143   case 0:
144   case ' ':
145   case '\t':
146   case '\n':
147   case '\r':
148     // Ignore whitespace.
149     return LexToken();
150   case '/':
151     // If this is the start of a // comment, skip until the end of the line or
152     // the end of the buffer.
153     if (*CurPtr == '/')
154       SkipBCPLComment();
155     else if (*CurPtr == '*') {
156       if (SkipCComment())
157         return tgtok::Error;
158     } else // Otherwise, this is an error.
159       return ReturnError(TokStart, "Unexpected character");
160     return LexToken();
161   case '-': case '+':
162   case '0': case '1': case '2': case '3': case '4': case '5': case '6':
163   case '7': case '8': case '9':  
164     return LexNumber();
165   case '"': return LexString();
166   case '$': return LexVarName();
167   case '[': return LexBracket();
168   case '!': return LexExclaim();
169   }
170 }
171
172 /// LexString - Lex "[^"]*"
173 tgtok::TokKind TGLexer::LexString() {
174   const char *StrStart = CurPtr;
175   
176   while (*CurPtr != '"') {
177     // If we hit the end of the buffer, report an error.
178     if (*CurPtr == 0 && CurPtr == CurBuf->getBufferEnd())
179       return ReturnError(StrStart, "End of file in string literal");
180     
181     if (*CurPtr == '\n' || *CurPtr == '\r')
182       return ReturnError(StrStart, "End of line in string literal");
183     
184     ++CurPtr;
185   }
186   
187   CurStrVal.assign(StrStart, CurPtr);
188   ++CurPtr;
189   return tgtok::StrVal;
190 }
191
192 tgtok::TokKind TGLexer::LexVarName() {
193   if (!isalpha(CurPtr[0]) && CurPtr[0] != '_')
194     return ReturnError(TokStart, "Invalid variable name");
195   
196   // Otherwise, we're ok, consume the rest of the characters.
197   const char *VarNameStart = CurPtr++;
198   
199   while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
200     ++CurPtr;
201
202   CurStrVal.assign(VarNameStart, CurPtr);
203   return tgtok::VarName;
204 }
205
206
207 tgtok::TokKind TGLexer::LexIdentifier() {
208   // The first letter is [a-zA-Z_].
209   const char *IdentStart = TokStart;
210   
211   // Match the rest of the identifier regex: [0-9a-zA-Z_]*
212   while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
213     ++CurPtr;
214   
215   // Check to see if this identifier is a keyword.
216   unsigned Len = CurPtr-IdentStart;
217   
218   if (Len == 3 && !memcmp(IdentStart, "int", 3)) return tgtok::Int;
219   if (Len == 3 && !memcmp(IdentStart, "bit", 3)) return tgtok::Bit;
220   if (Len == 4 && !memcmp(IdentStart, "bits", 4)) return tgtok::Bits;
221   if (Len == 6 && !memcmp(IdentStart, "string", 6)) return tgtok::String;
222   if (Len == 4 && !memcmp(IdentStart, "list", 4)) return tgtok::List;
223   if (Len == 4 && !memcmp(IdentStart, "code", 4)) return tgtok::Code;
224   if (Len == 3 && !memcmp(IdentStart, "dag", 3)) return tgtok::Dag;
225   
226   if (Len == 5 && !memcmp(IdentStart, "class", 5)) return tgtok::Class;
227   if (Len == 3 && !memcmp(IdentStart, "def", 3)) return tgtok::Def;
228   if (Len == 4 && !memcmp(IdentStart, "defm", 4)) return tgtok::Defm;
229   if (Len == 10 && !memcmp(IdentStart, "multiclass", 10))
230     return tgtok::MultiClass;
231   if (Len == 5 && !memcmp(IdentStart, "field", 5)) return tgtok::Field;
232   if (Len == 3 && !memcmp(IdentStart, "let", 3)) return tgtok::Let;
233   if (Len == 2 && !memcmp(IdentStart, "in", 2)) return tgtok::In;
234   
235   if (Len == 7 && !memcmp(IdentStart, "include", 7)) {
236     if (LexInclude()) return tgtok::Error;
237     return Lex();
238   }
239     
240   CurStrVal.assign(IdentStart, CurPtr);
241   return tgtok::Id;
242 }
243
244 /// LexInclude - We just read the "include" token.  Get the string token that
245 /// comes next and enter the include.
246 bool TGLexer::LexInclude() {
247   // The token after the include must be a string.
248   tgtok::TokKind Tok = LexToken();
249   if (Tok == tgtok::Error) return true;
250   if (Tok != tgtok::StrVal) {
251     PrintError(getLoc(), "Expected filename after include");
252     return true;
253   }
254
255   // Get the string.
256   std::string Filename = CurStrVal;
257
258   // Try to find the file.
259   MemoryBuffer *NewBuf = MemoryBuffer::getFile(&Filename[0], Filename.size());
260
261   // If the file didn't exist directly, see if it's in an include path.
262   for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
263     std::string IncFile = IncludeDirectories[i] + "/" + Filename;
264     NewBuf = MemoryBuffer::getFile(&IncFile[0], IncFile.size());
265   }
266     
267   if (NewBuf == 0) {
268     PrintError(getLoc(), "Could not find include file '" + Filename + "'");
269     return true;
270   }
271   
272   // Save the line number and lex buffer of the includer.
273   IncludeStack.push_back(IncludeRec(CurBuf, CurPtr, CurLineNo));
274   
275   CurLineNo = 1;  // Reset line numbering.
276   CurBuf = NewBuf;
277   CurPtr = CurBuf->getBufferStart();
278   return false;
279 }
280
281 void TGLexer::SkipBCPLComment() {
282   ++CurPtr;  // skip the second slash.
283   while (1) {
284     switch (*CurPtr) {
285     case '\n':
286     case '\r':
287       return;  // Newline is end of comment.
288     case 0:
289       // If this is the end of the buffer, end the comment.
290       if (CurPtr == CurBuf->getBufferEnd())
291         return;
292       break;
293     }
294     // Otherwise, skip the character.
295     ++CurPtr;
296   }
297 }
298
299 /// SkipCComment - This skips C-style /**/ comments.  The only difference from C
300 /// is that we allow nesting.
301 bool TGLexer::SkipCComment() {
302   ++CurPtr;  // skip the star.
303   unsigned CommentDepth = 1;
304   
305   while (1) {
306     int CurChar = getNextChar();
307     switch (CurChar) {
308     case EOF:
309       PrintError(TokStart, "Unterminated comment!");
310       return true;
311     case '*':
312       // End of the comment?
313       if (CurPtr[0] != '/') break;
314       
315       ++CurPtr;   // End the */.
316       if (--CommentDepth == 0)
317         return false;
318       break;
319     case '/':
320       // Start of a nested comment?
321       if (CurPtr[0] != '*') break;
322       ++CurPtr;
323       ++CommentDepth;
324       break;
325     }
326   }
327 }
328
329 /// LexNumber - Lex:
330 ///    [-+]?[0-9]+
331 ///    0x[0-9a-fA-F]+
332 ///    0b[01]+
333 tgtok::TokKind TGLexer::LexNumber() {
334   if (CurPtr[-1] == '0') {
335     if (CurPtr[0] == 'x') {
336       ++CurPtr;
337       const char *NumStart = CurPtr;
338       while (isxdigit(CurPtr[0]))
339         ++CurPtr;
340       
341       // Requires at least one hex digit.
342       if (CurPtr == NumStart)
343         return ReturnError(CurPtr-2, "Invalid hexadecimal number");
344
345       CurIntVal = strtoll(NumStart, 0, 16);
346       return tgtok::IntVal;
347     } else if (CurPtr[0] == 'b') {
348       ++CurPtr;
349       const char *NumStart = CurPtr;
350       while (CurPtr[0] == '0' || CurPtr[0] == '1')
351         ++CurPtr;
352
353       // Requires at least one binary digit.
354       if (CurPtr == NumStart)
355         return ReturnError(CurPtr-2, "Invalid binary number");
356       CurIntVal = strtoll(NumStart, 0, 2);
357       return tgtok::IntVal;
358     }
359   }
360
361   // Check for a sign without a digit.
362   if (!isdigit(CurPtr[0])) {
363     if (CurPtr[-1] == '-')
364       return tgtok::minus;
365     else if (CurPtr[-1] == '+')
366       return tgtok::plus;
367   }
368   
369   while (isdigit(CurPtr[0]))
370     ++CurPtr;
371   CurIntVal = strtoll(TokStart, 0, 10);
372   return tgtok::IntVal;
373 }
374
375 /// LexBracket - We just read '['.  If this is a code block, return it,
376 /// otherwise return the bracket.  Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
377 tgtok::TokKind TGLexer::LexBracket() {
378   if (CurPtr[0] != '{')
379     return tgtok::l_square;
380   ++CurPtr;
381   const char *CodeStart = CurPtr;
382   while (1) {
383     int Char = getNextChar();
384     if (Char == EOF) break;
385     
386     if (Char != '}') continue;
387     
388     Char = getNextChar();
389     if (Char == EOF) break;
390     if (Char == ']') {
391       CurStrVal.assign(CodeStart, CurPtr-2);
392       return tgtok::CodeFragment;
393     }
394   }
395   
396   return ReturnError(CodeStart-2, "Unterminated Code Block");
397 }
398
399 /// LexExclaim - Lex '!' and '![a-zA-Z]+'.
400 tgtok::TokKind TGLexer::LexExclaim() {
401   if (!isalpha(*CurPtr))
402     return ReturnError(CurPtr-1, "Invalid \"!operator\"");
403   
404   const char *Start = CurPtr++;
405   while (isalpha(*CurPtr))
406     ++CurPtr;
407   
408   // Check to see which operator this is.
409   unsigned Len = CurPtr-Start;
410   
411   if (Len == 3 && !memcmp(Start, "con", 3)) return tgtok::XConcat;
412   if (Len == 3 && !memcmp(Start, "sra", 3)) return tgtok::XSRA;
413   if (Len == 3 && !memcmp(Start, "srl", 3)) return tgtok::XSRL;
414   if (Len == 3 && !memcmp(Start, "shl", 3)) return tgtok::XSHL;
415   if (Len == 9 && !memcmp(Start, "strconcat", 9)) return tgtok::XStrConcat;
416   
417   return ReturnError(Start-1, "Unknown operator");
418 }
419