1 /*	$NetBSD: main.c,v 1.12 2016/01/09 22:05:33 christos Exp $	*/
2 
3 #include "defs.h"
4 
5 #include <sys/cdefs.h>
6 __RCSID("$NetBSD: main.c,v 1.12 2016/01/09 22:05:33 christos Exp $");
7 /* Id: main.c,v 1.55 2015/07/11 00:34:19 tom Exp  */
8 
9 #include <signal.h>
10 #ifndef _WIN32
11 #include <unistd.h>		/* for _exit() */
12 #else
13 #include <stdlib.h>		/* for _exit() */
14 #endif
15 
16 
17 #ifdef HAVE_MKSTEMP
18 # define USE_MKSTEMP 1
19 #elif defined(HAVE_FCNTL_H)
20 # define USE_MKSTEMP 1
21 # include <fcntl.h>		/* for open(), O_EXCL, etc. */
22 #else
23 # define USE_MKSTEMP 0
24 #endif
25 
26 #if USE_MKSTEMP
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 
30 typedef struct _my_tmpfiles
31 {
32     struct _my_tmpfiles *next;
33     char *name;
34 }
35 MY_TMPFILES;
36 
37 static MY_TMPFILES *my_tmpfiles;
38 #endif /* USE_MKSTEMP */
39 
40 char dflag;
41 char gflag;
42 char iflag;
43 char lflag;
44 static char oflag;
45 char rflag;
46 char sflag;
47 char tflag;
48 char vflag;
49 
50 const char *symbol_prefix;
51 const char *myname = "yacc";
52 
53 int lineno;
54 int outline;
55 
56 static char empty_string[] = "";
57 static char default_file_prefix[] = "y";
58 static int explicit_file_name;
59 
60 static char *file_prefix = default_file_prefix;
61 
62 char *code_file_name;
63 char *input_file_name = empty_string;
64 char *defines_file_name;
65 char *externs_file_name;
66 
67 static char *graph_file_name;
68 static char *output_file_name;
69 static char *verbose_file_name;
70 
71 FILE *action_file;	/*  a temp file, used to save actions associated    */
72 			/*  with rules until the parser is written          */
73 FILE *code_file;	/*  y.code.c (used when the -r option is specified) */
74 FILE *defines_file;	/*  y.tab.h                                         */
75 FILE *externs_file;	/*  y.tab.i                                         */
76 FILE *input_file;	/*  the input file                                  */
77 FILE *output_file;	/*  y.tab.c                                         */
78 FILE *text_file;	/*  a temp file, used to save text until all        */
79 			/*  symbols have been defined                       */
80 FILE *union_file;	/*  a temp file, used to save the union             */
81 			/*  definition until all symbol have been           */
82 			/*  defined                                         */
83 FILE *verbose_file;	/*  y.output                                        */
84 FILE *graph_file;	/*  y.dot                                           */
85 
86 Value_t nitems;
87 Value_t nrules;
88 Value_t nsyms;
89 Value_t ntokens;
90 Value_t nvars;
91 
92 Value_t start_symbol;
93 char **symbol_name;
94 char **symbol_pname;
95 Value_t *symbol_value;
96 Value_t *symbol_prec;
97 char *symbol_assoc;
98 
99 int pure_parser;
100 int token_table;
101 int error_verbose;
102 
103 #if defined(YYBTYACC)
104 Value_t *symbol_pval;
105 char **symbol_destructor;
106 char **symbol_type_tag;
107 int locations = 0;	/* default to no position processing */
108 int backtrack = 0;	/* default is no backtracking */
109 char *initial_action = NULL;
110 #endif
111 
112 int exit_code;
113 
114 Value_t *ritem;
115 Value_t *rlhs;
116 Value_t *rrhs;
117 Value_t *rprec;
118 Assoc_t *rassoc;
119 Value_t **derives;
120 char *nullable;
121 
122 /*
123  * Since fclose() is called via the signal handler, it might die.  Don't loop
124  * if there is a problem closing a file.
125  */
126 #define DO_CLOSE(fp) \
127 	if (fp != 0) { \
128 	    FILE *use = fp; \
129 	    fp = 0; \
130 	    fclose(use); \
131 	}
132 
133 static int got_intr = 0;
134 
135 void
done(int k)136 done(int k)
137 {
138     DO_CLOSE(input_file);
139     DO_CLOSE(output_file);
140     if (iflag)
141 	DO_CLOSE(externs_file);
142     if (rflag)
143 	DO_CLOSE(code_file);
144 
145     DO_CLOSE(action_file);
146     DO_CLOSE(defines_file);
147     DO_CLOSE(graph_file);
148     DO_CLOSE(text_file);
149     DO_CLOSE(union_file);
150     DO_CLOSE(verbose_file);
151 
152     if (got_intr)
153 	_exit(EXIT_FAILURE);
154 
155 #ifdef NO_LEAKS
156     if (rflag)
157 	DO_FREE(code_file_name);
158 
159     if (dflag)
160 	DO_FREE(defines_file_name);
161 
162     if (iflag)
163 	DO_FREE(externs_file_name);
164 
165     if (oflag)
166 	DO_FREE(output_file_name);
167 
168     if (vflag)
169 	DO_FREE(verbose_file_name);
170 
171     if (gflag)
172 	DO_FREE(graph_file_name);
173 
174     lr0_leaks();
175     lalr_leaks();
176     mkpar_leaks();
177     mstring_leaks();
178     output_leaks();
179     reader_leaks();
180 #endif
181 
182     exit(k);
183 }
184 
185 static void
onintr(int sig GCC_UNUSED)186 onintr(int sig GCC_UNUSED)
187 {
188     got_intr = 1;
189     done(EXIT_FAILURE);
190 }
191 
192 static void
set_signals(void)193 set_signals(void)
194 {
195 #ifdef SIGINT
196     if (signal(SIGINT, SIG_IGN) != SIG_IGN)
197 	signal(SIGINT, onintr);
198 #endif
199 #ifdef SIGTERM
200     if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
201 	signal(SIGTERM, onintr);
202 #endif
203 #ifdef SIGHUP
204     if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
205 	signal(SIGHUP, onintr);
206 #endif
207 }
208 
209 static void
usage(void)210 usage(void)
211 {
212     static const char *msg[] =
213     {
214 	""
215 	,"Options:"
216 	,"  -b file_prefix        set filename prefix (default \"y.\")"
217 	,"  -B                    create a backtracking parser"
218 	,"  -d                    write definitions (" DEFINES_SUFFIX ")"
219 	,"  -i                    write interface (y.tab.i)"
220 	,"  -g                    write a graphical description"
221 	,"  -l                    suppress #line directives"
222 	,"  -L                    enable position processing, e.g., \"%locations\""
223 	,"  -o output_file        (default \"" OUTPUT_SUFFIX "\")"
224 	,"  -p symbol_prefix      set symbol prefix (default \"yy\")"
225 	,"  -P                    create a reentrant parser, e.g., \"%pure-parser\""
226 	,"  -r                    produce separate code and table files (y.code.c)"
227 	,"  -s                    suppress #define's for quoted names in %token lines"
228 	,"  -t                    add debugging support"
229 	,"  -v                    write description (y.output)"
230 	,"  -V                    show version information and exit"
231     };
232     unsigned n;
233 
234     fflush(stdout);
235     fprintf(stderr, "Usage: %s [options] filename\n", myname);
236     for (n = 0; n < sizeof(msg) / sizeof(msg[0]); ++n)
237 	fprintf(stderr, "%s\n", msg[n]);
238 
239     exit(1);
240 }
241 
242 static void
setflag(int ch)243 setflag(int ch)
244 {
245     switch (ch)
246     {
247     case 'B':
248 #if defined(YYBTYACC)
249 	backtrack = 1;
250 #else
251 	unsupported_flag_warning("-B", "reconfigure with --enable-btyacc");
252 #endif
253 	break;
254 
255     case 'd':
256 	dflag = 1;
257 	break;
258 
259     case 'g':
260 	gflag = 1;
261 	break;
262 
263     case 'i':
264 	iflag = 1;
265 	break;
266 
267     case 'l':
268 	lflag = 1;
269 	break;
270 
271     case 'L':
272 #if defined(YYBTYACC)
273 	locations = 1;
274 #else
275 	unsupported_flag_warning("-B", "reconfigure with --enable-btyacc");
276 #endif
277 	break;
278 
279     case 'P':
280 	pure_parser = 1;
281 	break;
282 
283     case 'r':
284 	rflag = 1;
285 	break;
286 
287     case 's':
288 	sflag = 1;
289 	break;
290 
291     case 't':
292 	tflag = 1;
293 	break;
294 
295     case 'v':
296 	vflag = 1;
297 	break;
298 
299     case 'V':
300 	printf("%s - %s\n", myname, VERSION);
301 	exit(EXIT_SUCCESS);
302 
303     case 'y':
304 	/* noop for bison compatibility. byacc is already designed to be posix
305 	 * yacc compatible. */
306 	break;
307 
308     default:
309 	usage();
310     }
311 }
312 
313 static void
getargs(int argc,char * argv[])314 getargs(int argc, char *argv[])
315 {
316     int i;
317     char *s;
318     int ch;
319 
320     if (argc > 0)
321 	myname = argv[0];
322 
323     for (i = 1; i < argc; ++i)
324     {
325 	s = argv[i];
326 	if (*s != '-')
327 	    break;
328 	switch (ch = *++s)
329 	{
330 	case '\0':
331 	    input_file = stdin;
332 	    if (i + 1 < argc)
333 		usage();
334 	    return;
335 
336 	case '-':
337 	    ++i;
338 	    goto no_more_options;
339 
340 	case 'b':
341 	    if (*++s)
342 		file_prefix = s;
343 	    else if (++i < argc)
344 		file_prefix = argv[i];
345 	    else
346 		usage();
347 	    continue;
348 
349 	case 'o':
350 	    if (*++s)
351 		output_file_name = s;
352 	    else if (++i < argc)
353 		output_file_name = argv[i];
354 	    else
355 		usage();
356 	    explicit_file_name = 1;
357 	    continue;
358 
359 	case 'p':
360 	    if (*++s)
361 		symbol_prefix = s;
362 	    else if (++i < argc)
363 		symbol_prefix = argv[i];
364 	    else
365 		usage();
366 	    continue;
367 
368 	default:
369 	    setflag(ch);
370 	    break;
371 	}
372 
373 	for (;;)
374 	{
375 	    switch (ch = *++s)
376 	    {
377 	    case '\0':
378 		goto end_of_option;
379 
380 	    default:
381 		setflag(ch);
382 		break;
383 	    }
384 	}
385       end_of_option:;
386     }
387 
388   no_more_options:;
389     if (i + 1 != argc)
390 	usage();
391     input_file_name = argv[i];
392 }
393 
394 void *
allocate(size_t n)395 allocate(size_t n)
396 {
397     void *p;
398 
399     p = NULL;
400     if (n)
401     {
402 	p = CALLOC(1, n);
403 	NO_SPACE(p);
404     }
405     return (p);
406 }
407 
408 #define CREATE_FILE_NAME(dest, suffix) \
409 	dest = alloc_file_name(len, suffix)
410 
411 static char *
alloc_file_name(size_t len,const char * suffix)412 alloc_file_name(size_t len, const char *suffix)
413 {
414     char *result = TMALLOC(char, len + strlen(suffix) + 1);
415     if (result == 0)
416 	no_space();
417     strcpy(result, file_prefix);
418     strcpy(result + len, suffix);
419     return result;
420 }
421 
422 static void
create_file_names(void)423 create_file_names(void)
424 {
425     size_t len;
426     const char *defines_suffix;
427     const char *externs_suffix;
428     char *prefix;
429 
430     prefix = NULL;
431     defines_suffix = DEFINES_SUFFIX;
432     externs_suffix = EXTERNS_SUFFIX;
433 
434     /* compute the file_prefix from the user provided output_file_name */
435     if (output_file_name != 0)
436     {
437 	if (!(prefix = strstr(output_file_name, OUTPUT_SUFFIX))
438 	    && (prefix = strstr(output_file_name, ".c")))
439 	{
440 	    defines_suffix = ".h";
441 	    externs_suffix = ".i";
442 	}
443     }
444 
445     if (prefix != NULL)
446     {
447 	len = (size_t) (prefix - output_file_name);
448 	file_prefix = TMALLOC(char, len + 1);
449 	NO_SPACE(file_prefix);
450 	strncpy(file_prefix, output_file_name, len)[len] = 0;
451     }
452     else
453 	len = strlen(file_prefix);
454 
455     /* if "-o filename" was not given */
456     if (output_file_name == 0)
457     {
458 	oflag = 1;
459 	CREATE_FILE_NAME(output_file_name, OUTPUT_SUFFIX);
460     }
461 
462     if (rflag)
463     {
464 	CREATE_FILE_NAME(code_file_name, CODE_SUFFIX);
465     }
466     else
467 	code_file_name = output_file_name;
468 
469     if (dflag)
470     {
471 	if (explicit_file_name)
472 	{
473 	    char *suffix;
474 	    defines_file_name = strdup(output_file_name);
475 	    if (defines_file_name == 0)
476 		no_space();
477 	    /* does the output_file_name have a known suffix */
478             suffix = strrchr(output_file_name, '.');
479             if (suffix != 0 &&
480 		(!strcmp(suffix, ".c") ||   /* good, old-fashioned C */
481                  !strcmp(suffix, ".C") ||   /* C++, or C on Windows */
482                  !strcmp(suffix, ".cc") ||  /* C++ */
483                  !strcmp(suffix, ".cxx") || /* C++ */
484                  !strcmp(suffix, ".cpp")))  /* C++ (Windows) */
485             {
486                 strncpy(defines_file_name, output_file_name,
487                         suffix - output_file_name + 1);
488                 defines_file_name[suffix - output_file_name + 1] = 'h';
489                 defines_file_name[suffix - output_file_name + 2] = 0;
490             } else {
491                 fprintf(stderr,"%s: suffix of output file name %s"
492                                " not recognized, no -d file generated.\n",
493                         myname, output_file_name);
494                 dflag = 0;
495                 free(defines_file_name);
496                 defines_file_name = 0;
497             }
498 	} else {
499 	    CREATE_FILE_NAME(defines_file_name, defines_suffix);
500 	}
501     }
502 
503     if (iflag)
504     {
505 	CREATE_FILE_NAME(externs_file_name, externs_suffix);
506     }
507 
508     if (vflag)
509     {
510 	CREATE_FILE_NAME(verbose_file_name, VERBOSE_SUFFIX);
511     }
512 
513     if (gflag)
514     {
515 	CREATE_FILE_NAME(graph_file_name, GRAPH_SUFFIX);
516     }
517 
518     if (prefix != NULL)
519     {
520 	FREE(file_prefix);
521     }
522 }
523 
524 #if USE_MKSTEMP
525 static void
close_tmpfiles(void)526 close_tmpfiles(void)
527 {
528     while (my_tmpfiles != 0)
529     {
530 	MY_TMPFILES *next = my_tmpfiles->next;
531 
532 	(void)chmod(my_tmpfiles->name, 0644);
533 	(void)unlink(my_tmpfiles->name);
534 
535 	free(my_tmpfiles->name);
536 	free(my_tmpfiles);
537 
538 	my_tmpfiles = next;
539     }
540 }
541 
542 #ifndef HAVE_MKSTEMP
543 static int
my_mkstemp(char * temp)544 my_mkstemp(char *temp)
545 {
546     int fd;
547     char *dname;
548     char *fname;
549     char *name;
550 
551     /*
552      * Split-up to use tempnam, rather than tmpnam; the latter (like
553      * mkstemp) is unusable on Windows.
554      */
555     if ((fname = strrchr(temp, '/')) != 0)
556     {
557 	dname = strdup(temp);
558 	dname[++fname - temp] = '\0';
559     }
560     else
561     {
562 	dname = 0;
563 	fname = temp;
564     }
565     if ((name = tempnam(dname, fname)) != 0)
566     {
567 	fd = open(name, O_CREAT | O_EXCL | O_RDWR);
568 	strcpy(temp, name);
569     }
570     else
571     {
572 	fd = -1;
573     }
574 
575     if (dname != 0)
576 	free(dname);
577 
578     return fd;
579 }
580 #define mkstemp(s) my_mkstemp(s)
581 #endif
582 
583 #endif
584 
585 /*
586  * tmpfile() should be adequate, except that it may require special privileges
587  * to use, e.g., MinGW and Windows 7 where it tries to use the root directory.
588  */
589 static FILE *
open_tmpfile(const char * label)590 open_tmpfile(const char *label)
591 {
592 #define MY_FMT "%s/%.*sXXXXXX"
593     FILE *result;
594 #if USE_MKSTEMP
595     int fd;
596     const char *tmpdir;
597     char *name;
598     const char *mark;
599 
600     if ((tmpdir = getenv("TMPDIR")) == 0 || access(tmpdir, W_OK) != 0)
601     {
602 #ifdef P_tmpdir
603 	tmpdir = P_tmpdir;
604 #else
605 	tmpdir = "/tmp";
606 #endif
607 	if (access(tmpdir, W_OK) != 0)
608 	    tmpdir = ".";
609     }
610 
611     /* The size of the format is guaranteed to be longer than the result from
612      * printing empty strings with it; this calculation accounts for the
613      * string-lengths as well.
614      */
615     name = malloc(strlen(tmpdir) + sizeof(MY_FMT) + strlen(label));
616 
617     result = 0;
618     if (name != 0)
619     {
620 	mode_t save_umask = umask(0177);
621 
622 	if ((mark = strrchr(label, '_')) == 0)
623 	    mark = label + strlen(label);
624 
625 	sprintf(name, MY_FMT, tmpdir, (int)(mark - label), label);
626 	fd = mkstemp(name);
627 	if (fd >= 0)
628 	{
629 	    result = fdopen(fd, "w+");
630 	    if (result != 0)
631 	    {
632 		MY_TMPFILES *item;
633 
634 		if (my_tmpfiles == 0)
635 		{
636 		    atexit(close_tmpfiles);
637 		}
638 
639 		item = NEW(MY_TMPFILES);
640 		NO_SPACE(item);
641 
642 		item->name = name;
643 		NO_SPACE(item->name);
644 
645 		item->next = my_tmpfiles;
646 		my_tmpfiles = item;
647 	    }
648 	}
649 	(void)umask(save_umask);
650     }
651 #else
652     result = tmpfile();
653 #endif
654 
655     if (result == 0)
656 	open_error(label);
657     return result;
658 #undef MY_FMT
659 }
660 
661 static void
open_files(void)662 open_files(void)
663 {
664     create_file_names();
665 
666     if (input_file == 0)
667     {
668 	input_file = fopen(input_file_name, "r");
669 	if (input_file == 0)
670 	    open_error(input_file_name);
671     }
672 
673     action_file = open_tmpfile("action_file");
674     text_file = open_tmpfile("text_file");
675 
676     if (vflag)
677     {
678 	verbose_file = fopen(verbose_file_name, "w");
679 	if (verbose_file == 0)
680 	    open_error(verbose_file_name);
681     }
682 
683     if (gflag)
684     {
685 	graph_file = fopen(graph_file_name, "w");
686 	if (graph_file == 0)
687 	    open_error(graph_file_name);
688 	fprintf(graph_file, "digraph %s {\n", file_prefix);
689 	fprintf(graph_file, "\tedge [fontsize=10];\n");
690 	fprintf(graph_file, "\tnode [shape=box,fontsize=10];\n");
691 	fprintf(graph_file, "\torientation=landscape;\n");
692 	fprintf(graph_file, "\trankdir=LR;\n");
693 	fprintf(graph_file, "\t/*\n");
694 	fprintf(graph_file, "\tmargin=0.2;\n");
695 	fprintf(graph_file, "\tpage=\"8.27,11.69\"; // for A4 printing\n");
696 	fprintf(graph_file, "\tratio=auto;\n");
697 	fprintf(graph_file, "\t*/\n");
698     }
699 
700     if (dflag)
701     {
702 	defines_file = fopen(defines_file_name, "w");
703 	if (defines_file == 0)
704 	    open_error(defines_file_name);
705 	union_file = open_tmpfile("union_file");
706     }
707 
708     if (iflag)
709     {
710 	externs_file = fopen(externs_file_name, "w");
711 	if (externs_file == 0)
712 	    open_error(externs_file_name);
713     }
714 
715     output_file = fopen(output_file_name, "w");
716     if (output_file == 0)
717 	open_error(output_file_name);
718 
719     if (rflag)
720     {
721 	code_file = fopen(code_file_name, "w");
722 	if (code_file == 0)
723 	    open_error(code_file_name);
724     }
725     else
726 	code_file = output_file;
727 }
728 
729 int
main(int argc,char * argv[])730 main(int argc, char *argv[])
731 {
732     SRexpect = -1;
733     RRexpect = -1;
734     exit_code = EXIT_SUCCESS;
735 
736     set_signals();
737     getargs(argc, argv);
738     open_files();
739     reader();
740     lr0();
741     lalr();
742     make_parser();
743     graph();
744     finalize_closure();
745     verbose();
746     output();
747     done(exit_code);
748     /*NOTREACHED */
749 }
750