@@ -44,6 +44,28 @@ constexpr PreprocessorDir PreprocessorDirs[] = {{tgtok::Ifdef, "ifdef"},
44
44
{tgtok::Endif, " endif" },
45
45
{tgtok::Define, " define" }};
46
46
47
+ // Returns a pointer past the end of a valid macro name at the start of `Str`.
48
+ // Valid macro names match the regular expression [a-zA-Z_][0-9a-zA-Z_]*.
49
+ static const char *lexMacroName (StringRef Str) {
50
+ assert (!Str.empty ());
51
+
52
+ const char *Next = Str.begin ();
53
+
54
+ // Macro names start with [a-zA-Z_].
55
+ if (*Next != ' _' && !isalpha (*Next))
56
+ return Next;
57
+
58
+ // Eat the first character of the name.
59
+ Next++;
60
+
61
+ const char *End = Str.end ();
62
+ // Match the rest of the identifier regex: [0-9a-zA-Z_]*
63
+ while (Next != End && (isalpha (*Next) || isdigit (*Next) || *Next == ' _' ))
64
+ ++Next;
65
+
66
+ return Next;
67
+ }
68
+
47
69
TGLexer::TGLexer (SourceMgr &SM, ArrayRef<std::string> Macros) : SrcMgr(SM) {
48
70
CurBuffer = SrcMgr.getMainFileID ();
49
71
CurBuf = SrcMgr.getMemoryBuffer (CurBuffer)->getBuffer ();
@@ -54,9 +76,16 @@ TGLexer::TGLexer(SourceMgr &SM, ArrayRef<std::string> Macros) : SrcMgr(SM) {
54
76
PrepIncludeStack.push_back (
55
77
std::make_unique<std::vector<PreprocessorControlDesc>>());
56
78
57
- // Put all macros defined in the command line into the DefinedMacros set.
58
- for (const std::string &MacroName : Macros)
79
+ // Add all macros defined on the command line to the DefinedMacros set.
80
+ // Check invalid macro names and print fatal error if we find one.
81
+ for (StringRef MacroName : Macros) {
82
+ const char *End = lexMacroName (MacroName);
83
+ if (End != MacroName.end ())
84
+ PrintFatalError (" Invalid macro name `" + MacroName +
85
+ " ` specified on command line" );
86
+
59
87
DefinedMacros.insert (MacroName);
88
+ }
60
89
}
61
90
62
91
SMLoc TGLexer::getLoc () const {
@@ -699,9 +728,8 @@ bool TGLexer::prepEatPreprocessorDirective(tgtok::TokKind Kind) {
699
728
return false ;
700
729
}
701
730
702
- tgtok::TokKind TGLexer::lexPreprocessor (
703
- tgtok::TokKind Kind, bool ReturnNextLiveToken) {
704
-
731
+ tgtok::TokKind TGLexer::lexPreprocessor (tgtok::TokKind Kind,
732
+ bool ReturnNextLiveToken) {
705
733
// We must be looking at a preprocessing directive. Eat it!
706
734
if (!prepEatPreprocessorDirective (Kind))
707
735
PrintFatalError (" lexPreprocessor() called for unknown "
@@ -901,14 +929,7 @@ StringRef TGLexer::prepLexMacroName() {
901
929
++CurPtr;
902
930
903
931
TokStart = CurPtr;
904
- // Macro names start with [a-zA-Z_].
905
- if (*CurPtr != ' _' && !isalpha (*CurPtr))
906
- return " " ;
907
-
908
- // Match the rest of the identifier regex: [0-9a-zA-Z_]*
909
- while (isalpha (*CurPtr) || isdigit (*CurPtr) || *CurPtr == ' _' )
910
- ++CurPtr;
911
-
932
+ CurPtr = lexMacroName (StringRef (CurPtr, CurBuf.end () - CurPtr));
912
933
return StringRef (TokStart, CurPtr - TokStart);
913
934
}
914
935
0 commit comments