Release 5.9.
[wine/zf.git] / libs / wpp / ppl.l
bloba68124355be118a1fdc8d5f9d43965db29fe90b1
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  */
124 %top{
125 #include "config.h"
126 #include "wine/port.h"
130  * Special flex options and exclusive scanner start-conditions
131  */
132 %option stack
133 %option 8bit never-interactive
134 %option noinput nounput
135 %option prefix="ppy_"
137 %x pp_pp
138 %x pp_eol
139 %x pp_inc
140 %x pp_dqs
141 %x pp_sqs
142 %x pp_iqs
143 %x pp_comment
144 %x pp_def
145 %x pp_define
146 %x pp_macro
147 %x pp_mbody
148 %x pp_macign
149 %x pp_macscan
150 %x pp_macexp
151 %x pp_if
152 %x pp_ifd
153 %x pp_ifignored
154 %x pp_endif
155 %x pp_line
156 %x pp_defined
157 %x pp_ignore
158 %x RCINCL
160 ws      [ \v\f\t\r]
161 cident  [a-zA-Z_][0-9a-zA-Z_]*
162 ul      [uUlL]|[uUlL][lL]|[lL][uU]|[lL][lL][uU]|[uU][lL][lL]|[lL][uU][lL]
165 #include <stdio.h>
166 #include <stdlib.h>
167 #include <string.h>
168 #include <ctype.h>
169 #include <assert.h>
170 #include <errno.h>
171 #include <limits.h>
173 #ifndef LLONG_MAX
174 # define LLONG_MAX  ((__int64)0x7fffffff << 32 | 0xffffffff)
175 # define LLONG_MIN  (-LLONG_MAX - 1)
176 #endif
177 #ifndef ULLONG_MAX
178 # define ULLONG_MAX ((__int64)0xffffffff << 32 | 0xffffffff)
179 #endif
181 #ifndef HAVE_UNISTD_H
182 #define YY_NO_UNISTD_H
183 #endif
185 #include "wine/wpp.h"
186 #include "wpp_private.h"
187 #include "ppy.tab.h"
190  * Make sure that we are running an appropriate version of flex.
191  */
192 #if !defined(YY_FLEX_MAJOR_VERSION) || (1000 * YY_FLEX_MAJOR_VERSION + YY_FLEX_MINOR_VERSION < 2005)
193 #error Must use flex version 2.5.1 or higher (yy_scan_* routines are required).
194 #endif
196 #define YY_READ_BUF_SIZE        65536           /* So we read most of a file at once */
198 #define yy_current_state()      YY_START
199 #define yy_pp_state(x)          yy_pop_state(); yy_push_state(x)
202  * Always update the current character position within a line
203  */
204 #define YY_USER_ACTION  pp_status.char_number+=ppy_leng;
207  * Buffer management for includes and expansions
208  */
209 #define MAXBUFFERSTACK  128     /* Nesting more than 128 includes or macro expansion textss is insane */
211 typedef struct bufferstackentry {
212         YY_BUFFER_STATE bufferstate;    /* Buffer to switch back to */
213         void            *filehandle;    /* Handle to be used with wpp_callbacks->read */
214         pp_entry_t      *define;        /* Points to expanding define or NULL if handling includes */
215         int             line_number;    /* Line that we were handling */
216         int             char_number;    /* The current position on that line */
217         char            *filename;      /* Filename that we were handling */
218         int             if_depth;       /* How many #if:s deep to check matching #endif:s */
219         int             ncontinuations; /* Remember the continuation state */
220         int             should_pop;     /* Set if we must pop the start-state on EOF */
221         /* Include management */
222         include_state_t incl;
223         char            *include_filename;
224 } bufferstackentry_t;
226 #define ALLOCBLOCKSIZE  (1 << 10)       /* Allocate these chunks at a time for string-buffers */
229  * Macro expansion nesting
230  * We need the stack to handle expansions while scanning
231  * a macro's arguments. The TOS must always be the macro
232  * that receives the current expansion from the scanner.
233  */
234 #define MAXMACEXPSTACK  128     /* Nesting more than 128 macro expansions is insane */
236 typedef struct macexpstackentry {
237         pp_entry_t      *ppp;           /* This macro we are scanning */
238         char            **args;         /* With these arguments */
239         char            **ppargs;       /* Resulting in these preprocessed arguments */
240         int             *nnls;          /* Number of newlines per argument */
241         int             nargs;          /* And this many arguments scanned */
242         int             parentheses;    /* Nesting level of () */
243         int             curargsize;     /* Current scanning argument's size */
244         int             curargalloc;    /* Current scanning argument's block allocated */
245         char            *curarg;        /* Current scanning argument's content */
246 } macexpstackentry_t;
248 #define MACROPARENTHESES()      (top_macro()->parentheses)
251  * Prototypes
252  */
253 static void newline(int);
254 static int make_number(int radix, YYSTYPE *val, const char *str, int len);
255 static void put_buffer(const char *s, int len);
256 /* Buffer management */
257 static void push_buffer(pp_entry_t *ppp, char *filename, char *incname, int pop);
258 static bufferstackentry_t *pop_buffer(void);
259 /* String functions */
260 static void new_string(void);
261 static void add_string(const char *str, int len);
262 static char *get_string(void);
263 static void put_string(void);
264 static int string_start(void);
265 /* Macro functions */
266 static void push_macro(pp_entry_t *ppp);
267 static macexpstackentry_t *top_macro(void);
268 static macexpstackentry_t *pop_macro(void);
269 static void free_macro(macexpstackentry_t *mep);
270 static void add_text_to_macro(const char *text, int len);
271 static void macro_add_arg(int last);
272 static void macro_add_expansion(void);
273 /* Expansion */
274 static void expand_special(pp_entry_t *ppp);
275 static void expand_define(pp_entry_t *ppp);
276 static void expand_macro(macexpstackentry_t *mep);
279  * Local variables
280  */
281 static int ncontinuations;
283 static int strbuf_idx = 0;
284 static int strbuf_alloc = 0;
285 static char *strbuffer = NULL;
286 static int str_startline;
288 static macexpstackentry_t *macexpstack[MAXMACEXPSTACK];
289 static int macexpstackidx = 0;
291 static bufferstackentry_t bufferstack[MAXBUFFERSTACK];
292 static int bufferstackidx = 0;
295  * Global variables
296  */
297 include_state_t pp_incl_state =
299     -1,    /* state */
300     NULL,  /* ppp */
301     0,     /* ifdepth */
302     0      /* seen_junk */
305 includelogicentry_t *pp_includelogiclist = NULL;
307 #define YY_INPUT(buf,result,max_size)                                        \
308         {                                                                    \
309                 result = fread(buf, 1, max_size, pp_status.file);            \
310         }
312 #define BUFFERINITIALCAPACITY 256
314 void pp_writestring(const char *format, ...)
316         va_list valist;
317         int len;
318         static char *buffer;
319         static int buffercapacity;
320         char *new_buffer;
322         if(buffercapacity == 0)
323         {
324                 buffer = pp_xmalloc(BUFFERINITIALCAPACITY);
325                 if(buffer == NULL)
326                         return;
327                 buffercapacity = BUFFERINITIALCAPACITY;
328         }
330         va_start(valist, format);
331         len = vsnprintf(buffer, buffercapacity,
332                         format, valist);
333         va_end(valist);
334         /* If the string is longer than buffersize, vsnprintf returns
335          * the string length with glibc >= 2.1, -1 with glibc < 2.1 */
336         while(len > buffercapacity || len < 0)
337         {
338                 do
339                 {
340                         buffercapacity *= 2;
341                 } while(len > buffercapacity);
343                 new_buffer = pp_xrealloc(buffer, buffercapacity);
344                 if(new_buffer == NULL)
345                 {
346                         va_end(valist);
347                         return;
348                 }
349                 buffer = new_buffer;
350                 va_start(valist, format);
351                 len = vsnprintf(buffer, buffercapacity,
352                                 format, valist);
353                 va_end(valist);
354         }
356         fwrite(buffer, 1, len, ppy_out);
362  **************************************************************************
363  * The scanner starts here
364  **************************************************************************
365  */
368         /*
369          * Catch line-continuations.
370          * Note: Gcc keeps the line-continuations in, for example, strings
371          * intact. However, I prefer to remove them all so that the next
372          * scanner will not need to reduce the continuation state.
373          *
374          * <*>\\\n              newline(0);
375          */
377         /*
378          * Detect the leading # of a preprocessor directive.
379          */
380 <INITIAL,pp_ignore>^{ws}*#      pp_incl_state.seen_junk++; yy_push_state(pp_pp);
382         /*
383          * Scan for the preprocessor directives
384          */
385 <pp_pp>{ws}*include{ws}*        if(yy_top_state() != pp_ignore) {yy_pp_state(pp_inc); return tINCLUDE;} else {yy_pp_state(pp_eol);}
386 <pp_pp>{ws}*define{ws}*         yy_pp_state(yy_current_state() != pp_ignore ? pp_def : pp_eol);
387 <pp_pp>{ws}*error{ws}*          yy_pp_state(pp_eol);    if(yy_top_state() != pp_ignore) return tERROR;
388 <pp_pp>{ws}*warning{ws}*        yy_pp_state(pp_eol);    if(yy_top_state() != pp_ignore) return tWARNING;
389 <pp_pp>{ws}*pragma{ws}*         yy_pp_state(pp_eol);    if(yy_top_state() != pp_ignore) return tPRAGMA;
390 <pp_pp>{ws}*ident{ws}*          yy_pp_state(pp_eol);    if(yy_top_state() != pp_ignore) return tPPIDENT;
391 <pp_pp>{ws}*undef{ws}*          if(yy_top_state() != pp_ignore) {yy_pp_state(pp_ifd); return tUNDEF;} else {yy_pp_state(pp_eol);}
392 <pp_pp>{ws}*ifdef{ws}*          yy_pp_state(pp_ifd);    return tIFDEF;
393 <pp_pp>{ws}*ifndef{ws}*         pp_incl_state.seen_junk--; yy_pp_state(pp_ifd); return tIFNDEF;
394 <pp_pp>{ws}*if{ws}*             if(yy_top_state() != pp_ignore) {yy_pp_state(pp_if);} else {yy_pp_state(pp_ifignored);} return tIF;
395 <pp_pp>{ws}*elif{ws}*           yy_pp_state(pp_if);     return tELIF;
396 <pp_pp>{ws}*else{ws}*           yy_pp_state(pp_endif);  return tELSE;
397 <pp_pp>{ws}*endif{ws}*          yy_pp_state(pp_endif);  return tENDIF;
398 <pp_pp>{ws}*line{ws}*           if(yy_top_state() != pp_ignore) {yy_pp_state(pp_line); return tLINE;} else {yy_pp_state(pp_eol);}
399 <pp_pp>{ws}+                    if(yy_top_state() != pp_ignore) {yy_pp_state(pp_line); return tGCCLINE;} else {yy_pp_state(pp_eol);}
400 <pp_pp>{ws}*[a-z]+              ppy_error("Invalid preprocessor token '%s'", ppy_text);
401 <pp_pp>\r?\n                    newline(1); yy_pop_state(); return tNL; /* This could be the null-token */
402 <pp_pp>\\\r?\n                  newline(0);
403 <pp_pp>\\\r?                    ppy_error("Preprocessor junk '%s'", ppy_text);
404 <pp_pp>.                        return *ppy_text;
406         /*
407          * Handle #include and #line
408          */
409 <pp_line>[0-9]+                 return make_number(10, &ppy_lval, ppy_text, ppy_leng);
410 <pp_inc>\<                      new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_iqs);
411 <pp_inc,pp_line>\"              new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_dqs);
412 <pp_inc,pp_line>{ws}+           ;
413 <pp_inc,pp_line>\n              newline(1); yy_pop_state(); return tNL;
414 <pp_inc,pp_line>\\\r?\n         newline(0);
415 <pp_inc,pp_line>(\\\r?)|(.)     ppy_error(yy_current_state() == pp_inc ? "Trailing junk in #include" : "Trailing junk in #line");
417         /*
418          * Ignore all input when a false clause is parsed
419          */
420 <pp_ignore>[^#/\\\n]+           ;
421 <pp_ignore>\n                   newline(1);
422 <pp_ignore>\\\r?\n              newline(0);
423 <pp_ignore>(\\\r?)|(.)          ;
425         /*
426          * Handle #if and #elif.
427          * These require conditionals to be evaluated, but we do not
428          * want to jam the scanner normally when we see these tokens.
429          * Note: tIDENT is handled below.
430          */
432 <pp_if>0[0-7]*{ul}?             return make_number(8, &ppy_lval, ppy_text, ppy_leng);
433 <pp_if>0[0-7]*[8-9]+{ul}?       ppy_error("Invalid octal digit");
434 <pp_if>[1-9][0-9]*{ul}?         return make_number(10, &ppy_lval, ppy_text, ppy_leng);
435 <pp_if>0[xX][0-9a-fA-F]+{ul}?   return make_number(16, &ppy_lval, ppy_text, ppy_leng);
436 <pp_if>0[xX]                    ppy_error("Invalid hex number");
437 <pp_if>defined                  yy_push_state(pp_defined); return tDEFINED;
438 <pp_if>"<<"                     return tLSHIFT;
439 <pp_if>">>"                     return tRSHIFT;
440 <pp_if>"&&"                     return tLOGAND;
441 <pp_if>"||"                     return tLOGOR;
442 <pp_if>"=="                     return tEQ;
443 <pp_if>"!="                     return tNE;
444 <pp_if>"<="                     return tLTE;
445 <pp_if>">="                     return tGTE;
446 <pp_if>\n                       newline(1); yy_pop_state(); return tNL;
447 <pp_if>\\\r?\n                  newline(0);
448 <pp_if>\\\r?                    ppy_error("Junk in conditional expression");
449 <pp_if>{ws}+                    ;
450 <pp_if>\'                       new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_sqs);
451 <pp_if>\"                       ppy_error("String constants not allowed in conditionals");
452 <pp_if>.                        return *ppy_text;
454 <pp_ifignored>[^\n]+            ppy_lval.sint = 0; return tSINT;
455 <pp_ifignored>\n                newline(1); yy_pop_state(); return tNL;
457         /*
458          * Handle #ifdef, #ifndef and #undef
459          * to get only an untranslated/unexpanded identifier
460          */
461 <pp_ifd>{cident}        ppy_lval.cptr = pp_xstrdup(ppy_text); return tIDENT;
462 <pp_ifd>{ws}+           ;
463 <pp_ifd>\n              newline(1); yy_pop_state(); return tNL;
464 <pp_ifd>\\\r?\n         newline(0);
465 <pp_ifd>(\\\r?)|(.)     ppy_error("Identifier expected");
467         /*
468          * Handle #else and #endif.
469          */
470 <pp_endif>{ws}+         ;
471 <pp_endif>\n            newline(1); yy_pop_state(); return tNL;
472 <pp_endif>\\\r?\n       newline(0);
473 <pp_endif>.             ppy_error("Garbage after #else or #endif.");
475         /*
476          * Handle the special 'defined' keyword.
477          * This is necessary to get the identifier prior to any
478          * substitutions.
479          */
480 <pp_defined>{cident}            yy_pop_state(); ppy_lval.cptr = pp_xstrdup(ppy_text); return tIDENT;
481 <pp_defined>{ws}+               ;
482 <pp_defined>(\()|(\))           return *ppy_text;
483 <pp_defined>\\\r?\n             newline(0);
484 <pp_defined>(\\.)|(\n)|(.)      ppy_error("Identifier expected");
486         /*
487          * Handle #error, #warning, #pragma and #ident.
488          * Pass everything literally to the parser, which
489          * will act appropriately.
490          * Comments are stripped from the literal text.
491          */
492 <pp_eol>[^/\\\n]+               if(yy_top_state() != pp_ignore) { ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL; }
493 <pp_eol>\/[^/\\\n*]*            if(yy_top_state() != pp_ignore) { ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL; }
494 <pp_eol>(\\\r?)|(\/[^/*])       if(yy_top_state() != pp_ignore) { ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL; }
495 <pp_eol>\n                      newline(1); yy_pop_state(); if(yy_current_state() != pp_ignore) { return tNL; }
496 <pp_eol>\\\r?\n                 newline(0);
498         /*
499          * Handle left side of #define
500          */
501 <pp_def>{cident}\(              ppy_lval.cptr = pp_xstrdup(ppy_text); if(ppy_lval.cptr) ppy_lval.cptr[ppy_leng-1] = '\0'; yy_pp_state(pp_macro);  return tMACRO;
502 <pp_def>{cident}                ppy_lval.cptr = pp_xstrdup(ppy_text); yy_pp_state(pp_define); return tDEFINE;
503 <pp_def>{ws}+                   ;
504 <pp_def>\\\r?\n                 newline(0);
505 <pp_def>(\\\r?)|(\n)|(.)        perror("Identifier expected");
507         /*
508          * Scan the substitution of a define
509          */
510 <pp_define>[^'"/\\\n]+          ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL;
511 <pp_define>(\\\r?)|(\/[^/*])    ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL;
512 <pp_define>\\\r?\n{ws}+         newline(0); ppy_lval.cptr = pp_xstrdup(" "); return tLITERAL;
513 <pp_define>\\\r?\n              newline(0);
514 <pp_define>\n                   newline(1); yy_pop_state(); return tNL;
515 <pp_define>\'                   new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_sqs);
516 <pp_define>\"                   new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_dqs);
518         /*
519          * Scan the definition macro arguments
520          */
521 <pp_macro>\){ws}*               yy_pp_state(pp_mbody); return tMACROEND;
522 <pp_macro>{ws}+                 ;
523 <pp_macro>{cident}              ppy_lval.cptr = pp_xstrdup(ppy_text); return tIDENT;
524 <pp_macro>,                     return ',';
525 <pp_macro>"..."                 return tELIPSIS;
526 <pp_macro>(\\\r?)|(\n)|(.)|(\.\.?)      ppy_error("Argument identifier expected");
527 <pp_macro>\\\r?\n               newline(0);
529         /*
530          * Scan the substitution of a macro
531          */
532 <pp_mbody>[^a-zA-Z0-9'"#/\\\n]+ ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL;
533 <pp_mbody>{cident}              ppy_lval.cptr = pp_xstrdup(ppy_text); return tIDENT;
534 <pp_mbody>\#\#                  return tCONCAT;
535 <pp_mbody>\#                    return tSTRINGIZE;
536 <pp_mbody>[0-9][a-zA-Z0-9]*[^a-zA-Z0-9'"#/\\\n]*        ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL;
537 <pp_mbody>(\\\r?)|(\/[^/*'"#\\\n]*)     ppy_lval.cptr = pp_xstrdup(ppy_text); return tLITERAL;
538 <pp_mbody>\\\r?\n{ws}+          newline(0); ppy_lval.cptr = pp_xstrdup(" "); return tLITERAL;
539 <pp_mbody>\\\r?\n               newline(0);
540 <pp_mbody>\n                    newline(1); yy_pop_state(); return tNL;
541 <pp_mbody>\'                    new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_sqs);
542 <pp_mbody>\"                    new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_dqs);
544         /*
545          * Macro expansion text scanning.
546          * This state is active just after the identifier is scanned
547          * that triggers an expansion. We *must* delete the leading
548          * whitespace before we can start scanning for arguments.
549          *
550          * If we do not see a '(' as next trailing token, then we have
551          * a false alarm. We just continue with a nose-bleed...
552          */
553 <pp_macign>{ws}*/\(     yy_pp_state(pp_macscan);
554 <pp_macign>{ws}*\n      {
555                 if(yy_top_state() != pp_macscan)
556                         newline(0);
557         }
558 <pp_macign>{ws}*\\\r?\n newline(0);
559 <pp_macign>{ws}+|{ws}*\\\r?|.   {
560                 macexpstackentry_t *mac = pop_macro();
561                 yy_pop_state();
562                 put_buffer(mac->ppp->ident, strlen(mac->ppp->ident));
563                 put_buffer(ppy_text, ppy_leng);
564                 free_macro(mac);
565         }
567         /*
568          * Macro expansion argument text scanning.
569          * This state is active when a macro's arguments are being read for expansion.
570          */
571 <pp_macscan>\(  {
572                 if(++MACROPARENTHESES() > 1)
573                         add_text_to_macro(ppy_text, ppy_leng);
574         }
575 <pp_macscan>\)  {
576                 if(--MACROPARENTHESES() == 0)
577                 {
578                         yy_pop_state();
579                         macro_add_arg(1);
580                 }
581                 else
582                         add_text_to_macro(ppy_text, ppy_leng);
583         }
584 <pp_macscan>,           {
585                 if(MACROPARENTHESES() > 1)
586                         add_text_to_macro(ppy_text, ppy_leng);
587                 else
588                         macro_add_arg(0);
589         }
590 <pp_macscan>\"          new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_dqs);
591 <pp_macscan>\'          new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_sqs);
592 <pp_macscan>"/*"        yy_push_state(pp_comment); add_text_to_macro(" ", 1);
593 <pp_macscan>\n          pp_status.line_number++; pp_status.char_number = 1; add_text_to_macro(ppy_text, ppy_leng);
594 <pp_macscan>([^/(),\\\n"']+)|(\/[^/*(),\\\n'"]*)|(\\\r?)|(.)    add_text_to_macro(ppy_text, ppy_leng);
595 <pp_macscan>\\\r?\n     newline(0);
597         /*
598          * Comment handling (almost all start-conditions)
599          */
600 <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);
601 <pp_comment>[^*\n]*|"*"+[^*/\n]*        ;
602 <pp_comment>\n                          newline(0);
603 <pp_comment>"*"+"/"                     yy_pop_state();
605         /*
606          * Remove C++ style comment (almost all start-conditions)
607          */
608 <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]* {
609                 if(ppy_text[ppy_leng-1] == '\\')
610                         ppy_warning("C++ style comment ends with an escaped newline (escape ignored)");
611         }
613         /*
614          * Single, double and <> quoted constants
615          */
616 <INITIAL,pp_macexp>\"           pp_incl_state.seen_junk++; new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_dqs);
617 <INITIAL,pp_macexp>\'           pp_incl_state.seen_junk++; new_string(); add_string(ppy_text, ppy_leng); yy_push_state(pp_sqs);
618 <pp_dqs>[^"\\\n]+               add_string(ppy_text, ppy_leng);
619 <pp_dqs>\"                      {
620                 add_string(ppy_text, ppy_leng);
621                 yy_pop_state();
622                 switch(yy_current_state())
623                 {
624                 case pp_pp:
625                 case pp_define:
626                 case pp_mbody:
627                 case pp_inc:
628                 case RCINCL:
629                         if (yy_current_state()==RCINCL) yy_pop_state();
630                         ppy_lval.cptr = get_string();
631                         return tDQSTRING;
632                 case pp_line:
633                         ppy_lval.cptr = get_string();
634                         return tDQSTRING;
635                 default:
636                         put_string();
637                 }
638         }
639 <pp_sqs>[^'\\\n]+               add_string(ppy_text, ppy_leng);
640 <pp_sqs>\'                      {
641                 add_string(ppy_text, ppy_leng);
642                 yy_pop_state();
643                 switch(yy_current_state())
644                 {
645                 case pp_if:
646                 case pp_define:
647                 case pp_mbody:
648                         ppy_lval.cptr = get_string();
649                         return tSQSTRING;
650                 default:
651                         put_string();
652                 }
653         }
654 <pp_iqs>[^\>\\\n]+              add_string(ppy_text, ppy_leng);
655 <pp_iqs>\>                      {
656                 add_string(ppy_text, ppy_leng);
657                 yy_pop_state();
658                 ppy_lval.cptr = get_string();
659                 return tIQSTRING;
660         }
661 <pp_dqs>\\\r?\n         {
662                 /*
663                  * This is tricky; we need to remove the line-continuation
664                  * from preprocessor strings, but OTOH retain them in all
665                  * other strings. This is because the resource grammar is
666                  * even more braindead than initially analysed and line-
667                  * continuations in strings introduce, sigh, newlines in
668                  * the output. There goes the concept of non-breaking, non-
669                  * spacing whitespace.
670                  */
671                 switch(yy_top_state())
672                 {
673                 case pp_pp:
674                 case pp_define:
675                 case pp_mbody:
676                 case pp_inc:
677                 case pp_line:
678                         newline(0);
679                         break;
680                 default:
681                         add_string(ppy_text, ppy_leng);
682                         newline(-1);
683                 }
684         }
685 <pp_iqs,pp_dqs,pp_sqs>\\.       add_string(ppy_text, ppy_leng);
686 <pp_iqs,pp_dqs,pp_sqs>\n        {
687                 newline(1);
688                 add_string(ppy_text, ppy_leng);
689                 ppy_warning("Newline in string constant encountered (started line %d)", string_start());
690         }
692         /*
693          * Identifier scanning
694          */
695 <INITIAL,pp_if,pp_inc,pp_macexp>{cident}        {
696                 pp_entry_t *ppp;
697                 pp_incl_state.seen_junk++;
698                 if(!(ppp = pplookup(ppy_text)))
699                 {
700                         if(yy_current_state() == pp_inc)
701                                 ppy_error("Expected include filename");
703                         else if(yy_current_state() == pp_if)
704                         {
705                                 ppy_lval.cptr = pp_xstrdup(ppy_text);
706                                 return tIDENT;
707                         }
708                         else {
709                                 if((yy_current_state()==INITIAL) && (strcasecmp(ppy_text,"RCINCLUDE")==0)){
710                                         yy_push_state(RCINCL);
711                                         return tRCINCLUDE;
712                                 }
713                                 else put_buffer(ppy_text, ppy_leng);
714                         }
715                 }
716                 else if(!ppp->expanding)
717                 {
718                         switch(ppp->type)
719                         {
720                         case def_special:
721                                 expand_special(ppp);
722                                 break;
723                         case def_define:
724                                 expand_define(ppp);
725                                 break;
726                         case def_macro:
727                                 yy_push_state(pp_macign);
728                                 push_macro(ppp);
729                                 break;
730                         default:
731                                 pp_internal_error(__FILE__, __LINE__, "Invalid define type %d\n", ppp->type);
732                         }
733                 }
734                 else put_buffer(ppy_text, ppy_leng);
735         }
737         /*
738          * Everything else that needs to be passed and
739          * newline and continuation handling
740          */
741 <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);
742 <INITIAL,pp_macexp>{ws}+        put_buffer(ppy_text, ppy_leng);
743 <INITIAL>\n                     newline(1);
744 <INITIAL>\\\r?\n                newline(0);
745 <INITIAL>\\\r?                  pp_incl_state.seen_junk++; put_buffer(ppy_text, ppy_leng);
747         /*
748          * Special catcher for macro argmument expansion to prevent
749          * newlines to propagate to the output or admin.
750          */
751 <pp_macexp>(\n)|(.)|(\\\r?(\n|.))       put_buffer(ppy_text, ppy_leng);
753 <RCINCL>[A-Za-z0-9_\.\\/]+ {
754                 ppy_lval.cptr=pp_xstrdup(ppy_text);
755                 yy_pop_state();
756                 return tRCINCLUDEPATH;
757         }
759 <RCINCL>{ws}+ ;
761 <RCINCL>\"              {
762                 new_string(); add_string(ppy_text,ppy_leng);yy_push_state(pp_dqs);
763         }
765         /*
766          * This is a 'catch-all' rule to discover errors in the scanner
767          * in an orderly manner.
768          */
769 <*>.            pp_incl_state.seen_junk++; ppy_warning("Unmatched text '%c' (0x%02x); please report\n", isprint(*ppy_text & 0xff) ? *ppy_text : ' ', *ppy_text);
771 <<EOF>> {
772                 YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
773                 bufferstackentry_t *bep = pop_buffer();
775                 if((!bep && pp_get_if_depth()) || (bep && pp_get_if_depth() != bep->if_depth))
776                         ppy_warning("Unmatched #if/#endif at end of file");
778                 if(!bep)
779                 {
780                         if(YY_START != INITIAL)
781                         {
782                                 ppy_error("Unexpected end of file during preprocessing");
783                                 BEGIN(INITIAL);
784                         }
785                         yyterminate();
786                 }
787                 else if(bep->should_pop == 2)
788                 {
789                         macexpstackentry_t *mac;
790                         mac = pop_macro();
791                         expand_macro(mac);
792                 }
793                 ppy__delete_buffer(b);
794         }
798  **************************************************************************
799  * Support functions
800  **************************************************************************
801  */
803 #ifndef ppy_wrap
804 int ppy_wrap(void)
806         return 1;
808 #endif
812  *-------------------------------------------------------------------------
813  * Output newlines or set them as continuations
815  * Input: -1 - Don't count this one, but update local position (see pp_dqs)
816  *         0 - Line-continuation seen and cache output
817  *         1 - Newline seen and flush output
818  *-------------------------------------------------------------------------
819  */
820 static void newline(int dowrite)
822         pp_status.line_number++;
823         pp_status.char_number = 1;
825         if(dowrite == -1)
826                 return;
828         ncontinuations++;
829         if(dowrite)
830         {
831                 for(;ncontinuations; ncontinuations--)
832                         put_buffer("\n", 1);
833         }
838  *-------------------------------------------------------------------------
839  * Make a number out of an any-base and suffixed string
841  * Possible number extensions:
842  * - ""         int
843  * - "L"        long int
844  * - "LL"       long long int
845  * - "U"        unsigned int
846  * - "UL"       unsigned long int
847  * - "ULL"      unsigned long long int
848  * - "LU"       unsigned long int
849  * - "LLU"      unsigned long long int
850  * - "LUL"      invalid
852  * FIXME:
853  * The sizes of resulting 'int' and 'long' are compiler specific.
854  * I depend on sizeof(int) > 2 here (although a relatively safe
855  * assumption).
856  * Long longs are not yet implemented because this is very compiler
857  * specific and I don't want to think too much about the problems.
859  *-------------------------------------------------------------------------
860  */
861 static int make_number(int radix, YYSTYPE *val, const char *str, int len)
863         int is_l  = 0;
864         int is_ll = 0;
865         int is_u  = 0;
866         char ext[4];
867         long l;
869         ext[3] = '\0';
870         ext[2] = toupper(str[len-1]);
871         ext[1] = len > 1 ? toupper(str[len-2]) : ' ';
872         ext[0] = len > 2 ? toupper(str[len-3]) : ' ';
874         if(!strcmp(ext, "LUL"))
875         {
876                 ppy_error("Invalid constant suffix");
877                 return 0;
878         }
879         else if(!strcmp(ext, "LLU") || !strcmp(ext, "ULL"))
880         {
881                 is_ll++;
882                 is_u++;
883         }
884         else if(!strcmp(ext+1, "LU") || !strcmp(ext+1, "UL"))
885         {
886                 is_l++;
887                 is_u++;
888         }
889         else if(!strcmp(ext+1, "LL"))
890         {
891                 is_ll++;
892         }
893         else if(!strcmp(ext+2, "L"))
894         {
895                 is_l++;
896         }
897         else if(!strcmp(ext+2, "U"))
898         {
899                 is_u++;
900         }
902         if(is_u && is_ll)
903         {
904                 errno = 0;
905                 val->ull = strtoull(str, NULL, radix);
906                 if (val->ull == ULLONG_MAX && errno == ERANGE)
907                     ppy_error("integer constant %s is too large\n", str);
908                 return tULONGLONG;
909         }
910         else if(!is_u && is_ll)
911         {
912                 errno = 0;
913                 val->sll = strtoll(str, NULL, radix);
914                 if ((val->sll == LLONG_MIN || val->sll == LLONG_MAX) && errno == ERANGE)
915                     ppy_error("integer constant %s is too large\n", str);
916                 return tSLONGLONG;
917         }
918         else if(is_u && is_l)
919         {
920                 errno = 0;
921                 val->ulong = strtoul(str, NULL, radix);
922                 if (val->ulong == ULONG_MAX && errno == ERANGE)
923                         ppy_error("integer constant %s is too large\n", str);
924                 return tULONG;
925         }
926         else if(!is_u && is_l)
927         {
928                 errno = 0;
929                 val->slong = strtol(str, NULL, radix);
930                 if ((val->slong == LONG_MIN || val->slong == LONG_MAX) && errno == ERANGE)
931                         ppy_error("integer constant %s is too large\n", str);
932                 return tSLONG;
933         }
934         else if(is_u && !is_l)
935         {
936                 unsigned long ul;
937                 errno = 0;
938                 ul = strtoul(str, NULL, radix);
939                 if ((ul == ULONG_MAX && errno == ERANGE) || (ul > UINT_MAX))
940                         ppy_error("integer constant %s is too large\n", str);
941                 val->uint = (unsigned int)ul;
942                 return tUINT;
943         }
945         /* Else it must be an int... */
946         errno = 0;
947         l = strtol(str, NULL, radix);
948         if (((l == LONG_MIN || l == LONG_MAX) && errno == ERANGE) ||
949                 (l > INT_MAX) || (l < INT_MIN))
950                 ppy_error("integer constant %s is too large\n", str);
951         val->sint = (int)l;
952         return tSINT;
957  *-------------------------------------------------------------------------
958  * Macro and define expansion support
960  * FIXME: Variable macro arguments.
961  *-------------------------------------------------------------------------
962  */
963 static void expand_special(pp_entry_t *ppp)
965         static char *buf = NULL;
966         char *new_buf;
968         assert(ppp->type == def_special);
970         if(!strcmp(ppp->ident, "__LINE__"))
971         {
972                 new_buf = pp_xrealloc(buf, 32);
973                 if(!new_buf)
974                         return;
975                 buf = new_buf;
976                 sprintf(buf, "%d", pp_status.line_number);
977         }
978         else if(!strcmp(ppp->ident, "__FILE__"))
979         {
980                 new_buf = pp_xrealloc(buf, strlen(pp_status.input) + 3);
981                 if(!new_buf)
982                         return;
983                 buf = new_buf;
984                 sprintf(buf, "\"%s\"", pp_status.input);
985         }
986         else
987                 pp_internal_error(__FILE__, __LINE__, "Special macro '%s' not found...\n", ppp->ident);
989         if(pp_flex_debug)
990                 fprintf(stderr, "expand_special(%d): %s:%d: '%s' -> '%s'\n",
991                         macexpstackidx,
992                         pp_status.input,
993                         pp_status.line_number,
994                         ppp->ident,
995                         buf ? buf : "");
997         if(buf && buf[0])
998         {
999                 push_buffer(ppp, NULL, NULL, 0);
1000                 yy_scan_string(buf);
1001         }
1004 static void expand_define(pp_entry_t *ppp)
1006         assert(ppp->type == def_define);
1008         if(pp_flex_debug)
1009                 fprintf(stderr, "expand_define(%d): %s:%d: '%s' -> '%s'\n",
1010                         macexpstackidx,
1011                         pp_status.input,
1012                         pp_status.line_number,
1013                         ppp->ident,
1014                         ppp->subst.text);
1015         if(ppp->subst.text && ppp->subst.text[0])
1016         {
1017                 push_buffer(ppp, NULL, NULL, 0);
1018                 yy_scan_string(ppp->subst.text);
1019         }
1022 static int curdef_idx = 0;
1023 static int curdef_alloc = 0;
1024 static char *curdef_text = NULL;
1026 static void add_text(const char *str, int len)
1028         int new_alloc;
1029         char *new_text;
1031         if(len == 0)
1032                 return;
1033         if(curdef_idx >= curdef_alloc || curdef_alloc - curdef_idx < len)
1034         {
1035                 new_alloc = curdef_alloc + ((len + ALLOCBLOCKSIZE-1) & ~(ALLOCBLOCKSIZE-1));
1036                 new_text = pp_xrealloc(curdef_text, new_alloc * sizeof(curdef_text[0]));
1037                 if(!new_text)
1038                         return;
1039                 curdef_text = new_text;
1040                 curdef_alloc = new_alloc;
1041                 if(curdef_alloc > 65536)
1042                         ppy_warning("Reallocating macro-expansion buffer larger than 64kB");
1043         }
1044         memcpy(&curdef_text[curdef_idx], str, len);
1045         curdef_idx += len;
1048 static mtext_t *add_expand_text(mtext_t *mtp, macexpstackentry_t *mep, int *nnl)
1050         char *cptr;
1051         char *exp;
1052         int tag;
1053         int n;
1055         if(mtp == NULL)
1056                 return NULL;
1058         switch(mtp->type)
1059         {
1060         case exp_text:
1061                 if(pp_flex_debug)
1062                         fprintf(stderr, "add_expand_text: exp_text: '%s'\n", mtp->subst.text);
1063                 add_text(mtp->subst.text, strlen(mtp->subst.text));
1064                 break;
1066         case exp_stringize:
1067                 if(pp_flex_debug)
1068                         fprintf(stderr, "add_expand_text: exp_stringize(%d): '%s'\n",
1069                                 mtp->subst.argidx,
1070                                 mep->args[mtp->subst.argidx]);
1071                 cptr = mep->args[mtp->subst.argidx];
1072                 add_text("\"", 1);
1073                 while(*cptr)
1074                 {
1075                         if(*cptr == '"' || *cptr == '\\')
1076                                 add_text("\\", 1);
1077                         add_text(cptr, 1);
1078                         cptr++;
1079                 }
1080                 add_text("\"", 1);
1081                 break;
1083         case exp_concat:
1084                 if(pp_flex_debug)
1085                         fprintf(stderr, "add_expand_text: exp_concat\n");
1086                 /* Remove trailing whitespace from current expansion text */
1087                 while(curdef_idx)
1088                 {
1089                         if(isspace(curdef_text[curdef_idx-1] & 0xff))
1090                                 curdef_idx--;
1091                         else
1092                                 break;
1093                 }
1094                 /* tag current position and recursively expand the next part */
1095                 tag = curdef_idx;
1096                 mtp = add_expand_text(mtp->next, mep, nnl);
1098                 /* Now get rid of the leading space of the expansion */
1099                 cptr = &curdef_text[tag];
1100                 n = curdef_idx - tag;
1101                 while(n)
1102                 {
1103                         if(isspace(*cptr & 0xff))
1104                         {
1105                                 cptr++;
1106                                 n--;
1107                         }
1108                         else
1109                                 break;
1110                 }
1111                 if(cptr != &curdef_text[tag])
1112                 {
1113                         memmove(&curdef_text[tag], cptr, n);
1114                         curdef_idx -= (curdef_idx - tag) - n;
1115                 }
1116                 break;
1118         case exp_subst:
1119                 if((mtp->next && mtp->next->type == exp_concat) || (mtp->prev && mtp->prev->type == exp_concat))
1120                         exp = mep->args[mtp->subst.argidx];
1121                 else
1122                         exp = mep->ppargs[mtp->subst.argidx];
1123                 if(exp)
1124                 {
1125                         add_text(exp, strlen(exp));
1126                         *nnl -= mep->nnls[mtp->subst.argidx];
1127                         cptr = strchr(exp, '\n');
1128                         while(cptr)
1129                         {
1130                                 *cptr = ' ';
1131                                 cptr = strchr(cptr+1, '\n');
1132                         }
1133                         mep->nnls[mtp->subst.argidx] = 0;
1134                 }
1135                 if(pp_flex_debug)
1136                         fprintf(stderr, "add_expand_text: exp_subst(%d): '%s'\n", mtp->subst.argidx, exp);
1137                 break;
1139         default:
1140                 pp_internal_error(__FILE__, __LINE__, "Invalid expansion type (%d) in macro expansion\n", mtp->type);
1141         }
1142         return mtp;
1145 static void expand_macro(macexpstackentry_t *mep)
1147         mtext_t *mtp;
1148         int n, k;
1149         char *cptr;
1150         int nnl = 0;
1151         pp_entry_t *ppp = mep->ppp;
1152         int nargs = mep->nargs;
1154         assert(ppp->type == def_macro);
1155         assert(ppp->expanding == 0);
1157         if((ppp->nargs >= 0 && nargs != ppp->nargs) || (ppp->nargs < 0 && nargs < -ppp->nargs))
1158         {
1159                 ppy_error("Too %s macro arguments (%d)", nargs < abs(ppp->nargs) ? "few" : "many", nargs);
1160                 return;
1161         }
1163         for(n = 0; n < nargs; n++)
1164                 nnl += mep->nnls[n];
1166         if(pp_flex_debug)
1167                 fprintf(stderr, "expand_macro(%d): %s:%d: '%s'(%d,%d) -> ...\n",
1168                         macexpstackidx,
1169                         pp_status.input,
1170                         pp_status.line_number,
1171                         ppp->ident,
1172                         mep->nargs,
1173                         nnl);
1175         curdef_idx = 0;
1177         for(mtp = ppp->subst.mtext; mtp; mtp = mtp->next)
1178         {
1179                 if(!(mtp = add_expand_text(mtp, mep, &nnl)))
1180                         break;
1181         }
1183         for(n = 0; n < nnl; n++)
1184                 add_text("\n", 1);
1186         /* To make sure there is room and termination (see below) */
1187         add_text(" \0", 2);
1189         /* Strip trailing whitespace from expansion */
1190         for(k = curdef_idx, cptr = &curdef_text[curdef_idx-1]; k > 0; k--, cptr--)
1191         {
1192                 if(!isspace(*cptr & 0xff))
1193                         break;
1194         }
1196         /*
1197          * We must add *one* whitespace to make sure that there
1198          * is a token-separation after the expansion.
1199          */
1200         *(++cptr) = ' ';
1201         *(++cptr) = '\0';
1202         k++;
1204         /* Strip leading whitespace from expansion */
1205         for(n = 0, cptr = curdef_text; n < k; n++, cptr++)
1206         {
1207                 if(!isspace(*cptr & 0xff))
1208                         break;
1209         }
1211         if(k - n > 0)
1212         {
1213                 if(pp_flex_debug)
1214                         fprintf(stderr, "expand_text: '%s'\n", curdef_text + n);
1215                 push_buffer(ppp, NULL, NULL, 0);
1216                 /*yy_scan_bytes(curdef_text + n, k - n);*/
1217                 yy_scan_string(curdef_text + n);
1218         }
1222  *-------------------------------------------------------------------------
1223  * String collection routines
1224  *-------------------------------------------------------------------------
1225  */
1226 static void new_string(void)
1228 #ifdef DEBUG
1229         if(strbuf_idx)
1230                 ppy_warning("new_string: strbuf_idx != 0");
1231 #endif
1232         strbuf_idx = 0;
1233         str_startline = pp_status.line_number;
1236 static void add_string(const char *str, int len)
1238         int new_alloc;
1239         char *new_buffer;
1241         if(len == 0)
1242                 return;
1243         if(strbuf_idx >= strbuf_alloc || strbuf_alloc - strbuf_idx < len)
1244         {
1245                 new_alloc = strbuf_alloc + ((len + ALLOCBLOCKSIZE-1) & ~(ALLOCBLOCKSIZE-1));
1246                 new_buffer = pp_xrealloc(strbuffer, new_alloc * sizeof(strbuffer[0]));
1247                 if(!new_buffer)
1248                         return;
1249                 strbuffer = new_buffer;
1250                 strbuf_alloc = new_alloc;
1251                 if(strbuf_alloc > 65536)
1252                         ppy_warning("Reallocating string buffer larger than 64kB");
1253         }
1254         memcpy(&strbuffer[strbuf_idx], str, len);
1255         strbuf_idx += len;
1258 static char *get_string(void)
1260         char *str = pp_xmalloc(strbuf_idx + 1);
1261         if(!str)
1262                 return NULL;
1263         memcpy(str, strbuffer, strbuf_idx);
1264         str[strbuf_idx] = '\0';
1265 #ifdef DEBUG
1266         strbuf_idx = 0;
1267 #endif
1268         return str;
1271 static void put_string(void)
1273         put_buffer(strbuffer, strbuf_idx);
1274 #ifdef DEBUG
1275         strbuf_idx = 0;
1276 #endif
1279 static int string_start(void)
1281         return str_startline;
1286  *-------------------------------------------------------------------------
1287  * Buffer management
1288  *-------------------------------------------------------------------------
1289  */
1290 static void push_buffer(pp_entry_t *ppp, char *filename, char *incname, int pop)
1292         if(ppy_debug)
1293                 printf("push_buffer(%d): %p %p %p %d\n", bufferstackidx, ppp, filename, incname, pop);
1294         if(bufferstackidx >= MAXBUFFERSTACK)
1295                 pp_internal_error(__FILE__, __LINE__, "Buffer stack overflow");
1297         memset(&bufferstack[bufferstackidx], 0, sizeof(bufferstack[0]));
1298         bufferstack[bufferstackidx].bufferstate = YY_CURRENT_BUFFER;
1299         bufferstack[bufferstackidx].filehandle  = pp_status.file;
1300         bufferstack[bufferstackidx].define      = ppp;
1301         bufferstack[bufferstackidx].line_number = pp_status.line_number;
1302         bufferstack[bufferstackidx].char_number = pp_status.char_number;
1303         bufferstack[bufferstackidx].if_depth    = pp_get_if_depth();
1304         bufferstack[bufferstackidx].should_pop  = pop;
1305         bufferstack[bufferstackidx].filename    = pp_status.input;
1306         bufferstack[bufferstackidx].ncontinuations      = ncontinuations;
1307         bufferstack[bufferstackidx].incl                = pp_incl_state;
1308         bufferstack[bufferstackidx].include_filename    = incname;
1310         if(ppp)
1311                 ppp->expanding = 1;
1312         else if(filename)
1313         {
1314                 /* These will track the ppy_error to the correct file and line */
1315                 pp_status.line_number = 1;
1316                 pp_status.char_number = 1;
1317                 pp_status.input  = filename;
1318                 ncontinuations = 0;
1319         }
1320         else if(!pop)
1321                 pp_internal_error(__FILE__, __LINE__, "Pushing buffer without knowing where to go to");
1322         bufferstackidx++;
1325 static bufferstackentry_t *pop_buffer(void)
1327         if(bufferstackidx < 0)
1328                 pp_internal_error(__FILE__, __LINE__, "Bufferstack underflow?");
1330         if(bufferstackidx == 0)
1331                 return NULL;
1333         bufferstackidx--;
1335         if(bufferstack[bufferstackidx].define)
1336                 bufferstack[bufferstackidx].define->expanding = 0;
1337         else
1338         {
1339                 includelogicentry_t *iep = NULL;
1341                 if(!bufferstack[bufferstackidx].should_pop)
1342                 {
1343                         fclose(pp_status.file);
1344                         pp_writestring("# %d \"%s\" 2\n", bufferstack[bufferstackidx].line_number, bufferstack[bufferstackidx].filename);
1346                         /* We have EOF, check the include logic */
1347                         if(pp_incl_state.state == 2 && !pp_incl_state.seen_junk && pp_incl_state.ppp)
1348                         {
1349                                 pp_entry_t *ppp = pplookup(pp_incl_state.ppp);
1350                                 if(ppp)
1351                                 {
1352                                         iep = pp_xmalloc(sizeof(includelogicentry_t));
1353                                         if (iep)
1354                                         {
1355                                                 iep->ppp = ppp;
1356                                                 ppp->iep = iep;
1357                                                 iep->filename = bufferstack[bufferstackidx].include_filename;
1358                                                 iep->prev = NULL;
1359                                                 iep->next = pp_includelogiclist;
1360                                                 if(iep->next)
1361                                                         iep->next->prev = iep;
1362                                                 pp_includelogiclist = iep;
1363                                                 if(pp_status.debug)
1364                                                         fprintf(stderr, "pop_buffer: %s:%d: includelogic added, include_ppp='%s', file='%s'\n",
1365                                                                 bufferstack[bufferstackidx].filename, bufferstack[bufferstackidx].line_number, pp_incl_state.ppp, iep->filename);
1366                                         }
1367                                 }
1368                         }
1369                         free(pp_incl_state.ppp);
1370                         pp_incl_state   = bufferstack[bufferstackidx].incl;
1372                 }
1373                 if (bufferstack[bufferstackidx].include_filename)
1374                 {
1375                         free(pp_status.input);
1376                         pp_status.input = bufferstack[bufferstackidx].filename;
1377                 }
1378                 pp_status.line_number = bufferstack[bufferstackidx].line_number;
1379                 pp_status.char_number = bufferstack[bufferstackidx].char_number;
1380                 ncontinuations = bufferstack[bufferstackidx].ncontinuations;
1381                 if (!iep)
1382                         free(bufferstack[bufferstackidx].include_filename);
1383         }
1385         if(ppy_debug)
1386                 printf("pop_buffer(%d): %p %p (%d, %d, %d) %p %d\n",
1387                         bufferstackidx,
1388                         bufferstack[bufferstackidx].bufferstate,
1389                         bufferstack[bufferstackidx].define,
1390                         bufferstack[bufferstackidx].line_number,
1391                         bufferstack[bufferstackidx].char_number,
1392                         bufferstack[bufferstackidx].if_depth,
1393                         bufferstack[bufferstackidx].filename,
1394                         bufferstack[bufferstackidx].should_pop);
1396         pp_status.file = bufferstack[bufferstackidx].filehandle;
1397         ppy__switch_to_buffer(bufferstack[bufferstackidx].bufferstate);
1399         if(bufferstack[bufferstackidx].should_pop)
1400         {
1401                 if(yy_current_state() == pp_macexp)
1402                         macro_add_expansion();
1403                 else
1404                         pp_internal_error(__FILE__, __LINE__, "Pop buffer and state without macro expansion state");
1405                 yy_pop_state();
1406         }
1408         return &bufferstack[bufferstackidx];
1413  *-------------------------------------------------------------------------
1414  * Macro nestng support
1415  *-------------------------------------------------------------------------
1416  */
1417 static void push_macro(pp_entry_t *ppp)
1419         if(macexpstackidx >= MAXMACEXPSTACK)
1420         {
1421                 ppy_error("Too many nested macros");
1422                 return;
1423         }
1425         macexpstack[macexpstackidx] = pp_xmalloc(sizeof(macexpstack[0][0]));
1426         if(!macexpstack[macexpstackidx])
1427                 return;
1428         memset( macexpstack[macexpstackidx], 0, sizeof(macexpstack[0][0]));
1429         macexpstack[macexpstackidx]->ppp = ppp;
1430         macexpstackidx++;
1433 static macexpstackentry_t *top_macro(void)
1435         return macexpstackidx > 0 ? macexpstack[macexpstackidx-1] : NULL;
1438 static macexpstackentry_t *pop_macro(void)
1440         if(macexpstackidx <= 0)
1441                 pp_internal_error(__FILE__, __LINE__, "Macro expansion stack underflow\n");
1442         return macexpstack[--macexpstackidx];
1445 static void free_macro(macexpstackentry_t *mep)
1447         int i;
1449         for(i = 0; i < mep->nargs; i++)
1450                 free(mep->args[i]);
1451         free(mep->args);
1452         free(mep->nnls);
1453         free(mep->curarg);
1454         free(mep);
1457 static void add_text_to_macro(const char *text, int len)
1459         macexpstackentry_t *mep = top_macro();
1461         assert(mep->ppp->expanding == 0);
1463         if(mep->curargalloc - mep->curargsize <= len+1) /* +1 for '\0' */
1464         {
1465                 char *new_curarg;
1466                 int new_alloc = mep->curargalloc + ((ALLOCBLOCKSIZE > len+1) ? ALLOCBLOCKSIZE : len+1);
1467                 new_curarg = pp_xrealloc(mep->curarg, new_alloc * sizeof(mep->curarg[0]));
1468                 if(!new_curarg)
1469                         return;
1470                 mep->curarg = new_curarg;
1471                 mep->curargalloc = new_alloc;
1472         }
1473         memcpy(mep->curarg + mep->curargsize, text, len);
1474         mep->curargsize += len;
1475         mep->curarg[mep->curargsize] = '\0';
1478 static void macro_add_arg(int last)
1480         int nnl = 0;
1481         char *cptr;
1482         char **new_args, **new_ppargs;
1483         int *new_nnls;
1484         macexpstackentry_t *mep = top_macro();
1486         assert(mep->ppp->expanding == 0);
1488         new_args = pp_xrealloc(mep->args, (mep->nargs+1) * sizeof(mep->args[0]));
1489         if(!new_args)
1490                 return;
1491         mep->args = new_args;
1493         new_ppargs = pp_xrealloc(mep->ppargs, (mep->nargs+1) * sizeof(mep->ppargs[0]));
1494         if(!new_ppargs)
1495                 return;
1496         mep->ppargs = new_ppargs;
1498         new_nnls = pp_xrealloc(mep->nnls, (mep->nargs+1) * sizeof(mep->nnls[0]));
1499         if(!new_nnls)
1500                 return;
1501         mep->nnls = new_nnls;
1503         mep->args[mep->nargs] = pp_xstrdup(mep->curarg ? mep->curarg : "");
1504         if(!mep->args[mep->nargs])
1505                 return;
1506         cptr = mep->args[mep->nargs]-1;
1507         while((cptr = strchr(cptr+1, '\n')))
1508         {
1509                 nnl++;
1510         }
1511         mep->nnls[mep->nargs] = nnl;
1512         mep->nargs++;
1513         free(mep->curarg);
1514         mep->curargalloc = mep->curargsize = 0;
1515         mep->curarg = NULL;
1517         if(pp_flex_debug)
1518                 fprintf(stderr, "macro_add_arg: %s:%d: %d -> '%s'\n",
1519                         pp_status.input,
1520                         pp_status.line_number,
1521                         mep->nargs-1,
1522                         mep->args[mep->nargs-1]);
1524         /* Each macro argument must be expanded to cope with stingize */
1525         if(last || mep->args[mep->nargs-1][0])
1526         {
1527                 yy_push_state(pp_macexp);
1528                 push_buffer(NULL, NULL, NULL, last ? 2 : 1);
1529                 yy_scan_string(mep->args[mep->nargs-1]);
1530                 /*mep->bufferstackidx = bufferstackidx;  But not nested! */
1531         }
1534 static void macro_add_expansion(void)
1536         macexpstackentry_t *mep = top_macro();
1538         assert(mep->ppp->expanding == 0);
1540         mep->ppargs[mep->nargs-1] = pp_xstrdup(mep->curarg ? mep->curarg : "");
1541         free(mep->curarg);
1542         mep->curargalloc = mep->curargsize = 0;
1543         mep->curarg = NULL;
1545         if(pp_flex_debug)
1546                 fprintf(stderr, "macro_add_expansion: %s:%d: %d -> '%s'\n",
1547                         pp_status.input,
1548                         pp_status.line_number,
1549                         mep->nargs-1,
1550                         mep->ppargs[mep->nargs-1] ? mep->ppargs[mep->nargs-1] : "");
1555  *-------------------------------------------------------------------------
1556  * Output management
1557  *-------------------------------------------------------------------------
1558  */
1559 static void put_buffer(const char *s, int len)
1561         if(top_macro())
1562                 add_text_to_macro(s, len);
1563         else
1564                 fwrite(s, 1, len, ppy_out);
1569  *-------------------------------------------------------------------------
1570  * Include management
1571  *-------------------------------------------------------------------------
1572  */
1573 void pp_do_include(char *fname, int type)
1575         char *newpath;
1576         int n;
1577         includelogicentry_t *iep;
1578         void *fp;
1580         if(!fname)
1581                 return;
1583         for(iep = pp_includelogiclist; iep; iep = iep->next)
1584         {
1585                 if(!strcmp(iep->filename, fname))
1586                 {
1587                         /*
1588                          * We are done. The file was included before.
1589                          * If the define was deleted, then this entry would have
1590                          * been deleted too.
1591                          */
1592                         free(fname);
1593                         return;
1594                 }
1595         }
1597         n = strlen(fname);
1599         if(n <= 2)
1600         {
1601                 ppy_error("Empty include filename");
1602                 free(fname);
1603                 return;
1604         }
1606         /* Undo the effect of the quotation */
1607         fname[n-1] = '\0';
1609         if((fp = pp_open_include(fname+1, type, pp_status.input, &newpath)) == NULL)
1610         {
1611                 ppy_error("Unable to open include file %s", fname+1);
1612                 free(fname);
1613                 return;
1614         }
1616         fname[n-1] = *fname;    /* Redo the quotes */
1617         push_buffer(NULL, newpath, fname, 0);
1618         pp_incl_state.seen_junk = 0;
1619         pp_incl_state.state = 0;
1620         pp_incl_state.ppp = NULL;
1622         if(pp_status.debug)
1623                 fprintf(stderr, "pp_do_include: %s:%d: include_state=%d, include_ifdepth=%d\n",
1624                         pp_status.input, pp_status.line_number, pp_incl_state.state, pp_incl_state.ifdepth);
1625         pp_status.file = fp;
1626         ppy__switch_to_buffer(ppy__create_buffer(NULL, YY_BUF_SIZE));
1628         pp_writestring("# 1 \"%s\" 1%s\n", newpath, type ? "" : " 3");
1632  *-------------------------------------------------------------------------
1633  * Push/pop preprocessor ignore state when processing conditionals
1634  * which are false.
1635  *-------------------------------------------------------------------------
1636  */
1637 void pp_push_ignore_state(void)
1639         yy_push_state(pp_ignore);
1642 void pp_pop_ignore_state(void)
1644         yy_pop_state();