2 * Wrc preprocessor lexical analysis
4 * Copyright 1999-2000 Bertho A. Stultiens (BS)
6 * 24-Apr-2000 BS - Started from scratch to restructure everything
7 * and reintegrate the source into the wine-tree.
8 * 04-Jan-2000 BS - Added comments about the lexicographical
9 * grammar to give some insight in the complexity.
10 * 28-Dec-1999 BS - Eliminated backing-up of the flexer by running
11 * `flex -b' on the source. This results in some
12 * weirdo extra rules, but a much faster scanner.
13 * 23-Dec-1999 BS - Started this file
15 *-------------------------------------------------------------------------
16 * The preprocessor's lexographical grammar (approximately):
18 * pp := {ws} # {ws} if {ws} {expr} {ws} \n
19 * | {ws} # {ws} ifdef {ws} {id} {ws} \n
20 * | {ws} # {ws} ifndef {ws} {id} {ws} \n
21 * | {ws} # {ws} elif {ws} {expr} {ws} \n
22 * | {ws} # {ws} else {ws} \n
23 * | {ws} # {ws} endif {ws} \n
24 * | {ws} # {ws} include {ws} < {anytext} > \n
25 * | {ws} # {ws} include {ws} " {anytext} " \n
26 * | {ws} # {ws} define {ws} {anytext} \n
27 * | {ws} # {ws} define( {arglist} ) {ws} {expansion} \n
28 * | {ws} # {ws} pragma {ws} {anytext} \n
29 * | {ws} # {ws} ident {ws} {anytext} \n
30 * | {ws} # {ws} error {ws} {anytext} \n
31 * | {ws} # {ws} warning {ws} {anytext} \n
32 * | {ws} # {ws} line {ws} " {anytext} " {number} \n
33 * | {ws} # {ws} {number} " {anytext} " {number} [{number} [{number}]] \n
38 * expr := {expr} [+-*%^/|&] {expr}
39 * | {expr} {logor|logand} {expr}
41 * | {expr} ? {expr} : {expr}
47 * id := [a-zA-Z_][a-zA-Z0-9_]*
49 * anytext := [^\n]* (see note)
54 * | {arglist} , {id} ...
59 * | {anytext} ## {anytext}
63 * Note: "anytext" is not always "[^\n]*". This is because the
64 * trailing context must be considered as well.
66 * The only certain assumption for the preprocessor to make is that
67 * directives start at the beginning of the line, followed by a '#'
68 * and end with a newline.
69 * Any directive may be suffixed with a line-continuation. Also
70 * classical comment / *...* / (note: no comments within comments,
71 * therefore spaces) is considered to be a line-continuation
72 * (according to gcc and egcs AFAIK, ANSI is a bit vague).
73 * Comments have not been added to the above grammer for simplicity
74 * reasons. However, it is allowed to enter comment anywhere within
75 * the directives as long as they do not interfere with the context.
76 * All comments are considered to be deletable whitespace (both
77 * classical form "/ *...* /" and C++ form "//...\n").
79 * All recursive scans, except for macro-expansion, are done by the
80 * parser, whereas the simple state transitions of non-recursive
81 * directives are done in the scanner. This results in the many
82 * exclusive start-conditions of the scanner.
84 * Macro expansions are slightly more difficult because they have to
85 * prescan the arguments. Parameter substitution is literal if the
86 * substitution is # or ## (either side). This enables new identifiers
87 * to be created (see 'info cpp' node Macro|Pitfalls|Prescan for more
90 * FIXME: Variable macro parameters is recognized, but not yet
91 * expanded. I have to reread the ANSI standard on the subject (yes,
94 * The following special defines are supported:
95 * __FILE__ -> "thissource.c"
97 * __DATE__ -> "May 1 2000"
98 * __TIME__ -> "23:59:59"
99 * These macros expand, as expected, into their ANSI defined values.
101 * The same include prevention is implemented as gcc and egcs does.
102 * This results in faster processing because we do not read the text
103 * at all. Some wine-sources attempt to include the same file 4 or 5
104 * times. This strategy also saves a lot blank output-lines, which in
105 * its turn improves the real resource scanner/parser.
110 * Special flex options and exclusive scanner start-conditions
113 %option never-interactive
137 cident [a-zA-Z_][0-9a-zA-Z_]*
138 ul [uUlL]|[uUlL][lL]|[lL][uU]|[lL][lL][uU]|[uU][lL][lL]|[lL][uU][lL]
156 * Make sure that we are running an appropriate version of flex.
158 #if !defined(YY_FLEX_MAJOR_VERSION) || (1000 * YY_FLEX_MAJOR_VERSION + YY_FLEX_MINOR_VERSION < 2005)
159 #error Must use flex version 2.5.1 or higher (yy_scan_* routines are required).
162 #define YY_USE_PROTOS
164 #define YY_READ_BUF_SIZE 65536 /* So we read most of a file at once */
166 #define yy_current_state() YY_START
167 #define yy_pp_state(x) yy_pop_state(); yy_push_state(x)
170 * Always update the current character position within a line
172 #define YY_USER_ACTION char_number+=ppleng;
175 * Buffer management for includes and expansions
177 #define MAXBUFFERSTACK 128 /* Nesting more than 128 includes or macro expansion textss is insane */
179 typedef struct bufferstackentry {
180 YY_BUFFER_STATE bufferstate; /* Buffer to switch back to */
181 pp_entry_t *define; /* Points to expanding define or NULL if handling includes */
182 int line_number; /* Line that we were handling */
183 int char_number; /* The current position on that line */
184 char *filename; /* Filename that we were handling */
185 int if_depth; /* How many #if:s deep to check matching #endif:s */
186 int ncontinuations; /* Remember the continuation state */
187 int should_pop; /* Set if we must pop the start-state on EOF */
188 /* Include management */
191 char *include_filename;
195 } bufferstackentry_t;
197 #define ALLOCBLOCKSIZE (1 << 10) /* Allocate these chunks at a time for string-buffers */
200 * Macro expansion nesting
201 * We need the stack to handle expansions while scanning
202 * a macro's arguments. The TOS must always be the macro
203 * that receives the current expansion from the scanner.
205 #define MAXMACEXPSTACK 128 /* Nesting more than 128 macro expansions is insane */
207 typedef struct macexpstackentry {
208 pp_entry_t *ppp; /* This macro we are scanning */
209 char **args; /* With these arguments */
210 char **ppargs; /* Resulting in these preprocessed arguments */
211 int *nnls; /* Number of newlines per argument */
212 int nargs; /* And this many arguments scanned */
213 int parentheses; /* Nesting level of () */
214 int curargsize; /* Current scanning argument's size */
215 int curargalloc; /* Current scanning argument's block allocated */
216 char *curarg; /* Current scanning argument's content */
217 } macexpstackentry_t;
219 #define MACROPARENTHESES() (top_macro()->parentheses)
224 static void newline(int);
225 static int make_number(int radix, YYSTYPE *val, char *str, int len);
226 static void put_buffer(char *s, int len);
227 /* Buffer management */
228 static void push_buffer(pp_entry_t *ppp, char *filename, char *incname, int pop);
229 static bufferstackentry_t *pop_buffer(void);
230 /* String functions */
231 static void new_string(void);
232 static void add_string(char *str, int len);
233 static char *get_string(void);
234 static void put_string(void);
235 static int string_start(void);
236 /* Macro functions */
237 static void push_macro(pp_entry_t *ppp);
238 static macexpstackentry_t *top_macro(void);
239 static macexpstackentry_t *pop_macro(void);
240 static void free_macro(macexpstackentry_t *mep);
241 static void add_text_to_macro(char *text, int len);
242 static void macro_add_arg(int last);
243 static void macro_add_expansion(void);
245 static void expand_special(pp_entry_t *ppp);
246 static void expand_define(pp_entry_t *ppp);
247 static void expand_macro(macexpstackentry_t *mep);
252 static int ncontinuations;
254 static int strbuf_idx = 0;
255 static int strbuf_alloc = 0;
256 static char *strbuffer = NULL;
257 static int str_startline;
259 static macexpstackentry_t *macexpstack[MAXMACEXPSTACK];
260 static int macexpstackidx = 0;
262 static bufferstackentry_t bufferstack[MAXBUFFERSTACK];
263 static int bufferstackidx = 0;
265 static int pass_data=1;
271 * Trace the include files to prevent double reading.
272 * This save 20..30% of processing time for most stuff
273 * that uses complex includes.
275 * -1 Don't track or seen junk
276 * 0 New include, waiting for "#ifndef __xxx_h"
277 * 1 Seen #ifndef, waiting for "#define __xxx_h ..."
278 * 2 Seen #endif, waiting for EOF
280 int include_state = -1;
281 char *include_ppp = NULL; /* The define to be set from the #ifndef */
282 int include_ifdepth = 0; /* The level of ifs at the #ifdef */
283 int seen_junk = 0; /* Set when junk is seen */
284 includelogicentry_t *includelogiclist = NULL;
289 **************************************************************************
290 * The scanner starts here
291 **************************************************************************
296 * Catch line-continuations.
297 * Note: Gcc keeps the line-continuations in, for example, strings
298 * intact. However, I prefer to remove them all so that the next
299 * scanner will not need to reduce the continuation state.
301 * <*>\\\n newline(0);
305 * Detect the leading # of a preprocessor directive.
307 <INITIAL,pp_ignore>^{ws}*# seen_junk++; yy_push_state(pp_pp);
310 * Scan for the preprocessor directives
312 <pp_pp>{ws}*include{ws}* if(yy_top_state() != pp_ignore) {yy_pp_state(pp_inc); return tINCLUDE;} else {yy_pp_state(pp_eol);}
313 <pp_pp>{ws}*define{ws}* yy_pp_state(yy_current_state() != pp_ignore ? pp_def : pp_eol);
314 <pp_pp>{ws}*error{ws}* yy_pp_state(pp_eol); if(yy_top_state() != pp_ignore) return tERROR;
315 <pp_pp>{ws}*warning{ws}* yy_pp_state(pp_eol); if(yy_top_state() != pp_ignore) return tWARNING;
316 <pp_pp>{ws}*pragma{ws}* yy_pp_state(pp_eol); if(yy_top_state() != pp_ignore) return tPRAGMA;
317 <pp_pp>{ws}*ident{ws}* yy_pp_state(pp_eol); if(yy_top_state() != pp_ignore) return tPPIDENT;
318 <pp_pp>{ws}*undef{ws}* if(yy_top_state() != pp_ignore) {yy_pp_state(pp_ifd); return tUNDEF;} else {yy_pp_state(pp_eol);}
319 <pp_pp>{ws}*ifdef{ws}* yy_pp_state(pp_ifd); return tIFDEF;
320 <pp_pp>{ws}*ifndef{ws}* seen_junk--; yy_pp_state(pp_ifd); return tIFNDEF;
321 <pp_pp>{ws}*if{ws}* yy_pp_state(pp_if); return tIF;
322 <pp_pp>{ws}*elif{ws}* yy_pp_state(pp_if); return tELIF;
323 <pp_pp>{ws}*else{ws}* return tELSE;
324 <pp_pp>{ws}*endif{ws}* return tENDIF;
325 <pp_pp>{ws}*line{ws}* if(yy_top_state() != pp_ignore) {yy_pp_state(pp_line); return tLINE;} else {yy_pp_state(pp_eol);}
326 <pp_pp>{ws}+ if(yy_top_state() != pp_ignore) {yy_pp_state(pp_line); return tGCCLINE;} else {yy_pp_state(pp_eol);}
327 <pp_pp>{ws}*[a-z]+ pperror("Invalid preprocessor token '%s'", pptext);
328 <pp_pp>\r?\n newline(1); yy_pop_state(); return tNL; /* This could be the null-token */
329 <pp_pp>\\\r?\n newline(0);
330 <pp_pp>\\\r? pperror("Preprocessor junk '%s'", pptext);
331 <pp_pp>. return *pptext;
334 * Handle #include and #line
336 <pp_line>[0-9]+ return make_number(10, &pplval, pptext, ppleng);
337 <pp_inc>\< new_string(); add_string(pptext, ppleng); yy_push_state(pp_iqs);
338 <pp_inc,pp_line>\" new_string(); add_string(pptext, ppleng); yy_push_state(pp_dqs);
339 <pp_inc,pp_line>{ws}+ ;
340 <pp_inc,pp_line>\n newline(1); yy_pop_state(); return tNL;
341 <pp_inc,pp_line>\\\r?\n newline(0);
342 <pp_inc,pp_line>(\\\r?)|(.) pperror(yy_current_state() == pp_inc ? "Trailing junk in #include" : "Trailing junk in #line");
345 * Ignore all input when a false clause is parsed
347 <pp_ignore>[^#/\\\n]+ ;
348 <pp_ignore>\n newline(1);
349 <pp_ignore>\\\r?\n newline(0);
350 <pp_ignore>(\\\r?)|(.) ;
353 * Handle #if and #elif.
354 * These require conditionals to be evaluated, but we do not
355 * want to jam the scanner normally when we see these tokens.
356 * Note: tIDENT is handled below.
359 <pp_if>0[0-7]*{ul}? return make_number(8, &pplval, pptext, ppleng);
360 <pp_if>0[0-7]*[8-9]+{ul}? pperror("Invalid octal digit");
361 <pp_if>[1-9][0-9]*{ul}? return make_number(10, &pplval, pptext, ppleng);
362 <pp_if>0[xX][0-9a-fA-F]+{ul}? return make_number(16, &pplval, pptext, ppleng);
363 <pp_if>0[xX] pperror("Invalid hex number");
364 <pp_if>defined yy_push_state(pp_defined); return tDEFINED;
365 <pp_if>"<<" return tLSHIFT;
366 <pp_if>">>" return tRSHIFT;
367 <pp_if>"&&" return tLOGAND;
368 <pp_if>"||" return tLOGOR;
369 <pp_if>"==" return tEQ;
370 <pp_if>"!=" return tNE;
371 <pp_if>"<=" return tLTE;
372 <pp_if>">=" return tGTE;
373 <pp_if>\n newline(1); yy_pop_state(); return tNL;
374 <pp_if>\\\r?\n newline(0);
375 <pp_if>\\\r? pperror("Junk in conditional expression");
377 <pp_if>\' new_string(); add_string(pptext, ppleng); yy_push_state(pp_sqs);
378 <pp_if>\" pperror("String constants not allowed in conditionals");
379 <pp_if>. return *pptext;
382 * Handle #ifdef, #ifndef and #undef
383 * to get only an untranslated/unexpanded identifier
385 <pp_ifd>{cident} pplval.cptr = xstrdup(pptext); return tIDENT;
387 <pp_ifd>\n newline(1); yy_pop_state(); return tNL;
388 <pp_ifd>\\\r?\n newline(0);
389 <pp_ifd>(\\\r?)|(.) pperror("Identifier expected");
392 * Handle the special 'defined' keyword.
393 * This is necessary to get the identifier prior to any
396 <pp_defined>{cident} yy_pop_state(); pplval.cptr = xstrdup(pptext); return tIDENT;
398 <pp_defined>(\()|(\)) return *pptext;
399 <pp_defined>\\\r?\n newline(0);
400 <pp_defined>(\\.)|(\n)|(.) pperror("Identifier expected");
403 * Handle #error, #warning, #pragma and #ident.
404 * Pass everything literally to the parser, which
405 * will act appropriately.
406 * Comments are stripped from the literal text.
408 <pp_eol>[^/\\\n]+ if(yy_top_state() != pp_ignore) { pplval.cptr = xstrdup(pptext); return tLITERAL; }
409 <pp_eol>\/[^/\\\n*]* if(yy_top_state() != pp_ignore) { pplval.cptr = xstrdup(pptext); return tLITERAL; }
410 <pp_eol>(\\\r?)|(\/[^/*]) if(yy_top_state() != pp_ignore) { pplval.cptr = xstrdup(pptext); return tLITERAL; }
411 <pp_eol>\n newline(1); yy_pop_state(); if(yy_current_state() != pp_ignore) { return tNL; }
412 <pp_eol>\\\r?\n newline(0);
415 * Handle left side of #define
417 <pp_def>{cident}\( pplval.cptr = xstrdup(pptext); pplval.cptr[ppleng-1] = '\0'; yy_pp_state(pp_macro); return tMACRO;
418 <pp_def>{cident} pplval.cptr = xstrdup(pptext); yy_pp_state(pp_define); return tDEFINE;
420 <pp_def>\\\r?\n newline(0);
421 <pp_def>(\\\r?)|(\n)|(.) perror("Identifier expected");
424 * Scan the substitution of a define
426 <pp_define>[^'"/\\\n]+ pplval.cptr = xstrdup(pptext); return tLITERAL;
427 <pp_define>(\\\r?)|(\/[^/*]) pplval.cptr = xstrdup(pptext); return tLITERAL;
428 <pp_define>\\\r?\n{ws}+ newline(0); pplval.cptr = xstrdup(" "); return tLITERAL;
429 <pp_define>\\\r?\n newline(0);
430 <pp_define>\n newline(1); yy_pop_state(); return tNL;
431 <pp_define>\' new_string(); add_string(pptext, ppleng); yy_push_state(pp_sqs);
432 <pp_define>\" new_string(); add_string(pptext, ppleng); yy_push_state(pp_dqs);
435 * Scan the definition macro arguments
437 <pp_macro>\){ws}* yy_pp_state(pp_mbody); return tMACROEND;
439 <pp_macro>{cident} pplval.cptr = xstrdup(pptext); return tIDENT;
440 <pp_macro>, return ',';
441 <pp_macro>"..." return tELIPSIS;
442 <pp_macro>(\\\r?)|(\n)|(.)|(\.\.?) pperror("Argument identifier expected");
443 <pp_macro>\\\r?\n newline(0);
446 * Scan the substitution of a macro
448 <pp_mbody>[^a-zA-Z0-9'"#/\\\n]+ pplval.cptr = xstrdup(pptext); return tLITERAL;
449 <pp_mbody>{cident} pplval.cptr = xstrdup(pptext); return tIDENT;
450 <pp_mbody>\#\# return tCONCAT;
451 <pp_mbody>\# return tSTRINGIZE;
452 <pp_mbody>[0-9][^'"#/\\\n]* pplval.cptr = xstrdup(pptext); return tLITERAL;
453 <pp_mbody>(\\\r?)|(\/[^/*'"#\\\n]*) pplval.cptr = xstrdup(pptext); return tLITERAL;
454 <pp_mbody>\\\r?\n{ws}+ newline(0); pplval.cptr = xstrdup(" "); return tLITERAL;
455 <pp_mbody>\\\r?\n newline(0);
456 <pp_mbody>\n newline(1); yy_pop_state(); return tNL;
457 <pp_mbody>\' new_string(); add_string(pptext, ppleng); yy_push_state(pp_sqs);
458 <pp_mbody>\" new_string(); add_string(pptext, ppleng); yy_push_state(pp_dqs);
461 * Macro expansion text scanning.
462 * This state is active just after the identifier is scanned
463 * that triggers an expansion. We *must* delete the leading
464 * whitespace before we can start scanning for arguments.
466 * If we do not see a '(' as next trailing token, then we have
467 * a false alarm. We just continue with a nose-bleed...
469 <pp_macign>{ws}*/\( yy_pp_state(pp_macscan);
471 if(yy_top_state() != pp_macscan)
474 <pp_macign>{ws}*\\\r?\n newline(0);
475 <pp_macign>{ws}+|{ws}*\\\r?|. {
476 macexpstackentry_t *mac = pop_macro();
478 put_buffer(mac->ppp->ident, strlen(mac->ppp->ident));
479 put_buffer(pptext, ppleng);
484 * Macro expansion argument text scanning.
485 * This state is active when a macro's arguments are being read for expansion.
488 if(++MACROPARENTHESES() > 1)
489 add_text_to_macro(pptext, ppleng);
492 if(--MACROPARENTHESES() == 0)
498 add_text_to_macro(pptext, ppleng);
501 if(MACROPARENTHESES() > 1)
502 add_text_to_macro(pptext, ppleng);
506 <pp_macscan>\" new_string(); add_string(pptext, ppleng); yy_push_state(pp_dqs);
507 <pp_macscan>\' new_string(); add_string(pptext, ppleng); yy_push_state(pp_sqs);
508 <pp_macscan>"/*" yy_push_state(pp_comment); add_text_to_macro(" ", 1);
509 <pp_macscan>\n line_number++; char_number = 1; add_text_to_macro(pptext, ppleng);
510 <pp_macscan>([^/(),\\\n"']+)|(\/[^/*(),\\\n'"]*)|(\\\r?)|(.) add_text_to_macro(pptext, ppleng);
511 <pp_macscan>\\\r?\n newline(0);
514 * Comment handling (almost all start-conditions)
516 <INITIAL,pp_pp,pp_ignore,pp_eol,pp_inc,pp_if,pp_ifd,pp_defined,pp_def,pp_define,pp_macro,pp_mbody,RCINCL>"/*" yy_push_state(pp_comment);
517 <pp_comment>[^*\n]*|"*"+[^*/\n]* ;
518 <pp_comment>\n newline(0);
519 <pp_comment>"*"+"/" yy_pop_state();
522 * Remove C++ style comment (almost all start-conditions)
524 <INITIAL,pp_pp,pp_ignore,pp_eol,pp_inc,pp_if,pp_ifd,pp_defined,pp_def,pp_define,pp_macro,pp_mbody,pp_macscan,RCINCL>"//"[^\n]* {
525 if(pptext[ppleng-1] == '\\')
526 ppwarning("C++ style comment ends with an escaped newline (escape ignored)");
530 * Single, double and <> quoted constants
532 <INITIAL,pp_macexp>\" seen_junk++; new_string(); add_string(pptext, ppleng); yy_push_state(pp_dqs);
533 <INITIAL,pp_macexp>\' seen_junk++; new_string(); add_string(pptext, ppleng); yy_push_state(pp_sqs);
534 <pp_dqs>[^"\\\n]+ add_string(pptext, ppleng);
536 add_string(pptext, ppleng);
538 switch(yy_current_state())
546 if (yy_current_state()==RCINCL) yy_pop_state();
547 pplval.cptr = get_string();
553 <pp_sqs>[^'\\\n]+ add_string(pptext, ppleng);
555 add_string(pptext, ppleng);
557 switch(yy_current_state())
562 pplval.cptr = get_string();
568 <pp_iqs>[^\>\\\n]+ add_string(pptext, ppleng);
570 add_string(pptext, ppleng);
572 pplval.cptr = get_string();
577 * This is tricky; we need to remove the line-continuation
578 * from preprocessor strings, but OTOH retain them in all
579 * other strings. This is because the resource grammar is
580 * even more braindead than initially analysed and line-
581 * continuations in strings introduce, sigh, newlines in
582 * the output. There goes the concept of non-breaking, non-
583 * spacing whitespace.
585 switch(yy_top_state())
595 add_string(pptext, ppleng);
599 <pp_iqs,pp_dqs,pp_sqs>\\. add_string(pptext, ppleng);
600 <pp_iqs,pp_dqs,pp_sqs>\n {
602 add_string(pptext, ppleng);
603 ppwarning("Newline in string constant encounterd (started line %d)", string_start());
607 * Identifier scanning
609 <INITIAL,pp_if,pp_inc,pp_macexp>{cident} {
612 if(!(ppp = pplookup(pptext)))
614 if(yy_current_state() == pp_inc)
615 pperror("Expected include filename");
617 if(yy_current_state() == pp_if)
619 pplval.cptr = xstrdup(pptext);
623 if((yy_current_state()==INITIAL) && (strcasecmp(pptext,"RCINCLUDE")==0)){
624 yy_push_state(RCINCL);
627 else put_buffer(pptext, ppleng);
630 else if(!ppp->expanding)
641 yy_push_state(pp_macign);
645 internal_error(__FILE__, __LINE__, "Invalid define type %d\n", ppp->type);
651 * Everything else that needs to be passed and
652 * newline and continuation handling
654 <INITIAL,pp_macexp>[^a-zA-Z_#'"/\\\n \r\t\f\v]+|(\/|\\)[^a-zA-Z_/*'"\\\n \r\t\v\f]* seen_junk++; put_buffer(pptext, ppleng);
655 <INITIAL,pp_macexp>{ws}+ put_buffer(pptext, ppleng);
656 <INITIAL>\n newline(1);
657 <INITIAL>\\\r?\n newline(0);
658 <INITIAL>\\\r? seen_junk++; put_buffer(pptext, ppleng);
661 * Special catcher for macro argmument expansion to prevent
662 * newlines to propagate to the output or admin.
664 <pp_macexp>(\n)|(.)|(\\\r?(\n|.)) put_buffer(pptext, ppleng);
666 <RCINCL>[A-Za-z0-9_\.\\/]+ {
667 pplval.cptr=xstrdup(pptext);
669 return tRCINCLUDEPATH;
675 new_string(); add_string(pptext,ppleng);yy_push_state(pp_dqs);
679 * This is a 'catch-all' rule to discover errors in the scanner
680 * in an orderly manner.
682 <*>. seen_junk++; ppwarning("Unmatched text '%c' (0x%02x); please report\n", isprint(*pptext & 0xff) ? *pptext : ' ', *pptext);
685 YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
686 bufferstackentry_t *bep = pop_buffer();
688 if((!bep && get_if_depth()) || (bep && get_if_depth() != bep->if_depth))
689 ppwarning("Unmatched #if/#endif at end of file");
693 if(YY_START != INITIAL)
694 pperror("Unexpected end of file during preprocessing");
697 else if(bep->should_pop == 2)
699 macexpstackentry_t *mac;
708 **************************************************************************
710 **************************************************************************
722 *-------------------------------------------------------------------------
723 * Output newlines or set them as continuations
725 * Input: -1 - Don't count this one, but update local position (see pp_dqs)
726 * 0 - Line-continuation seen and cache output
727 * 1 - Newline seen and flush output
728 *-------------------------------------------------------------------------
730 static void newline(int dowrite)
741 for(;ncontinuations; ncontinuations--)
748 *-------------------------------------------------------------------------
749 * Make a number out of an any-base and suffixed string
751 * Possible number extensions:
754 * - "LL" long long int
756 * - "UL" unsigned long int
757 * - "ULL" unsigned long long int
758 * - "LU" unsigned long int
759 * - "LLU" unsigned long long int
763 * The sizes of resulting 'int' and 'long' are compiler specific.
764 * I depend on sizeof(int) > 2 here (although a relatively safe
766 * Long longs are not yet implemented because this is very compiler
767 * specific and I don't want to think too much about the problems.
769 *-------------------------------------------------------------------------
771 static int make_number(int radix, YYSTYPE *val, char *str, int len)
779 ext[2] = toupper(str[len-1]);
780 ext[1] = len > 1 ? toupper(str[len-2]) : ' ';
781 ext[0] = len > 2 ? toupper(str[len-3]) : ' ';
783 if(!strcmp(ext, "LUL"))
784 pperror("Invalid constant suffix");
785 else if(!strcmp(ext, "LLU") || !strcmp(ext, "ULL"))
790 else if(!strcmp(ext+1, "LU") || !strcmp(ext+1, "UL"))
795 else if(!strcmp(ext+1, "LL"))
799 else if(!strcmp(ext+2, "L"))
803 else if(!strcmp(ext+2, "U"))
809 internal_error(__FILE__, __LINE__, "long long constants not implemented yet");
813 val->ulong = strtoul(str, NULL, radix);
816 else if(!is_u && is_l)
818 val->slong = strtol(str, NULL, radix);
821 else if(is_u && !is_l)
823 val->uint = (unsigned int)strtoul(str, NULL, radix);
824 if(!win32 && val->uint > 65535)
826 pperror("Constant overflow");
831 /* Else it must be an int... */
832 val->sint = (int)strtol(str, NULL, radix);
833 if(!win32 && (val->sint < -32768 || val->sint > 32768))
836 * Note: test must be > 32768 because unary minus
837 * is handled as an expression! This can result in
838 * failure and must be checked in the parser.
840 pperror("Constant overflow");
847 *-------------------------------------------------------------------------
848 * Macro and define expansion support
850 * FIXME: Variable macro arguments.
851 *-------------------------------------------------------------------------
853 static void expand_special(pp_entry_t *ppp)
856 static char *buf = NULL;
858 assert(ppp->type == def_special);
860 if(!strcmp(ppp->ident, "__LINE__"))
862 dbgtext = "def_special(__LINE__)";
863 buf = xrealloc(buf, 32);
864 sprintf(buf, "%d", line_number);
866 else if(!strcmp(ppp->ident, "__FILE__"))
868 dbgtext = "def_special(__FILE__)";
869 buf = xrealloc(buf, strlen(input_name) + 3);
870 sprintf(buf, "\"%s\"", input_name);
872 else if(!strcmp(ppp->ident, "__DATE__"))
874 dbgtext = "def_special(__DATE__)";
875 buf = xrealloc(buf, 32);
876 strftime(buf, 32, "\"%b %d %Y\"", localtime(&now));
878 else if(!strcmp(ppp->ident, "__TIME__"))
880 dbgtext = "def_special(__TIME__)";
881 buf = xrealloc(buf, 32);
882 strftime(buf, 32, "\"%H:%M:%S\"", localtime(&now));
885 internal_error(__FILE__, __LINE__, "Special macro '%s' not found...\n", ppp->ident);
887 if(debuglevel & DEBUGLEVEL_PPLEX)
888 fprintf(stderr, "expand_special(%d): %s:%d: '%s' -> '%s'\n",
897 push_buffer(ppp, NULL, NULL, 0);
902 static void expand_define(pp_entry_t *ppp)
904 assert(ppp->type == def_define);
906 if(debuglevel & DEBUGLEVEL_PPLEX)
907 fprintf(stderr, "expand_define(%d): %s:%d: '%s' -> '%s'\n",
913 if(ppp->subst.text && ppp->subst.text[0])
915 push_buffer(ppp, NULL, NULL, 0);
916 yy_scan_string(ppp->subst.text);
920 static int curdef_idx = 0;
921 static int curdef_alloc = 0;
922 static char *curdef_text = NULL;
924 static void add_text(char *str, int len)
928 if(curdef_idx >= curdef_alloc || curdef_alloc - curdef_idx < len)
930 curdef_alloc += (len + ALLOCBLOCKSIZE-1) & ~(ALLOCBLOCKSIZE-1);
931 curdef_text = xrealloc(curdef_text, curdef_alloc * sizeof(curdef_text[0]));
932 if(curdef_alloc > 65536)
933 ppwarning("Reallocating macro-expansion buffer larger than 64kB");
935 memcpy(&curdef_text[curdef_idx], str, len);
939 static mtext_t *add_expand_text(mtext_t *mtp, macexpstackentry_t *mep, int *nnl)
952 if(debuglevel & DEBUGLEVEL_PPLEX)
953 fprintf(stderr, "add_expand_text: exp_text: '%s'\n", mtp->subst.text);
954 add_text(mtp->subst.text, strlen(mtp->subst.text));
958 if(debuglevel & DEBUGLEVEL_PPLEX)
959 fprintf(stderr, "add_expand_text: exp_stringize(%d): '%s'\n",
961 mep->args[mtp->subst.argidx]);
962 cptr = mep->args[mtp->subst.argidx];
966 if(*cptr == '"' || *cptr == '\\')
975 if(debuglevel & DEBUGLEVEL_PPLEX)
976 fprintf(stderr, "add_expand_text: exp_concat\n");
977 /* Remove trailing whitespace from current expansion text */
980 if(isspace(curdef_text[curdef_idx-1] & 0xff))
985 /* tag current position and recursively expand the next part */
987 mtp = add_expand_text(mtp->next, mep, nnl);
989 /* Now get rid of the leading space of the expansion */
990 cptr = &curdef_text[tag];
991 n = curdef_idx - tag;
994 if(isspace(*cptr & 0xff))
1002 if(cptr != &curdef_text[tag])
1004 memmove(&curdef_text[tag], cptr, n);
1005 curdef_idx -= (curdef_idx - tag) - n;
1010 if((mtp->next && mtp->next->type == exp_concat) || (mtp->prev && mtp->prev->type == exp_concat))
1011 exp = mep->args[mtp->subst.argidx];
1013 exp = mep->ppargs[mtp->subst.argidx];
1016 add_text(exp, strlen(exp));
1017 *nnl -= mep->nnls[mtp->subst.argidx];
1018 cptr = strchr(exp, '\n');
1022 cptr = strchr(cptr+1, '\n');
1024 mep->nnls[mtp->subst.argidx] = 0;
1026 if(debuglevel & DEBUGLEVEL_PPLEX)
1027 fprintf(stderr, "add_expand_text: exp_subst(%d): '%s'\n", mtp->subst.argidx, exp);
1031 internal_error(__FILE__, __LINE__, "Invalid expansion type (%d) in macro expansion\n", mtp->type);
1036 static void expand_macro(macexpstackentry_t *mep)
1042 pp_entry_t *ppp = mep->ppp;
1043 int nargs = mep->nargs;
1045 assert(ppp->type == def_macro);
1046 assert(ppp->expanding == 0);
1048 if((ppp->nargs >= 0 && nargs != ppp->nargs) || (ppp->nargs < 0 && nargs < -ppp->nargs))
1049 pperror("Too %s macro arguments (%d)", nargs < abs(ppp->nargs) ? "few" : "many", nargs);
1051 for(n = 0; n < nargs; n++)
1052 nnl += mep->nnls[n];
1054 if(debuglevel & DEBUGLEVEL_PPLEX)
1055 fprintf(stderr, "expand_macro(%d): %s:%d: '%s'(%d,%d) -> ...\n",
1065 for(mtp = ppp->subst.mtext; mtp; mtp = mtp->next)
1067 if(!(mtp = add_expand_text(mtp, mep, &nnl)))
1071 for(n = 0; n < nnl; n++)
1074 /* To make sure there is room and termination (see below) */
1077 /* Strip trailing whitespace from expansion */
1078 for(k = curdef_idx, cptr = &curdef_text[curdef_idx-1]; k > 0; k--, cptr--)
1080 if(!isspace(*cptr & 0xff))
1085 * We must add *one* whitespace to make sure that there
1086 * is a token-seperation after the expansion.
1092 /* Strip leading whitespace from expansion */
1093 for(n = 0, cptr = curdef_text; n < k; n++, cptr++)
1095 if(!isspace(*cptr & 0xff))
1101 if(debuglevel & DEBUGLEVEL_PPLEX)
1102 fprintf(stderr, "expand_text: '%s'\n", curdef_text + n);
1103 push_buffer(ppp, NULL, NULL, 0);
1104 /*yy_scan_bytes(curdef_text + n, k - n);*/
1105 yy_scan_string(curdef_text + n);
1110 *-------------------------------------------------------------------------
1111 * String collection routines
1112 *-------------------------------------------------------------------------
1114 static void new_string(void)
1118 ppwarning("new_string: strbuf_idx != 0");
1121 str_startline = line_number;
1124 static void add_string(char *str, int len)
1128 if(strbuf_idx >= strbuf_alloc || strbuf_alloc - strbuf_idx < len)
1130 strbuf_alloc += (len + ALLOCBLOCKSIZE-1) & ~(ALLOCBLOCKSIZE-1);
1131 strbuffer = xrealloc(strbuffer, strbuf_alloc * sizeof(strbuffer[0]));
1132 if(strbuf_alloc > 65536)
1133 ppwarning("Reallocating string buffer larger than 64kB");
1135 memcpy(&strbuffer[strbuf_idx], str, len);
1139 static char *get_string(void)
1141 char *str = (char *)xmalloc(strbuf_idx + 1);
1142 memcpy(str, strbuffer, strbuf_idx);
1143 str[strbuf_idx] = '\0';
1150 static void put_string(void)
1152 put_buffer(strbuffer, strbuf_idx);
1158 static int string_start(void)
1160 return str_startline;
1165 *-------------------------------------------------------------------------
1167 *-------------------------------------------------------------------------
1169 static void push_buffer(pp_entry_t *ppp, char *filename, char *incname, int pop)
1172 printf("push_buffer(%d): %p %p %p %d\n", bufferstackidx, ppp, filename, incname, pop);
1173 if(bufferstackidx >= MAXBUFFERSTACK)
1174 internal_error(__FILE__, __LINE__, "Buffer stack overflow");
1176 memset(&bufferstack[bufferstackidx], 0, sizeof(bufferstack[0]));
1177 bufferstack[bufferstackidx].bufferstate = YY_CURRENT_BUFFER;
1178 bufferstack[bufferstackidx].define = ppp;
1179 bufferstack[bufferstackidx].line_number = line_number;
1180 bufferstack[bufferstackidx].char_number = char_number;
1181 bufferstack[bufferstackidx].if_depth = get_if_depth();
1182 bufferstack[bufferstackidx].should_pop = pop;
1183 bufferstack[bufferstackidx].filename = input_name;
1184 bufferstack[bufferstackidx].ncontinuations = ncontinuations;
1185 bufferstack[bufferstackidx].include_state = include_state;
1186 bufferstack[bufferstackidx].include_ppp = include_ppp;
1187 bufferstack[bufferstackidx].include_filename = incname;
1188 bufferstack[bufferstackidx].include_ifdepth = include_ifdepth;
1189 bufferstack[bufferstackidx].seen_junk = seen_junk;
1190 bufferstack[bufferstackidx].pass_data = pass_data;
1196 /* These will track the pperror to the correct file and line */
1199 input_name = filename;
1203 internal_error(__FILE__, __LINE__, "Pushing buffer without knowing where to go to");
1207 static bufferstackentry_t *pop_buffer(void)
1209 if(bufferstackidx < 0)
1210 internal_error(__FILE__, __LINE__, "Bufferstack underflow?");
1212 if(bufferstackidx == 0)
1217 if(bufferstack[bufferstackidx].define)
1218 bufferstack[bufferstackidx].define->expanding = 0;
1221 line_number = bufferstack[bufferstackidx].line_number;
1222 char_number = bufferstack[bufferstackidx].char_number;
1223 input_name = bufferstack[bufferstackidx].filename;
1224 ncontinuations = bufferstack[bufferstackidx].ncontinuations;
1225 if(!bufferstack[bufferstackidx].should_pop)
1228 fprintf(ppout, "# %d \"%s\" 2\n", line_number, input_name);
1230 /* We have EOF, check the include logic */
1231 if(include_state == 2 && !seen_junk && include_ppp)
1233 pp_entry_t *ppp = pplookup(include_ppp);
1236 includelogicentry_t *iep = xmalloc(sizeof(includelogicentry_t));
1239 iep->filename = bufferstack[bufferstackidx].include_filename;
1240 iep->next = includelogiclist;
1242 iep->next->prev = iep;
1243 includelogiclist = iep;
1244 if(debuglevel & DEBUGLEVEL_PPMSG)
1245 fprintf(stderr, "pop_buffer: %s:%d: includelogic added, include_ppp='%s', file='%s'\n", input_name, line_number, include_ppp, iep->filename);
1247 else if(bufferstack[bufferstackidx].include_filename)
1248 free(bufferstack[bufferstackidx].include_filename);
1252 include_state = bufferstack[bufferstackidx].include_state;
1253 include_ppp = bufferstack[bufferstackidx].include_ppp;
1254 include_ifdepth = bufferstack[bufferstackidx].include_ifdepth;
1255 seen_junk = bufferstack[bufferstackidx].seen_junk;
1256 pass_data = bufferstack[bufferstackidx].pass_data;
1262 printf("pop_buffer(%d): %p %p (%d, %d, %d) %p %d\n",
1264 bufferstack[bufferstackidx].bufferstate,
1265 bufferstack[bufferstackidx].define,
1266 bufferstack[bufferstackidx].line_number,
1267 bufferstack[bufferstackidx].char_number,
1268 bufferstack[bufferstackidx].if_depth,
1269 bufferstack[bufferstackidx].filename,
1270 bufferstack[bufferstackidx].should_pop);
1272 pp_switch_to_buffer(bufferstack[bufferstackidx].bufferstate);
1274 if(bufferstack[bufferstackidx].should_pop)
1276 if(yy_current_state() == pp_macexp)
1277 macro_add_expansion();
1279 internal_error(__FILE__, __LINE__, "Pop buffer and state without macro expansion state");
1283 return &bufferstack[bufferstackidx];
1288 *-------------------------------------------------------------------------
1289 * Macro nestng support
1290 *-------------------------------------------------------------------------
1292 static void push_macro(pp_entry_t *ppp)
1294 if(macexpstackidx >= MAXMACEXPSTACK)
1295 pperror("Too many nested macros");
1297 macexpstack[macexpstackidx] = xmalloc(sizeof(macexpstack[0][0]));
1299 macexpstack[macexpstackidx]->ppp = ppp;
1303 static macexpstackentry_t *top_macro(void)
1305 return macexpstackidx > 0 ? macexpstack[macexpstackidx-1] : NULL;
1308 static macexpstackentry_t *pop_macro(void)
1310 if(macexpstackidx <= 0)
1311 internal_error(__FILE__, __LINE__, "Macro expansion stack underflow\n");
1312 return macexpstack[--macexpstackidx];
1315 static void free_macro(macexpstackentry_t *mep)
1319 for(i = 0; i < mep->nargs; i++)
1330 static void add_text_to_macro(char *text, int len)
1332 macexpstackentry_t *mep = top_macro();
1334 assert(mep->ppp->expanding == 0);
1336 if(mep->curargalloc - mep->curargsize <= len+1) /* +1 for '\0' */
1338 mep->curargalloc += MAX(ALLOCBLOCKSIZE, len+1);
1339 mep->curarg = xrealloc(mep->curarg, mep->curargalloc * sizeof(mep->curarg[0]));
1341 memcpy(mep->curarg + mep->curargsize, text, len);
1342 mep->curargsize += len;
1343 mep->curarg[mep->curargsize] = '\0';
1346 static void macro_add_arg(int last)
1350 macexpstackentry_t *mep = top_macro();
1352 assert(mep->ppp->expanding == 0);
1354 mep->args = xrealloc(mep->args, (mep->nargs+1) * sizeof(mep->args[0]));
1355 mep->ppargs = xrealloc(mep->ppargs, (mep->nargs+1) * sizeof(mep->ppargs[0]));
1356 mep->nnls = xrealloc(mep->nnls, (mep->nargs+1) * sizeof(mep->nnls[0]));
1357 mep->args[mep->nargs] = xstrdup(mep->curarg ? mep->curarg : "");
1358 cptr = mep->args[mep->nargs]-1;
1359 while((cptr = strchr(cptr+1, '\n')))
1363 mep->nnls[mep->nargs] = nnl;
1366 mep->curargalloc = mep->curargsize = 0;
1369 if(debuglevel & DEBUGLEVEL_PPLEX)
1370 fprintf(stderr, "macro_add_arg: %s:%d: %d -> '%s'\n",
1374 mep->args[mep->nargs-1]);
1376 /* Each macro argument must be expanded to cope with stingize */
1377 if(last || mep->args[mep->nargs-1][0])
1379 yy_push_state(pp_macexp);
1380 push_buffer(NULL, NULL, NULL, last ? 2 : 1);
1381 yy_scan_string(mep->args[mep->nargs-1]);
1382 /*mep->bufferstackidx = bufferstackidx; But not nested! */
1386 static void macro_add_expansion(void)
1388 macexpstackentry_t *mep = top_macro();
1390 assert(mep->ppp->expanding == 0);
1392 mep->ppargs[mep->nargs-1] = xstrdup(mep->curarg ? mep->curarg : "");
1394 mep->curargalloc = mep->curargsize = 0;
1397 if(debuglevel & DEBUGLEVEL_PPLEX)
1398 fprintf(stderr, "macro_add_expansion: %s:%d: %d -> '%s'\n",
1402 mep->ppargs[mep->nargs-1]);
1407 *-------------------------------------------------------------------------
1409 *-------------------------------------------------------------------------
1411 static void put_buffer(char *s, int len)
1414 add_text_to_macro(s, len);
1417 fwrite(s, 1, len, ppout);
1423 *-------------------------------------------------------------------------
1424 * Include management
1425 *-------------------------------------------------------------------------
1427 int is_c_h_include(char *fname)
1429 int sl=strlen(fname);
1430 if (sl < 2) return 0;
1431 if ((toupper(fname[sl-1])!='H') && (toupper(fname[sl-1])!='C')) return 0;
1432 if (fname[sl-2]!='.') return 0;
1436 void do_include(char *fname, int type)
1440 includelogicentry_t *iep;
1442 for(iep = includelogiclist; iep; iep = iep->next)
1444 if(!strcmp(iep->filename, fname))
1447 * We are done. The file was included before.
1448 * If the define was deleted, then this entry would have
1458 pperror("Empty include filename");
1460 /* Undo the effect of the quotation */
1463 if((ppin = open_include(fname+1, type, &newpath)) == NULL)
1464 pperror("Unable to open include file %s", fname+1);
1466 fname[n-1] = *fname; /* Redo the quotes */
1467 push_buffer(NULL, newpath, fname, 0);
1471 if (is_c_h_include(newpath)) pass_data=0;
1474 if(debuglevel & DEBUGLEVEL_PPMSG)
1475 fprintf(stderr, "do_include: %s:%d: include_state=%d, include_ppp='%s', include_ifdepth=%d ,pass_data=%d\n", input_name, line_number, include_state, include_ppp, include_ifdepth,pass_data);
1476 pp_switch_to_buffer(pp_create_buffer(ppin, YY_BUF_SIZE));
1478 fprintf(ppout, "# 1 \"%s\" 1%s\n", newpath, type ? "" : " 3");
1482 *-------------------------------------------------------------------------
1483 * Push/pop preprocessor ignore state when processing conditionals
1485 *-------------------------------------------------------------------------
1487 void push_ignore_state(void)
1489 yy_push_state(pp_ignore);
1492 void pop_ignore_state(void)