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