Add noinput directive to all lex files to avoid a compiler warning.
[wine] / libs / wpp / ppl.l
1 /* -*-C-*-
2  * Wrc preprocessor lexical analysis
3  *
4  * Copyright 1999-2000  Bertho A. Stultiens (BS)
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * History:
21  * 24-Apr-2000 BS       - Started from scratch to restructure everything
22  *                        and reintegrate the source into the wine-tree.
23  * 04-Jan-2000 BS       - Added comments about the lexicographical
24  *                        grammar to give some insight in the complexity.
25  * 28-Dec-1999 BS       - Eliminated backing-up of the flexer by running
26  *                        `flex -b' on the source. This results in some
27  *                        weirdo extra rules, but a much faster scanner.
28  * 23-Dec-1999 BS       - Started this file
29  *
30  *-------------------------------------------------------------------------
31  * The preprocessor's lexographical grammar (approximately):
32  *
33  * pp           := {ws} # {ws} if {ws} {expr} {ws} \n
34  *              |  {ws} # {ws} ifdef {ws} {id} {ws} \n
35  *              |  {ws} # {ws} ifndef {ws} {id} {ws} \n
36  *              |  {ws} # {ws} elif {ws} {expr} {ws} \n
37  *              |  {ws} # {ws} else {ws} \n
38  *              |  {ws} # {ws} endif {ws} \n
39  *              |  {ws} # {ws} include {ws} < {anytext} > \n
40  *              |  {ws} # {ws} include {ws} " {anytext} " \n
41  *              |  {ws} # {ws} define {ws} {anytext} \n
42  *              |  {ws} # {ws} define( {arglist} ) {ws} {expansion} \n
43  *              |  {ws} # {ws} pragma {ws} {anytext} \n
44  *              |  {ws} # {ws} ident {ws} {anytext} \n
45  *              |  {ws} # {ws} error {ws} {anytext} \n
46  *              |  {ws} # {ws} warning {ws} {anytext} \n
47  *              |  {ws} # {ws} line {ws} " {anytext} " {number} \n
48  *              |  {ws} # {ws} {number} " {anytext} " {number} [ {number} [{number}] ] \n
49  *              |  {ws} # {ws} \n
50  *
51  * ws           := [ \t\r\f\v]*
52  *
53  * expr         := {expr} [+-*%^/|&] {expr}
54  *              |  {expr} {logor|logand} {expr}
55  *              |  [!~+-] {expr}
56  *              |  {expr} ? {expr} : {expr}
57  *
58  * logor        := ||
59  *
60  * logand       := &&
61  *
62  * id           := [a-zA-Z_][a-zA-Z0-9_]*
63  *
64  * anytext      := [^\n]*       (see note)
65  *
66  * arglist      :=
67  *              |  {id}
68  *              |  {arglist} , {id}
69  *              |  {arglist} , {id} ...
70  *
71  * expansion    := {id}
72  *              |  # {id}
73  *              |  {anytext}
74  *              |  {anytext} ## {anytext}
75  *
76  * number       := [0-9]+
77  *
78  * Note: "anytext" is not always "[^\n]*". This is because the
79  *       trailing context must be considered as well.
80  *
81  * The only certain assumption for the preprocessor to make is that
82  * directives start at the beginning of the line, followed by a '#'
83  * and end with a newline.
84  * Any directive may be suffixed with a line-continuation. Also
85  * classical comment / *...* / (note: no comments within comments,
86  * therefore spaces) is considered to be a line-continuation
87  * (according to gcc and egcs AFAIK, ANSI is a bit vague).
88  * Comments have not been added to the above grammar for simplicity
89  * reasons. However, it is allowed to enter comment anywhere within
90  * the directives as long as they do not interfere with the context.
91  * All comments are considered to be deletable whitespace (both
92  * classical form "/ *...* /" and C++ form "//...\n").
93  *
94  * All recursive scans, except for macro-expansion, are done by the
95  * parser, whereas the simple state transitions of non-recursive
96  * directives are done in the scanner. This results in the many
97  * exclusive start-conditions of the scanner.
98  *
99  * Macro expansions are slightly more difficult because they have to
100  * prescan the arguments. Parameter substitution is literal if the
101  * substitution is # or ## (either side). This enables new identifiers
102  * to be created (see 'info cpp' node Macro|Pitfalls|Prescan for more
103  * information).
104  *
105  * FIXME: Variable macro parameters is recognized, but not yet
106  * expanded. I have to reread the ANSI standard on the subject (yes,
107  * ANSI defines it).
108  *
109  * The following special defines are supported:
110  * __FILE__     -> "thissource.c"
111  * __LINE__     -> 123
112  * __DATE__     -> "May  1 2000"
113  * __TIME__     -> "23:59:59"
114  * These macros expand, as expected, into their ANSI defined values.
115  *
116  * The same include prevention is implemented as gcc and egcs does.
117  * This results in faster processing because we do not read the text
118  * at all. Some wine-sources attempt to include the same file 4 or 5
119  * times. This strategy also saves a lot blank output-lines, which in
120  * its turn improves the real resource scanner/parser.
121  *
122  */
123
124 /*
125  * Special flex options and exclusive scanner start-conditions
126  */
127 %option stack
128 %option 8bit never-interactive
129 %option noinput nounput
130 %option prefix="ppy_"
131
132 %x pp_pp
133 %x pp_eol
134 %x pp_inc
135 %x pp_dqs
136 %x pp_sqs
137 %x pp_iqs
138 %x pp_comment
139 %x pp_def
140 %x pp_define
141 %x pp_macro
142 %x pp_mbody
143 %x pp_macign
144 %x pp_macscan
145 %x pp_macexp
146 %x pp_if
147 %x pp_ifd
148 %x pp_endif
149 %x pp_line
150 %x pp_defined
151 %x pp_ignore
152 %x RCINCL
153
154 ws      [ \v\f\t\r]
155 cident  [a-zA-Z_][0-9a-zA-Z_]*
156 ul      [uUlL]|[uUlL][lL]|[lL][uU]|[lL][lL][uU]|[uU][lL][lL]|[lL][uU][lL]
157
158 %{
159 #include "config.h"
160 #include "wine/port.h"
161 #include <stdio.h>
162 #include <stdlib.h>
163 #include <string.h>
164 #include <ctype.h>
165 #include <assert.h>
166
167 #ifndef HAVE_UNISTD_H
168 #define YY_NO_UNISTD_H
169 #endif
170
171 #include "wpp_private.h"
172 #include "ppy.tab.h"
173
174 /*
175  * Make sure that we are running an appropriate version of flex.
176  */
177 #if !defined(YY_FLEX_MAJOR_VERSION) || (1000 * YY_FLEX_MAJOR_VERSION + YY_FLEX_MINOR_VERSION < 2005)
178 #error Must use flex version 2.5.1 or higher (yy_scan_* routines are required).
179 #endif
180
181 #define YY_READ_BUF_SIZE        65536           /* So we read most of a file at once */
182
183 #define yy_current_state()      YY_START
184 #define yy_pp_state(x)          yy_pop_state(); yy_push_state(x)
185
186 /*
187  * Always update the current character position within a line
188  */
189 #define YY_USER_ACTION  pp_status.char_number+=ppy_leng;
190
191 /*
192  * Buffer management for includes and expansions
193  */
194 #define MAXBUFFERSTACK  128     /* Nesting more than 128 includes or macro expansion textss is insane */
195
196 typedef struct bufferstackentry {
197         YY_BUFFER_STATE bufferstate;    /* Buffer to switch back to */
198         pp_entry_t      *define;        /* Points to expanding define or NULL if handling includes */
199         int             line_number;    /* Line that we were handling */
200         int             char_number;    /* The current position on that line */
201         const char      *filename;      /* Filename that we were handling */
202         int             if_depth;       /* How many #if:s deep to check matching #endif:s */
203         int             ncontinuations; /* Remember the continuation state */
204         int             should_pop;     /* Set if we must pop the start-state on EOF */
205         /* Include management */
206         include_state_t incl;
207         char            *include_filename;
208 } bufferstackentry_t;
209
210 #define ALLOCBLOCKSIZE  (1 << 10)       /* Allocate these chunks at a time for string-buffers */
211
212 /*
213  * Macro expansion nesting
214  * We need the stack to handle expansions while scanning
215  * a macro's arguments. The TOS must always be the macro
216  * that receives the current expansion from the scanner.
217  */
218 #define MAXMACEXPSTACK  128     /* Nesting more than 128 macro expansions is insane */
219
220 typedef struct macexpstackentry {
221         pp_entry_t      *ppp;           /* This macro we are scanning */
222         char            **args;         /* With these arguments */
223         char            **ppargs;       /* Resulting in these preprocessed arguments */
224         int             *nnls;          /* Number of newlines per argument */
225         int             nargs;          /* And this many arguments scanned */
226         int             parentheses;    /* Nesting level of () */
227         int             curargsize;     /* Current scanning argument's size */
228         int             curargalloc;    /* Current scanning argument's block allocated */
229         char            *curarg;        /* Current scanning argument's content */
230 } macexpstackentry_t;
231
232 #define MACROPARENTHESES()      (top_macro()->parentheses)
233
234 /*
235  * Prototypes
236  */
237 static void newline(int);
238 static int make_number(int radix, YYSTYPE *val, const char *str, int len);
239 static void put_buffer(const char *s, int len);
240 /* Buffer management */
241 static void push_buffer(pp_entry_t *ppp, char *filename, char *incname, int pop);
242 static bufferstackentry_t *pop_buffer(void);
243 /* String functions */
244 static void new_string(void);
245 static void add_string(const char *str, int len);
246 static char *get_string(void);
247 static void put_string(void);
248 static int string_start(void);
249 /* Macro functions */
250 static void push_macro(pp_entry_t *ppp);
251 static macexpstackentry_t *top_macro(void);
252 static macexpstackentry_t *pop_macro(void);
253 static void free_macro(macexpstackentry_t *mep);
254 static void add_text_to_macro(const char *text, int len);
255 static void macro_add_arg(int last);
256 static void macro_add_expansion(void);
257 /* Expansion */
258 static void expand_special(pp_entry_t *ppp);
259 static void expand_define(pp_entry_t *ppp);
260 static void expand_macro(macexpstackentry_t *mep);
261
262 /*
263  * Local variables
264  */
265 static int ncontinuations;
266
267 static int strbuf_idx = 0;
268 static int strbuf_alloc = 0;
269 static char *strbuffer = NULL;
270 static int str_startline;
271
272 static macexpstackentry_t *macexpstack[MAXMACEXPSTACK];
273 static int macexpstackidx = 0;
274
275 static bufferstackentry_t bufferstack[MAXBUFFERSTACK];
276 static int bufferstackidx = 0;
277
278 /*
279  * Global variables
280  */
281 include_state_t pp_incl_state =
282 {
283     -1,    /* state */
284     NULL,  /* ppp */
285     0,     /* ifdepth */
286     0      /* seen_junk */
287 };
288
289 includelogicentry_t *pp_includelogiclist = NULL;
290
291 %}
292
293 /*
294  **************************************************************************
295  * The scanner starts here
296  **************************************************************************
297  */
298
299 %%
300         /*
301          * Catch line-continuations.
302          * Note: Gcc keeps the line-continuations in, for example, strings
303          * intact. However, I prefer to remove them all so that the next
304          * scanner will not need to reduce the continuation state.
305          *
306          * <*>\\\n              newline(0);
307          */
308
309         /*
310          * Detect the leading # of a preprocessor directive.
311          */
312 <INITIAL,pp_ignore>^{ws}*#      pp_incl_state.seen_junk++; yy_push_state(pp_pp);
313
314         /*
315          * Scan for the preprocessor directives
316          */
317 <pp_pp>{ws}*include{ws}*        if(yy_top_state() != pp_ignore) {yy_pp_state(pp_inc); return tINCLUDE;} else {yy_pp_state(pp_eol);}
318 <pp_pp>{ws}*define{ws}*         yy_pp_state(yy_current_state() != pp_ignore ? pp_def : pp_eol);
319 <pp_pp>{ws}*error{ws}*          yy_pp_state(pp_eol);    if(yy_top_state() != pp_ignore) return tERROR;
320 <pp_pp>{ws}*warning{ws}*        yy_pp_state(pp_eol);    if(yy_top_state() != pp_ignore) return tWARNING;
321 <pp_pp>{ws}*pragma{ws}*         yy_pp_state(pp_eol);    if(yy_top_state() != pp_ignore) return tPRAGMA;
322 <pp_pp>{ws}*ident{ws}*          yy_pp_state(pp_eol);    if(yy_top_state() != pp_ignore) return tPPIDENT;
323 <pp_pp>{ws}*undef{ws}*          if(yy_top_state() != pp_ignore) {yy_pp_state(pp_ifd); return tUNDEF;} else {yy_pp_state(pp_eol);}
324 <pp_pp>{ws}*ifdef{ws}*          yy_pp_state(pp_ifd);    return tIFDEF;
325 <pp_pp>{ws}*ifndef{ws}*         pp_incl_state.seen_junk--; yy_pp_state(pp_ifd); return tIFNDEF;
326 <pp_pp>{ws}*if{ws}*             yy_pp_state(pp_if);     return tIF;
327 <pp_pp>{ws}*elif{ws}*           yy_pp_state(pp_if);     return tELIF;
328 <pp_pp>{ws}*else{ws}*           yy_pp_state(pp_endif);  return tELSE;
329 <pp_pp>{ws}*endif{ws}*          yy_pp_state(pp_endif);  return tENDIF;
330 <pp_pp>{ws}*line{ws}*           if(yy_top_state() != pp_ignore) {yy_pp_state(pp_line); return tLINE;} else {yy_pp_state(pp_eol);}
331 <pp_pp>{ws}+                    if(yy_top_state() != pp_ignore) {yy_pp_state(pp_line); return tGCCLINE;} else {yy_pp_state(pp_eol);}
332 <pp_pp>{ws}*[a-z]+              ppy_error("Invalid preprocessor token '%s'", ppy_text);
333 <pp_pp>\r?\n                    newline(1); yy_pop_state(); return tNL; /* This could be the null-token */
334 <pp_pp>\\\r?\n                  newline(0);
335 <pp_pp>\\\r?                    ppy_error("Preprocessor junk '%s'", ppy_text);
336 <pp_pp>.                        return *ppy_text;
337
338         /*
339          * Handle #include and #line
340          */
341 <pp_line>[0-9]+                 return make_number(10, &ppy_lval, ppy_text, ppy_leng);
342 <pp_inc>\<                      new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_iqs);
343 <pp_inc,pp_line>\"              new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_dqs);
344 <pp_inc,pp_line>{ws}+           ;
345 <pp_inc,pp_line>\n              newline(1); yy_pop_state(); return tNL;
346 <pp_inc,pp_line>\\\r?\n         newline(0);
347 <pp_inc,pp_line>(\\\r?)|(.)     ppy_error(yy_current_state() == pp_inc ? "Trailing junk in #include" : "Trailing junk in #line");
348
349         /*
350          * Ignore all input when a false clause is parsed
351          */
352 <pp_ignore>[^#/\\\n]+           ;
353 <pp_ignore>\n                   newline(1);
354 <pp_ignore>\\\r?\n              newline(0);
355 <pp_ignore>(\\\r?)|(.)          ;
356
357         /*
358          * Handle #if and #elif.
359          * These require conditionals to be evaluated, but we do not
360          * want to jam the scanner normally when we see these tokens.
361          * Note: tIDENT is handled below.
362          */
363
364 <pp_if>0[0-7]*{ul}?             return make_number(8, &ppy_lval, ppy_text, ppy_leng);
365 <pp_if>0[0-7]*[8-9]+{ul}?       ppy_error("Invalid octal digit");
366 <pp_if>[1-9][0-9]*{ul}?         return make_number(10, &ppy_lval, ppy_text, ppy_leng);
367 <pp_if>0[xX][0-9a-fA-F]+{ul}?   return make_number(16, &ppy_lval, ppy_text, ppy_leng);
368 <pp_if>0[xX]                    ppy_error("Invalid hex number");
369 <pp_if>defined                  yy_push_state(pp_defined); return tDEFINED;
370 <pp_if>"<<"                     return tLSHIFT;
371 <pp_if>">>"                     return tRSHIFT;
372 <pp_if>"&&"                     return tLOGAND;
373 <pp_if>"||"                     return tLOGOR;
374 <pp_if>"=="                     return tEQ;
375 <pp_if>"!="                     return tNE;
376 <pp_if>"<="                     return tLTE;
377 <pp_if>">="                     return tGTE;
378 <pp_if>\n                       newline(1); yy_pop_state(); return tNL;
379 <pp_if>\\\r?\n                  newline(0);
380 <pp_if>\\\r?                    ppy_error("Junk in conditional expression");
381 <pp_if>{ws}+                    ;
382 <pp_if>\'                       new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_sqs);
383 <pp_if>\"                       ppy_error("String constants not allowed in conditionals");
384 <pp_if>.                        return *ppy_text;
385
386         /*
387          * Handle #ifdef, #ifndef and #undef
388          * to get only an untranslated/unexpanded identifier
389          */
390 <pp_ifd>{cident}        ppy_lval.cptr = pp_xstrdup(ppy_text); return tIDENT;
391 <pp_ifd>{ws}+           ;
392 <pp_ifd>\n              newline(1); yy_pop_state(); return tNL;
393 <pp_ifd>\\\r?\n         newline(0);
394 <pp_ifd>(\\\r?)|(.)     ppy_error("Identifier expected");
395
396         /*
397          * Handle #else and #endif.
398          */
399 <pp_endif>{ws}+         ;
400 <pp_endif>\n            newline(1); yy_pop_state(); return tNL;
401 <pp_endif>\\\r?\n       newline(0);
402 <pp_endif>.             ppy_error("Garbage after #else or #endif.");
403
404         /*
405          * Handle the special 'defined' keyword.
406          * This is necessary to get the identifier prior to any
407          * substitutions.
408          */
409 <pp_defined>{cident}            yy_pop_state(); ppy_lval.cptr = pp_xstrdup(ppy_text); return tIDENT;
410 <pp_defined>{ws}+               ;
411 <pp_defined>(\()|(\))           return *ppy_text;
412 <pp_defined>\\\r?\n             newline(0);
413 <pp_defined>(\\.)|(\n)|(.)      ppy_error("Identifier expected");
414
415         /*
416          * Handle #error, #warning, #pragma and #ident.
417          * Pass everything literally to the parser, which
418          * will act appropriately.
419          * Comments are stripped from the literal text.
420          */
421 <pp_eol>[^/\\\n]+               if(yy_top_state() != pp_ignore) { ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL; }
422 <pp_eol>\/[^/\\\n*]*            if(yy_top_state() != pp_ignore) { ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL; }
423 <pp_eol>(\\\r?)|(\/[^/*])       if(yy_top_state() != pp_ignore) { ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL; }
424 <pp_eol>\n                      newline(1); yy_pop_state(); if(yy_current_state() != pp_ignore) { return tNL; }
425 <pp_eol>\\\r?\n                 newline(0);
426
427         /*
428          * Handle left side of #define
429          */
430 <pp_def>{cident}\(              ppy_lval.cptr = pp_xstrdup(ppy_text); ppy_lval.cptr[ppy_leng-1] = '\0'; yy_pp_state(pp_macro);  return tMACRO;
431 <pp_def>{cident}                ppy_lval.cptr = pp_xstrdup(ppy_text); yy_pp_state(pp_define); return tDEFINE;
432 <pp_def>{ws}+                   ;
433 <pp_def>\\\r?\n                 newline(0);
434 <pp_def>(\\\r?)|(\n)|(.)        perror("Identifier expected");
435
436         /*
437          * Scan the substitution of a define
438          */
439 <pp_define>[^'"/\\\n]+          ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL;
440 <pp_define>(\\\r?)|(\/[^/*])    ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL;
441 <pp_define>\\\r?\n{ws}+         newline(0); ppy_lval.cptr = pp_xstrdup(" "); return tLITERAL;
442 <pp_define>\\\r?\n              newline(0);
443 <pp_define>\n                   newline(1); yy_pop_state(); return tNL;
444 <pp_define>\'                   new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_sqs);
445 <pp_define>\"                   new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_dqs);
446
447         /*
448          * Scan the definition macro arguments
449          */
450 <pp_macro>\){ws}*               yy_pp_state(pp_mbody); return tMACROEND;
451 <pp_macro>{ws}+                 ;
452 <pp_macro>{cident}              ppy_lval.cptr = pp_xstrdup(ppy_text); return tIDENT;
453 <pp_macro>,                     return ',';
454 <pp_macro>"..."                 return tELIPSIS;
455 <pp_macro>(\\\r?)|(\n)|(.)|(\.\.?)      ppy_error("Argument identifier expected");
456 <pp_macro>\\\r?\n               newline(0);
457
458         /*
459          * Scan the substitution of a macro
460          */
461 <pp_mbody>[^a-zA-Z0-9'"#/\\\n]+ ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL;
462 <pp_mbody>{cident}              ppy_lval.cptr = pp_xstrdup(ppy_text); return tIDENT;
463 <pp_mbody>\#\#                  return tCONCAT;
464 <pp_mbody>\#                    return tSTRINGIZE;
465 <pp_mbody>[0-9][^'"#/\\\n]*     ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL;
466 <pp_mbody>(\\\r?)|(\/[^/*'"#\\\n]*)     ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL;
467 <pp_mbody>\\\r?\n{ws}+          newline(0); ppy_lval.cptr = pp_xstrdup(" "); return tLITERAL;
468 <pp_mbody>\\\r?\n               newline(0);
469 <pp_mbody>\n                    newline(1); yy_pop_state(); return tNL;
470 <pp_mbody>\'                    new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_sqs);
471 <pp_mbody>\"                    new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_dqs);
472
473         /*
474          * Macro expansion text scanning.
475          * This state is active just after the identifier is scanned
476          * that triggers an expansion. We *must* delete the leading
477          * whitespace before we can start scanning for arguments.
478          *
479          * If we do not see a '(' as next trailing token, then we have
480          * a false alarm. We just continue with a nose-bleed...
481          */
482 <pp_macign>{ws}*/\(     yy_pp_state(pp_macscan);
483 <pp_macign>{ws}*\n      {
484                 if(yy_top_state() != pp_macscan)
485                         newline(0);
486         }
487 <pp_macign>{ws}*\\\r?\n newline(0);
488 <pp_macign>{ws}+|{ws}*\\\r?|.   {
489                 macexpstackentry_t *mac = pop_macro();
490                 yy_pop_state();
491                 put_buffer(mac->ppp->ident, strlen(mac->ppp->ident));
492                 put_buffer(ppy_text, ppy_leng);
493                 free_macro(mac);
494         }
495
496         /*
497          * Macro expansion argument text scanning.
498          * This state is active when a macro's arguments are being read for expansion.
499          */
500 <pp_macscan>\(  {
501                 if(++MACROPARENTHESES() > 1)
502                         add_text_to_macro(ppy_text, ppy_leng);
503         }
504 <pp_macscan>\)  {
505                 if(--MACROPARENTHESES() == 0)
506                 {
507                         yy_pop_state();
508                         macro_add_arg(1);
509                 }
510                 else
511                         add_text_to_macro(ppy_text, ppy_leng);
512         }
513 <pp_macscan>,           {
514                 if(MACROPARENTHESES() > 1)
515                         add_text_to_macro(ppy_text, ppy_leng);
516                 else
517                         macro_add_arg(0);
518         }
519 <pp_macscan>\"          new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_dqs);
520 <pp_macscan>\'          new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_sqs);
521 <pp_macscan>"/*"        yy_push_state(pp_comment); add_text_to_macro(" ", 1);
522 <pp_macscan>\n          pp_status.line_number++; pp_status.char_number = 1; add_text_to_macro(ppy_text, ppy_leng);
523 <pp_macscan>([^/(),\\\n"']+)|(\/[^/*(),\\\n'"]*)|(\\\r?)|(.)    add_text_to_macro(ppy_text, ppy_leng);
524 <pp_macscan>\\\r?\n     newline(0);
525
526         /*
527          * Comment handling (almost all start-conditions)
528          */
529 <INITIAL,pp_pp,pp_ignore,pp_eol,pp_inc,pp_if,pp_ifd,pp_endif,pp_defined,pp_def,pp_define,pp_macro,pp_mbody,RCINCL>"/*" yy_push_state(pp_comment);
530 <pp_comment>[^*\n]*|"*"+[^*/\n]*        ;
531 <pp_comment>\n                          newline(0);
532 <pp_comment>"*"+"/"                     yy_pop_state();
533
534         /*
535          * Remove C++ style comment (almost all start-conditions)
536          */
537 <INITIAL,pp_pp,pp_ignore,pp_eol,pp_inc,pp_if,pp_ifd,pp_endif,pp_defined,pp_def,pp_define,pp_macro,pp_mbody,pp_macscan,RCINCL>"//"[^\n]* {
538                 if(ppy_text[ppy_leng-1] == '\\')
539                         ppy_warning("C++ style comment ends with an escaped newline (escape ignored)");
540         }
541
542         /*
543          * Single, double and <> quoted constants
544          */
545 <INITIAL,pp_macexp>\"           pp_incl_state.seen_junk++; new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_dqs);
546 <INITIAL,pp_macexp>\'           pp_incl_state.seen_junk++; new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_sqs);
547 <pp_dqs>[^"\\\n]+               add_string(ppy_text, ppy_leng);
548 <pp_dqs>\"                      {
549                 add_string(ppy_text, ppy_leng);
550                 yy_pop_state();
551                 switch(yy_current_state())
552                 {
553                 case pp_pp:
554                 case pp_define:
555                 case pp_mbody:
556                 case pp_inc:
557                 case RCINCL:
558                         if (yy_current_state()==RCINCL) yy_pop_state();
559                         ppy_lval.cptr = get_string();
560                         return tDQSTRING;
561                 case pp_line:
562                         ppy_lval.cptr = get_string();
563                         return tDQSTRING;
564                 default:
565                         put_string();
566                 }
567         }
568 <pp_sqs>[^'\\\n]+               add_string(ppy_text, ppy_leng);
569 <pp_sqs>\'                      {
570                 add_string(ppy_text, ppy_leng);
571                 yy_pop_state();
572                 switch(yy_current_state())
573                 {
574                 case pp_if:
575                 case pp_define:
576                 case pp_mbody:
577                         ppy_lval.cptr = get_string();
578                         return tSQSTRING;
579                 default:
580                         put_string();
581                 }
582         }
583 <pp_iqs>[^\>\\\n]+              add_string(ppy_text, ppy_leng);
584 <pp_iqs>\>                      {
585                 add_string(ppy_text, ppy_leng);
586                 yy_pop_state();
587                 ppy_lval.cptr = get_string();
588                 return tIQSTRING;
589         }
590 <pp_dqs>\\\r?\n         {
591                 /*
592                  * This is tricky; we need to remove the line-continuation
593                  * from preprocessor strings, but OTOH retain them in all
594                  * other strings. This is because the resource grammar is
595                  * even more braindead than initially analysed and line-
596                  * continuations in strings introduce, sigh, newlines in
597                  * the output. There goes the concept of non-breaking, non-
598                  * spacing whitespace.
599                  */
600                 switch(yy_top_state())
601                 {
602                 case pp_pp:
603                 case pp_define:
604                 case pp_mbody:
605                 case pp_inc:
606                 case pp_line:
607                         newline(0);
608                         break;
609                 default:
610                         add_string(ppy_text, ppy_leng);
611                         newline(-1);
612                 }
613         }
614 <pp_iqs,pp_dqs,pp_sqs>\\.       add_string(ppy_text, ppy_leng);
615 <pp_iqs,pp_dqs,pp_sqs>\n        {
616                 newline(1);
617                 add_string(ppy_text, ppy_leng);
618                 ppy_warning("Newline in string constant encounterd (started line %d)", string_start());
619         }
620
621         /*
622          * Identifier scanning
623          */
624 <INITIAL,pp_if,pp_inc,pp_macexp>{cident}        {
625                 pp_entry_t *ppp;
626                 pp_incl_state.seen_junk++;
627                 if(!(ppp = pplookup(ppy_text)))
628                 {
629                         if(yy_current_state() == pp_inc)
630                                 ppy_error("Expected include filename");
631
632                         if(yy_current_state() == pp_if)
633                         {
634                                 ppy_lval.cptr = pp_xstrdup(ppy_text);
635                                 return tIDENT;
636                         }
637                         else {
638                                 if((yy_current_state()==INITIAL) && (strcasecmp(ppy_text,"RCINCLUDE")==0)){
639                                         yy_push_state(RCINCL);
640                                         return tRCINCLUDE;
641                                 }
642                                 else put_buffer(ppy_text, ppy_leng);
643                         }
644                 }
645                 else if(!ppp->expanding)
646                 {
647                         switch(ppp->type)
648                         {
649                         case def_special:
650                                 expand_special(ppp);
651                                 break;
652                         case def_define:
653                                 expand_define(ppp);
654                                 break;
655                         case def_macro:
656                                 yy_push_state(pp_macign);
657                                 push_macro(ppp);
658                                 break;
659                         default:
660                                 pp_internal_error(__FILE__, __LINE__, "Invalid define type %d\n", ppp->type);
661                         }
662                 }
663                 else put_buffer(ppy_text, ppy_leng);
664         }
665
666         /*
667          * Everything else that needs to be passed and
668          * newline and continuation handling
669          */
670 <INITIAL,pp_macexp>[^a-zA-Z_#'"/\\\n \r\t\f\v]+|(\/|\\)[^a-zA-Z_/*'"\\\n \r\t\v\f]*     pp_incl_state.seen_junk++; put_buffer(ppy_text, ppy_leng);
671 <INITIAL,pp_macexp>{ws}+        put_buffer(ppy_text, ppy_leng);
672 <INITIAL>\n                     newline(1);
673 <INITIAL>\\\r?\n                newline(0);
674 <INITIAL>\\\r?                  pp_incl_state.seen_junk++; put_buffer(ppy_text, ppy_leng);
675
676         /*
677          * Special catcher for macro argmument expansion to prevent
678          * newlines to propagate to the output or admin.
679          */
680 <pp_macexp>(\n)|(.)|(\\\r?(\n|.))       put_buffer(ppy_text, ppy_leng);
681
682 <RCINCL>[A-Za-z0-9_\.\\/]+ {
683                 ppy_lval.cptr=pp_xstrdup(ppy_text);
684                 yy_pop_state();
685                 return tRCINCLUDEPATH;
686         }
687
688 <RCINCL>{ws}+ ;
689
690 <RCINCL>\"              {
691                 new_string(); add_string(ppy_text,ppy_leng);yy_push_state(pp_dqs);
692         }
693
694         /*
695          * This is a 'catch-all' rule to discover errors in the scanner
696          * in an orderly manner.
697          */
698 <*>.            pp_incl_state.seen_junk++; ppy_warning("Unmatched text '%c' (0x%02x); please report\n", isprint(*ppy_text & 0xff) ? *ppy_text : ' ', *ppy_text);
699
700 <<EOF>> {
701                 YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
702                 bufferstackentry_t *bep = pop_buffer();
703
704                 if((!bep && pp_get_if_depth()) || (bep && pp_get_if_depth() != bep->if_depth))
705                         ppy_warning("Unmatched #if/#endif at end of file");
706
707                 if(!bep)
708                 {
709                         if(YY_START != INITIAL)
710                                 ppy_error("Unexpected end of file during preprocessing");
711                         yyterminate();
712                 }
713                 else if(bep->should_pop == 2)
714                 {
715                         macexpstackentry_t *mac;
716                         mac = pop_macro();
717                         expand_macro(mac);
718                 }
719                 ppy__delete_buffer(b);
720         }
721
722 %%
723 /*
724  **************************************************************************
725  * Support functions
726  **************************************************************************
727  */
728
729 #ifndef ppy_wrap
730 int ppy_wrap(void)
731 {
732         return 1;
733 }
734 #endif
735
736
737 /*
738  *-------------------------------------------------------------------------
739  * Output newlines or set them as continuations
740  *
741  * Input: -1 - Don't count this one, but update local position (see pp_dqs)
742  *         0 - Line-continuation seen and cache output
743  *         1 - Newline seen and flush output
744  *-------------------------------------------------------------------------
745  */
746 static void newline(int dowrite)
747 {
748         pp_status.line_number++;
749         pp_status.char_number = 1;
750
751         if(dowrite == -1)
752                 return;
753
754         ncontinuations++;
755         if(dowrite)
756         {
757                 for(;ncontinuations; ncontinuations--)
758                         put_buffer("\n", 1);
759         }
760 }
761
762
763 /*
764  *-------------------------------------------------------------------------
765  * Make a number out of an any-base and suffixed string
766  *
767  * Possible number extensions:
768  * - ""         int
769  * - "L"        long int
770  * - "LL"       long long int
771  * - "U"        unsigned int
772  * - "UL"       unsigned long int
773  * - "ULL"      unsigned long long int
774  * - "LU"       unsigned long int
775  * - "LLU"      unsigned long long int
776  * - "LUL"      invalid
777  *
778  * FIXME:
779  * The sizes of resulting 'int' and 'long' are compiler specific.
780  * I depend on sizeof(int) > 2 here (although a relatively safe
781  * assumption).
782  * Long longs are not yet implemented because this is very compiler
783  * specific and I don't want to think too much about the problems.
784  *
785  *-------------------------------------------------------------------------
786  */
787 static int make_number(int radix, YYSTYPE *val, const char *str, int len)
788 {
789         int is_l  = 0;
790         int is_ll = 0;
791         int is_u  = 0;
792         char ext[4];
793
794         ext[3] = '\0';
795         ext[2] = toupper(str[len-1]);
796         ext[1] = len > 1 ? toupper(str[len-2]) : ' ';
797         ext[0] = len > 2 ? toupper(str[len-3]) : ' ';
798
799         if(!strcmp(ext, "LUL"))
800                 ppy_error("Invalid constant suffix");
801         else if(!strcmp(ext, "LLU") || !strcmp(ext, "ULL"))
802         {
803                 is_ll++;
804                 is_u++;
805         }
806         else if(!strcmp(ext+1, "LU") || !strcmp(ext+1, "UL"))
807         {
808                 is_l++;
809                 is_u++;
810         }
811         else if(!strcmp(ext+1, "LL"))
812         {
813                 is_ll++;
814         }
815         else if(!strcmp(ext+2, "L"))
816         {
817                 is_l++;
818         }
819         else if(!strcmp(ext+2, "U"))
820         {
821                 is_u++;
822         }
823
824         if(is_ll)
825         {
826 /* Assume as in the declaration of wrc_ull_t and wrc_sll_t */
827 #ifdef HAVE_LONG_LONG
828                 if (is_u)
829                 {
830                         val->ull = strtoull(str, NULL, radix);
831                         return tULONGLONG;
832                 }
833                 else
834                 {
835                         val->sll = strtoll(str, NULL, radix);
836                         return tSLONGLONG;
837                 }
838 #else
839                 pp_internal_error(__FILE__, __LINE__, "long long constants not supported on this platform");
840 #endif
841         }
842         else if(is_u && is_l)
843         {
844                 val->ulong = strtoul(str, NULL, radix);
845                 return tULONG;
846         }
847         else if(!is_u && is_l)
848         {
849                 val->slong = strtol(str, NULL, radix);
850                 return tSLONG;
851         }
852         else if(is_u && !is_l)
853         {
854                 val->uint = (unsigned int)strtoul(str, NULL, radix);
855                 return tUINT;
856         }
857
858         /* Else it must be an int... */
859         val->sint = (int)strtol(str, NULL, radix);
860         return tSINT;
861 }
862
863
864 /*
865  *-------------------------------------------------------------------------
866  * Macro and define expansion support
867  *
868  * FIXME: Variable macro arguments.
869  *-------------------------------------------------------------------------
870  */
871 static void expand_special(pp_entry_t *ppp)
872 {
873         const char *dbgtext = "?";
874         static char *buf = NULL;
875
876         assert(ppp->type == def_special);
877
878         if(!strcmp(ppp->ident, "__LINE__"))
879         {
880                 dbgtext = "def_special(__LINE__)";
881                 buf = pp_xrealloc(buf, 32);
882                 sprintf(buf, "%d", pp_status.line_number);
883         }
884         else if(!strcmp(ppp->ident, "__FILE__"))
885         {
886                 dbgtext = "def_special(__FILE__)";
887                 buf = pp_xrealloc(buf, strlen(pp_status.input) + 3);
888                 sprintf(buf, "\"%s\"", pp_status.input);
889         }
890         else
891                 pp_internal_error(__FILE__, __LINE__, "Special macro '%s' not found...\n", ppp->ident);
892
893         if(pp_flex_debug)
894                 fprintf(stderr, "expand_special(%d): %s:%d: '%s' -> '%s'\n",
895                         macexpstackidx,
896                         pp_status.input,
897                         pp_status.line_number,
898                         ppp->ident,
899                         buf ? buf : "");
900
901         if(buf && buf[0])
902         {
903                 push_buffer(ppp, NULL, NULL, 0);
904                 yy_scan_string(buf);
905         }
906 }
907
908 static void expand_define(pp_entry_t *ppp)
909 {
910         assert(ppp->type == def_define);
911
912         if(pp_flex_debug)
913                 fprintf(stderr, "expand_define(%d): %s:%d: '%s' -> '%s'\n",
914                         macexpstackidx,
915                         pp_status.input,
916                         pp_status.line_number,
917                         ppp->ident,
918                         ppp->subst.text);
919         if(ppp->subst.text && ppp->subst.text[0])
920         {
921                 push_buffer(ppp, NULL, NULL, 0);
922                 yy_scan_string(ppp->subst.text);
923         }
924 }
925
926 static int curdef_idx = 0;
927 static int curdef_alloc = 0;
928 static char *curdef_text = NULL;
929
930 static void add_text(const char *str, int len)
931 {
932         if(len == 0)
933                 return;
934         if(curdef_idx >= curdef_alloc || curdef_alloc - curdef_idx < len)
935         {
936                 curdef_alloc += (len + ALLOCBLOCKSIZE-1) & ~(ALLOCBLOCKSIZE-1);
937                 curdef_text = pp_xrealloc(curdef_text, curdef_alloc * sizeof(curdef_text[0]));
938                 if(curdef_alloc > 65536)
939                         ppy_warning("Reallocating macro-expansion buffer larger than 64kB");
940         }
941         memcpy(&curdef_text[curdef_idx], str, len);
942         curdef_idx += len;
943 }
944
945 static mtext_t *add_expand_text(mtext_t *mtp, macexpstackentry_t *mep, int *nnl)
946 {
947         char *cptr;
948         char *exp;
949         int tag;
950         int n;
951
952         if(mtp == NULL)
953                 return NULL;
954
955         switch(mtp->type)
956         {
957         case exp_text:
958                 if(pp_flex_debug)
959                         fprintf(stderr, "add_expand_text: exp_text: '%s'\n", mtp->subst.text);
960                 add_text(mtp->subst.text, strlen(mtp->subst.text));
961                 break;
962
963         case exp_stringize:
964                 if(pp_flex_debug)
965                         fprintf(stderr, "add_expand_text: exp_stringize(%d): '%s'\n",
966                                 mtp->subst.argidx,
967                                 mep->args[mtp->subst.argidx]);
968                 cptr = mep->args[mtp->subst.argidx];
969                 add_text("\"", 1);
970                 while(*cptr)
971                 {
972                         if(*cptr == '"' || *cptr == '\\')
973                                 add_text("\\", 1);
974                         add_text(cptr, 1);
975                         cptr++;
976                 }
977                 add_text("\"", 1);
978                 break;
979
980         case exp_concat:
981                 if(pp_flex_debug)
982                         fprintf(stderr, "add_expand_text: exp_concat\n");
983                 /* Remove trailing whitespace from current expansion text */
984                 while(curdef_idx)
985                 {
986                         if(isspace(curdef_text[curdef_idx-1] & 0xff))
987                                 curdef_idx--;
988                         else
989                                 break;
990                 }
991                 /* tag current position and recursively expand the next part */
992                 tag = curdef_idx;
993                 mtp = add_expand_text(mtp->next, mep, nnl);
994
995                 /* Now get rid of the leading space of the expansion */
996                 cptr = &curdef_text[tag];
997                 n = curdef_idx - tag;
998                 while(n)
999                 {
1000                         if(isspace(*cptr & 0xff))
1001                         {
1002                                 cptr++;
1003                                 n--;
1004                         }
1005                         else
1006                                 break;
1007                 }
1008                 if(cptr != &curdef_text[tag])
1009                 {
1010                         memmove(&curdef_text[tag], cptr, n);
1011                         curdef_idx -= (curdef_idx - tag) - n;
1012                 }
1013                 break;
1014
1015         case exp_subst:
1016                 if((mtp->next && mtp->next->type == exp_concat) || (mtp->prev && mtp->prev->type == exp_concat))
1017                         exp = mep->args[mtp->subst.argidx];
1018                 else
1019                         exp = mep->ppargs[mtp->subst.argidx];
1020                 if(exp)
1021                 {
1022                         add_text(exp, strlen(exp));
1023                         *nnl -= mep->nnls[mtp->subst.argidx];
1024                         cptr = strchr(exp, '\n');
1025                         while(cptr)
1026                         {
1027                                 *cptr = ' ';
1028                                 cptr = strchr(cptr+1, '\n');
1029                         }
1030                         mep->nnls[mtp->subst.argidx] = 0;
1031                 }
1032                 if(pp_flex_debug)
1033                         fprintf(stderr, "add_expand_text: exp_subst(%d): '%s'\n", mtp->subst.argidx, exp);
1034                 break;
1035
1036         default:
1037                 pp_internal_error(__FILE__, __LINE__, "Invalid expansion type (%d) in macro expansion\n", mtp->type);
1038         }
1039         return mtp;
1040 }
1041
1042 static void expand_macro(macexpstackentry_t *mep)
1043 {
1044         mtext_t *mtp;
1045         int n, k;
1046         char *cptr;
1047         int nnl = 0;
1048         pp_entry_t *ppp = mep->ppp;
1049         int nargs = mep->nargs;
1050
1051         assert(ppp->type == def_macro);
1052         assert(ppp->expanding == 0);
1053
1054         if((ppp->nargs >= 0 && nargs != ppp->nargs) || (ppp->nargs < 0 && nargs < -ppp->nargs))
1055                 ppy_error("Too %s macro arguments (%d)", nargs < abs(ppp->nargs) ? "few" : "many", nargs);
1056
1057         for(n = 0; n < nargs; n++)
1058                 nnl += mep->nnls[n];
1059
1060         if(pp_flex_debug)
1061                 fprintf(stderr, "expand_macro(%d): %s:%d: '%s'(%d,%d) -> ...\n",
1062                         macexpstackidx,
1063                         pp_status.input,
1064                         pp_status.line_number,
1065                         ppp->ident,
1066                         mep->nargs,
1067                         nnl);
1068
1069         curdef_idx = 0;
1070
1071         for(mtp = ppp->subst.mtext; mtp; mtp = mtp->next)
1072         {
1073                 if(!(mtp = add_expand_text(mtp, mep, &nnl)))
1074                         break;
1075         }
1076
1077         for(n = 0; n < nnl; n++)
1078                 add_text("\n", 1);
1079
1080         /* To make sure there is room and termination (see below) */
1081         add_text(" \0", 2);
1082
1083         /* Strip trailing whitespace from expansion */
1084         for(k = curdef_idx, cptr = &curdef_text[curdef_idx-1]; k > 0; k--, cptr--)
1085         {
1086                 if(!isspace(*cptr & 0xff))
1087                         break;
1088         }
1089
1090         /*
1091          * We must add *one* whitespace to make sure that there
1092          * is a token-separation after the expansion.
1093          */
1094         *(++cptr) = ' ';
1095         *(++cptr) = '\0';
1096         k++;
1097
1098         /* Strip leading whitespace from expansion */
1099         for(n = 0, cptr = curdef_text; n < k; n++, cptr++)
1100         {
1101                 if(!isspace(*cptr & 0xff))
1102                         break;
1103         }
1104
1105         if(k - n > 0)
1106         {
1107                 if(pp_flex_debug)
1108                         fprintf(stderr, "expand_text: '%s'\n", curdef_text + n);
1109                 push_buffer(ppp, NULL, NULL, 0);
1110                 /*yy_scan_bytes(curdef_text + n, k - n);*/
1111                 yy_scan_string(curdef_text + n);
1112         }
1113 }
1114
1115 /*
1116  *-------------------------------------------------------------------------
1117  * String collection routines
1118  *-------------------------------------------------------------------------
1119  */
1120 static void new_string(void)
1121 {
1122 #ifdef DEBUG
1123         if(strbuf_idx)
1124                 ppy_warning("new_string: strbuf_idx != 0");
1125 #endif
1126         strbuf_idx = 0;
1127         str_startline = pp_status.line_number;
1128 }
1129
1130 static void add_string(const char *str, int len)
1131 {
1132         if(len == 0)
1133                 return;
1134         if(strbuf_idx >= strbuf_alloc || strbuf_alloc - strbuf_idx < len)
1135         {
1136                 strbuf_alloc += (len + ALLOCBLOCKSIZE-1) & ~(ALLOCBLOCKSIZE-1);
1137                 strbuffer = pp_xrealloc(strbuffer, strbuf_alloc * sizeof(strbuffer[0]));
1138                 if(strbuf_alloc > 65536)
1139                         ppy_warning("Reallocating string buffer larger than 64kB");
1140         }
1141         memcpy(&strbuffer[strbuf_idx], str, len);
1142         strbuf_idx += len;
1143 }
1144
1145 static char *get_string(void)
1146 {
1147         char *str = pp_xmalloc(strbuf_idx + 1);
1148         memcpy(str, strbuffer, strbuf_idx);
1149         str[strbuf_idx] = '\0';
1150 #ifdef DEBUG
1151         strbuf_idx = 0;
1152 #endif
1153         return str;
1154 }
1155
1156 static void put_string(void)
1157 {
1158         put_buffer(strbuffer, strbuf_idx);
1159 #ifdef DEBUG
1160         strbuf_idx = 0;
1161 #endif
1162 }
1163
1164 static int string_start(void)
1165 {
1166         return str_startline;
1167 }
1168
1169
1170 /*
1171  *-------------------------------------------------------------------------
1172  * Buffer management
1173  *-------------------------------------------------------------------------
1174  */
1175 static void push_buffer(pp_entry_t *ppp, char *filename, char *incname, int pop)
1176 {
1177         if(ppy_debug)
1178                 printf("push_buffer(%d): %p %p %p %d\n", bufferstackidx, ppp, filename, incname, pop);
1179         if(bufferstackidx >= MAXBUFFERSTACK)
1180                 pp_internal_error(__FILE__, __LINE__, "Buffer stack overflow");
1181
1182         memset(&bufferstack[bufferstackidx], 0, sizeof(bufferstack[0]));
1183         bufferstack[bufferstackidx].bufferstate = YY_CURRENT_BUFFER;
1184         bufferstack[bufferstackidx].define      = ppp;
1185         bufferstack[bufferstackidx].line_number = pp_status.line_number;
1186         bufferstack[bufferstackidx].char_number = pp_status.char_number;
1187         bufferstack[bufferstackidx].if_depth    = pp_get_if_depth();
1188         bufferstack[bufferstackidx].should_pop  = pop;
1189         bufferstack[bufferstackidx].filename    = pp_status.input;
1190         bufferstack[bufferstackidx].ncontinuations      = ncontinuations;
1191         bufferstack[bufferstackidx].incl                = pp_incl_state;
1192         bufferstack[bufferstackidx].include_filename    = incname;
1193
1194         if(ppp)
1195                 ppp->expanding = 1;
1196         else if(filename)
1197         {
1198                 /* These will track the ppy_error to the correct file and line */
1199                 pp_status.line_number = 1;
1200                 pp_status.char_number = 1;
1201                 pp_status.input  = filename;
1202                 ncontinuations = 0;
1203         }
1204         else if(!pop)
1205                 pp_internal_error(__FILE__, __LINE__, "Pushing buffer without knowing where to go to");
1206         bufferstackidx++;
1207 }
1208
1209 static bufferstackentry_t *pop_buffer(void)
1210 {
1211         if(bufferstackidx < 0)
1212                 pp_internal_error(__FILE__, __LINE__, "Bufferstack underflow?");
1213
1214         if(bufferstackidx == 0)
1215                 return NULL;
1216
1217         bufferstackidx--;
1218
1219         if(bufferstack[bufferstackidx].define)
1220                 bufferstack[bufferstackidx].define->expanding = 0;
1221         else
1222         {
1223                 pp_status.line_number = bufferstack[bufferstackidx].line_number;
1224                 pp_status.char_number = bufferstack[bufferstackidx].char_number;
1225                 pp_status.input  = bufferstack[bufferstackidx].filename;
1226                 ncontinuations = bufferstack[bufferstackidx].ncontinuations;
1227                 if(!bufferstack[bufferstackidx].should_pop)
1228                 {
1229                         fclose(ppy_in);
1230                         fprintf(ppy_out, "# %d \"%s\" 2\n", pp_status.line_number, pp_status.input);
1231
1232                         /* We have EOF, check the include logic */
1233                         if(pp_incl_state.state == 2 && !pp_incl_state.seen_junk && pp_incl_state.ppp)
1234                         {
1235                                 pp_entry_t *ppp = pplookup(pp_incl_state.ppp);
1236                                 if(ppp)
1237                                 {
1238                                         includelogicentry_t *iep = pp_xmalloc(sizeof(includelogicentry_t));
1239                                         iep->ppp = ppp;
1240                                         ppp->iep = iep;
1241                                         iep->filename = bufferstack[bufferstackidx].include_filename;
1242                                         iep->prev = NULL;
1243                                         iep->next = pp_includelogiclist;
1244                                         if(iep->next)
1245                                                 iep->next->prev = iep;
1246                                         pp_includelogiclist = iep;
1247                                         if(pp_status.debug)
1248                                                 fprintf(stderr, "pop_buffer: %s:%d: includelogic added, include_ppp='%s', file='%s'\n", pp_status.input, pp_status.line_number, pp_incl_state.ppp, iep->filename);
1249                                 }
1250                                 else
1251                                         free(bufferstack[bufferstackidx].include_filename);
1252                         }
1253                         free(pp_incl_state.ppp);
1254                         pp_incl_state   = bufferstack[bufferstackidx].incl;
1255
1256                 }
1257         }
1258
1259         if(ppy_debug)
1260                 printf("pop_buffer(%d): %p %p (%d, %d, %d) %p %d\n",
1261                         bufferstackidx,
1262                         bufferstack[bufferstackidx].bufferstate,
1263                         bufferstack[bufferstackidx].define,
1264                         bufferstack[bufferstackidx].line_number,
1265                         bufferstack[bufferstackidx].char_number,
1266                         bufferstack[bufferstackidx].if_depth,
1267                         bufferstack[bufferstackidx].filename,
1268                         bufferstack[bufferstackidx].should_pop);
1269
1270         ppy__switch_to_buffer(bufferstack[bufferstackidx].bufferstate);
1271
1272         if(bufferstack[bufferstackidx].should_pop)
1273         {
1274                 if(yy_current_state() == pp_macexp)
1275                         macro_add_expansion();
1276                 else
1277                         pp_internal_error(__FILE__, __LINE__, "Pop buffer and state without macro expansion state");
1278                 yy_pop_state();
1279         }
1280
1281         return &bufferstack[bufferstackidx];
1282 }
1283
1284
1285 /*
1286  *-------------------------------------------------------------------------
1287  * Macro nestng support
1288  *-------------------------------------------------------------------------
1289  */
1290 static void push_macro(pp_entry_t *ppp)
1291 {
1292         if(macexpstackidx >= MAXMACEXPSTACK)
1293                 ppy_error("Too many nested macros");
1294
1295         macexpstack[macexpstackidx] = pp_xmalloc(sizeof(macexpstack[0][0]));
1296         memset( macexpstack[macexpstackidx], 0, sizeof(macexpstack[0][0]));
1297         macexpstack[macexpstackidx]->ppp = ppp;
1298         macexpstackidx++;
1299 }
1300
1301 static macexpstackentry_t *top_macro(void)
1302 {
1303         return macexpstackidx > 0 ? macexpstack[macexpstackidx-1] : NULL;
1304 }
1305
1306 static macexpstackentry_t *pop_macro(void)
1307 {
1308         if(macexpstackidx <= 0)
1309                 pp_internal_error(__FILE__, __LINE__, "Macro expansion stack underflow\n");
1310         return macexpstack[--macexpstackidx];
1311 }
1312
1313 static void free_macro(macexpstackentry_t *mep)
1314 {
1315         int i;
1316
1317         for(i = 0; i < mep->nargs; i++)
1318                 free(mep->args[i]);
1319         free(mep->args);
1320         free(mep->nnls);
1321         free(mep->curarg);
1322         free(mep);
1323 }
1324
1325 static void add_text_to_macro(const char *text, int len)
1326 {
1327         macexpstackentry_t *mep = top_macro();
1328
1329         assert(mep->ppp->expanding == 0);
1330
1331         if(mep->curargalloc - mep->curargsize <= len+1) /* +1 for '\0' */
1332         {
1333                 mep->curargalloc += (ALLOCBLOCKSIZE > len+1) ? ALLOCBLOCKSIZE : len+1;
1334                 mep->curarg = pp_xrealloc(mep->curarg, mep->curargalloc * sizeof(mep->curarg[0]));
1335         }
1336         memcpy(mep->curarg + mep->curargsize, text, len);
1337         mep->curargsize += len;
1338         mep->curarg[mep->curargsize] = '\0';
1339 }
1340
1341 static void macro_add_arg(int last)
1342 {
1343         int nnl = 0;
1344         char *cptr;
1345         macexpstackentry_t *mep = top_macro();
1346
1347         assert(mep->ppp->expanding == 0);
1348
1349         mep->args = pp_xrealloc(mep->args, (mep->nargs+1) * sizeof(mep->args[0]));
1350         mep->ppargs = pp_xrealloc(mep->ppargs, (mep->nargs+1) * sizeof(mep->ppargs[0]));
1351         mep->nnls = pp_xrealloc(mep->nnls, (mep->nargs+1) * sizeof(mep->nnls[0]));
1352         mep->args[mep->nargs] = pp_xstrdup(mep->curarg ? mep->curarg : "");
1353         cptr = mep->args[mep->nargs]-1;
1354         while((cptr = strchr(cptr+1, '\n')))
1355         {
1356                 nnl++;
1357         }
1358         mep->nnls[mep->nargs] = nnl;
1359         mep->nargs++;
1360         free(mep->curarg);
1361         mep->curargalloc = mep->curargsize = 0;
1362         mep->curarg = NULL;
1363
1364         if(pp_flex_debug)
1365                 fprintf(stderr, "macro_add_arg: %s:%d: %d -> '%s'\n",
1366                         pp_status.input,
1367                         pp_status.line_number,
1368                         mep->nargs-1,
1369                         mep->args[mep->nargs-1]);
1370
1371         /* Each macro argument must be expanded to cope with stingize */
1372         if(last || mep->args[mep->nargs-1][0])
1373         {
1374                 yy_push_state(pp_macexp);
1375                 push_buffer(NULL, NULL, NULL, last ? 2 : 1);
1376                 yy_scan_string(mep->args[mep->nargs-1]);
1377                 /*mep->bufferstackidx = bufferstackidx;  But not nested! */
1378         }
1379 }
1380
1381 static void macro_add_expansion(void)
1382 {
1383         macexpstackentry_t *mep = top_macro();
1384
1385         assert(mep->ppp->expanding == 0);
1386
1387         mep->ppargs[mep->nargs-1] = pp_xstrdup(mep->curarg ? mep->curarg : "");
1388         free(mep->curarg);
1389         mep->curargalloc = mep->curargsize = 0;
1390         mep->curarg = NULL;
1391
1392         if(pp_flex_debug)
1393                 fprintf(stderr, "macro_add_expansion: %s:%d: %d -> '%s'\n",
1394                         pp_status.input,
1395                         pp_status.line_number,
1396                         mep->nargs-1,
1397                         mep->ppargs[mep->nargs-1]);
1398 }
1399
1400
1401 /*
1402  *-------------------------------------------------------------------------
1403  * Output management
1404  *-------------------------------------------------------------------------
1405  */
1406 static void put_buffer(const char *s, int len)
1407 {
1408         if(top_macro())
1409                 add_text_to_macro(s, len);
1410         else
1411            fwrite(s, 1, len, ppy_out);
1412 }
1413
1414
1415 /*
1416  *-------------------------------------------------------------------------
1417  * Include management
1418  *-------------------------------------------------------------------------
1419  */
1420 void pp_do_include(char *fname, int type)
1421 {
1422         char *newpath;
1423         int n;
1424         includelogicentry_t *iep;
1425
1426         for(iep = pp_includelogiclist; iep; iep = iep->next)
1427         {
1428                 if(!strcmp(iep->filename, fname))
1429                 {
1430                         /*
1431                          * We are done. The file was included before.
1432                          * If the define was deleted, then this entry would have
1433                          * been deleted too.
1434                          */
1435                         return;
1436                 }
1437         }
1438
1439         n = strlen(fname);
1440
1441         if(n <= 2)
1442                 ppy_error("Empty include filename");
1443
1444         /* Undo the effect of the quotation */
1445         fname[n-1] = '\0';
1446
1447         if((ppy_in = pp_open_include(fname+1, type ? pp_status.input : NULL, &newpath)) == NULL)
1448                 ppy_error("Unable to open include file %s", fname+1);
1449
1450         fname[n-1] = *fname;    /* Redo the quotes */
1451         push_buffer(NULL, newpath, fname, 0);
1452         pp_incl_state.seen_junk = 0;
1453         pp_incl_state.state = 0;
1454         pp_incl_state.ppp = NULL;
1455
1456         if(pp_status.debug)
1457                 fprintf(stderr, "pp_do_include: %s:%d: include_state=%d, include_ppp='%s', include_ifdepth=%d\n",
1458                         pp_status.input, pp_status.line_number, pp_incl_state.state, pp_incl_state.ppp, pp_incl_state.ifdepth);
1459         ppy__switch_to_buffer(ppy__create_buffer(ppy_in, YY_BUF_SIZE));
1460
1461         fprintf(ppy_out, "# 1 \"%s\" 1%s\n", newpath, type ? "" : " 3");
1462 }
1463
1464 /*
1465  *-------------------------------------------------------------------------
1466  * Push/pop preprocessor ignore state when processing conditionals
1467  * which are false.
1468  *-------------------------------------------------------------------------
1469  */
1470 void pp_push_ignore_state(void)
1471 {
1472         yy_push_state(pp_ignore);
1473 }
1474
1475 void pp_pop_ignore_state(void)
1476 {
1477         yy_pop_state();
1478 }