#include "TGLexer.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/TableGen/Error.h"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace llvm;
namespace {
struct {
tgtok::TokKind Kind;
const char *Word;
} PreprocessorDirs[] = {
{ tgtok::Ifdef, "ifdef" },
{ tgtok::Ifndef, "ifndef" },
{ tgtok::Else, "else" },
{ tgtok::Endif, "endif" },
{ tgtok::Define, "define" }
};
}
TGLexer::TGLexer(SourceMgr &SM, ArrayRef<std::string> Macros) : SrcMgr(SM) {
CurBuffer = SrcMgr.getMainFileID();
CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
CurPtr = CurBuf.begin();
TokStart = nullptr;
PrepIncludeStack.push_back(
std::make_unique<std::vector<PreprocessorControlDesc>>());
for (const std::string &MacroName : Macros)
DefinedMacros.insert(MacroName);
}
SMLoc TGLexer::getLoc() const {
return SMLoc::getFromPointer(TokStart);
}
tgtok::TokKind TGLexer::ReturnError(SMLoc Loc, const Twine &Msg) {
PrintError(Loc, Msg);
return tgtok::Error;
}
tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) {
return ReturnError(SMLoc::getFromPointer(Loc), Msg);
}
bool TGLexer::processEOF() {
SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
if (ParentIncludeLoc != SMLoc()) {
if (!prepExitInclude(false))
return false;
CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
CurPtr = ParentIncludeLoc.getPointer();
TokStart = CurPtr;
return true;
}
prepExitInclude(true);
return false;
}
int TGLexer::getNextChar() {
char CurChar = *CurPtr++;
switch (CurChar) {
default:
return (unsigned char)CurChar;
case 0: {
if (CurPtr - 1 == CurBuf.end()) {
--CurPtr; return EOF;
}
PrintError(getLoc(),
"NUL character is invalid in source; treated as space");
return ' ';
}
case '\n':
case '\r':
if ((*CurPtr == '\n' || (*CurPtr == '\r')) &&
*CurPtr != CurChar)
++CurPtr; return '\n';
}
}
int TGLexer::peekNextChar(int Index) const {
return *(CurPtr + Index);
}
tgtok::TokKind TGLexer::LexToken(bool FileOrLineStart) {
TokStart = CurPtr;
int CurChar = getNextChar();
switch (CurChar) {
default:
if (isalpha(CurChar) || CurChar == '_')
return LexIdentifier();
return ReturnError(TokStart, "Unexpected character");
case EOF:
if (processEOF())
return LexToken();
return tgtok::Eof;
case ':': return tgtok::colon;
case ';': return tgtok::semi;
case ',': return tgtok::comma;
case '<': return tgtok::less;
case '>': return tgtok::greater;
case ']': return tgtok::r_square;
case '{': return tgtok::l_brace;
case '}': return tgtok::r_brace;
case '(': return tgtok::l_paren;
case ')': return tgtok::r_paren;
case '=': return tgtok::equal;
case '?': return tgtok::question;
case '#':
if (FileOrLineStart) {
tgtok::TokKind Kind = prepIsDirective();
if (Kind != tgtok::Error)
return lexPreprocessor(Kind);
}
return tgtok::paste;
case '.':
if (peekNextChar(0) == '.') {
++CurPtr; if (peekNextChar(0) == '.') {
++CurPtr; return tgtok::dotdotdot;
}
return ReturnError(TokStart, "Invalid '..' punctuation");
}
return tgtok::dot;
case '\r':
PrintFatalError("getNextChar() must never return '\r'");
return tgtok::Error;
case ' ':
case '\t':
return LexToken(FileOrLineStart);
case '\n':
return LexToken(true);
case '/':
if (*CurPtr == '/')
SkipBCPLComment();
else if (*CurPtr == '*') {
if (SkipCComment())
return tgtok::Error;
} else return ReturnError(TokStart, "Unexpected character");
return LexToken(FileOrLineStart);
case '-': case '+':
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9': {
int NextChar = 0;
if (isdigit(CurChar)) {
int i = 0;
do {
NextChar = peekNextChar(i++);
} while (isdigit(NextChar));
if (NextChar == 'x' || NextChar == 'b') {
int NextNextChar = peekNextChar(i);
switch (NextNextChar) {
default:
break;
case '0': case '1':
if (NextChar == 'b')
return LexNumber();
LLVM_FALLTHROUGH;
case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
if (NextChar == 'x')
return LexNumber();
break;
}
}
}
if (isalpha(NextChar) || NextChar == '_')
return LexIdentifier();
return LexNumber();
}
case '"': return LexString();
case '$': return LexVarName();
case '[': return LexBracket();
case '!': return LexExclaim();
}
}
tgtok::TokKind TGLexer::LexString() {
const char *StrStart = CurPtr;
CurStrVal = "";
while (*CurPtr != '"') {
if (*CurPtr == 0 && CurPtr == CurBuf.end())
return ReturnError(StrStart, "End of file in string literal");
if (*CurPtr == '\n' || *CurPtr == '\r')
return ReturnError(StrStart, "End of line in string literal");
if (*CurPtr != '\\') {
CurStrVal += *CurPtr++;
continue;
}
++CurPtr;
switch (*CurPtr) {
case '\\': case '\'': case '"':
CurStrVal += *CurPtr++;
break;
case 't':
CurStrVal += '\t';
++CurPtr;
break;
case 'n':
CurStrVal += '\n';
++CurPtr;
break;
case '\n':
case '\r':
return ReturnError(CurPtr, "escaped newlines not supported in tblgen");
case '\0':
if (CurPtr == CurBuf.end())
return ReturnError(StrStart, "End of file in string literal");
LLVM_FALLTHROUGH;
default:
return ReturnError(CurPtr, "invalid escape in string literal");
}
}
++CurPtr;
return tgtok::StrVal;
}
tgtok::TokKind TGLexer::LexVarName() {
if (!isalpha(CurPtr[0]) && CurPtr[0] != '_')
return ReturnError(TokStart, "Invalid variable name");
const char *VarNameStart = CurPtr++;
while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
++CurPtr;
CurStrVal.assign(VarNameStart, CurPtr);
return tgtok::VarName;
}
tgtok::TokKind TGLexer::LexIdentifier() {
const char *IdentStart = TokStart;
while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
++CurPtr;
StringRef Str(IdentStart, CurPtr-IdentStart);
tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(Str)
.Case("int", tgtok::Int)
.Case("bit", tgtok::Bit)
.Case("bits", tgtok::Bits)
.Case("string", tgtok::String)
.Case("list", tgtok::List)
.Case("code", tgtok::Code)
.Case("dag", tgtok::Dag)
.Case("class", tgtok::Class)
.Case("def", tgtok::Def)
.Case("true", tgtok::TrueVal)
.Case("false", tgtok::FalseVal)
.Case("foreach", tgtok::Foreach)
.Case("defm", tgtok::Defm)
.Case("defset", tgtok::Defset)
.Case("multiclass", tgtok::MultiClass)
.Case("field", tgtok::Field)
.Case("let", tgtok::Let)
.Case("in", tgtok::In)
.Case("defvar", tgtok::Defvar)
.Case("include", tgtok::Include)
.Case("if", tgtok::If)
.Case("then", tgtok::Then)
.Case("else", tgtok::ElseKW)
.Case("assert", tgtok::Assert)
.Default(tgtok::Id);
switch (Kind) {
case tgtok::Include:
if (LexInclude()) return tgtok::Error;
return Lex();
case tgtok::Id:
CurStrVal.assign(Str.begin(), Str.end());
break;
default:
break;
}
return Kind;
}
bool TGLexer::LexInclude() {
tgtok::TokKind Tok = LexToken();
if (Tok == tgtok::Error) return true;
if (Tok != tgtok::StrVal) {
PrintError(getLoc(), "Expected filename after include");
return true;
}
std::string Filename = CurStrVal;
std::string IncludedFile;
CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr),
IncludedFile);
if (!CurBuffer) {
PrintError(getLoc(), "Could not find include file '" + Filename + "'");
return true;
}
Dependencies.insert(IncludedFile);
CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
CurPtr = CurBuf.begin();
PrepIncludeStack.push_back(
std::make_unique<std::vector<PreprocessorControlDesc>>());
return false;
}
void TGLexer::SkipBCPLComment() {
++CurPtr; auto EOLPos = CurBuf.find_first_of("\r\n", CurPtr - CurBuf.data());
CurPtr = (EOLPos == StringRef::npos) ? CurBuf.end() : CurBuf.data() + EOLPos;
}
bool TGLexer::SkipCComment() {
++CurPtr; unsigned CommentDepth = 1;
while (true) {
int CurChar = getNextChar();
switch (CurChar) {
case EOF:
PrintError(TokStart, "Unterminated comment!");
return true;
case '*':
if (CurPtr[0] != '/') break;
++CurPtr; if (--CommentDepth == 0)
return false;
break;
case '/':
if (CurPtr[0] != '*') break;
++CurPtr;
++CommentDepth;
break;
}
}
}
tgtok::TokKind TGLexer::LexNumber() {
if (CurPtr[-1] == '0') {
if (CurPtr[0] == 'x') {
++CurPtr;
const char *NumStart = CurPtr;
while (isxdigit(CurPtr[0]))
++CurPtr;
if (CurPtr == NumStart)
return ReturnError(TokStart, "Invalid hexadecimal number");
errno = 0;
CurIntVal = strtoll(NumStart, nullptr, 16);
if (errno == EINVAL)
return ReturnError(TokStart, "Invalid hexadecimal number");
if (errno == ERANGE) {
errno = 0;
CurIntVal = (int64_t)strtoull(NumStart, nullptr, 16);
if (errno == EINVAL)
return ReturnError(TokStart, "Invalid hexadecimal number");
if (errno == ERANGE)
return ReturnError(TokStart, "Hexadecimal number out of range");
}
return tgtok::IntVal;
} else if (CurPtr[0] == 'b') {
++CurPtr;
const char *NumStart = CurPtr;
while (CurPtr[0] == '0' || CurPtr[0] == '1')
++CurPtr;
if (CurPtr == NumStart)
return ReturnError(CurPtr-2, "Invalid binary number");
CurIntVal = strtoll(NumStart, nullptr, 2);
return tgtok::BinaryIntVal;
}
}
if (!isdigit(CurPtr[0])) {
if (CurPtr[-1] == '-')
return tgtok::minus;
else if (CurPtr[-1] == '+')
return tgtok::plus;
}
while (isdigit(CurPtr[0]))
++CurPtr;
CurIntVal = strtoll(TokStart, nullptr, 10);
return tgtok::IntVal;
}
tgtok::TokKind TGLexer::LexBracket() {
if (CurPtr[0] != '{')
return tgtok::l_square;
++CurPtr;
const char *CodeStart = CurPtr;
while (true) {
int Char = getNextChar();
if (Char == EOF) break;
if (Char != '}') continue;
Char = getNextChar();
if (Char == EOF) break;
if (Char == ']') {
CurStrVal.assign(CodeStart, CurPtr-2);
return tgtok::CodeFragment;
}
}
return ReturnError(CodeStart - 2, "Unterminated code block");
}
tgtok::TokKind TGLexer::LexExclaim() {
if (!isalpha(*CurPtr))
return ReturnError(CurPtr - 1, "Invalid \"!operator\"");
const char *Start = CurPtr++;
while (isalpha(*CurPtr))
++CurPtr;
tgtok::TokKind Kind =
StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start))
.Case("eq", tgtok::XEq)
.Case("ne", tgtok::XNe)
.Case("le", tgtok::XLe)
.Case("lt", tgtok::XLt)
.Case("ge", tgtok::XGe)
.Case("gt", tgtok::XGt)
.Case("if", tgtok::XIf)
.Case("cond", tgtok::XCond)
.Case("isa", tgtok::XIsA)
.Case("head", tgtok::XHead)
.Case("tail", tgtok::XTail)
.Case("size", tgtok::XSize)
.Case("con", tgtok::XConcat)
.Case("dag", tgtok::XDag)
.Case("add", tgtok::XADD)
.Case("sub", tgtok::XSUB)
.Case("mul", tgtok::XMUL)
.Case("not", tgtok::XNOT)
.Case("and", tgtok::XAND)
.Case("or", tgtok::XOR)
.Case("xor", tgtok::XXOR)
.Case("shl", tgtok::XSHL)
.Case("sra", tgtok::XSRA)
.Case("srl", tgtok::XSRL)
.Case("cast", tgtok::XCast)
.Case("empty", tgtok::XEmpty)
.Case("subst", tgtok::XSubst)
.Case("foldl", tgtok::XFoldl)
.Case("foreach", tgtok::XForEach)
.Case("filter", tgtok::XFilter)
.Case("listconcat", tgtok::XListConcat)
.Case("listsplat", tgtok::XListSplat)
.Case("strconcat", tgtok::XStrConcat)
.Case("interleave", tgtok::XInterleave)
.Case("substr", tgtok::XSubstr)
.Case("find", tgtok::XFind)
.Cases("setdagop", "setop", tgtok::XSetDagOp) .Cases("getdagop", "getop", tgtok::XGetDagOp) .Case("exists", tgtok::XExists)
.Default(tgtok::Error);
return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator");
}
bool TGLexer::prepExitInclude(bool IncludeStackMustBeEmpty) {
if (!PrepIncludeStack.back()->empty()) {
prepReportPreprocessorStackError();
return false;
}
if (PrepIncludeStack.empty()) {
PrintFatalError("Preprocessor include stack is empty");
}
PrepIncludeStack.pop_back();
if (IncludeStackMustBeEmpty) {
if (!PrepIncludeStack.empty())
PrintFatalError("Preprocessor include stack is not empty");
} else {
if (PrepIncludeStack.empty())
PrintFatalError("Preprocessor include stack is empty");
}
return true;
}
tgtok::TokKind TGLexer::prepIsDirective() const {
for (const auto &PD : PreprocessorDirs) {
int NextChar = *CurPtr;
bool Match = true;
unsigned I = 0;
for (; I < strlen(PD.Word); ++I) {
if (NextChar != PD.Word[I]) {
Match = false;
break;
}
NextChar = peekNextChar(I + 1);
}
if (Match) {
tgtok::TokKind Kind = PD.Kind;
if (NextChar == ' ' || NextChar == '\t' || NextChar == EOF ||
NextChar == '\n' ||
NextChar == '\r')
return Kind;
if (NextChar == '/') {
NextChar = peekNextChar(I + 1);
if (NextChar == '*' || NextChar == '/')
return Kind;
}
}
}
return tgtok::Error;
}
bool TGLexer::prepEatPreprocessorDirective(tgtok::TokKind Kind) {
TokStart = CurPtr;
for (const auto &PD : PreprocessorDirs)
if (PD.Kind == Kind) {
CurPtr += strlen(PD.Word);
return true;
}
PrintFatalError("Unsupported preprocessing token in "
"prepEatPreprocessorDirective()");
return false;
}
tgtok::TokKind TGLexer::lexPreprocessor(
tgtok::TokKind Kind, bool ReturnNextLiveToken) {
if (!prepEatPreprocessorDirective(Kind))
PrintFatalError("lexPreprocessor() called for unknown "
"preprocessor directive");
if (Kind == tgtok::Ifdef || Kind == tgtok::Ifndef) {
StringRef MacroName = prepLexMacroName();
StringRef IfTokName = Kind == tgtok::Ifdef ? "#ifdef" : "#ifndef";
if (MacroName.empty())
return ReturnError(TokStart, "Expected macro name after " + IfTokName);
bool MacroIsDefined = DefinedMacros.count(MacroName) != 0;
if (Kind == tgtok::Ifndef) {
MacroIsDefined = !MacroIsDefined;
Kind = tgtok::Ifdef;
}
PrepIncludeStack.back()->push_back(
{Kind, MacroIsDefined, SMLoc::getFromPointer(TokStart)});
if (!prepSkipDirectiveEnd())
return ReturnError(CurPtr, "Only comments are supported after " +
IfTokName + " NAME");
if (!ReturnNextLiveToken)
return Kind;
if (MacroIsDefined)
return LexToken();
if (prepSkipRegion(ReturnNextLiveToken))
return LexToken();
return tgtok::Error;
} else if (Kind == tgtok::Else) {
if (PrepIncludeStack.back()->empty())
return ReturnError(TokStart, "#else without #ifdef or #ifndef");
PreprocessorControlDesc IfdefEntry = PrepIncludeStack.back()->back();
if (IfdefEntry.Kind != tgtok::Ifdef) {
PrintError(TokStart, "double #else");
return ReturnError(IfdefEntry.SrcPos, "Previous #else is here");
}
PrepIncludeStack.back()->pop_back();
PrepIncludeStack.back()->push_back(
{Kind, !IfdefEntry.IsDefined, SMLoc::getFromPointer(TokStart)});
if (!prepSkipDirectiveEnd())
return ReturnError(CurPtr, "Only comments are supported after #else");
if (ReturnNextLiveToken) {
if (prepSkipRegion(ReturnNextLiveToken))
return LexToken();
return tgtok::Error;
}
return Kind;
} else if (Kind == tgtok::Endif) {
if (PrepIncludeStack.back()->empty())
return ReturnError(TokStart, "#endif without #ifdef");
auto &IfdefOrElseEntry = PrepIncludeStack.back()->back();
if (IfdefOrElseEntry.Kind != tgtok::Ifdef &&
IfdefOrElseEntry.Kind != tgtok::Else) {
PrintFatalError("Invalid preprocessor control on the stack");
return tgtok::Error;
}
if (!prepSkipDirectiveEnd())
return ReturnError(CurPtr, "Only comments are supported after #endif");
PrepIncludeStack.back()->pop_back();
if (ReturnNextLiveToken) {
return LexToken();
}
return Kind;
} else if (Kind == tgtok::Define) {
StringRef MacroName = prepLexMacroName();
if (MacroName.empty())
return ReturnError(TokStart, "Expected macro name after #define");
if (!DefinedMacros.insert(MacroName).second)
PrintWarning(getLoc(),
"Duplicate definition of macro: " + Twine(MacroName));
if (!prepSkipDirectiveEnd())
return ReturnError(CurPtr,
"Only comments are supported after #define NAME");
if (!ReturnNextLiveToken) {
PrintFatalError("#define must be ignored during the lines skipping");
return tgtok::Error;
}
return LexToken();
}
PrintFatalError("Preprocessing directive is not supported");
return tgtok::Error;
}
bool TGLexer::prepSkipRegion(bool MustNeverBeFalse) {
if (!MustNeverBeFalse)
PrintFatalError("Invalid recursion.");
do {
prepSkipToLineEnd();
if (!prepSkipLineBegin())
return false;
if (*CurPtr == '#')
++CurPtr;
else
continue;
tgtok::TokKind Kind = prepIsDirective();
if (Kind == tgtok::Error || Kind == tgtok::Define)
continue;
tgtok::TokKind ProcessedKind = lexPreprocessor(Kind, false);
if (ProcessedKind == tgtok::Error)
return false;
if (Kind != ProcessedKind)
PrintFatalError("prepIsDirective() and lexPreprocessor() "
"returned different token kinds");
if (prepIsProcessingEnabled()) {
if (Kind != tgtok::Else && Kind != tgtok::Endif) {
PrintFatalError("Tokens processing was enabled by an unexpected "
"preprocessing directive");
return false;
}
return true;
}
} while (CurPtr != CurBuf.end());
prepReportPreprocessorStackError();
return false;
}
StringRef TGLexer::prepLexMacroName() {
while (*CurPtr == ' ' || *CurPtr == '\t')
++CurPtr;
TokStart = CurPtr;
if (*CurPtr != '_' && !isalpha(*CurPtr))
return "";
while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_')
++CurPtr;
return StringRef(TokStart, CurPtr - TokStart);
}
bool TGLexer::prepSkipLineBegin() {
while (CurPtr != CurBuf.end()) {
switch (*CurPtr) {
case ' ':
case '\t':
case '\n':
case '\r':
break;
case '/': {
int NextChar = peekNextChar(1);
if (NextChar == '*') {
TokStart = CurPtr;
++CurPtr;
if (SkipCComment())
return false;
} else {
return true;
}
continue;
}
default:
return true;
}
++CurPtr;
}
return true;
}
bool TGLexer::prepSkipDirectiveEnd() {
while (CurPtr != CurBuf.end()) {
switch (*CurPtr) {
case ' ':
case '\t':
break;
case '\n':
case '\r':
return true;
case '/': {
int NextChar = peekNextChar(1);
if (NextChar == '/') {
++CurPtr;
SkipBCPLComment();
} else if (NextChar == '*') {
TokStart = CurPtr;
++CurPtr;
if (SkipCComment())
return false;
} else {
TokStart = CurPtr;
PrintError(CurPtr, "Unexpected character");
return false;
}
continue;
}
default:
TokStart = CurPtr;
return false;
}
++CurPtr;
}
return true;
}
void TGLexer::prepSkipToLineEnd() {
while (*CurPtr != '\n' && *CurPtr != '\r' && CurPtr != CurBuf.end())
++CurPtr;
}
bool TGLexer::prepIsProcessingEnabled() {
for (const PreprocessorControlDesc &I :
llvm::reverse(*PrepIncludeStack.back()))
if (!I.IsDefined)
return false;
return true;
}
void TGLexer::prepReportPreprocessorStackError() {
if (PrepIncludeStack.back()->empty())
PrintFatalError("prepReportPreprocessorStackError() called with "
"empty control stack");
auto &PrepControl = PrepIncludeStack.back()->back();
PrintError(CurBuf.end(), "Reached EOF without matching #endif");
PrintError(PrepControl.SrcPos, "The latest preprocessor control is here");
TokStart = CurPtr;
}