2 /* C pre-processor functions */
31 /*****************************************************************************/
33 /*****************************************************************************/
37 static int Pass1 (const char* From, char* To);
38 /* Preprocessor pass 1. Remove whitespace and comments. */
42 /*****************************************************************************/
44 /*****************************************************************************/
48 /* Set when the preprocessor calls expr() recursively */
49 unsigned char Preprocessing = 0;
51 /* Management data for #if */
53 #define IFCOND_NONE 0x00U
54 #define IFCOND_SKIP 0x01U
55 #define IFCOND_ELSE 0x02U
56 #define IFCOND_NEEDTERM 0x04U
57 static unsigned char IfStack[MAX_IFS];
58 static int IfIndex = -1;
60 /* Buffer for macro expansion */
61 static char mlinebuf [LINESIZE];
62 static char* mline = mlinebuf;
65 /* Flag: Expand macros in this line */
66 static int ExpandMacros = 1;
70 /*****************************************************************************/
71 /* Low level preprocessor token handling */
72 /*****************************************************************************/
76 /* Types of preprocessor tokens */
95 /* Preprocessor keyword to token mapping table */
96 static const struct PPToken {
97 const char* Key; /* Keyword */
98 pptoken_t Tok; /* Token */
100 { "define", PP_DEFINE },
103 { "endif", PP_ENDIF },
104 { "error", PP_ERROR },
106 { "ifdef", PP_IFDEF },
107 { "ifndef", PP_IFNDEF },
108 { "include", PP_INCLUDE },
110 { "pragma", PP_PRAGMA },
111 { "undef", PP_UNDEF },
114 /* Number of preprocessor tokens */
115 #define PPTOKEN_COUNT (sizeof(PPTokens) / sizeof(PPTokens[0]))
119 static int CmpToken (const void* Key, const void* Elem)
120 /* Compare function for bsearch */
122 return strcmp ((const char*) Key, ((const struct PPToken*) Elem)->Key);
127 static pptoken_t FindPPToken (const char* Ident)
128 /* Find a preprocessor token and return ut. Return PP_ILLEGAL if the identifier
129 * is not a valid preprocessor token.
133 P = bsearch (Ident, PPTokens, PPTOKEN_COUNT, sizeof (PPTokens[0]), CmpToken);
134 return P? P->Tok : PP_ILLEGAL;
139 /*****************************************************************************/
141 /*****************************************************************************/
145 static void keepch (char c)
146 /* Put character c into translation buffer. */
153 static void keepstr (const char* S)
154 /* Put string str into translation buffer. */
156 unsigned Len = strlen (S);
157 memcpy (mptr, S, Len);
163 static void OldStyleComment (void)
164 /* Remove an old style C comment from line. */
166 /* Remember the current line number, so we can output better error
167 * messages if the comment is not terminated in the current file.
169 unsigned StartingLine = GetCurrentLine();
171 /* Skip the start of comment chars */
175 /* Skip the comment */
176 while (CurC != '*' || NextC != '/') {
178 if (NextLine () == 0) {
179 PPError ("End-of-file reached in comment starting at line %u",
184 if (CurC == '/' && NextC == '*') {
185 PPWarning ("`/*' found inside a comment");
191 /* Skip the end of comment chars */
198 static void NewStyleComment (void)
199 /* Remove a new style C comment from line. */
201 /* Beware: Because line continuation chars are handled when reading
202 * lines, we may only skip til the end of the source line, which
203 * may not be the same as the end of the input line. The end of the
204 * source line is denoted by a lf (\n) character.
208 } while (CurC != '\n' && CurC != '\0');
216 static void SkipBlank (void)
217 /* Skip blanks and tabs in the input stream. */
219 while (IsBlank (CurC)) {
226 static char* CopyQuotedString (char* Target)
227 /* Copy a single or double quoted string from the input to Target. Return the
228 * new target pointer. Target will not be terminated after the copy.
231 /* Remember the quote character, copy it to the target buffer and skip it */
236 /* Copy the characters inside the string */
237 while (CurC != '\0' && CurC != Quote) {
238 /* Keep an escaped char */
243 /* Copy the character */
248 /* If we had a terminating quote, copy it */
254 /* Return the new target pointer */
260 /*****************************************************************************/
262 /*****************************************************************************/
266 static int MacName (char* Ident)
267 /* Get a macro symbol name into Ident. If we have an error, print a
268 * diagnostic message and clear the line.
271 if (IsSym (Ident) == 0) {
272 PPError ("Identifier expected");
282 static void ExpandMacroArgs (Macro* M)
283 /* Expand the arguments of a macro */
286 const char* Replacement;
289 /* Save the current line pointer and setup the new ones */
291 InitLine (M->Replacement);
293 /* Copy the macro replacement checking for parameters to replace */
294 while (CurC != '\0') {
295 /* If the next token is an identifier, check for a macro arg */
296 if (IsIdent (CurC)) {
298 Replacement = FindMacroArg (M, Ident);
300 /* Macro arg, keep the replacement */
301 keepstr (Replacement);
303 /* No macro argument, keep the original identifier */
306 } else if (CurC == '#' && IsIdent (NextC)) {
309 Replacement = FindMacroArg (M, Ident);
312 keepstr (Replacement);
318 } else if (IsQuote (CurC)) {
319 mptr = CopyQuotedString (mptr);
326 /* Reset the line pointer */
332 static int MacroCall (Macro* M)
333 /* Process a function like macro */
335 int ArgCount; /* Macro argument count */
336 unsigned ParCount; /* Number of open parenthesis */
337 char Buf[LINESIZE]; /* Argument buffer */
338 const char* ArgStart;
341 /* Expect an argument list */
344 PPError ("Illegal macro call");
348 /* Eat the left paren */
351 /* Read the actual macro arguments and store pointers to these arguments
352 * into the array of actual arguments in the macro definition.
360 /* Nested parenthesis */
364 } else if (IsQuote (CurC)) {
365 B = CopyQuotedString (B);
366 } else if (CurC == ',' || CurC == ')') {
368 /* End of actual argument */
370 while (IsBlank(*ArgStart)) {
373 if (ArgCount < M->ArgCount) {
374 M->ActualArgs[ArgCount++] = ArgStart;
375 } else if (CurC != ')' || *ArgStart != '\0' || M->ArgCount > 0) {
376 /* Be sure not to count the single empty argument for a
377 * macro that does not have arguments.
382 /* Check for end of macro param list */
388 /* Start the next param */
392 /* Comma or right paren inside nested parenthesis */
399 } else if (IsBlank (CurC)) {
400 /* Squeeze runs of blanks */
403 } else if (CurC == '/' && NextC == '*') {
406 } else if (ANSI == 0 && CurC == '/' && NextC == '/') {
409 } else if (CurC == '\0') {
410 /* End of line inside macro argument list - read next line */
411 if (NextLine () == 0) {
415 /* Just copy the character */
421 /* Compare formal argument count with actual */
422 if (M->ArgCount != ArgCount) {
423 PPError ("Macro argument count mismatch");
424 /* Be sure to make enough empty arguments available */
425 while (ArgCount < M->ArgCount) {
426 M->ActualArgs [ArgCount++] = "";
430 /* Preprocess the line, replacing macro parameters */
439 static void ExpandMacro (Macro* M)
442 /* Check if this is a function like macro */
443 if (M->ArgCount >= 0) {
444 /* Function like macro */
445 if (MacroCall (M) == 0) {
449 /* Just copy the replacement text */
450 keepstr (M->Replacement);
456 static void DefineMacro (void)
457 /* Handle a macro definition. */
465 /* Read the macro name */
467 if (!MacName (Ident)) {
471 /* Get an existing macro definition with this name */
472 Existing = FindMacro (Ident);
474 /* Create a new macro definition */
475 M = NewMacro (Ident);
477 /* Check if this is a function like macro */
480 /* Skip the left paren */
483 /* Set the marker that this is a function like macro */
486 /* Read the formal parameter list */
491 if (MacName (Ident) == 0) {
494 AddMacroArg (M, Ident);
501 /* Check for a right paren and eat it if we find one */
503 PPError ("`)' expected");
510 /* Insert the macro into the macro table and allocate the ActualArgs array */
513 /* Remove whitespace and comments from the line, store the preprocessed
521 /* Create a copy of the replacement */
522 M->Replacement = xstrdup (Buf);
524 /* If we have an existing macro, check if the redefinition is identical.
525 * Print a diagnostic if not.
528 if (MacroCmp (M, Existing) != 0) {
529 PPError ("Macro redefinition is not identical");
536 /*****************************************************************************/
538 /*****************************************************************************/
542 static int Pass1 (const char* From, char* To)
543 /* Preprocessor pass 1. Remove whitespace and comments. */
549 /* Initialize reading from "From" */
555 /* Loop removing ws and comments */
557 while (CurC != '\0') {
558 if (IsBlank (CurC)) {
561 } else if (IsIdent (CurC)) {
563 if (Preprocessing && strcmp(Ident, "defined") == 0) {
564 /* Handle the "defined" operator */
572 if (!IsIdent (CurC)) {
573 PPError ("Identifier expected");
577 *mptr++ = IsMacro (Ident)? '1' : '0';
581 PPError ("`)' expected");
588 if (MaybeMacro (Ident[0])) {
593 } else if (IsQuote (CurC)) {
594 mptr = CopyQuotedString (mptr);
595 } else if (CurC == '/' && NextC == '*') {
598 } else if (ANSI == 0 && CurC == '/' && NextC == '/') {
612 static int Pass2 (const char* From, char* To)
613 /* Preprocessor pass 2. Perform macro substitution. */
619 /* Initialize reading from "From" */
625 /* Loop substituting macros */
627 while (CurC != '\0') {
628 /* If we have an identifier, check if it's a macro */
629 if (IsIdent (CurC)) {
631 M = FindMacro (Ident);
638 } else if (IsQuote (CurC)) {
639 mptr = CopyQuotedString (mptr);
650 static void xlateline (void)
651 /* Translate one line. */
656 Done = Pass1 (line, mline);
657 if (ExpandMacros == 0) {
659 ExpandMacros = 1; /* Reset to default */
663 /* Swap mline and line */
669 Done = Pass2 (line, mline);
673 /* Reinitialize line parsing */
679 static void DoUndef (void)
680 /* Process the #undef directive */
685 if (MacName (Ident)) {
686 UndefineMacro (Ident);
692 static int PushIf (int Skip, int Invert, int Cond)
693 /* Push a new if level onto the if stack */
695 /* Check for an overflow of the if stack */
696 if (IfIndex >= MAX_IFS-1) {
697 PPError ("Too many nested #if clauses");
701 /* Push the #if condition */
704 IfStack[IfIndex] = IFCOND_SKIP | IFCOND_NEEDTERM;
707 IfStack[IfIndex] = IFCOND_NONE | IFCOND_NEEDTERM;
708 return (Invert ^ Cond);
714 static int DoIf (int Skip)
715 /* Process #if directive */
720 /* We're about to abuse the compiler expression parser to evaluate the
721 * #if expression. Save the current tokens to come back here later.
722 * NOTE: Yes, this is a hack, but it saves a complete separate expression
723 * evaluation for the preprocessor.
728 /* Make sure the line infos for the tokens won't get removed */
730 UseLineInfo (sv1.LI);
733 UseLineInfo (sv2.LI);
736 /* Remove the #if from the line and add two semicolons as sentinels */
739 while (CurC != '\0') {
747 /* Start over parsing from line */
750 /* Switch into special preprocessing mode */
753 /* Expand macros in this line */
756 /* Prime the token pump (remove old tokens from the stream) */
760 /* Call the expression parser */
763 /* End preprocessing mode */
766 /* Reset the old tokens */
770 /* Set the #if condition according to the expression result */
771 return PushIf (Skip, 1, lval.ConstVal != 0);
776 static int DoIfDef (int skip, int flag)
777 /* Process #ifdef if flag == 1, or #ifndef if flag == 0. */
782 if (MacName (Ident) == 0) {
785 return PushIf (skip, flag, IsMacro(Ident));
791 static void DoInclude (void)
792 /* Open an include file. */
801 /* Get the next char and check for a valid file name terminator. Setup
802 * the include directory spec (SYS/USR) by looking at the terminator.
817 PPError ("`\"' or `<' expected");
822 /* Copy the filename into mline. Since mline has the same size as the
823 * input line, we don't need to check for an overflow here.
826 while (CurC != '\0' && CurC != RTerm) {
832 /* Check if we got a terminator */
834 /* No terminator found */
835 PPError ("Missing terminator or file name too long");
839 /* Open the include file */
840 OpenIncludeFile (mline, DirSpec);
843 /* Clear the remaining line so the next input will come from the new
851 static void DoError (void)
856 PPError ("Invalid #error directive");
858 PPError ("#error: %s", lptr);
861 /* Clear the rest of line */
867 void Preprocess (void)
868 /* Preprocess a line */
873 /* Skip white space at the beginning of the line */
876 /* Check for stuff to skip */
878 while (CurC == '\0' || CurC == '#' || Skip) {
880 /* Check for preprocessor lines lines */
885 /* Ignore the empty preprocessor directive */
888 if (!IsSym (Directive)) {
889 PPError ("Preprocessor directive expected");
892 switch (FindPPToken (Directive)) {
902 if ((IfStack[IfIndex] & IFCOND_ELSE) == 0) {
904 /* Handle as #else/#if combination */
905 if ((IfStack[IfIndex] & IFCOND_SKIP) == 0) {
908 IfStack[IfIndex] |= IFCOND_ELSE;
911 /* #elif doesn't need a terminator */
912 IfStack[IfIndex] &= ~IFCOND_NEEDTERM;
914 PPError ("Duplicate #else/#elif");
917 PPError ("Unexpected #elif");
923 if ((IfStack[IfIndex] & IFCOND_ELSE) == 0) {
924 if ((IfStack[IfIndex] & IFCOND_SKIP) == 0) {
927 IfStack[IfIndex] |= IFCOND_ELSE;
929 PPError ("Duplicate #else");
932 PPError ("Unexpected `#else'");
938 /* Remove any clauses on top of stack that do not
939 * need a terminating #endif.
941 while (IfIndex >= 0 && (IfStack[IfIndex] & IFCOND_NEEDTERM) == 0) {
945 /* Stack may not be empty here or something is wrong */
946 CHECK (IfIndex >= 0);
948 /* Remove the clause that needs a terminator */
949 Skip = (IfStack[IfIndex--] & IFCOND_SKIP) != 0;
951 PPError ("Unexpected `#endif'");
966 Skip = DoIfDef (Skip, 1);
970 Skip = DoIfDef (Skip, 0);
980 /* Not allowed in strict ANSI mode */
982 PPError ("Preprocessor directive expected");
989 /* Don't expand macros in this line */
991 /* #pragma is handled on the scanner level */
1003 PPError ("Preprocessor directive expected");
1009 if (NextLine () == 0) {
1011 PPError ("`#endif' expected");
1020 Print (stdout, 2, "line: %s\n", line);