OSDN Git Service

gcc/fortran/
[pf3gnuchains/gcc-fork.git] / gcc / fortran / module.c
1 /* Handle modules, which amounts to loading and saving symbols and
2    their attendant structures.
3    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
4    2009, 2010
5    Free Software Foundation, Inc.
6    Contributed by Andy Vaught
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
14
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18 for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* The syntax of gfortran modules resembles that of lisp lists, i.e. a
25    sequence of atoms, which can be left or right parenthesis, names,
26    integers or strings.  Parenthesis are always matched which allows
27    us to skip over sections at high speed without having to know
28    anything about the internal structure of the lists.  A "name" is
29    usually a fortran 95 identifier, but can also start with '@' in
30    order to reference a hidden symbol.
31
32    The first line of a module is an informational message about what
33    created the module, the file it came from and when it was created.
34    The second line is a warning for people not to edit the module.
35    The rest of the module looks like:
36
37    ( ( <Interface info for UPLUS> )
38      ( <Interface info for UMINUS> )
39      ...
40    )
41    ( ( <name of operator interface> <module of op interface> <i/f1> ... )
42      ...
43    )
44    ( ( <name of generic interface> <module of generic interface> <i/f1> ... )
45      ...
46    )
47    ( ( <common name> <symbol> <saved flag>)
48      ...
49    )
50
51    ( equivalence list )
52
53    ( <Symbol Number (in no particular order)>
54      <True name of symbol>
55      <Module name of symbol>
56      ( <symbol information> )
57      ...
58    )
59    ( <Symtree name>
60      <Ambiguous flag>
61      <Symbol number>
62      ...
63    )
64
65    In general, symbols refer to other symbols by their symbol number,
66    which are zero based.  Symbols are written to the module in no
67    particular order.  */
68
69 #include "config.h"
70 #include "system.h"
71 #include "gfortran.h"
72 #include "arith.h"
73 #include "match.h"
74 #include "parse.h" /* FIXME */
75 #include "md5.h"
76
77 #define MODULE_EXTENSION ".mod"
78
79 /* Don't put any single quote (') in MOD_VERSION, 
80    if yout want it to be recognized.  */
81 #define MOD_VERSION "4"
82
83
84 /* Structure that describes a position within a module file.  */
85
86 typedef struct
87 {
88   int column, line;
89   fpos_t pos;
90 }
91 module_locus;
92
93 /* Structure for list of symbols of intrinsic modules.  */
94 typedef struct
95 {
96   int id;
97   const char *name;
98   int value;
99   int standard;
100 }
101 intmod_sym;
102
103
104 typedef enum
105 {
106   P_UNKNOWN = 0, P_OTHER, P_NAMESPACE, P_COMPONENT, P_SYMBOL
107 }
108 pointer_t;
109
110 /* The fixup structure lists pointers to pointers that have to
111    be updated when a pointer value becomes known.  */
112
113 typedef struct fixup_t
114 {
115   void **pointer;
116   struct fixup_t *next;
117 }
118 fixup_t;
119
120
121 /* Structure for holding extra info needed for pointers being read.  */
122
123 enum gfc_rsym_state
124 {
125   UNUSED,
126   NEEDED,
127   USED
128 };
129
130 enum gfc_wsym_state
131 {
132   UNREFERENCED = 0,
133   NEEDS_WRITE,
134   WRITTEN
135 };
136
137 typedef struct pointer_info
138 {
139   BBT_HEADER (pointer_info);
140   int integer;
141   pointer_t type;
142
143   /* The first component of each member of the union is the pointer
144      being stored.  */
145
146   fixup_t *fixup;
147
148   union
149   {
150     void *pointer;      /* Member for doing pointer searches.  */
151
152     struct
153     {
154       gfc_symbol *sym;
155       char true_name[GFC_MAX_SYMBOL_LEN + 1], module[GFC_MAX_SYMBOL_LEN + 1];
156       enum gfc_rsym_state state;
157       int ns, referenced, renamed;
158       module_locus where;
159       fixup_t *stfixup;
160       gfc_symtree *symtree;
161       char binding_label[GFC_MAX_SYMBOL_LEN + 1];
162     }
163     rsym;
164
165     struct
166     {
167       gfc_symbol *sym;
168       enum gfc_wsym_state state;
169     }
170     wsym;
171   }
172   u;
173
174 }
175 pointer_info;
176
177 #define gfc_get_pointer_info() XCNEW (pointer_info)
178
179
180 /* Local variables */
181
182 /* The FILE for the module we're reading or writing.  */
183 static FILE *module_fp;
184
185 /* MD5 context structure.  */
186 static struct md5_ctx ctx;
187
188 /* The name of the module we're reading (USE'ing) or writing.  */
189 static char module_name[GFC_MAX_SYMBOL_LEN + 1];
190
191 /* The way the module we're reading was specified.  */
192 static bool specified_nonint, specified_int;
193
194 static int module_line, module_column, only_flag;
195 static enum
196 { IO_INPUT, IO_OUTPUT }
197 iomode;
198
199 static gfc_use_rename *gfc_rename_list;
200 static pointer_info *pi_root;
201 static int symbol_number;       /* Counter for assigning symbol numbers */
202
203 /* Tells mio_expr_ref to make symbols for unused equivalence members.  */
204 static bool in_load_equiv;
205
206 static locus use_locus;
207
208
209
210 /*****************************************************************/
211
212 /* Pointer/integer conversion.  Pointers between structures are stored
213    as integers in the module file.  The next couple of subroutines
214    handle this translation for reading and writing.  */
215
216 /* Recursively free the tree of pointer structures.  */
217
218 static void
219 free_pi_tree (pointer_info *p)
220 {
221   if (p == NULL)
222     return;
223
224   if (p->fixup != NULL)
225     gfc_internal_error ("free_pi_tree(): Unresolved fixup");
226
227   free_pi_tree (p->left);
228   free_pi_tree (p->right);
229
230   gfc_free (p);
231 }
232
233
234 /* Compare pointers when searching by pointer.  Used when writing a
235    module.  */
236
237 static int
238 compare_pointers (void *_sn1, void *_sn2)
239 {
240   pointer_info *sn1, *sn2;
241
242   sn1 = (pointer_info *) _sn1;
243   sn2 = (pointer_info *) _sn2;
244
245   if (sn1->u.pointer < sn2->u.pointer)
246     return -1;
247   if (sn1->u.pointer > sn2->u.pointer)
248     return 1;
249
250   return 0;
251 }
252
253
254 /* Compare integers when searching by integer.  Used when reading a
255    module.  */
256
257 static int
258 compare_integers (void *_sn1, void *_sn2)
259 {
260   pointer_info *sn1, *sn2;
261
262   sn1 = (pointer_info *) _sn1;
263   sn2 = (pointer_info *) _sn2;
264
265   if (sn1->integer < sn2->integer)
266     return -1;
267   if (sn1->integer > sn2->integer)
268     return 1;
269
270   return 0;
271 }
272
273
274 /* Initialize the pointer_info tree.  */
275
276 static void
277 init_pi_tree (void)
278 {
279   compare_fn compare;
280   pointer_info *p;
281
282   pi_root = NULL;
283   compare = (iomode == IO_INPUT) ? compare_integers : compare_pointers;
284
285   /* Pointer 0 is the NULL pointer.  */
286   p = gfc_get_pointer_info ();
287   p->u.pointer = NULL;
288   p->integer = 0;
289   p->type = P_OTHER;
290
291   gfc_insert_bbt (&pi_root, p, compare);
292
293   /* Pointer 1 is the current namespace.  */
294   p = gfc_get_pointer_info ();
295   p->u.pointer = gfc_current_ns;
296   p->integer = 1;
297   p->type = P_NAMESPACE;
298
299   gfc_insert_bbt (&pi_root, p, compare);
300
301   symbol_number = 2;
302 }
303
304
305 /* During module writing, call here with a pointer to something,
306    returning the pointer_info node.  */
307
308 static pointer_info *
309 find_pointer (void *gp)
310 {
311   pointer_info *p;
312
313   p = pi_root;
314   while (p != NULL)
315     {
316       if (p->u.pointer == gp)
317         break;
318       p = (gp < p->u.pointer) ? p->left : p->right;
319     }
320
321   return p;
322 }
323
324
325 /* Given a pointer while writing, returns the pointer_info tree node,
326    creating it if it doesn't exist.  */
327
328 static pointer_info *
329 get_pointer (void *gp)
330 {
331   pointer_info *p;
332
333   p = find_pointer (gp);
334   if (p != NULL)
335     return p;
336
337   /* Pointer doesn't have an integer.  Give it one.  */
338   p = gfc_get_pointer_info ();
339
340   p->u.pointer = gp;
341   p->integer = symbol_number++;
342
343   gfc_insert_bbt (&pi_root, p, compare_pointers);
344
345   return p;
346 }
347
348
349 /* Given an integer during reading, find it in the pointer_info tree,
350    creating the node if not found.  */
351
352 static pointer_info *
353 get_integer (int integer)
354 {
355   pointer_info *p, t;
356   int c;
357
358   t.integer = integer;
359
360   p = pi_root;
361   while (p != NULL)
362     {
363       c = compare_integers (&t, p);
364       if (c == 0)
365         break;
366
367       p = (c < 0) ? p->left : p->right;
368     }
369
370   if (p != NULL)
371     return p;
372
373   p = gfc_get_pointer_info ();
374   p->integer = integer;
375   p->u.pointer = NULL;
376
377   gfc_insert_bbt (&pi_root, p, compare_integers);
378
379   return p;
380 }
381
382
383 /* Recursive function to find a pointer within a tree by brute force.  */
384
385 static pointer_info *
386 fp2 (pointer_info *p, const void *target)
387 {
388   pointer_info *q;
389
390   if (p == NULL)
391     return NULL;
392
393   if (p->u.pointer == target)
394     return p;
395
396   q = fp2 (p->left, target);
397   if (q != NULL)
398     return q;
399
400   return fp2 (p->right, target);
401 }
402
403
404 /* During reading, find a pointer_info node from the pointer value.
405    This amounts to a brute-force search.  */
406
407 static pointer_info *
408 find_pointer2 (void *p)
409 {
410   return fp2 (pi_root, p);
411 }
412
413
414 /* Resolve any fixups using a known pointer.  */
415
416 static void
417 resolve_fixups (fixup_t *f, void *gp)
418 {
419   fixup_t *next;
420
421   for (; f; f = next)
422     {
423       next = f->next;
424       *(f->pointer) = gp;
425       gfc_free (f);
426     }
427 }
428
429
430 /* Call here during module reading when we know what pointer to
431    associate with an integer.  Any fixups that exist are resolved at
432    this time.  */
433
434 static void
435 associate_integer_pointer (pointer_info *p, void *gp)
436 {
437   if (p->u.pointer != NULL)
438     gfc_internal_error ("associate_integer_pointer(): Already associated");
439
440   p->u.pointer = gp;
441
442   resolve_fixups (p->fixup, gp);
443
444   p->fixup = NULL;
445 }
446
447
448 /* During module reading, given an integer and a pointer to a pointer,
449    either store the pointer from an already-known value or create a
450    fixup structure in order to store things later.  Returns zero if
451    the reference has been actually stored, or nonzero if the reference
452    must be fixed later (i.e., associate_integer_pointer must be called
453    sometime later.  Returns the pointer_info structure.  */
454
455 static pointer_info *
456 add_fixup (int integer, void *gp)
457 {
458   pointer_info *p;
459   fixup_t *f;
460   char **cp;
461
462   p = get_integer (integer);
463
464   if (p->integer == 0 || p->u.pointer != NULL)
465     {
466       cp = (char **) gp;
467       *cp = (char *) p->u.pointer;
468     }
469   else
470     {
471       f = XCNEW (fixup_t);
472
473       f->next = p->fixup;
474       p->fixup = f;
475
476       f->pointer = (void **) gp;
477     }
478
479   return p;
480 }
481
482
483 /*****************************************************************/
484
485 /* Parser related subroutines */
486
487 /* Free the rename list left behind by a USE statement.  */
488
489 static void
490 free_rename (void)
491 {
492   gfc_use_rename *next;
493
494   for (; gfc_rename_list; gfc_rename_list = next)
495     {
496       next = gfc_rename_list->next;
497       gfc_free (gfc_rename_list);
498     }
499 }
500
501
502 /* Match a USE statement.  */
503
504 match
505 gfc_match_use (void)
506 {
507   char name[GFC_MAX_SYMBOL_LEN + 1], module_nature[GFC_MAX_SYMBOL_LEN + 1];
508   gfc_use_rename *tail = NULL, *new_use;
509   interface_type type, type2;
510   gfc_intrinsic_op op;
511   match m;
512
513   specified_int = false;
514   specified_nonint = false;
515
516   if (gfc_match (" , ") == MATCH_YES)
517     {
518       if ((m = gfc_match (" %n ::", module_nature)) == MATCH_YES)
519         {
520           if (gfc_notify_std (GFC_STD_F2003, "Fortran 2003: module "
521                               "nature in USE statement at %C") == FAILURE)
522             return MATCH_ERROR;
523
524           if (strcmp (module_nature, "intrinsic") == 0)
525             specified_int = true;
526           else
527             {
528               if (strcmp (module_nature, "non_intrinsic") == 0)
529                 specified_nonint = true;
530               else
531                 {
532                   gfc_error ("Module nature in USE statement at %C shall "
533                              "be either INTRINSIC or NON_INTRINSIC");
534                   return MATCH_ERROR;
535                 }
536             }
537         }
538       else
539         {
540           /* Help output a better error message than "Unclassifiable
541              statement".  */
542           gfc_match (" %n", module_nature);
543           if (strcmp (module_nature, "intrinsic") == 0
544               || strcmp (module_nature, "non_intrinsic") == 0)
545             gfc_error ("\"::\" was expected after module nature at %C "
546                        "but was not found");
547           return m;
548         }
549     }
550   else
551     {
552       m = gfc_match (" ::");
553       if (m == MATCH_YES &&
554           gfc_notify_std (GFC_STD_F2003, "Fortran 2003: "
555                           "\"USE :: module\" at %C") == FAILURE)
556         return MATCH_ERROR;
557
558       if (m != MATCH_YES)
559         {
560           m = gfc_match ("% ");
561           if (m != MATCH_YES)
562             return m;
563         }
564     }
565
566   use_locus = gfc_current_locus;
567
568   m = gfc_match_name (module_name);
569   if (m != MATCH_YES)
570     return m;
571
572   free_rename ();
573   only_flag = 0;
574
575   if (gfc_match_eos () == MATCH_YES)
576     return MATCH_YES;
577   if (gfc_match_char (',') != MATCH_YES)
578     goto syntax;
579
580   if (gfc_match (" only :") == MATCH_YES)
581     only_flag = 1;
582
583   if (gfc_match_eos () == MATCH_YES)
584     return MATCH_YES;
585
586   for (;;)
587     {
588       /* Get a new rename struct and add it to the rename list.  */
589       new_use = gfc_get_use_rename ();
590       new_use->where = gfc_current_locus;
591       new_use->found = 0;
592
593       if (gfc_rename_list == NULL)
594         gfc_rename_list = new_use;
595       else
596         tail->next = new_use;
597       tail = new_use;
598
599       /* See what kind of interface we're dealing with.  Assume it is
600          not an operator.  */
601       new_use->op = INTRINSIC_NONE;
602       if (gfc_match_generic_spec (&type, name, &op) == MATCH_ERROR)
603         goto cleanup;
604
605       switch (type)
606         {
607         case INTERFACE_NAMELESS:
608           gfc_error ("Missing generic specification in USE statement at %C");
609           goto cleanup;
610
611         case INTERFACE_USER_OP:
612         case INTERFACE_GENERIC:
613           m = gfc_match (" =>");
614
615           if (type == INTERFACE_USER_OP && m == MATCH_YES
616               && (gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Renaming "
617                                   "operators in USE statements at %C")
618                  == FAILURE))
619             goto cleanup;
620
621           if (type == INTERFACE_USER_OP)
622             new_use->op = INTRINSIC_USER;
623
624           if (only_flag)
625             {
626               if (m != MATCH_YES)
627                 strcpy (new_use->use_name, name);
628               else
629                 {
630                   strcpy (new_use->local_name, name);
631                   m = gfc_match_generic_spec (&type2, new_use->use_name, &op);
632                   if (type != type2)
633                     goto syntax;
634                   if (m == MATCH_NO)
635                     goto syntax;
636                   if (m == MATCH_ERROR)
637                     goto cleanup;
638                 }
639             }
640           else
641             {
642               if (m != MATCH_YES)
643                 goto syntax;
644               strcpy (new_use->local_name, name);
645
646               m = gfc_match_generic_spec (&type2, new_use->use_name, &op);
647               if (type != type2)
648                 goto syntax;
649               if (m == MATCH_NO)
650                 goto syntax;
651               if (m == MATCH_ERROR)
652                 goto cleanup;
653             }
654
655           if (strcmp (new_use->use_name, module_name) == 0
656               || strcmp (new_use->local_name, module_name) == 0)
657             {
658               gfc_error ("The name '%s' at %C has already been used as "
659                          "an external module name.", module_name);
660               goto cleanup;
661             }
662           break;
663
664         case INTERFACE_INTRINSIC_OP:
665           new_use->op = op;
666           break;
667
668         default:
669           gcc_unreachable ();
670         }
671
672       if (gfc_match_eos () == MATCH_YES)
673         break;
674       if (gfc_match_char (',') != MATCH_YES)
675         goto syntax;
676     }
677
678   return MATCH_YES;
679
680 syntax:
681   gfc_syntax_error (ST_USE);
682
683 cleanup:
684   free_rename ();
685   return MATCH_ERROR;
686  }
687
688
689 /* Given a name and a number, inst, return the inst name
690    under which to load this symbol. Returns NULL if this
691    symbol shouldn't be loaded. If inst is zero, returns
692    the number of instances of this name. If interface is
693    true, a user-defined operator is sought, otherwise only
694    non-operators are sought.  */
695
696 static const char *
697 find_use_name_n (const char *name, int *inst, bool interface)
698 {
699   gfc_use_rename *u;
700   int i;
701
702   i = 0;
703   for (u = gfc_rename_list; u; u = u->next)
704     {
705       if (strcmp (u->use_name, name) != 0
706           || (u->op == INTRINSIC_USER && !interface)
707           || (u->op != INTRINSIC_USER &&  interface))
708         continue;
709       if (++i == *inst)
710         break;
711     }
712
713   if (!*inst)
714     {
715       *inst = i;
716       return NULL;
717     }
718
719   if (u == NULL)
720     return only_flag ? NULL : name;
721
722   u->found = 1;
723
724   return (u->local_name[0] != '\0') ? u->local_name : name;
725 }
726
727
728 /* Given a name, return the name under which to load this symbol.
729    Returns NULL if this symbol shouldn't be loaded.  */
730
731 static const char *
732 find_use_name (const char *name, bool interface)
733 {
734   int i = 1;
735   return find_use_name_n (name, &i, interface);
736 }
737
738
739 /* Given a real name, return the number of use names associated with it.  */
740
741 static int
742 number_use_names (const char *name, bool interface)
743 {
744   int i = 0;
745   find_use_name_n (name, &i, interface);
746   return i;
747 }
748
749
750 /* Try to find the operator in the current list.  */
751
752 static gfc_use_rename *
753 find_use_operator (gfc_intrinsic_op op)
754 {
755   gfc_use_rename *u;
756
757   for (u = gfc_rename_list; u; u = u->next)
758     if (u->op == op)
759       return u;
760
761   return NULL;
762 }
763
764
765 /*****************************************************************/
766
767 /* The next couple of subroutines maintain a tree used to avoid a
768    brute-force search for a combination of true name and module name.
769    While symtree names, the name that a particular symbol is known by
770    can changed with USE statements, we still have to keep track of the
771    true names to generate the correct reference, and also avoid
772    loading the same real symbol twice in a program unit.
773
774    When we start reading, the true name tree is built and maintained
775    as symbols are read.  The tree is searched as we load new symbols
776    to see if it already exists someplace in the namespace.  */
777
778 typedef struct true_name
779 {
780   BBT_HEADER (true_name);
781   gfc_symbol *sym;
782 }
783 true_name;
784
785 static true_name *true_name_root;
786
787
788 /* Compare two true_name structures.  */
789
790 static int
791 compare_true_names (void *_t1, void *_t2)
792 {
793   true_name *t1, *t2;
794   int c;
795
796   t1 = (true_name *) _t1;
797   t2 = (true_name *) _t2;
798
799   c = ((t1->sym->module > t2->sym->module)
800        - (t1->sym->module < t2->sym->module));
801   if (c != 0)
802     return c;
803
804   return strcmp (t1->sym->name, t2->sym->name);
805 }
806
807
808 /* Given a true name, search the true name tree to see if it exists
809    within the main namespace.  */
810
811 static gfc_symbol *
812 find_true_name (const char *name, const char *module)
813 {
814   true_name t, *p;
815   gfc_symbol sym;
816   int c;
817
818   sym.name = gfc_get_string (name);
819   if (module != NULL)
820     sym.module = gfc_get_string (module);
821   else
822     sym.module = NULL;
823   t.sym = &sym;
824
825   p = true_name_root;
826   while (p != NULL)
827     {
828       c = compare_true_names ((void *) (&t), (void *) p);
829       if (c == 0)
830         return p->sym;
831
832       p = (c < 0) ? p->left : p->right;
833     }
834
835   return NULL;
836 }
837
838
839 /* Given a gfc_symbol pointer that is not in the true name tree, add it.  */
840
841 static void
842 add_true_name (gfc_symbol *sym)
843 {
844   true_name *t;
845
846   t = XCNEW (true_name);
847   t->sym = sym;
848
849   gfc_insert_bbt (&true_name_root, t, compare_true_names);
850 }
851
852
853 /* Recursive function to build the initial true name tree by
854    recursively traversing the current namespace.  */
855
856 static void
857 build_tnt (gfc_symtree *st)
858 {
859   if (st == NULL)
860     return;
861
862   build_tnt (st->left);
863   build_tnt (st->right);
864
865   if (find_true_name (st->n.sym->name, st->n.sym->module) != NULL)
866     return;
867
868   add_true_name (st->n.sym);
869 }
870
871
872 /* Initialize the true name tree with the current namespace.  */
873
874 static void
875 init_true_name_tree (void)
876 {
877   true_name_root = NULL;
878   build_tnt (gfc_current_ns->sym_root);
879 }
880
881
882 /* Recursively free a true name tree node.  */
883
884 static void
885 free_true_name (true_name *t)
886 {
887   if (t == NULL)
888     return;
889   free_true_name (t->left);
890   free_true_name (t->right);
891
892   gfc_free (t);
893 }
894
895
896 /*****************************************************************/
897
898 /* Module reading and writing.  */
899
900 typedef enum
901 {
902   ATOM_NAME, ATOM_LPAREN, ATOM_RPAREN, ATOM_INTEGER, ATOM_STRING
903 }
904 atom_type;
905
906 static atom_type last_atom;
907
908
909 /* The name buffer must be at least as long as a symbol name.  Right
910    now it's not clear how we're going to store numeric constants--
911    probably as a hexadecimal string, since this will allow the exact
912    number to be preserved (this can't be done by a decimal
913    representation).  Worry about that later.  TODO!  */
914
915 #define MAX_ATOM_SIZE 100
916
917 static int atom_int;
918 static char *atom_string, atom_name[MAX_ATOM_SIZE];
919
920
921 /* Report problems with a module.  Error reporting is not very
922    elaborate, since this sorts of errors shouldn't really happen.
923    This subroutine never returns.  */
924
925 static void bad_module (const char *) ATTRIBUTE_NORETURN;
926
927 static void
928 bad_module (const char *msgid)
929 {
930   fclose (module_fp);
931
932   switch (iomode)
933     {
934     case IO_INPUT:
935       gfc_fatal_error ("Reading module %s at line %d column %d: %s",
936                        module_name, module_line, module_column, msgid);
937       break;
938     case IO_OUTPUT:
939       gfc_fatal_error ("Writing module %s at line %d column %d: %s",
940                        module_name, module_line, module_column, msgid);
941       break;
942     default:
943       gfc_fatal_error ("Module %s at line %d column %d: %s",
944                        module_name, module_line, module_column, msgid);
945       break;
946     }
947 }
948
949
950 /* Set the module's input pointer.  */
951
952 static void
953 set_module_locus (module_locus *m)
954 {
955   module_column = m->column;
956   module_line = m->line;
957   fsetpos (module_fp, &m->pos);
958 }
959
960
961 /* Get the module's input pointer so that we can restore it later.  */
962
963 static void
964 get_module_locus (module_locus *m)
965 {
966   m->column = module_column;
967   m->line = module_line;
968   fgetpos (module_fp, &m->pos);
969 }
970
971
972 /* Get the next character in the module, updating our reckoning of
973    where we are.  */
974
975 static int
976 module_char (void)
977 {
978   int c;
979
980   c = getc (module_fp);
981
982   if (c == EOF)
983     bad_module ("Unexpected EOF");
984
985   if (c == '\n')
986     {
987       module_line++;
988       module_column = 0;
989     }
990
991   module_column++;
992   return c;
993 }
994
995
996 /* Parse a string constant.  The delimiter is guaranteed to be a
997    single quote.  */
998
999 static void
1000 parse_string (void)
1001 {
1002   module_locus start;
1003   int len, c;
1004   char *p;
1005
1006   get_module_locus (&start);
1007
1008   len = 0;
1009
1010   /* See how long the string is.  */
1011   for ( ; ; )
1012     {
1013       c = module_char ();
1014       if (c == EOF)
1015         bad_module ("Unexpected end of module in string constant");
1016
1017       if (c != '\'')
1018         {
1019           len++;
1020           continue;
1021         }
1022
1023       c = module_char ();
1024       if (c == '\'')
1025         {
1026           len++;
1027           continue;
1028         }
1029
1030       break;
1031     }
1032
1033   set_module_locus (&start);
1034
1035   atom_string = p = XCNEWVEC (char, len + 1);
1036
1037   for (; len > 0; len--)
1038     {
1039       c = module_char ();
1040       if (c == '\'')
1041         module_char ();         /* Guaranteed to be another \'.  */
1042       *p++ = c;
1043     }
1044
1045   module_char ();               /* Terminating \'.  */
1046   *p = '\0';                    /* C-style string for debug purposes.  */
1047 }
1048
1049
1050 /* Parse a small integer.  */
1051
1052 static void
1053 parse_integer (int c)
1054 {
1055   module_locus m;
1056
1057   atom_int = c - '0';
1058
1059   for (;;)
1060     {
1061       get_module_locus (&m);
1062
1063       c = module_char ();
1064       if (!ISDIGIT (c))
1065         break;
1066
1067       atom_int = 10 * atom_int + c - '0';
1068       if (atom_int > 99999999)
1069         bad_module ("Integer overflow");
1070     }
1071
1072   set_module_locus (&m);
1073 }
1074
1075
1076 /* Parse a name.  */
1077
1078 static void
1079 parse_name (int c)
1080 {
1081   module_locus m;
1082   char *p;
1083   int len;
1084
1085   p = atom_name;
1086
1087   *p++ = c;
1088   len = 1;
1089
1090   get_module_locus (&m);
1091
1092   for (;;)
1093     {
1094       c = module_char ();
1095       if (!ISALNUM (c) && c != '_' && c != '-')
1096         break;
1097
1098       *p++ = c;
1099       if (++len > GFC_MAX_SYMBOL_LEN)
1100         bad_module ("Name too long");
1101     }
1102
1103   *p = '\0';
1104
1105   fseek (module_fp, -1, SEEK_CUR);
1106   module_column = m.column + len - 1;
1107
1108   if (c == '\n')
1109     module_line--;
1110 }
1111
1112
1113 /* Read the next atom in the module's input stream.  */
1114
1115 static atom_type
1116 parse_atom (void)
1117 {
1118   int c;
1119
1120   do
1121     {
1122       c = module_char ();
1123     }
1124   while (c == ' ' || c == '\r' || c == '\n');
1125
1126   switch (c)
1127     {
1128     case '(':
1129       return ATOM_LPAREN;
1130
1131     case ')':
1132       return ATOM_RPAREN;
1133
1134     case '\'':
1135       parse_string ();
1136       return ATOM_STRING;
1137
1138     case '0':
1139     case '1':
1140     case '2':
1141     case '3':
1142     case '4':
1143     case '5':
1144     case '6':
1145     case '7':
1146     case '8':
1147     case '9':
1148       parse_integer (c);
1149       return ATOM_INTEGER;
1150
1151     case 'a':
1152     case 'b':
1153     case 'c':
1154     case 'd':
1155     case 'e':
1156     case 'f':
1157     case 'g':
1158     case 'h':
1159     case 'i':
1160     case 'j':
1161     case 'k':
1162     case 'l':
1163     case 'm':
1164     case 'n':
1165     case 'o':
1166     case 'p':
1167     case 'q':
1168     case 'r':
1169     case 's':
1170     case 't':
1171     case 'u':
1172     case 'v':
1173     case 'w':
1174     case 'x':
1175     case 'y':
1176     case 'z':
1177     case 'A':
1178     case 'B':
1179     case 'C':
1180     case 'D':
1181     case 'E':
1182     case 'F':
1183     case 'G':
1184     case 'H':
1185     case 'I':
1186     case 'J':
1187     case 'K':
1188     case 'L':
1189     case 'M':
1190     case 'N':
1191     case 'O':
1192     case 'P':
1193     case 'Q':
1194     case 'R':
1195     case 'S':
1196     case 'T':
1197     case 'U':
1198     case 'V':
1199     case 'W':
1200     case 'X':
1201     case 'Y':
1202     case 'Z':
1203       parse_name (c);
1204       return ATOM_NAME;
1205
1206     default:
1207       bad_module ("Bad name");
1208     }
1209
1210   /* Not reached.  */
1211 }
1212
1213
1214 /* Peek at the next atom on the input.  */
1215
1216 static atom_type
1217 peek_atom (void)
1218 {
1219   module_locus m;
1220   atom_type a;
1221
1222   get_module_locus (&m);
1223
1224   a = parse_atom ();
1225   if (a == ATOM_STRING)
1226     gfc_free (atom_string);
1227
1228   set_module_locus (&m);
1229   return a;
1230 }
1231
1232
1233 /* Read the next atom from the input, requiring that it be a
1234    particular kind.  */
1235
1236 static void
1237 require_atom (atom_type type)
1238 {
1239   module_locus m;
1240   atom_type t;
1241   const char *p;
1242
1243   get_module_locus (&m);
1244
1245   t = parse_atom ();
1246   if (t != type)
1247     {
1248       switch (type)
1249         {
1250         case ATOM_NAME:
1251           p = _("Expected name");
1252           break;
1253         case ATOM_LPAREN:
1254           p = _("Expected left parenthesis");
1255           break;
1256         case ATOM_RPAREN:
1257           p = _("Expected right parenthesis");
1258           break;
1259         case ATOM_INTEGER:
1260           p = _("Expected integer");
1261           break;
1262         case ATOM_STRING:
1263           p = _("Expected string");
1264           break;
1265         default:
1266           gfc_internal_error ("require_atom(): bad atom type required");
1267         }
1268
1269       set_module_locus (&m);
1270       bad_module (p);
1271     }
1272 }
1273
1274
1275 /* Given a pointer to an mstring array, require that the current input
1276    be one of the strings in the array.  We return the enum value.  */
1277
1278 static int
1279 find_enum (const mstring *m)
1280 {
1281   int i;
1282
1283   i = gfc_string2code (m, atom_name);
1284   if (i >= 0)
1285     return i;
1286
1287   bad_module ("find_enum(): Enum not found");
1288
1289   /* Not reached.  */
1290 }
1291
1292
1293 /**************** Module output subroutines ***************************/
1294
1295 /* Output a character to a module file.  */
1296
1297 static void
1298 write_char (char out)
1299 {
1300   if (putc (out, module_fp) == EOF)
1301     gfc_fatal_error ("Error writing modules file: %s", strerror (errno));
1302
1303   /* Add this to our MD5.  */
1304   md5_process_bytes (&out, sizeof (out), &ctx);
1305   
1306   if (out != '\n')
1307     module_column++;
1308   else
1309     {
1310       module_column = 1;
1311       module_line++;
1312     }
1313 }
1314
1315
1316 /* Write an atom to a module.  The line wrapping isn't perfect, but it
1317    should work most of the time.  This isn't that big of a deal, since
1318    the file really isn't meant to be read by people anyway.  */
1319
1320 static void
1321 write_atom (atom_type atom, const void *v)
1322 {
1323   char buffer[20];
1324   int i, len;
1325   const char *p;
1326
1327   switch (atom)
1328     {
1329     case ATOM_STRING:
1330     case ATOM_NAME:
1331       p = (const char *) v;
1332       break;
1333
1334     case ATOM_LPAREN:
1335       p = "(";
1336       break;
1337
1338     case ATOM_RPAREN:
1339       p = ")";
1340       break;
1341
1342     case ATOM_INTEGER:
1343       i = *((const int *) v);
1344       if (i < 0)
1345         gfc_internal_error ("write_atom(): Writing negative integer");
1346
1347       sprintf (buffer, "%d", i);
1348       p = buffer;
1349       break;
1350
1351     default:
1352       gfc_internal_error ("write_atom(): Trying to write dab atom");
1353
1354     }
1355
1356   if(p == NULL || *p == '\0') 
1357      len = 0;
1358   else
1359   len = strlen (p);
1360
1361   if (atom != ATOM_RPAREN)
1362     {
1363       if (module_column + len > 72)
1364         write_char ('\n');
1365       else
1366         {
1367
1368           if (last_atom != ATOM_LPAREN && module_column != 1)
1369             write_char (' ');
1370         }
1371     }
1372
1373   if (atom == ATOM_STRING)
1374     write_char ('\'');
1375
1376   while (p != NULL && *p)
1377     {
1378       if (atom == ATOM_STRING && *p == '\'')
1379         write_char ('\'');
1380       write_char (*p++);
1381     }
1382
1383   if (atom == ATOM_STRING)
1384     write_char ('\'');
1385
1386   last_atom = atom;
1387 }
1388
1389
1390
1391 /***************** Mid-level I/O subroutines *****************/
1392
1393 /* These subroutines let their caller read or write atoms without
1394    caring about which of the two is actually happening.  This lets a
1395    subroutine concentrate on the actual format of the data being
1396    written.  */
1397
1398 static void mio_expr (gfc_expr **);
1399 pointer_info *mio_symbol_ref (gfc_symbol **);
1400 pointer_info *mio_interface_rest (gfc_interface **);
1401 static void mio_symtree_ref (gfc_symtree **);
1402
1403 /* Read or write an enumerated value.  On writing, we return the input
1404    value for the convenience of callers.  We avoid using an integer
1405    pointer because enums are sometimes inside bitfields.  */
1406
1407 static int
1408 mio_name (int t, const mstring *m)
1409 {
1410   if (iomode == IO_OUTPUT)
1411     write_atom (ATOM_NAME, gfc_code2string (m, t));
1412   else
1413     {
1414       require_atom (ATOM_NAME);
1415       t = find_enum (m);
1416     }
1417
1418   return t;
1419 }
1420
1421 /* Specialization of mio_name.  */
1422
1423 #define DECL_MIO_NAME(TYPE) \
1424  static inline TYPE \
1425  MIO_NAME(TYPE) (TYPE t, const mstring *m) \
1426  { \
1427    return (TYPE) mio_name ((int) t, m); \
1428  }
1429 #define MIO_NAME(TYPE) mio_name_##TYPE
1430
1431 static void
1432 mio_lparen (void)
1433 {
1434   if (iomode == IO_OUTPUT)
1435     write_atom (ATOM_LPAREN, NULL);
1436   else
1437     require_atom (ATOM_LPAREN);
1438 }
1439
1440
1441 static void
1442 mio_rparen (void)
1443 {
1444   if (iomode == IO_OUTPUT)
1445     write_atom (ATOM_RPAREN, NULL);
1446   else
1447     require_atom (ATOM_RPAREN);
1448 }
1449
1450
1451 static void
1452 mio_integer (int *ip)
1453 {
1454   if (iomode == IO_OUTPUT)
1455     write_atom (ATOM_INTEGER, ip);
1456   else
1457     {
1458       require_atom (ATOM_INTEGER);
1459       *ip = atom_int;
1460     }
1461 }
1462
1463
1464 /* Read or write a gfc_intrinsic_op value.  */
1465
1466 static void
1467 mio_intrinsic_op (gfc_intrinsic_op* op)
1468 {
1469   /* FIXME: Would be nicer to do this via the operators symbolic name.  */
1470   if (iomode == IO_OUTPUT)
1471     {
1472       int converted = (int) *op;
1473       write_atom (ATOM_INTEGER, &converted);
1474     }
1475   else
1476     {
1477       require_atom (ATOM_INTEGER);
1478       *op = (gfc_intrinsic_op) atom_int;
1479     }
1480 }
1481
1482
1483 /* Read or write a character pointer that points to a string on the heap.  */
1484
1485 static const char *
1486 mio_allocated_string (const char *s)
1487 {
1488   if (iomode == IO_OUTPUT)
1489     {
1490       write_atom (ATOM_STRING, s);
1491       return s;
1492     }
1493   else
1494     {
1495       require_atom (ATOM_STRING);
1496       return atom_string;
1497     }
1498 }
1499
1500
1501 /* Functions for quoting and unquoting strings.  */
1502
1503 static char *
1504 quote_string (const gfc_char_t *s, const size_t slength)
1505 {
1506   const gfc_char_t *p;
1507   char *res, *q;
1508   size_t len = 0, i;
1509
1510   /* Calculate the length we'll need: a backslash takes two ("\\"),
1511      non-printable characters take 10 ("\Uxxxxxxxx") and others take 1.  */
1512   for (p = s, i = 0; i < slength; p++, i++)
1513     {
1514       if (*p == '\\')
1515         len += 2;
1516       else if (!gfc_wide_is_printable (*p))
1517         len += 10;
1518       else
1519         len++;
1520     }
1521
1522   q = res = XCNEWVEC (char, len + 1);
1523   for (p = s, i = 0; i < slength; p++, i++)
1524     {
1525       if (*p == '\\')
1526         *q++ = '\\', *q++ = '\\';
1527       else if (!gfc_wide_is_printable (*p))
1528         {
1529           sprintf (q, "\\U%08" HOST_WIDE_INT_PRINT "x",
1530                    (unsigned HOST_WIDE_INT) *p);
1531           q += 10;
1532         }
1533       else
1534         *q++ = (unsigned char) *p;
1535     }
1536
1537   res[len] = '\0';
1538   return res;
1539 }
1540
1541 static gfc_char_t *
1542 unquote_string (const char *s)
1543 {
1544   size_t len, i;
1545   const char *p;
1546   gfc_char_t *res;
1547
1548   for (p = s, len = 0; *p; p++, len++)
1549     {
1550       if (*p != '\\')
1551         continue;
1552         
1553       if (p[1] == '\\')
1554         p++;
1555       else if (p[1] == 'U')
1556         p += 9; /* That is a "\U????????". */
1557       else
1558         gfc_internal_error ("unquote_string(): got bad string");
1559     }
1560
1561   res = gfc_get_wide_string (len + 1);
1562   for (i = 0, p = s; i < len; i++, p++)
1563     {
1564       gcc_assert (*p);
1565
1566       if (*p != '\\')
1567         res[i] = (unsigned char) *p;
1568       else if (p[1] == '\\')
1569         {
1570           res[i] = (unsigned char) '\\';
1571           p++;
1572         }
1573       else
1574         {
1575           /* We read the 8-digits hexadecimal constant that follows.  */
1576           int j;
1577           unsigned n;
1578           gfc_char_t c = 0;
1579
1580           gcc_assert (p[1] == 'U');
1581           for (j = 0; j < 8; j++)
1582             {
1583               c = c << 4;
1584               gcc_assert (sscanf (&p[j+2], "%01x", &n) == 1);
1585               c += n;
1586             }
1587
1588           res[i] = c;
1589           p += 9;
1590         }
1591     }
1592
1593   res[len] = '\0';
1594   return res;
1595 }
1596
1597
1598 /* Read or write a character pointer that points to a wide string on the
1599    heap, performing quoting/unquoting of nonprintable characters using the
1600    form \U???????? (where each ? is a hexadecimal digit).
1601    Length is the length of the string, only known and used in output mode.  */
1602
1603 static const gfc_char_t *
1604 mio_allocated_wide_string (const gfc_char_t *s, const size_t length)
1605 {
1606   if (iomode == IO_OUTPUT)
1607     {
1608       char *quoted = quote_string (s, length);
1609       write_atom (ATOM_STRING, quoted);
1610       gfc_free (quoted);
1611       return s;
1612     }
1613   else
1614     {
1615       gfc_char_t *unquoted;
1616
1617       require_atom (ATOM_STRING);
1618       unquoted = unquote_string (atom_string);
1619       gfc_free (atom_string);
1620       return unquoted;
1621     }
1622 }
1623
1624
1625 /* Read or write a string that is in static memory.  */
1626
1627 static void
1628 mio_pool_string (const char **stringp)
1629 {
1630   /* TODO: one could write the string only once, and refer to it via a
1631      fixup pointer.  */
1632
1633   /* As a special case we have to deal with a NULL string.  This
1634      happens for the 'module' member of 'gfc_symbol's that are not in a
1635      module.  We read / write these as the empty string.  */
1636   if (iomode == IO_OUTPUT)
1637     {
1638       const char *p = *stringp == NULL ? "" : *stringp;
1639       write_atom (ATOM_STRING, p);
1640     }
1641   else
1642     {
1643       require_atom (ATOM_STRING);
1644       *stringp = atom_string[0] == '\0' ? NULL : gfc_get_string (atom_string);
1645       gfc_free (atom_string);
1646     }
1647 }
1648
1649
1650 /* Read or write a string that is inside of some already-allocated
1651    structure.  */
1652
1653 static void
1654 mio_internal_string (char *string)
1655 {
1656   if (iomode == IO_OUTPUT)
1657     write_atom (ATOM_STRING, string);
1658   else
1659     {
1660       require_atom (ATOM_STRING);
1661       strcpy (string, atom_string);
1662       gfc_free (atom_string);
1663     }
1664 }
1665
1666
1667 typedef enum
1668 { AB_ALLOCATABLE, AB_DIMENSION, AB_EXTERNAL, AB_INTRINSIC, AB_OPTIONAL,
1669   AB_POINTER, AB_TARGET, AB_DUMMY, AB_RESULT, AB_DATA,
1670   AB_IN_NAMELIST, AB_IN_COMMON, AB_FUNCTION, AB_SUBROUTINE, AB_SEQUENCE,
1671   AB_ELEMENTAL, AB_PURE, AB_RECURSIVE, AB_GENERIC, AB_ALWAYS_EXPLICIT,
1672   AB_CRAY_POINTER, AB_CRAY_POINTEE, AB_THREADPRIVATE, AB_ALLOC_COMP,
1673   AB_POINTER_COMP, AB_PRIVATE_COMP, AB_VALUE, AB_VOLATILE, AB_PROTECTED,
1674   AB_IS_BIND_C, AB_IS_C_INTEROP, AB_IS_ISO_C, AB_ABSTRACT, AB_ZERO_COMP,
1675   AB_IS_CLASS, AB_PROCEDURE, AB_PROC_POINTER, AB_ASYNCHRONOUS
1676 }
1677 ab_attribute;
1678
1679 static const mstring attr_bits[] =
1680 {
1681     minit ("ALLOCATABLE", AB_ALLOCATABLE),
1682     minit ("ASYNCHRONOUS", AB_ASYNCHRONOUS),
1683     minit ("DIMENSION", AB_DIMENSION),
1684     minit ("EXTERNAL", AB_EXTERNAL),
1685     minit ("INTRINSIC", AB_INTRINSIC),
1686     minit ("OPTIONAL", AB_OPTIONAL),
1687     minit ("POINTER", AB_POINTER),
1688     minit ("VOLATILE", AB_VOLATILE),
1689     minit ("TARGET", AB_TARGET),
1690     minit ("THREADPRIVATE", AB_THREADPRIVATE),
1691     minit ("DUMMY", AB_DUMMY),
1692     minit ("RESULT", AB_RESULT),
1693     minit ("DATA", AB_DATA),
1694     minit ("IN_NAMELIST", AB_IN_NAMELIST),
1695     minit ("IN_COMMON", AB_IN_COMMON),
1696     minit ("FUNCTION", AB_FUNCTION),
1697     minit ("SUBROUTINE", AB_SUBROUTINE),
1698     minit ("SEQUENCE", AB_SEQUENCE),
1699     minit ("ELEMENTAL", AB_ELEMENTAL),
1700     minit ("PURE", AB_PURE),
1701     minit ("RECURSIVE", AB_RECURSIVE),
1702     minit ("GENERIC", AB_GENERIC),
1703     minit ("ALWAYS_EXPLICIT", AB_ALWAYS_EXPLICIT),
1704     minit ("CRAY_POINTER", AB_CRAY_POINTER),
1705     minit ("CRAY_POINTEE", AB_CRAY_POINTEE),
1706     minit ("IS_BIND_C", AB_IS_BIND_C),
1707     minit ("IS_C_INTEROP", AB_IS_C_INTEROP),
1708     minit ("IS_ISO_C", AB_IS_ISO_C),
1709     minit ("VALUE", AB_VALUE),
1710     minit ("ALLOC_COMP", AB_ALLOC_COMP),
1711     minit ("POINTER_COMP", AB_POINTER_COMP),
1712     minit ("PRIVATE_COMP", AB_PRIVATE_COMP),
1713     minit ("ZERO_COMP", AB_ZERO_COMP),
1714     minit ("PROTECTED", AB_PROTECTED),
1715     minit ("ABSTRACT", AB_ABSTRACT),
1716     minit ("IS_CLASS", AB_IS_CLASS),
1717     minit ("PROCEDURE", AB_PROCEDURE),
1718     minit ("PROC_POINTER", AB_PROC_POINTER),
1719     minit (NULL, -1)
1720 };
1721
1722 /* For binding attributes.  */
1723 static const mstring binding_passing[] =
1724 {
1725     minit ("PASS", 0),
1726     minit ("NOPASS", 1),
1727     minit (NULL, -1)
1728 };
1729 static const mstring binding_overriding[] =
1730 {
1731     minit ("OVERRIDABLE", 0),
1732     minit ("NON_OVERRIDABLE", 1),
1733     minit ("DEFERRED", 2),
1734     minit (NULL, -1)
1735 };
1736 static const mstring binding_generic[] =
1737 {
1738     minit ("SPECIFIC", 0),
1739     minit ("GENERIC", 1),
1740     minit (NULL, -1)
1741 };
1742 static const mstring binding_ppc[] =
1743 {
1744     minit ("NO_PPC", 0),
1745     minit ("PPC", 1),
1746     minit (NULL, -1)
1747 };
1748
1749 /* Specialization of mio_name.  */
1750 DECL_MIO_NAME (ab_attribute)
1751 DECL_MIO_NAME (ar_type)
1752 DECL_MIO_NAME (array_type)
1753 DECL_MIO_NAME (bt)
1754 DECL_MIO_NAME (expr_t)
1755 DECL_MIO_NAME (gfc_access)
1756 DECL_MIO_NAME (gfc_intrinsic_op)
1757 DECL_MIO_NAME (ifsrc)
1758 DECL_MIO_NAME (save_state)
1759 DECL_MIO_NAME (procedure_type)
1760 DECL_MIO_NAME (ref_type)
1761 DECL_MIO_NAME (sym_flavor)
1762 DECL_MIO_NAME (sym_intent)
1763 #undef DECL_MIO_NAME
1764
1765 /* Symbol attributes are stored in list with the first three elements
1766    being the enumerated fields, while the remaining elements (if any)
1767    indicate the individual attribute bits.  The access field is not
1768    saved-- it controls what symbols are exported when a module is
1769    written.  */
1770
1771 static void
1772 mio_symbol_attribute (symbol_attribute *attr)
1773 {
1774   atom_type t;
1775   unsigned ext_attr,extension_level;
1776
1777   mio_lparen ();
1778
1779   attr->flavor = MIO_NAME (sym_flavor) (attr->flavor, flavors);
1780   attr->intent = MIO_NAME (sym_intent) (attr->intent, intents);
1781   attr->proc = MIO_NAME (procedure_type) (attr->proc, procedures);
1782   attr->if_source = MIO_NAME (ifsrc) (attr->if_source, ifsrc_types);
1783   attr->save = MIO_NAME (save_state) (attr->save, save_status);
1784   
1785   ext_attr = attr->ext_attr;
1786   mio_integer ((int *) &ext_attr);
1787   attr->ext_attr = ext_attr;
1788
1789   extension_level = attr->extension;
1790   mio_integer ((int *) &extension_level);
1791   attr->extension = extension_level;
1792
1793   if (iomode == IO_OUTPUT)
1794     {
1795       if (attr->allocatable)
1796         MIO_NAME (ab_attribute) (AB_ALLOCATABLE, attr_bits);
1797       if (attr->asynchronous)
1798         MIO_NAME (ab_attribute) (AB_ASYNCHRONOUS, attr_bits);
1799       if (attr->dimension)
1800         MIO_NAME (ab_attribute) (AB_DIMENSION, attr_bits);
1801       if (attr->external)
1802         MIO_NAME (ab_attribute) (AB_EXTERNAL, attr_bits);
1803       if (attr->intrinsic)
1804         MIO_NAME (ab_attribute) (AB_INTRINSIC, attr_bits);
1805       if (attr->optional)
1806         MIO_NAME (ab_attribute) (AB_OPTIONAL, attr_bits);
1807       if (attr->pointer)
1808         MIO_NAME (ab_attribute) (AB_POINTER, attr_bits);
1809       if (attr->is_protected)
1810         MIO_NAME (ab_attribute) (AB_PROTECTED, attr_bits);
1811       if (attr->value)
1812         MIO_NAME (ab_attribute) (AB_VALUE, attr_bits);
1813       if (attr->volatile_)
1814         MIO_NAME (ab_attribute) (AB_VOLATILE, attr_bits);
1815       if (attr->target)
1816         MIO_NAME (ab_attribute) (AB_TARGET, attr_bits);
1817       if (attr->threadprivate)
1818         MIO_NAME (ab_attribute) (AB_THREADPRIVATE, attr_bits);
1819       if (attr->dummy)
1820         MIO_NAME (ab_attribute) (AB_DUMMY, attr_bits);
1821       if (attr->result)
1822         MIO_NAME (ab_attribute) (AB_RESULT, attr_bits);
1823       /* We deliberately don't preserve the "entry" flag.  */
1824
1825       if (attr->data)
1826         MIO_NAME (ab_attribute) (AB_DATA, attr_bits);
1827       if (attr->in_namelist)
1828         MIO_NAME (ab_attribute) (AB_IN_NAMELIST, attr_bits);
1829       if (attr->in_common)
1830         MIO_NAME (ab_attribute) (AB_IN_COMMON, attr_bits);
1831
1832       if (attr->function)
1833         MIO_NAME (ab_attribute) (AB_FUNCTION, attr_bits);
1834       if (attr->subroutine)
1835         MIO_NAME (ab_attribute) (AB_SUBROUTINE, attr_bits);
1836       if (attr->generic)
1837         MIO_NAME (ab_attribute) (AB_GENERIC, attr_bits);
1838       if (attr->abstract)
1839         MIO_NAME (ab_attribute) (AB_ABSTRACT, attr_bits);
1840
1841       if (attr->sequence)
1842         MIO_NAME (ab_attribute) (AB_SEQUENCE, attr_bits);
1843       if (attr->elemental)
1844         MIO_NAME (ab_attribute) (AB_ELEMENTAL, attr_bits);
1845       if (attr->pure)
1846         MIO_NAME (ab_attribute) (AB_PURE, attr_bits);
1847       if (attr->recursive)
1848         MIO_NAME (ab_attribute) (AB_RECURSIVE, attr_bits);
1849       if (attr->always_explicit)
1850         MIO_NAME (ab_attribute) (AB_ALWAYS_EXPLICIT, attr_bits);
1851       if (attr->cray_pointer)
1852         MIO_NAME (ab_attribute) (AB_CRAY_POINTER, attr_bits);
1853       if (attr->cray_pointee)
1854         MIO_NAME (ab_attribute) (AB_CRAY_POINTEE, attr_bits);
1855       if (attr->is_bind_c)
1856         MIO_NAME(ab_attribute) (AB_IS_BIND_C, attr_bits);
1857       if (attr->is_c_interop)
1858         MIO_NAME(ab_attribute) (AB_IS_C_INTEROP, attr_bits);
1859       if (attr->is_iso_c)
1860         MIO_NAME(ab_attribute) (AB_IS_ISO_C, attr_bits);
1861       if (attr->alloc_comp)
1862         MIO_NAME (ab_attribute) (AB_ALLOC_COMP, attr_bits);
1863       if (attr->pointer_comp)
1864         MIO_NAME (ab_attribute) (AB_POINTER_COMP, attr_bits);
1865       if (attr->private_comp)
1866         MIO_NAME (ab_attribute) (AB_PRIVATE_COMP, attr_bits);
1867       if (attr->zero_comp)
1868         MIO_NAME (ab_attribute) (AB_ZERO_COMP, attr_bits);
1869       if (attr->is_class)
1870         MIO_NAME (ab_attribute) (AB_IS_CLASS, attr_bits);
1871       if (attr->procedure)
1872         MIO_NAME (ab_attribute) (AB_PROCEDURE, attr_bits);
1873       if (attr->proc_pointer)
1874         MIO_NAME (ab_attribute) (AB_PROC_POINTER, attr_bits);
1875
1876       mio_rparen ();
1877
1878     }
1879   else
1880     {
1881       for (;;)
1882         {
1883           t = parse_atom ();
1884           if (t == ATOM_RPAREN)
1885             break;
1886           if (t != ATOM_NAME)
1887             bad_module ("Expected attribute bit name");
1888
1889           switch ((ab_attribute) find_enum (attr_bits))
1890             {
1891             case AB_ALLOCATABLE:
1892               attr->allocatable = 1;
1893               break;
1894             case AB_ASYNCHRONOUS:
1895               attr->asynchronous = 1;
1896               break;
1897             case AB_DIMENSION:
1898               attr->dimension = 1;
1899               break;
1900             case AB_EXTERNAL:
1901               attr->external = 1;
1902               break;
1903             case AB_INTRINSIC:
1904               attr->intrinsic = 1;
1905               break;
1906             case AB_OPTIONAL:
1907               attr->optional = 1;
1908               break;
1909             case AB_POINTER:
1910               attr->pointer = 1;
1911               break;
1912             case AB_PROTECTED:
1913               attr->is_protected = 1;
1914               break;
1915             case AB_VALUE:
1916               attr->value = 1;
1917               break;
1918             case AB_VOLATILE:
1919               attr->volatile_ = 1;
1920               break;
1921             case AB_TARGET:
1922               attr->target = 1;
1923               break;
1924             case AB_THREADPRIVATE:
1925               attr->threadprivate = 1;
1926               break;
1927             case AB_DUMMY:
1928               attr->dummy = 1;
1929               break;
1930             case AB_RESULT:
1931               attr->result = 1;
1932               break;
1933             case AB_DATA:
1934               attr->data = 1;
1935               break;
1936             case AB_IN_NAMELIST:
1937               attr->in_namelist = 1;
1938               break;
1939             case AB_IN_COMMON:
1940               attr->in_common = 1;
1941               break;
1942             case AB_FUNCTION:
1943               attr->function = 1;
1944               break;
1945             case AB_SUBROUTINE:
1946               attr->subroutine = 1;
1947               break;
1948             case AB_GENERIC:
1949               attr->generic = 1;
1950               break;
1951             case AB_ABSTRACT:
1952               attr->abstract = 1;
1953               break;
1954             case AB_SEQUENCE:
1955               attr->sequence = 1;
1956               break;
1957             case AB_ELEMENTAL:
1958               attr->elemental = 1;
1959               break;
1960             case AB_PURE:
1961               attr->pure = 1;
1962               break;
1963             case AB_RECURSIVE:
1964               attr->recursive = 1;
1965               break;
1966             case AB_ALWAYS_EXPLICIT:
1967               attr->always_explicit = 1;
1968               break;
1969             case AB_CRAY_POINTER:
1970               attr->cray_pointer = 1;
1971               break;
1972             case AB_CRAY_POINTEE:
1973               attr->cray_pointee = 1;
1974               break;
1975             case AB_IS_BIND_C:
1976               attr->is_bind_c = 1;
1977               break;
1978             case AB_IS_C_INTEROP:
1979               attr->is_c_interop = 1;
1980               break;
1981             case AB_IS_ISO_C:
1982               attr->is_iso_c = 1;
1983               break;
1984             case AB_ALLOC_COMP:
1985               attr->alloc_comp = 1;
1986               break;
1987             case AB_POINTER_COMP:
1988               attr->pointer_comp = 1;
1989               break;
1990             case AB_PRIVATE_COMP:
1991               attr->private_comp = 1;
1992               break;
1993             case AB_ZERO_COMP:
1994               attr->zero_comp = 1;
1995               break;
1996             case AB_IS_CLASS:
1997               attr->is_class = 1;
1998               break;
1999             case AB_PROCEDURE:
2000               attr->procedure = 1;
2001               break;
2002             case AB_PROC_POINTER:
2003               attr->proc_pointer = 1;
2004               break;
2005             }
2006         }
2007     }
2008 }
2009
2010
2011 static const mstring bt_types[] = {
2012     minit ("INTEGER", BT_INTEGER),
2013     minit ("REAL", BT_REAL),
2014     minit ("COMPLEX", BT_COMPLEX),
2015     minit ("LOGICAL", BT_LOGICAL),
2016     minit ("CHARACTER", BT_CHARACTER),
2017     minit ("DERIVED", BT_DERIVED),
2018     minit ("CLASS", BT_CLASS),
2019     minit ("PROCEDURE", BT_PROCEDURE),
2020     minit ("UNKNOWN", BT_UNKNOWN),
2021     minit ("VOID", BT_VOID),
2022     minit (NULL, -1)
2023 };
2024
2025
2026 static void
2027 mio_charlen (gfc_charlen **clp)
2028 {
2029   gfc_charlen *cl;
2030
2031   mio_lparen ();
2032
2033   if (iomode == IO_OUTPUT)
2034     {
2035       cl = *clp;
2036       if (cl != NULL)
2037         mio_expr (&cl->length);
2038     }
2039   else
2040     {
2041       if (peek_atom () != ATOM_RPAREN)
2042         {
2043           cl = gfc_new_charlen (gfc_current_ns, NULL);
2044           mio_expr (&cl->length);
2045           *clp = cl;
2046         }
2047     }
2048
2049   mio_rparen ();
2050 }
2051
2052
2053 /* See if a name is a generated name.  */
2054
2055 static int
2056 check_unique_name (const char *name)
2057 {
2058   return *name == '@';
2059 }
2060
2061
2062 static void
2063 mio_typespec (gfc_typespec *ts)
2064 {
2065   mio_lparen ();
2066
2067   ts->type = MIO_NAME (bt) (ts->type, bt_types);
2068
2069   if (ts->type != BT_DERIVED && ts->type != BT_CLASS)
2070     mio_integer (&ts->kind);
2071   else
2072     mio_symbol_ref (&ts->u.derived);
2073
2074   /* Add info for C interop and is_iso_c.  */
2075   mio_integer (&ts->is_c_interop);
2076   mio_integer (&ts->is_iso_c);
2077   
2078   /* If the typespec is for an identifier either from iso_c_binding, or
2079      a constant that was initialized to an identifier from it, use the
2080      f90_type.  Otherwise, use the ts->type, since it shouldn't matter.  */
2081   if (ts->is_iso_c)
2082     ts->f90_type = MIO_NAME (bt) (ts->f90_type, bt_types);
2083   else
2084     ts->f90_type = MIO_NAME (bt) (ts->type, bt_types);
2085
2086   if (ts->type != BT_CHARACTER)
2087     {
2088       /* ts->u.cl is only valid for BT_CHARACTER.  */
2089       mio_lparen ();
2090       mio_rparen ();
2091     }
2092   else
2093     mio_charlen (&ts->u.cl);
2094
2095   mio_rparen ();
2096 }
2097
2098
2099 static const mstring array_spec_types[] = {
2100     minit ("EXPLICIT", AS_EXPLICIT),
2101     minit ("ASSUMED_SHAPE", AS_ASSUMED_SHAPE),
2102     minit ("DEFERRED", AS_DEFERRED),
2103     minit ("ASSUMED_SIZE", AS_ASSUMED_SIZE),
2104     minit (NULL, -1)
2105 };
2106
2107
2108 static void
2109 mio_array_spec (gfc_array_spec **asp)
2110 {
2111   gfc_array_spec *as;
2112   int i;
2113
2114   mio_lparen ();
2115
2116   if (iomode == IO_OUTPUT)
2117     {
2118       if (*asp == NULL)
2119         goto done;
2120       as = *asp;
2121     }
2122   else
2123     {
2124       if (peek_atom () == ATOM_RPAREN)
2125         {
2126           *asp = NULL;
2127           goto done;
2128         }
2129
2130       *asp = as = gfc_get_array_spec ();
2131     }
2132
2133   mio_integer (&as->rank);
2134   as->type = MIO_NAME (array_type) (as->type, array_spec_types);
2135
2136   for (i = 0; i < as->rank; i++)
2137     {
2138       mio_expr (&as->lower[i]);
2139       mio_expr (&as->upper[i]);
2140     }
2141
2142 done:
2143   mio_rparen ();
2144 }
2145
2146
2147 /* Given a pointer to an array reference structure (which lives in a
2148    gfc_ref structure), find the corresponding array specification
2149    structure.  Storing the pointer in the ref structure doesn't quite
2150    work when loading from a module. Generating code for an array
2151    reference also needs more information than just the array spec.  */
2152
2153 static const mstring array_ref_types[] = {
2154     minit ("FULL", AR_FULL),
2155     minit ("ELEMENT", AR_ELEMENT),
2156     minit ("SECTION", AR_SECTION),
2157     minit (NULL, -1)
2158 };
2159
2160
2161 static void
2162 mio_array_ref (gfc_array_ref *ar)
2163 {
2164   int i;
2165
2166   mio_lparen ();
2167   ar->type = MIO_NAME (ar_type) (ar->type, array_ref_types);
2168   mio_integer (&ar->dimen);
2169
2170   switch (ar->type)
2171     {
2172     case AR_FULL:
2173       break;
2174
2175     case AR_ELEMENT:
2176       for (i = 0; i < ar->dimen; i++)
2177         mio_expr (&ar->start[i]);
2178
2179       break;
2180
2181     case AR_SECTION:
2182       for (i = 0; i < ar->dimen; i++)
2183         {
2184           mio_expr (&ar->start[i]);
2185           mio_expr (&ar->end[i]);
2186           mio_expr (&ar->stride[i]);
2187         }
2188
2189       break;
2190
2191     case AR_UNKNOWN:
2192       gfc_internal_error ("mio_array_ref(): Unknown array ref");
2193     }
2194
2195   /* Unfortunately, ar->dimen_type is an anonymous enumerated type so
2196      we can't call mio_integer directly.  Instead loop over each element
2197      and cast it to/from an integer.  */
2198   if (iomode == IO_OUTPUT)
2199     {
2200       for (i = 0; i < ar->dimen; i++)
2201         {
2202           int tmp = (int)ar->dimen_type[i];
2203           write_atom (ATOM_INTEGER, &tmp);
2204         }
2205     }
2206   else
2207     {
2208       for (i = 0; i < ar->dimen; i++)
2209         {
2210           require_atom (ATOM_INTEGER);
2211           ar->dimen_type[i] = (enum gfc_array_ref_dimen_type) atom_int;
2212         }
2213     }
2214
2215   if (iomode == IO_INPUT)
2216     {
2217       ar->where = gfc_current_locus;
2218
2219       for (i = 0; i < ar->dimen; i++)
2220         ar->c_where[i] = gfc_current_locus;
2221     }
2222
2223   mio_rparen ();
2224 }
2225
2226
2227 /* Saves or restores a pointer.  The pointer is converted back and
2228    forth from an integer.  We return the pointer_info pointer so that
2229    the caller can take additional action based on the pointer type.  */
2230
2231 static pointer_info *
2232 mio_pointer_ref (void *gp)
2233 {
2234   pointer_info *p;
2235
2236   if (iomode == IO_OUTPUT)
2237     {
2238       p = get_pointer (*((char **) gp));
2239       write_atom (ATOM_INTEGER, &p->integer);
2240     }
2241   else
2242     {
2243       require_atom (ATOM_INTEGER);
2244       p = add_fixup (atom_int, gp);
2245     }
2246
2247   return p;
2248 }
2249
2250
2251 /* Save and load references to components that occur within
2252    expressions.  We have to describe these references by a number and
2253    by name.  The number is necessary for forward references during
2254    reading, and the name is necessary if the symbol already exists in
2255    the namespace and is not loaded again.  */
2256
2257 static void
2258 mio_component_ref (gfc_component **cp, gfc_symbol *sym)
2259 {
2260   char name[GFC_MAX_SYMBOL_LEN + 1];
2261   gfc_component *q;
2262   pointer_info *p;
2263
2264   p = mio_pointer_ref (cp);
2265   if (p->type == P_UNKNOWN)
2266     p->type = P_COMPONENT;
2267
2268   if (iomode == IO_OUTPUT)
2269     mio_pool_string (&(*cp)->name);
2270   else
2271     {
2272       mio_internal_string (name);
2273
2274       /* It can happen that a component reference can be read before the
2275          associated derived type symbol has been loaded. Return now and
2276          wait for a later iteration of load_needed.  */
2277       if (sym == NULL)
2278         return;
2279
2280       if (sym->components != NULL && p->u.pointer == NULL)
2281         {
2282           /* Symbol already loaded, so search by name.  */
2283           for (q = sym->components; q; q = q->next)
2284             if (strcmp (q->name, name) == 0)
2285               break;
2286
2287           if (q == NULL)
2288             gfc_internal_error ("mio_component_ref(): Component not found");
2289
2290           associate_integer_pointer (p, q);
2291         }
2292
2293       /* Make sure this symbol will eventually be loaded.  */
2294       p = find_pointer2 (sym);
2295       if (p->u.rsym.state == UNUSED)
2296         p->u.rsym.state = NEEDED;
2297     }
2298 }
2299
2300
2301 static void mio_namespace_ref (gfc_namespace **nsp);
2302 static void mio_formal_arglist (gfc_formal_arglist **formal);
2303 static void mio_typebound_proc (gfc_typebound_proc** proc);
2304
2305 static void
2306 mio_component (gfc_component *c)
2307 {
2308   pointer_info *p;
2309   int n;
2310   gfc_formal_arglist *formal;
2311
2312   mio_lparen ();
2313
2314   if (iomode == IO_OUTPUT)
2315     {
2316       p = get_pointer (c);
2317       mio_integer (&p->integer);
2318     }
2319   else
2320     {
2321       mio_integer (&n);
2322       p = get_integer (n);
2323       associate_integer_pointer (p, c);
2324     }
2325
2326   if (p->type == P_UNKNOWN)
2327     p->type = P_COMPONENT;
2328
2329   mio_pool_string (&c->name);
2330   mio_typespec (&c->ts);
2331   mio_array_spec (&c->as);
2332
2333   mio_symbol_attribute (&c->attr);
2334   c->attr.access = MIO_NAME (gfc_access) (c->attr.access, access_types); 
2335
2336   mio_expr (&c->initializer);
2337
2338   if (c->attr.proc_pointer)
2339     {
2340       if (iomode == IO_OUTPUT)
2341         {
2342           formal = c->formal;
2343           while (formal && !formal->sym)
2344             formal = formal->next;
2345
2346           if (formal)
2347             mio_namespace_ref (&formal->sym->ns);
2348           else
2349             mio_namespace_ref (&c->formal_ns);
2350         }
2351       else
2352         {
2353           mio_namespace_ref (&c->formal_ns);
2354           /* TODO: if (c->formal_ns)
2355             {
2356               c->formal_ns->proc_name = c;
2357               c->refs++;
2358             }*/
2359         }
2360
2361       mio_formal_arglist (&c->formal);
2362
2363       mio_typebound_proc (&c->tb);
2364     }
2365
2366   mio_rparen ();
2367 }
2368
2369
2370 static void
2371 mio_component_list (gfc_component **cp)
2372 {
2373   gfc_component *c, *tail;
2374
2375   mio_lparen ();
2376
2377   if (iomode == IO_OUTPUT)
2378     {
2379       for (c = *cp; c; c = c->next)
2380         mio_component (c);
2381     }
2382   else
2383     {
2384       *cp = NULL;
2385       tail = NULL;
2386
2387       for (;;)
2388         {
2389           if (peek_atom () == ATOM_RPAREN)
2390             break;
2391
2392           c = gfc_get_component ();
2393           mio_component (c);
2394
2395           if (tail == NULL)
2396             *cp = c;
2397           else
2398             tail->next = c;
2399
2400           tail = c;
2401         }
2402     }
2403
2404   mio_rparen ();
2405 }
2406
2407
2408 static void
2409 mio_actual_arg (gfc_actual_arglist *a)
2410 {
2411   mio_lparen ();
2412   mio_pool_string (&a->name);
2413   mio_expr (&a->expr);
2414   mio_rparen ();
2415 }
2416
2417
2418 static void
2419 mio_actual_arglist (gfc_actual_arglist **ap)
2420 {
2421   gfc_actual_arglist *a, *tail;
2422
2423   mio_lparen ();
2424
2425   if (iomode == IO_OUTPUT)
2426     {
2427       for (a = *ap; a; a = a->next)
2428         mio_actual_arg (a);
2429
2430     }
2431   else
2432     {
2433       tail = NULL;
2434
2435       for (;;)
2436         {
2437           if (peek_atom () != ATOM_LPAREN)
2438             break;
2439
2440           a = gfc_get_actual_arglist ();
2441
2442           if (tail == NULL)
2443             *ap = a;
2444           else
2445             tail->next = a;
2446
2447           tail = a;
2448           mio_actual_arg (a);
2449         }
2450     }
2451
2452   mio_rparen ();
2453 }
2454
2455
2456 /* Read and write formal argument lists.  */
2457
2458 static void
2459 mio_formal_arglist (gfc_formal_arglist **formal)
2460 {
2461   gfc_formal_arglist *f, *tail;
2462
2463   mio_lparen ();
2464
2465   if (iomode == IO_OUTPUT)
2466     {
2467       for (f = *formal; f; f = f->next)
2468         mio_symbol_ref (&f->sym);
2469     }
2470   else
2471     {
2472       *formal = tail = NULL;
2473
2474       while (peek_atom () != ATOM_RPAREN)
2475         {
2476           f = gfc_get_formal_arglist ();
2477           mio_symbol_ref (&f->sym);
2478
2479           if (*formal == NULL)
2480             *formal = f;
2481           else
2482             tail->next = f;
2483
2484           tail = f;
2485         }
2486     }
2487
2488   mio_rparen ();
2489 }
2490
2491
2492 /* Save or restore a reference to a symbol node.  */
2493
2494 pointer_info *
2495 mio_symbol_ref (gfc_symbol **symp)
2496 {
2497   pointer_info *p;
2498
2499   p = mio_pointer_ref (symp);
2500   if (p->type == P_UNKNOWN)
2501     p->type = P_SYMBOL;
2502
2503   if (iomode == IO_OUTPUT)
2504     {
2505       if (p->u.wsym.state == UNREFERENCED)
2506         p->u.wsym.state = NEEDS_WRITE;
2507     }
2508   else
2509     {
2510       if (p->u.rsym.state == UNUSED)
2511         p->u.rsym.state = NEEDED;
2512     }
2513   return p;
2514 }
2515
2516
2517 /* Save or restore a reference to a symtree node.  */
2518
2519 static void
2520 mio_symtree_ref (gfc_symtree **stp)
2521 {
2522   pointer_info *p;
2523   fixup_t *f;
2524
2525   if (iomode == IO_OUTPUT)
2526     mio_symbol_ref (&(*stp)->n.sym);
2527   else
2528     {
2529       require_atom (ATOM_INTEGER);
2530       p = get_integer (atom_int);
2531
2532       /* An unused equivalence member; make a symbol and a symtree
2533          for it.  */
2534       if (in_load_equiv && p->u.rsym.symtree == NULL)
2535         {
2536           /* Since this is not used, it must have a unique name.  */
2537           p->u.rsym.symtree = gfc_get_unique_symtree (gfc_current_ns);
2538
2539           /* Make the symbol.  */
2540           if (p->u.rsym.sym == NULL)
2541             {
2542               p->u.rsym.sym = gfc_new_symbol (p->u.rsym.true_name,
2543                                               gfc_current_ns);
2544               p->u.rsym.sym->module = gfc_get_string (p->u.rsym.module);
2545             }
2546
2547           p->u.rsym.symtree->n.sym = p->u.rsym.sym;
2548           p->u.rsym.symtree->n.sym->refs++;
2549           p->u.rsym.referenced = 1;
2550
2551           /* If the symbol is PRIVATE and in COMMON, load_commons will
2552              generate a fixup symbol, which must be associated.  */
2553           if (p->fixup)
2554             resolve_fixups (p->fixup, p->u.rsym.sym);
2555           p->fixup = NULL;
2556         }
2557       
2558       if (p->type == P_UNKNOWN)
2559         p->type = P_SYMBOL;
2560
2561       if (p->u.rsym.state == UNUSED)
2562         p->u.rsym.state = NEEDED;
2563
2564       if (p->u.rsym.symtree != NULL)
2565         {
2566           *stp = p->u.rsym.symtree;
2567         }
2568       else
2569         {
2570           f = XCNEW (fixup_t);
2571
2572           f->next = p->u.rsym.stfixup;
2573           p->u.rsym.stfixup = f;
2574
2575           f->pointer = (void **) stp;
2576         }
2577     }
2578 }
2579
2580
2581 static void
2582 mio_iterator (gfc_iterator **ip)
2583 {
2584   gfc_iterator *iter;
2585
2586   mio_lparen ();
2587
2588   if (iomode == IO_OUTPUT)
2589     {
2590       if (*ip == NULL)
2591         goto done;
2592     }
2593   else
2594     {
2595       if (peek_atom () == ATOM_RPAREN)
2596         {
2597           *ip = NULL;
2598           goto done;
2599         }
2600
2601       *ip = gfc_get_iterator ();
2602     }
2603
2604   iter = *ip;
2605
2606   mio_expr (&iter->var);
2607   mio_expr (&iter->start);
2608   mio_expr (&iter->end);
2609   mio_expr (&iter->step);
2610
2611 done:
2612   mio_rparen ();
2613 }
2614
2615
2616 static void
2617 mio_constructor (gfc_constructor **cp)
2618 {
2619   gfc_constructor *c, *tail;
2620
2621   mio_lparen ();
2622
2623   if (iomode == IO_OUTPUT)
2624     {
2625       for (c = *cp; c; c = c->next)
2626         {
2627           mio_lparen ();
2628           mio_expr (&c->expr);
2629           mio_iterator (&c->iterator);
2630           mio_rparen ();
2631         }
2632     }
2633   else
2634     {
2635       *cp = NULL;
2636       tail = NULL;
2637
2638       while (peek_atom () != ATOM_RPAREN)
2639         {
2640           c = gfc_get_constructor ();
2641
2642           if (tail == NULL)
2643             *cp = c;
2644           else
2645             tail->next = c;
2646
2647           tail = c;
2648
2649           mio_lparen ();
2650           mio_expr (&c->expr);
2651           mio_iterator (&c->iterator);
2652           mio_rparen ();
2653         }
2654     }
2655
2656   mio_rparen ();
2657 }
2658
2659
2660 static const mstring ref_types[] = {
2661     minit ("ARRAY", REF_ARRAY),
2662     minit ("COMPONENT", REF_COMPONENT),
2663     minit ("SUBSTRING", REF_SUBSTRING),
2664     minit (NULL, -1)
2665 };
2666
2667
2668 static void
2669 mio_ref (gfc_ref **rp)
2670 {
2671   gfc_ref *r;
2672
2673   mio_lparen ();
2674
2675   r = *rp;
2676   r->type = MIO_NAME (ref_type) (r->type, ref_types);
2677
2678   switch (r->type)
2679     {
2680     case REF_ARRAY:
2681       mio_array_ref (&r->u.ar);
2682       break;
2683
2684     case REF_COMPONENT:
2685       mio_symbol_ref (&r->u.c.sym);
2686       mio_component_ref (&r->u.c.component, r->u.c.sym);
2687       break;
2688
2689     case REF_SUBSTRING:
2690       mio_expr (&r->u.ss.start);
2691       mio_expr (&r->u.ss.end);
2692       mio_charlen (&r->u.ss.length);
2693       break;
2694     }
2695
2696   mio_rparen ();
2697 }
2698
2699
2700 static void
2701 mio_ref_list (gfc_ref **rp)
2702 {
2703   gfc_ref *ref, *head, *tail;
2704
2705   mio_lparen ();
2706
2707   if (iomode == IO_OUTPUT)
2708     {
2709       for (ref = *rp; ref; ref = ref->next)
2710         mio_ref (&ref);
2711     }
2712   else
2713     {
2714       head = tail = NULL;
2715
2716       while (peek_atom () != ATOM_RPAREN)
2717         {
2718           if (head == NULL)
2719             head = tail = gfc_get_ref ();
2720           else
2721             {
2722               tail->next = gfc_get_ref ();
2723               tail = tail->next;
2724             }
2725
2726           mio_ref (&tail);
2727         }
2728
2729       *rp = head;
2730     }
2731
2732   mio_rparen ();
2733 }
2734
2735
2736 /* Read and write an integer value.  */
2737
2738 static void
2739 mio_gmp_integer (mpz_t *integer)
2740 {
2741   char *p;
2742
2743   if (iomode == IO_INPUT)
2744     {
2745       if (parse_atom () != ATOM_STRING)
2746         bad_module ("Expected integer string");
2747
2748       mpz_init (*integer);
2749       if (mpz_set_str (*integer, atom_string, 10))
2750         bad_module ("Error converting integer");
2751
2752       gfc_free (atom_string);
2753     }
2754   else
2755     {
2756       p = mpz_get_str (NULL, 10, *integer);
2757       write_atom (ATOM_STRING, p);
2758       gfc_free (p);
2759     }
2760 }
2761
2762
2763 static void
2764 mio_gmp_real (mpfr_t *real)
2765 {
2766   mp_exp_t exponent;
2767   char *p;
2768
2769   if (iomode == IO_INPUT)
2770     {
2771       if (parse_atom () != ATOM_STRING)
2772         bad_module ("Expected real string");
2773
2774       mpfr_init (*real);
2775       mpfr_set_str (*real, atom_string, 16, GFC_RND_MODE);
2776       gfc_free (atom_string);
2777     }
2778   else
2779     {
2780       p = mpfr_get_str (NULL, &exponent, 16, 0, *real, GFC_RND_MODE);
2781
2782       if (mpfr_nan_p (*real) || mpfr_inf_p (*real))
2783         {
2784           write_atom (ATOM_STRING, p);
2785           gfc_free (p);
2786           return;
2787         }
2788
2789       atom_string = XCNEWVEC (char, strlen (p) + 20);
2790
2791       sprintf (atom_string, "0.%s@%ld", p, exponent);
2792
2793       /* Fix negative numbers.  */
2794       if (atom_string[2] == '-')
2795         {
2796           atom_string[0] = '-';
2797           atom_string[1] = '0';
2798           atom_string[2] = '.';
2799         }
2800
2801       write_atom (ATOM_STRING, atom_string);
2802
2803       gfc_free (atom_string);
2804       gfc_free (p);
2805     }
2806 }
2807
2808
2809 /* Save and restore the shape of an array constructor.  */
2810
2811 static void
2812 mio_shape (mpz_t **pshape, int rank)
2813 {
2814   mpz_t *shape;
2815   atom_type t;
2816   int n;
2817
2818   /* A NULL shape is represented by ().  */
2819   mio_lparen ();
2820
2821   if (iomode == IO_OUTPUT)
2822     {
2823       shape = *pshape;
2824       if (!shape)
2825         {
2826           mio_rparen ();
2827           return;
2828         }
2829     }
2830   else
2831     {
2832       t = peek_atom ();
2833       if (t == ATOM_RPAREN)
2834         {
2835           *pshape = NULL;
2836           mio_rparen ();
2837           return;
2838         }
2839
2840       shape = gfc_get_shape (rank);
2841       *pshape = shape;
2842     }
2843
2844   for (n = 0; n < rank; n++)
2845     mio_gmp_integer (&shape[n]);
2846
2847   mio_rparen ();
2848 }
2849
2850
2851 static const mstring expr_types[] = {
2852     minit ("OP", EXPR_OP),
2853     minit ("FUNCTION", EXPR_FUNCTION),
2854     minit ("CONSTANT", EXPR_CONSTANT),
2855     minit ("VARIABLE", EXPR_VARIABLE),
2856     minit ("SUBSTRING", EXPR_SUBSTRING),
2857     minit ("STRUCTURE", EXPR_STRUCTURE),
2858     minit ("ARRAY", EXPR_ARRAY),
2859     minit ("NULL", EXPR_NULL),
2860     minit ("COMPCALL", EXPR_COMPCALL),
2861     minit (NULL, -1)
2862 };
2863
2864 /* INTRINSIC_ASSIGN is missing because it is used as an index for
2865    generic operators, not in expressions.  INTRINSIC_USER is also
2866    replaced by the correct function name by the time we see it.  */
2867
2868 static const mstring intrinsics[] =
2869 {
2870     minit ("UPLUS", INTRINSIC_UPLUS),
2871     minit ("UMINUS", INTRINSIC_UMINUS),
2872     minit ("PLUS", INTRINSIC_PLUS),
2873     minit ("MINUS", INTRINSIC_MINUS),
2874     minit ("TIMES", INTRINSIC_TIMES),
2875     minit ("DIVIDE", INTRINSIC_DIVIDE),
2876     minit ("POWER", INTRINSIC_POWER),
2877     minit ("CONCAT", INTRINSIC_CONCAT),
2878     minit ("AND", INTRINSIC_AND),
2879     minit ("OR", INTRINSIC_OR),
2880     minit ("EQV", INTRINSIC_EQV),
2881     minit ("NEQV", INTRINSIC_NEQV),
2882     minit ("EQ_SIGN", INTRINSIC_EQ),
2883     minit ("EQ", INTRINSIC_EQ_OS),
2884     minit ("NE_SIGN", INTRINSIC_NE),
2885     minit ("NE", INTRINSIC_NE_OS),
2886     minit ("GT_SIGN", INTRINSIC_GT),
2887     minit ("GT", INTRINSIC_GT_OS),
2888     minit ("GE_SIGN", INTRINSIC_GE),
2889     minit ("GE", INTRINSIC_GE_OS),
2890     minit ("LT_SIGN", INTRINSIC_LT),
2891     minit ("LT", INTRINSIC_LT_OS),
2892     minit ("LE_SIGN", INTRINSIC_LE),
2893     minit ("LE", INTRINSIC_LE_OS),
2894     minit ("NOT", INTRINSIC_NOT),
2895     minit ("PARENTHESES", INTRINSIC_PARENTHESES),
2896     minit (NULL, -1)
2897 };
2898
2899
2900 /* Remedy a couple of situations where the gfc_expr's can be defective.  */
2901  
2902 static void
2903 fix_mio_expr (gfc_expr *e)
2904 {
2905   gfc_symtree *ns_st = NULL;
2906   const char *fname;
2907
2908   if (iomode != IO_OUTPUT)
2909     return;
2910
2911   if (e->symtree)
2912     {
2913       /* If this is a symtree for a symbol that came from a contained module
2914          namespace, it has a unique name and we should look in the current
2915          namespace to see if the required, non-contained symbol is available
2916          yet. If so, the latter should be written.  */
2917       if (e->symtree->n.sym && check_unique_name (e->symtree->name))
2918         ns_st = gfc_find_symtree (gfc_current_ns->sym_root,
2919                                   e->symtree->n.sym->name);
2920
2921       /* On the other hand, if the existing symbol is the module name or the
2922          new symbol is a dummy argument, do not do the promotion.  */
2923       if (ns_st && ns_st->n.sym
2924           && ns_st->n.sym->attr.flavor != FL_MODULE
2925           && !e->symtree->n.sym->attr.dummy)
2926         e->symtree = ns_st;
2927     }
2928   else if (e->expr_type == EXPR_FUNCTION && e->value.function.name)
2929     {
2930       /* In some circumstances, a function used in an initialization
2931          expression, in one use associated module, can fail to be
2932          coupled to its symtree when used in a specification
2933          expression in another module.  */
2934       fname = e->value.function.esym ? e->value.function.esym->name
2935                                      : e->value.function.isym->name;
2936       e->symtree = gfc_find_symtree (gfc_current_ns->sym_root, fname);
2937     }
2938 }
2939
2940
2941 /* Read and write expressions.  The form "()" is allowed to indicate a
2942    NULL expression.  */
2943
2944 static void
2945 mio_expr (gfc_expr **ep)
2946 {
2947   gfc_expr *e;
2948   atom_type t;
2949   int flag;
2950
2951   mio_lparen ();
2952
2953   if (iomode == IO_OUTPUT)
2954     {
2955       if (*ep == NULL)
2956         {
2957           mio_rparen ();
2958           return;
2959         }
2960
2961       e = *ep;
2962       MIO_NAME (expr_t) (e->expr_type, expr_types);
2963     }
2964   else
2965     {
2966       t = parse_atom ();
2967       if (t == ATOM_RPAREN)
2968         {
2969           *ep = NULL;
2970           return;
2971         }
2972
2973       if (t != ATOM_NAME)
2974         bad_module ("Expected expression type");
2975
2976       e = *ep = gfc_get_expr ();
2977       e->where = gfc_current_locus;
2978       e->expr_type = (expr_t) find_enum (expr_types);
2979     }
2980
2981   mio_typespec (&e->ts);
2982   mio_integer (&e->rank);
2983
2984   fix_mio_expr (e);
2985
2986   switch (e->expr_type)
2987     {
2988     case EXPR_OP:
2989       e->value.op.op
2990         = MIO_NAME (gfc_intrinsic_op) (e->value.op.op, intrinsics);
2991
2992       switch (e->value.op.op)
2993         {
2994         case INTRINSIC_UPLUS:
2995         case INTRINSIC_UMINUS:
2996         case INTRINSIC_NOT:
2997         case INTRINSIC_PARENTHESES:
2998           mio_expr (&e->value.op.op1);
2999           break;
3000
3001         case INTRINSIC_PLUS:
3002         case INTRINSIC_MINUS:
3003         case INTRINSIC_TIMES:
3004         case INTRINSIC_DIVIDE:
3005         case INTRINSIC_POWER:
3006         case INTRINSIC_CONCAT:
3007         case INTRINSIC_AND:
3008         case INTRINSIC_OR:
3009         case INTRINSIC_EQV:
3010         case INTRINSIC_NEQV:
3011         case INTRINSIC_EQ:
3012         case INTRINSIC_EQ_OS:
3013         case INTRINSIC_NE:
3014         case INTRINSIC_NE_OS:
3015         case INTRINSIC_GT:
3016         case INTRINSIC_GT_OS:
3017         case INTRINSIC_GE:
3018         case INTRINSIC_GE_OS:
3019         case INTRINSIC_LT:
3020         case INTRINSIC_LT_OS:
3021         case INTRINSIC_LE:
3022         case INTRINSIC_LE_OS:
3023           mio_expr (&e->value.op.op1);
3024           mio_expr (&e->value.op.op2);
3025           break;
3026
3027         default:
3028           bad_module ("Bad operator");
3029         }
3030
3031       break;
3032
3033     case EXPR_FUNCTION:
3034       mio_symtree_ref (&e->symtree);
3035       mio_actual_arglist (&e->value.function.actual);
3036
3037       if (iomode == IO_OUTPUT)
3038         {
3039           e->value.function.name
3040             = mio_allocated_string (e->value.function.name);
3041           flag = e->value.function.esym != NULL;
3042           mio_integer (&flag);
3043           if (flag)
3044             mio_symbol_ref (&e->value.function.esym);
3045           else
3046             write_atom (ATOM_STRING, e->value.function.isym->name);
3047         }
3048       else
3049         {
3050           require_atom (ATOM_STRING);
3051           e->value.function.name = gfc_get_string (atom_string);
3052           gfc_free (atom_string);
3053
3054           mio_integer (&flag);
3055           if (flag)
3056             mio_symbol_ref (&e->value.function.esym);
3057           else
3058             {
3059               require_atom (ATOM_STRING);
3060               e->value.function.isym = gfc_find_function (atom_string);
3061               gfc_free (atom_string);
3062             }
3063         }
3064
3065       break;
3066
3067     case EXPR_VARIABLE:
3068       mio_symtree_ref (&e->symtree);
3069       mio_ref_list (&e->ref);
3070       break;
3071
3072     case EXPR_SUBSTRING:
3073       e->value.character.string
3074         = CONST_CAST (gfc_char_t *,
3075                       mio_allocated_wide_string (e->value.character.string,
3076                                                  e->value.character.length));
3077       mio_ref_list (&e->ref);
3078       break;
3079
3080     case EXPR_STRUCTURE:
3081     case EXPR_ARRAY:
3082       mio_constructor (&e->value.constructor);
3083       mio_shape (&e->shape, e->rank);
3084       break;
3085
3086     case EXPR_CONSTANT:
3087       switch (e->ts.type)
3088         {
3089         case BT_INTEGER:
3090           mio_gmp_integer (&e->value.integer);
3091           break;
3092
3093         case BT_REAL:
3094           gfc_set_model_kind (e->ts.kind);
3095           mio_gmp_real (&e->value.real);
3096           break;
3097
3098         case BT_COMPLEX:
3099           gfc_set_model_kind (e->ts.kind);
3100           mio_gmp_real (&mpc_realref (e->value.complex));
3101           mio_gmp_real (&mpc_imagref (e->value.complex));
3102           break;
3103
3104         case BT_LOGICAL:
3105           mio_integer (&e->value.logical);
3106           break;
3107
3108         case BT_CHARACTER:
3109           mio_integer (&e->value.character.length);
3110           e->value.character.string
3111             = CONST_CAST (gfc_char_t *,
3112                           mio_allocated_wide_string (e->value.character.string,
3113                                                      e->value.character.length));
3114           break;
3115
3116         default:
3117           bad_module ("Bad type in constant expression");
3118         }
3119
3120       break;
3121
3122     case EXPR_NULL:
3123       break;
3124
3125     case EXPR_COMPCALL:
3126     case EXPR_PPC:
3127       gcc_unreachable ();
3128       break;
3129     }
3130
3131   mio_rparen ();
3132 }
3133
3134
3135 /* Read and write namelists.  */
3136
3137 static void
3138 mio_namelist (gfc_symbol *sym)
3139 {
3140   gfc_namelist *n, *m;
3141   const char *check_name;
3142
3143   mio_lparen ();
3144
3145   if (iomode == IO_OUTPUT)
3146     {
3147       for (n = sym->namelist; n; n = n->next)
3148         mio_symbol_ref (&n->sym);
3149     }
3150   else
3151     {
3152       /* This departure from the standard is flagged as an error.
3153          It does, in fact, work correctly. TODO: Allow it
3154          conditionally?  */
3155       if (sym->attr.flavor == FL_NAMELIST)
3156         {
3157           check_name = find_use_name (sym->name, false);
3158           if (check_name && strcmp (check_name, sym->name) != 0)
3159             gfc_error ("Namelist %s cannot be renamed by USE "
3160                        "association to %s", sym->name, check_name);
3161         }
3162
3163       m = NULL;
3164       while (peek_atom () != ATOM_RPAREN)
3165         {
3166           n = gfc_get_namelist ();
3167           mio_symbol_ref (&n->sym);
3168
3169           if (sym->namelist == NULL)
3170             sym->namelist = n;
3171           else
3172             m->next = n;
3173
3174           m = n;
3175         }
3176       sym->namelist_tail = m;
3177     }
3178
3179   mio_rparen ();
3180 }
3181
3182
3183 /* Save/restore lists of gfc_interface structures.  When loading an
3184    interface, we are really appending to the existing list of
3185    interfaces.  Checking for duplicate and ambiguous interfaces has to
3186    be done later when all symbols have been loaded.  */
3187
3188 pointer_info *
3189 mio_interface_rest (gfc_interface **ip)
3190 {
3191   gfc_interface *tail, *p;
3192   pointer_info *pi = NULL;
3193
3194   if (iomode == IO_OUTPUT)
3195     {
3196       if (ip != NULL)
3197         for (p = *ip; p; p = p->next)
3198           mio_symbol_ref (&p->sym);
3199     }
3200   else
3201     {
3202       if (*ip == NULL)
3203         tail = NULL;
3204       else
3205         {
3206           tail = *ip;
3207           while (tail->next)
3208             tail = tail->next;
3209         }
3210
3211       for (;;)
3212         {
3213           if (peek_atom () == ATOM_RPAREN)
3214             break;
3215
3216           p = gfc_get_interface ();
3217           p->where = gfc_current_locus;
3218           pi = mio_symbol_ref (&p->sym);
3219
3220           if (tail == NULL)
3221             *ip = p;
3222           else
3223             tail->next = p;
3224
3225           tail = p;
3226         }
3227     }
3228
3229   mio_rparen ();
3230   return pi;
3231 }
3232
3233
3234 /* Save/restore a nameless operator interface.  */
3235
3236 static void
3237 mio_interface (gfc_interface **ip)
3238 {
3239   mio_lparen ();
3240   mio_interface_rest (ip);
3241 }
3242
3243
3244 /* Save/restore a named operator interface.  */
3245
3246 static void
3247 mio_symbol_interface (const char **name, const char **module,
3248                       gfc_interface **ip)
3249 {
3250   mio_lparen ();
3251   mio_pool_string (name);
3252   mio_pool_string (module);
3253   mio_interface_rest (ip);
3254 }
3255
3256
3257 static void
3258 mio_namespace_ref (gfc_namespace **nsp)
3259 {
3260   gfc_namespace *ns;
3261   pointer_info *p;
3262
3263   p = mio_pointer_ref (nsp);
3264
3265   if (p->type == P_UNKNOWN)
3266     p->type = P_NAMESPACE;
3267
3268   if (iomode == IO_INPUT && p->integer != 0)
3269     {
3270       ns = (gfc_namespace *) p->u.pointer;
3271       if (ns == NULL)
3272         {
3273           ns = gfc_get_namespace (NULL, 0);
3274           associate_integer_pointer (p, ns);
3275         }
3276       else
3277         ns->refs++;
3278     }
3279 }
3280
3281
3282 /* Save/restore the f2k_derived namespace of a derived-type symbol.  */
3283
3284 static gfc_namespace* current_f2k_derived;
3285
3286 static void
3287 mio_typebound_proc (gfc_typebound_proc** proc)
3288 {
3289   int flag;
3290   int overriding_flag;
3291
3292   if (iomode == IO_INPUT)
3293     {
3294       *proc = gfc_get_typebound_proc ();
3295       (*proc)->where = gfc_current_locus;
3296     }
3297   gcc_assert (*proc);
3298
3299   mio_lparen ();
3300
3301   (*proc)->access = MIO_NAME (gfc_access) ((*proc)->access, access_types);
3302
3303   /* IO the NON_OVERRIDABLE/DEFERRED combination.  */
3304   gcc_assert (!((*proc)->deferred && (*proc)->non_overridable));
3305   overriding_flag = ((*proc)->deferred << 1) | (*proc)->non_overridable;
3306   overriding_flag = mio_name (overriding_flag, binding_overriding);
3307   (*proc)->deferred = ((overriding_flag & 2) != 0);
3308   (*proc)->non_overridable = ((overriding_flag & 1) != 0);
3309   gcc_assert (!((*proc)->deferred && (*proc)->non_overridable));
3310
3311   (*proc)->nopass = mio_name ((*proc)->nopass, binding_passing);
3312   (*proc)->is_generic = mio_name ((*proc)->is_generic, binding_generic);
3313   (*proc)->ppc = mio_name((*proc)->ppc, binding_ppc);
3314
3315   mio_pool_string (&((*proc)->pass_arg));
3316
3317   flag = (int) (*proc)->pass_arg_num;
3318   mio_integer (&flag);
3319   (*proc)->pass_arg_num = (unsigned) flag;
3320
3321   if ((*proc)->is_generic)
3322     {
3323       gfc_tbp_generic* g;
3324
3325       mio_lparen ();
3326
3327       if (iomode == IO_OUTPUT)
3328         for (g = (*proc)->u.generic; g; g = g->next)
3329           mio_allocated_string (g->specific_st->name);
3330       else
3331         {
3332           (*proc)->u.generic = NULL;
3333           while (peek_atom () != ATOM_RPAREN)
3334             {
3335               gfc_symtree** sym_root;
3336
3337               g = gfc_get_tbp_generic ();
3338               g->specific = NULL;
3339
3340               require_atom (ATOM_STRING);
3341               sym_root = &current_f2k_derived->tb_sym_root;
3342               g->specific_st = gfc_get_tbp_symtree (sym_root, atom_string);
3343               gfc_free (atom_string);
3344
3345               g->next = (*proc)->u.generic;
3346               (*proc)->u.generic = g;
3347             }
3348         }
3349
3350       mio_rparen ();
3351     }
3352   else if (!(*proc)->ppc)
3353     mio_symtree_ref (&(*proc)->u.specific);
3354
3355   mio_rparen ();
3356 }
3357
3358 /* Walker-callback function for this purpose.  */
3359 static void
3360 mio_typebound_symtree (gfc_symtree* st)
3361 {
3362   if (iomode == IO_OUTPUT && !st->n.tb)
3363     return;
3364
3365   if (iomode == IO_OUTPUT)
3366     {
3367       mio_lparen ();
3368       mio_allocated_string (st->name);
3369     }
3370   /* For IO_INPUT, the above is done in mio_f2k_derived.  */
3371
3372   mio_typebound_proc (&st->n.tb);
3373   mio_rparen ();
3374 }
3375
3376 /* IO a full symtree (in all depth).  */
3377 static void
3378 mio_full_typebound_tree (gfc_symtree** root)
3379 {
3380   mio_lparen ();
3381
3382   if (iomode == IO_OUTPUT)
3383     gfc_traverse_symtree (*root, &mio_typebound_symtree);
3384   else
3385     {
3386       while (peek_atom () == ATOM_LPAREN)
3387         {
3388           gfc_symtree* st;
3389
3390           mio_lparen (); 
3391
3392           require_atom (ATOM_STRING);
3393           st = gfc_get_tbp_symtree (root, atom_string);
3394           gfc_free (atom_string);
3395
3396           mio_typebound_symtree (st);
3397         }
3398     }
3399
3400   mio_rparen ();
3401 }
3402
3403 static void
3404 mio_finalizer (gfc_finalizer **f)
3405 {
3406   if (iomode == IO_OUTPUT)
3407     {
3408       gcc_assert (*f);
3409       gcc_assert ((*f)->proc_tree); /* Should already be resolved.  */
3410       mio_symtree_ref (&(*f)->proc_tree);
3411     }
3412   else
3413     {
3414       *f = gfc_get_finalizer ();
3415       (*f)->where = gfc_current_locus; /* Value should not matter.  */
3416       (*f)->next = NULL;
3417
3418       mio_symtree_ref (&(*f)->proc_tree);
3419       (*f)->proc_sym = NULL;
3420     }
3421 }
3422
3423 static void
3424 mio_f2k_derived (gfc_namespace *f2k)
3425 {
3426   current_f2k_derived = f2k;
3427
3428   /* Handle the list of finalizer procedures.  */
3429   mio_lparen ();
3430   if (iomode == IO_OUTPUT)
3431     {
3432       gfc_finalizer *f;
3433       for (f = f2k->finalizers; f; f = f->next)
3434         mio_finalizer (&f);
3435     }
3436   else
3437     {
3438       f2k->finalizers = NULL;
3439       while (peek_atom () != ATOM_RPAREN)
3440         {
3441           gfc_finalizer *cur = NULL;
3442           mio_finalizer (&cur);
3443           cur->next = f2k->finalizers;
3444           f2k->finalizers = cur;
3445         }
3446     }
3447   mio_rparen ();
3448
3449   /* Handle type-bound procedures.  */
3450   mio_full_typebound_tree (&f2k->tb_sym_root);
3451
3452   /* Type-bound user operators.  */
3453   mio_full_typebound_tree (&f2k->tb_uop_root);
3454
3455   /* Type-bound intrinsic operators.  */
3456   mio_lparen ();
3457   if (iomode == IO_OUTPUT)
3458     {
3459       int op;
3460       for (op = GFC_INTRINSIC_BEGIN; op != GFC_INTRINSIC_END; ++op)
3461         {
3462           gfc_intrinsic_op realop;
3463
3464           if (op == INTRINSIC_USER || !f2k->tb_op[op])
3465             continue;
3466
3467           mio_lparen ();
3468           realop = (gfc_intrinsic_op) op;
3469           mio_intrinsic_op (&realop);
3470           mio_typebound_proc (&f2k->tb_op[op]);
3471           mio_rparen ();
3472         }
3473     }
3474   else
3475     while (peek_atom () != ATOM_RPAREN)
3476       {
3477         gfc_intrinsic_op op = 0; /* Silence GCC.  */
3478
3479         mio_lparen ();
3480         mio_intrinsic_op (&op);
3481         mio_typebound_proc (&f2k->tb_op[op]);
3482         mio_rparen ();
3483       }
3484   mio_rparen ();
3485 }
3486
3487 static void
3488 mio_full_f2k_derived (gfc_symbol *sym)
3489 {
3490   mio_lparen ();
3491   
3492   if (iomode == IO_OUTPUT)
3493     {
3494       if (sym->f2k_derived)
3495         mio_f2k_derived (sym->f2k_derived);
3496     }
3497   else
3498     {
3499       if (peek_atom () != ATOM_RPAREN)
3500         {
3501           sym->f2k_derived = gfc_get_namespace (NULL, 0);
3502           mio_f2k_derived (sym->f2k_derived);
3503         }
3504       else
3505         gcc_assert (!sym->f2k_derived);
3506     }
3507
3508   mio_rparen ();
3509 }
3510
3511
3512 /* Unlike most other routines, the address of the symbol node is already
3513    fixed on input and the name/module has already been filled in.  */
3514
3515 static void
3516 mio_symbol (gfc_symbol *sym)
3517 {
3518   int intmod = INTMOD_NONE;
3519   
3520   mio_lparen ();
3521
3522   mio_symbol_attribute (&sym->attr);
3523   mio_typespec (&sym->ts);
3524
3525   if (iomode == IO_OUTPUT)
3526     mio_namespace_ref (&sym->formal_ns);
3527   else
3528     {
3529       mio_namespace_ref (&sym->formal_ns);
3530       if (sym->formal_ns)
3531         {
3532           sym->formal_ns->proc_name = sym;
3533           sym->refs++;
3534         }
3535     }
3536
3537   /* Save/restore common block links.  */
3538   mio_symbol_ref (&sym->common_next);
3539
3540   mio_formal_arglist (&sym->formal);
3541
3542   if (sym->attr.flavor == FL_PARAMETER)
3543     mio_expr (&sym->value);
3544
3545   mio_array_spec (&sym->as);
3546
3547   mio_symbol_ref (&sym->result);
3548
3549   if (sym->attr.cray_pointee)
3550     mio_symbol_ref (&sym->cp_pointer);
3551
3552   /* Note that components are always saved, even if they are supposed
3553      to be private.  Component access is checked during searching.  */
3554
3555   mio_component_list (&sym->components);
3556
3557   if (sym->components != NULL)
3558     sym->component_access
3559       = MIO_NAME (gfc_access) (sym->component_access, access_types);
3560
3561   /* Load/save the f2k_derived namespace of a derived-type symbol.  */
3562   mio_full_f2k_derived (sym);
3563
3564   mio_namelist (sym);
3565
3566   /* Add the fields that say whether this is from an intrinsic module,
3567      and if so, what symbol it is within the module.  */
3568 /*   mio_integer (&(sym->from_intmod)); */
3569   if (iomode == IO_OUTPUT)
3570     {
3571       intmod = sym->from_intmod;
3572       mio_integer (&intmod);
3573     }
3574   else
3575     {
3576       mio_integer (&intmod);
3577       sym->from_intmod = (intmod_id) intmod;
3578     }
3579   
3580   mio_integer (&(sym->intmod_sym_id));
3581
3582   if (sym->attr.flavor == FL_DERIVED)
3583     mio_integer (&(sym->hash_value));
3584
3585   mio_rparen ();
3586 }
3587
3588
3589 /************************* Top level subroutines *************************/
3590
3591 /* Given a root symtree node and a symbol, try to find a symtree that
3592    references the symbol that is not a unique name.  */
3593
3594 static gfc_symtree *
3595 find_symtree_for_symbol (gfc_symtree *st, gfc_symbol *sym)
3596 {
3597   gfc_symtree *s = NULL;
3598
3599   if (st == NULL)
3600     return s;
3601
3602   s = find_symtree_for_symbol (st->right, sym);
3603   if (s != NULL)
3604     return s;
3605   s = find_symtree_for_symbol (st->left, sym);
3606   if (s != NULL)
3607     return s;
3608
3609   if (st->n.sym == sym && !check_unique_name (st->name))
3610     return st;
3611
3612   return s;
3613 }
3614
3615
3616 /* A recursive function to look for a specific symbol by name and by
3617    module.  Whilst several symtrees might point to one symbol, its
3618    is sufficient for the purposes here than one exist.  Note that
3619    generic interfaces are distinguished as are symbols that have been
3620    renamed in another module.  */
3621 static gfc_symtree *
3622 find_symbol (gfc_symtree *st, const char *name,
3623              const char *module, int generic)
3624 {
3625   int c;
3626   gfc_symtree *retval, *s;
3627
3628   if (st == NULL || st->n.sym == NULL)
3629     return NULL;
3630
3631   c = strcmp (name, st->n.sym->name);
3632   if (c == 0 && st->n.sym->module
3633              && strcmp (module, st->n.sym->module) == 0
3634              && !check_unique_name (st->name))
3635     {
3636       s = gfc_find_symtree (gfc_current_ns->sym_root, name);
3637
3638       /* Detect symbols that are renamed by use association in another
3639          module by the absence of a symtree and null attr.use_rename,
3640          since the latter is not transmitted in the module file.  */
3641       if (((!generic && !st->n.sym->attr.generic)
3642                 || (generic && st->n.sym->attr.generic))
3643             && !(s == NULL && !st->n.sym->attr.use_rename))
3644         return st;
3645     }
3646
3647   retval = find_symbol (st->left, name, module, generic);
3648
3649   if (retval == NULL)
3650     retval = find_symbol (st->right, name, module, generic);
3651
3652   return retval;
3653 }
3654
3655
3656 /* Skip a list between balanced left and right parens.  */
3657
3658 static void
3659 skip_list (void)
3660 {
3661   int level;
3662
3663   level = 0;
3664   do
3665     {
3666       switch (parse_atom ())
3667         {
3668         case ATOM_LPAREN:
3669           level++;
3670           break;
3671
3672         case ATOM_RPAREN:
3673           level--;
3674           break;
3675
3676         case ATOM_STRING:
3677           gfc_free (atom_string);
3678           break;
3679
3680         case ATOM_NAME:
3681         case ATOM_INTEGER:
3682           break;
3683         }
3684     }
3685   while (level > 0);
3686 }
3687
3688
3689 /* Load operator interfaces from the module.  Interfaces are unusual
3690    in that they attach themselves to existing symbols.  */
3691
3692 static void
3693 load_operator_interfaces (void)
3694 {
3695   const char *p;
3696   char name[GFC_MAX_SYMBOL_LEN + 1], module[GFC_MAX_SYMBOL_LEN + 1];
3697   gfc_user_op *uop;
3698   pointer_info *pi = NULL;
3699   int n, i;
3700
3701   mio_lparen ();
3702
3703   while (peek_atom () != ATOM_RPAREN)
3704     {
3705       mio_lparen ();
3706
3707       mio_internal_string (name);
3708       mio_internal_string (module);
3709
3710       n = number_use_names (name, true);
3711       n = n ? n : 1;
3712
3713       for (i = 1; i <= n; i++)
3714         {
3715           /* Decide if we need to load this one or not.  */
3716           p = find_use_name_n (name, &i, true);
3717
3718           if (p == NULL)
3719             {
3720               while (parse_atom () != ATOM_RPAREN);
3721               continue;
3722             }
3723
3724           if (i == 1)
3725             {
3726               uop = gfc_get_uop (p);
3727               pi = mio_interface_rest (&uop->op);
3728             }
3729           else
3730             {
3731               if (gfc_find_uop (p, NULL))
3732                 continue;
3733               uop = gfc_get_uop (p);
3734               uop->op = gfc_get_interface ();
3735               uop->op->where = gfc_current_locus;
3736               add_fixup (pi->integer, &uop->op->sym);
3737             }
3738         }
3739     }
3740
3741   mio_rparen ();
3742 }
3743
3744
3745 /* Load interfaces from the module.  Interfaces are unusual in that
3746    they attach themselves to existing symbols.  */
3747
3748 static void
3749 load_generic_interfaces (void)
3750 {
3751   const char *p;
3752   char name[GFC_MAX_SYMBOL_LEN + 1], module[GFC_MAX_SYMBOL_LEN + 1];
3753   gfc_symbol *sym;
3754   gfc_interface *generic = NULL, *gen = NULL;
3755   int n, i, renamed;
3756   bool ambiguous_set = false;
3757
3758   mio_lparen ();
3759
3760   while (peek_atom () != ATOM_RPAREN)
3761     {
3762       mio_lparen ();
3763
3764       mio_internal_string (name);
3765       mio_internal_string (module);
3766
3767       n = number_use_names (name, false);
3768       renamed = n ? 1 : 0;
3769       n = n ? n : 1;
3770
3771       for (i = 1; i <= n; i++)
3772         {
3773           gfc_symtree *st;
3774           /* Decide if we need to load this one or not.  */
3775           p = find_use_name_n (name, &i, false);
3776
3777           st = find_symbol (gfc_current_ns->sym_root,
3778                             name, module_name, 1);
3779
3780           if (!p || gfc_find_symbol (p, NULL, 0, &sym))
3781             {
3782               /* Skip the specific names for these cases.  */
3783               while (i == 1 && parse_atom () != ATOM_RPAREN);
3784
3785               continue;
3786             }
3787
3788           /* If the symbol exists already and is being USEd without being
3789              in an ONLY clause, do not load a new symtree(11.3.2).  */
3790           if (!only_flag && st)
3791             sym = st->n.sym;
3792
3793           if (!sym)
3794             {
3795               /* Make the symbol inaccessible if it has been added by a USE
3796                  statement without an ONLY(11.3.2).  */
3797               if (st && only_flag
3798                      && !st->n.sym->attr.use_only
3799                      && !st->n.sym->attr.use_rename
3800                      && strcmp (st->n.sym->module, module_name) == 0)
3801                 {
3802                   sym = st->n.sym;
3803                   gfc_delete_symtree (&gfc_current_ns->sym_root, name);
3804                   st = gfc_get_unique_symtree (gfc_current_ns);
3805                   st->n.sym = sym;
3806                   sym = NULL;
3807                 }
3808               else if (st)
3809                 {
3810                   sym = st->n.sym;
3811                   if (strcmp (st->name, p) != 0)
3812                     {
3813                       st = gfc_new_symtree (&gfc_current_ns->sym_root, p);
3814                       st->n.sym = sym;
3815                       sym->refs++;
3816                     }
3817                 }
3818
3819               /* Since we haven't found a valid generic interface, we had
3820                  better make one.  */
3821               if (!sym)
3822                 {
3823                   gfc_get_symbol (p, NULL, &sym);
3824                   sym->name = gfc_get_string (name);
3825                   sym->module = gfc_get_string (module_name);
3826                   sym->attr.flavor = FL_PROCEDURE;
3827                   sym->attr.generic = 1;
3828                   sym->attr.use_assoc = 1;
3829                 }
3830             }
3831           else
3832             {
3833               /* Unless sym is a generic interface, this reference
3834                  is ambiguous.  */
3835               if (st == NULL)
3836                 st = gfc_find_symtree (gfc_current_ns->sym_root, p);
3837
3838               sym = st->n.sym;
3839
3840               if (st && !sym->attr.generic
3841                      && !st->ambiguous
3842                      && sym->module
3843                      && strcmp(module, sym->module))
3844                 {
3845                   ambiguous_set = true;
3846                   st->ambiguous = 1;
3847                 }
3848             }
3849
3850           sym->attr.use_only = only_flag;
3851           sym->attr.use_rename = renamed;
3852
3853           if (i == 1)
3854             {
3855               mio_interface_rest (&sym->generic);
3856               generic = sym->generic;
3857             }
3858           else if (!sym->generic)
3859             {
3860               sym->generic = generic;
3861               sym->attr.generic_copy = 1;
3862             }
3863
3864           /* If a procedure that is not generic has generic interfaces
3865              that include itself, it is generic! We need to take care
3866              to retain symbols ambiguous that were already so.  */
3867           if (sym->attr.use_assoc
3868                 && !sym->attr.generic
3869                 && sym->attr.flavor == FL_PROCEDURE)
3870             {
3871               for (gen = generic; gen; gen = gen->next)
3872                 {
3873                   if (gen->sym == sym)
3874                     {
3875                       sym->attr.generic = 1;
3876                       if (ambiguous_set)
3877                         st->ambiguous = 0;
3878                       break;
3879                     }
3880                 }
3881             }
3882
3883         }
3884     }
3885
3886   mio_rparen ();
3887 }
3888
3889
3890 /* Load common blocks.  */
3891
3892 static void
3893 load_commons (void)
3894 {
3895   char name[GFC_MAX_SYMBOL_LEN + 1];
3896   gfc_common_head *p;
3897
3898   mio_lparen ();
3899
3900   while (peek_atom () != ATOM_RPAREN)
3901     {
3902       int flags;
3903       mio_lparen ();
3904       mio_internal_string (name);
3905
3906       p = gfc_get_common (name, 1);
3907
3908       mio_symbol_ref (&p->head);
3909       mio_integer (&flags);
3910       if (flags & 1)
3911         p->saved = 1;
3912       if (flags & 2)
3913         p->threadprivate = 1;
3914       p->use_assoc = 1;
3915
3916       /* Get whether this was a bind(c) common or not.  */
3917       mio_integer (&p->is_bind_c);
3918       /* Get the binding label.  */
3919       mio_internal_string (p->binding_label);
3920       
3921       mio_rparen ();
3922     }
3923
3924   mio_rparen ();
3925 }
3926
3927
3928 /* Load equivalences.  The flag in_load_equiv informs mio_expr_ref of this
3929    so that unused variables are not loaded and so that the expression can
3930    be safely freed.  */
3931
3932 static void
3933 load_equiv (void)
3934 {
3935   gfc_equiv *head, *tail, *end, *eq;
3936   bool unused;
3937
3938   mio_lparen ();
3939   in_load_equiv = true;
3940
3941   end = gfc_current_ns->equiv;
3942   while (end != NULL && end->next != NULL)
3943     end = end->next;
3944
3945   while (peek_atom () != ATOM_RPAREN) {
3946     mio_lparen ();
3947     head = tail = NULL;
3948
3949     while(peek_atom () != ATOM_RPAREN)
3950       {
3951         if (head == NULL)
3952           head = tail = gfc_get_equiv ();
3953         else
3954           {
3955             tail->eq = gfc_get_equiv ();
3956             tail = tail->eq;
3957           }
3958
3959         mio_pool_string (&tail->module);
3960         mio_expr (&tail->expr);
3961       }
3962
3963     /* Unused equivalence members have a unique name.  In addition, it
3964        must be checked that the symbols are from the same module.  */
3965     unused = true;
3966     for (eq = head; eq; eq = eq->eq)
3967       {
3968         if (eq->expr->symtree->n.sym->module
3969               && head->expr->symtree->n.sym->module
3970               && strcmp (head->expr->symtree->n.sym->module,
3971                          eq->expr->symtree->n.sym->module) == 0
3972               && !check_unique_name (eq->expr->symtree->name))
3973           {
3974             unused = false;
3975             break;
3976           }
3977       }
3978
3979     if (unused)
3980       {
3981         for (eq = head; eq; eq = head)
3982           {
3983             head = eq->eq;
3984             gfc_free_expr (eq->expr);
3985             gfc_free (eq);
3986           }
3987       }
3988
3989     if (end == NULL)
3990       gfc_current_ns->equiv = head;
3991     else
3992       end->next = head;
3993
3994     if (head != NULL)
3995       end = head;
3996
3997     mio_rparen ();
3998   }
3999
4000   mio_rparen ();
4001   in_load_equiv = false;
4002 }
4003
4004
4005 /* This function loads the sym_root of f2k_derived with the extensions to
4006    the derived type.  */
4007 static void
4008 load_derived_extensions (void)
4009 {
4010   int symbol, j;
4011   gfc_symbol *derived;
4012   gfc_symbol *dt;
4013   gfc_symtree *st;
4014   pointer_info *info;
4015   char name[GFC_MAX_SYMBOL_LEN + 1];
4016   char module[GFC_MAX_SYMBOL_LEN + 1];
4017   const char *p;
4018
4019   mio_lparen ();
4020   while (peek_atom () != ATOM_RPAREN)
4021     {
4022       mio_lparen ();
4023       mio_integer (&symbol);
4024       info = get_integer (symbol);
4025       derived = info->u.rsym.sym;
4026
4027       /* This one is not being loaded.  */
4028       if (!info || !derived)
4029         {
4030           while (peek_atom () != ATOM_RPAREN)
4031             skip_list ();
4032           continue;
4033         }
4034
4035       gcc_assert (derived->attr.flavor == FL_DERIVED);
4036       if (derived->f2k_derived == NULL)
4037         derived->f2k_derived = gfc_get_namespace (NULL, 0);
4038
4039       while (peek_atom () != ATOM_RPAREN)
4040         {
4041           mio_lparen ();
4042           mio_internal_string (name);
4043           mio_internal_string (module);
4044
4045           /* Only use one use name to find the symbol.  */
4046           j = 1;
4047           p = find_use_name_n (name, &j, false);
4048           if (p)
4049             {
4050               st = gfc_find_symtree (gfc_current_ns->sym_root, p);
4051               dt = st->n.sym;
4052               st = gfc_find_symtree (derived->f2k_derived->sym_root, name);
4053               if (st == NULL)
4054                 {
4055                   /* Only use the real name in f2k_derived to ensure a single
4056                     symtree.  */
4057                   st = gfc_new_symtree (&derived->f2k_derived->sym_root, name);
4058                   st->n.sym = dt;
4059                   st->n.sym->refs++;
4060                 }
4061             }
4062           mio_rparen ();
4063         }
4064       mio_rparen ();
4065     }
4066   mio_rparen ();
4067 }
4068
4069
4070 /* Recursive function to traverse the pointer_info tree and load a
4071    needed symbol.  We return nonzero if we load a symbol and stop the
4072    traversal, because the act of loading can alter the tree.  */
4073
4074 static int
4075 load_needed (pointer_info *p)
4076 {
4077   gfc_namespace *ns;
4078   pointer_info *q;
4079   gfc_symbol *sym;
4080   int rv;
4081
4082   rv = 0;
4083   if (p == NULL)
4084     return rv;
4085
4086   rv |= load_needed (p->left);
4087   rv |= load_needed (p->right);
4088
4089   if (p->type != P_SYMBOL || p->u.rsym.state != NEEDED)
4090     return rv;
4091
4092   p->u.rsym.state = USED;
4093
4094   set_module_locus (&p->u.rsym.where);
4095
4096   sym = p->u.rsym.sym;
4097   if (sym == NULL)
4098     {
4099       q = get_integer (p->u.rsym.ns);
4100
4101       ns = (gfc_namespace *) q->u.pointer;
4102       if (ns == NULL)
4103         {
4104           /* Create an interface namespace if necessary.  These are
4105              the namespaces that hold the formal parameters of module
4106              procedures.  */
4107
4108           ns = gfc_get_namespace (NULL, 0);
4109           associate_integer_pointer (q, ns);
4110         }
4111
4112       /* Use the module sym as 'proc_name' so that gfc_get_symbol_decl
4113          doesn't go pear-shaped if the symbol is used.  */
4114       if (!ns->proc_name)
4115         gfc_find_symbol (p->u.rsym.module, gfc_current_ns,
4116                                  1, &ns->proc_name);
4117
4118       sym = gfc_new_symbol (p->u.rsym.true_name, ns);
4119       sym->module = gfc_get_string (p->u.rsym.module);
4120       strcpy (sym->binding_label, p->u.rsym.binding_label);
4121
4122       associate_integer_pointer (p, sym);
4123     }
4124
4125   mio_symbol (sym);
4126   sym->attr.use_assoc = 1;
4127   if (only_flag)
4128     sym->attr.use_only = 1;
4129   if (p->u.rsym.renamed)
4130     sym->attr.use_rename = 1;
4131
4132   return 1;
4133 }
4134
4135
4136 /* Recursive function for cleaning up things after a module has been read.  */
4137
4138 static void
4139 read_cleanup (pointer_info *p)
4140 {
4141   gfc_symtree *st;
4142   pointer_info *q;
4143
4144   if (p == NULL)
4145     return;
4146
4147   read_cleanup (p->left);
4148   read_cleanup (p->right);
4149
4150   if (p->type == P_SYMBOL && p->u.rsym.state == USED && !p->u.rsym.referenced)
4151     {
4152       /* Add hidden symbols to the symtree.  */
4153       q = get_integer (p->u.rsym.ns);
4154       st = gfc_get_unique_symtree ((gfc_namespace *) q->u.pointer);
4155
4156       st->n.sym = p->u.rsym.sym;
4157       st->n.sym->refs++;
4158
4159       /* Fixup any symtree references.  */
4160       p->u.rsym.symtree = st;
4161       resolve_fixups (p->u.rsym.stfixup, st);
4162       p->u.rsym.stfixup = NULL;
4163     }
4164
4165   /* Free unused symbols.  */
4166   if (p->type == P_SYMBOL && p->u.rsym.state == UNUSED)
4167     gfc_free_symbol (p->u.rsym.sym);
4168 }
4169
4170
4171 /* It is not quite enough to check for ambiguity in the symbols by
4172    the loaded symbol and the new symbol not being identical.  */
4173 static bool
4174 check_for_ambiguous (gfc_symbol *st_sym, pointer_info *info)
4175 {
4176   gfc_symbol *rsym;
4177   module_locus locus;
4178   symbol_attribute attr;
4179
4180   rsym = info->u.rsym.sym;
4181   if (st_sym == rsym)
4182     return false;
4183
4184   /* If the existing symbol is generic from a different module and
4185      the new symbol is generic there can be no ambiguity.  */
4186   if (st_sym->attr.generic
4187         && st_sym->module
4188         && strcmp (st_sym->module, module_name))
4189     {
4190       /* The new symbol's attributes have not yet been read.  Since
4191          we need attr.generic, read it directly.  */
4192       get_module_locus (&locus);
4193       set_module_locus (&info->u.rsym.where);
4194       mio_lparen ();
4195       attr.generic = 0;
4196       mio_symbol_attribute (&attr);
4197       set_module_locus (&locus);
4198       if (attr.generic)
4199         return false;
4200     }
4201
4202   return true;
4203 }
4204
4205
4206 /* Read a module file.  */
4207
4208 static void
4209 read_module (void)
4210 {
4211   module_locus operator_interfaces, user_operators, extensions;
4212   const char *p;
4213   char name[GFC_MAX_SYMBOL_LEN + 1];
4214   int i;
4215   int ambiguous, j, nuse, symbol;
4216   pointer_info *info, *q;
4217   gfc_use_rename *u;
4218   gfc_symtree *st;
4219   gfc_symbol *sym;
4220
4221   get_module_locus (&operator_interfaces);      /* Skip these for now.  */
4222   skip_list ();
4223
4224   get_module_locus (&user_operators);
4225   skip_list ();
4226   skip_list ();
4227
4228   /* Skip commons, equivalences and derived type extensions for now.  */
4229   skip_list ();
4230   skip_list ();
4231
4232   get_module_locus (&extensions);
4233   skip_list ();
4234
4235   mio_lparen ();
4236
4237   /* Create the fixup nodes for all the symbols.  */
4238
4239   while (peek_atom () != ATOM_RPAREN)
4240     {
4241       require_atom (ATOM_INTEGER);
4242       info = get_integer (atom_int);
4243
4244       info->type = P_SYMBOL;
4245       info->u.rsym.state = UNUSED;
4246
4247       mio_internal_string (info->u.rsym.true_name);
4248       mio_internal_string (info->u.rsym.module);
4249       mio_internal_string (info->u.rsym.binding_label);
4250
4251       
4252       require_atom (ATOM_INTEGER);
4253       info->u.rsym.ns = atom_int;
4254
4255       get_module_locus (&info->u.rsym.where);
4256       skip_list ();
4257
4258       /* See if the symbol has already been loaded by a previous module.
4259          If so, we reference the existing symbol and prevent it from
4260          being loaded again.  This should not happen if the symbol being
4261          read is an index for an assumed shape dummy array (ns != 1).  */
4262
4263       sym = find_true_name (info->u.rsym.true_name, info->u.rsym.module);
4264
4265       if (sym == NULL
4266           || (sym->attr.flavor == FL_VARIABLE && info->u.rsym.ns !=1))
4267         continue;
4268
4269       info->u.rsym.state = USED;
4270       info->u.rsym.sym = sym;
4271
4272       /* Some symbols do not have a namespace (eg. formal arguments),
4273          so the automatic "unique symtree" mechanism must be suppressed
4274          by marking them as referenced.  */
4275       q = get_integer (info->u.rsym.ns);
4276       if (q->u.pointer == NULL)
4277         {
4278           info->u.rsym.referenced = 1;
4279           continue;
4280         }
4281
4282       /* If possible recycle the symtree that references the symbol.
4283          If a symtree is not found and the module does not import one,
4284          a unique-name symtree is found by read_cleanup.  */
4285       st = find_symtree_for_symbol (gfc_current_ns->sym_root, sym);
4286       if (st != NULL)
4287         {
4288           info->u.rsym.symtree = st;
4289           info->u.rsym.referenced = 1;
4290         }
4291     }
4292
4293   mio_rparen ();
4294
4295   /* Parse the symtree lists.  This lets us mark which symbols need to
4296      be loaded.  Renaming is also done at this point by replacing the
4297      symtree name.  */
4298
4299   mio_lparen ();
4300
4301   while (peek_atom () != ATOM_RPAREN)
4302     {
4303       mio_internal_string (name);
4304       mio_integer (&ambiguous);
4305       mio_integer (&symbol);
4306
4307       info = get_integer (symbol);
4308
4309       /* See how many use names there are.  If none, go through the start
4310          of the loop at least once.  */
4311       nuse = number_use_names (name, false);
4312       info->u.rsym.renamed = nuse ? 1 : 0;
4313
4314       if (nuse == 0)
4315         nuse = 1;
4316
4317       for (j = 1; j <= nuse; j++)
4318         {
4319           /* Get the jth local name for this symbol.  */
4320           p = find_use_name_n (name, &j, false);
4321
4322           if (p == NULL && strcmp (name, module_name) == 0)
4323             p = name;
4324
4325           /* Skip symtree nodes not in an ONLY clause, unless there
4326              is an existing symtree loaded from another USE statement.  */
4327           if (p == NULL)
4328             {
4329               st = gfc_find_symtree (gfc_current_ns->sym_root, name);
4330               if (st != NULL)
4331                 info->u.rsym.symtree = st;
4332               continue;
4333             }
4334
4335           /* If a symbol of the same name and module exists already,
4336              this symbol, which is not in an ONLY clause, must not be
4337              added to the namespace(11.3.2).  Note that find_symbol
4338              only returns the first occurrence that it finds.  */
4339           if (!only_flag && !info->u.rsym.renamed
4340                 && strcmp (name, module_name) != 0
4341                 && find_symbol (gfc_current_ns->sym_root, name,
4342                                 module_name, 0))
4343             continue;
4344
4345           st = gfc_find_symtree (gfc_current_ns->sym_root, p);
4346
4347           if (st != NULL)
4348             {
4349               /* Check for ambiguous symbols.  */
4350               if (check_for_ambiguous (st->n.sym, info))
4351                 st->ambiguous = 1;
4352               info->u.rsym.symtree = st;
4353             }
4354           else
4355             {
4356               st = gfc_find_symtree (gfc_current_ns->sym_root, name);
4357
4358               /* Delete the symtree if the symbol has been added by a USE
4359                  statement without an ONLY(11.3.2).  Remember that the rsym
4360                  will be the same as the symbol found in the symtree, for
4361                  this case.  */
4362               if (st && (only_flag || info->u.rsym.renamed)
4363                      && !st->n.sym->attr.use_only
4364                      && !st->n.sym->attr.use_rename
4365                      && info->u.rsym.sym == st->n.sym)
4366                 gfc_delete_symtree (&gfc_current_ns->sym_root, name);
4367
4368               /* Create a symtree node in the current namespace for this
4369                  symbol.  */
4370               st = check_unique_name (p)
4371                    ? gfc_get_unique_symtree (gfc_current_ns)
4372                    : gfc_new_symtree (&gfc_current_ns->sym_root, p);
4373               st->ambiguous = ambiguous;
4374
4375               sym = info->u.rsym.sym;
4376
4377               /* Create a symbol node if it doesn't already exist.  */
4378               if (sym == NULL)
4379                 {
4380                   info->u.rsym.sym = gfc_new_symbol (info->u.rsym.true_name,
4381                                                      gfc_current_ns);
4382                   sym = info->u.rsym.sym;
4383                   sym->module = gfc_get_string (info->u.rsym.module);
4384
4385                   /* TODO: hmm, can we test this?  Do we know it will be
4386                      initialized to zeros?  */
4387                   if (info->u.rsym.binding_label[0] != '\0')
4388                     strcpy (sym->binding_label, info->u.rsym.binding_label);
4389                 }
4390
4391               st->n.sym = sym;
4392               st->n.sym->refs++;
4393
4394               if (strcmp (name, p) != 0)
4395                 sym->attr.use_rename = 1;
4396
4397               /* We need to set the only_flag here so that symbols from the
4398                  same USE...ONLY but earlier are not deleted from the tree in
4399                  the gfc_delete_symtree above.  */
4400               sym->attr.use_only = only_flag;
4401
4402               /* Store the symtree pointing to this symbol.  */
4403               info->u.rsym.symtree = st;
4404
4405               if (info->u.rsym.state == UNUSED)
4406                 info->u.rsym.state = NEEDED;
4407               info->u.rsym.referenced = 1;
4408             }
4409         }
4410     }
4411
4412   mio_rparen ();
4413
4414   /* Load intrinsic operator interfaces.  */
4415   set_module_locus (&operator_interfaces);
4416   mio_lparen ();
4417
4418   for (i = GFC_INTRINSIC_BEGIN; i != GFC_INTRINSIC_END; i++)
4419     {
4420       if (i == INTRINSIC_USER)
4421         continue;
4422
4423       if (only_flag)
4424         {
4425           u = find_use_operator ((gfc_intrinsic_op) i);
4426
4427           if (u == NULL)
4428             {
4429               skip_list ();
4430               continue;
4431             }
4432
4433           u->found = 1;
4434         }
4435
4436       mio_interface (&gfc_current_ns->op[i]);
4437     }
4438
4439   mio_rparen ();
4440
4441   /* Load generic and user operator interfaces.  These must follow the
4442      loading of symtree because otherwise symbols can be marked as
4443      ambiguous.  */
4444
4445   set_module_locus (&user_operators);
4446
4447   load_operator_interfaces ();
4448   load_generic_interfaces ();
4449
4450   load_commons ();
4451   load_equiv ();
4452
4453   /* At this point, we read those symbols that are needed but haven't
4454      been loaded yet.  If one symbol requires another, the other gets
4455      marked as NEEDED if its previous state was UNUSED.  */
4456
4457   while (load_needed (pi_root));
4458
4459   /* Make sure all elements of the rename-list were found in the module.  */
4460
4461   for (u = gfc_rename_list; u; u = u->next)
4462     {
4463       if (u->found)
4464         continue;
4465
4466       if (u->op == INTRINSIC_NONE)
4467         {
4468           gfc_error ("Symbol '%s' referenced at %L not found in module '%s'",
4469                      u->use_name, &u->where, module_name);
4470           continue;
4471         }
4472
4473       if (u->op == INTRINSIC_USER)
4474         {
4475           gfc_error ("User operator '%s' referenced at %L not found "
4476                      "in module '%s'", u->use_name, &u->where, module_name);
4477           continue;
4478         }
4479
4480       gfc_error ("Intrinsic operator '%s' referenced at %L not found "
4481                  "in module '%s'", gfc_op2string (u->op), &u->where,
4482                  module_name);
4483     }
4484
4485   /* Now we should be in a position to fill f2k_derived with derived type
4486      extensions, since everything has been loaded.  */
4487   set_module_locus (&extensions);
4488   load_derived_extensions ();
4489
4490   /* Clean up symbol nodes that were never loaded, create references
4491      to hidden symbols.  */
4492
4493   read_cleanup (pi_root);
4494 }
4495
4496
4497 /* Given an access type that is specific to an entity and the default
4498    access, return nonzero if the entity is publicly accessible.  If the
4499    element is declared as PUBLIC, then it is public; if declared 
4500    PRIVATE, then private, and otherwise it is public unless the default
4501    access in this context has been declared PRIVATE.  */
4502
4503 bool
4504 gfc_check_access (gfc_access specific_access, gfc_access default_access)
4505 {
4506   if (specific_access == ACCESS_PUBLIC)
4507     return TRUE;
4508   if (specific_access == ACCESS_PRIVATE)
4509     return FALSE;
4510
4511   if (gfc_option.flag_module_private)
4512     return default_access == ACCESS_PUBLIC;
4513   else
4514     return default_access != ACCESS_PRIVATE;
4515 }
4516
4517
4518 /* A structure to remember which commons we've already written.  */
4519
4520 struct written_common
4521 {
4522   BBT_HEADER(written_common);
4523   const char *name, *label;
4524 };
4525
4526 static struct written_common *written_commons = NULL;
4527
4528 /* Comparison function used for balancing the binary tree.  */
4529
4530 static int
4531 compare_written_commons (void *a1, void *b1)
4532 {
4533   const char *aname = ((struct written_common *) a1)->name;
4534   const char *alabel = ((struct written_common *) a1)->label;
4535   const char *bname = ((struct written_common *) b1)->name;
4536   const char *blabel = ((struct written_common *) b1)->label;
4537   int c = strcmp (aname, bname);
4538
4539   return (c != 0 ? c : strcmp (alabel, blabel));
4540 }
4541
4542 /* Free a list of written commons.  */
4543
4544 static void
4545 free_written_common (struct written_common *w)
4546 {
4547   if (!w)
4548     return;
4549
4550   if (w->left)
4551     free_written_common (w->left);
4552   if (w->right)
4553     free_written_common (w->right);
4554
4555   gfc_free (w);
4556 }
4557
4558 /* Write a common block to the module -- recursive helper function.  */
4559
4560 static void
4561 write_common_0 (gfc_symtree *st, bool this_module)
4562 {
4563   gfc_common_head *p;
4564   const char * name;
4565   int flags;
4566   const char *label;
4567   struct written_common *w;
4568   bool write_me = true;
4569               
4570   if (st == NULL)
4571     return;
4572
4573   write_common_0 (st->left, this_module);
4574
4575   /* We will write out the binding label, or the name if no label given.  */
4576   name = st->n.common->name;
4577   p = st->n.common;
4578   label = p->is_bind_c ? p->binding_label : p->name;
4579
4580   /* Check if we've already output this common.  */
4581   w = written_commons;
4582   while (w)
4583     {
4584       int c = strcmp (name, w->name);
4585       c = (c != 0 ? c : strcmp (label, w->label));
4586       if (c == 0)
4587         write_me = false;
4588
4589       w = (c < 0) ? w->left : w->right;
4590     }
4591
4592   if (this_module && p->use_assoc)
4593     write_me = false;
4594
4595   if (write_me)
4596     {
4597       /* Write the common to the module.  */
4598       mio_lparen ();
4599       mio_pool_string (&name);
4600
4601       mio_symbol_ref (&p->head);
4602       flags = p->saved ? 1 : 0;
4603       if (p->threadprivate)
4604         flags |= 2;
4605       mio_integer (&flags);
4606
4607       /* Write out whether the common block is bind(c) or not.  */
4608       mio_integer (&(p->is_bind_c));
4609
4610       mio_pool_string (&label);
4611       mio_rparen ();
4612
4613       /* Record that we have written this common.  */
4614       w = XCNEW (struct written_common);
4615       w->name = p->name;
4616       w->label = label;
4617       gfc_insert_bbt (&written_commons, w, compare_written_commons);
4618     }
4619
4620   write_common_0 (st->right, this_module);
4621 }
4622
4623
4624 /* Write a common, by initializing the list of written commons, calling
4625    the recursive function write_common_0() and cleaning up afterwards.  */
4626
4627 static void
4628 write_common (gfc_symtree *st)
4629 {
4630   written_commons = NULL;
4631   write_common_0 (st, true);
4632   write_common_0 (st, false);
4633   free_written_common (written_commons);
4634   written_commons = NULL;
4635 }
4636
4637
4638 /* Write the blank common block to the module.  */
4639
4640 static void
4641 write_blank_common (void)
4642 {
4643   const char * name = BLANK_COMMON_NAME;
4644   int saved;
4645   /* TODO: Blank commons are not bind(c).  The F2003 standard probably says
4646      this, but it hasn't been checked.  Just making it so for now.  */  
4647   int is_bind_c = 0;  
4648
4649   if (gfc_current_ns->blank_common.head == NULL)
4650     return;
4651
4652   mio_lparen ();
4653
4654   mio_pool_string (&name);
4655
4656   mio_symbol_ref (&gfc_current_ns->blank_common.head);
4657   saved = gfc_current_ns->blank_common.saved;
4658   mio_integer (&saved);
4659
4660   /* Write out whether the common block is bind(c) or not.  */
4661   mio_integer (&is_bind_c);
4662
4663   /* Write out the binding label, which is BLANK_COMMON_NAME, though
4664      it doesn't matter because the label isn't used.  */
4665   mio_pool_string (&name);
4666
4667   mio_rparen ();
4668 }
4669
4670
4671 /* Write equivalences to the module.  */
4672
4673 static void
4674 write_equiv (void)
4675 {
4676   gfc_equiv *eq, *e;
4677   int num;
4678
4679   num = 0;
4680   for (eq = gfc_current_ns->equiv; eq; eq = eq->next)
4681     {
4682       mio_lparen ();
4683
4684       for (e = eq; e; e = e->eq)
4685         {
4686           if (e->module == NULL)
4687             e->module = gfc_get_string ("%s.eq.%d", module_name, num);
4688           mio_allocated_string (e->module);
4689           mio_expr (&e->expr);
4690         }
4691
4692       num++;
4693       mio_rparen ();
4694     }
4695 }
4696
4697
4698 /* Write derived type extensions to the module.  */
4699
4700 static void
4701 write_dt_extensions (gfc_symtree *st)
4702 {
4703   if (!gfc_check_access (st->n.sym->attr.access,
4704                          st->n.sym->ns->default_access))
4705     return;
4706
4707   mio_lparen ();
4708   mio_pool_string (&st->n.sym->name);
4709   if (st->n.sym->module != NULL)
4710     mio_pool_string (&st->n.sym->module);
4711   else
4712     mio_internal_string (module_name);
4713   mio_rparen ();
4714 }
4715
4716 static void
4717 write_derived_extensions (gfc_symtree *st)
4718 {
4719   if (!((st->n.sym->attr.flavor == FL_DERIVED)
4720           && (st->n.sym->f2k_derived != NULL)
4721           && (st->n.sym->f2k_derived->sym_root != NULL)))
4722     return;
4723
4724   mio_lparen ();
4725   mio_symbol_ref (&(st->n.sym));
4726   gfc_traverse_symtree (st->n.sym->f2k_derived->sym_root,
4727                         write_dt_extensions);
4728   mio_rparen ();
4729 }
4730
4731
4732 /* Write a symbol to the module.  */
4733
4734 static void
4735 write_symbol (int n, gfc_symbol *sym)
4736 {
4737   const char *label;
4738
4739   if (sym->attr.flavor == FL_UNKNOWN || sym->attr.flavor == FL_LABEL)
4740     gfc_internal_error ("write_symbol(): bad module symbol '%s'", sym->name);
4741
4742   mio_integer (&n);
4743   mio_pool_string (&sym->name);
4744
4745   mio_pool_string (&sym->module);
4746   if (sym->attr.is_bind_c || sym->attr.is_iso_c)
4747     {
4748       label = sym->binding_label;
4749       mio_pool_string (&label);
4750     }
4751   else
4752     mio_pool_string (&sym->name);
4753
4754   mio_pointer_ref (&sym->ns);
4755
4756   mio_symbol (sym);
4757   write_char ('\n');
4758 }
4759
4760
4761 /* Recursive traversal function to write the initial set of symbols to
4762    the module.  We check to see if the symbol should be written
4763    according to the access specification.  */
4764
4765 static void
4766 write_symbol0 (gfc_symtree *st)
4767 {
4768   gfc_symbol *sym;
4769   pointer_info *p;
4770   bool dont_write = false;
4771
4772   if (st == NULL)
4773     return;
4774
4775   write_symbol0 (st->left);
4776
4777   sym = st->n.sym;
4778   if (sym->module == NULL)
4779     sym->module = gfc_get_string (module_name);
4780
4781   if (sym->attr.flavor == FL_PROCEDURE && sym->attr.generic
4782       && !sym->attr.subroutine && !sym->attr.function)
4783     dont_write = true;
4784
4785   if (!gfc_check_access (sym->attr.access, sym->ns->default_access))
4786     dont_write = true;
4787
4788   if (!dont_write)
4789     {
4790       p = get_pointer (sym);
4791       if (p->type == P_UNKNOWN)
4792         p->type = P_SYMBOL;
4793
4794       if (p->u.wsym.state != WRITTEN)
4795         {
4796           write_symbol (p->integer, sym);
4797           p->u.wsym.state = WRITTEN;
4798         }
4799     }
4800
4801   write_symbol0 (st->right);
4802 }
4803
4804
4805 /* Recursive traversal function to write the secondary set of symbols
4806    to the module file.  These are symbols that were not public yet are
4807    needed by the public symbols or another dependent symbol.  The act
4808    of writing a symbol can modify the pointer_info tree, so we cease
4809    traversal if we find a symbol to write.  We return nonzero if a
4810    symbol was written and pass that information upwards.  */
4811
4812 static int
4813 write_symbol1 (pointer_info *p)
4814 {
4815   int result;
4816
4817   if (!p)
4818     return 0;
4819
4820   result = write_symbol1 (p->left);
4821
4822   if (!(p->type != P_SYMBOL || p->u.wsym.state != NEEDS_WRITE))
4823     {
4824       p->u.wsym.state = WRITTEN;
4825       write_symbol (p->integer, p->u.wsym.sym);
4826       result = 1;
4827     }
4828
4829   result |= write_symbol1 (p->right);
4830   return result;
4831 }
4832
4833
4834 /* Write operator interfaces associated with a symbol.  */
4835
4836 static void
4837 write_operator (gfc_user_op *uop)
4838 {
4839   static char nullstring[] = "";
4840   const char *p = nullstring;
4841
4842   if (uop->op == NULL
4843       || !gfc_check_access (uop->access, uop->ns->default_access))
4844     return;
4845
4846   mio_symbol_interface (&uop->name, &p, &uop->op);
4847 }
4848
4849
4850 /* Write generic interfaces from the namespace sym_root.  */
4851
4852 static void
4853 write_generic (gfc_symtree *st)
4854 {
4855   gfc_symbol *sym;
4856
4857   if (st == NULL)
4858     return;
4859
4860   write_generic (st->left);
4861   write_generic (st->right);
4862
4863   sym = st->n.sym;
4864   if (!sym || check_unique_name (st->name))
4865     return;
4866
4867   if (sym->generic == NULL
4868       || !gfc_check_access (sym->attr.access, sym->ns->default_access))
4869     return;
4870
4871   if (sym->module == NULL)
4872     sym->module = gfc_get_string (module_name);
4873
4874   mio_symbol_interface (&st->name, &sym->module, &sym->generic);
4875 }
4876
4877
4878 static void
4879 write_symtree (gfc_symtree *st)
4880 {
4881   gfc_symbol *sym;
4882   pointer_info *p;
4883
4884   sym = st->n.sym;
4885
4886   /* A symbol in an interface body must not be visible in the
4887      module file.  */
4888   if (sym->ns != gfc_current_ns
4889         && sym->ns->proc_name
4890         && sym->ns->proc_name->attr.if_source == IFSRC_IFBODY)
4891     return;
4892
4893   if (!gfc_check_access (sym->attr.access, sym->ns->default_access)
4894       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.generic
4895           && !sym->attr.subroutine && !sym->attr.function))
4896     return;
4897
4898   if (check_unique_name (st->name))
4899     return;
4900
4901   p = find_pointer (sym);
4902   if (p == NULL)
4903     gfc_internal_error ("write_symtree(): Symbol not written");
4904
4905   mio_pool_string (&st->name);
4906   mio_integer (&st->ambiguous);
4907   mio_integer (&p->integer);
4908 }
4909
4910
4911 static void
4912 write_module (void)
4913 {
4914   int i;
4915
4916   /* Write the operator interfaces.  */
4917   mio_lparen ();
4918
4919   for (i = GFC_INTRINSIC_BEGIN; i != GFC_INTRINSIC_END; i++)
4920     {
4921       if (i == INTRINSIC_USER)
4922         continue;
4923
4924       mio_interface (gfc_check_access (gfc_current_ns->operator_access[i],
4925                                        gfc_current_ns->default_access)
4926                      ? &gfc_current_ns->op[i] : NULL);
4927     }
4928
4929   mio_rparen ();
4930   write_char ('\n');
4931   write_char ('\n');
4932
4933   mio_lparen ();
4934   gfc_traverse_user_op (gfc_current_ns, write_operator);
4935   mio_rparen ();
4936   write_char ('\n');
4937   write_char ('\n');
4938
4939   mio_lparen ();
4940   write_generic (gfc_current_ns->sym_root);
4941   mio_rparen ();
4942   write_char ('\n');
4943   write_char ('\n');
4944
4945   mio_lparen ();
4946   write_blank_common ();
4947   write_common (gfc_current_ns->common_root);
4948   mio_rparen ();
4949   write_char ('\n');
4950   write_char ('\n');
4951
4952   mio_lparen ();
4953   write_equiv ();
4954   mio_rparen ();
4955   write_char ('\n');
4956   write_char ('\n');
4957
4958   mio_lparen ();
4959   gfc_traverse_symtree (gfc_current_ns->sym_root,
4960                         write_derived_extensions);
4961   mio_rparen ();
4962   write_char ('\n');
4963   write_char ('\n');
4964
4965   /* Write symbol information.  First we traverse all symbols in the
4966      primary namespace, writing those that need to be written.
4967      Sometimes writing one symbol will cause another to need to be
4968      written.  A list of these symbols ends up on the write stack, and
4969      we end by popping the bottom of the stack and writing the symbol
4970      until the stack is empty.  */
4971
4972   mio_lparen ();
4973
4974   write_symbol0 (gfc_current_ns->sym_root);
4975   while (write_symbol1 (pi_root))
4976     /* Nothing.  */;
4977
4978   mio_rparen ();
4979
4980   write_char ('\n');
4981   write_char ('\n');
4982
4983   mio_lparen ();
4984   gfc_traverse_symtree (gfc_current_ns->sym_root, write_symtree);
4985   mio_rparen ();
4986 }
4987
4988
4989 /* Read a MD5 sum from the header of a module file.  If the file cannot
4990    be opened, or we have any other error, we return -1.  */
4991
4992 static int
4993 read_md5_from_module_file (const char * filename, unsigned char md5[16])
4994 {
4995   FILE *file;
4996   char buf[1024];
4997   int n;
4998
4999   /* Open the file.  */
5000   if ((file = fopen (filename, "r")) == NULL)
5001     return -1;
5002
5003   /* Read the first line.  */
5004   if (fgets (buf, sizeof (buf) - 1, file) == NULL)
5005     {
5006       fclose (file);
5007       return -1;
5008     }
5009
5010   /* The file also needs to be overwritten if the version number changed.  */
5011   n = strlen ("GFORTRAN module version '" MOD_VERSION "' created");
5012   if (strncmp (buf, "GFORTRAN module version '" MOD_VERSION "' created", n) != 0)
5013     {
5014       fclose (file);
5015       return -1;
5016     }
5017  
5018   /* Read a second line.  */
5019   if (fgets (buf, sizeof (buf) - 1, file) == NULL)
5020     {
5021       fclose (file);
5022       return -1;
5023     }
5024
5025   /* Close the file.  */
5026   fclose (file);
5027
5028   /* If the header is not what we expect, or is too short, bail out.  */
5029   if (strncmp (buf, "MD5:", 4) != 0 || strlen (buf) < 4 + 16)
5030     return -1;
5031
5032   /* Now, we have a real MD5, read it into the array.  */
5033   for (n = 0; n < 16; n++)
5034     {
5035       unsigned int x;
5036
5037       if (sscanf (&(buf[4+2*n]), "%02x", &x) != 1)
5038        return -1;
5039
5040       md5[n] = x;
5041     }
5042
5043   return 0;
5044 }
5045
5046
5047 /* Given module, dump it to disk.  If there was an error while
5048    processing the module, dump_flag will be set to zero and we delete
5049    the module file, even if it was already there.  */
5050
5051 void
5052 gfc_dump_module (const char *name, int dump_flag)
5053 {
5054   int n;
5055   char *filename, *filename_tmp, *p;
5056   time_t now;
5057   fpos_t md5_pos;
5058   unsigned char md5_new[16], md5_old[16];
5059
5060   n = strlen (name) + strlen (MODULE_EXTENSION) + 1;
5061   if (gfc_option.module_dir != NULL)
5062     {
5063       n += strlen (gfc_option.module_dir);
5064       filename = (char *) alloca (n);
5065       strcpy (filename, gfc_option.module_dir);
5066       strcat (filename, name);
5067     }
5068   else
5069     {
5070       filename = (char *) alloca (n);
5071       strcpy (filename, name);
5072     }
5073   strcat (filename, MODULE_EXTENSION);
5074
5075   /* Name of the temporary file used to write the module.  */
5076   filename_tmp = (char *) alloca (n + 1);
5077   strcpy (filename_tmp, filename);
5078   strcat (filename_tmp, "0");
5079
5080   /* There was an error while processing the module.  We delete the
5081      module file, even if it was already there.  */
5082   if (!dump_flag)
5083     {
5084       unlink (filename);
5085       return;
5086     }
5087
5088   /* Write the module to the temporary file.  */
5089   module_fp = fopen (filename_tmp, "w");
5090   if (module_fp == NULL)
5091     gfc_fatal_error ("Can't open module file '%s' for writing at %C: %s",
5092                      filename_tmp, strerror (errno));
5093
5094   /* Write the header, including space reserved for the MD5 sum.  */
5095   now = time (NULL);
5096   p = ctime (&now);
5097
5098   *strchr (p, '\n') = '\0';
5099
5100   fprintf (module_fp, "GFORTRAN module version '%s' created from %s on %s\n"
5101            "MD5:", MOD_VERSION, gfc_source_file, p);
5102   fgetpos (module_fp, &md5_pos);
5103   fputs ("00000000000000000000000000000000 -- "
5104         "If you edit this, you'll get what you deserve.\n\n", module_fp);
5105
5106   /* Initialize the MD5 context that will be used for output.  */
5107   md5_init_ctx (&ctx);
5108
5109   /* Write the module itself.  */
5110   iomode = IO_OUTPUT;
5111   strcpy (module_name, name);
5112
5113   init_pi_tree ();
5114
5115   write_module ();
5116
5117   free_pi_tree (pi_root);
5118   pi_root = NULL;
5119
5120   write_char ('\n');
5121
5122   /* Write the MD5 sum to the header of the module file.  */
5123   md5_finish_ctx (&ctx, md5_new);
5124   fsetpos (module_fp, &md5_pos);
5125   for (n = 0; n < 16; n++)
5126     fprintf (module_fp, "%02x", md5_new[n]);
5127
5128   if (fclose (module_fp))
5129     gfc_fatal_error ("Error writing module file '%s' for writing: %s",
5130                      filename_tmp, strerror (errno));
5131
5132   /* Read the MD5 from the header of the old module file and compare.  */
5133   if (read_md5_from_module_file (filename, md5_old) != 0
5134       || memcmp (md5_old, md5_new, sizeof (md5_old)) != 0)
5135     {
5136       /* Module file have changed, replace the old one.  */
5137       if (unlink (filename) && errno != ENOENT)
5138         gfc_fatal_error ("Can't delete module file '%s': %s", filename,
5139                          strerror (errno));
5140       if (rename (filename_tmp, filename))
5141         gfc_fatal_error ("Can't rename module file '%s' to '%s': %s",
5142                          filename_tmp, filename, strerror (errno));
5143     }
5144   else
5145     {
5146       if (unlink (filename_tmp))
5147         gfc_fatal_error ("Can't delete temporary module file '%s': %s",
5148                          filename_tmp, strerror (errno));
5149     }
5150 }
5151
5152
5153 static void
5154 sort_iso_c_rename_list (void)
5155 {
5156   gfc_use_rename *tmp_list = NULL;
5157   gfc_use_rename *curr;
5158   gfc_use_rename *kinds_used[ISOCBINDING_NUMBER] = {NULL};
5159   int c_kind;
5160   int i;
5161
5162   for (curr = gfc_rename_list; curr; curr = curr->next)
5163     {
5164       c_kind = get_c_kind (curr->use_name, c_interop_kinds_table);
5165       if (c_kind == ISOCBINDING_INVALID || c_kind == ISOCBINDING_LAST)
5166         {
5167           gfc_error ("Symbol '%s' referenced at %L does not exist in "
5168                      "intrinsic module ISO_C_BINDING.", curr->use_name,
5169                      &curr->where);
5170         }
5171       else
5172         /* Put it in the list.  */
5173         kinds_used[c_kind] = curr;
5174     }
5175
5176   /* Make a new (sorted) rename list.  */
5177   i = 0;
5178   while (i < ISOCBINDING_NUMBER && kinds_used[i] == NULL)
5179     i++;
5180
5181   if (i < ISOCBINDING_NUMBER)
5182     {
5183       tmp_list = kinds_used[i];
5184
5185       i++;
5186       curr = tmp_list;
5187       for (; i < ISOCBINDING_NUMBER; i++)
5188         if (kinds_used[i] != NULL)
5189           {
5190             curr->next = kinds_used[i];
5191             curr = curr->next;
5192             curr->next = NULL;
5193           }
5194     }
5195
5196   gfc_rename_list = tmp_list;
5197 }
5198
5199
5200 /* Import the intrinsic ISO_C_BINDING module, generating symbols in
5201    the current namespace for all named constants, pointer types, and
5202    procedures in the module unless the only clause was used or a rename
5203    list was provided.  */
5204
5205 static void
5206 import_iso_c_binding_module (void)
5207 {
5208   gfc_symbol *mod_sym = NULL;
5209   gfc_symtree *mod_symtree = NULL;
5210   const char *iso_c_module_name = "__iso_c_binding";
5211   gfc_use_rename *u;
5212   int i;
5213   char *local_name;
5214
5215   /* Look only in the current namespace.  */
5216   mod_symtree = gfc_find_symtree (gfc_current_ns->sym_root, iso_c_module_name);
5217
5218   if (mod_symtree == NULL)
5219     {
5220       /* symtree doesn't already exist in current namespace.  */
5221       gfc_get_sym_tree (iso_c_module_name, gfc_current_ns, &mod_symtree,
5222                         false);
5223       
5224       if (mod_symtree != NULL)
5225         mod_sym = mod_symtree->n.sym;
5226       else
5227         gfc_internal_error ("import_iso_c_binding_module(): Unable to "
5228                             "create symbol for %s", iso_c_module_name);
5229
5230       mod_sym->attr.flavor = FL_MODULE;
5231       mod_sym->attr.intrinsic = 1;
5232       mod_sym->module = gfc_get_string (iso_c_module_name);
5233       mod_sym->from_intmod = INTMOD_ISO_C_BINDING;
5234     }
5235
5236   /* Generate the symbols for the named constants representing
5237      the kinds for intrinsic data types.  */
5238   if (only_flag)
5239     {
5240       /* Sort the rename list because there are dependencies between types
5241          and procedures (e.g., c_loc needs c_ptr).  */
5242       sort_iso_c_rename_list ();
5243       
5244       for (u = gfc_rename_list; u; u = u->next)
5245         {
5246           i = get_c_kind (u->use_name, c_interop_kinds_table);
5247
5248           if (i == ISOCBINDING_INVALID || i == ISOCBINDING_LAST)
5249             {
5250               gfc_error ("Symbol '%s' referenced at %L does not exist in "
5251                          "intrinsic module ISO_C_BINDING.", u->use_name,
5252                          &u->where);
5253               continue;
5254             }
5255           
5256           generate_isocbinding_symbol (iso_c_module_name,
5257                                        (iso_c_binding_symbol) i,
5258                                        u->local_name);
5259         }
5260     }
5261   else
5262     {
5263       for (i = 0; i < ISOCBINDING_NUMBER; i++)
5264         {
5265           local_name = NULL;
5266           for (u = gfc_rename_list; u; u = u->next)
5267             {
5268               if (strcmp (c_interop_kinds_table[i].name, u->use_name) == 0)
5269                 {
5270                   local_name = u->local_name;
5271                   u->found = 1;
5272                   break;
5273                 }
5274             }
5275           generate_isocbinding_symbol (iso_c_module_name,
5276                                        (iso_c_binding_symbol) i,
5277                                        local_name);
5278         }
5279
5280       for (u = gfc_rename_list; u; u = u->next)
5281         {
5282           if (u->found)
5283             continue;
5284
5285           gfc_error ("Symbol '%s' referenced at %L not found in intrinsic "
5286                      "module ISO_C_BINDING", u->use_name, &u->where);
5287         }
5288     }
5289 }
5290
5291
5292 /* Add an integer named constant from a given module.  */
5293
5294 static void
5295 create_int_parameter (const char *name, int value, const char *modname,
5296                       intmod_id module, int id)
5297 {
5298   gfc_symtree *tmp_symtree;
5299   gfc_symbol *sym;
5300
5301   tmp_symtree = gfc_find_symtree (gfc_current_ns->sym_root, name);
5302   if (tmp_symtree != NULL)
5303     {
5304       if (strcmp (modname, tmp_symtree->n.sym->module) == 0)
5305         return;
5306       else
5307         gfc_error ("Symbol '%s' already declared", name);
5308     }
5309
5310   gfc_get_sym_tree (name, gfc_current_ns, &tmp_symtree, false);
5311   sym = tmp_symtree->n.sym;
5312
5313   sym->module = gfc_get_string (modname);
5314   sym->attr.flavor = FL_PARAMETER;
5315   sym->ts.type = BT_INTEGER;
5316   sym->ts.kind = gfc_default_integer_kind;
5317   sym->value = gfc_int_expr (value);
5318   sym->attr.use_assoc = 1;
5319   sym->from_intmod = module;
5320   sym->intmod_sym_id = id;
5321 }
5322
5323
5324 /* USE the ISO_FORTRAN_ENV intrinsic module.  */
5325
5326 static void
5327 use_iso_fortran_env_module (void)
5328 {
5329   static char mod[] = "iso_fortran_env";
5330   const char *local_name;
5331   gfc_use_rename *u;
5332   gfc_symbol *mod_sym;
5333   gfc_symtree *mod_symtree;
5334   int i;
5335
5336   intmod_sym symbol[] = {
5337 #define NAMED_INTCST(a,b,c,d) { a, b, 0, d },
5338 #include "iso-fortran-env.def"
5339 #undef NAMED_INTCST
5340     { ISOFORTRANENV_INVALID, NULL, -1234, 0 } };
5341
5342   i = 0;
5343 #define NAMED_INTCST(a,b,c,d) symbol[i++].value = c;
5344 #include "iso-fortran-env.def"
5345 #undef NAMED_INTCST
5346
5347   /* Generate the symbol for the module itself.  */
5348   mod_symtree = gfc_find_symtree (gfc_current_ns->sym_root, mod);
5349   if (mod_symtree == NULL)
5350     {
5351       gfc_get_sym_tree (mod, gfc_current_ns, &mod_symtree, false);
5352       gcc_assert (mod_symtree);
5353       mod_sym = mod_symtree->n.sym;
5354
5355       mod_sym->attr.flavor = FL_MODULE;
5356       mod_sym->attr.intrinsic = 1;
5357       mod_sym->module = gfc_get_string (mod);
5358       mod_sym->from_intmod = INTMOD_ISO_FORTRAN_ENV;
5359     }
5360   else
5361     if (!mod_symtree->n.sym->attr.intrinsic)
5362       gfc_error ("Use of intrinsic module '%s' at %C conflicts with "
5363                  "non-intrinsic module name used previously", mod);
5364
5365   /* Generate the symbols for the module integer named constants.  */
5366   if (only_flag)
5367     for (u = gfc_rename_list; u; u = u->next)
5368       {
5369         for (i = 0; symbol[i].name; i++)
5370           if (strcmp (symbol[i].name, u->use_name) == 0)
5371             break;
5372
5373         if (symbol[i].name == NULL)
5374           {
5375             gfc_error ("Symbol '%s' referenced at %L does not exist in "
5376                        "intrinsic module ISO_FORTRAN_ENV", u->use_name,
5377                        &u->where);
5378             continue;
5379           }
5380
5381         if ((gfc_option.flag_default_integer || gfc_option.flag_default_real)
5382             && symbol[i].id == ISOFORTRANENV_NUMERIC_STORAGE_SIZE)
5383           gfc_warning_now ("Use of the NUMERIC_STORAGE_SIZE named constant "
5384                            "from intrinsic module ISO_FORTRAN_ENV at %L is "
5385                            "incompatible with option %s", &u->where,
5386                            gfc_option.flag_default_integer
5387                              ? "-fdefault-integer-8" : "-fdefault-real-8");
5388
5389         create_int_parameter (u->local_name[0] ? u->local_name
5390                                                : symbol[i].name,
5391                               symbol[i].value, mod, INTMOD_ISO_FORTRAN_ENV,
5392                               symbol[i].id);
5393       }
5394   else
5395     {
5396       for (i = 0; symbol[i].name; i++)
5397         {
5398           local_name = NULL;
5399           for (u = gfc_rename_list; u; u = u->next)
5400             {
5401               if (strcmp (symbol[i].name, u->use_name) == 0)
5402                 {
5403                   local_name = u->local_name;
5404                   u->found = 1;
5405                   break;
5406                 }
5407             }
5408
5409           if ((gfc_option.flag_default_integer || gfc_option.flag_default_real)
5410               && symbol[i].id == ISOFORTRANENV_NUMERIC_STORAGE_SIZE)
5411             gfc_warning_now ("Use of the NUMERIC_STORAGE_SIZE named constant "
5412                              "from intrinsic module ISO_FORTRAN_ENV at %C is "
5413                              "incompatible with option %s",
5414                              gfc_option.flag_default_integer
5415                                 ? "-fdefault-integer-8" : "-fdefault-real-8");
5416
5417           create_int_parameter (local_name ? local_name : symbol[i].name,
5418                                 symbol[i].value, mod, INTMOD_ISO_FORTRAN_ENV,
5419                                 symbol[i].id);
5420         }
5421
5422       for (u = gfc_rename_list; u; u = u->next)
5423         {
5424           if (u->found)
5425             continue;
5426
5427           gfc_error ("Symbol '%s' referenced at %L not found in intrinsic "
5428                      "module ISO_FORTRAN_ENV", u->use_name, &u->where);
5429         }
5430     }
5431 }
5432
5433
5434 /* Process a USE directive.  */
5435
5436 void
5437 gfc_use_module (void)
5438 {
5439   char *filename;
5440   gfc_state_data *p;
5441   int c, line, start;
5442   gfc_symtree *mod_symtree;
5443   gfc_use_list *use_stmt;
5444
5445   filename = (char *) alloca (strlen (module_name) + strlen (MODULE_EXTENSION)
5446                               + 1);
5447   strcpy (filename, module_name);
5448   strcat (filename, MODULE_EXTENSION);
5449
5450   /* First, try to find an non-intrinsic module, unless the USE statement
5451      specified that the module is intrinsic.  */
5452   module_fp = NULL;
5453   if (!specified_int)
5454     module_fp = gfc_open_included_file (filename, true, true);
5455
5456   /* Then, see if it's an intrinsic one, unless the USE statement
5457      specified that the module is non-intrinsic.  */
5458   if (module_fp == NULL && !specified_nonint)
5459     {
5460       if (strcmp (module_name, "iso_fortran_env") == 0
5461           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: ISO_FORTRAN_ENV "
5462                              "intrinsic module at %C") != FAILURE)
5463        {
5464          use_iso_fortran_env_module ();
5465          return;
5466        }
5467
5468       if (strcmp (module_name, "iso_c_binding") == 0
5469           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: "
5470                              "ISO_C_BINDING module at %C") != FAILURE)
5471         {
5472           import_iso_c_binding_module();
5473           return;
5474         }
5475
5476       module_fp = gfc_open_intrinsic_module (filename);
5477
5478       if (module_fp == NULL && specified_int)
5479         gfc_fatal_error ("Can't find an intrinsic module named '%s' at %C",
5480                          module_name);
5481     }
5482
5483   if (module_fp == NULL)
5484     gfc_fatal_error ("Can't open module file '%s' for reading at %C: %s",
5485                      filename, strerror (errno));
5486
5487   /* Check that we haven't already USEd an intrinsic module with the
5488      same name.  */
5489
5490   mod_symtree = gfc_find_symtree (gfc_current_ns->sym_root, module_name);
5491   if (mod_symtree && mod_symtree->n.sym->attr.intrinsic)
5492     gfc_error ("Use of non-intrinsic module '%s' at %C conflicts with "
5493                "intrinsic module name used previously", module_name);
5494
5495   iomode = IO_INPUT;
5496   module_line = 1;
5497   module_column = 1;
5498   start = 0;
5499
5500   /* Skip the first two lines of the module, after checking that this is
5501      a gfortran module file.  */
5502   line = 0;
5503   while (line < 2)
5504     {
5505       c = module_char ();
5506       if (c == EOF)
5507         bad_module ("Unexpected end of module");
5508       if (start++ < 3)
5509         parse_name (c);
5510       if ((start == 1 && strcmp (atom_name, "GFORTRAN") != 0)
5511           || (start == 2 && strcmp (atom_name, " module") != 0))
5512         gfc_fatal_error ("File '%s' opened at %C is not a GFORTRAN module "
5513                          "file", filename);
5514       if (start == 3)
5515         {
5516           if (strcmp (atom_name, " version") != 0
5517               || module_char () != ' '
5518               || parse_atom () != ATOM_STRING)
5519             gfc_fatal_error ("Parse error when checking module version"
5520                              " for file '%s' opened at %C", filename);
5521
5522           if (strcmp (atom_string, MOD_VERSION))
5523             {
5524               gfc_fatal_error ("Wrong module version '%s' (expected '%s') "
5525                                "for file '%s' opened at %C", atom_string,
5526                                MOD_VERSION, filename);
5527             }
5528         }
5529
5530       if (c == '\n')
5531         line++;
5532     }
5533
5534   /* Make sure we're not reading the same module that we may be building.  */
5535   for (p = gfc_state_stack; p; p = p->previous)
5536     if (p->state == COMP_MODULE && strcmp (p->sym->name, module_name) == 0)
5537       gfc_fatal_error ("Can't USE the same module we're building!");
5538
5539   init_pi_tree ();
5540   init_true_name_tree ();
5541
5542   read_module ();
5543
5544   free_true_name (true_name_root);
5545   true_name_root = NULL;
5546
5547   free_pi_tree (pi_root);
5548   pi_root = NULL;
5549
5550   fclose (module_fp);
5551
5552   use_stmt = gfc_get_use_list ();
5553   use_stmt->module_name = gfc_get_string (module_name);
5554   use_stmt->only_flag = only_flag;
5555   use_stmt->rename = gfc_rename_list;
5556   use_stmt->where = use_locus;
5557   gfc_rename_list = NULL;
5558   use_stmt->next = gfc_current_ns->use_stmts;
5559   gfc_current_ns->use_stmts = use_stmt;
5560 }
5561
5562
5563 void
5564 gfc_free_use_stmts (gfc_use_list *use_stmts)
5565 {
5566   gfc_use_list *next;
5567   for (; use_stmts; use_stmts = next)
5568     {
5569       gfc_use_rename *next_rename;
5570
5571       for (; use_stmts->rename; use_stmts->rename = next_rename)
5572         {
5573           next_rename = use_stmts->rename->next;
5574           gfc_free (use_stmts->rename);
5575         }
5576       next = use_stmts->next;
5577       gfc_free (use_stmts);
5578     }
5579 }
5580
5581
5582 void
5583 gfc_module_init_2 (void)
5584 {
5585   last_atom = ATOM_LPAREN;
5586 }
5587
5588
5589 void
5590 gfc_module_done_2 (void)
5591 {
5592   free_rename ();
5593 }