* get rid of diagnistic.[ch], pretty-print.[ch],
[fw/sdcc] / support / cpp2 / opts.c
1 /* Command line option handling.
2    Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
3    Contributed by Neil Booth.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "intl.h"
25 #include "opts.h"
26 #include "options.h"
27
28 /* True if we should exit after parsing options.  */
29 bool exit_after_options;
30
31 /* Treat warnings as errors.  -Werror.  */
32 bool warnings_are_errors;
33
34 /* Don't suppress warnings from system headers.  -Wsystem-headers.  */
35 bool warn_system_headers;
36
37 /* Columns of --help display.  */
38 static unsigned int columns = 80;
39
40 /* What to print when a switch has no documentation.  */
41 static const char undocumented_msg[] = N_("This switch lacks documentation");
42
43 /* Input file names.  */
44 const char **in_fnames;
45 unsigned num_in_fnames;
46
47 static size_t find_opt (const char *, int);
48 static int common_handle_option (size_t scode, const char *arg, int value);
49 static unsigned int handle_option (const char **argv, unsigned int lang_mask);
50 static char *write_langs (unsigned int lang_mask);
51 static void complain_wrong_lang (const char *, const struct cl_option *,
52                                  unsigned int lang_mask);
53 static void handle_options (unsigned int, const char **, unsigned int);
54 static void wrap_help (const char *help, const char *item, unsigned int);
55 static void print_help (void);
56 static void print_filtered_help (unsigned int flag);
57 static unsigned int print_switch (const char *text, unsigned int indent);
58
59 /* Perform a binary search to find which option the command-line INPUT
60    matches.  Returns its index in the option array, and N_OPTS
61    (cl_options_count) on failure.
62
63    This routine is quite subtle.  A normal binary search is not good
64    enough because some options can be suffixed with an argument, and
65    multiple sub-matches can occur, e.g. input of "-pedantic" matching
66    the initial substring of "-pedantic-errors".
67
68    A more complicated example is -gstabs.  It should match "-g" with
69    an argument of "stabs".  Suppose, however, that the number and list
70    of switches are such that the binary search tests "-gen-decls"
71    before having tested "-g".  This doesn't match, and as "-gen-decls"
72    is less than "-gstabs", it will become the lower bound of the
73    binary search range, and "-g" will never be seen.  To resolve this
74    issue, opts.sh makes "-gen-decls" point, via the back_chain member,
75    to "-g" so that failed searches that end between "-gen-decls" and
76    the lexicographically subsequent switch know to go back and see if
77    "-g" causes a match (which it does in this example).
78
79    This search is done in such a way that the longest match for the
80    front end in question wins.  If there is no match for the current
81    front end, the longest match for a different front end is returned
82    (or N_OPTS if none) and the caller emits an error message.  */
83 static size_t
84 find_opt (const char *input, int lang_mask)
85 {
86   size_t mn, mx, md, opt_len;
87   size_t match_wrong_lang;
88   int comp;
89
90   mn = 0;
91   mx = cl_options_count;
92
93   /* Find mn such this lexicographical inequality holds:
94      cl_options[mn] <= input < cl_options[mn + 1].  */
95   while (mx - mn > 1)
96     {
97       md = (mn + mx) / 2;
98       opt_len = cl_options[md].opt_len;
99       comp = strncmp (input, cl_options[md].opt_text + 1, opt_len);
100
101       if (comp < 0)
102         mx = md;
103       else
104         mn = md;
105     }
106
107   /* This is the switch that is the best match but for a different
108      front end, or cl_options_count if there is no match at all.  */
109   match_wrong_lang = cl_options_count;
110
111   /* Backtrace the chain of possible matches, returning the longest
112      one, if any, that fits best.  With current GCC switches, this
113      loop executes at most twice.  */
114   do
115     {
116       const struct cl_option *opt = &cl_options[mn];
117
118       /* Is the input either an exact match or a prefix that takes a
119          joined argument?  */
120       if (!strncmp (input, opt->opt_text + 1, opt->opt_len)
121           && (input[opt->opt_len] == '\0' || (opt->flags & CL_JOINED)))
122         {
123           /* If language is OK, return it.  */
124           if (opt->flags & lang_mask)
125
126
127           /* If we haven't remembered a prior match, remember this
128              one.  Any prior match is necessarily better.  */
129           if (match_wrong_lang == cl_options_count)
130             match_wrong_lang = mn;
131         }
132
133       /* Try the next possibility.  This is cl_options_count if there
134          are no more.  */
135       mn = opt->back_chain;
136     }
137   while (mn != cl_options_count);
138
139   /* Return the best wrong match, or cl_options_count if none.  */
140   return match_wrong_lang;
141 }
142
143 /* If ARG is a non-negative integer made up solely of digits, return its
144    value, otherwise return -1.  */
145 static int
146 integral_argument (const char *arg)
147 {
148   const char *p = arg;
149
150   while (*p && ISDIGIT (*p))
151     p++;
152
153   if (*p == '\0')
154     return atoi (arg);
155
156   return -1;
157 }
158
159 /* Return a malloced slash-separated list of languages in MASK.  */
160 static char *
161 write_langs (unsigned int mask)
162 {
163   unsigned int n = 0, len = 0;
164   const char *lang_name;
165   char *result;
166
167   for (n = 0; (lang_name = lang_names[n]) != 0; n++)
168     if (mask & (1U << n))
169       len += strlen (lang_name) + 1;
170
171   result = xmalloc (len);
172   len = 0;
173   for (n = 0; (lang_name = lang_names[n]) != 0; n++)
174     if (mask & (1U << n))
175       {
176         if (len)
177           result[len++] = '/';
178         strcpy (result + len, lang_name);
179         len += strlen (lang_name);
180       }
181
182   result[len] = 0;
183
184   return result;
185 }
186
187 /* Complain that switch OPT_INDEX does not apply to this front end.  */
188 static void
189 complain_wrong_lang (const char *text, const struct cl_option *option,
190                      unsigned int lang_mask)
191 {
192   char *ok_langs, *bad_lang;
193
194   ok_langs = write_langs (option->flags);
195   bad_lang = write_langs (lang_mask);
196
197   /* Eventually this should become a hard error IMO.  */
198   warning (0, "command line option \"%s\" is valid for %s but not for %s",
199            text, ok_langs, bad_lang);
200
201   free (ok_langs);
202   free (bad_lang);
203 }
204
205 /* Handle the switch beginning at ARGV for the language indicated by
206    LANG_MASK.  Returns the number of switches consumed.  */
207 static unsigned int
208 handle_option (const char **argv, unsigned int lang_mask)
209 {
210   size_t opt_index;
211   const char *opt, *arg = 0;
212   char *dup = 0;
213   int value = 1;
214   unsigned int result = 0;
215   const struct cl_option *option;
216
217   opt = argv[0];
218
219   opt_index = find_opt (opt + 1, lang_mask | CL_COMMON | CL_TARGET);
220   if (opt_index == cl_options_count
221       && (opt[1] == 'W' || opt[1] == 'f' || opt[1] == 'm')
222       && opt[2] == 'n' && opt[3] == 'o' && opt[4] == '-')
223     {
224       /* Drop the "no-" from negative switches.  */
225       size_t len = strlen (opt) - 3;
226
227       dup = xmalloc (len + 1);
228       dup[0] = '-';
229       dup[1] = opt[1];
230       memcpy (dup + 2, opt + 5, len - 2 + 1);
231       opt = dup;
232       value = 0;
233       opt_index = find_opt (opt + 1, lang_mask | CL_COMMON | CL_TARGET);
234     }
235
236   if (opt_index == cl_options_count)
237     goto done;
238
239   option = &cl_options[opt_index];
240
241   /* Reject negative form of switches that don't take negatives as
242      unrecognized.  */
243   if (!value && (option->flags & CL_REJECT_NEGATIVE))
244     goto done;
245
246   /* We've recognized this switch.  */
247   result = 1;
248
249   /* Check to see if the option is disabled for this configuration.  */
250   if (option->flags & CL_DISABLED)
251     {
252       error ("command line option \"%s\""
253              " is not supported by this configuration", opt);
254       goto done;
255     }
256
257   /* Sort out any argument the switch takes.  */
258   if (option->flags & CL_JOINED)
259     {
260       /* Have arg point to the original switch.  This is because
261          some code, such as disable_builtin_function, expects its
262          argument to be persistent until the program exits.  */
263       arg = argv[0] + cl_options[opt_index].opt_len + 1;
264       if (!value)
265         arg += strlen ("no-");
266
267       if (*arg == '\0' && !(option->flags & CL_MISSING_OK))
268         {
269           if (option->flags & CL_SEPARATE)
270             {
271               arg = argv[1];
272               result = 2;
273             }
274           else
275             /* Missing argument.  */
276             arg = NULL;
277         }
278     }
279   else if (option->flags & CL_SEPARATE)
280     {
281       arg = argv[1];
282       result = 2;
283     }
284
285   /* Now we've swallowed any potential argument, complain if this
286      is a switch for a different front end.  */
287   if (!(option->flags & (lang_mask | CL_COMMON | CL_TARGET)))
288     {
289       complain_wrong_lang (argv[0], option, lang_mask);
290       goto done;
291     }
292
293   if (arg == NULL && (option->flags & (CL_JOINED | CL_SEPARATE)))
294     {
295       if (!lang_hooks.missing_argument (opt, opt_index))
296         error ("missing argument to \"%s\"", opt);
297       goto done;
298     }
299
300   /* If the switch takes an integer, convert it.  */
301   if (arg && (option->flags & CL_UINTEGER))
302     {
303       value = integral_argument (arg);
304       if (value == -1)
305         {
306           error ("argument to \"%s\" should be a non-negative integer",
307                  option->opt_text);
308           goto done;
309         }
310     }
311
312   if (option->flag_var)
313     switch (option->var_type)
314       {
315       case CLVC_BOOLEAN:
316         *(int *) option->flag_var = value;
317         break;
318
319       case CLVC_EQUAL:
320         *(int *) option->flag_var = (value
321                                      ? option->var_value
322                                      : !option->var_value);
323         break;
324
325       case CLVC_BIT_CLEAR:
326       case CLVC_BIT_SET:
327         if ((value != 0) == (option->var_type == CLVC_BIT_SET))
328           *(int *) option->flag_var |= option->var_value;
329         else
330           *(int *) option->flag_var &= ~option->var_value;
331         ////if (option->flag_var == &target_flags)
332         ////  target_flags_explicit |= option->var_value;
333         break;
334
335       case CLVC_STRING:
336         *(const char **) option->flag_var = arg;
337         break;
338       }
339
340   if (option->flags & lang_mask)
341     if ((*lang_hooks.handle_option) (opt_index, arg, value) == 0)
342       result = 0;
343
344   if (result && (option->flags & CL_COMMON))
345     if (common_handle_option (opt_index, arg, value) == 0)
346       result = 0;
347
348   ////if (result && (option->flags & CL_TARGET))
349   ////  if (!targetm.handle_option (opt_index, arg, value))
350   ////    result = 0;
351
352  done:
353   if (dup)
354     free (dup);
355   return result;
356 }
357
358 /* Handle FILENAME from the command line.  */
359 void
360 add_input_filename (const char *filename)
361 {
362   num_in_fnames++;
363   in_fnames = xrealloc (in_fnames, num_in_fnames * sizeof (in_fnames[0]));
364   in_fnames[num_in_fnames - 1] = filename;
365 }
366
367 /* Decode and handle the vector of command line options.  LANG_MASK
368    contains has a single bit set representing the current
369    language.  */
370 static void
371 handle_options (unsigned int argc, const char **argv, unsigned int lang_mask)
372 {
373   unsigned int n, i;
374
375   for (i = 1; i < argc; i += n)
376     {
377       const char *opt = argv[i];
378
379       /* Interpret "-" or a non-switch as a file name.  */
380       if (opt[0] != '-' || opt[1] == '\0')
381         {
382           if (main_input_filename == NULL)
383             main_input_filename = opt;
384           add_input_filename (opt);
385           n = 1;
386           continue;
387         }
388
389       n = handle_option (argv + i, lang_mask);
390
391       if (!n)
392         {
393           n = 1;
394           error ("unrecognized command line option \"%s\"", opt);
395         }
396     }
397 }
398
399 /* Parse command line options and set default flag values.  Do minimal
400    options processing.  */
401 void
402 decode_options (unsigned int argc, const char **argv)
403 {
404   unsigned int lang_mask;
405
406   /* Perform language-specific options initialization.  */
407   lang_mask = lang_hooks.init_options (argc, argv);
408
409   /* Scan to see what optimization level has been specified.  That will
410      determine the default value of many flags.  */
411
412   handle_options (argc, argv, lang_mask);
413 }
414
415 /* Handle target- and language-independent options.  Return zero to
416    generate an "unknown option" message.  Only options that need
417    extra handling need to be listed here; if you simply want
418    VALUE assigned to a variable, it happens automatically.  */
419
420 static int
421 common_handle_option (size_t scode, const char *arg,
422                       int value ATTRIBUTE_UNUSED)
423 {
424   enum opt_code code = (enum opt_code) scode;
425
426   switch (code)
427     {
428     default:
429       abort ();
430
431     case OPT__help:
432       print_help ();
433       exit_after_options = true;
434       break;
435
436     case OPT__version:
437       print_version (stderr, "");
438       exit_after_options = true;
439       break;
440
441     case OPT_Werror:
442       warnings_are_errors = value;
443       break;
444
445     case OPT_Wsystem_headers:
446       warn_system_headers = value;
447       break;
448
449     case OPT_d:
450       decode_d_option (arg);
451       break;
452
453     case OPT_pedantic_errors:
454       flag_pedantic_errors = 1;
455       break;
456
457     case OPT_w:
458       inhibit_warnings = true;
459       break;
460     }
461
462   return 1;
463 }
464
465 /* Output --help text.  */
466 static void
467 print_help (void)
468 {
469   size_t i;
470   const char *p;
471
472   GET_ENVIRONMENT (p, "COLUMNS");
473   if (p)
474     {
475       int value = atoi (p);
476       if (value > 0)
477         columns = value;
478     }
479
480   puts (_("The following options are language-independent:\n"));
481
482   print_filtered_help (CL_COMMON);
483
484   for (i = 0; lang_names[i]; i++)
485     {
486       printf (_("The %s front end recognizes the following options:\n\n"),
487               lang_names[i]);
488       print_filtered_help (1U << i);
489     }
490 }
491
492 /* Print help for a specific front-end, etc.  */
493 static void
494 print_filtered_help (unsigned int flag)
495 {
496   unsigned int i, len, filter, indent = 0;
497   bool duplicates = false;
498   const char *help, *opt, *tab;
499   static char *printed;
500
501   if (flag == CL_COMMON || flag == CL_TARGET)
502     {
503       filter = flag;
504       if (!printed)
505         printed = xmalloc (cl_options_count);
506       memset (printed, 0, cl_options_count);
507     }
508   else
509     {
510       /* Don't print COMMON options twice.  */
511       filter = flag | CL_COMMON;
512
513       for (i = 0; i < cl_options_count; i++)
514         {
515           if ((cl_options[i].flags & filter) != flag)
516             continue;
517
518           /* Skip help for internal switches.  */
519           if (cl_options[i].flags & CL_UNDOCUMENTED)
520             continue;
521
522           /* Skip switches that have already been printed, mark them to be
523              listed later.  */
524           if (printed[i])
525             {
526               duplicates = true;
527               indent = print_switch (cl_options[i].opt_text, indent);
528             }
529         }
530
531       if (duplicates)
532         {
533           putchar ('\n');
534           putchar ('\n');
535         }
536     }
537
538   for (i = 0; i < cl_options_count; i++)
539     {
540       if ((cl_options[i].flags & filter) != flag)
541         continue;
542
543       /* Skip help for internal switches.  */
544       if (cl_options[i].flags & CL_UNDOCUMENTED)
545         continue;
546
547       /* Skip switches that have already been printed.  */
548       if (printed[i])
549         continue;
550
551       printed[i] = true;
552
553       help = cl_options[i].help;
554       if (!help)
555         help = undocumented_msg;
556
557       /* Get the translation.  */
558       help = _(help);
559
560       tab = strchr (help, '\t');
561       if (tab)
562         {
563           len = tab - help;
564           opt = help;
565           help = tab + 1;
566         }
567       else
568         {
569           opt = cl_options[i].opt_text;
570           len = strlen (opt);
571         }
572
573       wrap_help (help, opt, len);
574     }
575
576   putchar ('\n');
577 }
578
579 /* Output ITEM, of length ITEM_WIDTH, in the left column, followed by
580    word-wrapped HELP in a second column.  */
581 static unsigned int
582 print_switch (const char *text, unsigned int indent)
583 {
584   unsigned int len = strlen (text) + 1; /* trailing comma */
585
586   if (indent)
587     {
588       putchar (',');
589       if (indent + len > columns)
590         {
591           putchar ('\n');
592           putchar (' ');
593           indent = 1;
594         }
595     }
596   else
597     putchar (' ');
598
599   putchar (' ');
600   fputs (text, stdout);
601
602   return indent + len + 1;
603 }
604
605 /* Output ITEM, of length ITEM_WIDTH, in the left column, followed by
606    word-wrapped HELP in a second column.  */
607 static void
608 wrap_help (const char *help, const char *item, unsigned int item_width)
609 {
610   unsigned int col_width = 27;
611   unsigned int remaining, room, len;
612
613   remaining = strlen (help);
614
615   do
616     {
617       room = columns - 3 - MAX (col_width, item_width);
618       if (room > columns)
619         room = 0;
620       len = remaining;
621
622       if (room < len)
623         {
624           unsigned int i;
625
626           for (i = 0; help[i]; i++)
627             {
628               if (i >= room && len != remaining)
629                 break;
630               if (help[i] == ' ')
631                 len = i;
632               else if ((help[i] == '-' || help[i] == '/')
633                        && help[i + 1] != ' '
634                        && i > 0 && ISALPHA (help[i - 1]))
635                 len = i + 1;
636             }
637         }
638
639       printf( "  %-*.*s %.*s\n", col_width, item_width, item, len, help);
640       item_width = 0;
641       while (help[len] == ' ')
642         len++;
643       help += len;
644       remaining -= len;
645     }
646   while (remaining);
647 }
648
649 /* Return 1 if OPTION is enabled, 0 if it is disabled, or -1 if it isn't
650    a simple on-off switch.  */
651
652 int
653 option_enabled (int opt_idx)
654 {
655   const struct cl_option *option = &(cl_options[opt_idx]);
656   if (option->flag_var)
657     switch (option->var_type)
658       {
659       case CLVC_BOOLEAN:
660         return *(int *) option->flag_var != 0;
661
662       case CLVC_EQUAL:
663         return *(int *) option->flag_var == option->var_value;
664
665       case CLVC_BIT_CLEAR:
666         return (*(int *) option->flag_var & option->var_value) == 0;
667
668       case CLVC_BIT_SET:
669         return (*(int *) option->flag_var & option->var_value) != 0;
670
671       case CLVC_STRING:
672         break;
673       }
674   return -1;
675 }
676
677 /* Fill STATE with the current state of option OPTION.  Return true if
678    there is some state to store.  */
679
680 bool
681 get_option_state (int option, struct cl_option_state *state)
682 {
683   if (cl_options[option].flag_var == 0)
684     return false;
685
686   switch (cl_options[option].var_type)
687     {
688     case CLVC_BOOLEAN:
689     case CLVC_EQUAL:
690       state->data = cl_options[option].flag_var;
691       state->size = sizeof (int);
692       break;
693
694     case CLVC_BIT_CLEAR:
695     case CLVC_BIT_SET:
696       state->ch = option_enabled (option);
697       state->data = &state->ch;
698       state->size = 1;
699       break;
700
701     case CLVC_STRING:
702       state->data = *(const char **) cl_options[option].flag_var;
703       if (state->data == 0)
704         state->data = "";
705       state->size = strlen (state->data) + 1;
706       break;
707     }
708   return true;
709 }