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