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