MIR Parser: Simplify the handling of quoted tokens. NFC.
[oota-llvm.git] / lib / CodeGen / MIRParser / MILexer.cpp
1 //===- MILexer.cpp - Machine instructions lexer implementation ----------===//
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 file implements the lexing of machine instructions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "MILexer.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include <cctype>
19
20 using namespace llvm;
21
22 namespace {
23
24 /// This class provides a way to iterate and get characters from the source
25 /// string.
26 class Cursor {
27   const char *Ptr;
28   const char *End;
29
30 public:
31   Cursor(NoneType) : Ptr(nullptr), End(nullptr) {}
32
33   explicit Cursor(StringRef Str) {
34     Ptr = Str.data();
35     End = Ptr + Str.size();
36   }
37
38   bool isEOF() const { return Ptr == End; }
39
40   char peek(int I = 0) const { return End - Ptr <= I ? 0 : Ptr[I]; }
41
42   void advance(unsigned I = 1) { Ptr += I; }
43
44   StringRef remaining() const { return StringRef(Ptr, End - Ptr); }
45
46   StringRef upto(Cursor C) const {
47     assert(C.Ptr >= Ptr && C.Ptr <= End);
48     return StringRef(Ptr, C.Ptr - Ptr);
49   }
50
51   StringRef::iterator location() const { return Ptr; }
52
53   operator bool() const { return Ptr != nullptr; }
54 };
55
56 } // end anonymous namespace
57
58 /// Skip the leading whitespace characters and return the updated cursor.
59 static Cursor skipWhitespace(Cursor C) {
60   while (isspace(C.peek()))
61     C.advance();
62   return C;
63 }
64
65 /// Return true if the given character satisfies the following regular
66 /// expression: [-a-zA-Z$._0-9]
67 static bool isIdentifierChar(char C) {
68   return isalpha(C) || isdigit(C) || C == '_' || C == '-' || C == '.' ||
69          C == '$';
70 }
71
72 /// Unescapes the given string value.
73 ///
74 /// Expects the string value to be quoted.
75 static std::string unescapeQuotedString(StringRef Value) {
76   assert(Value.front() == '"' && Value.back() == '"');
77   Cursor C = Cursor(Value.substr(1, Value.size() - 2));
78
79   std::string Str;
80   Str.reserve(C.remaining().size());
81   while (!C.isEOF()) {
82     char Char = C.peek();
83     if (Char == '\\') {
84       if (C.peek(1) == '\\') {
85         // Two '\' become one
86         Str += '\\';
87         C.advance(2);
88         continue;
89       }
90       if (isxdigit(C.peek(1)) && isxdigit(C.peek(2))) {
91         Str += hexDigitValue(C.peek(1)) * 16 + hexDigitValue(C.peek(2));
92         C.advance(3);
93         continue;
94       }
95     }
96     Str += Char;
97     C.advance();
98   }
99   return Str;
100 }
101
102 /// Lex a string constant using the following regular expression: \"[^\"]*\"
103 static Cursor lexStringConstant(
104     Cursor C,
105     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
106   assert(C.peek() == '"');
107   for (C.advance(); C.peek() != '"'; C.advance()) {
108     if (C.isEOF()) {
109       ErrorCallback(
110           C.location(),
111           "end of machine instruction reached before the closing '\"'");
112       return None;
113     }
114   }
115   C.advance();
116   return C;
117 }
118
119 static Cursor lexName(
120     Cursor C, MIToken &Token, MIToken::TokenKind Type, unsigned PrefixLength,
121     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
122   auto Range = C;
123   C.advance(PrefixLength);
124   if (C.peek() == '"') {
125     if (Cursor R = lexStringConstant(C, ErrorCallback)) {
126       StringRef String = Range.upto(R);
127       Token = MIToken(Type, String,
128                       unescapeQuotedString(String.drop_front(PrefixLength)),
129                       PrefixLength);
130       return R;
131     }
132     Token = MIToken(MIToken::Error, Range.remaining());
133     return Range;
134   }
135   while (isIdentifierChar(C.peek()))
136     C.advance();
137   Token = MIToken(Type, Range.upto(C), PrefixLength);
138   return C;
139 }
140
141 static MIToken::TokenKind getIdentifierKind(StringRef Identifier) {
142   return StringSwitch<MIToken::TokenKind>(Identifier)
143       .Case("_", MIToken::underscore)
144       .Case("implicit", MIToken::kw_implicit)
145       .Case("implicit-def", MIToken::kw_implicit_define)
146       .Case("dead", MIToken::kw_dead)
147       .Case("killed", MIToken::kw_killed)
148       .Case("undef", MIToken::kw_undef)
149       .Case("frame-setup", MIToken::kw_frame_setup)
150       .Case("debug-location", MIToken::kw_debug_location)
151       .Case(".cfi_offset", MIToken::kw_cfi_offset)
152       .Case(".cfi_def_cfa_register", MIToken::kw_cfi_def_cfa_register)
153       .Case(".cfi_def_cfa_offset", MIToken::kw_cfi_def_cfa_offset)
154       .Case(".cfi_def_cfa", MIToken::kw_cfi_def_cfa)
155       .Case("blockaddress", MIToken::kw_blockaddress)
156       .Case("target-index", MIToken::kw_target_index)
157       .Case("half", MIToken::kw_half)
158       .Case("float", MIToken::kw_float)
159       .Case("double", MIToken::kw_double)
160       .Case("x86_fp80", MIToken::kw_x86_fp80)
161       .Case("fp128", MIToken::kw_fp128)
162       .Case("ppc_fp128", MIToken::kw_ppc_fp128)
163       .Case("volatile", MIToken::kw_volatile)
164       .Default(MIToken::Identifier);
165 }
166
167 static Cursor maybeLexIdentifier(Cursor C, MIToken &Token) {
168   if (!isalpha(C.peek()) && C.peek() != '_' && C.peek() != '.')
169     return None;
170   auto Range = C;
171   while (isIdentifierChar(C.peek()))
172     C.advance();
173   auto Identifier = Range.upto(C);
174   Token = MIToken(getIdentifierKind(Identifier), Identifier);
175   return C;
176 }
177
178 static Cursor maybeLexMachineBasicBlock(
179     Cursor C, MIToken &Token,
180     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
181   if (!C.remaining().startswith("%bb."))
182     return None;
183   auto Range = C;
184   C.advance(4); // Skip '%bb.'
185   if (!isdigit(C.peek())) {
186     Token = MIToken(MIToken::Error, C.remaining());
187     ErrorCallback(C.location(), "expected a number after '%bb.'");
188     return C;
189   }
190   auto NumberRange = C;
191   while (isdigit(C.peek()))
192     C.advance();
193   StringRef Number = NumberRange.upto(C);
194   unsigned StringOffset = 4 + Number.size(); // Drop '%bb.<id>'
195   if (C.peek() == '.') {
196     C.advance(); // Skip '.'
197     ++StringOffset;
198     while (isIdentifierChar(C.peek()))
199       C.advance();
200   }
201   Token = MIToken(MIToken::MachineBasicBlock, Range.upto(C), APSInt(Number),
202                   StringOffset);
203   return C;
204 }
205
206 static Cursor maybeLexIndex(Cursor C, MIToken &Token, StringRef Rule,
207                             MIToken::TokenKind Kind) {
208   if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
209     return None;
210   auto Range = C;
211   C.advance(Rule.size());
212   auto NumberRange = C;
213   while (isdigit(C.peek()))
214     C.advance();
215   Token = MIToken(Kind, Range.upto(C), APSInt(NumberRange.upto(C)));
216   return C;
217 }
218
219 static Cursor maybeLexIndexAndName(Cursor C, MIToken &Token, StringRef Rule,
220                                    MIToken::TokenKind Kind) {
221   if (!C.remaining().startswith(Rule) || !isdigit(C.peek(Rule.size())))
222     return None;
223   auto Range = C;
224   C.advance(Rule.size());
225   auto NumberRange = C;
226   while (isdigit(C.peek()))
227     C.advance();
228   StringRef Number = NumberRange.upto(C);
229   unsigned StringOffset = Rule.size() + Number.size();
230   if (C.peek() == '.') {
231     C.advance();
232     ++StringOffset;
233     while (isIdentifierChar(C.peek()))
234       C.advance();
235   }
236   Token = MIToken(Kind, Range.upto(C), APSInt(Number), StringOffset);
237   return C;
238 }
239
240 static Cursor maybeLexJumpTableIndex(Cursor C, MIToken &Token) {
241   return maybeLexIndex(C, Token, "%jump-table.", MIToken::JumpTableIndex);
242 }
243
244 static Cursor maybeLexStackObject(Cursor C, MIToken &Token) {
245   return maybeLexIndexAndName(C, Token, "%stack.", MIToken::StackObject);
246 }
247
248 static Cursor maybeLexFixedStackObject(Cursor C, MIToken &Token) {
249   return maybeLexIndex(C, Token, "%fixed-stack.", MIToken::FixedStackObject);
250 }
251
252 static Cursor maybeLexConstantPoolItem(Cursor C, MIToken &Token) {
253   return maybeLexIndex(C, Token, "%const.", MIToken::ConstantPoolItem);
254 }
255
256 static Cursor maybeLexIRBlock(
257     Cursor C, MIToken &Token,
258     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
259   const StringRef Rule = "%ir-block.";
260   if (!C.remaining().startswith(Rule))
261     return None;
262   if (isdigit(C.peek(Rule.size())))
263     return maybeLexIndex(C, Token, Rule, MIToken::IRBlock);
264   return lexName(C, Token, MIToken::NamedIRBlock, Rule.size(), ErrorCallback);
265 }
266
267 static Cursor maybeLexIRValue(
268     Cursor C, MIToken &Token,
269     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
270   const StringRef Rule = "%ir.";
271   if (!C.remaining().startswith(Rule))
272     return None;
273   return lexName(C, Token, MIToken::NamedIRValue, Rule.size(), ErrorCallback);
274 }
275
276 static Cursor lexVirtualRegister(Cursor C, MIToken &Token) {
277   auto Range = C;
278   C.advance(); // Skip '%'
279   auto NumberRange = C;
280   while (isdigit(C.peek()))
281     C.advance();
282   Token = MIToken(MIToken::VirtualRegister, Range.upto(C),
283                   APSInt(NumberRange.upto(C)));
284   return C;
285 }
286
287 static Cursor maybeLexRegister(Cursor C, MIToken &Token) {
288   if (C.peek() != '%')
289     return None;
290   if (isdigit(C.peek(1)))
291     return lexVirtualRegister(C, Token);
292   auto Range = C;
293   C.advance(); // Skip '%'
294   while (isIdentifierChar(C.peek()))
295     C.advance();
296   Token = MIToken(MIToken::NamedRegister, Range.upto(C),
297                   /*StringOffset=*/1); // Drop the '%'
298   return C;
299 }
300
301 static Cursor maybeLexGlobalValue(
302     Cursor C, MIToken &Token,
303     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
304   if (C.peek() != '@')
305     return None;
306   if (!isdigit(C.peek(1)))
307     return lexName(C, Token, MIToken::NamedGlobalValue, /*PrefixLength=*/1,
308                    ErrorCallback);
309   auto Range = C;
310   C.advance(1); // Skip the '@'
311   auto NumberRange = C;
312   while (isdigit(C.peek()))
313     C.advance();
314   Token =
315       MIToken(MIToken::GlobalValue, Range.upto(C), APSInt(NumberRange.upto(C)));
316   return C;
317 }
318
319 static Cursor maybeLexExternalSymbol(
320     Cursor C, MIToken &Token,
321     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
322   if (C.peek() != '$')
323     return None;
324   return lexName(C, Token, MIToken::ExternalSymbol, /*PrefixLength=*/1,
325                  ErrorCallback);
326 }
327
328 static bool isValidHexFloatingPointPrefix(char C) {
329   return C == 'H' || C == 'K' || C == 'L' || C == 'M';
330 }
331
332 static Cursor maybeLexHexFloatingPointLiteral(Cursor C, MIToken &Token) {
333   if (C.peek() != '0' || C.peek(1) != 'x')
334     return None;
335   Cursor Range = C;
336   C.advance(2); // Skip '0x'
337   if (isValidHexFloatingPointPrefix(C.peek()))
338     C.advance();
339   while (isxdigit(C.peek()))
340     C.advance();
341   Token = MIToken(MIToken::FloatingPointLiteral, Range.upto(C));
342   return C;
343 }
344
345 static Cursor lexFloatingPointLiteral(Cursor Range, Cursor C, MIToken &Token) {
346   C.advance();
347   // Skip over [0-9]*([eE][-+]?[0-9]+)?
348   while (isdigit(C.peek()))
349     C.advance();
350   if ((C.peek() == 'e' || C.peek() == 'E') &&
351       (isdigit(C.peek(1)) ||
352        ((C.peek(1) == '-' || C.peek(1) == '+') && isdigit(C.peek(2))))) {
353     C.advance(2);
354     while (isdigit(C.peek()))
355       C.advance();
356   }
357   Token = MIToken(MIToken::FloatingPointLiteral, Range.upto(C));
358   return C;
359 }
360
361 static Cursor maybeLexNumericalLiteral(Cursor C, MIToken &Token) {
362   if (!isdigit(C.peek()) && (C.peek() != '-' || !isdigit(C.peek(1))))
363     return None;
364   auto Range = C;
365   C.advance();
366   while (isdigit(C.peek()))
367     C.advance();
368   if (C.peek() == '.')
369     return lexFloatingPointLiteral(Range, C, Token);
370   StringRef StrVal = Range.upto(C);
371   Token = MIToken(MIToken::IntegerLiteral, StrVal, APSInt(StrVal));
372   return C;
373 }
374
375 static MIToken::TokenKind symbolToken(char C) {
376   switch (C) {
377   case ',':
378     return MIToken::comma;
379   case '=':
380     return MIToken::equal;
381   case ':':
382     return MIToken::colon;
383   case '!':
384     return MIToken::exclaim;
385   case '(':
386     return MIToken::lparen;
387   case ')':
388     return MIToken::rparen;
389   default:
390     return MIToken::Error;
391   }
392 }
393
394 static Cursor maybeLexSymbol(Cursor C, MIToken &Token) {
395   MIToken::TokenKind Kind;
396   unsigned Length = 1;
397   if (C.peek() == ':' && C.peek(1) == ':') {
398     Kind = MIToken::coloncolon;
399     Length = 2;
400   } else
401     Kind = symbolToken(C.peek());
402   if (Kind == MIToken::Error)
403     return None;
404   auto Range = C;
405   C.advance(Length);
406   Token = MIToken(Kind, Range.upto(C));
407   return C;
408 }
409
410 StringRef llvm::lexMIToken(
411     StringRef Source, MIToken &Token,
412     function_ref<void(StringRef::iterator Loc, const Twine &)> ErrorCallback) {
413   auto C = skipWhitespace(Cursor(Source));
414   if (C.isEOF()) {
415     Token = MIToken(MIToken::Eof, C.remaining());
416     return C.remaining();
417   }
418
419   if (Cursor R = maybeLexIdentifier(C, Token))
420     return R.remaining();
421   if (Cursor R = maybeLexMachineBasicBlock(C, Token, ErrorCallback))
422     return R.remaining();
423   if (Cursor R = maybeLexJumpTableIndex(C, Token))
424     return R.remaining();
425   if (Cursor R = maybeLexStackObject(C, Token))
426     return R.remaining();
427   if (Cursor R = maybeLexFixedStackObject(C, Token))
428     return R.remaining();
429   if (Cursor R = maybeLexConstantPoolItem(C, Token))
430     return R.remaining();
431   if (Cursor R = maybeLexIRBlock(C, Token, ErrorCallback))
432     return R.remaining();
433   if (Cursor R = maybeLexIRValue(C, Token, ErrorCallback))
434     return R.remaining();
435   if (Cursor R = maybeLexRegister(C, Token))
436     return R.remaining();
437   if (Cursor R = maybeLexGlobalValue(C, Token, ErrorCallback))
438     return R.remaining();
439   if (Cursor R = maybeLexExternalSymbol(C, Token, ErrorCallback))
440     return R.remaining();
441   if (Cursor R = maybeLexHexFloatingPointLiteral(C, Token))
442     return R.remaining();
443   if (Cursor R = maybeLexNumericalLiteral(C, Token))
444     return R.remaining();
445   if (Cursor R = maybeLexSymbol(C, Token))
446     return R.remaining();
447
448   Token = MIToken(MIToken::Error, C.remaining());
449   ErrorCallback(C.location(),
450                 Twine("unexpected character '") + Twine(C.peek()) + "'");
451   return C.remaining();
452 }