Skip to content

Commit 085cca4

Browse files
committed
[TableGen] Detect invalid -D arguments and fail.
- Detect invalid macro names specified on command line and fail if one found. - Specifically, -DXYZ=1 for example, will fail instead is being silently accepted.
1 parent d1957dd commit 085cca4

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

llvm/lib/TableGen/TGLexer.cpp

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,25 @@ struct {
4242
{ tgtok::Endif, "endif" },
4343
{ tgtok::Define, "define" }
4444
};
45+
46+
// Returns true if `MacroName` is a valid macro name. Valid macro names match
47+
// the regular expression [a-zA-Z_][0-9a-zA-Z_]* (see prepLexMacroName).
48+
bool IsValidMacroName(StringRef MacroName) {
49+
if (MacroName.size() == 0)
50+
return false;
51+
52+
char First = MacroName[0];
53+
if (First != '_' && !isalpha(First))
54+
return false;
55+
56+
// Match the rest of the identifier regex: [0-9a-zA-Z_]*
57+
for (char Rest : MacroName.drop_front())
58+
if (Rest != '_' && !isalpha(Rest) && !isdigit(Rest))
59+
return false;
60+
61+
return true;
62+
}
63+
4564
} // end anonymous namespace
4665

4766
TGLexer::TGLexer(SourceMgr &SM, ArrayRef<std::string> Macros) : SrcMgr(SM) {
@@ -54,9 +73,15 @@ TGLexer::TGLexer(SourceMgr &SM, ArrayRef<std::string> Macros) : SrcMgr(SM) {
5473
PrepIncludeStack.push_back(
5574
std::make_unique<std::vector<PreprocessorControlDesc>>());
5675

57-
// Put all macros defined in the command line into the DefinedMacros set.
58-
for (const std::string &MacroName : Macros)
76+
// Add all macros defined on the command line to the DefinedMacros set.
77+
// Check invalid macro names and print fatal error if we find one.
78+
for (const std::string &MacroName : Macros) {
79+
if (!IsValidMacroName(MacroName))
80+
PrintFatalError(Twine("Invalid macro name `") + Twine(MacroName) +
81+
Twine("` specified on command line."));
82+
5983
DefinedMacros.insert(MacroName);
84+
}
6085
}
6186

6287
SMLoc TGLexer::getLoc() const {
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// RUN: not llvm-tblgen %s -DMACRO=1 2>&1 | FileCheck %s --check-prefix=CHECK-TEST-1
2+
// RUN: not llvm-tblgen %s -D0MAC 2>&1 | FileCheck %s --check-prefix=CHECK-TEST-2
3+
// RUN: not llvm-tblgen %s -D_MAC# 2>&1 | FileCheck %s --check-prefix=CHECK-TEST-3
4+
// RUN: not llvm-tblgen %s -D 2>&1 | FileCheck %s --check-prefix=CHECK-TEST-4
5+
6+
// CHECK-TEST-1: error: Invalid macro name `MACRO=1` specified on command line.
7+
// CHECK-TEST-2: error: Invalid macro name `0MAC` specified on command line.
8+
// CHECK-TEST-3: error: Invalid macro name `_MAC#` specified on command line.
9+
// CHECK-TEST-4: for the -D option: requires a value!

0 commit comments

Comments
 (0)