Implement -Wswitch-default.
[cparser] / main.c
1 #include <config.h>
2
3 #define _GNU_SOURCE
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdbool.h>
8 #include <errno.h>
9 #include <string.h>
10 #include <assert.h>
11
12 #ifdef _WIN32
13
14 #include <fcntl.h>
15 #include <io.h>
16
17 /* no eXecute on Win32 */
18 #define X_OK 0
19 #define W_OK 2
20 #define R_OK 4
21
22 #define O_RDWR          _O_RDWR
23 #define O_CREAT         _O_CREAT
24 #define O_EXCL          _O_EXCL
25 #define O_BINARY        _O_BINARY
26
27 /* remap some names, we are not in the POSIX world */
28 #define access(fname, mode)      _access(fname, mode)
29 #define mktemp(tmpl)             _mktemp(tmpl)
30 #define open(fname, oflag, mode) _open(fname, oflag, mode)
31 #define fdopen(fd, mode)         _fdopen(fd, mode)
32 #define popen(cmd, mode)         _popen(cmd, mode)
33 #define pclose(file)             _pclose(file)
34
35 #else
36 #include <unistd.h>
37 #define HAVE_MKSTEMP
38 #endif
39
40 #ifndef WITH_LIBCORE
41 #define WITH_LIBCORE
42 #endif
43
44 #include <libfirm/firm.h>
45 #include <libfirm/be.h>
46
47 #include "lexer.h"
48 #include "token_t.h"
49 #include "types.h"
50 #include "type_hash.h"
51 #include "parser.h"
52 #include "ast2firm.h"
53 #include "diagnostic.h"
54 #include "lang_features.h"
55 #include "driver/firm_opt.h"
56 #include "driver/firm_cmdline.h"
57 #include "adt/error.h"
58 #include "write_fluffy.h"
59 #include "revision.h"
60 #include "warning.h"
61
62 #ifndef PREPROCESSOR
63 #define PREPROCESSOR "cpp -std=c99 -U__WCHAR_TYPE__ -D__WCHAR_TYPE__=int"
64 #endif
65
66 #ifndef LINKER
67 #define LINKER    "gcc -m32"
68 #endif
69
70 #ifndef ASSEMBLER
71 #define ASSEMBLER "as --32"
72 #endif
73
74 /** The current c mode/dialect. */
75 unsigned int c_mode = _C89|_C99|_GNUC;
76
77 /** The 'machine size', 16, 32 or 64 bit, 32bit is the default. */
78 unsigned int machine_size = 32;
79
80 /** true if the char type is signed. */
81 bool char_is_signed = true;
82
83 /** true for strict language checking. */
84 bool strict_mode = false;
85
86 static int            verbose;
87 static struct obstack cppflags_obst;
88
89 #if defined(_DEBUG) || defined(FIRM_DEBUG)
90 /**
91  * Debug printf implementation.
92  *
93  * @param fmt  printf style format parameter
94  */
95 void dbg_printf(const char *fmt, ...)
96 {
97         va_list list;
98
99         if (firm_dump.debug_print) {
100                 va_start(list, fmt);
101                 vprintf(fmt, list);
102                 va_end(list);
103         }  /* if */
104 }
105 #endif /* defined(_DEBUG) || defined(FIRM_DEBUG) */
106
107 static void initialize_firm(void)
108 {
109         firm_early_init();
110
111         dump_consts_local(1);
112         dump_keepalive_edges(1);
113 }
114
115 static void get_output_name(char *buf, size_t buflen, const char *inputname,
116                             const char *newext)
117 {
118         size_t last_dot = 0xffffffff;
119         size_t i = 0;
120
121         if(inputname == NULL) {
122                 snprintf(buf, buflen, "a%s", newext);
123                 return;
124         }
125
126         for(const char *c = inputname; *c != 0; ++c) {
127                 if(*c == '.')
128                         last_dot = i;
129                 ++i;
130         }
131         if(last_dot == 0xffffffff)
132                 last_dot = i;
133
134         if(last_dot >= buflen)
135                 panic("filename too long");
136         memcpy(buf, inputname, last_dot);
137
138         size_t extlen = strlen(newext) + 1;
139         if(extlen + last_dot >= buflen)
140                 panic("filename too long");
141         memcpy(buf+last_dot, newext, extlen);
142 }
143
144 static translation_unit_t *do_parsing(FILE *const in, const char *const input)
145 {
146         lexer_open_stream(in, input);
147         translation_unit_t *unit = parse();
148         return unit;
149 }
150
151 static void lextest(FILE *in, const char *fname)
152 {
153         lexer_open_stream(in, fname);
154
155         do {
156                 lexer_next_preprocessing_token();
157                 print_token(stdout, &lexer_token);
158                 puts("");
159         } while(lexer_token.type != T_EOF);
160 }
161
162 static FILE* preprocess(FILE* in, const char *fname)
163 {
164         char buf[4096];
165         const char *flags = obstack_finish(&cppflags_obst);
166
167         if(in != stdin) {
168                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s %s", flags, fname);
169         } else {
170                 /* read from stdin */
171                 snprintf(buf, sizeof(buf), PREPROCESSOR " %s -", flags);
172         }
173
174         if(verbose) {
175                 puts(buf);
176         }
177         FILE* f = popen(buf, "r");
178         if (f == NULL) {
179                 fprintf(stderr, "invoking preprocessor failed\n");
180                 exit(1);
181         }
182         return f;
183 }
184
185 static void do_link(const char *out, const char *in)
186 {
187         char buf[4096];
188
189         snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out);
190         if(verbose) {
191                 puts(buf);
192         }
193         int err = system(buf);
194         if(err != 0) {
195                 fprintf(stderr, "linker reported an error\n");
196                 exit(1);
197         }
198 }
199
200 static void assemble(const char *out, const char *in)
201 {
202         char buf[4096];
203
204         snprintf(buf, sizeof(buf), "%s %s -o %s", ASSEMBLER, in, out);
205         if(verbose) {
206                 puts(buf);
207         }
208
209         int err = system(buf);
210         if(err != 0) {
211                 fprintf(stderr, "assembler reported an error\n");
212                 exit(1);
213         }
214 }
215
216 static const char *try_dir(const char *dir)
217 {
218         if(dir == NULL)
219                 return dir;
220         if(access(dir, R_OK | W_OK | X_OK) == 0)
221                 return dir;
222         return NULL;
223 }
224
225 static const char *get_tempdir(void)
226 {
227         static const char *tmpdir = NULL;
228
229         if(tmpdir != NULL)
230                 return tmpdir;
231
232         if(tmpdir == NULL)
233                 tmpdir = try_dir(getenv("TMPDIR"));
234         if(tmpdir == NULL)
235                 tmpdir = try_dir(getenv("TMP"));
236         if(tmpdir == NULL)
237                 tmpdir = try_dir(getenv("TEMP"));
238
239 #ifdef P_tmpdir
240         if(tmpdir == NULL)
241                 tmpdir = try_dir(P_tmpdir);
242 #endif
243
244         if(tmpdir == NULL)
245                 tmpdir = try_dir("/var/tmp");
246         if(tmpdir == NULL)
247                 tmpdir = try_dir("/usr/tmp");
248         if(tmpdir == NULL)
249                 tmpdir = try_dir("/tmp");
250
251         if(tmpdir == NULL)
252                 tmpdir = ".";
253
254         return tmpdir;
255 }
256
257 #ifndef HAVE_MKSTEMP
258 /* cheap and nasty mkstemp replacement */
259 static int mkstemp(char *templ)
260 {
261         mktemp(templ);
262         return open(templ, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
263 }
264 #endif
265
266 /**
267  * an own version of tmpnam, which: writes in a buffer, appends a user specified
268  * suffix, emits no warnings during linking (like glibc/gnu ld do for tmpnam)...
269  */
270 static FILE *make_temp_file(char *buffer, size_t buflen,
271                             const char *prefix, const char *suffix)
272 {
273         const char *tempdir = get_tempdir();
274
275         /* oh well... mkstemp doesn't accept a suffix after XXXXXX... */
276         (void) suffix;
277         suffix = "";
278
279         snprintf(buffer, buflen, "%s/%sXXXXXX%s", tempdir, prefix, suffix);
280
281         int fd = mkstemp(buffer);
282         if(fd == -1) {
283                 fprintf(stderr, "couldn't create temporary file: %s\n",
284                         strerror(errno));
285                 exit(1);
286         }
287         FILE *out = fdopen(fd, "w");
288         if(out == NULL) {
289                 fprintf(stderr, "couldn't create temporary file FILE*\n");
290                 exit(1);
291         }
292
293         return out;
294 }
295
296 /**
297  * Do the necessary lowering for compound parameters.
298  */
299 void lower_compound_params(void)
300 {
301         lower_params_t params;
302
303         params.def_ptr_alignment    = 4;
304         params.flags                = LF_COMPOUND_RETURN | LF_RETURN_HIDDEN;
305         params.hidden_params        = ADD_HIDDEN_ALWAYS_IN_FRONT;
306         params.find_pointer_type    = NULL;
307         params.ret_compound_in_regs = NULL;
308         lower_calls_with_compounds(&params);
309 }
310
311 typedef enum compile_mode_t {
312         ParseOnly,
313         Compile,
314         CompileDump,
315         CompileAssemble,
316         CompileAssembleLink,
317         LexTest,
318         PrintAst,
319         PrintFluffy
320 } compile_mode_t;
321
322 static void usage(const char *argv0)
323 {
324         fprintf(stderr, "Usage %s input [-o output] [-c]\n", argv0);
325 }
326
327 int main(int argc, char **argv)
328 {
329         initialize_firm();
330
331         const char     *input        = NULL;
332         const char     *outname      = NULL;
333         const char     *dumpfunction = NULL;
334         compile_mode_t  mode         = CompileAssembleLink;
335
336         obstack_init(&cppflags_obst);
337
338 #define GET_ARG_AFTER(def, args)                                             \
339         def = &arg[sizeof(args)-1];                                              \
340         if(def[0] == '\0') {                                                     \
341                 ++i;                                                                 \
342                 if(i >= argc) {                                                      \
343                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
344                         argument_errors = true;                                          \
345                         break;                                                           \
346                 }                                                                    \
347                 def = argv[i];                                                       \
348                 if(def[0] == '-' && def[1] != '\0') {                                \
349                         fprintf(stderr, "error: expected argument after '" args "'\n");  \
350                         argument_errors = true;                                          \
351                         continue;                                                        \
352                 }                                                                    \
353         }
354
355         bool help_displayed  = false;
356         bool argument_errors = false;
357         for(int i = 1; i < argc; ++i) {
358                 const char *arg = argv[i];
359                 if(strncmp(arg, "-o", 2) == 0) {
360                         GET_ARG_AFTER(outname, "-o");
361                 } else if(strcmp(arg, "-c") == 0) {
362                         mode = CompileAssemble;
363                 } else if(strcmp(arg, "-S") == 0) {
364                         mode = Compile;
365                 } else if(strcmp(arg, "--gcc") == 0) {
366                         c_mode |= _GNUC;
367                 } else if(strcmp(arg, "--no-gcc") == 0) {
368                         c_mode &= ~_GNUC;
369                 } else if(strcmp(arg, "--ms") == 0) {
370                         c_mode |= _MS;
371                 } else if(strcmp(arg, "--signed-chars") == 0) {
372                         char_is_signed = true;
373                 } else if(strcmp(arg, "--unsigned-chars") == 0) {
374                         char_is_signed = false;
375                 } else if(strcmp(arg, "--strict") == 0) {
376                         strict_mode = true;
377                 } else if(strcmp(arg, "--no-ms") == 0) {
378                         c_mode &= ~_MS;
379                 } else if(strcmp(arg, "--lextest") == 0) {
380                         mode = LexTest;
381                 } else if(strcmp(arg, "--print-ast") == 0) {
382                         mode = PrintAst;
383                 } else if(strcmp(arg, "--print-fluffy") == 0) {
384                         mode = PrintFluffy;
385                 } else if(strcmp(arg, "--version") == 0) {
386                         firm_version_t ver;
387                         firm_get_version(&ver);
388                         printf("cparser (%d.%d %s) using libFirm (%u.%u", 0, 1, cparser_REVISION, ver.major, ver.minor);
389                         if(ver.revision[0] != 0) {
390                                 putchar(' ');
391                                 fputs(ver.revision, stdout);
392                         }
393                         if(ver.build[0] != 0) {
394                                 putchar(' ');
395                                 fputs(ver.build, stdout);
396                         }
397                         puts(")\n");
398                         exit(EXIT_SUCCESS);
399                 } else if(strcmp(arg, "-fsyntax-only") == 0) {
400                         mode = ParseOnly;
401                 } else if(strncmp(arg, "-I", 2) == 0) {
402                         const char *opt;
403                         GET_ARG_AFTER(opt, "-I");
404                         obstack_printf(&cppflags_obst, " -I%s", opt);
405                 } else if(strncmp(arg, "-D", 2) == 0) {
406                         const char *opt;
407                         GET_ARG_AFTER(opt, "-D");
408                         obstack_printf(&cppflags_obst, " -D%s", opt);
409                 } else if(strncmp(arg, "-U", 2) == 0) {
410                         const char *opt;
411                         GET_ARG_AFTER(opt, "-U");
412                         obstack_printf(&cppflags_obst, " -U%s", opt);
413                 } else if(strcmp(arg, "--dump-function") == 0) {
414                         ++i;
415                         if(i >= argc) {
416                                 fprintf(stderr, "error: "
417                                         "expected argument after '--dump-function'\n");
418                                 argument_errors = true;
419                                 break;
420                         }
421                         dumpfunction = argv[i];
422                         mode         = CompileDump;
423                 } else if(strcmp(arg, "-v") == 0) {
424                         verbose = 1;
425                 } else if(strcmp(arg, "-w") == 0) {
426                         inhibit_all_warnings = true;
427                 } else if(arg[0] == '-' && arg[1] == 'f') {
428                         const char *opt;
429                         GET_ARG_AFTER(opt, "-f");
430
431                         if(strcmp(opt, "omit-frame-pointer") == 0) {
432                                 firm_be_option("omitfp");
433                         } else if(strcmp(opt, "no-omit-frame-pointer") == 0) {
434                                 firm_be_option("omitfp=no");
435                         } else {
436                                 int res = firm_option(opt);
437                                 if (res == 0) {
438                                         fprintf(stderr, "error: unknown Firm option '-f %s'\n",
439                                                 opt);
440                                         argument_errors = true;
441                                         continue;
442                                 } else if (res == -1) {
443                                         help_displayed = true;
444                                 }
445                         }
446                 } else if(arg[0] == '-' && arg[1] == 'b') {
447                         const char *opt;
448                         GET_ARG_AFTER(opt, "-b");
449                         int res = firm_be_option(opt);
450                         if (res == 0) {
451                                 fprintf(stderr, "error: unknown Firm backend option '-b %s'\n",
452                                         opt);
453                                 argument_errors = true;
454                         } else if (res == -1) {
455                                 help_displayed = true;
456                         }
457                 } else if(arg[0] == '-' && arg[1] == 'W') {
458                         const char *opt;
459                         GET_ARG_AFTER(opt, "-W");
460                         set_warning_opt(opt);
461                 } else if(arg[0] == '-' && arg[1] == 'm') {
462                         const char *opt;
463                         GET_ARG_AFTER(opt, "-m");
464                         char *endptr;
465                         long int value = strtol(opt, &endptr, 10);
466                         if (*endptr != '\0') {
467                                 fprintf(stderr, "error: wrong option '-m %s'\n",  opt);
468                                 argument_errors = true;
469                         }
470                         if (value != 16 && value != 32 && value != 64) {
471                                 fprintf(stderr, "error: option -m supports only 16, 32 or 64\n");
472                                 argument_errors = true;
473                         } else {
474                                 machine_size = (unsigned int)value;
475                         }
476                 } else if(arg[0] == '-') {
477                         if (arg[1] == '\0') {
478                                 if(input != NULL) {
479                                         fprintf(stderr, "error: multiple input files specified\n");
480                                         argument_errors = true;
481                                 } else {
482                                         input = arg;
483                                 }
484                         } else if(strcmp(arg, "-pedantic") == 0) {
485                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
486                         } else if(arg[1] == 'O' ||
487                                         arg[1] == 'g' ||
488                                         strncmp(arg + 1, "std=", 4) == 0) {
489                                 fprintf(stderr, "warning: ignoring gcc option '%s'\n", arg);
490                         } else {
491                                 fprintf(stderr, "error: unknown argument '%s'\n", arg);
492                                 argument_errors = true;
493                         }
494                 } else {
495                         if(input != NULL) {
496                                 fprintf(stderr, "error: multiple input files specified\n");
497                                 argument_errors = true;
498                         } else {
499                                 input = arg;
500                         }
501                 }
502         }
503
504         /* we do the lowering in ast2firm */
505         firm_opt.lower_bitfields = FALSE;
506
507         if(help_displayed) {
508                 return !argument_errors;
509         }
510         if(argument_errors) {
511                 usage(argv[0]);
512                 return 1;
513         }
514
515         gen_firm_init();
516         init_symbol_table();
517         init_tokens();
518         init_types();
519         init_typehash();
520         init_basic_types();
521         init_lexer();
522         init_ast();
523         init_parser();
524         init_ast2firm();
525
526         FILE *out = NULL;
527         char  outnamebuf[4096];
528         if(outname == NULL) {
529                 switch(mode) {
530                 case PrintAst:
531                 case PrintFluffy:
532                 case LexTest:
533                         if(outname == NULL)
534                                 outname = "-";
535                         break;
536                 case ParseOnly:
537                         break;
538                 case Compile:
539                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".s");
540                         outname = outnamebuf;
541                         break;
542                 case CompileAssemble:
543                         get_output_name(outnamebuf, sizeof(outnamebuf), input, ".o");
544                         outname = outnamebuf;
545                         break;
546                 case CompileDump:
547                         get_output_name(outnamebuf, sizeof(outnamebuf), dumpfunction,
548                                         ".vcg");
549                         outname = outnamebuf;
550                         break;
551                 case CompileAssembleLink:
552                         outname = "a.out";
553                         break;
554                 }
555         }
556
557         if(outname != NULL) {
558                 if(strcmp(outname, "-") == 0) {
559                         out = stdout;
560                 } else {
561                         out = fopen(outname, "w");
562                         if(out == NULL) {
563                                 fprintf(stderr, "Couldn't open '%s' for writing: %s\n", outname,
564                                         strerror(errno));
565                                 return 1;
566                         }
567                 }
568         }
569
570         FILE *in;
571         if(input == NULL) {
572                 fprintf(stderr, "%s: no input files\n", argv[0]);
573                 return 1;
574         } else if(strcmp(input, "-") == 0) {
575                 in    = stdin;
576                 input = "<stdin>";
577         } else {
578                 in = fopen(input, "r");
579                 if(in == NULL) {
580                         fprintf(stderr, "Couldn't open '%s': %s\n", input, strerror(errno));
581                         return 1;
582                 }
583         }
584
585         if(mode == LexTest) {
586                 lextest(in, input);
587                 fclose(in);
588                 return 0;
589         }
590
591         FILE *preprocessed_in = preprocess(in, input);
592         translation_unit_t *const unit = do_parsing(preprocessed_in, input);
593         int result = pclose(preprocessed_in);
594         if(result != 0) {
595                 return result;
596         }
597         if(unit == NULL) {
598                 /* parsing failed because of errors */
599                 fprintf(stderr, "%u error(s), %u warning(s)\n", error_count, warning_count);
600                 return EXIT_FAILURE;
601         }
602         if (warning_count > 0) {
603                 fprintf(stderr, "%u warning(s)\n", warning_count);
604         }
605
606         if(mode == PrintAst) {
607                 type_set_output(out);
608                 ast_set_output(out);
609                 print_ast(unit);
610                 return 0;
611         }
612         if(mode == PrintFluffy) {
613                 type_set_output(out);
614                 ast_set_output(out);
615                 write_fluffy_decls(out, unit);
616         }
617
618         translation_unit_to_firm(unit);
619
620         if(mode == ParseOnly) {
621                 return 0;
622         }
623
624         FILE *asm_out;
625         char  asm_tempfile[1024];
626         if(mode == CompileDump) {
627                 asm_out = NULL;
628                 firm_be_opt.selection = BE_NONE;
629         } else if(mode == Compile) {
630                 asm_out = out;
631         } else {
632                 asm_out
633                         = make_temp_file(asm_tempfile, sizeof(asm_tempfile), "cc", ".s");
634         }
635         gen_firm_finish(asm_out, input, /*c_mode=*/1, /*firm_const_exists=*/0);
636
637         if(mode == CompileDump) {
638                 /* find irg */
639                 ident    *id     = new_id_from_str(dumpfunction);
640                 ir_graph *irg    = NULL;
641                 int       n_irgs = get_irp_n_irgs();
642                 for(int i = 0; i < n_irgs; ++i) {
643                         ir_graph *tirg   = get_irp_irg(i);
644                         ident    *irg_id = get_entity_ident(get_irg_entity(tirg));
645                         if(irg_id == id) {
646                                 irg = tirg;
647                                 break;
648                         }
649                 }
650
651                 if(irg == NULL) {
652                         fprintf(stderr, "No graph for function '%s' found\n", dumpfunction);
653                         return 1;
654                 }
655
656                 dump_ir_block_graph_file(irg, out);
657                 fclose(out);
658                 return 0;
659         }
660
661         fclose(asm_out);
662
663         /* assemble assembler and create object file */
664         char obj_tfile[1024];
665         if(mode == CompileAssemble || mode == CompileAssembleLink) {
666                 const char *obj_outfile;
667                 if(mode == CompileAssemble) {
668                         fclose(out);
669                         obj_outfile = outname;
670                 } else {
671                         FILE *tempf
672                                 = make_temp_file(obj_tfile, sizeof(obj_tfile), "cc", ".o");
673                         fclose(tempf);
674                         obj_outfile = obj_tfile;
675                 }
676
677                 assemble(obj_outfile, asm_tempfile);
678         }
679
680         /* link object file */
681         if(mode == CompileAssembleLink) {
682                 do_link(outname, obj_tfile);
683         }
684
685         obstack_free(&cppflags_obst, NULL);
686
687         exit_ast2firm();
688         exit_parser();
689         exit_ast();
690         exit_lexer();
691         exit_typehash();
692         exit_types();
693         exit_tokens();
694         exit_symbol_table();
695         return 0;
696 }