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 "TGSourceMgr.h"
16 #include "llvm/Support/Streams.h"
17 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Config/config.h"
27 TGLexer::TGLexer(TGSourceMgr &SM) : SrcMgr(SM) {
29 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);
30 CurPtr = CurBuf->getBufferStart();
34 TGLoc TGLexer::getLoc() const {
35 return TGLoc::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 std::string &Msg) {
47 void TGLexer::PrintError(const char *Loc, const std::string &Msg) const {
48 SrcMgr.PrintError(TGLoc::getFromPointer(Loc), Msg);
51 void TGLexer::PrintError(TGLoc Loc, const std::string &Msg) const {
52 SrcMgr.PrintError(Loc, Msg);
56 int TGLexer::getNextChar() {
57 char CurChar = *CurPtr++;
60 return (unsigned char)CurChar;
62 // A nul character in the stream is either the end of the current buffer or
63 // a random nul in the file. Disambiguate that here.
64 if (CurPtr-1 != CurBuf->getBufferEnd())
65 return 0; // Just whitespace.
67 // If this is the end of an included file, pop the parent file off the
69 TGLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
70 if (ParentIncludeLoc != TGLoc()) {
71 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
72 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);
73 CurPtr = ParentIncludeLoc.getPointer();
77 // Otherwise, return end of file.
78 --CurPtr; // Another call to lex will return EOF again.
83 // Handle the newline character by ignoring it and incrementing the line
84 // count. However, be careful about 'dos style' files with \n\r in them.
85 // Only treat a \n\r or \r\n as a single line.
86 if ((*CurPtr == '\n' || (*CurPtr == '\r')) &&
88 ++CurPtr; // Eat the two char newline sequence.
93 tgtok::TokKind TGLexer::LexToken() {
95 // This always consumes at least one character.
96 int CurChar = getNextChar();
100 // Handle letters: [a-zA-Z_]
101 if (isalpha(CurChar) || CurChar == '_')
102 return LexIdentifier();
104 // Unknown character, emit an error.
105 return ReturnError(TokStart, "Unexpected character");
106 case EOF: return tgtok::Eof;
107 case ':': return tgtok::colon;
108 case ';': return tgtok::semi;
109 case '.': return tgtok::period;
110 case ',': return tgtok::comma;
111 case '<': return tgtok::less;
112 case '>': return tgtok::greater;
113 case ']': return tgtok::r_square;
114 case '{': return tgtok::l_brace;
115 case '}': return tgtok::r_brace;
116 case '(': return tgtok::l_paren;
117 case ')': return tgtok::r_paren;
118 case '=': return tgtok::equal;
119 case '?': return tgtok::question;
126 // Ignore whitespace.
129 // If this is the start of a // comment, skip until the end of the line or
130 // the end of the buffer.
133 else if (*CurPtr == '*') {
136 } else // Otherwise, this is an error.
137 return ReturnError(TokStart, "Unexpected character");
140 case '0': case '1': case '2': case '3': case '4': case '5': case '6':
141 case '7': case '8': case '9':
143 case '"': return LexString();
144 case '$': return LexVarName();
145 case '[': return LexBracket();
146 case '!': return LexExclaim();
150 /// LexString - Lex "[^"]*"
151 tgtok::TokKind TGLexer::LexString() {
152 const char *StrStart = CurPtr;
156 while (*CurPtr != '"') {
157 // If we hit the end of the buffer, report an error.
158 if (*CurPtr == 0 && CurPtr == CurBuf->getBufferEnd())
159 return ReturnError(StrStart, "End of file in string literal");
161 if (*CurPtr == '\n' || *CurPtr == '\r')
162 return ReturnError(StrStart, "End of line in string literal");
164 if (*CurPtr != '\\') {
165 CurStrVal += *CurPtr++;
172 case '\\': case '\'': case '"':
173 // These turn into their literal character.
174 CurStrVal += *CurPtr++;
178 return ReturnError(CurPtr, "escaped newlines not supported in tblgen");
180 // If we hit the end of the buffer, report an error.
182 if (CurPtr == CurBuf->getBufferEnd())
183 return ReturnError(StrStart, "End of file in string literal");
186 return ReturnError(CurPtr, "invalid escape in string literal");
191 return tgtok::StrVal;
194 tgtok::TokKind TGLexer::LexVarName() {
195 if (!isalpha(CurPtr[0]) && CurPtr[0] != '_')
196 return ReturnError(TokStart, "Invalid variable name");
198 // Otherwise, we're ok, consume the rest of the characters.
199 const char *VarNameStart = CurPtr++;
201 while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
204 CurStrVal.assign(VarNameStart, CurPtr);
205 return tgtok::VarName;
209 tgtok::TokKind TGLexer::LexIdentifier() {
210 // The first letter is [a-zA-Z_].
211 const char *IdentStart = TokStart;
213 // Match the rest of the identifier regex: [0-9a-zA-Z_]*
214 while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
217 // Check to see if this identifier is a keyword.
218 unsigned Len = CurPtr-IdentStart;
220 if (Len == 3 && !memcmp(IdentStart, "int", 3)) return tgtok::Int;
221 if (Len == 3 && !memcmp(IdentStart, "bit", 3)) return tgtok::Bit;
222 if (Len == 4 && !memcmp(IdentStart, "bits", 4)) return tgtok::Bits;
223 if (Len == 6 && !memcmp(IdentStart, "string", 6)) return tgtok::String;
224 if (Len == 4 && !memcmp(IdentStart, "list", 4)) return tgtok::List;
225 if (Len == 4 && !memcmp(IdentStart, "code", 4)) return tgtok::Code;
226 if (Len == 3 && !memcmp(IdentStart, "dag", 3)) return tgtok::Dag;
228 if (Len == 5 && !memcmp(IdentStart, "class", 5)) return tgtok::Class;
229 if (Len == 3 && !memcmp(IdentStart, "def", 3)) return tgtok::Def;
230 if (Len == 4 && !memcmp(IdentStart, "defm", 4)) return tgtok::Defm;
231 if (Len == 10 && !memcmp(IdentStart, "multiclass", 10))
232 return tgtok::MultiClass;
233 if (Len == 5 && !memcmp(IdentStart, "field", 5)) return tgtok::Field;
234 if (Len == 3 && !memcmp(IdentStart, "let", 3)) return tgtok::Let;
235 if (Len == 2 && !memcmp(IdentStart, "in", 2)) return tgtok::In;
237 if (Len == 7 && !memcmp(IdentStart, "include", 7)) {
238 if (LexInclude()) return tgtok::Error;
242 CurStrVal.assign(IdentStart, CurPtr);
246 /// LexInclude - We just read the "include" token. Get the string token that
247 /// comes next and enter the include.
248 bool TGLexer::LexInclude() {
249 // The token after the include must be a string.
250 tgtok::TokKind Tok = LexToken();
251 if (Tok == tgtok::Error) return true;
252 if (Tok != tgtok::StrVal) {
253 PrintError(getLoc(), "Expected filename after include");
258 std::string Filename = CurStrVal;
260 // Try to find the file.
261 MemoryBuffer *NewBuf = MemoryBuffer::getFile(Filename.c_str());
263 // If the file didn't exist directly, see if it's in an include path.
264 for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
265 std::string IncFile = IncludeDirectories[i] + "/" + Filename;
266 NewBuf = MemoryBuffer::getFile(IncFile.c_str());
270 PrintError(getLoc(), "Could not find include file '" + Filename + "'");
274 // Save the line number and lex buffer of the includer.
275 CurBuffer = SrcMgr.AddNewSourceBuffer(NewBuf, TGLoc::getFromPointer(CurPtr));
278 CurPtr = CurBuf->getBufferStart();
282 void TGLexer::SkipBCPLComment() {
283 ++CurPtr; // skip the second slash.
288 return; // Newline is end of comment.
290 // If this is the end of the buffer, end the comment.
291 if (CurPtr == CurBuf->getBufferEnd())
295 // Otherwise, skip the character.
300 /// SkipCComment - This skips C-style /**/ comments. The only difference from C
301 /// is that we allow nesting.
302 bool TGLexer::SkipCComment() {
303 ++CurPtr; // skip the star.
304 unsigned CommentDepth = 1;
307 int CurChar = getNextChar();
310 PrintError(TokStart, "Unterminated comment!");
313 // End of the comment?
314 if (CurPtr[0] != '/') break;
316 ++CurPtr; // End the */.
317 if (--CommentDepth == 0)
321 // Start of a nested comment?
322 if (CurPtr[0] != '*') break;
334 tgtok::TokKind TGLexer::LexNumber() {
335 if (CurPtr[-1] == '0') {
336 if (CurPtr[0] == 'x') {
338 const char *NumStart = CurPtr;
339 while (isxdigit(CurPtr[0]))
342 // Requires at least one hex digit.
343 if (CurPtr == NumStart)
344 return ReturnError(CurPtr-2, "Invalid hexadecimal number");
347 CurIntVal = strtoll(NumStart, 0, 16);
349 return ReturnError(CurPtr-2, "Invalid hexadecimal number");
350 if (errno == ERANGE) {
352 CurIntVal = (int64_t)strtoull(NumStart, 0, 16);
354 return ReturnError(CurPtr-2, "Invalid hexadecimal number");
356 return ReturnError(CurPtr-2, "Hexadecimal number out of range");
358 return tgtok::IntVal;
359 } else if (CurPtr[0] == 'b') {
361 const char *NumStart = CurPtr;
362 while (CurPtr[0] == '0' || CurPtr[0] == '1')
365 // Requires at least one binary digit.
366 if (CurPtr == NumStart)
367 return ReturnError(CurPtr-2, "Invalid binary number");
368 CurIntVal = strtoll(NumStart, 0, 2);
369 return tgtok::IntVal;
373 // Check for a sign without a digit.
374 if (!isdigit(CurPtr[0])) {
375 if (CurPtr[-1] == '-')
377 else if (CurPtr[-1] == '+')
381 while (isdigit(CurPtr[0]))
383 CurIntVal = strtoll(TokStart, 0, 10);
384 return tgtok::IntVal;
387 /// LexBracket - We just read '['. If this is a code block, return it,
388 /// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
389 tgtok::TokKind TGLexer::LexBracket() {
390 if (CurPtr[0] != '{')
391 return tgtok::l_square;
393 const char *CodeStart = CurPtr;
395 int Char = getNextChar();
396 if (Char == EOF) break;
398 if (Char != '}') continue;
400 Char = getNextChar();
401 if (Char == EOF) break;
403 CurStrVal.assign(CodeStart, CurPtr-2);
404 return tgtok::CodeFragment;
408 return ReturnError(CodeStart-2, "Unterminated Code Block");
411 /// LexExclaim - Lex '!' and '![a-zA-Z]+'.
412 tgtok::TokKind TGLexer::LexExclaim() {
413 if (!isalpha(*CurPtr))
414 return ReturnError(CurPtr-1, "Invalid \"!operator\"");
416 const char *Start = CurPtr++;
417 while (isalpha(*CurPtr))
420 // Check to see which operator this is.
421 unsigned Len = CurPtr-Start;
423 if (Len == 3 && !memcmp(Start, "con", 3)) return tgtok::XConcat;
424 if (Len == 3 && !memcmp(Start, "sra", 3)) return tgtok::XSRA;
425 if (Len == 3 && !memcmp(Start, "srl", 3)) return tgtok::XSRL;
426 if (Len == 3 && !memcmp(Start, "shl", 3)) return tgtok::XSHL;
427 if (Len == 9 && !memcmp(Start, "strconcat", 9)) return tgtok::XStrConcat;
429 return ReturnError(Start-1, "Unknown operator");