Add support for lexing single quotes like 'c'.
[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 /// LexFloatLiteral: [0-9]*[.][0-9]*([eE][+-]?[0-9]*)?
68 ///
69 /// The leading integral digit sequence and dot should have already been
70 /// consumed, some or all of the fractional digit sequence *can* have been
71 /// consumed.
72 AsmToken AsmLexer::LexFloatLiteral() {
73   // Skip the fractional digit sequence.
74   while (isdigit(*CurPtr))
75     ++CurPtr;
76
77   // Check for exponent; we intentionally accept a slighlty wider set of
78   // literals here and rely on the upstream client to reject invalid ones (e.g.,
79   // "1e+").
80   if (*CurPtr == 'e' || *CurPtr == 'E') {
81     ++CurPtr;
82     if (*CurPtr == '-' || *CurPtr == '+')
83       ++CurPtr;
84     while (isdigit(*CurPtr))
85       ++CurPtr;
86   }
87
88   return AsmToken(AsmToken::Real,
89                   StringRef(TokStart, CurPtr - TokStart));
90 }
91
92 /// LexIdentifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*
93 static bool IsIdentifierChar(char c) {
94   return isalnum(c) || c == '_' || c == '$' || c == '.' || c == '@';
95 }
96 AsmToken AsmLexer::LexIdentifier() {
97   // Check for floating point literals.
98   if (CurPtr[-1] == '.' && isdigit(*CurPtr)) {
99     // Disambiguate a .1243foo identifier from a floating literal.
100     while (isdigit(*CurPtr))
101       ++CurPtr;
102     if (*CurPtr == 'e' || *CurPtr == 'E' || !IsIdentifierChar(*CurPtr))
103       return LexFloatLiteral();
104   }
105
106   while (IsIdentifierChar(*CurPtr))
107     ++CurPtr;
108   
109   // Handle . as a special case.
110   if (CurPtr == TokStart+1 && TokStart[0] == '.')
111     return AsmToken(AsmToken::Dot, StringRef(TokStart, 1));
112   
113   return AsmToken(AsmToken::Identifier, StringRef(TokStart, CurPtr - TokStart));
114 }
115
116 /// LexSlash: Slash: /
117 ///           C-Style Comment: /* ... */
118 AsmToken AsmLexer::LexSlash() {
119   switch (*CurPtr) {
120   case '*': break; // C style comment.
121   case '/': return ++CurPtr, LexLineComment();
122   default:  return AsmToken(AsmToken::Slash, StringRef(CurPtr-1, 1));
123   }
124
125   // C Style comment.
126   ++CurPtr;  // skip the star.
127   while (1) {
128     int CurChar = getNextChar();
129     switch (CurChar) {
130     case EOF:
131       return ReturnError(TokStart, "unterminated comment");
132     case '*':
133       // End of the comment?
134       if (CurPtr[0] != '/') break;
135       
136       ++CurPtr;   // End the */.
137       return LexToken();
138     }
139   }
140 }
141
142 /// LexLineComment: Comment: #[^\n]*
143 ///                        : //[^\n]*
144 AsmToken AsmLexer::LexLineComment() {
145   // FIXME: This is broken if we happen to a comment at the end of a file, which
146   // was .included, and which doesn't end with a newline.
147   int CurChar = getNextChar();
148   while (CurChar != '\n' && CurChar != '\n' && CurChar != EOF)
149     CurChar = getNextChar();
150   
151   if (CurChar == EOF)
152     return AsmToken(AsmToken::Eof, StringRef(CurPtr, 0));
153   return AsmToken(AsmToken::EndOfStatement, StringRef(CurPtr, 0));
154 }
155
156 static void SkipIgnoredIntegerSuffix(const char *&CurPtr) {
157   if (CurPtr[0] == 'L' && CurPtr[1] == 'L')
158     CurPtr += 2;
159   if (CurPtr[0] == 'U' && CurPtr[1] == 'L' && CurPtr[2] == 'L')
160     CurPtr += 3;
161 }
162
163 /// LexDigit: First character is [0-9].
164 ///   Local Label: [0-9][:]
165 ///   Forward/Backward Label: [0-9][fb]
166 ///   Binary integer: 0b[01]+
167 ///   Octal integer: 0[0-7]+
168 ///   Hex integer: 0x[0-9a-fA-F]+
169 ///   Decimal integer: [1-9][0-9]*
170 AsmToken AsmLexer::LexDigit() {
171   // Decimal integer: [1-9][0-9]*
172   if (CurPtr[-1] != '0' || CurPtr[0] == '.') {
173     while (isdigit(*CurPtr))
174       ++CurPtr;
175
176     // Check for floating point literals.
177     if (*CurPtr == '.' || *CurPtr == 'e') {
178       ++CurPtr;
179       return LexFloatLiteral();
180     }
181
182     StringRef Result(TokStart, CurPtr - TokStart);
183
184     long long Value;
185     if (Result.getAsInteger(10, Value)) {
186       // We have to handle minint_as_a_positive_value specially, because
187       // - minint_as_a_positive_value = minint and it is valid.
188       if (Result == "9223372036854775808")
189         Value = -9223372036854775808ULL;
190       else
191         return ReturnError(TokStart, "Invalid decimal number");
192     }
193     
194     // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
195     // suffixes on integer literals.
196     SkipIgnoredIntegerSuffix(CurPtr);
197     
198     return AsmToken(AsmToken::Integer, Result, Value);
199   }
200   
201   if (*CurPtr == 'b') {
202     ++CurPtr;
203     // See if we actually have "0b" as part of something like "jmp 0b\n"
204     if (!isdigit(CurPtr[0])) {
205       --CurPtr;
206       StringRef Result(TokStart, CurPtr - TokStart);
207       return AsmToken(AsmToken::Integer, Result, 0);
208     }
209     const char *NumStart = CurPtr;
210     while (CurPtr[0] == '0' || CurPtr[0] == '1')
211       ++CurPtr;
212     
213     // Requires at least one binary digit.
214     if (CurPtr == NumStart)
215       return ReturnError(TokStart, "Invalid binary number");
216     
217     StringRef Result(TokStart, CurPtr - TokStart);
218     
219     long long Value;
220     if (Result.substr(2).getAsInteger(2, Value))
221       return ReturnError(TokStart, "Invalid binary 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, Result, Value);
228   }
229  
230   if (*CurPtr == 'x') {
231     ++CurPtr;
232     const char *NumStart = CurPtr;
233     while (isxdigit(CurPtr[0]))
234       ++CurPtr;
235     
236     // Requires at least one hex digit.
237     if (CurPtr == NumStart)
238       return ReturnError(CurPtr-2, "Invalid hexadecimal number");
239
240     unsigned long long Result;
241     if (StringRef(TokStart, CurPtr - TokStart).getAsInteger(0, Result))
242       return ReturnError(TokStart, "Invalid hexadecimal number");
243       
244     // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
245     // suffixes on integer literals.
246     SkipIgnoredIntegerSuffix(CurPtr);
247     
248     return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart),
249                     (int64_t)Result);
250   }
251   
252   // Must be an octal number, it starts with 0.
253   while (*CurPtr >= '0' && *CurPtr <= '7')
254     ++CurPtr;
255   
256   StringRef Result(TokStart, CurPtr - TokStart);
257   long long Value;
258   if (Result.getAsInteger(8, Value))
259     return ReturnError(TokStart, "Invalid octal number");
260   
261   // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
262   // suffixes on integer literals.
263   SkipIgnoredIntegerSuffix(CurPtr);
264   
265   return AsmToken(AsmToken::Integer, Result, Value);
266 }
267
268 /// LexSingleQuote: Integer: 'b'
269 AsmToken AsmLexer::LexSingleQuote() {
270   int CurChar = getNextChar();
271
272   if (CurChar == '\\')
273     CurChar = getNextChar();
274
275   if (CurChar == EOF)
276     return ReturnError(TokStart, "unterminated single quote");
277
278   CurChar = getNextChar();
279
280   if (CurChar != '\'')
281     return ReturnError(TokStart, "single quote way too long");
282
283   // The idea here being that 'c' is basically just an integral
284   // constant.
285   StringRef Res = StringRef(TokStart,CurPtr - TokStart);
286   long long Value;
287
288   if (Res.startswith("\'\\")) {
289     char theChar = Res[2];
290     switch (theChar) {
291       default: Value = theChar; break;
292       case '\'': Value = '\''; break;
293       case 't': Value = '\t'; break;
294       case 'n': Value = '\n'; break;
295       case 'b': Value = '\b'; break;
296     }
297   } else
298     Value = TokStart[1];
299
300   return AsmToken(AsmToken::Integer, Res, Value); 
301 }
302
303
304 /// LexQuote: String: "..."
305 AsmToken AsmLexer::LexQuote() {
306   int CurChar = getNextChar();
307   // TODO: does gas allow multiline string constants?
308   while (CurChar != '"') {
309     if (CurChar == '\\') {
310       // Allow \", etc.
311       CurChar = getNextChar();
312     }
313     
314     if (CurChar == EOF)
315       return ReturnError(TokStart, "unterminated string constant");
316
317     CurChar = getNextChar();
318   }
319   
320   return AsmToken(AsmToken::String, StringRef(TokStart, CurPtr - TokStart));
321 }
322
323 StringRef AsmLexer::LexUntilEndOfStatement() {
324   TokStart = CurPtr;
325
326   while (!isAtStartOfComment(*CurPtr) && // Start of line comment.
327           *CurPtr != ';' &&  // End of statement marker.
328          *CurPtr != '\n' &&
329          *CurPtr != '\r' &&
330          (*CurPtr != 0 || CurPtr != CurBuf->getBufferEnd())) {
331     ++CurPtr;
332   }
333   return StringRef(TokStart, CurPtr-TokStart);
334 }
335
336 bool AsmLexer::isAtStartOfComment(char Char) {
337   // FIXME: This won't work for multi-character comment indicators like "//".
338   return Char == *MAI.getCommentString();
339 }
340
341 AsmToken AsmLexer::LexToken() {
342   TokStart = CurPtr;
343   // This always consumes at least one character.
344   int CurChar = getNextChar();
345   
346   if (isAtStartOfComment(CurChar))
347     return LexLineComment();
348
349   switch (CurChar) {
350   default:
351     // Handle identifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*
352     if (isalpha(CurChar) || CurChar == '_' || CurChar == '.')
353       return LexIdentifier();
354     
355     // Unknown character, emit an error.
356     return ReturnError(TokStart, "invalid character in input");
357   case EOF: return AsmToken(AsmToken::Eof, StringRef(TokStart, 0));
358   case 0:
359   case ' ':
360   case '\t':
361     // Ignore whitespace.
362     return LexToken();
363   case '\n': // FALL THROUGH.
364   case '\r': // FALL THROUGH.
365   case ';': return AsmToken(AsmToken::EndOfStatement, StringRef(TokStart, 1));
366   case ':': return AsmToken(AsmToken::Colon, StringRef(TokStart, 1));
367   case '+': return AsmToken(AsmToken::Plus, StringRef(TokStart, 1));
368   case '-': return AsmToken(AsmToken::Minus, StringRef(TokStart, 1));
369   case '~': return AsmToken(AsmToken::Tilde, StringRef(TokStart, 1));
370   case '(': return AsmToken(AsmToken::LParen, StringRef(TokStart, 1));
371   case ')': return AsmToken(AsmToken::RParen, StringRef(TokStart, 1));
372   case '[': return AsmToken(AsmToken::LBrac, StringRef(TokStart, 1));
373   case ']': return AsmToken(AsmToken::RBrac, StringRef(TokStart, 1));
374   case '{': return AsmToken(AsmToken::LCurly, StringRef(TokStart, 1));
375   case '}': return AsmToken(AsmToken::RCurly, StringRef(TokStart, 1));
376   case '*': return AsmToken(AsmToken::Star, StringRef(TokStart, 1));
377   case ',': return AsmToken(AsmToken::Comma, StringRef(TokStart, 1));
378   case '$': return AsmToken(AsmToken::Dollar, StringRef(TokStart, 1));
379   case '@': return AsmToken(AsmToken::At, StringRef(TokStart, 1));
380   case '=': 
381     if (*CurPtr == '=')
382       return ++CurPtr, AsmToken(AsmToken::EqualEqual, StringRef(TokStart, 2));
383     return AsmToken(AsmToken::Equal, StringRef(TokStart, 1));
384   case '|': 
385     if (*CurPtr == '|')
386       return ++CurPtr, AsmToken(AsmToken::PipePipe, StringRef(TokStart, 2));
387     return AsmToken(AsmToken::Pipe, StringRef(TokStart, 1));
388   case '^': return AsmToken(AsmToken::Caret, StringRef(TokStart, 1));
389   case '&': 
390     if (*CurPtr == '&')
391       return ++CurPtr, AsmToken(AsmToken::AmpAmp, StringRef(TokStart, 2));
392     return AsmToken(AsmToken::Amp, StringRef(TokStart, 1));
393   case '!': 
394     if (*CurPtr == '=')
395       return ++CurPtr, AsmToken(AsmToken::ExclaimEqual, StringRef(TokStart, 2));
396     return AsmToken(AsmToken::Exclaim, StringRef(TokStart, 1));
397   case '%': return AsmToken(AsmToken::Percent, StringRef(TokStart, 1));
398   case '/': return LexSlash();
399   case '#': return AsmToken(AsmToken::Hash, StringRef(TokStart, 1));
400   case '\'': return LexSingleQuote();
401   case '"': return LexQuote();
402   case '0': case '1': case '2': case '3': case '4':
403   case '5': case '6': case '7': case '8': case '9':
404     return LexDigit();
405   case '<':
406     switch (*CurPtr) {
407     case '<': return ++CurPtr, AsmToken(AsmToken::LessLess, 
408                                         StringRef(TokStart, 2));
409     case '=': return ++CurPtr, AsmToken(AsmToken::LessEqual, 
410                                         StringRef(TokStart, 2));
411     case '>': return ++CurPtr, AsmToken(AsmToken::LessGreater, 
412                                         StringRef(TokStart, 2));
413     default: return AsmToken(AsmToken::Less, StringRef(TokStart, 1));
414     }
415   case '>':
416     switch (*CurPtr) {
417     case '>': return ++CurPtr, AsmToken(AsmToken::GreaterGreater, 
418                                         StringRef(TokStart, 2));
419     case '=': return ++CurPtr, AsmToken(AsmToken::GreaterEqual, 
420                                         StringRef(TokStart, 2));
421     default: return AsmToken(AsmToken::Greater, StringRef(TokStart, 1));
422     }
423       
424   // TODO: Quoted identifiers (objc methods etc)
425   // local labels: [0-9][:]
426   // Forward/backward labels: [0-9][fb]
427   // Integers, fp constants, character constants.
428   }
429 }