3 * Copyright (c) 1999-2008 Stephen Williams (steve@icarus.com)
5 * This source code is free software; you can redistribute it
6 * and/or modify it in source code form under the terms of the GNU
7 * General Public License as published by the Free Software
8 * Foundation; either version 2 of the License, or (at your option)
11 * This program 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
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
34 static void output_init();
35 #define YY_USER_INIT output_init()
37 static void def_start();
38 static void def_add_arg();
39 static void def_finish();
40 static void def_undefine();
41 static void do_define();
42 static int def_is_done();
43 static int is_defined(const char*name);
45 static int macro_needs_args(const char*name);
46 static void macro_start_args();
47 static void macro_add_to_arg();
48 static void macro_finish_arg();
49 static void do_expand(int use_args);
50 static char* macro_name();
52 static void include_filename();
53 static void do_include();
55 static int load_next_input();
57 struct include_stack_t
61 /* If the current input is from a file, this member is set. */
64 /* If we are reparsing a macro expansion, file is 0 and this
65 * member points to the string in progress
69 /* If we are reparsing a macro expansion, this member indicates
70 * the amount of space it occupies in the macro expansion buffer.
71 * This will be zero for macros without arguments.
80 struct include_stack_t* next;
83 static void emit_pathline(struct include_stack_t* isp);
86 * The file_queue is a singly-linked list of the files that were
87 * listed on the command line/file list.
89 static struct include_stack_t* file_queue = 0;
91 static int do_expand_stringify_flag = 0;
94 * The istack is the inclusion stack.
96 static struct include_stack_t* istack = 0;
97 static struct include_stack_t* standby = 0;
100 * Keep a stack of active ifdef, so that I can report errors
101 * when there are missing endifs.
108 struct ifdef_stack_t* next;
111 static struct ifdef_stack_t* ifdef_stack = 0;
113 static void ifdef_enter(void)
115 struct ifdef_stack_t*cur;
117 cur = (struct ifdef_stack_t*) calloc(1, sizeof(struct ifdef_stack_t));
118 cur->path = strdup(istack->path);
119 cur->lineno = istack->lineno;
120 cur->next = ifdef_stack;
125 static void ifdef_leave(void)
127 struct ifdef_stack_t* cur;
132 ifdef_stack = cur->next;
134 if (strcmp(istack->path,cur->path) != 0)
139 "%s:%u: warning: This `endif matches an ifdef in another file.\n",
147 "%s:%u: This is the odd matched `ifdef.\n",
157 #define YY_INPUT(buf,result,max_size) do { \
158 if (istack->file) { \
159 size_t rc = fread(buf, 1, max_size, istack->file); \
160 result = (rc == 0) ? YY_NULL : rc; \
162 if (*istack->str == 0) \
165 buf[0] = *istack->str++; \
171 static int comment_enter = 0;
172 static int pragma_enter = 0;
173 static int string_enter = 0;
175 static int ma_parenthesis_level = 0;
181 %option noyy_top_state
203 /* The grouping parentheses are necessary for compatibility with
204 * older versions of flex (at least 2.5.31); they are supposed to
205 * be implied, according to the flex manual.
207 keywords (include|define|undef|ifdef|ifndef|else|elseif|endif)
211 "//"[^\r\n]* { ECHO; }
213 /* detect multiline, c-style comments, passing them directly to the
214 * output. This is necessary to allow for ignoring directives that
215 * are included within the comments.
218 "/*" { comment_enter = YY_START; BEGIN(CCOMMENT); ECHO; }
219 <CCOMMENT>[^\r\n] { ECHO; }
223 <CCOMMENT>\r { istack->lineno += 1; fputc('\n', yyout); }
224 <CCOMMENT>"*/" { BEGIN(comment_enter); ECHO; }
226 /* Detect and pass multiline pragma comments. As with C-style
227 * comments, pragma comments are passed through, and preprocessor
228 * directives contained within are ignored. Contains macros are
231 "(*"{W}?")" { ECHO; }
232 "(*" { pragma_enter = YY_START; BEGIN(PCOMENT); ECHO; }
233 <PCOMENT>[^\r\n] { ECHO; }
237 <PCOMENT>\r { istack->lineno += 1; fputc('\n', yyout); }
238 <PCOMENT>"*)" { BEGIN(pragma_enter); ECHO; }
240 <PCOMENT>`{keywords} {
241 emit_pathline(istack);
246 "error: macro names cannot be directive keywords ('%s'); replaced with nothing.\n",
251 <PCOMENT>`[a-zA-Z][a-zA-Z0-9_$]* {
252 if (macro_needs_args(yytext+1)) yy_push_state(MA_START); else do_expand(0);
255 /* Strings do not contain preprocessor directives, but can expand
256 * macros. If that happens, they get expanded in the context of the
259 \" { string_enter = YY_START; BEGIN(CSTRING); ECHO; }
261 <CSTRING>\\` { ECHO; }
265 <CSTRING>\r { fputc('\n', yyout); }
266 <CSTRING>\" { BEGIN(string_enter); ECHO; }
269 /* This set of patterns matches the include directive and the name
270 * that follows it. when the directive ends, the do_include function
271 * performs the include operation.
273 ^{W}?`include { yy_push_state(PPINCLUDE); }
275 <PPINCLUDE>`{keywords} {
276 emit_pathline(istack);
281 "error: macro names cannot be directive keywords ('%s'); replaced with nothing.\n",
286 <PPINCLUDE>`[a-zA-Z][a-zA-Z0-9_]* {
287 if (macro_needs_args(yytext+1)) yy_push_state(MA_START); else do_expand(0);
290 <PPINCLUDE>\"[^\"]*\" { include_filename(); }
292 <PPINCLUDE>[ \t\b\f] { ; }
294 /* Catch single-line comments that share the line with an include
295 * directive. And while I'm at it, I might as well preserve the
296 * comment in the output stream.
298 <PPINCLUDE>"//"[^\r\n]* { ECHO; }
300 /* These finish the include directive (EOF or EOL) so I revert the
301 * lexor state and execute the inclusion.
304 /* There is a bug in flex <= 2.5.34 that prevents the continued action '|'
305 * from working properly when the final action is associated with <<EOF>>.
306 * Therefore, the action is repeated. */
311 <PPINCLUDE>\r { istack->lineno += 1; yy_pop_state(); do_include(); }
312 <PPINCLUDE><<EOF>> { istack->lineno += 1; yy_pop_state(); do_include(); }
314 /* Anything that is not matched by the above is an error of some
315 * sort. Print an error message and absorb the rest of the line.
318 emit_pathline(istack);
319 fprintf(stderr, "error: malformed `include directive. Did you quote the file name?\n");
324 /* Detect the define directive, and match the name. If followed by a
325 * '(', collect the formal arguments. Consume any white space, then
326 * go into DEF_TXT mode and collect the defined value.
328 `define{W} { yy_push_state(DEF_NAME); }
330 <DEF_NAME>{keywords}{W}? {
331 emit_pathline(istack);
337 "error: malformed `define directive: macro names cannot be directive keywords\n"
341 <DEF_NAME>[a-zA-Z_][a-zA-Z0-9_$]*"("{W}? { BEGIN(DEF_ARG); def_start(); }
342 <DEF_NAME>[a-zA-Z_][a-zA-Z0-9_$]*{W}? { BEGIN(DEF_TXT); def_start(); }
344 <DEF_ARG>[a-zA-Z_][a-zA-Z0-9_$]*{W}? { BEGIN(DEF_SEP); def_add_arg(); }
346 <DEF_SEP>","{W}? { BEGIN(DEF_ARG); }
347 <DEF_SEP>")"{W}? { BEGIN(DEF_TXT); }
349 <DEF_ARG,DEF_SEP>"//"[^\r\n]* { ECHO; }
350 <DEF_ARG,DEF_SEP>"/*" { comment_enter = YY_START; BEGIN(CCOMMENT); ECHO; }
351 <DEF_ARG,DEF_SEP>{W} {}
353 <DEF_ARG,DEF_SEP>(\n|"\r\n"|"\n\r"|\r){W}? { istack->lineno += 1; fputc('\n', yyout); }
355 <DEF_NAME,DEF_ARG,DEF_SEP>. {
356 emit_pathline(istack);
357 fprintf(stderr, "error: malformed `define directive.\n");
362 <DEF_TXT>.*[^\r\n] { do_define(); }
364 <DEF_TXT>(\n|"\r\n"|"\n\r"|\r) {
374 /* If the define is terminated by an EOF, then finish the define
375 * whether there was a continuation or not.
385 if (!load_next_input())
389 `undef{W}[a-zA-Z_][a-zA-Z0-9_$]*{W}?.* { def_undefine(); }
391 /* Detect conditional compilation directives, and parse them. If I
392 * find the name defined, switch to the IFDEF_TRUE state and stay
393 * there until I get an `else or `endif. Otherwise, switch to the
394 * IFDEF_FALSE state and start tossing data.
396 * Handle suppressed `ifdef with an additional suppress start
397 * condition that stacks on top of the IFDEF_FALSE so that output is
398 * not accidentally turned on within nested ifdefs.
400 `ifdef{W}[a-zA-Z_][a-zA-Z0-9_$]* {
401 char* name = strchr(yytext, '`'); assert(name);
404 name += strspn(name, " \t\b\f");
408 if (is_defined(name))
409 yy_push_state(IFDEF_TRUE);
411 yy_push_state(IFDEF_FALSE);
414 `ifndef{W}[a-zA-Z_][a-zA-Z0-9_$]* {
415 char* name = strchr(yytext, '`'); assert(name);
418 name += strspn(name, " \t\b\f");
422 if (!is_defined(name))
423 yy_push_state(IFDEF_TRUE);
425 yy_push_state(IFDEF_FALSE);
428 <IFDEF_FALSE,IFDEF_SUPR>`ifdef{W} |
429 <IFDEF_FALSE,IFDEF_SUPR>`ifndef{W} { ifdef_enter(); yy_push_state(IFDEF_SUPR); }
431 <IFDEF_TRUE>`elsif{W}[a-zA-Z_][a-zA-Z0-9_$]* { BEGIN(IFDEF_SUPR); }
433 <IFDEF_FALSE>`elsif{W}[a-zA-Z_][a-zA-Z0-9_$]* {
434 char* name = strchr(yytext, '`'); assert(name);
437 name += strspn(name, " \t\b\f");
439 if (is_defined(name))
445 <IFDEF_SUPR>`elsif{W}[a-zA-Z_][a-zA-Z0-9_$]* { }
447 <IFDEF_TRUE>`else { BEGIN(IFDEF_SUPR); }
448 <IFDEF_FALSE>`else { BEGIN(IFDEF_TRUE); }
451 <IFDEF_FALSE,IFDEF_SUPR>"//"[^\r\n]* {}
453 <IFDEF_FALSE,IFDEF_SUPR>"/*" { comment_enter = YY_START; BEGIN(IFCCOMMENT); }
455 <IFCCOMMENT>[^\r\n] {}
459 <IFCCOMMENT>\r { istack->lineno += 1; }
460 <IFCCOMMENT>"*/" { BEGIN(comment_enter); }
462 <IFDEF_FALSE,IFDEF_SUPR>[^\r\n] { }
463 <IFDEF_FALSE,IFDEF_SUPR>\n\r |
464 <IFDEF_FALSE,IFDEF_SUPR>\r\n |
465 <IFDEF_FALSE,IFDEF_SUPR>\n |
466 <IFDEF_FALSE,IFDEF_SUPR>\r { istack->lineno += 1; fputc('\n', yyout); }
468 <IFDEF_FALSE,IFDEF_TRUE,IFDEF_SUPR>`endif { ifdef_leave(); yy_pop_state(); }
475 "%s:%u: `ifdef without a macro name - ignored.\n",
476 istack->path, istack->lineno+1
485 "%s:%u: `ifndef without a macro name - ignored.\n",
486 istack->path, istack->lineno+1
495 "%s:%u: `elsif without a macro name - ignored.\n",
496 istack->path, istack->lineno+1
500 `elsif{W}[a-zA-Z_][a-zA-Z0-9_$]* {
505 "%s:%u: `elsif without a matching `ifdef - ignored.\n",
506 istack->path, istack->lineno+1
515 "%s:%u: `else without a matching `ifdef - ignored.\n",
516 istack->path, istack->lineno+1
525 "%s:%u: `endif without a matching `ifdef - ignored.\n",
526 istack->path, istack->lineno+1
531 emit_pathline(istack);
536 "error: macro names cannot be directive keywords ('%s'); replaced with nothing.\n",
541 /* This pattern notices macros and arranges for them to be replaced. */
542 `[a-zA-Z_][a-zA-Z0-9_$]* {
543 if (macro_needs_args(yytext+1))
544 yy_push_state(MA_START);
549 /* Stringified version of macro expansion. */
550 ``[a-zA-Z_][a-zA-Z0-9_$]* {
551 assert(do_expand_stringify_flag == 0);
552 do_expand_stringify_flag = 1;
554 if (macro_needs_args(yytext+2))
555 yy_push_state(MA_START);
560 <MA_START>\( { BEGIN(MA_ADD); macro_start_args(); }
564 <MA_START>(\n|"\r\n"|"\n\r"|\r){W}? {
570 emit_pathline(istack);
572 fprintf(stderr, "error: missing argument list for `%s.\n", macro_name());
579 <MA_ADD>\"[^\"\n\r]*\" { macro_add_to_arg(0); }
581 <MA_ADD>\"[^\"\n\r]* {
582 emit_pathline(istack);
584 fprintf(stderr, "error: unterminated string.\n");
590 <MA_ADD>'[^\n\r]' { macro_add_to_arg(0); }
592 <MA_ADD>{W} { macro_add_to_arg(1); }
594 <MA_ADD>"(" { macro_add_to_arg(0); ma_parenthesis_level++; }
596 <MA_ADD>"," { macro_finish_arg(); }
599 if (ma_parenthesis_level > 0) {
601 ma_parenthesis_level--;
609 <MA_ADD>(\n|"\r\n"|"\n\r"|\r){W}? {
615 <MA_ADD>. { macro_add_to_arg(0); }
617 <MA_START,MA_ADD>"//"[^\r\n]* { ECHO; }
619 <MA_START,MA_ADD>"/*" { comment_enter = YY_START; BEGIN(CCOMMENT); ECHO; }
621 /* Any text that is not a directive just gets passed through to the
628 \r { istack->lineno += 1; fputc('\n', yyout); }
630 /* Absorb the rest of the line when a broken directive is detected. */
631 <ERROR_LINE>[^\r\n]* { yy_pop_state(); }
633 <ERROR_LINE>(\n|"\r\n"|"\n\r"|\r) {
639 <<EOF>> { if (!load_next_input()) yyterminate(); }
642 /* Defined macros are kept in this table for convenient lookup. As
643 * `define directives are matched (and the do_define() function
644 * called) the tree is built up to match names with values. If a
645 * define redefines an existing name, the new value it taken.
651 int keyword; /* keywords don't get rescanned for fresh values. */
654 struct define_t* left;
655 struct define_t* right;
659 static struct define_t* def_table = 0;
661 static struct define_t* def_lookup(const char*name)
663 struct define_t* cur = def_table;
668 assert(cur->up == 0);
672 int cmp = strcmp(name, cur->name);
677 cur = (cmp < 0) ? cur->left : cur->right;
683 static int is_defined(const char*name)
685 return def_lookup(name) != 0;
689 * The following variables are used to temporarily hold the name and
690 * formal arguments of a macro definition as it is being parsed. As
691 * for C program arguments, def_argc counts the arguments (including
692 * the macro name), the value returned by def_argv(0) points to the
693 * macro name, the value returned by def_argv(1) points to the first
694 * argument, and so on.
696 * These variables are also used for storing the actual arguments when
697 * a macro is instantiated.
699 #define MAX_DEF_ARG 256 // allows argument IDs to be stored in a single char
701 #define DEF_BUF_CHUNK 256
703 static char* def_buf = 0;
704 static int def_buf_size = 0;
705 static int def_buf_free = 0;
707 static int def_argc = 0;
708 static int def_argo[MAX_DEF_ARG]; // offset of first character in arg
709 static int def_argl[MAX_DEF_ARG]; // length of arg string.
712 * Return a pointer to the start of argument 'arg'. Returned pointers
713 * may go stale after a call to def_buf_grow_to_fit.
715 static inline char* def_argv(int arg)
717 return def_buf + def_argo[arg];
720 static void check_for_max_args()
722 if (def_argc == MAX_DEF_ARG)
724 emit_pathline(istack);
725 fprintf(stderr, "error: too many macro arguments - aborting\n");
730 static void def_buf_grow_to_fit(int length)
732 while (length >= def_buf_free)
734 def_buf_size += DEF_BUF_CHUNK;
735 def_buf_free += DEF_BUF_CHUNK;
736 def_buf = realloc(def_buf, def_buf_size);
737 assert(def_buf != 0);
741 static void def_start()
743 def_buf_free = def_buf_size;
748 static void def_add_arg()
752 check_for_max_args();
754 /* Remove trailing white space and, if necessary, opening brace. */
755 while (isspace(yytext[length - 1]))
758 if (yytext[length - 1] == '(')
763 /* Make sure there's room in the buffer for the new argument. */
764 def_buf_grow_to_fit(length);
766 /* Store the new argument. */
767 def_argl[def_argc] = length;
768 def_argo[def_argc] = def_buf_size - def_buf_free;
769 strcpy(def_argv(def_argc++), yytext);
770 def_buf_free -= length + 1;
773 void define_macro(const char* name, const char* value, int keyword, int argc)
775 struct define_t* def;
777 def = malloc(sizeof(struct define_t));
778 def->name = strdup(name);
779 def->value = strdup(value);
780 def->keyword = keyword;
790 struct define_t* cur = def_table;
794 int cmp = strcmp(def->name, cur->name);
799 cur->value = def->value;
831 * The do_define function accumulates the defined value in these
832 * variables. When the define is over, the def_finish() function
833 * executes the define and clears this text. The define_continue_flag
834 * is set if do_define detects that the definition is to be continued
837 static char* define_text = 0;
838 static size_t define_cnt = 0;
840 static int define_continue_flag = 0;
843 * Define a special character code used to mark the insertion point
844 * for arguments in the macro text. This should be a character that
845 * will not occur in the Verilog source code.
847 #define ARG_MARK '\a'
850 #define _STR2(x) _STR1(x)
853 * Find an argument, but only if it is not directly preceded by something
854 * that would make it part of another simple identifier ([a-zA-Z0-9_$]).
856 static char *find_arg(char*ptr, char*head, char*arg)
861 /* Look for a candidate match, just return if none is found. */
862 cp = strstr(cp, arg);
865 /* If we are not at the start of the string verify that this
866 * match is not in the middle of another identifier.
869 (isalnum(*(cp-1)) || *(cp-1) == '_' || *(cp-1) == '$')) {
881 * Collect the definition. Normally, this returns 0. If there is a
882 * continuation, then return 1 and this function may be called again
883 * to collect another line of the definition.
885 static void do_define()
893 define_continue_flag = 0;
895 /* Look for comments in the definition, and remove them. The
896 * "//" style comments go to the end of the line and terminate
897 * the definition, but the multi-line comments are simply cut
898 * out, and the define continues.
900 cp = strchr(yytext, '/');
911 tail = strstr(cp+2, "*/");
919 "%s:%u: Unterminated comment in define\n",
920 istack->path, istack->lineno+1
925 memmove(cp, tail+2, strlen(tail+2)+1);
929 cp = strchr(cp+1, '/');
932 /* Trim trailing white space. */
933 cp = yytext + strlen(yytext);
936 if (!isspace(cp[-1]))
943 /* Detect the continuation sequence. If I find it, remove it
944 * and the white space that preceeds it, then replace all that
945 * with a single newline.
947 if ((cp > yytext) && (cp[-1] == '\\'))
952 while ((cp > yytext) && isspace(cp[-1])) {
960 define_continue_flag = 1;
963 /* Accumulate this text into the define_text string. */
964 define_text = realloc(define_text, define_cnt + (cp-yytext) + 1); assert(define_text != 0);
966 head = &define_text[define_cnt];
967 strcpy(head, yytext);
969 define_cnt += cp-yytext;
971 tail = &define_text[define_cnt];
973 /* If the text for a macro with arguments contains occurrences
974 * of ARG_MARK, issue an error message and suppress the macro.
976 if ((def_argc > 1) && strchr(head, ARG_MARK))
978 emit_pathline(istack);
985 "error: implementation restriction - macro text may not contain a %s character\n",
990 /* Look for formal argument names in the definition, and replace
991 * each occurrence with the sequence ARG_MARK,'\ddd' where ddd is
992 * the formal argument index number.
995 for (arg = 1; arg < def_argc; arg++)
997 int argl = def_argl[arg];
999 cp = find_arg(head, head, def_argv(arg));
1003 added_cnt += 2 - argl;
1007 char* base = define_text;
1009 define_cnt += added_cnt;
1010 define_text = realloc(define_text, define_cnt + 1); assert(define_text != 0);
1012 head = &define_text[head - base];
1013 tail = &define_text[tail - base];
1014 cp = &define_text[cp - base];
1019 memmove(cp+2, cp+argl, tail-(cp+argl)+1);
1025 cp = find_arg(cp, head, def_argv(arg));
1028 define_cnt += added_cnt;
1032 * Return true if the definition text is done. This is the opposite of
1033 * the define_continue_flag.
1035 static int def_is_done()
1037 return !define_continue_flag;
1041 * After some number of calls to do_define, this function is called to
1042 * assigned value to the parsed name. If there is no value, then
1043 * assign the string "" (empty string.)
1045 static void def_finish()
1047 define_continue_flag = 0;
1053 define_macro(def_argv(0), "", 0, def_argc);
1056 define_macro(def_argv(0), define_text, 0, def_argc);
1067 static void def_undefine()
1069 struct define_t* cur;
1070 struct define_t* tail;
1072 /* def_buf is used to store the macro name. Make sure there is
1075 def_buf_grow_to_fit(yyleng);
1077 sscanf(yytext, "`undef %s", def_buf);
1079 cur = def_lookup(def_buf);
1080 if (cur == 0) return;
1084 if ((cur->left == 0) && (cur->right == 0))
1086 else if (cur->left == 0)
1088 def_table = cur->right;
1092 else if (cur->right == 0)
1095 def_table = cur->left;
1104 tail->right = cur->right;
1105 tail->right->up = tail;
1107 def_table = cur->left;
1111 else if (cur->left == 0)
1113 if (cur->up->left == cur)
1114 cur->up->left = cur->right;
1117 assert(cur->up->right == cur);
1118 cur->up->right = cur->right;
1122 cur->right->up = cur->up;
1124 else if (cur->right == 0)
1128 if (cur->up->left == cur)
1129 cur->up->left = cur->left;
1132 assert(cur->up->right == cur);
1133 cur->up->right = cur->left;
1136 cur->left->up = cur->up;
1142 assert(cur->left && cur->right);
1147 tail->right = cur->right;
1148 tail->right->up = tail;
1150 if (cur->up->left == cur)
1151 cur->up->left = cur->left;
1154 assert(cur->up->right == cur);
1155 cur->up->right = cur->left;
1158 cur->left->up = cur->up;
1167 * When a macro is instantiated in the source, macro_needs_args() is
1168 * used to look up the name and return whether it is a macro that
1169 * takes arguments. A pointer to the macro descriptor is stored in
1170 * cur_macro so that do_expand() doesn't need to look it up again.
1172 static struct define_t* cur_macro = 0;
1174 static int macro_needs_args(const char*text)
1176 cur_macro = def_lookup(text);
1179 return (cur_macro->argc > 1);
1182 emit_pathline(istack);
1183 fprintf(stderr, "warning: macro %s undefined (and assumed null) at this point.\n", text);
1188 static char* macro_name()
1190 return cur_macro ? cur_macro->name : "";
1193 static void macro_start_args()
1195 /* The macro name can be found via cur_macro, so create a null
1196 * entry for arg 0. This will be used by macro_finish_arg() to
1197 * calculate the buffer location for arg 1.
1199 def_buf_free = def_buf_size - 1;
1206 static void macro_add_to_arg(int is_white_space)
1209 int length = yyleng;
1211 check_for_max_args();
1213 /* Replace any run of white space with a single space */
1221 /* Make sure there's room in the buffer for the new argument. */
1222 def_buf_grow_to_fit(length);
1224 /* Store the new text. */
1225 tail = &def_buf[def_buf_size - def_buf_free];
1226 strcpy(tail, yytext);
1227 def_buf_free -= length;
1230 static void macro_finish_arg()
1232 char* tail = &def_buf[def_buf_size - def_buf_free];
1234 check_for_max_args();
1238 def_argo[def_argc] = def_argo[def_argc-1] + def_argl[def_argc-1] + 1;
1239 def_argl[def_argc] = tail - def_argv(def_argc);
1246 * The following variables are used to hold macro expansions that are
1247 * built dynamically using supplied arguments. Buffer space is allocated
1248 * as the macro is expanded, and is only released once the expansion has
1249 * been reparsed. This means that the buffer acts as a stack for nested
1252 * The expansion buffer is only used for macros with arguments - the
1253 * text for simple macros can be taken directly from the macro table.
1255 #define EXP_BUF_CHUNK 256
1257 static char*exp_buf = 0;
1258 static int exp_buf_size = 0;
1259 static int exp_buf_free = 0;
1261 static void exp_buf_grow_to_fit(int length)
1263 while (length >= exp_buf_free)
1265 exp_buf_size += EXP_BUF_CHUNK;
1266 exp_buf_free += EXP_BUF_CHUNK;
1267 exp_buf = realloc(exp_buf, exp_buf_size); assert(exp_buf != 0);
1271 static void expand_using_args()
1279 if (def_argc != cur_macro->argc)
1281 emit_pathline(istack);
1282 fprintf(stderr, "error: wrong number of arguments for `%s\n", cur_macro->name);
1286 head = cur_macro->value;
1291 if (*tail != ARG_MARK)
1295 arg = tail[1]; assert(arg < def_argc);
1297 length = (tail - head) + def_argl[arg];
1298 exp_buf_grow_to_fit(length);
1300 dest = &exp_buf[exp_buf_size - exp_buf_free];
1301 memcpy(dest, head, tail - head);
1302 dest += tail - head;
1303 memcpy(dest, def_argv(arg), def_argl[arg]);
1305 exp_buf_free -= length;
1312 length = tail - head;
1313 exp_buf_grow_to_fit(length);
1315 dest = &exp_buf[exp_buf_size - exp_buf_free];
1316 memcpy(dest, head, length + 1);
1318 exp_buf_free -= length + 1;
1322 * When a macro use is discovered in the source, this function is
1323 * used to emit the substitution in its place.
1325 static void do_expand(int use_args)
1329 struct include_stack_t*isp;
1333 if (cur_macro->keyword)
1335 fprintf(yyout, "%s", cur_macro->value);
1341 head = exp_buf_size - exp_buf_free;
1342 expand_using_args();
1343 tail = exp_buf_size - exp_buf_free;
1349 isp = (struct include_stack_t*) calloc(1, sizeof(struct include_stack_t));
1351 isp->stringify_flag = do_expand_stringify_flag;
1352 do_expand_stringify_flag = 0;
1355 isp->str = &exp_buf[head];
1356 isp->ebs = tail - head;
1360 isp->str = cur_macro->value;
1365 istack->yybs = YY_CURRENT_BUFFER;
1368 yy_switch_to_buffer(yy_create_buffer(istack->file, YY_BUF_SIZE));
1370 if (do_expand_stringify_flag) {
1371 do_expand_stringify_flag = 0;
1378 * Include file handling works by keeping an include stack of the
1379 * files that are opened and being processed. The first item on the
1380 * stack is the current file being scanned. If I get to an include
1383 * open the new file,
1384 * save the current buffer context,
1385 * create a new buffer context,
1386 * and push the new file information.
1388 * When the file runs out, it is closed and the buffer is deleted
1389 * If after popping the current file information there is another
1390 * file on the stack, that file's buffer context is restored and
1394 static void output_init()
1396 if (line_direct_flag)
1397 fprintf(yyout, "`line 1 \"%s\" 0\n", istack->path);
1400 static void include_filename()
1404 emit_pathline(istack);
1408 "error: malformed `include directive. Extra junk on line?\n"
1413 standby = malloc(sizeof(struct include_stack_t));
1414 standby->path = strdup(yytext+1);
1415 standby->path[strlen(standby->path)-1] = 0;
1416 standby->lineno = 0;
1419 static void do_include()
1421 /* standby is defined by include_filename() */
1422 if (standby->path[0] == '/')
1424 if ((standby->file = fopen(standby->path, "r")))
1425 goto code_that_switches_buffers;
1429 unsigned idx, start = 0;
1433 /* Add the current path to the start of the include_dir list. */
1434 strcpy(path, istack->path);
1435 cp = strrchr(path, '/');
1438 start = 1; /* A base file so already in [1] */
1443 /* We do not need a strdup here since the path is read before
1444 * it is overridden. If the search order is changed add a
1445 * strdup here and a free below.
1447 include_dir[0] = path;
1450 for (idx = start ; idx < include_cnt ; idx += 1)
1452 sprintf(path, "%s/%s", include_dir[idx], standby->path);
1454 if ((standby->file = fopen(path, "r")))
1456 standby->path = strdup(path);
1457 goto code_that_switches_buffers;
1462 fprintf(stderr, "%s:%u: Include file %s not found\n", istack->path, istack->lineno, standby->path);
1465 code_that_switches_buffers:
1468 fprintf(depend_file, "%s\n", standby->path);
1470 if (line_direct_flag)
1471 fprintf(yyout, "\n`line %u \"%s\" 1\n", istack->lineno+1, standby->path);
1473 standby->next = istack;
1474 standby->stringify_flag = 0;
1476 istack->yybs = YY_CURRENT_BUFFER;
1481 yy_switch_to_buffer(yy_create_buffer(istack->file, YY_BUF_SIZE));
1484 /* walk the include stack until we find an entry with a valid pathname,
1485 * and print the file and line from that entry for use in an error message.
1486 * The istack entries created by do_expand() for macro expansions do not
1487 * contain pathnames. This finds instead the real file in which the outermost
1490 static void emit_pathline(struct include_stack_t* isp)
1492 while(isp && (isp->path == NULL))
1497 fprintf(stderr, "%s:%u: ", isp->path, isp->lineno+1);
1500 static void lexor_done()
1504 struct ifdef_stack_t*cur = ifdef_stack;
1505 ifdef_stack = cur->next;
1510 "%s:%u: error: This `ifdef lacks an `endif.\n",
1511 cur->path, cur->lineno+1
1520 static int load_next_input()
1522 int line_mask_flag = 0;
1523 struct include_stack_t* isp = istack;
1526 /* Delete the current input buffers, and free the cell. */
1527 yy_delete_buffer(YY_CURRENT_BUFFER);
1536 /* If I am printing line directives and I just finished
1537 * macro substitution, I should terminate the line and
1538 * arrange for a new directive to be printed.
1540 if (line_direct_flag && istack && istack->path && isp->lineno)
1541 fprintf(yyout, "\n");
1545 exp_buf_free += isp->ebs;
1548 if (isp->stringify_flag) {
1554 /* If I am out of include stack, the main input is
1555 * done. Look for another file to process in the input
1556 * queue. If none are there, give up. Otherwise, open the file
1557 * and continue parsing.
1561 if (file_queue == 0)
1567 istack = file_queue;
1568 file_queue = file_queue->next;
1572 istack->file = fopen(istack->path, "r");
1574 if (istack->file == 0)
1576 perror(istack->path);
1581 if (line_direct_flag)
1582 fprintf(yyout, "\n`line 1 \"%s\" 0\n", istack->path);
1585 fprintf(depend_file, "%s\n", istack->path);
1587 yyrestart(istack->file);
1591 /* Otherwise, resume the input buffer that is the new stack
1592 * top. If I need to print a line directive, do so.
1594 yy_switch_to_buffer(istack->yybs);
1596 if (line_direct_flag && istack->path && !line_mask_flag)
1597 fprintf(yyout, "\n`line %u \"%s\" 2\n", istack->lineno+1, istack->path);
1603 * The dump_precompiled_defines() and load_precompiled_defines()
1604 * functions dump/load macro definitions to/from a file. The defines
1607 * <name>:<argc>:<len>:<value>
1609 * for easy extraction. The value is already precompiled to handle
1610 * macro substitution. The <len> is the number of bytes in the
1611 * <value>. This is necessary because the value may contain arbitrary
1612 * text, including ':' and \n characters.
1614 * Each record is terminated by a \n character.
1616 static void do_dump_precompiled_defines(FILE* out, struct define_t* table)
1618 if (!table->keyword)
1619 #ifdef __MINGW32__ /* MinGW does not know about z. */
1620 fprintf(out, "%s:%d:%d:%s\n", table->name, table->argc, strlen(table->value), table->value);
1622 fprintf(out, "%s:%d:%zd:%s\n", table->name, table->argc, strlen(table->value), table->value);
1626 do_dump_precompiled_defines(out, table->left);
1629 do_dump_precompiled_defines(out, table->right);
1632 void dump_precompiled_defines(FILE* out)
1635 do_dump_precompiled_defines(out, def_table);
1638 void load_precompiled_defines(FILE* src)
1643 while ((ch = fgetc(src)) != EOF)
1656 while ((ch = fgetc(src)) != EOF && ch != ':')
1662 /* Terminate the name string. */
1665 /* Read the argc number */
1666 while (isdigit(ch = fgetc(src)))
1667 argc = 10*argc + ch-'0';
1672 while (isdigit(ch = fgetc(src)))
1673 len = 10*len + ch-'0';
1696 define_macro(name, value, 0, argc);
1701 * This function initializes the whole process. The first file is
1702 * opened, and the lexor is initialized. The include stack is cleared
1705 void reset_lexor(FILE* out, char* paths[])
1708 struct include_stack_t* isp;
1709 struct include_stack_t* tail = 0;
1711 isp = malloc(sizeof(struct include_stack_t));
1713 isp->path = strdup(paths[0]);
1714 isp->file = fopen(paths[0], "r");
1718 isp->stringify_flag = 0;
1727 fprintf(depend_file, "%s\n", paths[0]);
1731 yyrestart(isp->file);
1733 assert(istack == 0);
1736 /* Now build up a queue of all the remaining file names, so
1737 * that load_next_input() can pull them when needed.
1739 for (idx = 1 ; paths[idx] ; idx += 1)
1741 isp = malloc(sizeof(struct include_stack_t));
1742 isp->path = strdup(paths[idx]);
1748 isp->stringify_flag = 0;