MC/Lexer: Add 'Real' token type for floating point literals.
[oota-llvm.git] / lib / MC / MCParser / AsmLexer.cpp
1 //===- AsmLexer.cpp - Lexer for Assembly Files ----------------------------===//
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 class implements the lexer for assembly files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/MC/MCParser/AsmLexer.h"
15 #include "llvm/Support/SMLoc.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include <cerrno>
19 #include <cstdio>
20 #include <cstdlib>
21 using namespace llvm;
22
23 AsmLexer::AsmLexer(const MCAsmInfo &_MAI) : MAI(_MAI)  {
24   CurBuf = NULL;
25   CurPtr = NULL;
26 }
27
28 AsmLexer::~AsmLexer() {
29 }
30
31 void AsmLexer::setBuffer(const MemoryBuffer *buf, const char *ptr) {
32   CurBuf = buf;
33   
34   if (ptr)
35     CurPtr = ptr;
36   else
37     CurPtr = CurBuf->getBufferStart();
38   
39   TokStart = 0;
40 }
41
42 /// ReturnError - Set the error to the specified string at the specified
43 /// location.  This is defined to always return AsmToken::Error.
44 AsmToken AsmLexer::ReturnError(const char *Loc, const std::string &Msg) {
45   SetError(SMLoc::getFromPointer(Loc), Msg);
46   
47   return AsmToken(AsmToken::Error, StringRef(Loc, 0));
48 }
49
50 int AsmLexer::getNextChar() {
51   char CurChar = *CurPtr++;
52   switch (CurChar) {
53   default:
54     return (unsigned char)CurChar;
55   case 0:
56     // A nul character in the stream is either the end of the current buffer or
57     // a random nul in the file.  Disambiguate that here.
58     if (CurPtr-1 != CurBuf->getBufferEnd())
59       return 0;  // Just whitespace.
60     
61     // Otherwise, return end of file.
62     --CurPtr;  // Another call to lex will return EOF again.  
63     return EOF;
64   }
65 }
66
67 /// LexIdentifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*
68 static bool IsIdentifierChar(char c) {
69   return isalnum(c) || c == '_' || c == '$' || c == '.' || c == '@';
70 }
71 AsmToken AsmLexer::LexIdentifier() {
72   // Check for floating point literals.
73   if (CurPtr[-1] == '.' && isdigit(*CurPtr)) {
74     while (isdigit(*CurPtr))
75       ++CurPtr;
76     if (!IsIdentifierChar(*CurPtr)) {
77       return AsmToken(AsmToken::Real,
78                       StringRef(TokStart, CurPtr - TokStart));
79     }
80   }
81
82   while (IsIdentifierChar(*CurPtr))
83     ++CurPtr;
84   
85   // Handle . as a special case.
86   if (CurPtr == TokStart+1 && TokStart[0] == '.')
87     return AsmToken(AsmToken::Dot, StringRef(TokStart, 1));
88   
89   return AsmToken(AsmToken::Identifier, StringRef(TokStart, CurPtr - TokStart));
90 }
91
92 /// LexSlash: Slash: /
93 ///           C-Style Comment: /* ... */
94 AsmToken AsmLexer::LexSlash() {
95   switch (*CurPtr) {
96   case '*': break; // C style comment.
97   case '/': return ++CurPtr, LexLineComment();
98   default:  return AsmToken(AsmToken::Slash, StringRef(CurPtr, 1));
99   }
100
101   // C Style comment.
102   ++CurPtr;  // skip the star.
103   while (1) {
104     int CurChar = getNextChar();
105     switch (CurChar) {
106     case EOF:
107       return ReturnError(TokStart, "unterminated comment");
108     case '*':
109       // End of the comment?
110       if (CurPtr[0] != '/') break;
111       
112       ++CurPtr;   // End the */.
113       return LexToken();
114     }
115   }
116 }
117
118 /// LexLineComment: Comment: #[^\n]*
119 ///                        : //[^\n]*
120 AsmToken AsmLexer::LexLineComment() {
121   // FIXME: This is broken if we happen to a comment at the end of a file, which
122   // was .included, and which doesn't end with a newline.
123   int CurChar = getNextChar();
124   while (CurChar != '\n' && CurChar != '\n' && CurChar != EOF)
125     CurChar = getNextChar();
126   
127   if (CurChar == EOF)
128     return AsmToken(AsmToken::Eof, StringRef(CurPtr, 0));
129   return AsmToken(AsmToken::EndOfStatement, StringRef(CurPtr, 0));
130 }
131
132 static void SkipIgnoredIntegerSuffix(const char *&CurPtr) {
133   if (CurPtr[0] == 'L' && CurPtr[1] == 'L')
134     CurPtr += 2;
135   if (CurPtr[0] == 'U' && CurPtr[1] == 'L' && CurPtr[2] == 'L')
136     CurPtr += 3;
137 }
138
139 /// LexDigit: First character is [0-9].
140 ///   Local Label: [0-9][:]
141 ///   Forward/Backward Label: [0-9][fb]
142 ///   Binary integer: 0b[01]+
143 ///   Octal integer: 0[0-7]+
144 ///   Hex integer: 0x[0-9a-fA-F]+
145 ///   Decimal integer: [1-9][0-9]*
146 AsmToken AsmLexer::LexDigit() {
147   // Decimal integer: [1-9][0-9]*
148   if (CurPtr[-1] != '0') {
149     while (isdigit(*CurPtr))
150       ++CurPtr;
151
152     // Check for floating point literals.
153     if (*CurPtr == '.') {
154       ++CurPtr;
155       while (isdigit(*CurPtr))
156         ++CurPtr;
157
158       return AsmToken(AsmToken::Real, StringRef(TokStart, CurPtr - TokStart));
159     }
160
161     StringRef Result(TokStart, CurPtr - TokStart);
162
163     long long Value;
164     if (Result.getAsInteger(10, Value)) {
165       // We have to handle minint_as_a_positive_value specially, because
166       // - minint_as_a_positive_value = minint and it is valid.
167       if (Result == "9223372036854775808")
168         Value = -9223372036854775808ULL;
169       else
170         return ReturnError(TokStart, "Invalid decimal number");
171     }
172     
173     // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
174     // suffixes on integer literals.
175     SkipIgnoredIntegerSuffix(CurPtr);
176     
177     return AsmToken(AsmToken::Integer, Result, Value);
178   }
179   
180   if (*CurPtr == 'b') {
181     ++CurPtr;
182     // See if we actually have "0b" as part of something like "jmp 0b\n"
183     if (!isdigit(CurPtr[0])) {
184       --CurPtr;
185       StringRef Result(TokStart, CurPtr - TokStart);
186       return AsmToken(AsmToken::Integer, Result, 0);
187     }
188     const char *NumStart = CurPtr;
189     while (CurPtr[0] == '0' || CurPtr[0] == '1')
190       ++CurPtr;
191     
192     // Requires at least one binary digit.
193     if (CurPtr == NumStart)
194       return ReturnError(TokStart, "Invalid binary number");
195     
196     StringRef Result(TokStart, CurPtr - TokStart);
197     
198     long long Value;
199     if (Result.substr(2).getAsInteger(2, Value))
200       return ReturnError(TokStart, "Invalid binary number");
201     
202     // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
203     // suffixes on integer literals.
204     SkipIgnoredIntegerSuffix(CurPtr);
205     
206     return AsmToken(AsmToken::Integer, Result, Value);
207   }
208  
209   if (*CurPtr == 'x') {
210     ++CurPtr;
211     const char *NumStart = CurPtr;
212     while (isxdigit(CurPtr[0]))
213       ++CurPtr;
214     
215     // Requires at least one hex digit.
216     if (CurPtr == NumStart)
217       return ReturnError(CurPtr-2, "Invalid hexadecimal number");
218
219     unsigned long long Result;
220     if (StringRef(TokStart, CurPtr - TokStart).getAsInteger(0, Result))
221       return ReturnError(TokStart, "Invalid hexadecimal number");
222       
223     // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
224     // suffixes on integer literals.
225     SkipIgnoredIntegerSuffix(CurPtr);
226     
227     return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart),
228                     (int64_t)Result);
229   }
230   
231   // Must be an octal number, it starts with 0.
232   while (*CurPtr >= '0' && *CurPtr <= '7')
233     ++CurPtr;
234   
235   StringRef Result(TokStart, CurPtr - TokStart);
236   long long Value;
237   if (Result.getAsInteger(8, Value))
238     return ReturnError(TokStart, "Invalid octal number");
239   
240   // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
241   // suffixes on integer literals.
242   SkipIgnoredIntegerSuffix(CurPtr);
243   
244   return AsmToken(AsmToken::Integer, Result, Value);
245 }
246
247 /// LexQuote: String: "..."
248 AsmToken AsmLexer::LexQuote() {
249   int CurChar = getNextChar();
250   // TODO: does gas allow multiline string constants?
251   while (CurChar != '"') {
252     if (CurChar == '\\') {
253       // Allow \", etc.
254       CurChar = getNextChar();
255     }
256     
257     if (CurChar == EOF)
258       return ReturnError(TokStart, "unterminated string constant");
259
260     CurChar = getNextChar();
261   }
262   
263   return AsmToken(AsmToken::String, StringRef(TokStart, CurPtr - TokStart));
264 }
265
266 StringRef AsmLexer::LexUntilEndOfStatement() {
267   TokStart = CurPtr;
268
269   while (!isAtStartOfComment(*CurPtr) && // Start of line comment.
270           *CurPtr != ';' &&  // End of statement marker.
271          *CurPtr != '\n' &&
272          *CurPtr != '\r' &&
273          (*CurPtr != 0 || CurPtr != CurBuf->getBufferEnd())) {
274     ++CurPtr;
275   }
276   return StringRef(TokStart, CurPtr-TokStart);
277 }
278
279 bool AsmLexer::isAtStartOfComment(char Char) {
280   // FIXME: This won't work for multi-character comment indicators like "//".
281   return Char == *MAI.getCommentString();
282 }
283
284 AsmToken AsmLexer::LexToken() {
285   TokStart = CurPtr;
286   // This always consumes at least one character.
287   int CurChar = getNextChar();
288   
289   if (isAtStartOfComment(CurChar))
290     return LexLineComment();
291
292   switch (CurChar) {
293   default:
294     // Handle identifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*
295     if (isalpha(CurChar) || CurChar == '_' || CurChar == '.')
296       return LexIdentifier();
297     
298     // Unknown character, emit an error.
299     return ReturnError(TokStart, "invalid character in input");
300   case EOF: return AsmToken(AsmToken::Eof, StringRef(TokStart, 0));
301   case 0:
302   case ' ':
303   case '\t':
304     // Ignore whitespace.
305     return LexToken();
306   case '\n': // FALL THROUGH.
307   case '\r': // FALL THROUGH.
308   case ';': return AsmToken(AsmToken::EndOfStatement, StringRef(TokStart, 1));
309   case ':': return AsmToken(AsmToken::Colon, StringRef(TokStart, 1));
310   case '+': return AsmToken(AsmToken::Plus, StringRef(TokStart, 1));
311   case '-': return AsmToken(AsmToken::Minus, StringRef(TokStart, 1));
312   case '~': return AsmToken(AsmToken::Tilde, StringRef(TokStart, 1));
313   case '(': return AsmToken(AsmToken::LParen, StringRef(TokStart, 1));
314   case ')': return AsmToken(AsmToken::RParen, StringRef(TokStart, 1));
315   case '[': return AsmToken(AsmToken::LBrac, StringRef(TokStart, 1));
316   case ']': return AsmToken(AsmToken::RBrac, StringRef(TokStart, 1));
317   case '{': return AsmToken(AsmToken::LCurly, StringRef(TokStart, 1));
318   case '}': return AsmToken(AsmToken::RCurly, StringRef(TokStart, 1));
319   case '*': return AsmToken(AsmToken::Star, StringRef(TokStart, 1));
320   case ',': return AsmToken(AsmToken::Comma, StringRef(TokStart, 1));
321   case '$': return AsmToken(AsmToken::Dollar, StringRef(TokStart, 1));
322   case '@': return AsmToken(AsmToken::At, StringRef(TokStart, 1));
323   case '=': 
324     if (*CurPtr == '=')
325       return ++CurPtr, AsmToken(AsmToken::EqualEqual, StringRef(TokStart, 2));
326     return AsmToken(AsmToken::Equal, StringRef(TokStart, 1));
327   case '|': 
328     if (*CurPtr == '|')
329       return ++CurPtr, AsmToken(AsmToken::PipePipe, StringRef(TokStart, 2));
330     return AsmToken(AsmToken::Pipe, StringRef(TokStart, 1));
331   case '^': return AsmToken(AsmToken::Caret, StringRef(TokStart, 1));
332   case '&': 
333     if (*CurPtr == '&')
334       return ++CurPtr, AsmToken(AsmToken::AmpAmp, StringRef(TokStart, 2));
335     return AsmToken(AsmToken::Amp, StringRef(TokStart, 1));
336   case '!': 
337     if (*CurPtr == '=')
338       return ++CurPtr, AsmToken(AsmToken::ExclaimEqual, StringRef(TokStart, 2));
339     return AsmToken(AsmToken::Exclaim, StringRef(TokStart, 1));
340   case '%': return AsmToken(AsmToken::Percent, StringRef(TokStart, 1));
341   case '/': return LexSlash();
342   case '#': return AsmToken(AsmToken::Hash, StringRef(TokStart, 1));
343   case '"': return LexQuote();
344   case '0': case '1': case '2': case '3': case '4':
345   case '5': case '6': case '7': case '8': case '9':
346     return LexDigit();
347   case '<':
348     switch (*CurPtr) {
349     case '<': return ++CurPtr, AsmToken(AsmToken::LessLess, 
350                                         StringRef(TokStart, 2));
351     case '=': return ++CurPtr, AsmToken(AsmToken::LessEqual, 
352                                         StringRef(TokStart, 2));
353     case '>': return ++CurPtr, AsmToken(AsmToken::LessGreater, 
354                                         StringRef(TokStart, 2));
355     default: return AsmToken(AsmToken::Less, StringRef(TokStart, 1));
356     }
357   case '>':
358     switch (*CurPtr) {
359     case '>': return ++CurPtr, AsmToken(AsmToken::GreaterGreater, 
360                                         StringRef(TokStart, 2));
361     case '=': return ++CurPtr, AsmToken(AsmToken::GreaterEqual, 
362                                         StringRef(TokStart, 2));
363     default: return AsmToken(AsmToken::Greater, StringRef(TokStart, 1));
364     }
365       
366   // TODO: Quoted identifiers (objc methods etc)
367   // local labels: [0-9][:]
368   // Forward/backward labels: [0-9][fb]
369   // Integers, fp constants, character constants.
370   }
371 }