llvm-mc: Factor AsmToken class out of AsmLexer.
[oota-llvm.git] / tools / llvm-mc / 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 "AsmLexer.h"
15 #include "llvm/Support/SourceMgr.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Config/config.h"  // for strtoull.
18 #include <cerrno>
19 #include <cstdio>
20 #include <cstdlib>
21 using namespace llvm;
22
23 AsmLexer::AsmLexer(SourceMgr &SM) : SrcMgr(SM)  {
24   CurBuffer = 0;
25   CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);
26   CurPtr = CurBuf->getBufferStart();
27   CurTok = AsmToken(asmtok::Error, StringRef(CurPtr, 0));
28   TokStart = 0;
29 }
30
31 AsmLexer::~AsmLexer() {
32 }
33
34 SMLoc AsmLexer::getLoc() const {
35   return SMLoc::getFromPointer(TokStart);
36 }
37
38 void AsmLexer::PrintMessage(SMLoc Loc, const std::string &Msg, 
39                             const char *Type) const {
40   SrcMgr.PrintMessage(Loc, Msg, Type);
41 }
42
43 /// ReturnError - Set the error to the specified string at the specified
44 /// location.  This is defined to always return asmtok::Error.
45 AsmToken AsmLexer::ReturnError(const char *Loc, const std::string &Msg) {
46   SrcMgr.PrintMessage(SMLoc::getFromPointer(Loc), Msg, "error");
47   return AsmToken(asmtok::Error, StringRef(Loc, 0));
48 }
49
50 /// EnterIncludeFile - Enter the specified file.  This prints an error and
51 /// returns true on failure.
52 bool AsmLexer::EnterIncludeFile(const std::string &Filename) {
53   int NewBuf = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr));
54   if (NewBuf == -1)
55     return true;
56   
57   // Save the line number and lex buffer of the includer.
58   CurBuffer = NewBuf;
59   CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);
60   CurPtr = CurBuf->getBufferStart();
61   return false;
62 }
63
64
65 int AsmLexer::getNextChar() {
66   char CurChar = *CurPtr++;
67   switch (CurChar) {
68   default:
69     return (unsigned char)CurChar;
70   case 0: {
71     // A nul character in the stream is either the end of the current buffer or
72     // a random nul in the file.  Disambiguate that here.
73     if (CurPtr-1 != CurBuf->getBufferEnd())
74       return 0;  // Just whitespace.
75     
76     // If this is the end of an included file, pop the parent file off the
77     // include stack.
78     SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
79     if (ParentIncludeLoc != SMLoc()) {
80       CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
81       CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);
82       CurPtr = ParentIncludeLoc.getPointer();
83       
84       // Reset the token start pointer to the start of the new file.
85       TokStart = CurPtr;
86       
87       return getNextChar();
88     }
89     
90     // Otherwise, return end of file.
91     --CurPtr;  // Another call to lex will return EOF again.  
92     return EOF;
93   }
94   }
95 }
96
97 /// LexIdentifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*
98 AsmToken AsmLexer::LexIdentifier() {
99   while (isalnum(*CurPtr) || *CurPtr == '_' || *CurPtr == '$' ||
100          *CurPtr == '.' || *CurPtr == '@')
101     ++CurPtr;
102   return AsmToken(asmtok::Identifier, StringRef(TokStart, CurPtr - TokStart));
103 }
104
105 /// LexPercent: Register: %[a-zA-Z0-9]+
106 AsmToken AsmLexer::LexPercent() {
107   if (!isalnum(*CurPtr))
108     return AsmToken(asmtok::Percent, StringRef(CurPtr, 1));  // Single %.
109   
110   while (isalnum(*CurPtr))
111     ++CurPtr;
112   
113   return AsmToken(asmtok::Register, 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(asmtok::Slash, StringRef(CurPtr, 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(asmtok::Eof, StringRef(CurPtr, 0));
153   return AsmToken(asmtok::EndOfStatement, StringRef(CurPtr, 0));
154 }
155
156
157 /// LexDigit: First character is [0-9].
158 ///   Local Label: [0-9][:]
159 ///   Forward/Backward Label: [0-9][fb]
160 ///   Binary integer: 0b[01]+
161 ///   Octal integer: 0[0-7]+
162 ///   Hex integer: 0x[0-9a-fA-F]+
163 ///   Decimal integer: [1-9][0-9]*
164 /// TODO: FP literal.
165 AsmToken AsmLexer::LexDigit() {
166   if (*CurPtr == ':')
167     return ReturnError(TokStart, "FIXME: local label not implemented");
168   if (*CurPtr == 'f' || *CurPtr == 'b')
169     return ReturnError(TokStart, "FIXME: directional label not implemented");
170   
171   // Decimal integer: [1-9][0-9]*
172   if (CurPtr[-1] != '0') {
173     while (isdigit(*CurPtr))
174       ++CurPtr;
175     return AsmToken(asmtok::IntVal, StringRef(TokStart, CurPtr - TokStart), 
176                     strtoll(TokStart, 0, 10));
177   }
178   
179   if (*CurPtr == 'b') {
180     ++CurPtr;
181     const char *NumStart = CurPtr;
182     while (CurPtr[0] == '0' || CurPtr[0] == '1')
183       ++CurPtr;
184     
185     // Requires at least one binary digit.
186     if (CurPtr == NumStart)
187       return ReturnError(CurPtr-2, "Invalid binary number");
188     return AsmToken(asmtok::IntVal, StringRef(TokStart, CurPtr - TokStart),
189                     strtoll(NumStart, 0, 2));
190   }
191  
192   if (*CurPtr == 'x') {
193     ++CurPtr;
194     const char *NumStart = CurPtr;
195     while (isxdigit(CurPtr[0]))
196       ++CurPtr;
197     
198     // Requires at least one hex digit.
199     if (CurPtr == NumStart)
200       return ReturnError(CurPtr-2, "Invalid hexadecimal number");
201     
202     errno = 0;
203     if (errno == EINVAL)
204       return ReturnError(CurPtr-2, "Invalid hexadecimal number");
205     if (errno == ERANGE) {
206       errno = 0;
207       if (errno == EINVAL)
208         return ReturnError(CurPtr-2, "Invalid hexadecimal number");
209       if (errno == ERANGE)
210         return ReturnError(CurPtr-2, "Hexadecimal number out of range");
211     }
212     return AsmToken(asmtok::IntVal, StringRef(TokStart, CurPtr - TokStart),
213                     (int64_t) strtoull(NumStart, 0, 16));
214   }
215   
216   // Must be an octal number, it starts with 0.
217   while (*CurPtr >= '0' && *CurPtr <= '7')
218     ++CurPtr;
219   return AsmToken(asmtok::IntVal, StringRef(TokStart, CurPtr - TokStart),
220                   strtoll(TokStart, 0, 8));
221 }
222
223 /// LexQuote: String: "..."
224 AsmToken AsmLexer::LexQuote() {
225   int CurChar = getNextChar();
226   // TODO: does gas allow multiline string constants?
227   while (CurChar != '"') {
228     if (CurChar == '\\') {
229       // Allow \", etc.
230       CurChar = getNextChar();
231     }
232     
233     if (CurChar == EOF)
234       return ReturnError(TokStart, "unterminated string constant");
235
236     CurChar = getNextChar();
237   }
238   
239   return AsmToken(asmtok::String, StringRef(TokStart, CurPtr - TokStart));
240 }
241
242
243 AsmToken AsmLexer::LexToken() {
244   TokStart = CurPtr;
245   // This always consumes at least one character.
246   int CurChar = getNextChar();
247   
248   switch (CurChar) {
249   default:
250     // Handle identifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*
251     if (isalpha(CurChar) || CurChar == '_' || CurChar == '.')
252       return LexIdentifier();
253     
254     // Unknown character, emit an error.
255     return ReturnError(TokStart, "invalid character in input");
256   case EOF: return AsmToken(asmtok::Eof, StringRef(TokStart, 0));
257   case 0:
258   case ' ':
259   case '\t':
260     // Ignore whitespace.
261     return LexToken();
262   case '\n': // FALL THROUGH.
263   case '\r': // FALL THROUGH.
264   case ';': return AsmToken(asmtok::EndOfStatement, StringRef(TokStart, 1));
265   case ':': return AsmToken(asmtok::Colon, StringRef(TokStart, 1));
266   case '+': return AsmToken(asmtok::Plus, StringRef(TokStart, 1));
267   case '-': return AsmToken(asmtok::Minus, StringRef(TokStart, 1));
268   case '~': return AsmToken(asmtok::Tilde, StringRef(TokStart, 1));
269   case '(': return AsmToken(asmtok::LParen, StringRef(TokStart, 1));
270   case ')': return AsmToken(asmtok::RParen, StringRef(TokStart, 1));
271   case '*': return AsmToken(asmtok::Star, StringRef(TokStart, 1));
272   case ',': return AsmToken(asmtok::Comma, StringRef(TokStart, 1));
273   case '$': return AsmToken(asmtok::Dollar, StringRef(TokStart, 1));
274   case '=': 
275     if (*CurPtr == '=')
276       return ++CurPtr, AsmToken(asmtok::EqualEqual, StringRef(TokStart, 2));
277     return AsmToken(asmtok::Equal, StringRef(TokStart, 1));
278   case '|': 
279     if (*CurPtr == '|')
280       return ++CurPtr, AsmToken(asmtok::PipePipe, StringRef(TokStart, 2));
281     return AsmToken(asmtok::Pipe, StringRef(TokStart, 1));
282   case '^': return AsmToken(asmtok::Caret, StringRef(TokStart, 1));
283   case '&': 
284     if (*CurPtr == '&')
285       return ++CurPtr, AsmToken(asmtok::AmpAmp, StringRef(TokStart, 2));
286     return AsmToken(asmtok::Amp, StringRef(TokStart, 1));
287   case '!': 
288     if (*CurPtr == '=')
289       return ++CurPtr, AsmToken(asmtok::ExclaimEqual, StringRef(TokStart, 2));
290     return AsmToken(asmtok::Exclaim, StringRef(TokStart, 1));
291   case '%': return LexPercent();
292   case '/': return LexSlash();
293   case '#': return LexLineComment();
294   case '"': return LexQuote();
295   case '0': case '1': case '2': case '3': case '4':
296   case '5': case '6': case '7': case '8': case '9':
297     return LexDigit();
298   case '<':
299     switch (*CurPtr) {
300     case '<': return ++CurPtr, AsmToken(asmtok::LessLess, 
301                                         StringRef(TokStart, 2));
302     case '=': return ++CurPtr, AsmToken(asmtok::LessEqual, 
303                                         StringRef(TokStart, 2));
304     case '>': return ++CurPtr, AsmToken(asmtok::LessGreater, 
305                                         StringRef(TokStart, 2));
306     default: return AsmToken(asmtok::Less, StringRef(TokStart, 1));
307     }
308   case '>':
309     switch (*CurPtr) {
310     case '>': return ++CurPtr, AsmToken(asmtok::GreaterGreater, 
311                                         StringRef(TokStart, 2));
312     case '=': return ++CurPtr, AsmToken(asmtok::GreaterEqual, 
313                                         StringRef(TokStart, 2));
314     default: return AsmToken(asmtok::Greater, StringRef(TokStart, 1));
315     }
316       
317   // TODO: Quoted identifiers (objc methods etc)
318   // local labels: [0-9][:]
319   // Forward/backward labels: [0-9][fb]
320   // Integers, fp constants, character constants.
321   }
322 }