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