]> git.sur5r.net Git - cc65/blob - src/cc65/preproc.c
Fixed handling of function definitions with an empty parameter list. According
[cc65] / src / cc65 / preproc.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  preproc.c                                */
4 /*                                                                           */
5 /*                              cc65 preprocessor                            */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2008, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <errno.h>
40
41 /* common */
42 #include "chartype.h"
43 #include "check.h"
44 #include "inline.h"
45 #include "print.h"
46 #include "xmalloc.h"
47
48 /* cc65 */
49 #include "codegen.h"
50 #include "error.h"
51 #include "expr.h"
52 #include "global.h"
53 #include "ident.h"
54 #include "incpath.h"
55 #include "input.h"
56 #include "lineinfo.h"
57 #include "macrotab.h"
58 #include "preproc.h"
59 #include "scanner.h"
60 #include "standard.h"
61
62
63
64 /*****************************************************************************/
65 /*                                   Data                                    */
66 /*****************************************************************************/
67
68
69
70 /* Set when the preprocessor calls expr() recursively */
71 unsigned char Preprocessing = 0;
72
73 /* Management data for #if */
74 #define MAX_IFS         64
75 #define IFCOND_NONE     0x00U
76 #define IFCOND_SKIP     0x01U
77 #define IFCOND_ELSE     0x02U
78 #define IFCOND_NEEDTERM 0x04U
79 static unsigned char IfStack[MAX_IFS];
80 static int           IfIndex = -1;
81
82 /* Buffer for macro expansion */
83 static StrBuf* MLine;
84
85 /* Structure used when expanding macros */
86 typedef struct MacroExp MacroExp;
87 struct MacroExp {
88     Collection  ActualArgs;     /* Actual arguments */
89     StrBuf      Replacement;    /* Replacement with arguments substituted */
90     Macro*      M;              /* The macro we're handling */
91 };
92
93
94
95 /*****************************************************************************/
96 /*                                 Forwards                                  */
97 /*****************************************************************************/
98
99
100
101 static unsigned Pass1 (StrBuf* Source, StrBuf* Target);
102 /* Preprocessor pass 1. Remove whitespace. Handle old and new style comments
103  * and the "defined" operator.
104  */
105
106 static void MacroReplacement (StrBuf* Source, StrBuf* Target);
107 /* Perform macro replacement. */
108
109
110
111 /*****************************************************************************/
112 /*                   Low level preprocessor token handling                   */
113 /*****************************************************************************/
114
115
116
117 /* Types of preprocessor tokens */
118 typedef enum {
119     PP_ILLEGAL  = -1,
120     PP_DEFINE,
121     PP_ELIF,
122     PP_ELSE,
123     PP_ENDIF,
124     PP_ERROR,
125     PP_IF,
126     PP_IFDEF,
127     PP_IFNDEF,
128     PP_INCLUDE,
129     PP_LINE,
130     PP_PRAGMA,
131     PP_UNDEF,
132     PP_WARNING,
133 } pptoken_t;
134
135
136
137 /* Preprocessor keyword to token mapping table */
138 static const struct PPToken {
139     const char* Key;            /* Keyword */
140     pptoken_t   Tok;            /* Token */
141 } PPTokens[] = {
142     {   "define",       PP_DEFINE       },
143     {   "elif",         PP_ELIF         },
144     {   "else",         PP_ELSE         },
145     {   "endif",        PP_ENDIF        },
146     {   "error",        PP_ERROR        },
147     {   "if",           PP_IF           },
148     {   "ifdef",        PP_IFDEF        },
149     {   "ifndef",       PP_IFNDEF       },
150     {   "include",      PP_INCLUDE      },
151     {   "line",         PP_LINE         },
152     {   "pragma",       PP_PRAGMA       },
153     {   "undef",        PP_UNDEF        },
154     {   "warning",      PP_WARNING      },
155 };
156
157 /* Number of preprocessor tokens */
158 #define PPTOKEN_COUNT   (sizeof(PPTokens) / sizeof(PPTokens[0]))
159
160
161
162 static int CmpToken (const void* Key, const void* Elem)
163 /* Compare function for bsearch */
164 {
165     return strcmp ((const char*) Key, ((const struct PPToken*) Elem)->Key);
166 }
167
168
169
170 static pptoken_t FindPPToken (const char* Ident)
171 /* Find a preprocessor token and return it. Return PP_ILLEGAL if the identifier
172  * is not a valid preprocessor token.
173  */
174 {
175     struct PPToken* P;
176     P = bsearch (Ident, PPTokens, PPTOKEN_COUNT, sizeof (PPTokens[0]), CmpToken);
177     return P? P->Tok : PP_ILLEGAL;
178 }
179
180
181
182 /*****************************************************************************/
183 /*                              struct MacroExp                              */
184 /*****************************************************************************/
185
186
187
188 static MacroExp* InitMacroExp (MacroExp* E, Macro* M)
189 /* Initialize a MacroExp structure */
190 {
191     InitCollection (&E->ActualArgs);
192     SB_Init (&E->Replacement);
193     E->M = M;
194     return E;
195 }
196
197
198
199 static void DoneMacroExp (MacroExp* E)
200 /* Cleanup after use of a MacroExp structure */
201 {
202     unsigned I;
203
204     /* Delete the list with actual arguments */
205     for (I = 0; I < CollCount (&E->ActualArgs); ++I) {
206         FreeStrBuf (CollAtUnchecked (&E->ActualArgs, I));
207     }
208     DoneCollection (&E->ActualArgs);
209     SB_Done (&E->Replacement);
210 }
211
212
213
214 static void ME_AppendActual (MacroExp* E, StrBuf* Arg)
215 /* Add a copy of Arg to the list of actual macro arguments.
216  * NOTE: This function will clear Arg!
217  */
218 {
219     /* Create a new string buffer */
220     StrBuf* A = NewStrBuf ();
221
222     /* Move the contents of Arg to A */
223     SB_Move (A, Arg);
224
225     /* Add A to the actual arguments */
226     CollAppend (&E->ActualArgs, A);
227 }
228
229
230
231 static StrBuf* ME_GetActual (MacroExp* E, unsigned Index)
232 /* Return an actual macro argument with the given index */
233 {
234     return CollAt (&E->ActualArgs, Index);
235 }
236
237
238
239 static int ME_ArgIsVariadic (const MacroExp* E)
240 /* Return true if the next actual argument we will add is a variadic one */
241 {
242     return (E->M->Variadic &&
243             E->M->ArgCount == (int) CollCount (&E->ActualArgs) + 1);
244 }
245
246
247
248 /*****************************************************************************/
249 /*                                   Code                                    */
250 /*****************************************************************************/
251
252
253
254 static void Stringize (StrBuf* Source, StrBuf* Target)
255 /* Stringize the given string: Add double quotes at start and end and preceed
256  * each occurance of " and \ by a backslash.
257  */
258 {
259     char C;
260
261     /* Add a starting quote */
262     SB_AppendChar (Target, '\"');
263
264     /* Replace any characters inside the string may not be part of a string
265      * unescaped.
266      */
267     while ((C = SB_Get (Source)) != '\0') {
268         switch (C) {
269             case '\"':
270             case '\\':
271                 SB_AppendChar (Target, '\\');
272             /* FALLTHROUGH */
273             default:
274                 SB_AppendChar (Target, C);
275                 break;
276         }
277     }
278
279     /* Add the closing quote */
280     SB_AppendChar (Target, '\"');
281 }
282
283
284
285 static void OldStyleComment (void)
286 /* Remove an old style C comment from line. */
287 {
288     /* Remember the current line number, so we can output better error
289      * messages if the comment is not terminated in the current file.
290      */
291     unsigned StartingLine = GetCurrentLine();
292
293     /* Skip the start of comment chars */
294     NextChar ();
295     NextChar ();
296
297     /* Skip the comment */
298     while (CurC != '*' || NextC != '/') {
299         if (CurC == '\0') {
300             if (NextLine () == 0) {
301                 PPError ("End-of-file reached in comment starting at line %u",
302                          StartingLine);
303                 return;
304             }
305         } else {
306             if (CurC == '/' && NextC == '*') {
307                 PPWarning ("`/*' found inside a comment");
308             }
309             NextChar ();
310         }
311     }
312
313     /* Skip the end of comment chars */
314     NextChar ();
315     NextChar ();
316 }
317
318
319
320 static void NewStyleComment (void)
321 /* Remove a new style C comment from line. */
322 {
323     /* Beware: Because line continuation chars are handled when reading
324      * lines, we may only skip til the end of the source line, which
325      * may not be the same as the end of the input line. The end of the
326      * source line is denoted by a lf (\n) character.
327      */
328     do {
329         NextChar ();
330     } while (CurC != '\n' && CurC != '\0');
331     if (CurC == '\n') {
332         NextChar ();
333     }
334 }
335
336
337
338 static void SkipWhitespace (void)
339 /* Skip white space in the input stream. */
340 {
341     while (IsSpace (CurC)) {
342         NextChar ();
343     }
344 }
345
346
347
348 static void CopyQuotedString (StrBuf* Target)
349 /* Copy a single or double quoted string from the input to Target. */
350 {
351     /* Remember the quote character, copy it to the target buffer and skip it */
352     char Quote = CurC;
353     SB_AppendChar (Target, CurC);
354     NextChar ();
355
356     /* Copy the characters inside the string */
357     while (CurC != '\0' && CurC != Quote) {
358         /* Keep an escaped char */
359         if (CurC == '\\') {
360             SB_AppendChar (Target, CurC);
361             NextChar ();
362         }
363         /* Copy the character */
364         SB_AppendChar (Target, CurC);
365         NextChar ();
366     }
367
368     /* If we had a terminating quote, copy it */
369     if (CurC != '\0') {
370         SB_AppendChar (Target, CurC);
371         NextChar ();
372     }
373 }
374
375
376
377 /*****************************************************************************/
378 /*                                Macro stuff                                */
379 /*****************************************************************************/
380
381
382
383 static int MacName (char* Ident)
384 /* Get a macro symbol name into Ident.  If we have an error, print a
385  * diagnostic message and clear the line.
386  */
387 {
388     if (IsSym (Ident) == 0) {
389         PPError ("Identifier expected");
390         ClearLine ();
391         return 0;
392     } else {
393         return 1;
394     }
395 }
396
397
398
399 static void ReadMacroArgs (MacroExp* E)
400 /* Identify the arguments to a macro call */
401 {
402     unsigned    Parens;         /* Number of open parenthesis */
403     StrBuf      Arg = STATIC_STRBUF_INITIALIZER;
404
405     /* Read the actual macro arguments */
406     Parens = 0;
407     while (1) {
408         if (CurC == '(') {
409
410             /* Nested parenthesis */
411             SB_AppendChar (&Arg, CurC);
412             NextChar ();
413             ++Parens;
414
415         } else if (IsQuote (CurC)) {
416
417             /* Quoted string - just copy */
418             CopyQuotedString (&Arg);
419
420         } else if (CurC == ',' || CurC == ')') {
421
422             if (Parens) {
423                 /* Comma or right paren inside nested parenthesis */
424                 if (CurC == ')') {
425                     --Parens;
426                 }
427                 SB_AppendChar (&Arg, CurC);
428                 NextChar ();
429             } else if (CurC == ',' && ME_ArgIsVariadic (E)) {
430                 /* It's a comma, but we're inside a variadic macro argument, so
431                  * just copy it and proceed.
432                  */
433                 SB_AppendChar (&Arg, CurC);
434                 NextChar ();
435             } else {
436                 /* End of actual argument. Remove whitespace from the end. */
437                 while (IsSpace (SB_LookAtLast (&Arg))) {
438                     SB_Drop (&Arg, 1);
439                 }
440
441                 /* If this is not the single empty argument for a macro with
442                  * an empty argument list, remember it.
443                  */
444                 if (CurC != ')' || SB_NotEmpty (&Arg) || E->M->ArgCount > 0) {
445                     ME_AppendActual (E, &Arg);
446                 }
447
448                 /* Check for end of macro param list */
449                 if (CurC == ')') {
450                     NextChar ();
451                     break;
452                 }
453
454                 /* Start the next param */
455                 NextChar ();
456                 SB_Clear (&Arg);
457             }
458         } else if (IsSpace (CurC)) {
459             /* Squeeze runs of blanks within an arg */
460             if (SB_NotEmpty (&Arg)) {
461                 SB_AppendChar (&Arg, ' ');
462             }
463             SkipWhitespace ();
464         } else if (CurC == '/' && NextC == '*') {
465             if (SB_NotEmpty (&Arg)) {
466                 SB_AppendChar (&Arg, ' ');
467             }
468             OldStyleComment ();
469         } else if (IS_Get (&Standard) >= STD_C99 && CurC == '/' && NextC == '/') {
470             if (SB_NotEmpty (&Arg)) {
471                 SB_AppendChar (&Arg, ' ');
472             }
473             NewStyleComment ();
474         } else if (CurC == '\0') {
475             /* End of line inside macro argument list - read next line */
476             if (SB_NotEmpty (&Arg)) {
477                 SB_AppendChar (&Arg, ' ');
478             }
479             if (NextLine () == 0) {
480                 ClearLine ();
481                 break;
482             }
483         } else {
484             /* Just copy the character */
485             SB_AppendChar (&Arg, CurC);
486             NextChar ();
487         }
488     }
489
490     /* Deallocate string buf resources */
491     SB_Done (&Arg);
492 }
493
494
495
496 static void MacroArgSubst (MacroExp* E)
497 /* Argument substitution according to ISO/IEC 9899:1999 (E), 6.10.3.1ff */
498 {
499     ident       Ident;
500     int         ArgIdx;
501     StrBuf*     OldSource;
502     StrBuf*     Arg;
503     int         HaveSpace;
504
505
506     /* Remember the current input and switch to the macro replacement. */
507     SB_Reset (&E->M->Replacement);
508     OldSource = InitLine (&E->M->Replacement);
509
510     /* Argument handling loop */
511     while (CurC != '\0') {
512
513         /* If we have an identifier, check if it's a macro */
514         if (IsSym (Ident)) {
515
516             /* Check if it's a macro argument */
517             if ((ArgIdx = FindMacroArg (E->M, Ident)) >= 0) {
518
519                 /* A macro argument. Get the corresponding actual argument. */
520                 Arg = ME_GetActual (E, ArgIdx);
521
522                 /* Copy any following whitespace */
523                 HaveSpace = IsSpace (CurC);
524                 if (HaveSpace) {
525                     SkipWhitespace ();
526                 }
527
528                 /* If a ## operator follows, we have to insert the actual
529                  * argument as is, otherwise it must be macro replaced.
530                  */
531                 if (CurC == '#' && NextC == '#') {
532
533                     /* ### Add placemarker if necessary */
534                     SB_Append (&E->Replacement, Arg);
535
536                 } else {
537
538                     /* Replace the formal argument by a macro replaced copy
539                      * of the actual.
540                      */
541                     SB_Reset (Arg);
542                     MacroReplacement (Arg, &E->Replacement);
543
544                     /* If we skipped whitespace before, re-add it now */
545                     if (HaveSpace) {
546                         SB_AppendChar (&E->Replacement, ' ');
547                     }
548                 }
549
550
551             } else {
552
553                 /* An identifier, keep it */
554                 SB_AppendStr (&E->Replacement, Ident);
555
556             }
557
558         } else if (CurC == '#' && NextC == '#') {
559
560             /* ## operator. */
561             NextChar ();
562             NextChar ();
563             SkipWhitespace ();
564
565             /* Since we need to concatenate the token sequences, remove
566              * any whitespace that was added to target, since it must come
567              * from the input.
568              */
569             while (IsSpace (SB_LookAtLast (&E->Replacement))) {
570                 SB_Drop (&E->Replacement, 1);
571             }
572
573             /* If the next token is an identifier which is a macro argument,
574              * replace it, otherwise do nothing.
575              */
576             if (IsSym (Ident)) {
577
578                 /* Check if it's a macro argument */
579                 if ((ArgIdx = FindMacroArg (E->M, Ident)) >= 0) {
580
581                     /* Get the corresponding actual argument and add it. */
582                     SB_Append (&E->Replacement, ME_GetActual (E, ArgIdx));
583
584                 } else {
585
586                     /* Just an ordinary identifier - add as is */
587                     SB_AppendStr (&E->Replacement, Ident);
588
589                 }
590             }
591
592         } else if (CurC == '#' && E->M->ArgCount >= 0) {
593
594             /* A # operator within a macro expansion of a function like
595              * macro. Read the following identifier and check if it's a
596              * macro parameter.
597              */
598             NextChar ();
599             SkipWhitespace ();
600             if (!IsSym (Ident) || (ArgIdx = FindMacroArg (E->M, Ident)) < 0) {
601                 PPError ("`#' is not followed by a macro parameter");
602             } else {
603                 /* Make a valid string from Replacement */
604                 Arg = ME_GetActual (E, ArgIdx);
605                 SB_Reset (Arg);
606                 Stringize (Arg, &E->Replacement);
607             }
608
609         } else if (IsQuote (CurC)) {
610             CopyQuotedString (&E->Replacement);
611         } else {
612             SB_AppendChar (&E->Replacement, CurC);
613             NextChar ();
614         }
615     }
616
617 #if 0
618     /* Remove whitespace from the end of the line */
619     while (IsSpace (SB_LookAtLast (&E->Replacement))) {
620         SB_Drop (&E->Replacement, 1);
621     }
622 #endif
623
624     /* Switch back the input */
625     InitLine (OldSource);
626 }
627
628
629
630 static void MacroCall (StrBuf* Target, Macro* M)
631 /* Process a function like macro */
632 {
633     MacroExp    E;
634
635     /* Eat the left paren */
636     NextChar ();
637
638     /* Initialize our MacroExp structure */
639     InitMacroExp (&E, M);
640
641     /* Read the actual macro arguments */
642     ReadMacroArgs (&E);
643
644     /* Compare formal and actual argument count */
645     if (CollCount (&E.ActualArgs) != (unsigned) M->ArgCount) {
646
647         StrBuf Arg = STATIC_STRBUF_INITIALIZER;
648
649         /* Argument count mismatch */
650         PPError ("Macro argument count mismatch");
651
652         /* Be sure to make enough empty arguments available */
653         while (CollCount (&E.ActualArgs) < (unsigned) M->ArgCount) {
654             ME_AppendActual (&E, &Arg);
655         }
656     }
657
658     /* Replace macro arguments handling the # and ## operators */
659     MacroArgSubst (&E);
660
661     /* Do macro replacement on the macro that already has the parameters
662      * substituted.
663      */
664     M->Expanding = 1;
665     MacroReplacement (&E.Replacement, Target);
666     M->Expanding = 0;
667
668     /* Free memory allocated for the macro expansion structure */
669     DoneMacroExp (&E);
670 }
671
672
673
674 static void ExpandMacro (StrBuf* Target, Macro* M)
675 /* Expand a macro into Target */
676 {
677     /* ### printf ("Expanding %s(%u)\n", M->Name, ++V); */
678
679     /* Check if this is a function like macro */
680     if (M->ArgCount >= 0) {
681
682         int Whitespace = IsSpace (CurC);
683         if (Whitespace) {
684             SkipWhitespace ();
685         }
686         if (CurC != '(') {
687             /* Function like macro but no parameter list */
688             SB_AppendStr (Target, M->Name);
689             if (Whitespace) {
690                 SB_AppendChar (Target, ' ');
691             }
692         } else {
693             /* Function like macro */
694             MacroCall (Target, M);
695         }
696
697     } else {
698
699         MacroExp E;
700         InitMacroExp (&E, M);
701
702         /* Handle # and ## operators for object like macros */
703         MacroArgSubst (&E);
704
705         /* Do macro replacement on the macro that already has the parameters
706          * substituted.
707          */
708         M->Expanding = 1;
709         MacroReplacement (&E.Replacement, Target);
710         M->Expanding = 0;
711
712         /* Free memory allocated for the macro expansion structure */
713         DoneMacroExp (&E);
714
715     }
716     /* ### printf ("Done with %s(%u)\n", M->Name, V--); */
717 }
718
719
720
721 static void DefineMacro (void)
722 /* Handle a macro definition. */
723 {
724     ident       Ident;
725     Macro*      M;
726     Macro*      Existing;
727     int         C89;
728
729     /* Read the macro name */
730     SkipWhitespace ();
731     if (!MacName (Ident)) {
732         return;
733     }
734
735     /* Remember if we're in C89 mode */
736     C89 = (IS_Get (&Standard) == STD_C89);
737
738     /* Get an existing macro definition with this name */
739     Existing = FindMacro (Ident);
740
741     /* Create a new macro definition */
742     M = NewMacro (Ident);
743
744     /* Check if this is a function like macro */
745     if (CurC == '(') {
746
747         /* Skip the left paren */
748         NextChar ();
749
750         /* Set the marker that this is a function like macro */
751         M->ArgCount = 0;
752
753         /* Read the formal parameter list */
754         while (1) {
755
756             /* Skip white space and check for end of parameter list */
757             SkipWhitespace ();
758             if (CurC == ')') {
759                 break;
760             }
761
762             /* The next token must be either an identifier, or - if not in
763              * C89 mode - the ellipsis.
764              */
765             if (!C89 && CurC == '.') {
766                 /* Ellipsis */
767                 NextChar ();
768                 if (CurC != '.' || NextC != '.') {
769                     PPError ("`...' expected");
770                     ClearLine ();
771                     return;
772                 }
773                 NextChar ();
774                 NextChar ();
775
776                 /* Remember that the macro is variadic and use __VA_ARGS__ as
777                  * the argument name.
778                  */
779                 AddMacroArg (M, "__VA_ARGS__");
780                 M->Variadic = 1;
781
782             } else {
783                 /* Must be macro argument name */
784                 if (MacName (Ident) == 0) {
785                     return;
786                 }
787
788                 /* __VA_ARGS__ is only allowed in C89 mode */
789                 if (!C89 && strcmp (Ident, "__VA_ARGS__") == 0) {
790                     PPWarning ("`__VA_ARGS__' can only appear in the expansion "
791                                "of a C99 variadic macro");
792                 }
793
794                 /* Add the macro argument */
795                 AddMacroArg (M, Ident);
796             }
797
798             /* If we had an ellipsis, or the next char is not a comma, we've
799              * reached the end of the macro argument list.
800              */
801             SkipWhitespace ();
802             if (M->Variadic || CurC != ',') {
803                 break;
804             }
805             NextChar ();
806         }
807
808         /* Check for a right paren and eat it if we find one */
809         if (CurC != ')') {
810             PPError ("`)' expected");
811             ClearLine ();
812             return;
813         }
814         NextChar ();
815     }
816
817     /* Skip whitespace before the macro replacement */
818     SkipWhitespace ();
819
820     /* Insert the macro into the macro table and allocate the ActualArgs array */
821     InsertMacro (M);
822
823     /* Remove whitespace and comments from the line, store the preprocessed
824      * line into the macro replacement buffer.
825      */
826     Pass1 (Line, &M->Replacement);
827
828     /* Remove whitespace from the end of the line */
829     while (IsSpace (SB_LookAtLast (&M->Replacement))) {
830         SB_Drop (&M->Replacement, 1);
831     }
832
833     /* ### printf ("%s: <%.*s>\n", M->Name, SB_GetLen (&M->Replacement), SB_GetConstBuf (&M->Replacement)); */
834
835     /* If we have an existing macro, check if the redefinition is identical.
836      * Print a diagnostic if not.
837      */
838     if (Existing && MacroCmp (M, Existing) != 0) {
839         PPError ("Macro redefinition is not identical");
840     }
841 }
842
843
844
845 /*****************************************************************************/
846 /*                               Preprocessing                               */
847 /*****************************************************************************/
848
849
850
851 static unsigned Pass1 (StrBuf* Source, StrBuf* Target)
852 /* Preprocessor pass 1. Remove whitespace. Handle old and new style comments
853  * and the "defined" operator.
854  */
855 {
856     unsigned    IdentCount;
857     ident       Ident;
858     int         HaveParen;
859
860     /* Switch to the new input source */
861     StrBuf* OldSource = InitLine (Source);
862
863     /* Loop removing ws and comments */
864     IdentCount = 0;
865     while (CurC != '\0') {
866         if (IsSpace (CurC)) {
867             /* Squeeze runs of blanks */
868             if (!IsSpace (SB_LookAtLast (Target))) {
869                 SB_AppendChar (Target, ' ');
870             }
871             SkipWhitespace ();
872         } else if (IsSym (Ident)) {
873             if (Preprocessing && strcmp (Ident, "defined") == 0) {
874                 /* Handle the "defined" operator */
875                 SkipWhitespace ();
876                 HaveParen = 0;
877                 if (CurC == '(') {
878                     HaveParen = 1;
879                     NextChar ();
880                     SkipWhitespace ();
881                 }
882                 if (IsSym (Ident)) {
883                     SB_AppendChar (Target, IsMacro (Ident)? '1' : '0');
884                     if (HaveParen) {
885                         SkipWhitespace ();
886                         if (CurC != ')') {
887                             PPError ("`)' expected");
888                         } else {
889                             NextChar ();
890                         }
891                     }
892                 } else {
893                     PPError ("Identifier expected");
894                     SB_AppendChar (Target, '0');
895                 }
896             } else {
897                 ++IdentCount;
898                 SB_AppendStr (Target, Ident);
899             }
900         } else if (IsQuote (CurC)) {
901             CopyQuotedString (Target);
902         } else if (CurC == '/' && NextC == '*') {
903             if (!IsSpace (SB_LookAtLast (Target))) {
904                 SB_AppendChar (Target, ' ');
905             }
906             OldStyleComment ();
907         } else if (IS_Get (&Standard) >= STD_C99 && CurC == '/' && NextC == '/') {
908             if (!IsSpace (SB_LookAtLast (Target))) {
909                 SB_AppendChar (Target, ' ');
910             }
911             NewStyleComment ();
912         } else {
913             SB_AppendChar (Target, CurC);
914             NextChar ();
915         }
916     }
917
918     /* Switch back to the old source */
919     InitLine (OldSource);
920
921     /* Return the number of identifiers found in the line */
922     return IdentCount;
923 }
924
925
926
927 static void MacroReplacement (StrBuf* Source, StrBuf* Target)
928 /* Perform macro replacement. */
929 {
930     ident       Ident;
931     Macro*      M;
932
933     /* Remember the current input and switch to Source */
934     StrBuf* OldSource = InitLine (Source);
935
936     /* Loop substituting macros */
937     while (CurC != '\0') {
938         /* If we have an identifier, check if it's a macro */
939         if (IsSym (Ident)) {
940             /* Check if it's a macro */
941             if ((M = FindMacro (Ident)) != 0 && !M->Expanding) {
942                 /* It's a macro, expand it */
943                 ExpandMacro (Target, M);
944             } else {
945                 /* An identifier, keep it */
946                 SB_AppendStr (Target, Ident);
947             }
948         } else if (IsQuote (CurC)) {
949             CopyQuotedString (Target);
950         } else if (IsSpace (CurC)) {
951             if (!IsSpace (SB_LookAtLast (Target))) {
952                 SB_AppendChar (Target, CurC);
953             }
954             NextChar ();
955         } else {
956             SB_AppendChar (Target, CurC);
957             NextChar ();
958         }
959     }
960
961     /* Switch back the input */
962     InitLine (OldSource);
963 }
964
965
966
967 static void PreprocessLine (void)
968 /* Translate one line. */
969 {
970     /* Trim whitespace and remove comments. The function returns the number of
971      * identifiers found. If there were any, we will have to check for macros.
972      */
973     SB_Clear (MLine);
974     if (Pass1 (Line, MLine) > 0) {
975         MLine = InitLine (MLine);
976         SB_Reset (Line);
977         SB_Clear (MLine);
978         MacroReplacement (Line, MLine);
979     }
980
981     /* Read from the new line */
982     SB_Reset (MLine);
983     MLine = InitLine (MLine);
984 }
985
986
987
988 static int PushIf (int Skip, int Invert, int Cond)
989 /* Push a new if level onto the if stack */
990 {
991     /* Check for an overflow of the if stack */
992     if (IfIndex >= MAX_IFS-1) {
993         PPError ("Too many nested #if clauses");
994         return 1;
995     }
996
997     /* Push the #if condition */
998     ++IfIndex;
999     if (Skip) {
1000         IfStack[IfIndex] = IFCOND_SKIP | IFCOND_NEEDTERM;
1001         return 1;
1002     } else {
1003         IfStack[IfIndex] = IFCOND_NONE | IFCOND_NEEDTERM;
1004         return (Invert ^ Cond);
1005     }
1006 }
1007
1008
1009
1010 static void DoError (void)
1011 /* Print an error */
1012 {
1013     SkipWhitespace ();
1014     if (CurC == '\0') {
1015         PPError ("Invalid #error directive");
1016     } else {
1017         PPError ("#error: %s", SB_GetConstBuf (Line) + SB_GetIndex (Line));
1018     }
1019
1020     /* Clear the rest of line */
1021     ClearLine ();
1022 }
1023
1024
1025
1026 static int DoIf (int Skip)
1027 /* Process #if directive */
1028 {
1029     ExprDesc Expr;
1030
1031     /* We're about to abuse the compiler expression parser to evaluate the
1032      * #if expression. Save the current tokens to come back here later.
1033      * NOTE: Yes, this is a hack, but it saves a complete separate expression
1034      * evaluation for the preprocessor.
1035      */
1036     Token SavedCurTok  = CurTok;
1037     Token SavedNextTok = NextTok;
1038
1039     /* Make sure the line infos for the tokens won't get removed */
1040     if (SavedCurTok.LI) {
1041         UseLineInfo (SavedCurTok.LI);
1042     }
1043     if (SavedNextTok.LI) {
1044         UseLineInfo (SavedNextTok.LI);
1045     }
1046
1047     /* Switch into special preprocessing mode */
1048     Preprocessing = 1;
1049
1050     /* Expand macros in this line */
1051     PreprocessLine ();
1052
1053     /* Add two semicolons as sentinels to the line, so the following
1054      * expression evaluation will eat these two tokens but nothing from
1055      * the following line.
1056      */
1057     SB_AppendStr (Line, ";;");
1058     SB_Terminate (Line);
1059
1060     /* Load CurTok and NextTok with tokens from the new input */
1061     NextToken ();
1062     NextToken ();
1063
1064     /* Call the expression parser */
1065     ConstExpr (hie1, &Expr);
1066
1067     /* End preprocessing mode */
1068     Preprocessing = 0;
1069
1070     /* Reset the old tokens */
1071     CurTok  = SavedCurTok;
1072     NextTok = SavedNextTok;
1073
1074     /* Set the #if condition according to the expression result */
1075     return PushIf (Skip, 1, Expr.IVal != 0);
1076 }
1077
1078
1079
1080 static int DoIfDef (int skip, int flag)
1081 /* Process #ifdef if flag == 1, or #ifndef if flag == 0. */
1082 {
1083     ident Ident;
1084
1085     SkipWhitespace ();
1086     if (MacName (Ident) == 0) {
1087         return 0;
1088     } else {
1089         return PushIf (skip, flag, IsMacro(Ident));
1090     }
1091 }
1092
1093
1094
1095 static void DoInclude (void)
1096 /* Open an include file. */
1097 {
1098     char        RTerm;
1099     unsigned    DirSpec;
1100     StrBuf      Filename = STATIC_STRBUF_INITIALIZER;
1101
1102
1103     /* Preprocess the remainder of the line */
1104     PreprocessLine ();
1105
1106     /* Skip blanks */
1107     SkipWhitespace ();
1108
1109     /* Get the next char and check for a valid file name terminator. Setup
1110      * the include directory spec (SYS/USR) by looking at the terminator.
1111      */
1112     switch (CurC) {
1113
1114         case '\"':
1115             RTerm   = '\"';
1116             DirSpec = INC_USER;
1117             break;
1118
1119         case '<':
1120             RTerm   = '>';
1121             DirSpec = INC_SYS;
1122             break;
1123
1124         default:
1125             PPError ("`\"' or `<' expected");
1126             goto Done;
1127     }
1128     NextChar ();
1129
1130     /* Get a copy of the filename */
1131     while (CurC != '\0' && CurC != RTerm) {
1132         SB_AppendChar (&Filename, CurC);
1133         NextChar ();
1134     }
1135     SB_Terminate (&Filename);
1136
1137     /* Check if we got a terminator */
1138     if (CurC == RTerm) {
1139         /* Open the include file */
1140         OpenIncludeFile (SB_GetConstBuf (&Filename), DirSpec);
1141     } else if (CurC == '\0') {
1142         /* No terminator found */
1143         PPError ("#include expects \"FILENAME\" or <FILENAME>");
1144     }
1145
1146 Done:
1147     /* Free the allocated filename data */
1148     SB_Done (&Filename);
1149
1150     /* Clear the remaining line so the next input will come from the new
1151      * file (if open)
1152      */
1153     ClearLine ();
1154 }
1155
1156
1157
1158 static void DoPragma (void)
1159 /* Handle a #pragma line by converting the #pragma preprocessor directive into
1160  * the _Pragma() compiler operator.
1161  */
1162 {
1163     /* Skip blanks following the #pragma directive */
1164     SkipWhitespace ();
1165
1166     /* Copy the remainder of the line into MLine removing comments and ws */
1167     SB_Clear (MLine);
1168     Pass1 (Line, MLine);
1169
1170     /* Convert the directive into the operator */
1171     SB_CopyStr (Line, "_Pragma (");
1172     SB_Reset (MLine);
1173     Stringize (MLine, Line);
1174     SB_AppendChar (Line, ')');
1175
1176     /* Initialize reading from line */
1177     SB_Reset (Line);
1178     InitLine (Line);
1179 }
1180
1181
1182
1183 static void DoUndef (void)
1184 /* Process the #undef directive */
1185 {
1186     ident Ident;
1187
1188     SkipWhitespace ();
1189     if (MacName (Ident)) {
1190         UndefineMacro (Ident);
1191     }
1192 }
1193
1194
1195
1196 static void DoWarning (void)
1197 /* Print a warning */
1198 {
1199     SkipWhitespace ();
1200     if (CurC == '\0') {
1201         PPError ("Invalid #warning directive");
1202     } else {
1203         PPWarning ("#warning: %s", SB_GetConstBuf (Line) + SB_GetIndex (Line));
1204     }
1205
1206     /* Clear the rest of line */
1207     ClearLine ();
1208 }
1209
1210
1211
1212 void Preprocess (void)
1213 /* Preprocess a line */
1214 {
1215     int         Skip;
1216     ident       Directive;
1217
1218     /* Create the output buffer if we don't already have one */
1219     if (MLine == 0) {
1220         MLine = NewStrBuf ();
1221     }
1222
1223     /* Skip white space at the beginning of the line */
1224     SkipWhitespace ();
1225
1226     /* Check for stuff to skip */
1227     Skip = 0;
1228     while (CurC == '\0' || CurC == '#' || Skip) {
1229
1230         /* Check for preprocessor lines lines */
1231         if (CurC == '#') {
1232             NextChar ();
1233             SkipWhitespace ();
1234             if (CurC == '\0') {
1235                 /* Ignore the empty preprocessor directive */
1236                 continue;
1237             }
1238             if (!IsSym (Directive)) {
1239                 PPError ("Preprocessor directive expected");
1240                 ClearLine ();
1241             } else {
1242                 switch (FindPPToken (Directive)) {
1243
1244                     case PP_DEFINE:
1245                         if (!Skip) {
1246                             DefineMacro ();
1247                         }
1248                         break;
1249
1250                     case PP_ELIF:
1251                         if (IfIndex >= 0) {
1252                             if ((IfStack[IfIndex] & IFCOND_ELSE) == 0) {
1253
1254                                 /* Handle as #else/#if combination */
1255                                 if ((IfStack[IfIndex] & IFCOND_SKIP) == 0) {
1256                                     Skip = !Skip;
1257                                 }
1258                                 IfStack[IfIndex] |= IFCOND_ELSE;
1259                                 Skip = DoIf (Skip);
1260
1261                                 /* #elif doesn't need a terminator */
1262                                 IfStack[IfIndex] &= ~IFCOND_NEEDTERM;
1263                             } else {
1264                                 PPError ("Duplicate #else/#elif");
1265                             }
1266                         } else {
1267                             PPError ("Unexpected #elif");
1268                         }
1269                         break;
1270
1271                     case PP_ELSE:
1272                         if (IfIndex >= 0) {
1273                             if ((IfStack[IfIndex] & IFCOND_ELSE) == 0) {
1274                                 if ((IfStack[IfIndex] & IFCOND_SKIP) == 0) {
1275                                     Skip = !Skip;
1276                                 }
1277                                 IfStack[IfIndex] |= IFCOND_ELSE;
1278                             } else {
1279                                 PPError ("Duplicate #else");
1280                             }
1281                         } else {
1282                             PPError ("Unexpected `#else'");
1283                         }
1284                         break;
1285
1286                     case PP_ENDIF:
1287                         if (IfIndex >= 0) {
1288                             /* Remove any clauses on top of stack that do not
1289                              * need a terminating #endif.
1290                              */
1291                             while (IfIndex >= 0 && (IfStack[IfIndex] & IFCOND_NEEDTERM) == 0) {
1292                                 --IfIndex;
1293                             }
1294
1295                             /* Stack may not be empty here or something is wrong */
1296                             CHECK (IfIndex >= 0);
1297
1298                             /* Remove the clause that needs a terminator */
1299                             Skip = (IfStack[IfIndex--] & IFCOND_SKIP) != 0;
1300                         } else {
1301                             PPError ("Unexpected `#endif'");
1302                         }
1303                         break;
1304
1305                     case PP_ERROR:
1306                         if (!Skip) {
1307                             DoError ();
1308                         }
1309                         break;
1310
1311                     case PP_IF:
1312                         Skip = DoIf (Skip);
1313                         break;
1314
1315                     case PP_IFDEF:
1316                         Skip = DoIfDef (Skip, 1);
1317                         break;
1318
1319                     case PP_IFNDEF:
1320                         Skip = DoIfDef (Skip, 0);
1321                         break;
1322
1323                     case PP_INCLUDE:
1324                         if (!Skip) {
1325                             DoInclude ();
1326                         }
1327                         break;
1328
1329                     case PP_LINE:
1330                         /* Should do something in C99 at least, but we ignore it */
1331                         if (!Skip) {
1332                             ClearLine ();
1333                         }
1334                         break;
1335
1336                     case PP_PRAGMA:
1337                         if (!Skip) {
1338                             DoPragma ();
1339                             goto Done;
1340                         }
1341                         break;
1342
1343                     case PP_UNDEF:
1344                         if (!Skip) {
1345                             DoUndef ();
1346                         }
1347                         break;
1348
1349                     case PP_WARNING:
1350                         /* #warning is a non standard extension */
1351                         if (IS_Get (&Standard) > STD_C99) {
1352                             if (!Skip) {
1353                                 DoWarning ();
1354                             }
1355                         } else {
1356                             PPError ("Preprocessor directive expected");
1357                             ClearLine ();
1358                         }
1359                         break;
1360
1361                     default:
1362                         PPError ("Preprocessor directive expected");
1363                         ClearLine ();
1364                 }
1365             }
1366
1367         }
1368         if (NextLine () == 0) {
1369             if (IfIndex >= 0) {
1370                 PPError ("`#endif' expected");
1371             }
1372             return;
1373         }
1374         SkipWhitespace ();
1375     }
1376
1377     PreprocessLine ();
1378
1379 Done:
1380     if (Verbosity > 1 && SB_NotEmpty (Line)) {
1381         printf ("%s(%u): %.*s\n", GetCurrentFile (), GetCurrentLine (),
1382                 SB_GetLen (Line), SB_GetConstBuf (Line));
1383     }
1384 }
1385