2 /* C pre-processor functions */
32 /*****************************************************************************/
34 /*****************************************************************************/
38 static int Pass1 (const char* From, char* To);
39 /* Preprocessor pass 1. Remove whitespace and comments. */
43 /*****************************************************************************/
45 /*****************************************************************************/
49 /* Set when the preprocessor calls expr() recursively */
50 unsigned char Preprocessing = 0;
52 /* Management data for #if */
54 #define IFCOND_NONE 0x00U
55 #define IFCOND_SKIP 0x01U
56 #define IFCOND_ELSE 0x02U
57 #define IFCOND_NEEDTERM 0x04U
58 static unsigned char IfStack[MAX_IFS];
59 static int IfIndex = -1;
61 /* Buffer for macro expansion */
62 static char mlinebuf [LINESIZE];
63 static char* mline = mlinebuf;
68 /*****************************************************************************/
69 /* Low level preprocessor token handling */
70 /*****************************************************************************/
74 /* Types of preprocessor tokens */
93 /* Preprocessor keyword to token mapping table */
94 static const struct PPToken {
95 const char* Key; /* Keyword */
96 pptoken_t Tok; /* Token */
98 { "define", PP_DEFINE },
101 { "endif", PP_ENDIF },
102 { "error", PP_ERROR },
104 { "ifdef", PP_IFDEF },
105 { "ifndef", PP_IFNDEF },
106 { "include", PP_INCLUDE },
108 { "pragma", PP_PRAGMA },
109 { "undef", PP_UNDEF },
112 /* Number of preprocessor tokens */
113 #define PPTOKEN_COUNT (sizeof(PPTokens) / sizeof(PPTokens[0]))
117 static int CmpToken (const void* Key, const void* Elem)
118 /* Compare function for bsearch */
120 return strcmp ((const char*) Key, ((const struct PPToken*) Elem)->Key);
125 static pptoken_t FindPPToken (const char* Ident)
126 /* Find a preprocessor token and return ut. Return PP_ILLEGAL if the identifier
127 * is not a valid preprocessor token.
131 P = bsearch (Ident, PPTokens, PPTOKEN_COUNT, sizeof (PPTokens[0]), CmpToken);
132 return P? P->Tok : PP_ILLEGAL;
137 /*****************************************************************************/
139 /*****************************************************************************/
144 INLINE void KeepChar (char c)
145 /* Put character c into translation buffer. */
150 #define KeepChar(c) *mptr++ = (c)
155 static void KeepStr (const char* S)
156 /* Put string str into translation buffer. */
158 unsigned Len = strlen (S);
159 memcpy (mptr, S, Len);
165 static void Stringize (const char* S)
166 /* Stringize the given string: Add double quotes at start and end and preceed
167 * each occurance of " and \ by a backslash.
171 /* Replace any characters inside the string may not be part of a string
191 static void SwapLineBuffers (void)
192 /* Swap both line buffers */
194 /* Swap mline and line */
202 static void OldStyleComment (void)
203 /* Remove an old style C comment from line. */
205 /* Remember the current line number, so we can output better error
206 * messages if the comment is not terminated in the current file.
208 unsigned StartingLine = GetCurrentLine();
210 /* Skip the start of comment chars */
214 /* Skip the comment */
215 while (CurC != '*' || NextC != '/') {
217 if (NextLine () == 0) {
218 PPError ("End-of-file reached in comment starting at line %u",
223 if (CurC == '/' && NextC == '*') {
224 PPWarning ("`/*' found inside a comment");
230 /* Skip the end of comment chars */
237 static void NewStyleComment (void)
238 /* Remove a new style C comment from line. */
240 /* Beware: Because line continuation chars are handled when reading
241 * lines, we may only skip til the end of the source line, which
242 * may not be the same as the end of the input line. The end of the
243 * source line is denoted by a lf (\n) character.
247 } while (CurC != '\n' && CurC != '\0');
255 static void SkipBlank (void)
256 /* Skip blanks and tabs in the input stream. */
258 while (IsBlank (CurC)) {
265 static char* CopyQuotedString (char* Target)
266 /* Copy a single or double quoted string from the input to Target. Return the
267 * new target pointer. Target will not be terminated after the copy.
270 /* Remember the quote character, copy it to the target buffer and skip it */
275 /* Copy the characters inside the string */
276 while (CurC != '\0' && CurC != Quote) {
277 /* Keep an escaped char */
282 /* Copy the character */
287 /* If we had a terminating quote, copy it */
293 /* Return the new target pointer */
299 /*****************************************************************************/
301 /*****************************************************************************/
305 static int MacName (char* Ident)
306 /* Get a macro symbol name into Ident. If we have an error, print a
307 * diagnostic message and clear the line.
310 if (IsSym (Ident) == 0) {
311 PPError ("Identifier expected");
321 static void ExpandMacroArgs (Macro* M)
322 /* Expand the arguments of a macro */
325 const char* Replacement;
328 /* Save the current line pointer and setup the new ones */
330 InitLine (M->Replacement);
332 /* Copy the macro replacement checking for parameters to replace */
333 while (CurC != '\0') {
334 /* If the next token is an identifier, check for a macro arg */
335 if (IsIdent (CurC)) {
337 Replacement = FindMacroArg (M, Ident);
339 /* Macro arg, keep the replacement */
340 KeepStr (Replacement);
342 /* No macro argument, keep the original identifier */
345 } else if (CurC == '#' && IsIdent (NextC)) {
348 Replacement = FindMacroArg (M, Ident);
350 /* Make a valid string from Replacement */
351 Stringize (Replacement);
353 /* No replacement - keep the input */
357 } else if (IsQuote (CurC)) {
358 mptr = CopyQuotedString (mptr);
365 /* Reset the line pointer */
371 static int MacroCall (Macro* M)
372 /* Process a function like macro */
374 int ArgCount; /* Macro argument count */
375 unsigned ParCount; /* Number of open parenthesis */
376 char Buf[LINESIZE]; /* Argument buffer */
377 const char* ArgStart;
380 /* Expect an argument list */
383 PPError ("Illegal macro call");
387 /* Eat the left paren */
390 /* Read the actual macro arguments and store pointers to these arguments
391 * into the array of actual arguments in the macro definition.
399 /* Nested parenthesis */
403 } else if (IsQuote (CurC)) {
404 B = CopyQuotedString (B);
405 } else if (CurC == ',' || CurC == ')') {
407 /* End of actual argument */
409 while (IsBlank(*ArgStart)) {
412 if (ArgCount < M->ArgCount) {
413 M->ActualArgs[ArgCount++] = ArgStart;
414 } else if (CurC != ')' || *ArgStart != '\0' || M->ArgCount > 0) {
415 /* Be sure not to count the single empty argument for a
416 * macro that does not have arguments.
421 /* Check for end of macro param list */
427 /* Start the next param */
431 /* Comma or right paren inside nested parenthesis */
438 } else if (IsBlank (CurC)) {
439 /* Squeeze runs of blanks */
442 } else if (CurC == '/' && NextC == '*') {
445 } else if (ANSI == 0 && CurC == '/' && NextC == '/') {
448 } else if (CurC == '\0') {
449 /* End of line inside macro argument list - read next line */
450 if (NextLine () == 0) {
454 /* Just copy the character */
460 /* Compare formal argument count with actual */
461 if (M->ArgCount != ArgCount) {
462 PPError ("Macro argument count mismatch");
463 /* Be sure to make enough empty arguments available */
464 while (ArgCount < M->ArgCount) {
465 M->ActualArgs [ArgCount++] = "";
469 /* Preprocess the line, replacing macro parameters */
478 static void ExpandMacro (Macro* M)
481 /* Check if this is a function like macro */
482 if (M->ArgCount >= 0) {
483 /* Function like macro */
484 if (MacroCall (M) == 0) {
488 /* Just copy the replacement text */
489 KeepStr (M->Replacement);
495 static void DefineMacro (void)
496 /* Handle a macro definition. */
504 /* Read the macro name */
506 if (!MacName (Ident)) {
510 /* Get an existing macro definition with this name */
511 Existing = FindMacro (Ident);
513 /* Create a new macro definition */
514 M = NewMacro (Ident);
516 /* Check if this is a function like macro */
519 /* Skip the left paren */
522 /* Set the marker that this is a function like macro */
525 /* Read the formal parameter list */
530 if (MacName (Ident) == 0) {
533 AddMacroArg (M, Ident);
540 /* Check for a right paren and eat it if we find one */
542 PPError ("`)' expected");
549 /* Insert the macro into the macro table and allocate the ActualArgs array */
552 /* Remove whitespace and comments from the line, store the preprocessed
560 /* Create a copy of the replacement */
561 M->Replacement = xstrdup (Buf);
563 /* If we have an existing macro, check if the redefinition is identical.
564 * Print a diagnostic if not.
567 if (MacroCmp (M, Existing) != 0) {
568 PPError ("Macro redefinition is not identical");
575 /*****************************************************************************/
577 /*****************************************************************************/
581 static int Pass1 (const char* From, char* To)
582 /* Preprocessor pass 1. Remove whitespace and comments. */
588 /* Initialize reading from "From" */
594 /* Loop removing ws and comments */
596 while (CurC != '\0') {
597 if (IsBlank (CurC)) {
600 } else if (IsIdent (CurC)) {
602 if (Preprocessing && strcmp(Ident, "defined") == 0) {
603 /* Handle the "defined" operator */
611 if (!IsIdent (CurC)) {
612 PPError ("Identifier expected");
616 KeepChar (IsMacro (Ident)? '1' : '0');
620 PPError ("`)' expected");
627 if (MaybeMacro (Ident[0])) {
632 } else if (IsQuote (CurC)) {
633 mptr = CopyQuotedString (mptr);
634 } else if (CurC == '/' && NextC == '*') {
637 } else if (ANSI == 0 && CurC == '/' && NextC == '/') {
651 static int Pass2 (const char* From, char* To)
652 /* Preprocessor pass 2. Perform macro substitution. */
658 /* Initialize reading from "From" */
664 /* Loop substituting macros */
666 while (CurC != '\0') {
667 /* If we have an identifier, check if it's a macro */
668 if (IsIdent (CurC)) {
670 M = FindMacro (Ident);
677 } else if (IsQuote (CurC)) {
678 mptr = CopyQuotedString (mptr);
689 static void PreprocessLine (void)
690 /* Translate one line. */
694 /* Trim whitespace and remove comments. The function returns false if no
695 * identifiers were found that may be macros. If this is the case, no
696 * macro substitution is performed.
698 int Done = Pass1 (line, mline);
700 /* Repeatedly expand macros in the line */
701 for (I = 0; I < 5; ++I) {
702 /* Swap mline and line */
707 /* Perform macro expansion */
708 Done = Pass2 (line, mline);
712 /* Reinitialize line parsing */
718 static void DoUndef (void)
719 /* Process the #undef directive */
724 if (MacName (Ident)) {
725 UndefineMacro (Ident);
731 static int PushIf (int Skip, int Invert, int Cond)
732 /* Push a new if level onto the if stack */
734 /* Check for an overflow of the if stack */
735 if (IfIndex >= MAX_IFS-1) {
736 PPError ("Too many nested #if clauses");
740 /* Push the #if condition */
743 IfStack[IfIndex] = IFCOND_SKIP | IFCOND_NEEDTERM;
746 IfStack[IfIndex] = IFCOND_NONE | IFCOND_NEEDTERM;
747 return (Invert ^ Cond);
753 static int DoIf (int Skip)
754 /* Process #if directive */
759 /* We're about to abuse the compiler expression parser to evaluate the
760 * #if expression. Save the current tokens to come back here later.
761 * NOTE: Yes, this is a hack, but it saves a complete separate expression
762 * evaluation for the preprocessor.
767 /* Make sure the line infos for the tokens won't get removed */
769 UseLineInfo (sv1.LI);
772 UseLineInfo (sv2.LI);
775 /* Remove the #if from the line and add two semicolons as sentinels */
778 while (CurC != '\0') {
786 /* Start over parsing from line */
789 /* Switch into special preprocessing mode */
792 /* Expand macros in this line */
795 /* Prime the token pump (remove old tokens from the stream) */
799 /* Call the expression parser */
802 /* End preprocessing mode */
805 /* Reset the old tokens */
809 /* Set the #if condition according to the expression result */
810 return PushIf (Skip, 1, lval.ConstVal != 0);
815 static int DoIfDef (int skip, int flag)
816 /* Process #ifdef if flag == 1, or #ifndef if flag == 0. */
821 if (MacName (Ident) == 0) {
824 return PushIf (skip, flag, IsMacro(Ident));
830 static void DoInclude (void)
831 /* Open an include file. */
840 /* Get the next char and check for a valid file name terminator. Setup
841 * the include directory spec (SYS/USR) by looking at the terminator.
856 PPError ("`\"' or `<' expected");
861 /* Copy the filename into mline. Since mline has the same size as the
862 * input line, we don't need to check for an overflow here.
865 while (CurC != '\0' && CurC != RTerm) {
871 /* Check if we got a terminator */
873 /* No terminator found */
874 PPError ("Missing terminator or file name too long");
878 /* Open the include file */
879 OpenIncludeFile (mline, DirSpec);
882 /* Clear the remaining line so the next input will come from the new
890 static void DoError (void)
895 PPError ("Invalid #error directive");
897 PPError ("#error: %s", lptr);
900 /* Clear the rest of line */
906 static void DoPragma (void)
907 /* Handle a #pragma line by converting the #pragma preprocessor directive into
908 * the _Pragma() compiler operator.
911 /* Skip blanks following the #pragma directive */
914 /* Copy the remainder of the line into mline removing comments and ws */
917 /* Convert the directive into the operator */
919 KeepStr ("_Pragma (");
924 /* Initialize reading from line */
930 void Preprocess (void)
931 /* Preprocess a line */
936 /* Skip white space at the beginning of the line */
939 /* Check for stuff to skip */
941 while (CurC == '\0' || CurC == '#' || Skip) {
943 /* Check for preprocessor lines lines */
948 /* Ignore the empty preprocessor directive */
951 if (!IsSym (Directive)) {
952 PPError ("Preprocessor directive expected");
955 switch (FindPPToken (Directive)) {
965 if ((IfStack[IfIndex] & IFCOND_ELSE) == 0) {
967 /* Handle as #else/#if combination */
968 if ((IfStack[IfIndex] & IFCOND_SKIP) == 0) {
971 IfStack[IfIndex] |= IFCOND_ELSE;
974 /* #elif doesn't need a terminator */
975 IfStack[IfIndex] &= ~IFCOND_NEEDTERM;
977 PPError ("Duplicate #else/#elif");
980 PPError ("Unexpected #elif");
986 if ((IfStack[IfIndex] & IFCOND_ELSE) == 0) {
987 if ((IfStack[IfIndex] & IFCOND_SKIP) == 0) {
990 IfStack[IfIndex] |= IFCOND_ELSE;
992 PPError ("Duplicate #else");
995 PPError ("Unexpected `#else'");
1001 /* Remove any clauses on top of stack that do not
1002 * need a terminating #endif.
1004 while (IfIndex >= 0 && (IfStack[IfIndex] & IFCOND_NEEDTERM) == 0) {
1008 /* Stack may not be empty here or something is wrong */
1009 CHECK (IfIndex >= 0);
1011 /* Remove the clause that needs a terminator */
1012 Skip = (IfStack[IfIndex--] & IFCOND_SKIP) != 0;
1014 PPError ("Unexpected `#endif'");
1029 Skip = DoIfDef (Skip, 1);
1033 Skip = DoIfDef (Skip, 0);
1043 /* Not allowed in strict ANSI mode */
1044 if (!Skip && ANSI) {
1045 PPError ("Preprocessor directive expected");
1064 PPError ("Preprocessor directive expected");
1070 if (NextLine () == 0) {
1072 PPError ("`#endif' expected");
1082 Print (stdout, 2, "line: %s\n", line);