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/Support/Streams.h"
16 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Config/config.h"
24 TGLexer::TGLexer(MemoryBuffer *StartBuf) : CurLineNo(1), CurBuf(StartBuf) {
25 CurPtr = CurBuf->getBufferStart();
30 while (!IncludeStack.empty()) {
31 delete IncludeStack.back().Buffer;
32 IncludeStack.pop_back();
37 /// ReturnError - Set the error to the specified string at the specified
38 /// location. This is defined to always return tgtok::Error.
39 tgtok::TokKind TGLexer::ReturnError(const char *Loc, const std::string &Msg) {
44 void TGLexer::PrintIncludeStack(std::ostream &OS) const {
45 for (unsigned i = 0, e = IncludeStack.size(); i != e; ++i)
46 OS << "Included from " << IncludeStack[i].Buffer->getBufferIdentifier()
47 << ":" << IncludeStack[i].LineNo << ":\n";
48 OS << "Parsing " << CurBuf->getBufferIdentifier() << ":"
52 /// PrintError - Print the error at the specified location.
53 void TGLexer::PrintError(const char *ErrorLoc, const std::string &Msg) const {
54 PrintIncludeStack(*cerr.stream());
56 assert(ErrorLoc && "Location not specified!");
58 // Scan backward to find the start of the line.
59 const char *LineStart = ErrorLoc;
60 while (LineStart != CurBuf->getBufferStart() &&
61 LineStart[-1] != '\n' && LineStart[-1] != '\r')
63 // Get the end of the line.
64 const char *LineEnd = ErrorLoc;
65 while (LineEnd != CurBuf->getBufferEnd() &&
66 LineEnd[0] != '\n' && LineEnd[0] != '\r')
68 // Print out the line.
69 cerr << std::string(LineStart, LineEnd) << "\n";
70 // Print out spaces before the carat.
71 for (const char *Pos = LineStart; Pos != ErrorLoc; ++Pos)
72 cerr << (*Pos == '\t' ? '\t' : ' ');
76 int TGLexer::getNextChar() {
77 char CurChar = *CurPtr++;
80 return (unsigned char)CurChar;
82 // A nul character in the stream is either the end of the current buffer or
83 // a random nul in the file. Disambiguate that here.
84 if (CurPtr-1 != CurBuf->getBufferEnd())
85 return 0; // Just whitespace.
87 // If this is the end of an included file, pop the parent file off the
89 if (!IncludeStack.empty()) {
91 CurBuf = IncludeStack.back().Buffer;
92 CurLineNo = IncludeStack.back().LineNo;
93 CurPtr = IncludeStack.back().CurPtr;
94 IncludeStack.pop_back();
98 // Otherwise, return end of file.
99 --CurPtr; // Another call to lex will return EOF again.
103 // Handle the newline character by ignoring it and incrementing the line
104 // count. However, be careful about 'dos style' files with \n\r in them.
105 // Only treat a \n\r or \r\n as a single line.
106 if ((*CurPtr == '\n' || (*CurPtr == '\r')) &&
108 ++CurPtr; // Eat the two char newline sequence.
115 tgtok::TokKind TGLexer::LexToken() {
117 // This always consumes at least one character.
118 int CurChar = getNextChar();
122 // Handle letters: [a-zA-Z_]
123 if (isalpha(CurChar) || CurChar == '_')
124 return LexIdentifier();
126 // Unknown character, emit an error.
127 return ReturnError(TokStart, "Unexpected character");
128 case EOF: return tgtok::Eof;
129 case ':': return tgtok::colon;
130 case ';': return tgtok::semi;
131 case '.': return tgtok::period;
132 case ',': return tgtok::comma;
133 case '<': return tgtok::less;
134 case '>': return tgtok::greater;
135 case ']': return tgtok::r_square;
136 case '{': return tgtok::l_brace;
137 case '}': return tgtok::r_brace;
138 case '(': return tgtok::l_paren;
139 case ')': return tgtok::r_paren;
140 case '=': return tgtok::equal;
141 case '?': return tgtok::question;
148 // Ignore whitespace.
151 // If this is the start of a // comment, skip until the end of the line or
152 // the end of the buffer.
155 else if (*CurPtr == '*') {
158 } else // Otherwise, this is an error.
159 return ReturnError(TokStart, "Unexpected character");
162 case '0': case '1': case '2': case '3': case '4': case '5': case '6':
163 case '7': case '8': case '9':
165 case '"': return LexString();
166 case '$': return LexVarName();
167 case '[': return LexBracket();
168 case '!': return LexExclaim();
172 /// LexString - Lex "[^"]*"
173 tgtok::TokKind TGLexer::LexString() {
174 const char *StrStart = CurPtr;
176 while (*CurPtr != '"') {
177 // If we hit the end of the buffer, report an error.
178 if (*CurPtr == 0 && CurPtr == CurBuf->getBufferEnd())
179 return ReturnError(StrStart, "End of file in string literal");
181 if (*CurPtr == '\n' || *CurPtr == '\r')
182 return ReturnError(StrStart, "End of line in string literal");
187 CurStrVal.assign(StrStart, CurPtr);
189 return tgtok::StrVal;
192 tgtok::TokKind TGLexer::LexVarName() {
193 if (!isalpha(CurPtr[0]) && CurPtr[0] != '_')
194 return ReturnError(TokStart, "Invalid variable name");
196 // Otherwise, we're ok, consume the rest of the characters.
197 const char *VarNameStart = CurPtr++;
199 while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
202 CurStrVal.assign(VarNameStart, CurPtr);
203 return tgtok::VarName;
207 tgtok::TokKind TGLexer::LexIdentifier() {
208 // The first letter is [a-zA-Z_].
209 const char *IdentStart = TokStart;
211 // Match the rest of the identifier regex: [0-9a-zA-Z_]*
212 while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
215 // Check to see if this identifier is a keyword.
216 unsigned Len = CurPtr-IdentStart;
218 if (Len == 3 && !memcmp(IdentStart, "int", 3)) return tgtok::Int;
219 if (Len == 3 && !memcmp(IdentStart, "bit", 3)) return tgtok::Bit;
220 if (Len == 4 && !memcmp(IdentStart, "bits", 4)) return tgtok::Bits;
221 if (Len == 6 && !memcmp(IdentStart, "string", 6)) return tgtok::String;
222 if (Len == 4 && !memcmp(IdentStart, "list", 4)) return tgtok::List;
223 if (Len == 4 && !memcmp(IdentStart, "code", 4)) return tgtok::Code;
224 if (Len == 3 && !memcmp(IdentStart, "dag", 3)) return tgtok::Dag;
226 if (Len == 5 && !memcmp(IdentStart, "class", 5)) return tgtok::Class;
227 if (Len == 3 && !memcmp(IdentStart, "def", 3)) return tgtok::Def;
228 if (Len == 4 && !memcmp(IdentStart, "defm", 4)) return tgtok::Defm;
229 if (Len == 10 && !memcmp(IdentStart, "multiclass", 10))
230 return tgtok::MultiClass;
231 if (Len == 5 && !memcmp(IdentStart, "field", 5)) return tgtok::Field;
232 if (Len == 3 && !memcmp(IdentStart, "let", 3)) return tgtok::Let;
233 if (Len == 2 && !memcmp(IdentStart, "in", 2)) return tgtok::In;
235 if (Len == 7 && !memcmp(IdentStart, "include", 7)) {
236 if (LexInclude()) return tgtok::Error;
240 CurStrVal.assign(IdentStart, CurPtr);
244 /// LexInclude - We just read the "include" token. Get the string token that
245 /// comes next and enter the include.
246 bool TGLexer::LexInclude() {
247 // The token after the include must be a string.
248 tgtok::TokKind Tok = LexToken();
249 if (Tok == tgtok::Error) return true;
250 if (Tok != tgtok::StrVal) {
251 PrintError(getLoc(), "Expected filename after include");
256 std::string Filename = CurStrVal;
258 // Try to find the file.
259 MemoryBuffer *NewBuf = MemoryBuffer::getFile(Filename.c_str());
261 // If the file didn't exist directly, see if it's in an include path.
262 for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
263 std::string IncFile = IncludeDirectories[i] + "/" + Filename;
264 NewBuf = MemoryBuffer::getFile(IncFile.c_str());
268 PrintError(getLoc(), "Could not find include file '" + Filename + "'");
272 // Save the line number and lex buffer of the includer.
273 IncludeStack.push_back(IncludeRec(CurBuf, CurPtr, CurLineNo));
275 CurLineNo = 1; // Reset line numbering.
277 CurPtr = CurBuf->getBufferStart();
281 void TGLexer::SkipBCPLComment() {
282 ++CurPtr; // skip the second slash.
287 return; // Newline is end of comment.
289 // If this is the end of the buffer, end the comment.
290 if (CurPtr == CurBuf->getBufferEnd())
294 // Otherwise, skip the character.
299 /// SkipCComment - This skips C-style /**/ comments. The only difference from C
300 /// is that we allow nesting.
301 bool TGLexer::SkipCComment() {
302 ++CurPtr; // skip the star.
303 unsigned CommentDepth = 1;
306 int CurChar = getNextChar();
309 PrintError(TokStart, "Unterminated comment!");
312 // End of the comment?
313 if (CurPtr[0] != '/') break;
315 ++CurPtr; // End the */.
316 if (--CommentDepth == 0)
320 // Start of a nested comment?
321 if (CurPtr[0] != '*') break;
333 tgtok::TokKind TGLexer::LexNumber() {
334 if (CurPtr[-1] == '0') {
335 if (CurPtr[0] == 'x') {
337 const char *NumStart = CurPtr;
338 while (isxdigit(CurPtr[0]))
341 // Requires at least one hex digit.
342 if (CurPtr == NumStart)
343 return ReturnError(CurPtr-2, "Invalid hexadecimal number");
345 CurIntVal = strtoll(NumStart, 0, 16);
346 return tgtok::IntVal;
347 } else if (CurPtr[0] == 'b') {
349 const char *NumStart = CurPtr;
350 while (CurPtr[0] == '0' || CurPtr[0] == '1')
353 // Requires at least one binary digit.
354 if (CurPtr == NumStart)
355 return ReturnError(CurPtr-2, "Invalid binary number");
356 CurIntVal = strtoll(NumStart, 0, 2);
357 return tgtok::IntVal;
361 // Check for a sign without a digit.
362 if (!isdigit(CurPtr[0])) {
363 if (CurPtr[-1] == '-')
365 else if (CurPtr[-1] == '+')
369 while (isdigit(CurPtr[0]))
371 CurIntVal = strtoll(TokStart, 0, 10);
372 return tgtok::IntVal;
375 /// LexBracket - We just read '['. If this is a code block, return it,
376 /// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
377 tgtok::TokKind TGLexer::LexBracket() {
378 if (CurPtr[0] != '{')
379 return tgtok::l_square;
381 const char *CodeStart = CurPtr;
383 int Char = getNextChar();
384 if (Char == EOF) break;
386 if (Char != '}') continue;
388 Char = getNextChar();
389 if (Char == EOF) break;
391 CurStrVal.assign(CodeStart, CurPtr-2);
392 return tgtok::CodeFragment;
396 return ReturnError(CodeStart-2, "Unterminated Code Block");
399 /// LexExclaim - Lex '!' and '![a-zA-Z]+'.
400 tgtok::TokKind TGLexer::LexExclaim() {
401 if (!isalpha(*CurPtr))
402 return ReturnError(CurPtr-1, "Invalid \"!operator\"");
404 const char *Start = CurPtr++;
405 while (isalpha(*CurPtr))
408 // Check to see which operator this is.
409 unsigned Len = CurPtr-Start;
411 if (Len == 3 && !memcmp(Start, "con", 3)) return tgtok::XConcat;
412 if (Len == 3 && !memcmp(Start, "sra", 3)) return tgtok::XSRA;
413 if (Len == 3 && !memcmp(Start, "srl", 3)) return tgtok::XSRL;
414 if (Len == 3 && !memcmp(Start, "shl", 3)) return tgtok::XSHL;
415 if (Len == 9 && !memcmp(Start, "strconcat", 9)) return tgtok::XStrConcat;
417 return ReturnError(Start-1, "Unknown operator");