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