gdb - Local mods (compile)
[dragonfly.git] / contrib / gcc-5.0 / gcc / read-md.c
1 /* MD reader for GCC.
2    Copyright (C) 1987-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 #include "bconfig.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "hashtab.h"
24 #include "errors.h"
25 #include "read-md.h"
26
27 /* Associates PTR (which can be a string, etc.) with the file location
28    specified by FILENAME and LINENO.  */
29 struct ptr_loc {
30   const void *ptr;
31   const char *filename;
32   int lineno;
33 };
34
35 /* A singly-linked list of filenames.  */
36 struct file_name_list {
37   struct file_name_list *next;
38   const char *fname;
39 };
40
41 /* Obstack used for allocating MD strings.  */
42 struct obstack string_obstack;
43
44 /* A table of ptr_locs, hashed on the PTR field.  */
45 static htab_t ptr_locs;
46
47 /* An obstack for the above.  Plain xmalloc is a bit heavyweight for a
48    small structure like ptr_loc.  */
49 static struct obstack ptr_loc_obstack;
50
51 /* A hash table of triples (A, B, C), where each of A, B and C is a condition
52    and A is equivalent to "B && C".  This is used to keep track of the source
53    of conditions that are made up of separate MD strings (such as the split
54    condition of a define_insn_and_split).  */
55 static htab_t joined_conditions;
56
57 /* An obstack for allocating joined_conditions entries.  */
58 static struct obstack joined_conditions_obstack;
59
60 /* The file we are reading.  */
61 FILE *read_md_file;
62
63 /* The filename of READ_MD_FILE.  */
64 const char *read_md_filename;
65
66 /* The current line number in READ_MD_FILE.  */
67 int read_md_lineno;
68
69 /* The name of the toplevel file that indirectly included READ_MD_FILE.  */
70 const char *in_fname;
71
72 /* The directory part of IN_FNAME.  NULL if IN_FNAME is a bare filename.  */
73 static char *base_dir;
74
75 /* The first directory to search.  */
76 static struct file_name_list *first_dir_md_include;
77
78 /* A pointer to the null terminator of the md include chain.  */
79 static struct file_name_list **last_dir_md_include_ptr = &first_dir_md_include;
80
81 /* This callback will be invoked whenever an md include directive is
82    processed.  To be used for creation of the dependency file.  */
83 void (*include_callback) (const char *);
84
85 /* The current maximum length of directory names in the search path
86    for include files.  (Altered as we get more of them.)  */
87 static size_t max_include_len;
88
89 /* A table of md_constant structures, hashed by name.  Null if no
90    constant expansion should occur.  */
91 static htab_t md_constants;
92
93 /* A table of enum_type structures, hashed by name.  */
94 static htab_t enum_types;
95
96 static void handle_file (directive_handler_t);
97
98 /* Given an object that starts with a char * name field, return a hash
99    code for its name.  */
100
101 hashval_t
102 leading_string_hash (const void *def)
103 {
104   return htab_hash_string (*(const char *const *) def);
105 }
106
107 /* Given two objects that start with char * name fields, return true if
108    they have the same name.  */
109
110 int
111 leading_string_eq_p (const void *def1, const void *def2)
112 {
113   return strcmp (*(const char *const *) def1,
114                  *(const char *const *) def2) == 0;
115 }
116
117 /* Return a hash value for the pointer pointed to by DEF.  */
118
119 static hashval_t
120 leading_ptr_hash (const void *def)
121 {
122   return htab_hash_pointer (*(const void *const *) def);
123 }
124
125 /* Return true if DEF1 and DEF2 are pointers to the same pointer.  */
126
127 static int
128 leading_ptr_eq_p (const void *def1, const void *def2)
129 {
130   return *(const void *const *) def1 == *(const void *const *) def2;
131 }
132
133 /* Associate PTR with the file position given by FILENAME and LINENO.  */
134
135 static void
136 set_md_ptr_loc (const void *ptr, const char *filename, int lineno)
137 {
138   struct ptr_loc *loc;
139
140   loc = (struct ptr_loc *) obstack_alloc (&ptr_loc_obstack,
141                                           sizeof (struct ptr_loc));
142   loc->ptr = ptr;
143   loc->filename = filename;
144   loc->lineno = lineno;
145   *htab_find_slot (ptr_locs, loc, INSERT) = loc;
146 }
147
148 /* Return the position associated with pointer PTR.  Return null if no
149    position was set.  */
150
151 static const struct ptr_loc *
152 get_md_ptr_loc (const void *ptr)
153 {
154   return (const struct ptr_loc *) htab_find (ptr_locs, &ptr);
155 }
156
157 /* Associate NEW_PTR with the same file position as OLD_PTR.  */
158
159 void
160 copy_md_ptr_loc (const void *new_ptr, const void *old_ptr)
161 {
162   const struct ptr_loc *loc = get_md_ptr_loc (old_ptr);
163   if (loc != 0)
164     set_md_ptr_loc (new_ptr, loc->filename, loc->lineno);
165 }
166
167 /* If PTR is associated with a known file position, print a #line
168    directive for it to OUTF.  */
169
170 void
171 fprint_md_ptr_loc (FILE *outf, const void *ptr)
172 {
173   const struct ptr_loc *loc = get_md_ptr_loc (ptr);
174   if (loc != 0)
175     fprintf (outf, "#line %d \"%s\"\n", loc->lineno, loc->filename);
176 }
177
178 /* Special fprint_md_ptr_loc for writing to STDOUT.  */
179 void
180 print_md_ptr_loc (const void *ptr)
181 {
182   fprint_md_ptr_loc (stdout, ptr);
183 }
184
185 /* Return a condition that satisfies both COND1 and COND2.  Either string
186    may be null or empty.  */
187
188 const char *
189 join_c_conditions (const char *cond1, const char *cond2)
190 {
191   char *result;
192   const void **entry;
193
194   if (cond1 == 0 || cond1[0] == 0)
195     return cond2;
196
197   if (cond2 == 0 || cond2[0] == 0)
198     return cond1;
199
200   if (strcmp (cond1, cond2) == 0)
201     return cond1;
202
203   result = concat ("(", cond1, ") && (", cond2, ")", NULL);
204   obstack_ptr_grow (&joined_conditions_obstack, result);
205   obstack_ptr_grow (&joined_conditions_obstack, cond1);
206   obstack_ptr_grow (&joined_conditions_obstack, cond2);
207   entry = XOBFINISH (&joined_conditions_obstack, const void **);
208   *htab_find_slot (joined_conditions, entry, INSERT) = entry;
209   return result;
210 }
211
212 /* Print condition COND to OUTF, wrapped in brackets.  If COND was created
213    by join_c_conditions, recursively invoke this function for the original
214    conditions and join the result with "&&".  Otherwise print a #line
215    directive for COND if its original file position is known.  */
216
217 void
218 fprint_c_condition (FILE *outf, const char *cond)
219 {
220   const char **halves = (const char **) htab_find (joined_conditions, &cond);
221   if (halves != 0)
222     {
223       fprintf (outf, "(");
224       fprint_c_condition (outf, halves[1]);
225       fprintf (outf, " && ");
226       fprint_c_condition (outf, halves[2]);
227       fprintf (outf, ")");
228     }
229   else
230     {
231       fputc ('\n', outf);
232       fprint_md_ptr_loc (outf, cond);
233       fprintf (outf, "(%s)", cond);
234     }
235 }
236
237 /* Special fprint_c_condition for writing to STDOUT.  */
238
239 void
240 print_c_condition (const char *cond)
241 {
242   fprint_c_condition (stdout, cond);
243 }
244
245 /* A vfprintf-like function for reporting an error against line LINENO
246    of the current MD file.  */
247
248 static void ATTRIBUTE_PRINTF(2,0)
249 message_with_line_1 (int lineno, const char *msg, va_list ap)
250 {
251   fprintf (stderr, "%s:%d: ", read_md_filename, lineno);
252   vfprintf (stderr, msg, ap);
253   fputc ('\n', stderr);
254 }
255
256 /* A printf-like function for reporting an error against line LINENO
257    in the current MD file.  */
258
259 void
260 message_with_line (int lineno, const char *msg, ...)
261 {
262   va_list ap;
263
264   va_start (ap, msg);
265   message_with_line_1 (lineno, msg, ap);
266   va_end (ap);
267 }
268
269 /* Like message_with_line, but treat the condition as an error.  */
270
271 void
272 error_with_line (int lineno, const char *msg, ...)
273 {
274   va_list ap;
275
276   va_start (ap, msg);
277   message_with_line_1 (lineno, msg, ap);
278   va_end (ap);
279   have_error = 1;
280 }
281
282 /* A printf-like function for reporting an error against the current
283    position in the MD file.  */
284
285 void
286 fatal_with_file_and_line (const char *msg, ...)
287 {
288   char context[64];
289   size_t i;
290   int c;
291   va_list ap;
292
293   va_start (ap, msg);
294
295   fprintf (stderr, "%s:%d: ", read_md_filename, read_md_lineno);
296   vfprintf (stderr, msg, ap);
297   putc ('\n', stderr);
298
299   /* Gather some following context.  */
300   for (i = 0; i < sizeof (context)-1; ++i)
301     {
302       c = read_char ();
303       if (c == EOF)
304         break;
305       if (c == '\r' || c == '\n')
306         {
307           unread_char (c);
308           break;
309         }
310       context[i] = c;
311     }
312   context[i] = '\0';
313
314   fprintf (stderr, "%s:%d: following context is `%s'\n",
315            read_md_filename, read_md_lineno, context);
316
317   va_end (ap);
318   exit (1);
319 }
320
321 /* Report that we found character ACTUAL when we expected to find
322    character EXPECTED.  */
323
324 void
325 fatal_expected_char (int expected, int actual)
326 {
327   if (actual == EOF)
328     fatal_with_file_and_line ("expected character `%c', found EOF",
329                               expected);
330   else
331     fatal_with_file_and_line ("expected character `%c', found `%c'",
332                               expected, actual);
333 }
334
335 /* Read chars from the MD file until a non-whitespace char and return that.
336    Comments, both Lisp style and C style, are treated as whitespace.  */
337
338 int
339 read_skip_spaces (void)
340 {
341   int c;
342
343   while (1)
344     {
345       c = read_char ();
346       switch (c)
347         {
348         case ' ': case '\t': case '\f': case '\r': case '\n':
349           break;
350
351         case ';':
352           do
353             c = read_char ();
354           while (c != '\n' && c != EOF);
355           break;
356
357         case '/':
358           {
359             int prevc;
360             c = read_char ();
361             if (c != '*')
362               {
363                 unread_char (c);
364                 fatal_with_file_and_line ("stray '/' in file");
365               }
366
367             prevc = 0;
368             while ((c = read_char ()) && c != EOF)
369               {
370                 if (prevc == '*' && c == '/')
371                   break;
372                 prevc = c;
373               }
374           }
375           break;
376
377         default:
378           return c;
379         }
380     }
381 }
382
383 /* Read an rtx code name into NAME.  It is terminated by any of the
384    punctuation chars of rtx printed syntax.  */
385
386 void
387 read_name (struct md_name *name)
388 {
389   int c;
390   size_t i;
391
392   c = read_skip_spaces ();
393
394   i = 0;
395   while (1)
396     {
397       if (c == ' ' || c == '\n' || c == '\t' || c == '\f' || c == '\r'
398           || c == EOF)
399         break;
400       if (c == ':' || c == ')' || c == ']' || c == '"' || c == '/'
401           || c == '(' || c == '[')
402         {
403           unread_char (c);
404           break;
405         }
406
407       if (i == sizeof (name->buffer) - 1)
408         fatal_with_file_and_line ("name too long");
409       name->buffer[i++] = c;
410
411       c = read_char ();
412     }
413
414   if (i == 0)
415     fatal_with_file_and_line ("missing name or number");
416
417   name->buffer[i] = 0;
418   name->string = name->buffer;
419
420   if (md_constants)
421     {
422       /* Do constant expansion.  */
423       struct md_constant *def;
424
425       do
426         {
427           struct md_constant tmp_def;
428
429           tmp_def.name = name->string;
430           def = (struct md_constant *) htab_find (md_constants, &tmp_def);
431           if (def)
432             name->string = def->value;
433         }
434       while (def);
435     }
436 }
437
438 /* Subroutine of the string readers.  Handles backslash escapes.
439    Caller has read the backslash, but not placed it into the obstack.  */
440
441 static void
442 read_escape (void)
443 {
444   int c = read_char ();
445
446   switch (c)
447     {
448       /* Backslash-newline is replaced by nothing, as in C.  */
449     case '\n':
450       return;
451
452       /* \" \' \\ are replaced by the second character.  */
453     case '\\':
454     case '"':
455     case '\'':
456       break;
457
458       /* Standard C string escapes:
459          \a \b \f \n \r \t \v
460          \[0-7] \x
461          all are passed through to the output string unmolested.
462          In normal use these wind up in a string constant processed
463          by the C compiler, which will translate them appropriately.
464          We do not bother checking that \[0-7] are followed by up to
465          two octal digits, or that \x is followed by N hex digits.
466          \? \u \U are left out because they are not in traditional C.  */
467     case 'a': case 'b': case 'f': case 'n': case 'r': case 't': case 'v':
468     case '0': case '1': case '2': case '3': case '4': case '5': case '6':
469     case '7': case 'x':
470       obstack_1grow (&string_obstack, '\\');
471       break;
472
473       /* \; makes stuff for a C string constant containing
474          newline and tab.  */
475     case ';':
476       obstack_grow (&string_obstack, "\\n\\t", 4);
477       return;
478
479       /* pass anything else through, but issue a warning.  */
480     default:
481       fprintf (stderr, "%s:%d: warning: unrecognized escape \\%c\n",
482                read_md_filename, read_md_lineno, c);
483       obstack_1grow (&string_obstack, '\\');
484       break;
485     }
486
487   obstack_1grow (&string_obstack, c);
488 }
489
490 /* Read a double-quoted string onto the obstack.  Caller has scanned
491    the leading quote.  */
492
493 char *
494 read_quoted_string (void)
495 {
496   int c;
497
498   while (1)
499     {
500       c = read_char (); /* Read the string  */
501       if (c == '\\')
502         {
503           read_escape ();
504           continue;
505         }
506       else if (c == '"' || c == EOF)
507         break;
508
509       obstack_1grow (&string_obstack, c);
510     }
511
512   obstack_1grow (&string_obstack, 0);
513   return XOBFINISH (&string_obstack, char *);
514 }
515
516 /* Read a braced string (a la Tcl) onto the string obstack.  Caller
517    has scanned the leading brace.  Note that unlike quoted strings,
518    the outermost braces _are_ included in the string constant.  */
519
520 static char *
521 read_braced_string (void)
522 {
523   int c;
524   int brace_depth = 1;  /* caller-processed */
525   unsigned long starting_read_md_lineno = read_md_lineno;
526
527   obstack_1grow (&string_obstack, '{');
528   while (brace_depth)
529     {
530       c = read_char (); /* Read the string  */
531
532       if (c == '{')
533         brace_depth++;
534       else if (c == '}')
535         brace_depth--;
536       else if (c == '\\')
537         {
538           read_escape ();
539           continue;
540         }
541       else if (c == EOF)
542         fatal_with_file_and_line
543           ("missing closing } for opening brace on line %lu",
544            starting_read_md_lineno);
545
546       obstack_1grow (&string_obstack, c);
547     }
548
549   obstack_1grow (&string_obstack, 0);
550   return XOBFINISH (&string_obstack, char *);
551 }
552
553 /* Read some kind of string constant.  This is the high-level routine
554    used by read_rtx.  It handles surrounding parentheses, leading star,
555    and dispatch to the appropriate string constant reader.  */
556
557 char *
558 read_string (int star_if_braced)
559 {
560   char *stringbuf;
561   int saw_paren = 0;
562   int c, old_lineno;
563
564   c = read_skip_spaces ();
565   if (c == '(')
566     {
567       saw_paren = 1;
568       c = read_skip_spaces ();
569     }
570
571   old_lineno = read_md_lineno;
572   if (c == '"')
573     stringbuf = read_quoted_string ();
574   else if (c == '{')
575     {
576       if (star_if_braced)
577         obstack_1grow (&string_obstack, '*');
578       stringbuf = read_braced_string ();
579     }
580   else
581     fatal_with_file_and_line ("expected `\"' or `{', found `%c'", c);
582
583   if (saw_paren)
584     {
585       c = read_skip_spaces ();
586       if (c != ')')
587         fatal_expected_char (')', c);
588     }
589
590   set_md_ptr_loc (stringbuf, read_md_filename, old_lineno);
591   return stringbuf;
592 }
593
594 /* Skip the rest of a construct that started at line LINENO and that
595    is currently nested by DEPTH levels of parentheses.  */
596
597 void
598 read_skip_construct (int depth, int lineno)
599 {
600   struct md_name name;
601   int c;
602
603   do
604     {
605       c = read_skip_spaces ();
606       if (c == EOF)
607         {
608           error_with_line (lineno, "unterminated construct");
609           exit (1);
610         }
611       switch (c)
612         {
613         case '(':
614           depth++;
615           break;
616
617         case ')':
618           depth--;
619           break;
620
621         case ':':
622         case '[':
623         case ']':
624         case '/':
625           break;
626
627         case '\"':
628         case '{':
629           unread_char (c);
630           read_string (false);
631           break;
632
633         default:
634           unread_char (c);
635           read_name (&name);
636           break;
637         }
638     }
639   while (depth > 0);
640   unread_char (c);
641 }
642
643 /* Given a string, return the number of comma-separated elements in it.
644    Return 0 for the null string.  */
645
646 int
647 n_comma_elts (const char *s)
648 {
649   int n;
650
651   if (*s == '\0')
652     return 0;
653
654   for (n = 1; *s; s++)
655     if (*s == ',')
656       n++;
657
658   return n;
659 }
660
661 /* Given a pointer to a (char *), return a pointer to the beginning of the
662    next comma-separated element in the string.  Advance the pointer given
663    to the end of that element.  Return NULL if at end of string.  Caller
664    is responsible for copying the string if necessary.  White space between
665    a comma and an element is ignored.  */
666
667 const char *
668 scan_comma_elt (const char **pstr)
669 {
670   const char *start;
671   const char *p = *pstr;
672
673   if (*p == ',')
674     p++;
675   while (ISSPACE (*p))
676     p++;
677
678   if (*p == '\0')
679     return NULL;
680
681   start = p;
682
683   while (*p != ',' && *p != '\0')
684     p++;
685
686   *pstr = p;
687   return start;
688 }
689
690 /* Convert STRING to uppercase.  */
691
692 void
693 upcase_string (char *string)
694 {
695   int i;
696
697   for (i = 0; string[i]; i++)
698     string[i] = TOUPPER (string[i]);
699 }
700
701 /* Add a NAME = VALUE definition to md_constants-style hash table DEFS,
702    where both NAME and VALUE are malloc()ed strings.  PARENT_ENUM is the
703    enum to which NAME belongs, or null if NAME is a stand-alone constant.  */
704
705 static struct md_constant *
706 add_constant (htab_t defs, char *name, char *value,
707               struct enum_type *parent_enum)
708 {
709   struct md_constant *def, tmp_def;
710   void **entry_ptr;
711
712   tmp_def.name = name;
713   entry_ptr = htab_find_slot (defs, &tmp_def, INSERT);
714   if (*entry_ptr)
715     {
716       def = (struct md_constant *) *entry_ptr;
717       if (strcmp (def->value, value) != 0)
718         fatal_with_file_and_line ("redefinition of `%s', was `%s', now `%s'",
719                                   def->name, def->value, value);
720       else if (parent_enum || def->parent_enum)
721         fatal_with_file_and_line ("redefinition of `%s'", def->name);
722       free (name);
723       free (value);
724     }
725   else
726     {
727       def = XNEW (struct md_constant);
728       def->name = name;
729       def->value = value;
730       def->parent_enum = parent_enum;
731       *entry_ptr = def;
732     }
733   return def;
734 }
735
736 /* Process a define_constants directive, starting with the optional space
737    after the "define_constants".  */
738
739 static void
740 handle_constants (void)
741 {
742   int c;
743   htab_t defs;
744
745   c = read_skip_spaces ();
746   if (c != '[')
747     fatal_expected_char ('[', c);
748
749   /* Disable constant expansion during definition processing.  */
750   defs = md_constants;
751   md_constants = 0;
752   while ( (c = read_skip_spaces ()) != ']')
753     {
754       struct md_name name, value;
755
756       if (c != '(')
757         fatal_expected_char ('(', c);
758
759       read_name (&name);
760       read_name (&value);
761       add_constant (defs, xstrdup (name.string), xstrdup (value.string), 0);
762
763       c = read_skip_spaces ();
764       if (c != ')')
765         fatal_expected_char (')', c);
766     }
767   md_constants = defs;
768 }
769
770 /* For every constant definition, call CALLBACK with two arguments:
771    a pointer a pointer to the constant definition and INFO.
772    Stop when CALLBACK returns zero.  */
773
774 void
775 traverse_md_constants (htab_trav callback, void *info)
776 {
777   htab_traverse (md_constants, callback, info);
778 }
779
780 /* Return a malloc()ed decimal string that represents number NUMBER.  */
781
782 static char *
783 decimal_string (int number)
784 {
785   /* A safe overestimate.  +1 for sign, +1 for null terminator.  */
786   char buffer[sizeof (int) * CHAR_BIT + 1 + 1];
787
788   sprintf (buffer, "%d", number);
789   return xstrdup (buffer);
790 }
791
792 /* Process a define_enum or define_c_enum directive, starting with
793    the optional space after the "define_enum".  LINENO is the line
794    number on which the directive started and MD_P is true if the
795    directive is a define_enum rather than a define_c_enum.  */
796
797 static void
798 handle_enum (int lineno, bool md_p)
799 {
800   char *enum_name, *value_name;
801   struct md_name name;
802   struct enum_type *def;
803   struct enum_value *ev;
804   void **slot;
805   int c;
806
807   enum_name = read_string (false);
808   slot = htab_find_slot (enum_types, &enum_name, INSERT);
809   if (*slot)
810     {
811       def = (struct enum_type *) *slot;
812       if (def->md_p != md_p)
813         error_with_line (lineno, "redefining `%s' as a different type of enum",
814                          enum_name);
815     }
816   else
817     {
818       def = XNEW (struct enum_type);
819       def->name = enum_name;
820       def->md_p = md_p;
821       def->values = 0;
822       def->tail_ptr = &def->values;
823       def->num_values = 0;
824       *slot = def;
825     }
826
827   c = read_skip_spaces ();
828   if (c != '[')
829     fatal_expected_char ('[', c);
830
831   while ((c = read_skip_spaces ()) != ']')
832     {
833       if (c == EOF)
834         {
835           error_with_line (lineno, "unterminated construct");
836           exit (1);
837         }
838       unread_char (c);
839       read_name (&name);
840
841       ev = XNEW (struct enum_value);
842       ev->next = 0;
843       if (md_p)
844         {
845           value_name = concat (def->name, "_", name.string, NULL);
846           upcase_string (value_name);
847           ev->name = xstrdup (name.string);
848         }
849       else
850         {
851           value_name = xstrdup (name.string);
852           ev->name = value_name;
853         }
854       ev->def = add_constant (md_constants, value_name,
855                               decimal_string (def->num_values), def);
856
857       *def->tail_ptr = ev;
858       def->tail_ptr = &ev->next;
859       def->num_values++;
860     }
861 }
862
863 /* Try to find the definition of the given enum.  Return null on failure.  */
864
865 struct enum_type *
866 lookup_enum_type (const char *name)
867 {
868   return (struct enum_type *) htab_find (enum_types, &name);
869 }
870
871 /* For every enum definition, call CALLBACK with two arguments:
872    a pointer to the constant definition and INFO.  Stop when CALLBACK
873    returns zero.  */
874
875 void
876 traverse_enum_types (htab_trav callback, void *info)
877 {
878   htab_traverse (enum_types, callback, info);
879 }
880
881 /* Process an "include" directive, starting with the optional space
882    after the "include".  Read in the file and use HANDLE_DIRECTIVE
883    to process each unknown directive.  LINENO is the line number on
884    which the "include" occurred.  */
885
886 static void
887 handle_include (int lineno, directive_handler_t handle_directive)
888 {
889   const char *filename;
890   const char *old_filename;
891   int old_lineno;
892   char *pathname;
893   FILE *input_file, *old_file;
894
895   filename = read_string (false);
896   input_file = NULL;
897
898   /* If the specified file name is absolute, skip the include stack.  */
899   if (!IS_ABSOLUTE_PATH (filename))
900     {
901       struct file_name_list *stackp;
902
903       /* Search the directory path, trying to open the file.  */
904       for (stackp = first_dir_md_include; stackp; stackp = stackp->next)
905         {
906           static const char sep[2] = { DIR_SEPARATOR, '\0' };
907
908           pathname = concat (stackp->fname, sep, filename, NULL);
909           input_file = fopen (pathname, "r");
910           if (input_file != NULL)
911             break;
912           free (pathname);
913         }
914     }
915
916   /* If we haven't managed to open the file yet, try combining the
917      filename with BASE_DIR.  */
918   if (input_file == NULL)
919     {
920       if (base_dir)
921         pathname = concat (base_dir, filename, NULL);
922       else
923         pathname = xstrdup (filename);
924       input_file = fopen (pathname, "r");
925     }
926
927   if (input_file == NULL)
928     {
929       free (pathname);
930       error_with_line (lineno, "include file `%s' not found", filename);
931       return;
932     }
933
934   /* Save the old cursor.  Note that the LINENO argument to this
935      function is the beginning of the include statement, while
936      read_md_lineno has already been advanced.  */
937   old_file = read_md_file;
938   old_filename = read_md_filename;
939   old_lineno = read_md_lineno;
940
941   if (include_callback)
942     include_callback (pathname);
943
944   read_md_file = input_file;
945   read_md_filename = pathname;
946   handle_file (handle_directive);
947
948   /* Restore the old cursor.  */
949   read_md_file = old_file;
950   read_md_filename = old_filename;
951   read_md_lineno = old_lineno;
952
953   /* Do not free the pathname.  It is attached to the various rtx
954      queue elements.  */
955 }
956
957 /* Process the current file, assuming that read_md_file and
958    read_md_filename are valid.  Use HANDLE_DIRECTIVE to handle
959    unknown directives.  */
960
961 static void
962 handle_file (directive_handler_t handle_directive)
963 {
964   struct md_name directive;
965   int c, lineno;
966
967   read_md_lineno = 1;
968   while ((c = read_skip_spaces ()) != EOF)
969     {
970       lineno = read_md_lineno;
971       if (c != '(')
972         fatal_expected_char ('(', c);
973
974       read_name (&directive);
975       if (strcmp (directive.string, "define_constants") == 0)
976         handle_constants ();
977       else if (strcmp (directive.string, "define_enum") == 0)
978         handle_enum (lineno, true);
979       else if (strcmp (directive.string, "define_c_enum") == 0)
980         handle_enum (lineno, false);
981       else if (strcmp (directive.string, "include") == 0)
982         handle_include (lineno, handle_directive);
983       else if (handle_directive)
984         handle_directive (lineno, directive.string);
985       else
986         read_skip_construct (1, lineno);
987
988       c = read_skip_spaces ();
989       if (c != ')')
990         fatal_expected_char (')', c);
991     }
992   fclose (read_md_file);
993 }
994
995 /* Like handle_file, but for top-level files.  Set up in_fname and
996    base_dir accordingly.  */
997
998 static void
999 handle_toplevel_file (directive_handler_t handle_directive)
1000 {
1001   const char *base;
1002
1003   in_fname = read_md_filename;
1004   base = lbasename (in_fname);
1005   if (base == in_fname)
1006     base_dir = NULL;
1007   else
1008     base_dir = xstrndup (in_fname, base - in_fname);
1009
1010   handle_file (handle_directive);
1011 }
1012
1013 /* Parse a -I option with argument ARG.  */
1014
1015 static void
1016 parse_include (const char *arg)
1017 {
1018   struct file_name_list *dirtmp;
1019
1020   dirtmp = XNEW (struct file_name_list);
1021   dirtmp->next = 0;
1022   dirtmp->fname = arg;
1023   *last_dir_md_include_ptr = dirtmp;
1024   last_dir_md_include_ptr = &dirtmp->next;
1025   if (strlen (dirtmp->fname) > max_include_len)
1026     max_include_len = strlen (dirtmp->fname);
1027 }
1028
1029 /* The main routine for reading .md files.  Try to process all the .md
1030    files specified on the command line and return true if no error occurred.
1031
1032    ARGC and ARGV are the arguments to main.
1033
1034    PARSE_OPT, if nonnull, is passed all unknown command-line arguments.
1035    It should return true if it recognizes the argument or false if a
1036    generic error should be reported.
1037
1038    If HANDLE_DIRECTIVE is nonnull, the parser calls it for each
1039    unknown directive, otherwise it just skips such directives.
1040    See the comment above the directive_handler_t definition for
1041    details about the callback's interface.  */
1042
1043 bool
1044 read_md_files (int argc, char **argv, bool (*parse_opt) (const char *),
1045                directive_handler_t handle_directive)
1046 {
1047   int i;
1048   bool no_more_options;
1049   bool already_read_stdin;
1050   int num_files;
1051
1052   /* Initialize global data.  */
1053   obstack_init (&string_obstack);
1054   ptr_locs = htab_create (161, leading_ptr_hash, leading_ptr_eq_p, 0);
1055   obstack_init (&ptr_loc_obstack);
1056   joined_conditions = htab_create (161, leading_ptr_hash, leading_ptr_eq_p, 0);
1057   obstack_init (&joined_conditions_obstack);
1058   md_constants = htab_create (31, leading_string_hash,
1059                               leading_string_eq_p, (htab_del) 0);
1060   enum_types = htab_create (31, leading_string_hash,
1061                             leading_string_eq_p, (htab_del) 0);
1062
1063   /* Unlock the stdio streams.  */
1064   unlock_std_streams ();
1065
1066   /* First we loop over all the options.  */
1067   for (i = 1; i < argc; i++)
1068     if (argv[i][0] == '-')
1069       {
1070         /* An argument consisting of exactly one dash is a request to
1071            read stdin.  This will be handled in the second loop.  */
1072         if (argv[i][1] == '\0')
1073           continue;
1074
1075         /* An argument consisting of just two dashes causes option
1076            parsing to cease.  */
1077         if (argv[i][1] == '-' && argv[i][2] == '\0')
1078           break;
1079
1080         if (argv[i][1] == 'I')
1081           {
1082             if (argv[i][2] != '\0')
1083               parse_include (argv[i] + 2);
1084             else if (++i < argc)
1085               parse_include (argv[i]);
1086             else
1087               fatal ("directory name missing after -I option");
1088             continue;
1089           }
1090
1091         /* The program may have provided a callback so it can
1092            accept its own options.  */
1093         if (parse_opt && parse_opt (argv[i]))
1094           continue;
1095
1096         fatal ("invalid option `%s'", argv[i]);
1097       }
1098
1099   /* Now loop over all input files.  */
1100   num_files = 0;
1101   no_more_options = false;
1102   already_read_stdin = false;
1103   for (i = 1; i < argc; i++)
1104     {
1105       if (argv[i][0] == '-')
1106         {
1107           if (argv[i][1] == '\0')
1108             {
1109               /* Read stdin.  */
1110               if (already_read_stdin)
1111                 fatal ("cannot read standard input twice");
1112
1113               read_md_file = stdin;
1114               read_md_filename = "<stdin>";
1115               handle_toplevel_file (handle_directive);
1116               already_read_stdin = true;
1117               continue;
1118             }
1119           else if (argv[i][1] == '-' && argv[i][2] == '\0')
1120             {
1121               /* No further arguments are to be treated as options.  */
1122               no_more_options = true;
1123               continue;
1124             }
1125           else if (!no_more_options)
1126             continue;
1127         }
1128
1129       /* If we get here we are looking at a non-option argument, i.e.
1130          a file to be processed.  */
1131       read_md_filename = argv[i];
1132       read_md_file = fopen (read_md_filename, "r");
1133       if (read_md_file == 0)
1134         {
1135           perror (read_md_filename);
1136           return false;
1137         }
1138       handle_toplevel_file (handle_directive);
1139       num_files++;
1140     }
1141
1142   /* If we get to this point without having seen any files to process,
1143      read the standard input now.  */
1144   if (num_files == 0 && !already_read_stdin)
1145     {
1146       read_md_file = stdin;
1147       read_md_filename = "<stdin>";
1148       handle_toplevel_file (handle_directive);
1149     }
1150
1151   return !have_error;
1152 }