@@ -44,6 +44,25 @@ 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
+ // Macro names start with [a-zA-Z_].
53
+ const char *Next = Str.begin ();
54
+ if (*Next != ' _' && !isalpha (*Next))
55
+ return Next;
56
+ // Eat the first character of the name.
57
+ ++Next;
58
+
59
+ // Match the rest of the identifier regex: [0-9a-zA-Z_]*
60
+ const char *End = Str.end ();
61
+ while (Next != End && (isalpha (*Next) || isdigit (*Next) || *Next == ' _' ))
62
+ ++Next;
63
+ return Next;
64
+ }
65
+
47
66
TGLexer::TGLexer (SourceMgr &SM, ArrayRef<std::string> Macros) : SrcMgr(SM) {
48
67
CurBuffer = SrcMgr.getMainFileID ();
49
68
CurBuf = SrcMgr.getMemoryBuffer (CurBuffer)->getBuffer ();
@@ -54,9 +73,16 @@ TGLexer::TGLexer(SourceMgr &SM, ArrayRef<std::string> Macros) : SrcMgr(SM) {
54
73
PrepIncludeStack.push_back (
55
74
std::make_unique<std::vector<PreprocessorControlDesc>>());
56
75
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 (StringRef MacroName : Macros) {
79
+ const char *End = lexMacroName (MacroName);
80
+ if (End != MacroName.end ())
81
+ PrintFatalError (" Invalid macro name `" + MacroName +
82
+ " ` specified on command line" );
83
+
59
84
DefinedMacros.insert (MacroName);
85
+ }
60
86
}
61
87
62
88
SMLoc TGLexer::getLoc () const {
@@ -699,9 +725,8 @@ bool TGLexer::prepEatPreprocessorDirective(tgtok::TokKind Kind) {
699
725
return false ;
700
726
}
701
727
702
- tgtok::TokKind TGLexer::lexPreprocessor (
703
- tgtok::TokKind Kind, bool ReturnNextLiveToken) {
704
-
728
+ tgtok::TokKind TGLexer::lexPreprocessor (tgtok::TokKind Kind,
729
+ bool ReturnNextLiveToken) {
705
730
// We must be looking at a preprocessing directive. Eat it!
706
731
if (!prepEatPreprocessorDirective (Kind))
707
732
PrintFatalError (" lexPreprocessor() called for unknown "
@@ -901,14 +926,7 @@ StringRef TGLexer::prepLexMacroName() {
901
926
++CurPtr;
902
927
903
928
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
-
929
+ CurPtr = lexMacroName (StringRef (CurPtr, CurBuf.end () - CurPtr));
912
930
return StringRef (TokStart, CurPtr - TokStart);
913
931
}
914
932
0 commit comments