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