1 //===- TGLexer.cpp - Lexer for TableGen -----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the Lexer for TableGen.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/TableGen/Error.h"
16 #include "llvm/Support/SourceMgr.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Config/config.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Twine.h"
28 TGLexer::TGLexer(SourceMgr &SM) : SrcMgr(SM) {
30 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);
31 CurPtr = CurBuf->getBufferStart();
35 SMLoc TGLexer::getLoc() const {
36 return SMLoc::getFromPointer(TokStart);
39 /// ReturnError - Set the error to the specified string at the specified
40 /// location. This is defined to always return tgtok::Error.
41 tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) {
46 int TGLexer::getNextChar() {
47 char CurChar = *CurPtr++;
50 return (unsigned char)CurChar;
52 // A nul character in the stream is either the end of the current buffer or
53 // a random nul in the file. Disambiguate that here.
54 if (CurPtr-1 != CurBuf->getBufferEnd())
55 return 0; // Just whitespace.
57 // If this is the end of an included file, pop the parent file off the
59 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
60 if (ParentIncludeLoc != SMLoc()) {
61 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
62 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);
63 CurPtr = ParentIncludeLoc.getPointer();
67 // Otherwise, return end of file.
68 --CurPtr; // Another call to lex will return EOF again.
73 // Handle the newline character by ignoring it and incrementing the line
74 // count. However, be careful about 'dos style' files with \n\r in them.
75 // Only treat a \n\r or \r\n as a single line.
76 if ((*CurPtr == '\n' || (*CurPtr == '\r')) &&
78 ++CurPtr; // Eat the two char newline sequence.
83 tgtok::TokKind TGLexer::LexToken() {
85 // This always consumes at least one character.
86 int CurChar = getNextChar();
90 // Handle letters: [a-zA-Z_#]
91 if (isalpha(CurChar) || CurChar == '_' || CurChar == '#')
92 return LexIdentifier();
94 // Unknown character, emit an error.
95 return ReturnError(TokStart, "Unexpected character");
96 case EOF: return tgtok::Eof;
97 case ':': return tgtok::colon;
98 case ';': return tgtok::semi;
99 case '.': return tgtok::period;
100 case ',': return tgtok::comma;
101 case '<': return tgtok::less;
102 case '>': return tgtok::greater;
103 case ']': return tgtok::r_square;
104 case '{': return tgtok::l_brace;
105 case '}': return tgtok::r_brace;
106 case '(': return tgtok::l_paren;
107 case ')': return tgtok::r_paren;
108 case '=': return tgtok::equal;
109 case '?': return tgtok::question;
116 // Ignore whitespace.
119 // If this is the start of a // comment, skip until the end of the line or
120 // the end of the buffer.
123 else if (*CurPtr == '*') {
126 } else // Otherwise, this is an error.
127 return ReturnError(TokStart, "Unexpected character");
130 case '0': case '1': case '2': case '3': case '4': case '5': case '6':
131 case '7': case '8': case '9':
133 case '"': return LexString();
134 case '$': return LexVarName();
135 case '[': return LexBracket();
136 case '!': return LexExclaim();
140 /// LexString - Lex "[^"]*"
141 tgtok::TokKind TGLexer::LexString() {
142 const char *StrStart = CurPtr;
146 while (*CurPtr != '"') {
147 // If we hit the end of the buffer, report an error.
148 if (*CurPtr == 0 && CurPtr == CurBuf->getBufferEnd())
149 return ReturnError(StrStart, "End of file in string literal");
151 if (*CurPtr == '\n' || *CurPtr == '\r')
152 return ReturnError(StrStart, "End of line in string literal");
154 if (*CurPtr != '\\') {
155 CurStrVal += *CurPtr++;
162 case '\\': case '\'': case '"':
163 // These turn into their literal character.
164 CurStrVal += *CurPtr++;
177 return ReturnError(CurPtr, "escaped newlines not supported in tblgen");
179 // If we hit the end of the buffer, report an error.
181 if (CurPtr == CurBuf->getBufferEnd())
182 return ReturnError(StrStart, "End of file in string literal");
185 return ReturnError(CurPtr, "invalid escape in string literal");
190 return tgtok::StrVal;
193 tgtok::TokKind TGLexer::LexVarName() {
194 if (!isalpha(CurPtr[0]) && CurPtr[0] != '_')
195 return ReturnError(TokStart, "Invalid variable name");
197 // Otherwise, we're ok, consume the rest of the characters.
198 const char *VarNameStart = CurPtr++;
200 while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
203 CurStrVal.assign(VarNameStart, CurPtr);
204 return tgtok::VarName;
208 tgtok::TokKind TGLexer::LexIdentifier() {
209 // The first letter is [a-zA-Z_#].
210 const char *IdentStart = TokStart;
212 // Match the rest of the identifier regex: [0-9a-zA-Z_#]*
213 while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_' ||
217 // Check to see if this identifier is a keyword.
218 StringRef Str(IdentStart, CurPtr-IdentStart);
220 if (Str == "include") {
221 if (LexInclude()) return tgtok::Error;
225 tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(Str)
226 .Case("int", tgtok::Int)
227 .Case("bit", tgtok::Bit)
228 .Case("bits", tgtok::Bits)
229 .Case("string", tgtok::String)
230 .Case("list", tgtok::List)
231 .Case("code", tgtok::Code)
232 .Case("dag", tgtok::Dag)
233 .Case("class", tgtok::Class)
234 .Case("def", tgtok::Def)
235 .Case("multidef", tgtok::MultiDef)
236 .Case("defm", tgtok::Defm)
237 .Case("multiclass", tgtok::MultiClass)
238 .Case("field", tgtok::Field)
239 .Case("let", tgtok::Let)
240 .Case("in", tgtok::In)
243 if (Kind == tgtok::Id)
244 CurStrVal.assign(Str.begin(), Str.end());
248 /// LexInclude - We just read the "include" token. Get the string token that
249 /// comes next and enter the include.
250 bool TGLexer::LexInclude() {
251 // The token after the include must be a string.
252 tgtok::TokKind Tok = LexToken();
253 if (Tok == tgtok::Error) return true;
254 if (Tok != tgtok::StrVal) {
255 PrintError(getLoc(), "Expected filename after include");
260 std::string Filename = CurStrVal;
261 std::string IncludedFile;
264 CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr),
266 if (CurBuffer == -1) {
267 PrintError(getLoc(), "Could not find include file '" + Filename + "'");
271 Dependencies.push_back(IncludedFile);
272 // Save the line number and lex buffer of the includer.
273 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);
274 CurPtr = CurBuf->getBufferStart();
278 void TGLexer::SkipBCPLComment() {
279 ++CurPtr; // skip the second slash.
284 return; // Newline is end of comment.
286 // If this is the end of the buffer, end the comment.
287 if (CurPtr == CurBuf->getBufferEnd())
291 // Otherwise, skip the character.
296 /// SkipCComment - This skips C-style /**/ comments. The only difference from C
297 /// is that we allow nesting.
298 bool TGLexer::SkipCComment() {
299 ++CurPtr; // skip the star.
300 unsigned CommentDepth = 1;
303 int CurChar = getNextChar();
306 PrintError(TokStart, "Unterminated comment!");
309 // End of the comment?
310 if (CurPtr[0] != '/') break;
312 ++CurPtr; // End the */.
313 if (--CommentDepth == 0)
317 // Start of a nested comment?
318 if (CurPtr[0] != '*') break;
330 tgtok::TokKind TGLexer::LexNumber() {
331 if (CurPtr[-1] == '0') {
332 if (CurPtr[0] == 'x') {
334 const char *NumStart = CurPtr;
335 while (isxdigit(CurPtr[0]))
338 // Requires at least one hex digit.
339 if (CurPtr == NumStart)
340 return ReturnError(TokStart, "Invalid hexadecimal number");
343 CurIntVal = strtoll(NumStart, 0, 16);
345 return ReturnError(TokStart, "Invalid hexadecimal number");
346 if (errno == ERANGE) {
348 CurIntVal = (int64_t)strtoull(NumStart, 0, 16);
350 return ReturnError(TokStart, "Invalid hexadecimal number");
352 return ReturnError(TokStart, "Hexadecimal number out of range");
354 return tgtok::IntVal;
355 } else if (CurPtr[0] == 'b') {
357 const char *NumStart = CurPtr;
358 while (CurPtr[0] == '0' || CurPtr[0] == '1')
361 // Requires at least one binary digit.
362 if (CurPtr == NumStart)
363 return ReturnError(CurPtr-2, "Invalid binary number");
364 CurIntVal = strtoll(NumStart, 0, 2);
365 return tgtok::IntVal;
369 // Check for a sign without a digit.
370 if (!isdigit(CurPtr[0])) {
371 if (CurPtr[-1] == '-')
373 else if (CurPtr[-1] == '+')
377 while (isdigit(CurPtr[0]))
379 CurIntVal = strtoll(TokStart, 0, 10);
380 return tgtok::IntVal;
383 /// LexBracket - We just read '['. If this is a code block, return it,
384 /// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
385 tgtok::TokKind TGLexer::LexBracket() {
386 if (CurPtr[0] != '{')
387 return tgtok::l_square;
389 const char *CodeStart = CurPtr;
391 int Char = getNextChar();
392 if (Char == EOF) break;
394 if (Char != '}') continue;
396 Char = getNextChar();
397 if (Char == EOF) break;
399 CurStrVal.assign(CodeStart, CurPtr-2);
400 return tgtok::CodeFragment;
404 return ReturnError(CodeStart-2, "Unterminated Code Block");
407 /// LexExclaim - Lex '!' and '![a-zA-Z]+'.
408 tgtok::TokKind TGLexer::LexExclaim() {
409 if (!isalpha(*CurPtr))
410 return ReturnError(CurPtr - 1, "Invalid \"!operator\"");
412 const char *Start = CurPtr++;
413 while (isalpha(*CurPtr))
416 // Check to see which operator this is.
417 tgtok::TokKind Kind =
418 StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start))
419 .Case("eq", tgtok::XEq)
420 .Case("if", tgtok::XIf)
421 .Case("head", tgtok::XHead)
422 .Case("tail", tgtok::XTail)
423 .Case("con", tgtok::XConcat)
424 .Case("shl", tgtok::XSHL)
425 .Case("sra", tgtok::XSRA)
426 .Case("srl", tgtok::XSRL)
427 .Case("cast", tgtok::XCast)
428 .Case("empty", tgtok::XEmpty)
429 .Case("subst", tgtok::XSubst)
430 .Case("foreach", tgtok::XForEach)
431 .Case("strconcat", tgtok::XStrConcat)
432 .Default(tgtok::Error);
434 return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator");