Switching back to strtoll. Including config.h. On VStudio builds, this overrides...
[oota-llvm.git] / utils / TableGen / TGLexer.cpp
1 //===- TGLexer.cpp - Lexer for TableGen -----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implement the Lexer for TableGen.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TGLexer.h"
15 #include "Record.h"
16 #include "llvm/Support/Streams.h"
17 #include "Record.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 typedef std::pair<llvm::Record*, std::vector<llvm::Init*>*> SubClassRefTy;
20 #include "FileParser.h"
21 #include "llvm/Config/config.h"
22 #include <cctype>
23 using namespace llvm;
24
25 // FIXME: REMOVE THIS.
26 #define YYEOF 0
27 #define YYERROR -2
28
29 TGLexer::TGLexer(MemoryBuffer *StartBuf) : CurLineNo(1), CurBuf(StartBuf) {
30   CurPtr = CurBuf->getBufferStart();
31   TokStart = 0;
32 }
33
34 TGLexer::~TGLexer() {
35   while (!IncludeStack.empty()) {
36     delete IncludeStack.back().Buffer;
37     IncludeStack.pop_back();
38   }
39   delete CurBuf;
40 }
41
42 /// ReturnError - Set the error to the specified string at the specified
43 /// location.  This is defined to always return YYERROR.
44 int TGLexer::ReturnError(const char *Loc, const std::string &Msg) {
45   PrintError(Loc, Msg);
46   return YYERROR;
47 }
48
49 std::ostream &TGLexer::err() const {
50   PrintIncludeStack(*cerr.stream());
51   return *cerr.stream();
52 }
53
54
55 void TGLexer::PrintIncludeStack(std::ostream &OS) const {
56   for (unsigned i = 0, e = IncludeStack.size(); i != e; ++i)
57     OS << "Included from " << IncludeStack[i].Buffer->getBufferIdentifier()
58        << ":" << IncludeStack[i].LineNo << ":\n";
59   OS << "Parsing " << CurBuf->getBufferIdentifier() << ":"
60      << CurLineNo << ": ";
61 }
62
63 /// PrintError - Print the error at the specified location.
64 void TGLexer::PrintError(const char *ErrorLoc,  const std::string &Msg) const {
65   err() << Msg << "\n";
66   assert(ErrorLoc && "Location not specified!");
67   
68   // Scan backward to find the start of the line.
69   const char *LineStart = ErrorLoc;
70   while (LineStart != CurBuf->getBufferStart() && 
71          LineStart[-1] != '\n' && LineStart[-1] != '\r')
72     --LineStart;
73   // Get the end of the line.
74   const char *LineEnd = ErrorLoc;
75   while (LineEnd != CurBuf->getBufferEnd() && 
76          LineEnd[0] != '\n' && LineEnd[0] != '\r')
77     ++LineEnd;
78   // Print out the line.
79   cerr << std::string(LineStart, LineEnd) << "\n";
80   // Print out spaces before the carat.
81   for (const char *Pos = LineStart; Pos != ErrorLoc; ++Pos)
82     cerr << (*Pos == '\t' ? '\t' : ' ');
83   cerr << "^\n";
84 }
85
86 int TGLexer::getNextChar() {
87   char CurChar = *CurPtr++;
88   switch (CurChar) {
89   default:
90     return (unsigned char)CurChar;
91   case 0:
92     // A nul character in the stream is either the end of the current buffer or
93     // a random nul in the file.  Disambiguate that here.
94     if (CurPtr-1 != CurBuf->getBufferEnd())
95       return 0;  // Just whitespace.
96     
97     // If this is the end of an included file, pop the parent file off the
98     // include stack.
99     if (!IncludeStack.empty()) {
100       delete CurBuf;
101       CurBuf = IncludeStack.back().Buffer;
102       CurLineNo = IncludeStack.back().LineNo;
103       CurPtr = IncludeStack.back().CurPtr;
104       IncludeStack.pop_back();
105       return getNextChar();
106     }
107     
108     // Otherwise, return end of file.
109     --CurPtr;  // Another call to lex will return EOF again.  
110     return EOF;
111   case '\n':
112   case '\r':
113     // Handle the newline character by ignoring it and incrementing the line
114     // count.  However, be careful about 'dos style' files with \n\r in them.
115     // Only treat a \n\r or \r\n as a single line.
116     if ((*CurPtr == '\n' || (*CurPtr == '\r')) &&
117         *CurPtr != CurChar)
118       ++CurPtr;  // Eat the two char newline sequence.
119       
120     ++CurLineNo;
121     return '\n';
122   }  
123 }
124
125 int TGLexer::LexToken() {
126   TokStart = CurPtr;
127   // This always consumes at least one character.
128   int CurChar = getNextChar();
129
130   switch (CurChar) {
131   default:
132     // Handle letters: [a-zA-Z_]
133     if (isalpha(CurChar) || CurChar == '_')
134       return LexIdentifier();
135       
136     // Unknown character, return the char itself.
137     return (unsigned char)CurChar;
138   case EOF: return YYEOF;
139   case 0:
140   case ' ':
141   case '\t':
142   case '\n':
143   case '\r':
144     // Ignore whitespace.
145     return LexToken();
146   case '/':
147     // If this is the start of a // comment, skip until the end of the line or
148     // the end of the buffer.
149     if (*CurPtr == '/')
150       SkipBCPLComment();
151     else if (*CurPtr == '*') {
152       if (SkipCComment())
153         return YYERROR;
154     } else // Otherwise, return this / as a token.
155       return CurChar;
156     return LexToken();
157   case '-': case '+':
158   case '0': case '1': case '2': case '3': case '4': case '5': case '6':
159   case '7': case '8': case '9':  
160     return LexNumber();
161   case '"': return LexString();
162   case '$': return LexVarName();
163   case '[': return LexBracket();
164   case '!': return LexExclaim();
165   }
166 }
167
168 /// LexString - Lex "[^"]*"
169 int TGLexer::LexString() {
170   const char *StrStart = CurPtr;
171   
172   while (*CurPtr != '"') {
173     // If we hit the end of the buffer, report an error.
174     if (*CurPtr == 0 && CurPtr == CurBuf->getBufferEnd())
175       return ReturnError(StrStart, "End of file in string literal");
176     
177     if (*CurPtr == '\n' || *CurPtr == '\r')
178       return ReturnError(StrStart, "End of line in string literal");
179     
180     ++CurPtr;
181   }
182   
183   Filelval.StrVal = new std::string(StrStart, CurPtr);
184   ++CurPtr;
185   return STRVAL;
186 }
187
188 int TGLexer::LexVarName() {
189   if (!isalpha(CurPtr[0]) && CurPtr[0] != '_')
190     return '$'; // Invalid varname.
191   
192   // Otherwise, we're ok, consume the rest of the characters.
193   const char *VarNameStart = CurPtr++;
194   
195   while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
196     ++CurPtr;
197
198   Filelval.StrVal = new std::string(VarNameStart, CurPtr);
199   return VARNAME;
200 }
201
202
203 int TGLexer::LexIdentifier() {
204   // The first letter is [a-zA-Z_].
205   const char *IdentStart = CurPtr-1;
206   
207   // Match the rest of the identifier regex: [0-9a-zA-Z_]*
208   while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
209     ++CurPtr;
210   
211   // Check to see if this identifier is a keyword.
212   unsigned Len = CurPtr-IdentStart;
213   
214   if (Len == 3 && !memcmp(IdentStart, "int", 3)) return INT;
215   if (Len == 3 && !memcmp(IdentStart, "bit", 3)) return BIT;
216   if (Len == 4 && !memcmp(IdentStart, "bits", 4)) return BITS;
217   if (Len == 6 && !memcmp(IdentStart, "string", 6)) return STRING;
218   if (Len == 4 && !memcmp(IdentStart, "list", 4)) return LIST;
219   if (Len == 4 && !memcmp(IdentStart, "code", 4)) return CODE;
220   if (Len == 3 && !memcmp(IdentStart, "dag", 3)) return DAG;
221   
222   if (Len == 5 && !memcmp(IdentStart, "class", 5)) return CLASS;
223   if (Len == 3 && !memcmp(IdentStart, "def", 3)) return DEF;
224   if (Len == 4 && !memcmp(IdentStart, "defm", 4)) return DEFM;
225   if (Len == 10 && !memcmp(IdentStart, "multiclass", 10)) return MULTICLASS;
226   if (Len == 5 && !memcmp(IdentStart, "field", 5)) return FIELD;
227   if (Len == 3 && !memcmp(IdentStart, "let", 3)) return LET;
228   if (Len == 2 && !memcmp(IdentStart, "in", 2)) return IN;
229   
230   if (Len == 7 && !memcmp(IdentStart, "include", 7)) {
231     if (LexInclude()) return YYERROR;
232     return LexToken();
233   }
234     
235   Filelval.StrVal = new std::string(IdentStart, CurPtr);
236   return ID;
237 }
238
239 /// LexInclude - We just read the "include" token.  Get the string token that
240 /// comes next and enter the include.
241 bool TGLexer::LexInclude() {
242   // The token after the include must be a string.
243   int Tok = LexToken();
244   if (Tok == YYERROR) return true;
245   if (Tok != STRVAL) {
246     PrintError(getTokenStart(), "Expected filename after include");
247     return true;
248   }
249
250   // Get the string.
251   std::string Filename = *Filelval.StrVal;
252   delete Filelval.StrVal;
253
254   // Try to find the file.
255   MemoryBuffer *NewBuf = MemoryBuffer::getFile(&Filename[0], Filename.size());
256
257   // If the file didn't exist directly, see if it's in an include path.
258   for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
259     std::string IncFile = IncludeDirectories[i] + "/" + Filename;
260     NewBuf = MemoryBuffer::getFile(&IncFile[0], IncFile.size());
261   }
262     
263   if (NewBuf == 0) {
264     PrintError(getTokenStart(),
265                "Could not find include file '" + Filename + "'");
266     return true;
267   }
268   
269   // Save the line number and lex buffer of the includer.
270   IncludeStack.push_back(IncludeRec(CurBuf, CurPtr, CurLineNo));
271   
272   CurLineNo = 1;  // Reset line numbering.
273   CurBuf = NewBuf;
274   CurPtr = CurBuf->getBufferStart();
275   return false;
276 }
277
278 void TGLexer::SkipBCPLComment() {
279   ++CurPtr;  // skip the second slash.
280   while (1) {
281     switch (*CurPtr) {
282     case '\n':
283     case '\r':
284       return;  // Newline is end of comment.
285     case 0:
286       // If this is the end of the buffer, end the comment.
287       if (CurPtr == CurBuf->getBufferEnd())
288         return;
289       break;
290     }
291     // Otherwise, skip the character.
292     ++CurPtr;
293   }
294 }
295
296 /// SkipCComment - This skips C-style /**/ comments.  The only difference from C
297 /// is that we allow nesting.
298 bool TGLexer::SkipCComment() {
299   const char *CommentStart = CurPtr-1;
300   ++CurPtr;  // skip the star.
301   unsigned CommentDepth = 1;
302   
303   while (1) {
304     int CurChar = getNextChar();
305     switch (CurChar) {
306     case EOF:
307       PrintError(CommentStart, "Unterminated comment!");
308       return true;
309     case '*':
310       // End of the comment?
311       if (CurPtr[0] != '/') break;
312       
313       ++CurPtr;   // End the */.
314       if (--CommentDepth == 0)
315         return false;
316       break;
317     case '/':
318       // Start of a nested comment?
319       if (CurPtr[0] != '*') break;
320       ++CurPtr;
321       ++CommentDepth;
322       break;
323     }
324   }
325 }
326
327 /// LexNumber - Lex:
328 ///    [-+]?[0-9]+
329 ///    0x[0-9a-fA-F]+
330 ///    0b[01]+
331 int TGLexer::LexNumber() {
332   const char *NumStart = CurPtr-1;
333   
334   if (CurPtr[-1] == '0') {
335     if (CurPtr[0] == 'x') {
336       ++CurPtr;
337       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       Filelval.IntVal = strtoll(NumStart, 0, 16);
346
347       return INTVAL;
348     } else if (CurPtr[0] == 'b') {
349       ++CurPtr;
350       NumStart = CurPtr;
351       while (CurPtr[0] == '0' || CurPtr[0] == '1')
352         ++CurPtr;
353
354       // Requires at least one binary digit.
355       if (CurPtr == NumStart)
356         return ReturnError(CurPtr-2, "Invalid binary number");
357
358       Filelval.IntVal = strtoll(NumStart, 0, 2);
359       return INTVAL;
360     }
361   }
362
363   // Check for a sign without a digit.
364   if (CurPtr[-1] == '-' || CurPtr[-1] == '+') {
365     if (!isdigit(CurPtr[0]))
366       return CurPtr[-1];
367   }
368   
369   while (isdigit(CurPtr[0]))
370     ++CurPtr;
371
372   Filelval.IntVal = strtoll(NumStart, 0, 10);
373   return INTVAL;
374 }
375
376 /// LexBracket - We just read '['.  If this is a code block, return it,
377 /// otherwise return the bracket.  Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
378 int TGLexer::LexBracket() {
379   if (CurPtr[0] != '{')
380     return '[';
381   ++CurPtr;
382   const char *CodeStart = CurPtr;
383   while (1) {
384     int Char = getNextChar();
385     if (Char == EOF) break;
386     
387     if (Char != '}') continue;
388     
389     Char = getNextChar();
390     if (Char == EOF) break;
391     if (Char == ']') {
392       Filelval.StrVal = new std::string(CodeStart, CurPtr-2);
393       return CODEFRAGMENT;
394     }
395   }
396   
397   return ReturnError(CodeStart-2, "Unterminated Code Block");
398 }
399
400 /// LexExclaim - Lex '!' and '![a-zA-Z]+'.
401 int TGLexer::LexExclaim() {
402   if (!isalpha(*CurPtr))
403     return '!';
404   
405   const char *Start = CurPtr++;
406   while (isalpha(*CurPtr))
407     ++CurPtr;
408   
409   // Check to see which operator this is.
410   unsigned Len = CurPtr-Start;
411   
412   if (Len == 3 && !memcmp(Start, "con", 3)) return CONCATTOK;
413   if (Len == 3 && !memcmp(Start, "sra", 3)) return SRATOK;
414   if (Len == 3 && !memcmp(Start, "srl", 3)) return SRLTOK;
415   if (Len == 3 && !memcmp(Start, "shl", 3)) return SHLTOK;
416   if (Len == 9 && !memcmp(Start, "strconcat", 9)) return STRCONCATTOK;
417   
418   return ReturnError(Start-1, "Unknown operator");
419 }
420
421 //===----------------------------------------------------------------------===//
422 //  Interfaces used by the Bison parser.
423 //===----------------------------------------------------------------------===//
424
425 int Fileparse();
426 static TGLexer *TheLexer;
427
428 namespace llvm {
429   
430 std::ostream &err() {
431   return TheLexer->err();
432 }
433
434 /// ParseFile - this function begins the parsing of the specified tablegen
435 /// file.
436 ///
437 void ParseFile(const std::string &Filename, 
438                const std::vector<std::string> &IncludeDirs) {
439   std::string ErrorStr;
440   MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(&Filename[0], Filename.size(),
441                                                  &ErrorStr);
442   if (F == 0) {
443     cerr << "Could not open input file '" + Filename + "': " << ErrorStr <<"\n";
444     exit(1);
445   }
446   
447   assert(!TheLexer && "Lexer isn't reentrant yet!");
448   TheLexer = new TGLexer(F);
449   
450   // Record the location of the include directory so that the lexer can find
451   // it later.
452   TheLexer->setIncludeDirs(IncludeDirs);
453   
454   Fileparse();
455   
456   // Cleanup
457   delete TheLexer;
458   TheLexer = 0;
459 }
460 } // End llvm namespace
461
462
463 int Filelex() {
464   assert(TheLexer && "No lexer setup yet!");
465   int Tok = TheLexer->LexToken();
466   if (Tok == YYERROR)
467     exit(1);
468   return Tok;
469 }