[ms-inline asm] Add support for lexing binary integers with a [bB] suffix.
[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/MC/MCAsmInfo.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Support/SMLoc.h"
18 #include <cctype>
19 #include <cerrno>
20 #include <cstdio>
21 #include <cstdlib>
22 using namespace llvm;
23
24 AsmLexer::AsmLexer(const MCAsmInfo &_MAI) : MAI(_MAI)  {
25   CurBuf = NULL;
26   CurPtr = NULL;
27   isAtStartOfLine = true;
28 }
29
30 AsmLexer::~AsmLexer() {
31 }
32
33 void AsmLexer::setBuffer(const MemoryBuffer *buf, const char *ptr) {
34   CurBuf = buf;
35
36   if (ptr)
37     CurPtr = ptr;
38   else
39     CurPtr = CurBuf->getBufferStart();
40
41   TokStart = 0;
42 }
43
44 /// ReturnError - Set the error to the specified string at the specified
45 /// location.  This is defined to always return AsmToken::Error.
46 AsmToken AsmLexer::ReturnError(const char *Loc, const std::string &Msg) {
47   SetError(SMLoc::getFromPointer(Loc), Msg);
48
49   return AsmToken(AsmToken::Error, StringRef(Loc, 0));
50 }
51
52 int AsmLexer::getNextChar() {
53   char CurChar = *CurPtr++;
54   switch (CurChar) {
55   default:
56     return (unsigned char)CurChar;
57   case 0:
58     // A nul character in the stream is either the end of the current buffer or
59     // a random nul in the file.  Disambiguate that here.
60     if (CurPtr-1 != CurBuf->getBufferEnd())
61       return 0;  // Just whitespace.
62
63     // Otherwise, return end of file.
64     --CurPtr;  // Another call to lex will return EOF again.
65     return EOF;
66   }
67 }
68
69 /// LexFloatLiteral: [0-9]*[.][0-9]*([eE][+-]?[0-9]*)?
70 ///
71 /// The leading integral digit sequence and dot should have already been
72 /// consumed, some or all of the fractional digit sequence *can* have been
73 /// consumed.
74 AsmToken AsmLexer::LexFloatLiteral() {
75   // Skip the fractional digit sequence.
76   while (isdigit(*CurPtr))
77     ++CurPtr;
78
79   // Check for exponent; we intentionally accept a slighlty wider set of
80   // literals here and rely on the upstream client to reject invalid ones (e.g.,
81   // "1e+").
82   if (*CurPtr == 'e' || *CurPtr == 'E') {
83     ++CurPtr;
84     if (*CurPtr == '-' || *CurPtr == '+')
85       ++CurPtr;
86     while (isdigit(*CurPtr))
87       ++CurPtr;
88   }
89
90   return AsmToken(AsmToken::Real,
91                   StringRef(TokStart, CurPtr - TokStart));
92 }
93
94 /// LexIdentifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*
95 static bool IsIdentifierChar(char c) {
96   return isalnum(c) || c == '_' || c == '$' || c == '.' || c == '@';
97 }
98 AsmToken AsmLexer::LexIdentifier() {
99   // Check for floating point literals.
100   if (CurPtr[-1] == '.' && isdigit(*CurPtr)) {
101     // Disambiguate a .1243foo identifier from a floating literal.
102     while (isdigit(*CurPtr))
103       ++CurPtr;
104     if (*CurPtr == 'e' || *CurPtr == 'E' || !IsIdentifierChar(*CurPtr))
105       return LexFloatLiteral();
106   }
107
108   while (IsIdentifierChar(*CurPtr))
109     ++CurPtr;
110
111   // Handle . as a special case.
112   if (CurPtr == TokStart+1 && TokStart[0] == '.')
113     return AsmToken(AsmToken::Dot, StringRef(TokStart, 1));
114
115   return AsmToken(AsmToken::Identifier, StringRef(TokStart, CurPtr - TokStart));
116 }
117
118 /// LexSlash: Slash: /
119 ///           C-Style Comment: /* ... */
120 AsmToken AsmLexer::LexSlash() {
121   switch (*CurPtr) {
122   case '*': break; // C style comment.
123   case '/': return ++CurPtr, LexLineComment();
124   default:  return AsmToken(AsmToken::Slash, StringRef(CurPtr-1, 1));
125   }
126
127   // C Style comment.
128   ++CurPtr;  // skip the star.
129   while (1) {
130     int CurChar = getNextChar();
131     switch (CurChar) {
132     case EOF:
133       return ReturnError(TokStart, "unterminated comment");
134     case '*':
135       // End of the comment?
136       if (CurPtr[0] != '/') break;
137
138       ++CurPtr;   // End the */.
139       return LexToken();
140     }
141   }
142 }
143
144 /// LexLineComment: Comment: #[^\n]*
145 ///                        : //[^\n]*
146 AsmToken AsmLexer::LexLineComment() {
147   // FIXME: This is broken if we happen to a comment at the end of a file, which
148   // was .included, and which doesn't end with a newline.
149   int CurChar = getNextChar();
150   while (CurChar != '\n' && CurChar != '\r' && CurChar != EOF)
151     CurChar = getNextChar();
152
153   if (CurChar == EOF)
154     return AsmToken(AsmToken::Eof, StringRef(CurPtr, 0));
155   return AsmToken(AsmToken::EndOfStatement, StringRef(CurPtr, 0));
156 }
157
158 static void SkipIgnoredIntegerSuffix(const char *&CurPtr) {
159   if (CurPtr[0] == 'L' && CurPtr[1] == 'L')
160     CurPtr += 2;
161   if (CurPtr[0] == 'U' && CurPtr[1] == 'L' && CurPtr[2] == 'L')
162     CurPtr += 3;
163 }
164
165 // Look ahead to search for first non-hex digit, if it's [hH], then we treat the
166 // integer as a hexadecimal, possibly with leading zeroes.
167 static unsigned doLookAhead(const char *&CurPtr, unsigned DefaultRadix) {
168   const char *FirstHex = 0;
169   const char *LookAhead = CurPtr;
170   while (1) {
171     if (isdigit(*LookAhead)) {
172       ++LookAhead;
173     } else if (isxdigit(*LookAhead)) {
174       if (!FirstHex)
175         FirstHex = LookAhead;
176       ++LookAhead;
177     } else {
178       break;
179     }
180   }
181   bool isHex = *LookAhead == 'h' || *LookAhead == 'H';
182   bool isBinary = LookAhead[-1] == 'b' || LookAhead[-1] == 'B';
183   CurPtr = (isBinary || isHex || !FirstHex) ? LookAhead : FirstHex;
184   if (isHex)
185     return 16;
186   if (isBinary) {
187     --CurPtr;
188     return 2;
189   }
190   return DefaultRadix;
191 }
192
193 /// LexDigit: First character is [0-9].
194 ///   Local Label: [0-9][:]
195 ///   Forward/Backward Label: [0-9]+f or [0-9]b
196 ///   Binary integer: 0b[01]+ or [01][bB]
197 ///   Octal integer: 0[0-7]+
198 ///   Hex integer: 0x[0-9a-fA-F]+ or [0x]?[0-9][0-9a-fA-F]*[hH]
199 ///   Decimal integer: [1-9][0-9]*
200 AsmToken AsmLexer::LexDigit() {
201
202   // Backward Label: [0-9]b
203   if (*CurPtr == 'b') {
204     // See if we actually have "0b" as part of something like "jmp 0b\n"
205     if (!isdigit(CurPtr[1])) {
206       long long Value;
207       StringRef Result(TokStart, CurPtr - TokStart);
208       if (Result.getAsInteger(10, Value))
209         return ReturnError(TokStart, "invalid backward label");
210
211       return AsmToken(AsmToken::Integer, Result, Value);
212     }
213   }
214
215   // Binary integer: 1[01]*[bB]
216   // Decimal integer: [1-9][0-9]*
217   // Hexidecimal integer: [1-9][0-9a-fA-F]*[hH]
218   if (CurPtr[-1] != '0' || CurPtr[0] == '.') {
219     unsigned Radix = doLookAhead(CurPtr, 10);
220     bool isDecimal = Radix == 10;
221
222     // Check for floating point literals.
223     if (isDecimal && (*CurPtr == '.' || *CurPtr == 'e')) {
224       ++CurPtr;
225       return LexFloatLiteral();
226     }
227
228     StringRef Result(TokStart, CurPtr - TokStart);
229
230     long long Value;
231     if (Result.getAsInteger(Radix, Value)) {
232       // Allow positive values that are too large to fit into a signed 64-bit
233       // integer, but that do fit in an unsigned one, we just convert them over.
234       unsigned long long UValue;
235       if (Result.getAsInteger(Radix, UValue))
236         return ReturnError(TokStart, isDecimal ? "invalid decimal number" :
237                            "invalid hexdecimal number");
238       Value = (long long)UValue;
239     }
240
241     // Consume the [bB][hH].
242     if (Radix == 2 || Radix == 16)
243       ++CurPtr;
244
245     // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
246     // suffixes on integer literals.
247     SkipIgnoredIntegerSuffix(CurPtr);
248
249     return AsmToken(AsmToken::Integer, Result, Value);
250   }
251
252   // Binary integer: 0b[01]+
253   if (*CurPtr == 'b') {
254     const char *NumStart = ++CurPtr;
255     while (CurPtr[0] == '0' || CurPtr[0] == '1')
256       ++CurPtr;
257
258     // Requires at least one binary digit.
259     if (CurPtr == NumStart)
260       return ReturnError(TokStart, "invalid binary number");
261
262     StringRef Result(TokStart, CurPtr - TokStart);
263
264     long long Value;
265     if (Result.substr(2).getAsInteger(2, Value))
266       return ReturnError(TokStart, "invalid binary number");
267
268     // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
269     // suffixes on integer literals.
270     SkipIgnoredIntegerSuffix(CurPtr);
271
272     return AsmToken(AsmToken::Integer, Result, Value);
273   }
274
275   // Hex integer: 0x[0-9a-fA-F]+
276   if (*CurPtr == 'x') {
277     ++CurPtr;
278     const char *NumStart = CurPtr;
279     while (isxdigit(CurPtr[0]))
280       ++CurPtr;
281
282     // Requires at least one hex digit.
283     if (CurPtr == NumStart)
284       return ReturnError(CurPtr-2, "invalid hexadecimal number");
285
286     unsigned long long Result;
287     if (StringRef(TokStart, CurPtr - TokStart).getAsInteger(0, Result))
288       return ReturnError(TokStart, "invalid hexadecimal number");
289
290     // Consume the optional [hH].
291     if (*CurPtr == 'h' || *CurPtr == 'H')
292       ++CurPtr;
293
294     // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
295     // suffixes on integer literals.
296     SkipIgnoredIntegerSuffix(CurPtr);
297
298     return AsmToken(AsmToken::Integer, StringRef(TokStart, CurPtr - TokStart),
299                     (int64_t)Result);
300   }
301
302   // Binary: 0[01]*[Bb], but not 0b.
303   // Octal: 0[0-7]*
304   // Hexidecimal: [0][0-9a-fA-F]*[hH]
305   long long Value;
306   unsigned Radix = doLookAhead(CurPtr, 8);
307   bool isBinary = Radix == 2;
308   bool isOctal = Radix == 8;
309   StringRef Result(TokStart, CurPtr - TokStart);
310   if (Result.getAsInteger(Radix, Value))
311     return ReturnError(TokStart, isOctal ? "invalid octal number" :
312                        isBinary ? "invalid binary number" :
313                        "invalid hexdecimal number");
314
315   // Consume the [bB][hH].
316   if (Radix == 2 || Radix == 16)
317     ++CurPtr;
318
319   // The darwin/x86 (and x86-64) assembler accepts and ignores ULL and LL
320   // suffixes on integer literals.
321   SkipIgnoredIntegerSuffix(CurPtr);
322
323   return AsmToken(AsmToken::Integer, Result, Value);
324 }
325
326 /// LexSingleQuote: Integer: 'b'
327 AsmToken AsmLexer::LexSingleQuote() {
328   int CurChar = getNextChar();
329
330   if (CurChar == '\\')
331     CurChar = getNextChar();
332
333   if (CurChar == EOF)
334     return ReturnError(TokStart, "unterminated single quote");
335
336   CurChar = getNextChar();
337
338   if (CurChar != '\'')
339     return ReturnError(TokStart, "single quote way too long");
340
341   // The idea here being that 'c' is basically just an integral
342   // constant.
343   StringRef Res = StringRef(TokStart,CurPtr - TokStart);
344   long long Value;
345
346   if (Res.startswith("\'\\")) {
347     char theChar = Res[2];
348     switch (theChar) {
349       default: Value = theChar; break;
350       case '\'': Value = '\''; break;
351       case 't': Value = '\t'; break;
352       case 'n': Value = '\n'; break;
353       case 'b': Value = '\b'; break;
354     }
355   } else
356     Value = TokStart[1];
357
358   return AsmToken(AsmToken::Integer, Res, Value);
359 }
360
361
362 /// LexQuote: String: "..."
363 AsmToken AsmLexer::LexQuote() {
364   int CurChar = getNextChar();
365   // TODO: does gas allow multiline string constants?
366   while (CurChar != '"') {
367     if (CurChar == '\\') {
368       // Allow \", etc.
369       CurChar = getNextChar();
370     }
371
372     if (CurChar == EOF)
373       return ReturnError(TokStart, "unterminated string constant");
374
375     CurChar = getNextChar();
376   }
377
378   return AsmToken(AsmToken::String, StringRef(TokStart, CurPtr - TokStart));
379 }
380
381 StringRef AsmLexer::LexUntilEndOfStatement() {
382   TokStart = CurPtr;
383
384   while (!isAtStartOfComment(*CurPtr) &&    // Start of line comment.
385          !isAtStatementSeparator(CurPtr) && // End of statement marker.
386          *CurPtr != '\n' &&
387          *CurPtr != '\r' &&
388          (*CurPtr != 0 || CurPtr != CurBuf->getBufferEnd())) {
389     ++CurPtr;
390   }
391   return StringRef(TokStart, CurPtr-TokStart);
392 }
393
394 StringRef AsmLexer::LexUntilEndOfLine() {
395   TokStart = CurPtr;
396
397   while (*CurPtr != '\n' &&
398          *CurPtr != '\r' &&
399          (*CurPtr != 0 || CurPtr != CurBuf->getBufferEnd())) {
400     ++CurPtr;
401   }
402   return StringRef(TokStart, CurPtr-TokStart);
403 }
404
405 bool AsmLexer::isAtStartOfComment(char Char) {
406   // FIXME: This won't work for multi-character comment indicators like "//".
407   return Char == *MAI.getCommentString();
408 }
409
410 bool AsmLexer::isAtStatementSeparator(const char *Ptr) {
411   return strncmp(Ptr, MAI.getSeparatorString(),
412                  strlen(MAI.getSeparatorString())) == 0;
413 }
414
415 AsmToken AsmLexer::LexToken() {
416   TokStart = CurPtr;
417   // This always consumes at least one character.
418   int CurChar = getNextChar();
419
420   if (isAtStartOfComment(CurChar)) {
421     // If this comment starts with a '#', then return the Hash token and let
422     // the assembler parser see if it can be parsed as a cpp line filename
423     // comment. We do this only if we are at the start of a line.
424     if (CurChar == '#' && isAtStartOfLine)
425       return AsmToken(AsmToken::Hash, StringRef(TokStart, 1));
426     isAtStartOfLine = true;
427     return LexLineComment();
428   }
429   if (isAtStatementSeparator(TokStart)) {
430     CurPtr += strlen(MAI.getSeparatorString()) - 1;
431     return AsmToken(AsmToken::EndOfStatement,
432                     StringRef(TokStart, strlen(MAI.getSeparatorString())));
433   }
434
435   // If we're missing a newline at EOF, make sure we still get an
436   // EndOfStatement token before the Eof token.
437   if (CurChar == EOF && !isAtStartOfLine) {
438     isAtStartOfLine = true;
439     return AsmToken(AsmToken::EndOfStatement, StringRef(TokStart, 1));
440   }
441
442   isAtStartOfLine = false;
443   switch (CurChar) {
444   default:
445     // Handle identifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*
446     if (isalpha(CurChar) || CurChar == '_' || CurChar == '.')
447       return LexIdentifier();
448
449     // Unknown character, emit an error.
450     return ReturnError(TokStart, "invalid character in input");
451   case EOF: return AsmToken(AsmToken::Eof, StringRef(TokStart, 0));
452   case 0:
453   case ' ':
454   case '\t':
455     if (SkipSpace) {
456       // Ignore whitespace.
457       return LexToken();
458     } else {
459       int len = 1;
460       while (*CurPtr==' ' || *CurPtr=='\t') {
461         CurPtr++;
462         len++;
463       }
464       return AsmToken(AsmToken::Space, StringRef(TokStart, len));
465     }
466   case '\n': // FALL THROUGH.
467   case '\r':
468     isAtStartOfLine = true;
469     return AsmToken(AsmToken::EndOfStatement, StringRef(TokStart, 1));
470   case ':': return AsmToken(AsmToken::Colon, StringRef(TokStart, 1));
471   case '+': return AsmToken(AsmToken::Plus, StringRef(TokStart, 1));
472   case '-': return AsmToken(AsmToken::Minus, StringRef(TokStart, 1));
473   case '~': return AsmToken(AsmToken::Tilde, StringRef(TokStart, 1));
474   case '(': return AsmToken(AsmToken::LParen, StringRef(TokStart, 1));
475   case ')': return AsmToken(AsmToken::RParen, StringRef(TokStart, 1));
476   case '[': return AsmToken(AsmToken::LBrac, StringRef(TokStart, 1));
477   case ']': return AsmToken(AsmToken::RBrac, StringRef(TokStart, 1));
478   case '{': return AsmToken(AsmToken::LCurly, StringRef(TokStart, 1));
479   case '}': return AsmToken(AsmToken::RCurly, StringRef(TokStart, 1));
480   case '*': return AsmToken(AsmToken::Star, StringRef(TokStart, 1));
481   case ',': return AsmToken(AsmToken::Comma, StringRef(TokStart, 1));
482   case '$': return AsmToken(AsmToken::Dollar, StringRef(TokStart, 1));
483   case '@': return AsmToken(AsmToken::At, StringRef(TokStart, 1));
484   case '\\': return AsmToken(AsmToken::BackSlash, StringRef(TokStart, 1));
485   case '=':
486     if (*CurPtr == '=')
487       return ++CurPtr, AsmToken(AsmToken::EqualEqual, StringRef(TokStart, 2));
488     return AsmToken(AsmToken::Equal, StringRef(TokStart, 1));
489   case '|':
490     if (*CurPtr == '|')
491       return ++CurPtr, AsmToken(AsmToken::PipePipe, StringRef(TokStart, 2));
492     return AsmToken(AsmToken::Pipe, StringRef(TokStart, 1));
493   case '^': return AsmToken(AsmToken::Caret, StringRef(TokStart, 1));
494   case '&':
495     if (*CurPtr == '&')
496       return ++CurPtr, AsmToken(AsmToken::AmpAmp, StringRef(TokStart, 2));
497     return AsmToken(AsmToken::Amp, StringRef(TokStart, 1));
498   case '!':
499     if (*CurPtr == '=')
500       return ++CurPtr, AsmToken(AsmToken::ExclaimEqual, StringRef(TokStart, 2));
501     return AsmToken(AsmToken::Exclaim, StringRef(TokStart, 1));
502   case '%': return AsmToken(AsmToken::Percent, StringRef(TokStart, 1));
503   case '/': return LexSlash();
504   case '#': return AsmToken(AsmToken::Hash, StringRef(TokStart, 1));
505   case '\'': return LexSingleQuote();
506   case '"': return LexQuote();
507   case '0': case '1': case '2': case '3': case '4':
508   case '5': case '6': case '7': case '8': case '9':
509     return LexDigit();
510   case '<':
511     switch (*CurPtr) {
512     case '<': return ++CurPtr, AsmToken(AsmToken::LessLess,
513                                         StringRef(TokStart, 2));
514     case '=': return ++CurPtr, AsmToken(AsmToken::LessEqual,
515                                         StringRef(TokStart, 2));
516     case '>': return ++CurPtr, AsmToken(AsmToken::LessGreater,
517                                         StringRef(TokStart, 2));
518     default: return AsmToken(AsmToken::Less, StringRef(TokStart, 1));
519     }
520   case '>':
521     switch (*CurPtr) {
522     case '>': return ++CurPtr, AsmToken(AsmToken::GreaterGreater,
523                                         StringRef(TokStart, 2));
524     case '=': return ++CurPtr, AsmToken(AsmToken::GreaterEqual,
525                                         StringRef(TokStart, 2));
526     default: return AsmToken(AsmToken::Greater, StringRef(TokStart, 1));
527     }
528
529   // TODO: Quoted identifiers (objc methods etc)
530   // local labels: [0-9][:]
531   // Forward/backward labels: [0-9][fb]
532   // Integers, fp constants, character constants.
533   }
534 }