1 //===- TGLexer.cpp - Lexer for TableGen -----------------------------------===// 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 // Implement the Lexer for TableGen. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TGLexer.h" 15 #include "llvm/TableGen/Error.h" 16 #include "llvm/Support/SourceMgr.h" 17 #include "llvm/Support/MemoryBuffer.h" 18 #include "llvm/ADT/StringSwitch.h" 19 #include "llvm/ADT/Twine.h" 20 #include <cctype> 21 #include <cstdio> 22 #include <cstdlib> 23 #include <cstring> 24 #include <cerrno> 25 26 #include "llvm/Config/config.h" // for strtoull()/strtoll() define 27 28 using namespace llvm; 29 30 TGLexer::TGLexer(SourceMgr &SM) : SrcMgr(SM) { 31 CurBuffer = 0; 32 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); 33 CurPtr = CurBuf->getBufferStart(); 34 TokStart = 0; 35 } 36 37 SMLoc TGLexer::getLoc() const { 38 return SMLoc::getFromPointer(TokStart); 39 } 40 41 /// ReturnError - Set the error to the specified string at the specified 42 /// location. This is defined to always return tgtok::Error. 43 tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) { 44 PrintError(Loc, Msg); 45 return tgtok::Error; 46 } 47 48 int TGLexer::getNextChar() { 49 char CurChar = *CurPtr++; 50 switch (CurChar) { 51 default: 52 return (unsigned char)CurChar; 53 case 0: { 54 // A nul character in the stream is either the end of the current buffer or 55 // a random nul in the file. Disambiguate that here. 56 if (CurPtr-1 != CurBuf->getBufferEnd()) 57 return 0; // Just whitespace. 58 59 // If this is the end of an included file, pop the parent file off the 60 // include stack. 61 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); 62 if (ParentIncludeLoc != SMLoc()) { 63 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc); 64 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); 65 CurPtr = ParentIncludeLoc.getPointer(); 66 return getNextChar(); 67 } 68 69 // Otherwise, return end of file. 70 --CurPtr; // Another call to lex will return EOF again. 71 return EOF; 72 } 73 case '\n': 74 case '\r': 75 // Handle the newline character by ignoring it and incrementing the line 76 // count. However, be careful about 'dos style' files with \n\r in them. 77 // Only treat a \n\r or \r\n as a single line. 78 if ((*CurPtr == '\n' || (*CurPtr == '\r')) && 79 *CurPtr != CurChar) 80 ++CurPtr; // Eat the two char newline sequence. 81 return '\n'; 82 } 83 } 84 85 int TGLexer::peekNextChar(int Index) { 86 return *(CurPtr + Index); 87 } 88 89 tgtok::TokKind TGLexer::LexToken() { 90 TokStart = CurPtr; 91 // This always consumes at least one character. 92 int CurChar = getNextChar(); 93 94 switch (CurChar) { 95 default: 96 // Handle letters: [a-zA-Z_] 97 if (isalpha(CurChar) || CurChar == '_') 98 return LexIdentifier(); 99 100 // Unknown character, emit an error. 101 return ReturnError(TokStart, "Unexpected character"); 102 case EOF: return tgtok::Eof; 103 case ':': return tgtok::colon; 104 case ';': return tgtok::semi; 105 case '.': return tgtok::period; 106 case ',': return tgtok::comma; 107 case '<': return tgtok::less; 108 case '>': return tgtok::greater; 109 case ']': return tgtok::r_square; 110 case '{': return tgtok::l_brace; 111 case '}': return tgtok::r_brace; 112 case '(': return tgtok::l_paren; 113 case ')': return tgtok::r_paren; 114 case '=': return tgtok::equal; 115 case '?': return tgtok::question; 116 case '#': return tgtok::paste; 117 118 case 0: 119 case ' ': 120 case '\t': 121 case '\n': 122 case '\r': 123 // Ignore whitespace. 124 return LexToken(); 125 case '/': 126 // If this is the start of a // comment, skip until the end of the line or 127 // the end of the buffer. 128 if (*CurPtr == '/') 129 SkipBCPLComment(); 130 else if (*CurPtr == '*') { 131 if (SkipCComment()) 132 return tgtok::Error; 133 } else // Otherwise, this is an error. 134 return ReturnError(TokStart, "Unexpected character"); 135 return LexToken(); 136 case '-': case '+': 137 case '0': case '1': case '2': case '3': case '4': case '5': case '6': 138 case '7': case '8': case '9': { 139 int NextChar = 0; 140 if (isdigit(CurChar)) { 141 // Allow identifiers to start with a number if it is followed by 142 // an identifier. This can happen with paste operations like 143 // foo#8i. 144 int i = 0; 145 do { 146 NextChar = peekNextChar(i++); 147 } while (isdigit(NextChar)); 148 149 if (NextChar == 'x' || NextChar == 'b') { 150 // If this is [0-9]b[01] or [0-9]x[0-9A-fa-f] this is most 151 // likely a number. 152 int NextNextChar = peekNextChar(i); 153 switch (NextNextChar) { 154 default: 155 break; 156 case '0': case '1': 157 if (NextChar == 'b') 158 return LexNumber(); 159 // Fallthrough 160 case '2': case '3': case '4': case '5': 161 case '6': case '7': case '8': case '9': 162 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': 163 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': 164 if (NextChar == 'x') 165 return LexNumber(); 166 break; 167 } 168 } 169 } 170 171 if (isalpha(NextChar) || NextChar == '_') 172 return LexIdentifier(); 173 174 return LexNumber(); 175 } 176 case '"': return LexString(); 177 case '$': return LexVarName(); 178 case '[': return LexBracket(); 179 case '!': return LexExclaim(); 180 } 181 } 182 183 /// LexString - Lex "[^"]*" 184 tgtok::TokKind TGLexer::LexString() { 185 const char *StrStart = CurPtr; 186 187 CurStrVal = ""; 188 189 while (*CurPtr != '"') { 190 // If we hit the end of the buffer, report an error. 191 if (*CurPtr == 0 && CurPtr == CurBuf->getBufferEnd()) 192 return ReturnError(StrStart, "End of file in string literal"); 193 194 if (*CurPtr == '\n' || *CurPtr == '\r') 195 return ReturnError(StrStart, "End of line in string literal"); 196 197 if (*CurPtr != '\\') { 198 CurStrVal += *CurPtr++; 199 continue; 200 } 201 202 ++CurPtr; 203 204 switch (*CurPtr) { 205 case '\\': case '\'': case '"': 206 // These turn into their literal character. 207 CurStrVal += *CurPtr++; 208 break; 209 case 't': 210 CurStrVal += '\t'; 211 ++CurPtr; 212 break; 213 case 'n': 214 CurStrVal += '\n'; 215 ++CurPtr; 216 break; 217 218 case '\n': 219 case '\r': 220 return ReturnError(CurPtr, "escaped newlines not supported in tblgen"); 221 222 // If we hit the end of the buffer, report an error. 223 case '\0': 224 if (CurPtr == CurBuf->getBufferEnd()) 225 return ReturnError(StrStart, "End of file in string literal"); 226 // FALL THROUGH 227 default: 228 return ReturnError(CurPtr, "invalid escape in string literal"); 229 } 230 } 231 232 ++CurPtr; 233 return tgtok::StrVal; 234 } 235 236 tgtok::TokKind TGLexer::LexVarName() { 237 if (!isalpha(CurPtr[0]) && CurPtr[0] != '_') 238 return ReturnError(TokStart, "Invalid variable name"); 239 240 // Otherwise, we're ok, consume the rest of the characters. 241 const char *VarNameStart = CurPtr++; 242 243 while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_') 244 ++CurPtr; 245 246 CurStrVal.assign(VarNameStart, CurPtr); 247 return tgtok::VarName; 248 } 249 250 251 tgtok::TokKind TGLexer::LexIdentifier() { 252 // The first letter is [a-zA-Z_#]. 253 const char *IdentStart = TokStart; 254 255 // Match the rest of the identifier regex: [0-9a-zA-Z_#]* 256 while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_') 257 ++CurPtr; 258 259 // Check to see if this identifier is a keyword. 260 StringRef Str(IdentStart, CurPtr-IdentStart); 261 262 if (Str == "include") { 263 if (LexInclude()) return tgtok::Error; 264 return Lex(); 265 } 266 267 tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(Str) 268 .Case("int", tgtok::Int) 269 .Case("bit", tgtok::Bit) 270 .Case("bits", tgtok::Bits) 271 .Case("string", tgtok::String) 272 .Case("list", tgtok::List) 273 .Case("code", tgtok::Code) 274 .Case("dag", tgtok::Dag) 275 .Case("class", tgtok::Class) 276 .Case("def", tgtok::Def) 277 .Case("defm", tgtok::Defm) 278 .Case("multiclass", tgtok::MultiClass) 279 .Case("field", tgtok::Field) 280 .Case("let", tgtok::Let) 281 .Case("in", tgtok::In) 282 .Default(tgtok::Id); 283 284 if (Kind == tgtok::Id) 285 CurStrVal.assign(Str.begin(), Str.end()); 286 return Kind; 287 } 288 289 /// LexInclude - We just read the "include" token. Get the string token that 290 /// comes next and enter the include. 291 bool TGLexer::LexInclude() { 292 // The token after the include must be a string. 293 tgtok::TokKind Tok = LexToken(); 294 if (Tok == tgtok::Error) return true; 295 if (Tok != tgtok::StrVal) { 296 PrintError(getLoc(), "Expected filename after include"); 297 return true; 298 } 299 300 // Get the string. 301 std::string Filename = CurStrVal; 302 std::string IncludedFile; 303 304 305 CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr), 306 IncludedFile); 307 if (CurBuffer == -1) { 308 PrintError(getLoc(), "Could not find include file '" + Filename + "'"); 309 return true; 310 } 311 312 Dependencies.push_back(IncludedFile); 313 // Save the line number and lex buffer of the includer. 314 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); 315 CurPtr = CurBuf->getBufferStart(); 316 return false; 317 } 318 319 void TGLexer::SkipBCPLComment() { 320 ++CurPtr; // skip the second slash. 321 while (1) { 322 switch (*CurPtr) { 323 case '\n': 324 case '\r': 325 return; // Newline is end of comment. 326 case 0: 327 // If this is the end of the buffer, end the comment. 328 if (CurPtr == CurBuf->getBufferEnd()) 329 return; 330 break; 331 } 332 // Otherwise, skip the character. 333 ++CurPtr; 334 } 335 } 336 337 /// SkipCComment - This skips C-style /**/ comments. The only difference from C 338 /// is that we allow nesting. 339 bool TGLexer::SkipCComment() { 340 ++CurPtr; // skip the star. 341 unsigned CommentDepth = 1; 342 343 while (1) { 344 int CurChar = getNextChar(); 345 switch (CurChar) { 346 case EOF: 347 PrintError(TokStart, "Unterminated comment!"); 348 return true; 349 case '*': 350 // End of the comment? 351 if (CurPtr[0] != '/') break; 352 353 ++CurPtr; // End the */. 354 if (--CommentDepth == 0) 355 return false; 356 break; 357 case '/': 358 // Start of a nested comment? 359 if (CurPtr[0] != '*') break; 360 ++CurPtr; 361 ++CommentDepth; 362 break; 363 } 364 } 365 } 366 367 /// LexNumber - Lex: 368 /// [-+]?[0-9]+ 369 /// 0x[0-9a-fA-F]+ 370 /// 0b[01]+ 371 tgtok::TokKind TGLexer::LexNumber() { 372 if (CurPtr[-1] == '0') { 373 if (CurPtr[0] == 'x') { 374 ++CurPtr; 375 const char *NumStart = CurPtr; 376 while (isxdigit(CurPtr[0])) 377 ++CurPtr; 378 379 // Requires at least one hex digit. 380 if (CurPtr == NumStart) 381 return ReturnError(TokStart, "Invalid hexadecimal number"); 382 383 errno = 0; 384 CurIntVal = strtoll(NumStart, 0, 16); 385 if (errno == EINVAL) 386 return ReturnError(TokStart, "Invalid hexadecimal number"); 387 if (errno == ERANGE) { 388 errno = 0; 389 CurIntVal = (int64_t)strtoull(NumStart, 0, 16); 390 if (errno == EINVAL) 391 return ReturnError(TokStart, "Invalid hexadecimal number"); 392 if (errno == ERANGE) 393 return ReturnError(TokStart, "Hexadecimal number out of range"); 394 } 395 return tgtok::IntVal; 396 } else if (CurPtr[0] == 'b') { 397 ++CurPtr; 398 const char *NumStart = CurPtr; 399 while (CurPtr[0] == '0' || CurPtr[0] == '1') 400 ++CurPtr; 401 402 // Requires at least one binary digit. 403 if (CurPtr == NumStart) 404 return ReturnError(CurPtr-2, "Invalid binary number"); 405 CurIntVal = strtoll(NumStart, 0, 2); 406 return tgtok::IntVal; 407 } 408 } 409 410 // Check for a sign without a digit. 411 if (!isdigit(CurPtr[0])) { 412 if (CurPtr[-1] == '-') 413 return tgtok::minus; 414 else if (CurPtr[-1] == '+') 415 return tgtok::plus; 416 } 417 418 while (isdigit(CurPtr[0])) 419 ++CurPtr; 420 CurIntVal = strtoll(TokStart, 0, 10); 421 return tgtok::IntVal; 422 } 423 424 /// LexBracket - We just read '['. If this is a code block, return it, 425 /// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]' 426 tgtok::TokKind TGLexer::LexBracket() { 427 if (CurPtr[0] != '{') 428 return tgtok::l_square; 429 ++CurPtr; 430 const char *CodeStart = CurPtr; 431 while (1) { 432 int Char = getNextChar(); 433 if (Char == EOF) break; 434 435 if (Char != '}') continue; 436 437 Char = getNextChar(); 438 if (Char == EOF) break; 439 if (Char == ']') { 440 CurStrVal.assign(CodeStart, CurPtr-2); 441 return tgtok::CodeFragment; 442 } 443 } 444 445 return ReturnError(CodeStart-2, "Unterminated Code Block"); 446 } 447 448 /// LexExclaim - Lex '!' and '![a-zA-Z]+'. 449 tgtok::TokKind TGLexer::LexExclaim() { 450 if (!isalpha(*CurPtr)) 451 return ReturnError(CurPtr - 1, "Invalid \"!operator\""); 452 453 const char *Start = CurPtr++; 454 while (isalpha(*CurPtr)) 455 ++CurPtr; 456 457 // Check to see which operator this is. 458 tgtok::TokKind Kind = 459 StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start)) 460 .Case("eq", tgtok::XEq) 461 .Case("if", tgtok::XIf) 462 .Case("head", tgtok::XHead) 463 .Case("tail", tgtok::XTail) 464 .Case("con", tgtok::XConcat) 465 .Case("shl", tgtok::XSHL) 466 .Case("sra", tgtok::XSRA) 467 .Case("srl", tgtok::XSRL) 468 .Case("cast", tgtok::XCast) 469 .Case("empty", tgtok::XEmpty) 470 .Case("subst", tgtok::XSubst) 471 .Case("foreach", tgtok::XForEach) 472 .Case("strconcat", tgtok::XStrConcat) 473 .Default(tgtok::Error); 474 475 return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator"); 476 } 477 478