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