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 Comment (void)
164 /* Remove a 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 SkipBlank (void)
199 /* Skip blanks and tabs in the input stream. */
201 while (IsBlank (CurC)) {
208 static char* CopyQuotedString (char* Target)
209 /* Copy a single or double quoted string from the input to Target. Return the
210 * new target pointer. Target will not be terminated after the copy.
213 /* Remember the quote character, copy it to the target buffer and skip it */
218 /* Copy the characters inside the string */
219 while (CurC != '\0' && CurC != Quote) {
220 /* Keep an escaped char */
225 /* Copy the character */
230 /* If we had a terminating quote, copy it */
236 /* Return the new target pointer */
242 /*****************************************************************************/
244 /*****************************************************************************/
248 static int MacName (char* Ident)
249 /* Get a macro symbol name into Ident. If we have an error, print a
250 * diagnostic message and clear the line.
253 if (IsSym (Ident) == 0) {
254 PPError ("Identifier expected");
264 static void ExpandMacroArgs (Macro* M)
265 /* Expand the arguments of a macro */
268 const char* Replacement;
271 /* Save the current line pointer and setup the new ones */
273 InitLine (M->Replacement);
275 /* Copy the macro replacement checking for parameters to replace */
276 while (CurC != '\0') {
277 /* If the next token is an identifier, check for a macro arg */
278 if (IsIdent (CurC)) {
280 Replacement = FindMacroArg (M, Ident);
282 /* Macro arg, keep the replacement */
283 keepstr (Replacement);
285 /* No macro argument, keep the original identifier */
288 } else if (CurC == '#' && IsIdent (NextC)) {
291 Replacement = FindMacroArg (M, Ident);
294 keepstr (Replacement);
300 } else if (IsQuote (CurC)) {
301 mptr = CopyQuotedString (mptr);
308 /* Reset the line pointer */
314 static int MacroCall (Macro* M)
315 /* Process a function like macro */
317 int ArgCount; /* Macro argument count */
318 unsigned ParCount; /* Number of open parenthesis */
319 char Buf[LINESIZE]; /* Argument buffer */
320 const char* ArgStart;
323 /* Expect an argument list */
326 PPError ("Illegal macro call");
330 /* Eat the left paren */
333 /* Read the actual macro arguments and store pointers to these arguments
334 * into the array of actual arguments in the macro definition.
342 /* Nested parenthesis */
346 } else if (IsQuote (CurC)) {
347 B = CopyQuotedString (B);
348 } else if (CurC == ',' || CurC == ')') {
350 /* End of actual argument */
352 while (IsBlank(*ArgStart)) {
355 if (ArgCount < M->ArgCount) {
356 M->ActualArgs[ArgCount++] = ArgStart;
357 } else if (CurC != ')' || *ArgStart != '\0' || M->ArgCount > 0) {
358 /* Be sure not to count the single empty argument for a
359 * macro that does not have arguments.
364 /* Check for end of macro param list */
370 /* Start the next param */
374 /* Comma or right paren inside nested parenthesis */
381 } else if (IsBlank (CurC)) {
382 /* Squeeze runs of blanks */
385 } else if (CurC == '\0') {
386 /* End of line inside macro argument list - read next line */
387 if (NextLine () == 0) {
391 /* Just copy the character */
397 /* Compare formal argument count with actual */
398 if (M->ArgCount != ArgCount) {
399 PPError ("Macro argument count mismatch");
400 /* Be sure to make enough empty arguments available */
401 while (ArgCount < M->ArgCount) {
402 M->ActualArgs [ArgCount++] = "";
406 /* Preprocess the line, replacing macro parameters */
415 static void ExpandMacro (Macro* M)
418 /* Check if this is a function like macro */
419 if (M->ArgCount >= 0) {
420 /* Function like macro */
421 if (MacroCall (M) == 0) {
425 /* Just copy the replacement text */
426 keepstr (M->Replacement);
432 static void DefineMacro (void)
433 /* Handle a macro definition. */
441 /* Read the macro name */
443 if (!MacName (Ident)) {
447 /* Get an existing macro definition with this name */
448 Existing = FindMacro (Ident);
450 /* Create a new macro definition */
451 M = NewMacro (Ident);
453 /* Check if this is a function like macro */
456 /* Skip the left paren */
459 /* Set the marker that this is a function like macro */
462 /* Read the formal parameter list */
467 if (MacName (Ident) == 0) {
470 AddMacroArg (M, Ident);
477 /* Check for a right paren and eat it if we find one */
479 PPError ("`)' expected");
486 /* Insert the macro into the macro table and allocate the ActualArgs array */
489 /* Remove whitespace and comments from the line, store the preprocessed
497 /* Create a copy of the replacement */
498 M->Replacement = xstrdup (Buf);
500 /* If we have an existing macro, check if the redefinition is identical.
501 * Print a diagnostic if not.
504 if (MacroCmp (M, Existing) != 0) {
505 PPError ("Macro redefinition is not identical");
512 /*****************************************************************************/
514 /*****************************************************************************/
518 static int Pass1 (const char* From, char* To)
519 /* Preprocessor pass 1. Remove whitespace and comments. */
525 /* Initialize reading from "From" */
531 /* Loop removing ws and comments */
533 while (CurC != '\0') {
534 if (IsBlank (CurC)) {
537 } else if (IsIdent (CurC)) {
539 if (Preprocessing && strcmp(Ident, "defined") == 0) {
540 /* Handle the "defined" operator */
548 if (!IsIdent (CurC)) {
549 PPError ("Identifier expected");
553 *mptr++ = IsMacro (Ident)? '1' : '0';
557 PPError ("`)' expected");
564 if (MaybeMacro (Ident[0])) {
569 } else if (IsQuote (CurC)) {
570 mptr = CopyQuotedString (mptr);
571 } else if (CurC == '/' && NextC == '*') {
574 } else if (ANSI == 0 && CurC == '/' && NextC == '/') {
576 /* Beware: Because line continuation chars are handled when reading
577 * lines, we may only skip til the end of the source line, which
578 * may not be the same as the end of the input line. The end of the
579 * source line is denoted by a lf (\n) character.
583 } while (CurC != '\n' && CurC != '\0');
598 static int Pass2 (const char* From, char* To)
599 /* Preprocessor pass 2. Perform macro substitution. */
605 /* Initialize reading from "From" */
611 /* Loop substituting macros */
613 while (CurC != '\0') {
614 /* If we have an identifier, check if it's a macro */
615 if (IsIdent (CurC)) {
617 M = FindMacro (Ident);
624 } else if (IsQuote (CurC)) {
625 mptr = CopyQuotedString (mptr);
636 static void xlateline (void)
637 /* Translate one line. */
642 Done = Pass1 (line, mline);
643 if (ExpandMacros == 0) {
645 ExpandMacros = 1; /* Reset to default */
649 /* Swap mline and line */
655 Done = Pass2 (line, mline);
659 /* Reinitialize line parsing */
665 static void DoUndef (void)
666 /* Process the #undef directive */
671 if (MacName (Ident)) {
672 UndefineMacro (Ident);
678 static int PushIf (int Skip, int Invert, int Cond)
679 /* Push a new if level onto the if stack */
681 /* Check for an overflow of the if stack */
682 if (IfIndex >= MAX_IFS-1) {
683 PPError ("Too many nested #if clauses");
687 /* Push the #if condition */
690 IfStack[IfIndex] = IFCOND_SKIP | IFCOND_NEEDTERM;
693 IfStack[IfIndex] = IFCOND_NONE | IFCOND_NEEDTERM;
694 return (Invert ^ Cond);
700 static int DoIf (int Skip)
701 /* Process #if directive */
706 /* We're about to abuse the compiler expression parser to evaluate the
707 * #if expression. Save the current tokens to come back here later.
708 * NOTE: Yes, this is a hack, but it saves a complete separate expression
709 * evaluation for the preprocessor.
714 /* Make sure the line infos for the tokens won't get removed */
716 UseLineInfo (sv1.LI);
719 UseLineInfo (sv2.LI);
722 /* Remove the #if from the line and add two semicolons as sentinels */
725 while (CurC != '\0') {
733 /* Start over parsing from line */
736 /* Switch into special preprocessing mode */
739 /* Expand macros in this line */
742 /* Prime the token pump (remove old tokens from the stream) */
746 /* Call the expression parser */
749 /* End preprocessing mode */
752 /* Reset the old tokens */
756 /* Set the #if condition according to the expression result */
757 return PushIf (Skip, 1, lval.ConstVal != 0);
762 static int DoIfDef (int skip, int flag)
763 /* Process #ifdef if flag == 1, or #ifndef if flag == 0. */
768 if (MacName (Ident) == 0) {
771 return PushIf (skip, flag, IsMacro(Ident));
777 static void DoInclude (void)
778 /* Open an include file. */
787 /* Get the next char and check for a valid file name terminator. Setup
788 * the include directory spec (SYS/USR) by looking at the terminator.
803 PPError ("`\"' or `<' expected");
808 /* Copy the filename into mline. Since mline has the same size as the
809 * input line, we don't need to check for an overflow here.
812 while (CurC != '\0' && CurC != RTerm) {
818 /* Check if we got a terminator */
820 /* No terminator found */
821 PPError ("Missing terminator or file name too long");
825 /* Open the include file */
826 OpenIncludeFile (mline, DirSpec);
829 /* Clear the remaining line so the next input will come from the new
837 static void DoError (void)
842 PPError ("Invalid #error directive");
844 PPError ("#error: %s", lptr);
847 /* Clear the rest of line */
853 void Preprocess (void)
854 /* Preprocess a line */
859 /* Skip white space at the beginning of the line */
862 /* Check for stuff to skip */
864 while (CurC == '\0' || CurC == '#' || Skip) {
866 /* Check for preprocessor lines lines */
871 /* Ignore the empty preprocessor directive */
874 if (!IsSym (Directive)) {
875 PPError ("Preprocessor directive expected");
878 switch (FindPPToken (Directive)) {
888 if ((IfStack[IfIndex] & IFCOND_ELSE) == 0) {
890 /* Handle as #else/#if combination */
891 if ((IfStack[IfIndex] & IFCOND_SKIP) == 0) {
894 IfStack[IfIndex] |= IFCOND_ELSE;
897 /* #elif doesn't need a terminator */
898 IfStack[IfIndex] &= ~IFCOND_NEEDTERM;
900 PPError ("Duplicate #else/#elif");
903 PPError ("Unexpected #elif");
909 if ((IfStack[IfIndex] & IFCOND_ELSE) == 0) {
910 if ((IfStack[IfIndex] & IFCOND_SKIP) == 0) {
913 IfStack[IfIndex] |= IFCOND_ELSE;
915 PPError ("Duplicate #else");
918 PPError ("Unexpected `#else'");
924 /* Remove any clauses on top of stack that do not
925 * need a terminating #endif.
927 while (IfIndex >= 0 && (IfStack[IfIndex] & IFCOND_NEEDTERM) == 0) {
931 /* Stack may not be empty here or something is wrong */
932 CHECK (IfIndex >= 0);
934 /* Remove the clause that needs a terminator */
935 Skip = (IfStack[IfIndex--] & IFCOND_SKIP) != 0;
937 PPError ("Unexpected `#endif'");
952 Skip = DoIfDef (Skip, 1);
956 Skip = DoIfDef (Skip, 0);
966 /* Not allowed in strict ANSI mode */
968 PPError ("Preprocessor directive expected");
975 /* Don't expand macros in this line */
977 /* #pragma is handled on the scanner level */
989 PPError ("Preprocessor directive expected");
995 if (NextLine () == 0) {
997 PPError ("`#endif' expected");
1006 Print (stdout, 2, "line: %s\n", line);