OSDN Git Service

* gfortran.h (gfc_expr.function.name): Make const.
[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 Free Software Foundation, 
4    Inc.
5    Contributed by Andy Vaught
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 2, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to the Free
21 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
22 02111-1307, USA.  */
23
24 /* The syntax of gfortran modules resembles that of lisp lists, ie 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    ( <Symbol Number (in no particular order)>
51      <True name of symbol>
52      <Module name of symbol>
53      ( <symbol information> )
54      ...
55    )
56    ( <Symtree name>
57      <Ambiguous flag>
58      <Symbol number>
59      ...
60    )
61
62    In general, symbols refer to other symbols by their symbol number,
63    which are zero based.  Symbols are written to the module in no
64    particular order.  */
65
66 #include "config.h"
67 #include <string.h>
68 #include <stdio.h>
69 #include <errno.h>
70 #include <unistd.h>
71 #include <time.h>
72
73 #include "gfortran.h"
74 #include "arith.h"
75 #include "match.h"
76 #include "parse.h" /* FIXME */
77
78 #define MODULE_EXTENSION ".mod"
79
80
81 /* Structure that describes a position within a module file.  */
82
83 typedef struct
84 {
85   int column, line;
86   fpos_t pos;
87 }
88 module_locus;
89
90
91 typedef enum
92 {
93   P_UNKNOWN = 0, P_OTHER, P_NAMESPACE, P_COMPONENT, P_SYMBOL
94 }
95 pointer_t;
96
97 /* The fixup structure lists pointers to pointers that have to
98    be updated when a pointer value becomes known.  */
99
100 typedef struct fixup_t
101 {
102   void **pointer;
103   struct fixup_t *next;
104 }
105 fixup_t;
106
107
108 /* Structure for holding extra info needed for pointers being read.  */
109
110 typedef struct pointer_info
111 {
112   BBT_HEADER (pointer_info);
113   int integer;
114   pointer_t type;
115
116   /* The first component of each member of the union is the pointer
117      being stored.  */
118
119   fixup_t *fixup;
120
121   union
122   {
123     void *pointer;      /* Member for doing pointer searches.  */
124
125     struct
126     {
127       gfc_symbol *sym;
128       char true_name[GFC_MAX_SYMBOL_LEN + 1], module[GFC_MAX_SYMBOL_LEN + 1];
129       enum
130       { UNUSED, NEEDED, USED }
131       state;
132       int ns, referenced;
133       module_locus where;
134       fixup_t *stfixup;
135       gfc_symtree *symtree;
136     }
137     rsym;
138
139     struct
140     {
141       gfc_symbol *sym;
142       enum
143       { UNREFERENCED = 0, NEEDS_WRITE, WRITTEN }
144       state;
145     }
146     wsym;
147   }
148   u;
149
150 }
151 pointer_info;
152
153 #define gfc_get_pointer_info() gfc_getmem(sizeof(pointer_info))
154
155
156 /* Lists of rename info for the USE statement.  */
157
158 typedef struct gfc_use_rename
159 {
160   char local_name[GFC_MAX_SYMBOL_LEN + 1], use_name[GFC_MAX_SYMBOL_LEN + 1];
161   struct gfc_use_rename *next;
162   int found;
163   gfc_intrinsic_op operator;
164   locus where;
165 }
166 gfc_use_rename;
167
168 #define gfc_get_use_rename() gfc_getmem(sizeof(gfc_use_rename))
169
170 /* Local variables */
171
172 /* The FILE for the module we're reading or writing.  */
173 static FILE *module_fp;
174
175 /* The name of the module we're reading (USE'ing) or writing.  */
176 static char module_name[GFC_MAX_SYMBOL_LEN + 1];
177
178 static int module_line, module_column, only_flag;
179 static enum
180 { IO_INPUT, IO_OUTPUT }
181 iomode;
182
183 static gfc_use_rename *gfc_rename_list;
184 static pointer_info *pi_root;
185 static int symbol_number;       /* Counter for assigning symbol numbers */
186
187
188
189 /*****************************************************************/
190
191 /* Pointer/integer conversion.  Pointers between structures are stored
192    as integers in the module file.  The next couple of subroutines
193    handle this translation for reading and writing.  */
194
195 /* Recursively free the tree of pointer structures.  */
196
197 static void
198 free_pi_tree (pointer_info * p)
199 {
200   if (p == NULL)
201     return;
202
203   if (p->fixup != NULL)
204     gfc_internal_error ("free_pi_tree(): Unresolved fixup");
205
206   free_pi_tree (p->left);
207   free_pi_tree (p->right);
208
209   gfc_free (p);
210 }
211
212
213 /* Compare pointers when searching by pointer.  Used when writing a
214    module.  */
215
216 static int
217 compare_pointers (void * _sn1, void * _sn2)
218 {
219   pointer_info *sn1, *sn2;
220
221   sn1 = (pointer_info *) _sn1;
222   sn2 = (pointer_info *) _sn2;
223
224   if (sn1->u.pointer < sn2->u.pointer)
225     return -1;
226   if (sn1->u.pointer > sn2->u.pointer)
227     return 1;
228
229   return 0;
230 }
231
232
233 /* Compare integers when searching by integer.  Used when reading a
234    module.  */
235
236 static int
237 compare_integers (void * _sn1, void * _sn2)
238 {
239   pointer_info *sn1, *sn2;
240
241   sn1 = (pointer_info *) _sn1;
242   sn2 = (pointer_info *) _sn2;
243
244   if (sn1->integer < sn2->integer)
245     return -1;
246   if (sn1->integer > sn2->integer)
247     return 1;
248
249   return 0;
250 }
251
252
253 /* Initialize the pointer_info tree.  */
254
255 static void
256 init_pi_tree (void)
257 {
258   compare_fn compare;
259   pointer_info *p;
260
261   pi_root = NULL;
262   compare = (iomode == IO_INPUT) ? compare_integers : compare_pointers;
263
264   /* Pointer 0 is the NULL pointer.  */
265   p = gfc_get_pointer_info ();
266   p->u.pointer = NULL;
267   p->integer = 0;
268   p->type = P_OTHER;
269
270   gfc_insert_bbt (&pi_root, p, compare);
271
272   /* Pointer 1 is the current namespace.  */
273   p = gfc_get_pointer_info ();
274   p->u.pointer = gfc_current_ns;
275   p->integer = 1;
276   p->type = P_NAMESPACE;
277
278   gfc_insert_bbt (&pi_root, p, compare);
279
280   symbol_number = 2;
281 }
282
283
284 /* During module writing, call here with a pointer to something,
285    returning the pointer_info node.  */
286
287 static pointer_info *
288 find_pointer (void *gp)
289 {
290   pointer_info *p;
291
292   p = pi_root;
293   while (p != NULL)
294     {
295       if (p->u.pointer == gp)
296         break;
297       p = (gp < p->u.pointer) ? p->left : p->right;
298     }
299
300   return p;
301 }
302
303
304 /* Given a pointer while writing, returns the pointer_info tree node,
305    creating it if it doesn't exist.  */
306
307 static pointer_info *
308 get_pointer (void *gp)
309 {
310   pointer_info *p;
311
312   p = find_pointer (gp);
313   if (p != NULL)
314     return p;
315
316   /* Pointer doesn't have an integer.  Give it one.  */
317   p = gfc_get_pointer_info ();
318
319   p->u.pointer = gp;
320   p->integer = symbol_number++;
321
322   gfc_insert_bbt (&pi_root, p, compare_pointers);
323
324   return p;
325 }
326
327
328 /* Given an integer during reading, find it in the pointer_info tree,
329    creating the node if not found.  */
330
331 static pointer_info *
332 get_integer (int integer)
333 {
334   pointer_info *p, t;
335   int c;
336
337   t.integer = integer;
338
339   p = pi_root;
340   while (p != NULL)
341     {
342       c = compare_integers (&t, p);
343       if (c == 0)
344         break;
345
346       p = (c < 0) ? p->left : p->right;
347     }
348
349   if (p != NULL)
350     return p;
351
352   p = gfc_get_pointer_info ();
353   p->integer = integer;
354   p->u.pointer = NULL;
355
356   gfc_insert_bbt (&pi_root, p, compare_integers);
357
358   return p;
359 }
360
361
362 /* Recursive function to find a pointer within a tree by brute force.  */
363
364 static pointer_info *
365 fp2 (pointer_info * p, const void *target)
366 {
367   pointer_info *q;
368
369   if (p == NULL)
370     return NULL;
371
372   if (p->u.pointer == target)
373     return p;
374
375   q = fp2 (p->left, target);
376   if (q != NULL)
377     return q;
378
379   return fp2 (p->right, target);
380 }
381
382
383 /* During reading, find a pointer_info node from the pointer value.
384    This amounts to a brute-force search.  */
385
386 static pointer_info *
387 find_pointer2 (void *p)
388 {
389
390   return fp2 (pi_root, p);
391 }
392
393
394 /* Resolve any fixups using a known pointer.  */
395 static void
396 resolve_fixups (fixup_t *f, void * gp)
397 {
398   fixup_t *next;
399
400   for (; f; f = next)
401     {
402       next = f->next;
403       *(f->pointer) = gp;
404       gfc_free (f);
405     }
406 }
407
408 /* Call here during module reading when we know what pointer to
409    associate with an integer.  Any fixups that exist are resolved at
410    this time.  */
411
412 static void
413 associate_integer_pointer (pointer_info * p, void *gp)
414 {
415   if (p->u.pointer != NULL)
416     gfc_internal_error ("associate_integer_pointer(): Already associated");
417
418   p->u.pointer = gp;
419
420   resolve_fixups (p->fixup, gp);
421
422   p->fixup = NULL;
423 }
424
425
426 /* During module reading, given an integer and a pointer to a pointer,
427    either store the pointer from an already-known value or create a
428    fixup structure in order to store things later.  Returns zero if
429    the reference has been actually stored, or nonzero if the reference
430    must be fixed later (ie associate_integer_pointer must be called
431    sometime later.  Returns the pointer_info structure.  */
432
433 static pointer_info *
434 add_fixup (int integer, void *gp)
435 {
436   pointer_info *p;
437   fixup_t *f;
438   char **cp;
439
440   p = get_integer (integer);
441
442   if (p->integer == 0 || p->u.pointer != NULL)
443     {
444       cp = gp;
445       *cp = p->u.pointer;
446     }
447   else
448     {
449       f = gfc_getmem (sizeof (fixup_t));
450
451       f->next = p->fixup;
452       p->fixup = f;
453
454       f->pointer = gp;
455     }
456
457   return p;
458 }
459
460
461 /*****************************************************************/
462
463 /* Parser related subroutines */
464
465 /* Free the rename list left behind by a USE statement.  */
466
467 static void
468 free_rename (void)
469 {
470   gfc_use_rename *next;
471
472   for (; gfc_rename_list; gfc_rename_list = next)
473     {
474       next = gfc_rename_list->next;
475       gfc_free (gfc_rename_list);
476     }
477 }
478
479
480 /* Match a USE statement.  */
481
482 match
483 gfc_match_use (void)
484 {
485   char name[GFC_MAX_SYMBOL_LEN + 1];
486   gfc_use_rename *tail = NULL, *new;
487   interface_type type;
488   gfc_intrinsic_op operator;
489   match m;
490
491   m = gfc_match_name (module_name);
492   if (m != MATCH_YES)
493     return m;
494
495   free_rename ();
496   only_flag = 0;
497
498   if (gfc_match_eos () == MATCH_YES)
499     return MATCH_YES;
500   if (gfc_match_char (',') != MATCH_YES)
501     goto syntax;
502
503   if (gfc_match (" only :") == MATCH_YES)
504     only_flag = 1;
505
506   if (gfc_match_eos () == MATCH_YES)
507     return MATCH_YES;
508
509   for (;;)
510     {
511       /* Get a new rename struct and add it to the rename list.  */
512       new = gfc_get_use_rename ();
513       new->where = gfc_current_locus;
514       new->found = 0;
515
516       if (gfc_rename_list == NULL)
517         gfc_rename_list = new;
518       else
519         tail->next = new;
520       tail = new;
521
522       /* See what kind of interface we're dealing with.  Assume it is
523          not an operator.  */
524       new->operator = INTRINSIC_NONE;
525       if (gfc_match_generic_spec (&type, name, &operator) == MATCH_ERROR)
526         goto cleanup;
527
528       switch (type)
529         {
530         case INTERFACE_NAMELESS:
531           gfc_error ("Missing generic specification in USE statement at %C");
532           goto cleanup;
533
534         case INTERFACE_GENERIC:
535           m = gfc_match (" =>");
536
537           if (only_flag)
538             {
539               if (m != MATCH_YES)
540                 strcpy (new->use_name, name);
541               else
542                 {
543                   strcpy (new->local_name, name);
544
545                   m = gfc_match_name (new->use_name);
546                   if (m == MATCH_NO)
547                     goto syntax;
548                   if (m == MATCH_ERROR)
549                     goto cleanup;
550                 }
551             }
552           else
553             {
554               if (m != MATCH_YES)
555                 goto syntax;
556               strcpy (new->local_name, name);
557
558               m = gfc_match_name (new->use_name);
559               if (m == MATCH_NO)
560                 goto syntax;
561               if (m == MATCH_ERROR)
562                 goto cleanup;
563             }
564
565           break;
566
567         case INTERFACE_USER_OP:
568           strcpy (new->use_name, name);
569           /* Fall through */
570
571         case INTERFACE_INTRINSIC_OP:
572           new->operator = operator;
573           break;
574         }
575
576       if (gfc_match_eos () == MATCH_YES)
577         break;
578       if (gfc_match_char (',') != MATCH_YES)
579         goto syntax;
580     }
581
582   return MATCH_YES;
583
584 syntax:
585   gfc_syntax_error (ST_USE);
586
587 cleanup:
588   free_rename ();
589   return MATCH_ERROR;
590 }
591
592
593 /* Given a name, return the name under which to load this symbol.
594    Returns NULL if this symbol shouldn't be loaded.  */
595
596 static const char *
597 find_use_name (const char *name)
598 {
599   gfc_use_rename *u;
600
601   for (u = gfc_rename_list; u; u = u->next)
602     if (strcmp (u->use_name, name) == 0)
603       break;
604
605   if (u == NULL)
606     return only_flag ? NULL : name;
607
608   u->found = 1;
609
610   return (u->local_name[0] != '\0') ? u->local_name : name;
611 }
612
613
614 /* Try to find the operator in the current list.  */
615
616 static gfc_use_rename *
617 find_use_operator (gfc_intrinsic_op operator)
618 {
619   gfc_use_rename *u;
620
621   for (u = gfc_rename_list; u; u = u->next)
622     if (u->operator == operator)
623       return u;
624
625   return NULL;
626 }
627
628
629 /*****************************************************************/
630
631 /* The next couple of subroutines maintain a tree used to avoid a
632    brute-force search for a combination of true name and module name.
633    While symtree names, the name that a particular symbol is known by
634    can changed with USE statements, we still have to keep track of the
635    true names to generate the correct reference, and also avoid
636    loading the same real symbol twice in a program unit.
637
638    When we start reading, the true name tree is built and maintained
639    as symbols are read.  The tree is searched as we load new symbols
640    to see if it already exists someplace in the namespace.  */
641
642 typedef struct true_name
643 {
644   BBT_HEADER (true_name);
645   gfc_symbol *sym;
646 }
647 true_name;
648
649 static true_name *true_name_root;
650
651
652 /* Compare two true_name structures.  */
653
654 static int
655 compare_true_names (void * _t1, void * _t2)
656 {
657   true_name *t1, *t2;
658   int c;
659
660   t1 = (true_name *) _t1;
661   t2 = (true_name *) _t2;
662
663   c = strcmp (t1->sym->module, t2->sym->module);
664   if (c != 0)
665     return c;
666
667   return strcmp (t1->sym->name, t2->sym->name);
668 }
669
670
671 /* Given a true name, search the true name tree to see if it exists
672    within the main namespace.  */
673
674 static gfc_symbol *
675 find_true_name (const char *name, const char *module)
676 {
677   true_name t, *p;
678   gfc_symbol sym;
679   int c;
680
681   strcpy (sym.name, name);
682   strcpy (sym.module, module);
683   t.sym = &sym;
684
685   p = true_name_root;
686   while (p != NULL)
687     {
688       c = compare_true_names ((void *)(&t), (void *) p);
689       if (c == 0)
690         return p->sym;
691
692       p = (c < 0) ? p->left : p->right;
693     }
694
695   return NULL;
696 }
697
698
699 /* Given a gfc_symbol pointer that is not in the true name tree, add
700    it.  */
701
702 static void
703 add_true_name (gfc_symbol * sym)
704 {
705   true_name *t;
706
707   t = gfc_getmem (sizeof (true_name));
708   t->sym = sym;
709
710   gfc_insert_bbt (&true_name_root, t, compare_true_names);
711 }
712
713
714 /* Recursive function to build the initial true name tree by
715    recursively traversing the current namespace.  */
716
717 static void
718 build_tnt (gfc_symtree * st)
719 {
720
721   if (st == NULL)
722     return;
723
724   build_tnt (st->left);
725   build_tnt (st->right);
726
727   if (find_true_name (st->n.sym->name, st->n.sym->module) != NULL)
728     return;
729
730   add_true_name (st->n.sym);
731 }
732
733
734 /* Initialize the true name tree with the current namespace.  */
735
736 static void
737 init_true_name_tree (void)
738 {
739   true_name_root = NULL;
740
741   build_tnt (gfc_current_ns->sym_root);
742 }
743
744
745 /* Recursively free a true name tree node.  */
746
747 static void
748 free_true_name (true_name * t)
749 {
750
751   if (t == NULL)
752     return;
753   free_true_name (t->left);
754   free_true_name (t->right);
755
756   gfc_free (t);
757 }
758
759
760 /*****************************************************************/
761
762 /* Module reading and writing.  */
763
764 typedef enum
765 {
766   ATOM_NAME, ATOM_LPAREN, ATOM_RPAREN, ATOM_INTEGER, ATOM_STRING
767 }
768 atom_type;
769
770 static atom_type last_atom;
771
772
773 /* The name buffer must be at least as long as a symbol name.  Right
774    now it's not clear how we're going to store numeric constants--
775    probably as a hexadecimal string, since this will allow the exact
776    number to be preserved (this can't be done by a decimal
777    representation).  Worry about that later.  TODO!  */
778
779 #define MAX_ATOM_SIZE 100
780
781 static int atom_int;
782 static char *atom_string, atom_name[MAX_ATOM_SIZE];
783
784
785 /* Report problems with a module.  Error reporting is not very
786    elaborate, since this sorts of errors shouldn't really happen.
787    This subroutine never returns.  */
788
789 static void bad_module (const char *) ATTRIBUTE_NORETURN;
790
791 static void
792 bad_module (const char *message)
793 {
794   const char *p;
795
796   switch (iomode)
797     {
798     case IO_INPUT:
799       p = "Reading";
800       break;
801     case IO_OUTPUT:
802       p = "Writing";
803       break;
804     default:
805       p = "???";
806       break;
807     }
808
809   fclose (module_fp);
810
811   gfc_fatal_error ("%s module %s at line %d column %d: %s", p,
812                    module_name, module_line, module_column, message);
813 }
814
815
816 /* Set the module's input pointer.  */
817
818 static void
819 set_module_locus (module_locus * m)
820 {
821
822   module_column = m->column;
823   module_line = m->line;
824   fsetpos (module_fp, &m->pos);
825 }
826
827
828 /* Get the module's input pointer so that we can restore it later.  */
829
830 static void
831 get_module_locus (module_locus * m)
832 {
833
834   m->column = module_column;
835   m->line = module_line;
836   fgetpos (module_fp, &m->pos);
837 }
838
839
840 /* Get the next character in the module, updating our reckoning of
841    where we are.  */
842
843 static int
844 module_char (void)
845 {
846   int c;
847
848   c = fgetc (module_fp);
849
850   if (c == EOF)
851     bad_module ("Unexpected EOF");
852
853   if (c == '\n')
854     {
855       module_line++;
856       module_column = 0;
857     }
858
859   module_column++;
860   return c;
861 }
862
863
864 /* Parse a string constant.  The delimiter is guaranteed to be a
865    single quote.  */
866
867 static void
868 parse_string (void)
869 {
870   module_locus start;
871   int len, c;
872   char *p;
873
874   get_module_locus (&start);
875
876   len = 0;
877
878   /* See how long the string is */
879   for ( ; ; )
880     {
881       c = module_char ();
882       if (c == EOF)
883         bad_module ("Unexpected end of module in string constant");
884
885       if (c != '\'')
886         {
887           len++;
888           continue;
889         }
890
891       c = module_char ();
892       if (c == '\'')
893         {
894           len++;
895           continue;
896         }
897
898       break;
899     }
900
901   set_module_locus (&start);
902
903   atom_string = p = gfc_getmem (len + 1);
904
905   for (; len > 0; len--)
906     {
907       c = module_char ();
908       if (c == '\'')
909         module_char ();         /* Guaranteed to be another \' */
910       *p++ = c;
911     }
912
913   module_char ();               /* Terminating \' */
914   *p = '\0';                    /* C-style string for debug purposes */
915 }
916
917
918 /* Parse a small integer.  */
919
920 static void
921 parse_integer (int c)
922 {
923   module_locus m;
924
925   atom_int = c - '0';
926
927   for (;;)
928     {
929       get_module_locus (&m);
930
931       c = module_char ();
932       if (!ISDIGIT (c))
933         break;
934
935       atom_int = 10 * atom_int + c - '0';
936       if (atom_int > 99999999)
937         bad_module ("Integer overflow");
938     }
939
940   set_module_locus (&m);
941 }
942
943
944 /* Parse a name.  */
945
946 static void
947 parse_name (int c)
948 {
949   module_locus m;
950   char *p;
951   int len;
952
953   p = atom_name;
954
955   *p++ = c;
956   len = 1;
957
958   get_module_locus (&m);
959
960   for (;;)
961     {
962       c = module_char ();
963       if (!ISALNUM (c) && c != '_' && c != '-')
964         break;
965
966       *p++ = c;
967       if (++len > GFC_MAX_SYMBOL_LEN)
968         bad_module ("Name too long");
969     }
970
971   *p = '\0';
972
973   fseek (module_fp, -1, SEEK_CUR);
974   module_column = m.column + len - 1;
975
976   if (c == '\n')
977     module_line--;
978 }
979
980
981 /* Read the next atom in the module's input stream.  */
982
983 static atom_type
984 parse_atom (void)
985 {
986   int c;
987
988   do
989     {
990       c = module_char ();
991     }
992   while (c == ' ' || c == '\n');
993
994   switch (c)
995     {
996     case '(':
997       return ATOM_LPAREN;
998
999     case ')':
1000       return ATOM_RPAREN;
1001
1002     case '\'':
1003       parse_string ();
1004       return ATOM_STRING;
1005
1006     case '0':
1007     case '1':
1008     case '2':
1009     case '3':
1010     case '4':
1011     case '5':
1012     case '6':
1013     case '7':
1014     case '8':
1015     case '9':
1016       parse_integer (c);
1017       return ATOM_INTEGER;
1018
1019     case 'a':
1020     case 'b':
1021     case 'c':
1022     case 'd':
1023     case 'e':
1024     case 'f':
1025     case 'g':
1026     case 'h':
1027     case 'i':
1028     case 'j':
1029     case 'k':
1030     case 'l':
1031     case 'm':
1032     case 'n':
1033     case 'o':
1034     case 'p':
1035     case 'q':
1036     case 'r':
1037     case 's':
1038     case 't':
1039     case 'u':
1040     case 'v':
1041     case 'w':
1042     case 'x':
1043     case 'y':
1044     case 'z':
1045     case 'A':
1046     case 'B':
1047     case 'C':
1048     case 'D':
1049     case 'E':
1050     case 'F':
1051     case 'G':
1052     case 'H':
1053     case 'I':
1054     case 'J':
1055     case 'K':
1056     case 'L':
1057     case 'M':
1058     case 'N':
1059     case 'O':
1060     case 'P':
1061     case 'Q':
1062     case 'R':
1063     case 'S':
1064     case 'T':
1065     case 'U':
1066     case 'V':
1067     case 'W':
1068     case 'X':
1069     case 'Y':
1070     case 'Z':
1071       parse_name (c);
1072       return ATOM_NAME;
1073
1074     default:
1075       bad_module ("Bad name");
1076     }
1077
1078   /* Not reached */
1079 }
1080
1081
1082 /* Peek at the next atom on the input.  */
1083
1084 static atom_type
1085 peek_atom (void)
1086 {
1087   module_locus m;
1088   atom_type a;
1089
1090   get_module_locus (&m);
1091
1092   a = parse_atom ();
1093   if (a == ATOM_STRING)
1094     gfc_free (atom_string);
1095
1096   set_module_locus (&m);
1097   return a;
1098 }
1099
1100
1101 /* Read the next atom from the input, requiring that it be a
1102    particular kind.  */
1103
1104 static void
1105 require_atom (atom_type type)
1106 {
1107   module_locus m;
1108   atom_type t;
1109   const char *p;
1110
1111   get_module_locus (&m);
1112
1113   t = parse_atom ();
1114   if (t != type)
1115     {
1116       switch (type)
1117         {
1118         case ATOM_NAME:
1119           p = "Expected name";
1120           break;
1121         case ATOM_LPAREN:
1122           p = "Expected left parenthesis";
1123           break;
1124         case ATOM_RPAREN:
1125           p = "Expected right parenthesis";
1126           break;
1127         case ATOM_INTEGER:
1128           p = "Expected integer";
1129           break;
1130         case ATOM_STRING:
1131           p = "Expected string";
1132           break;
1133         default:
1134           gfc_internal_error ("require_atom(): bad atom type required");
1135         }
1136
1137       set_module_locus (&m);
1138       bad_module (p);
1139     }
1140 }
1141
1142
1143 /* Given a pointer to an mstring array, require that the current input
1144    be one of the strings in the array.  We return the enum value.  */
1145
1146 static int
1147 find_enum (const mstring * m)
1148 {
1149   int i;
1150
1151   i = gfc_string2code (m, atom_name);
1152   if (i >= 0)
1153     return i;
1154
1155   bad_module ("find_enum(): Enum not found");
1156
1157   /* Not reached */
1158 }
1159
1160
1161 /**************** Module output subroutines ***************************/
1162
1163 /* Output a character to a module file.  */
1164
1165 static void
1166 write_char (char out)
1167 {
1168
1169   if (fputc (out, module_fp) == EOF)
1170     gfc_fatal_error ("Error writing modules file: %s", strerror (errno));
1171
1172   if (out != '\n')
1173     module_column++;
1174   else
1175     {
1176       module_column = 1;
1177       module_line++;
1178     }
1179 }
1180
1181
1182 /* Write an atom to a module.  The line wrapping isn't perfect, but it
1183    should work most of the time.  This isn't that big of a deal, since
1184    the file really isn't meant to be read by people anyway.  */
1185
1186 static void
1187 write_atom (atom_type atom, const void *v)
1188 {
1189   char buffer[20];
1190   int i, len;
1191   const char *p;
1192
1193   switch (atom)
1194     {
1195     case ATOM_STRING:
1196     case ATOM_NAME:
1197       p = v;
1198       break;
1199
1200     case ATOM_LPAREN:
1201       p = "(";
1202       break;
1203
1204     case ATOM_RPAREN:
1205       p = ")";
1206       break;
1207
1208     case ATOM_INTEGER:
1209       i = *((const int *) v);
1210       if (i < 0)
1211         gfc_internal_error ("write_atom(): Writing negative integer");
1212
1213       sprintf (buffer, "%d", i);
1214       p = buffer;
1215       break;
1216
1217     default:
1218       gfc_internal_error ("write_atom(): Trying to write dab atom");
1219
1220     }
1221
1222   len = strlen (p);
1223
1224   if (atom != ATOM_RPAREN)
1225     {
1226       if (module_column + len > 72)
1227         write_char ('\n');
1228       else
1229         {
1230
1231           if (last_atom != ATOM_LPAREN && module_column != 1)
1232             write_char (' ');
1233         }
1234     }
1235
1236   if (atom == ATOM_STRING)
1237     write_char ('\'');
1238
1239   while (*p)
1240     {
1241       if (atom == ATOM_STRING && *p == '\'')
1242         write_char ('\'');
1243       write_char (*p++);
1244     }
1245
1246   if (atom == ATOM_STRING)
1247     write_char ('\'');
1248
1249   last_atom = atom;
1250 }
1251
1252
1253
1254 /***************** Mid-level I/O subroutines *****************/
1255
1256 /* These subroutines let their caller read or write atoms without
1257    caring about which of the two is actually happening.  This lets a
1258    subroutine concentrate on the actual format of the data being
1259    written.  */
1260
1261 static void mio_expr (gfc_expr **);
1262 static void mio_symbol_ref (gfc_symbol **);
1263 static void mio_symtree_ref (gfc_symtree **);
1264
1265 /* Read or write an enumerated value.  On writing, we return the input
1266    value for the convenience of callers.  We avoid using an integer
1267    pointer because enums are sometimes inside bitfields.  */
1268
1269 static int
1270 mio_name (int t, const mstring * m)
1271 {
1272
1273   if (iomode == IO_OUTPUT)
1274     write_atom (ATOM_NAME, gfc_code2string (m, t));
1275   else
1276     {
1277       require_atom (ATOM_NAME);
1278       t = find_enum (m);
1279     }
1280
1281   return t;
1282 }
1283
1284 /* Specialisation of mio_name.  */
1285
1286 #define DECL_MIO_NAME(TYPE) \
1287  static inline TYPE \
1288  MIO_NAME(TYPE) (TYPE t, const mstring * m) \
1289  { \
1290    return (TYPE)mio_name ((int)t, m); \
1291  }
1292 #define MIO_NAME(TYPE) mio_name_##TYPE
1293
1294 static void
1295 mio_lparen (void)
1296 {
1297
1298   if (iomode == IO_OUTPUT)
1299     write_atom (ATOM_LPAREN, NULL);
1300   else
1301     require_atom (ATOM_LPAREN);
1302 }
1303
1304
1305 static void
1306 mio_rparen (void)
1307 {
1308
1309   if (iomode == IO_OUTPUT)
1310     write_atom (ATOM_RPAREN, NULL);
1311   else
1312     require_atom (ATOM_RPAREN);
1313 }
1314
1315
1316 static void
1317 mio_integer (int *ip)
1318 {
1319
1320   if (iomode == IO_OUTPUT)
1321     write_atom (ATOM_INTEGER, ip);
1322   else
1323     {
1324       require_atom (ATOM_INTEGER);
1325       *ip = atom_int;
1326     }
1327 }
1328
1329
1330 /* Read or write a character pointer that points to a string on the
1331    heap.  */
1332
1333 static const char *
1334 mio_allocated_string (const char *s)
1335 {
1336   if (iomode == IO_OUTPUT)
1337     {
1338       write_atom (ATOM_STRING, s);
1339       return s;
1340     }
1341   else
1342     {
1343       require_atom (ATOM_STRING);
1344       return atom_string;
1345     }
1346 }
1347
1348
1349 /* Read or write a string that is in static memory or inside of some
1350    already-allocated structure.  */
1351
1352 static void
1353 mio_internal_string (char *string)
1354 {
1355
1356   if (iomode == IO_OUTPUT)
1357     write_atom (ATOM_STRING, string);
1358   else
1359     {
1360       require_atom (ATOM_STRING);
1361       strcpy (string, atom_string);
1362       gfc_free (atom_string);
1363     }
1364 }
1365
1366
1367
1368 typedef enum
1369 { AB_ALLOCATABLE, AB_DIMENSION, AB_EXTERNAL, AB_INTRINSIC, AB_OPTIONAL,
1370   AB_POINTER, AB_SAVE, AB_TARGET, AB_DUMMY, AB_RESULT,
1371   AB_DATA, AB_IN_NAMELIST, AB_IN_COMMON, 
1372   AB_FUNCTION, AB_SUBROUTINE, AB_SEQUENCE, AB_ELEMENTAL, AB_PURE,
1373   AB_RECURSIVE, AB_GENERIC, AB_ALWAYS_EXPLICIT
1374 }
1375 ab_attribute;
1376
1377 static const mstring attr_bits[] =
1378 {
1379     minit ("ALLOCATABLE", AB_ALLOCATABLE),
1380     minit ("DIMENSION", AB_DIMENSION),
1381     minit ("EXTERNAL", AB_EXTERNAL),
1382     minit ("INTRINSIC", AB_INTRINSIC),
1383     minit ("OPTIONAL", AB_OPTIONAL),
1384     minit ("POINTER", AB_POINTER),
1385     minit ("SAVE", AB_SAVE),
1386     minit ("TARGET", AB_TARGET),
1387     minit ("DUMMY", AB_DUMMY),
1388     minit ("RESULT", AB_RESULT),
1389     minit ("DATA", AB_DATA),
1390     minit ("IN_NAMELIST", AB_IN_NAMELIST),
1391     minit ("IN_COMMON", AB_IN_COMMON),
1392     minit ("FUNCTION", AB_FUNCTION),
1393     minit ("SUBROUTINE", AB_SUBROUTINE),
1394     minit ("SEQUENCE", AB_SEQUENCE),
1395     minit ("ELEMENTAL", AB_ELEMENTAL),
1396     minit ("PURE", AB_PURE),
1397     minit ("RECURSIVE", AB_RECURSIVE),
1398     minit ("GENERIC", AB_GENERIC),
1399     minit ("ALWAYS_EXPLICIT", AB_ALWAYS_EXPLICIT),
1400     minit (NULL, -1)
1401 };
1402
1403 /* Specialisation of mio_name.  */
1404 DECL_MIO_NAME(ab_attribute)
1405 DECL_MIO_NAME(ar_type)
1406 DECL_MIO_NAME(array_type)
1407 DECL_MIO_NAME(bt)
1408 DECL_MIO_NAME(expr_t)
1409 DECL_MIO_NAME(gfc_access)
1410 DECL_MIO_NAME(gfc_intrinsic_op)
1411 DECL_MIO_NAME(ifsrc)
1412 DECL_MIO_NAME(procedure_type)
1413 DECL_MIO_NAME(ref_type)
1414 DECL_MIO_NAME(sym_flavor)
1415 DECL_MIO_NAME(sym_intent)
1416 #undef DECL_MIO_NAME
1417
1418 /* Symbol attributes are stored in list with the first three elements
1419    being the enumerated fields, while the remaining elements (if any)
1420    indicate the individual attribute bits.  The access field is not
1421    saved-- it controls what symbols are exported when a module is
1422    written.  */
1423
1424 static void
1425 mio_symbol_attribute (symbol_attribute * attr)
1426 {
1427   atom_type t;
1428
1429   mio_lparen ();
1430
1431   attr->flavor = MIO_NAME(sym_flavor) (attr->flavor, flavors);
1432   attr->intent = MIO_NAME(sym_intent) (attr->intent, intents);
1433   attr->proc = MIO_NAME(procedure_type) (attr->proc, procedures);
1434   attr->if_source = MIO_NAME(ifsrc) (attr->if_source, ifsrc_types);
1435
1436   if (iomode == IO_OUTPUT)
1437     {
1438       if (attr->allocatable)
1439         MIO_NAME(ab_attribute) (AB_ALLOCATABLE, attr_bits);
1440       if (attr->dimension)
1441         MIO_NAME(ab_attribute) (AB_DIMENSION, attr_bits);
1442       if (attr->external)
1443         MIO_NAME(ab_attribute) (AB_EXTERNAL, attr_bits);
1444       if (attr->intrinsic)
1445         MIO_NAME(ab_attribute) (AB_INTRINSIC, attr_bits);
1446       if (attr->optional)
1447         MIO_NAME(ab_attribute) (AB_OPTIONAL, attr_bits);
1448       if (attr->pointer)
1449         MIO_NAME(ab_attribute) (AB_POINTER, attr_bits);
1450       if (attr->save)
1451         MIO_NAME(ab_attribute) (AB_SAVE, attr_bits);
1452       if (attr->target)
1453         MIO_NAME(ab_attribute) (AB_TARGET, attr_bits);
1454       if (attr->dummy)
1455         MIO_NAME(ab_attribute) (AB_DUMMY, attr_bits);
1456       if (attr->result)
1457         MIO_NAME(ab_attribute) (AB_RESULT, attr_bits);
1458       /* We deliberately don't preserve the "entry" flag.  */
1459
1460       if (attr->data)
1461         MIO_NAME(ab_attribute) (AB_DATA, attr_bits);
1462       if (attr->in_namelist)
1463         MIO_NAME(ab_attribute) (AB_IN_NAMELIST, attr_bits);
1464       if (attr->in_common)
1465         MIO_NAME(ab_attribute) (AB_IN_COMMON, attr_bits);
1466
1467       if (attr->function)
1468         MIO_NAME(ab_attribute) (AB_FUNCTION, attr_bits);
1469       if (attr->subroutine)
1470         MIO_NAME(ab_attribute) (AB_SUBROUTINE, attr_bits);
1471       if (attr->generic)
1472         MIO_NAME(ab_attribute) (AB_GENERIC, attr_bits);
1473
1474       if (attr->sequence)
1475         MIO_NAME(ab_attribute) (AB_SEQUENCE, attr_bits);
1476       if (attr->elemental)
1477         MIO_NAME(ab_attribute) (AB_ELEMENTAL, attr_bits);
1478       if (attr->pure)
1479         MIO_NAME(ab_attribute) (AB_PURE, attr_bits);
1480       if (attr->recursive)
1481         MIO_NAME(ab_attribute) (AB_RECURSIVE, attr_bits);
1482       if (attr->always_explicit)
1483         MIO_NAME(ab_attribute) (AB_ALWAYS_EXPLICIT, attr_bits);
1484
1485       mio_rparen ();
1486
1487     }
1488   else
1489     {
1490
1491       for (;;)
1492         {
1493           t = parse_atom ();
1494           if (t == ATOM_RPAREN)
1495             break;
1496           if (t != ATOM_NAME)
1497             bad_module ("Expected attribute bit name");
1498
1499           switch ((ab_attribute) find_enum (attr_bits))
1500             {
1501             case AB_ALLOCATABLE:
1502               attr->allocatable = 1;
1503               break;
1504             case AB_DIMENSION:
1505               attr->dimension = 1;
1506               break;
1507             case AB_EXTERNAL:
1508               attr->external = 1;
1509               break;
1510             case AB_INTRINSIC:
1511               attr->intrinsic = 1;
1512               break;
1513             case AB_OPTIONAL:
1514               attr->optional = 1;
1515               break;
1516             case AB_POINTER:
1517               attr->pointer = 1;
1518               break;
1519             case AB_SAVE:
1520               attr->save = 1;
1521               break;
1522             case AB_TARGET:
1523               attr->target = 1;
1524               break;
1525             case AB_DUMMY:
1526               attr->dummy = 1;
1527               break;
1528             case AB_RESULT:
1529               attr->result = 1;
1530               break;
1531             case AB_DATA:
1532               attr->data = 1;
1533               break;
1534             case AB_IN_NAMELIST:
1535               attr->in_namelist = 1;
1536               break;
1537             case AB_IN_COMMON:
1538               attr->in_common = 1;
1539               break;
1540             case AB_FUNCTION:
1541               attr->function = 1;
1542               break;
1543             case AB_SUBROUTINE:
1544               attr->subroutine = 1;
1545               break;
1546             case AB_GENERIC:
1547               attr->generic = 1;
1548               break;
1549             case AB_SEQUENCE:
1550               attr->sequence = 1;
1551               break;
1552             case AB_ELEMENTAL:
1553               attr->elemental = 1;
1554               break;
1555             case AB_PURE:
1556               attr->pure = 1;
1557               break;
1558             case AB_RECURSIVE:
1559               attr->recursive = 1;
1560               break;
1561             case AB_ALWAYS_EXPLICIT:
1562               attr->always_explicit = 1;
1563               break;
1564             }
1565         }
1566     }
1567 }
1568
1569
1570 static const mstring bt_types[] = {
1571     minit ("INTEGER", BT_INTEGER),
1572     minit ("REAL", BT_REAL),
1573     minit ("COMPLEX", BT_COMPLEX),
1574     minit ("LOGICAL", BT_LOGICAL),
1575     minit ("CHARACTER", BT_CHARACTER),
1576     minit ("DERIVED", BT_DERIVED),
1577     minit ("PROCEDURE", BT_PROCEDURE),
1578     minit ("UNKNOWN", BT_UNKNOWN),
1579     minit (NULL, -1)
1580 };
1581
1582
1583 static void
1584 mio_charlen (gfc_charlen ** clp)
1585 {
1586   gfc_charlen *cl;
1587
1588   mio_lparen ();
1589
1590   if (iomode == IO_OUTPUT)
1591     {
1592       cl = *clp;
1593       if (cl != NULL)
1594         mio_expr (&cl->length);
1595     }
1596   else
1597     {
1598
1599       if (peek_atom () != ATOM_RPAREN)
1600         {
1601           cl = gfc_get_charlen ();
1602           mio_expr (&cl->length);
1603
1604           *clp = cl;
1605
1606           cl->next = gfc_current_ns->cl_list;
1607           gfc_current_ns->cl_list = cl;
1608         }
1609     }
1610
1611   mio_rparen ();
1612 }
1613
1614
1615 /* Return a symtree node with a name that is guaranteed to be unique
1616    within the namespace and corresponds to an illegal fortran name.  */
1617
1618 static gfc_symtree *
1619 get_unique_symtree (gfc_namespace * ns)
1620 {
1621   char name[GFC_MAX_SYMBOL_LEN + 1];
1622   static int serial = 0;
1623
1624   sprintf (name, "@%d", serial++);
1625   return gfc_new_symtree (&ns->sym_root, name);
1626 }
1627
1628
1629 /* See if a name is a generated name.  */
1630
1631 static int
1632 check_unique_name (const char *name)
1633 {
1634
1635   return *name == '@';
1636 }
1637
1638
1639 static void
1640 mio_typespec (gfc_typespec * ts)
1641 {
1642
1643   mio_lparen ();
1644
1645   ts->type = MIO_NAME(bt) (ts->type, bt_types);
1646
1647   if (ts->type != BT_DERIVED)
1648     mio_integer (&ts->kind);
1649   else
1650     mio_symbol_ref (&ts->derived);
1651
1652   mio_charlen (&ts->cl);
1653
1654   mio_rparen ();
1655 }
1656
1657
1658 static const mstring array_spec_types[] = {
1659     minit ("EXPLICIT", AS_EXPLICIT),
1660     minit ("ASSUMED_SHAPE", AS_ASSUMED_SHAPE),
1661     minit ("DEFERRED", AS_DEFERRED),
1662     minit ("ASSUMED_SIZE", AS_ASSUMED_SIZE),
1663     minit (NULL, -1)
1664 };
1665
1666
1667 static void
1668 mio_array_spec (gfc_array_spec ** asp)
1669 {
1670   gfc_array_spec *as;
1671   int i;
1672
1673   mio_lparen ();
1674
1675   if (iomode == IO_OUTPUT)
1676     {
1677       if (*asp == NULL)
1678         goto done;
1679       as = *asp;
1680     }
1681   else
1682     {
1683       if (peek_atom () == ATOM_RPAREN)
1684         {
1685           *asp = NULL;
1686           goto done;
1687         }
1688
1689       *asp = as = gfc_get_array_spec ();
1690     }
1691
1692   mio_integer (&as->rank);
1693   as->type = MIO_NAME(array_type) (as->type, array_spec_types);
1694
1695   for (i = 0; i < as->rank; i++)
1696     {
1697       mio_expr (&as->lower[i]);
1698       mio_expr (&as->upper[i]);
1699     }
1700
1701 done:
1702   mio_rparen ();
1703 }
1704
1705
1706 /* Given a pointer to an array reference structure (which lives in a
1707    gfc_ref structure), find the corresponding array specification
1708    structure.  Storing the pointer in the ref structure doesn't quite
1709    work when loading from a module. Generating code for an array
1710    reference also needs more information than just the array spec.  */
1711
1712 static const mstring array_ref_types[] = {
1713     minit ("FULL", AR_FULL),
1714     minit ("ELEMENT", AR_ELEMENT),
1715     minit ("SECTION", AR_SECTION),
1716     minit (NULL, -1)
1717 };
1718
1719 static void
1720 mio_array_ref (gfc_array_ref * ar)
1721 {
1722   int i;
1723
1724   mio_lparen ();
1725   ar->type = MIO_NAME(ar_type) (ar->type, array_ref_types);
1726   mio_integer (&ar->dimen);
1727
1728   switch (ar->type)
1729     {
1730     case AR_FULL:
1731       break;
1732
1733     case AR_ELEMENT:
1734       for (i = 0; i < ar->dimen; i++)
1735         mio_expr (&ar->start[i]);
1736
1737       break;
1738
1739     case AR_SECTION:
1740       for (i = 0; i < ar->dimen; i++)
1741         {
1742           mio_expr (&ar->start[i]);
1743           mio_expr (&ar->end[i]);
1744           mio_expr (&ar->stride[i]);
1745         }
1746
1747       break;
1748
1749     case AR_UNKNOWN:
1750       gfc_internal_error ("mio_array_ref(): Unknown array ref");
1751     }
1752
1753   for (i = 0; i < ar->dimen; i++)
1754     mio_integer ((int *) &ar->dimen_type[i]);
1755
1756   if (iomode == IO_INPUT)
1757     {
1758       ar->where = gfc_current_locus;
1759
1760       for (i = 0; i < ar->dimen; i++)
1761         ar->c_where[i] = gfc_current_locus;
1762     }
1763
1764   mio_rparen ();
1765 }
1766
1767
1768 /* Saves or restores a pointer.  The pointer is converted back and
1769    forth from an integer.  We return the pointer_info pointer so that
1770    the caller can take additional action based on the pointer type.  */
1771
1772 static pointer_info *
1773 mio_pointer_ref (void *gp)
1774 {
1775   pointer_info *p;
1776
1777   if (iomode == IO_OUTPUT)
1778     {
1779       p = get_pointer (*((char **) gp));
1780       write_atom (ATOM_INTEGER, &p->integer);
1781     }
1782   else
1783     {
1784       require_atom (ATOM_INTEGER);
1785       p = add_fixup (atom_int, gp);
1786     }
1787
1788   return p;
1789 }
1790
1791
1792 /* Save and load references to components that occur within
1793    expressions.  We have to describe these references by a number and
1794    by name.  The number is necessary for forward references during
1795    reading, and the name is necessary if the symbol already exists in
1796    the namespace and is not loaded again.  */
1797
1798 static void
1799 mio_component_ref (gfc_component ** cp, gfc_symbol * sym)
1800 {
1801   char name[GFC_MAX_SYMBOL_LEN + 1];
1802   gfc_component *q;
1803   pointer_info *p;
1804
1805   p = mio_pointer_ref (cp);
1806   if (p->type == P_UNKNOWN)
1807     p->type = P_COMPONENT;
1808
1809   if (iomode == IO_OUTPUT)
1810     mio_internal_string ((*cp)->name);
1811   else
1812     {
1813       mio_internal_string (name);
1814
1815       if (sym->components != NULL && p->u.pointer == NULL)
1816         {
1817           /* Symbol already loaded, so search by name.  */
1818           for (q = sym->components; q; q = q->next)
1819             if (strcmp (q->name, name) == 0)
1820               break;
1821
1822           if (q == NULL)
1823             gfc_internal_error ("mio_component_ref(): Component not found");
1824
1825           associate_integer_pointer (p, q);
1826         }
1827
1828       /* Make sure this symbol will eventually be loaded.  */
1829       p = find_pointer2 (sym);
1830       if (p->u.rsym.state == UNUSED)
1831         p->u.rsym.state = NEEDED;
1832     }
1833 }
1834
1835
1836 static void
1837 mio_component (gfc_component * c)
1838 {
1839   pointer_info *p;
1840   int n;
1841
1842   mio_lparen ();
1843
1844   if (iomode == IO_OUTPUT)
1845     {
1846       p = get_pointer (c);
1847       mio_integer (&p->integer);
1848     }
1849   else
1850     {
1851       mio_integer (&n);
1852       p = get_integer (n);
1853       associate_integer_pointer (p, c);
1854     }
1855
1856   if (p->type == P_UNKNOWN)
1857     p->type = P_COMPONENT;
1858
1859   mio_internal_string (c->name);
1860   mio_typespec (&c->ts);
1861   mio_array_spec (&c->as);
1862
1863   mio_integer (&c->dimension);
1864   mio_integer (&c->pointer);
1865
1866   mio_expr (&c->initializer);
1867   mio_rparen ();
1868 }
1869
1870
1871 static void
1872 mio_component_list (gfc_component ** cp)
1873 {
1874   gfc_component *c, *tail;
1875
1876   mio_lparen ();
1877
1878   if (iomode == IO_OUTPUT)
1879     {
1880       for (c = *cp; c; c = c->next)
1881         mio_component (c);
1882     }
1883   else
1884     {
1885
1886       *cp = NULL;
1887       tail = NULL;
1888
1889       for (;;)
1890         {
1891           if (peek_atom () == ATOM_RPAREN)
1892             break;
1893
1894           c = gfc_get_component ();
1895           mio_component (c);
1896
1897           if (tail == NULL)
1898             *cp = c;
1899           else
1900             tail->next = c;
1901
1902           tail = c;
1903         }
1904     }
1905
1906   mio_rparen ();
1907 }
1908
1909
1910 static void
1911 mio_actual_arg (gfc_actual_arglist * a)
1912 {
1913
1914   mio_lparen ();
1915   mio_internal_string (a->name);
1916   mio_expr (&a->expr);
1917   mio_rparen ();
1918 }
1919
1920
1921 static void
1922 mio_actual_arglist (gfc_actual_arglist ** ap)
1923 {
1924   gfc_actual_arglist *a, *tail;
1925
1926   mio_lparen ();
1927
1928   if (iomode == IO_OUTPUT)
1929     {
1930       for (a = *ap; a; a = a->next)
1931         mio_actual_arg (a);
1932
1933     }
1934   else
1935     {
1936       tail = NULL;
1937
1938       for (;;)
1939         {
1940           if (peek_atom () != ATOM_LPAREN)
1941             break;
1942
1943           a = gfc_get_actual_arglist ();
1944
1945           if (tail == NULL)
1946             *ap = a;
1947           else
1948             tail->next = a;
1949
1950           tail = a;
1951           mio_actual_arg (a);
1952         }
1953     }
1954
1955   mio_rparen ();
1956 }
1957
1958
1959 /* Read and write formal argument lists.  */
1960
1961 static void
1962 mio_formal_arglist (gfc_symbol * sym)
1963 {
1964   gfc_formal_arglist *f, *tail;
1965
1966   mio_lparen ();
1967
1968   if (iomode == IO_OUTPUT)
1969     {
1970       for (f = sym->formal; f; f = f->next)
1971         mio_symbol_ref (&f->sym);
1972
1973     }
1974   else
1975     {
1976       sym->formal = tail = NULL;
1977
1978       while (peek_atom () != ATOM_RPAREN)
1979         {
1980           f = gfc_get_formal_arglist ();
1981           mio_symbol_ref (&f->sym);
1982
1983           if (sym->formal == NULL)
1984             sym->formal = f;
1985           else
1986             tail->next = f;
1987
1988           tail = f;
1989         }
1990     }
1991
1992   mio_rparen ();
1993 }
1994
1995
1996 /* Save or restore a reference to a symbol node.  */
1997
1998 void
1999 mio_symbol_ref (gfc_symbol ** symp)
2000 {
2001   pointer_info *p;
2002
2003   p = mio_pointer_ref (symp);
2004   if (p->type == P_UNKNOWN)
2005     p->type = P_SYMBOL;
2006
2007   if (iomode == IO_OUTPUT)
2008     {
2009       if (p->u.wsym.state == UNREFERENCED)
2010         p->u.wsym.state = NEEDS_WRITE;
2011     }
2012   else
2013     {
2014       if (p->u.rsym.state == UNUSED)
2015         p->u.rsym.state = NEEDED;
2016     }
2017 }
2018
2019
2020 /* Save or restore a reference to a symtree node.  */
2021
2022 static void
2023 mio_symtree_ref (gfc_symtree ** stp)
2024 {
2025   pointer_info *p;
2026   fixup_t *f;
2027
2028   if (iomode == IO_OUTPUT)
2029     {
2030       mio_symbol_ref (&(*stp)->n.sym);
2031     }
2032   else
2033     {
2034       require_atom (ATOM_INTEGER);
2035       p = get_integer (atom_int);
2036       if (p->type == P_UNKNOWN)
2037         p->type = P_SYMBOL;
2038
2039       if (p->u.rsym.state == UNUSED)
2040         p->u.rsym.state = NEEDED;
2041
2042       if (p->u.rsym.symtree != NULL)
2043         {
2044           *stp = p->u.rsym.symtree;
2045         }
2046       else
2047         {
2048           f = gfc_getmem (sizeof (fixup_t));
2049
2050           f->next = p->u.rsym.stfixup;
2051           p->u.rsym.stfixup = f;
2052
2053           f->pointer = (void **)stp;
2054         }
2055     }
2056 }
2057
2058 static void
2059 mio_iterator (gfc_iterator ** ip)
2060 {
2061   gfc_iterator *iter;
2062
2063   mio_lparen ();
2064
2065   if (iomode == IO_OUTPUT)
2066     {
2067       if (*ip == NULL)
2068         goto done;
2069     }
2070   else
2071     {
2072       if (peek_atom () == ATOM_RPAREN)
2073         {
2074           *ip = NULL;
2075           goto done;
2076         }
2077
2078       *ip = gfc_get_iterator ();
2079     }
2080
2081   iter = *ip;
2082
2083   mio_expr (&iter->var);
2084   mio_expr (&iter->start);
2085   mio_expr (&iter->end);
2086   mio_expr (&iter->step);
2087
2088 done:
2089   mio_rparen ();
2090 }
2091
2092
2093
2094 static void
2095 mio_constructor (gfc_constructor ** cp)
2096 {
2097   gfc_constructor *c, *tail;
2098
2099   mio_lparen ();
2100
2101   if (iomode == IO_OUTPUT)
2102     {
2103       for (c = *cp; c; c = c->next)
2104         {
2105           mio_lparen ();
2106           mio_expr (&c->expr);
2107           mio_iterator (&c->iterator);
2108           mio_rparen ();
2109         }
2110     }
2111   else
2112     {
2113
2114       *cp = NULL;
2115       tail = NULL;
2116
2117       while (peek_atom () != ATOM_RPAREN)
2118         {
2119           c = gfc_get_constructor ();
2120
2121           if (tail == NULL)
2122             *cp = c;
2123           else
2124             tail->next = c;
2125
2126           tail = c;
2127
2128           mio_lparen ();
2129           mio_expr (&c->expr);
2130           mio_iterator (&c->iterator);
2131           mio_rparen ();
2132         }
2133     }
2134
2135   mio_rparen ();
2136 }
2137
2138
2139
2140 static const mstring ref_types[] = {
2141     minit ("ARRAY", REF_ARRAY),
2142     minit ("COMPONENT", REF_COMPONENT),
2143     minit ("SUBSTRING", REF_SUBSTRING),
2144     minit (NULL, -1)
2145 };
2146
2147
2148 static void
2149 mio_ref (gfc_ref ** rp)
2150 {
2151   gfc_ref *r;
2152
2153   mio_lparen ();
2154
2155   r = *rp;
2156   r->type = MIO_NAME(ref_type) (r->type, ref_types);
2157
2158   switch (r->type)
2159     {
2160     case REF_ARRAY:
2161       mio_array_ref (&r->u.ar);
2162       break;
2163
2164     case REF_COMPONENT:
2165       mio_symbol_ref (&r->u.c.sym);
2166       mio_component_ref (&r->u.c.component, r->u.c.sym);
2167       break;
2168
2169     case REF_SUBSTRING:
2170       mio_expr (&r->u.ss.start);
2171       mio_expr (&r->u.ss.end);
2172       mio_charlen (&r->u.ss.length);
2173       break;
2174     }
2175
2176   mio_rparen ();
2177 }
2178
2179
2180 static void
2181 mio_ref_list (gfc_ref ** rp)
2182 {
2183   gfc_ref *ref, *head, *tail;
2184
2185   mio_lparen ();
2186
2187   if (iomode == IO_OUTPUT)
2188     {
2189       for (ref = *rp; ref; ref = ref->next)
2190         mio_ref (&ref);
2191     }
2192   else
2193     {
2194       head = tail = NULL;
2195
2196       while (peek_atom () != ATOM_RPAREN)
2197         {
2198           if (head == NULL)
2199             head = tail = gfc_get_ref ();
2200           else
2201             {
2202               tail->next = gfc_get_ref ();
2203               tail = tail->next;
2204             }
2205
2206           mio_ref (&tail);
2207         }
2208
2209       *rp = head;
2210     }
2211
2212   mio_rparen ();
2213 }
2214
2215
2216 /* Read and write an integer value.  */
2217
2218 static void
2219 mio_gmp_integer (mpz_t * integer)
2220 {
2221   char *p;
2222
2223   if (iomode == IO_INPUT)
2224     {
2225       if (parse_atom () != ATOM_STRING)
2226         bad_module ("Expected integer string");
2227
2228       mpz_init (*integer);
2229       if (mpz_set_str (*integer, atom_string, 10))
2230         bad_module ("Error converting integer");
2231
2232       gfc_free (atom_string);
2233
2234     }
2235   else
2236     {
2237       p = mpz_get_str (NULL, 10, *integer);
2238       write_atom (ATOM_STRING, p);
2239       gfc_free (p);
2240     }
2241 }
2242
2243
2244 static void
2245 mio_gmp_real (mpfr_t * real)
2246 {
2247   mp_exp_t exponent;
2248   char *p;
2249
2250   if (iomode == IO_INPUT)
2251     {
2252       if (parse_atom () != ATOM_STRING)
2253         bad_module ("Expected real string");
2254
2255       mpfr_init (*real);
2256       mpfr_set_str (*real, atom_string, 16, GFC_RND_MODE);
2257       gfc_free (atom_string);
2258
2259     }
2260   else
2261     {
2262       p = mpfr_get_str (NULL, &exponent, 16, 0, *real, GFC_RND_MODE);
2263       atom_string = gfc_getmem (strlen (p) + 20);
2264
2265       sprintf (atom_string, "0.%s@%ld", p, exponent);
2266
2267       /* Fix negative numbers.  */
2268       if (atom_string[2] == '-')
2269         {
2270           atom_string[0] = '-';
2271           atom_string[1] = '0';
2272           atom_string[2] = '.';
2273         }
2274
2275       write_atom (ATOM_STRING, atom_string);
2276
2277       gfc_free (atom_string);
2278       gfc_free (p);
2279     }
2280 }
2281
2282
2283 /* Save and restore the shape of an array constructor.  */
2284
2285 static void
2286 mio_shape (mpz_t ** pshape, int rank)
2287 {
2288   mpz_t *shape;
2289   atom_type t;
2290   int n;
2291
2292   /* A NULL shape is represented by ().  */
2293   mio_lparen ();
2294
2295   if (iomode == IO_OUTPUT)
2296     {
2297       shape = *pshape;
2298       if (!shape)
2299         {
2300           mio_rparen ();
2301           return;
2302         }
2303     }
2304   else
2305     {
2306       t = peek_atom ();
2307       if (t == ATOM_RPAREN)
2308         {
2309           *pshape = NULL;
2310           mio_rparen ();
2311           return;
2312         }
2313
2314       shape = gfc_get_shape (rank);
2315       *pshape = shape;
2316     }
2317
2318   for (n = 0; n < rank; n++)
2319     mio_gmp_integer (&shape[n]);
2320
2321   mio_rparen ();
2322 }
2323
2324
2325 static const mstring expr_types[] = {
2326     minit ("OP", EXPR_OP),
2327     minit ("FUNCTION", EXPR_FUNCTION),
2328     minit ("CONSTANT", EXPR_CONSTANT),
2329     minit ("VARIABLE", EXPR_VARIABLE),
2330     minit ("SUBSTRING", EXPR_SUBSTRING),
2331     minit ("STRUCTURE", EXPR_STRUCTURE),
2332     minit ("ARRAY", EXPR_ARRAY),
2333     minit ("NULL", EXPR_NULL),
2334     minit (NULL, -1)
2335 };
2336
2337 /* INTRINSIC_ASSIGN is missing because it is used as an index for
2338    generic operators, not in expressions.  INTRINSIC_USER is also
2339    replaced by the correct function name by the time we see it.  */
2340
2341 static const mstring intrinsics[] =
2342 {
2343     minit ("UPLUS", INTRINSIC_UPLUS),
2344     minit ("UMINUS", INTRINSIC_UMINUS),
2345     minit ("PLUS", INTRINSIC_PLUS),
2346     minit ("MINUS", INTRINSIC_MINUS),
2347     minit ("TIMES", INTRINSIC_TIMES),
2348     minit ("DIVIDE", INTRINSIC_DIVIDE),
2349     minit ("POWER", INTRINSIC_POWER),
2350     minit ("CONCAT", INTRINSIC_CONCAT),
2351     minit ("AND", INTRINSIC_AND),
2352     minit ("OR", INTRINSIC_OR),
2353     minit ("EQV", INTRINSIC_EQV),
2354     minit ("NEQV", INTRINSIC_NEQV),
2355     minit ("EQ", INTRINSIC_EQ),
2356     minit ("NE", INTRINSIC_NE),
2357     minit ("GT", INTRINSIC_GT),
2358     minit ("GE", INTRINSIC_GE),
2359     minit ("LT", INTRINSIC_LT),
2360     minit ("LE", INTRINSIC_LE),
2361     minit ("NOT", INTRINSIC_NOT),
2362     minit (NULL, -1)
2363 };
2364
2365 /* Read and write expressions.  The form "()" is allowed to indicate a
2366    NULL expression.  */
2367
2368 static void
2369 mio_expr (gfc_expr ** ep)
2370 {
2371   gfc_expr *e;
2372   atom_type t;
2373   int flag;
2374
2375   mio_lparen ();
2376
2377   if (iomode == IO_OUTPUT)
2378     {
2379       if (*ep == NULL)
2380         {
2381           mio_rparen ();
2382           return;
2383         }
2384
2385       e = *ep;
2386       MIO_NAME(expr_t) (e->expr_type, expr_types);
2387
2388     }
2389   else
2390     {
2391       t = parse_atom ();
2392       if (t == ATOM_RPAREN)
2393         {
2394           *ep = NULL;
2395           return;
2396         }
2397
2398       if (t != ATOM_NAME)
2399         bad_module ("Expected expression type");
2400
2401       e = *ep = gfc_get_expr ();
2402       e->where = gfc_current_locus;
2403       e->expr_type = (expr_t) find_enum (expr_types);
2404     }
2405
2406   mio_typespec (&e->ts);
2407   mio_integer (&e->rank);
2408
2409   switch (e->expr_type)
2410     {
2411     case EXPR_OP:
2412       e->operator = MIO_NAME(gfc_intrinsic_op) (e->operator, intrinsics);
2413
2414       switch (e->operator)
2415         {
2416         case INTRINSIC_UPLUS:
2417         case INTRINSIC_UMINUS:
2418         case INTRINSIC_NOT:
2419           mio_expr (&e->op1);
2420           break;
2421
2422         case INTRINSIC_PLUS:
2423         case INTRINSIC_MINUS:
2424         case INTRINSIC_TIMES:
2425         case INTRINSIC_DIVIDE:
2426         case INTRINSIC_POWER:
2427         case INTRINSIC_CONCAT:
2428         case INTRINSIC_AND:
2429         case INTRINSIC_OR:
2430         case INTRINSIC_EQV:
2431         case INTRINSIC_NEQV:
2432         case INTRINSIC_EQ:
2433         case INTRINSIC_NE:
2434         case INTRINSIC_GT:
2435         case INTRINSIC_GE:
2436         case INTRINSIC_LT:
2437         case INTRINSIC_LE:
2438           mio_expr (&e->op1);
2439           mio_expr (&e->op2);
2440           break;
2441
2442         default:
2443           bad_module ("Bad operator");
2444         }
2445
2446       break;
2447
2448     case EXPR_FUNCTION:
2449       mio_symtree_ref (&e->symtree);
2450       mio_actual_arglist (&e->value.function.actual);
2451
2452       if (iomode == IO_OUTPUT)
2453         {
2454           e->value.function.name
2455             = mio_allocated_string (e->value.function.name);
2456           flag = e->value.function.esym != NULL;
2457           mio_integer (&flag);
2458           if (flag)
2459             mio_symbol_ref (&e->value.function.esym);
2460           else
2461             write_atom (ATOM_STRING, e->value.function.isym->name);
2462
2463         }
2464       else
2465         {
2466           require_atom (ATOM_STRING);
2467           e->value.function.name = gfc_get_string (atom_string);
2468           gfc_free (atom_string);
2469
2470           mio_integer (&flag);
2471           if (flag)
2472             mio_symbol_ref (&e->value.function.esym);
2473           else
2474             {
2475               require_atom (ATOM_STRING);
2476               e->value.function.isym = gfc_find_function (atom_string);
2477               gfc_free (atom_string);
2478             }
2479         }
2480
2481       break;
2482
2483     case EXPR_VARIABLE:
2484       mio_symtree_ref (&e->symtree);
2485       mio_ref_list (&e->ref);
2486       break;
2487
2488     case EXPR_SUBSTRING:
2489       e->value.character.string = (char *)
2490         mio_allocated_string (e->value.character.string);
2491       mio_expr (&e->op1);
2492       mio_expr (&e->op2);
2493       break;
2494
2495     case EXPR_STRUCTURE:
2496     case EXPR_ARRAY:
2497       mio_constructor (&e->value.constructor);
2498       mio_shape (&e->shape, e->rank);
2499       break;
2500
2501     case EXPR_CONSTANT:
2502       switch (e->ts.type)
2503         {
2504         case BT_INTEGER:
2505           mio_gmp_integer (&e->value.integer);
2506           break;
2507
2508         case BT_REAL:
2509           gfc_set_model_kind (e->ts.kind);
2510           mio_gmp_real (&e->value.real);
2511           break;
2512
2513         case BT_COMPLEX:
2514           gfc_set_model_kind (e->ts.kind);
2515           mio_gmp_real (&e->value.complex.r);
2516           mio_gmp_real (&e->value.complex.i);
2517           break;
2518
2519         case BT_LOGICAL:
2520           mio_integer (&e->value.logical);
2521           break;
2522
2523         case BT_CHARACTER:
2524           mio_integer (&e->value.character.length);
2525           e->value.character.string = (char *)
2526             mio_allocated_string (e->value.character.string);
2527           break;
2528
2529         default:
2530           bad_module ("Bad type in constant expression");
2531         }
2532
2533       break;
2534
2535     case EXPR_NULL:
2536       break;
2537     }
2538
2539   mio_rparen ();
2540 }
2541
2542
2543 /* Save/restore lists of gfc_interface stuctures.  When loading an
2544    interface, we are really appending to the existing list of
2545    interfaces.  Checking for duplicate and ambiguous interfaces has to
2546    be done later when all symbols have been loaded.  */
2547
2548 static void
2549 mio_interface_rest (gfc_interface ** ip)
2550 {
2551   gfc_interface *tail, *p;
2552
2553   if (iomode == IO_OUTPUT)
2554     {
2555       if (ip != NULL)
2556         for (p = *ip; p; p = p->next)
2557           mio_symbol_ref (&p->sym);
2558     }
2559   else
2560     {
2561
2562       if (*ip == NULL)
2563         tail = NULL;
2564       else
2565         {
2566           tail = *ip;
2567           while (tail->next)
2568             tail = tail->next;
2569         }
2570
2571       for (;;)
2572         {
2573           if (peek_atom () == ATOM_RPAREN)
2574             break;
2575
2576           p = gfc_get_interface ();
2577           p->where = gfc_current_locus;
2578           mio_symbol_ref (&p->sym);
2579
2580           if (tail == NULL)
2581             *ip = p;
2582           else
2583             tail->next = p;
2584
2585           tail = p;
2586         }
2587     }
2588
2589   mio_rparen ();
2590 }
2591
2592
2593 /* Save/restore a nameless operator interface.  */
2594
2595 static void
2596 mio_interface (gfc_interface ** ip)
2597 {
2598
2599   mio_lparen ();
2600   mio_interface_rest (ip);
2601 }
2602
2603
2604 /* Save/restore a named operator interface.  */
2605
2606 static void
2607 mio_symbol_interface (char *name, char *module,
2608                       gfc_interface ** ip)
2609 {
2610
2611   mio_lparen ();
2612
2613   mio_internal_string (name);
2614   mio_internal_string (module);
2615
2616   mio_interface_rest (ip);
2617 }
2618
2619
2620 static void
2621 mio_namespace_ref (gfc_namespace ** nsp)
2622 {
2623   gfc_namespace *ns;
2624   pointer_info *p;
2625
2626   p = mio_pointer_ref (nsp);
2627
2628   if (p->type == P_UNKNOWN)
2629     p->type = P_NAMESPACE;
2630
2631   if (iomode == IO_INPUT && p->integer != 0)
2632     {
2633       ns = (gfc_namespace *)p->u.pointer;
2634       if (ns == NULL)
2635         {
2636           ns = gfc_get_namespace (NULL);
2637           associate_integer_pointer (p, ns);
2638         }
2639       else
2640         ns->refs++;
2641     }
2642 }
2643
2644
2645 /* Unlike most other routines, the address of the symbol node is
2646    already fixed on input and the name/module has already been filled
2647    in.  */
2648
2649 static void
2650 mio_symbol (gfc_symbol * sym)
2651 {
2652   gfc_formal_arglist *formal;
2653
2654   mio_lparen ();
2655
2656   mio_symbol_attribute (&sym->attr);
2657   mio_typespec (&sym->ts);
2658
2659   /* Contained procedures don't have formal namespaces.  Instead we output the
2660      procedure namespace.  The will contain the formal arguments.  */
2661   if (iomode == IO_OUTPUT)
2662     {
2663       formal = sym->formal;
2664       while (formal && !formal->sym)
2665         formal = formal->next;
2666
2667       if (formal)
2668         mio_namespace_ref (&formal->sym->ns);
2669       else
2670         mio_namespace_ref (&sym->formal_ns);
2671     }
2672   else
2673     {
2674       mio_namespace_ref (&sym->formal_ns);
2675       if (sym->formal_ns)
2676         {
2677           sym->formal_ns->proc_name = sym;
2678           sym->refs++;
2679         }
2680     }
2681
2682   /* Save/restore common block links */
2683   mio_symbol_ref (&sym->common_next);
2684
2685   mio_formal_arglist (sym);
2686
2687   if (sym->attr.flavor == FL_PARAMETER)
2688     mio_expr (&sym->value);
2689
2690   mio_array_spec (&sym->as);
2691
2692   mio_symbol_ref (&sym->result);
2693
2694   /* Note that components are always saved, even if they are supposed
2695      to be private.  Component access is checked during searching.  */
2696
2697   mio_component_list (&sym->components);
2698
2699   if (sym->components != NULL)
2700     sym->component_access =
2701       MIO_NAME(gfc_access) (sym->component_access, access_types);
2702
2703   mio_rparen ();
2704 }
2705
2706
2707 /************************* Top level subroutines *************************/
2708
2709 /* Skip a list between balanced left and right parens.  */
2710
2711 static void
2712 skip_list (void)
2713 {
2714   int level;
2715
2716   level = 0;
2717   do
2718     {
2719       switch (parse_atom ())
2720         {
2721         case ATOM_LPAREN:
2722           level++;
2723           break;
2724
2725         case ATOM_RPAREN:
2726           level--;
2727           break;
2728
2729         case ATOM_STRING:
2730           gfc_free (atom_string);
2731           break;
2732
2733         case ATOM_NAME:
2734         case ATOM_INTEGER:
2735           break;
2736         }
2737     }
2738   while (level > 0);
2739 }
2740
2741
2742 /* Load operator interfaces from the module.  Interfaces are unusual
2743    in that they attach themselves to existing symbols.  */
2744
2745 static void
2746 load_operator_interfaces (void)
2747 {
2748   const char *p;
2749   char name[GFC_MAX_SYMBOL_LEN + 1], module[GFC_MAX_SYMBOL_LEN + 1];
2750   gfc_user_op *uop;
2751
2752   mio_lparen ();
2753
2754   while (peek_atom () != ATOM_RPAREN)
2755     {
2756       mio_lparen ();
2757
2758       mio_internal_string (name);
2759       mio_internal_string (module);
2760
2761       /* Decide if we need to load this one or not.  */
2762       p = find_use_name (name);
2763       if (p == NULL)
2764         {
2765           while (parse_atom () != ATOM_RPAREN);
2766         }
2767       else
2768         {
2769           uop = gfc_get_uop (p);
2770           mio_interface_rest (&uop->operator);
2771         }
2772     }
2773
2774   mio_rparen ();
2775 }
2776
2777
2778 /* Load interfaces from the module.  Interfaces are unusual in that
2779    they attach themselves to existing symbols.  */
2780
2781 static void
2782 load_generic_interfaces (void)
2783 {
2784   const char *p;
2785   char name[GFC_MAX_SYMBOL_LEN + 1], module[GFC_MAX_SYMBOL_LEN + 1];
2786   gfc_symbol *sym;
2787
2788   mio_lparen ();
2789
2790   while (peek_atom () != ATOM_RPAREN)
2791     {
2792       mio_lparen ();
2793
2794       mio_internal_string (name);
2795       mio_internal_string (module);
2796
2797       /* Decide if we need to load this one or not.  */
2798       p = find_use_name (name);
2799
2800       if (p == NULL || gfc_find_symbol (p, NULL, 0, &sym))
2801         {
2802           while (parse_atom () != ATOM_RPAREN);
2803           continue;
2804         }
2805
2806       if (sym == NULL)
2807         {
2808           gfc_get_symbol (p, NULL, &sym);
2809
2810           sym->attr.flavor = FL_PROCEDURE;
2811           sym->attr.generic = 1;
2812           sym->attr.use_assoc = 1;
2813         }
2814
2815       mio_interface_rest (&sym->generic);
2816     }
2817
2818   mio_rparen ();
2819 }
2820
2821
2822 /* Load common blocks.  */
2823
2824 static void
2825 load_commons(void)
2826 {
2827   char name[GFC_MAX_SYMBOL_LEN+1];
2828   gfc_common_head *p;
2829
2830   mio_lparen ();
2831
2832   while (peek_atom () != ATOM_RPAREN)
2833     {
2834       mio_lparen ();
2835       mio_internal_string (name);
2836
2837       p = gfc_get_common (name, 1);
2838
2839       mio_symbol_ref (&p->head);
2840       mio_integer (&p->saved);
2841       p->use_assoc = 1;
2842
2843       mio_rparen();
2844     }
2845
2846   mio_rparen();
2847 }
2848
2849
2850 /* Recursive function to traverse the pointer_info tree and load a
2851    needed symbol.  We return nonzero if we load a symbol and stop the
2852    traversal, because the act of loading can alter the tree.  */
2853
2854 static int
2855 load_needed (pointer_info * p)
2856 {
2857   gfc_namespace *ns;
2858   pointer_info *q;
2859   gfc_symbol *sym;
2860
2861   if (p == NULL)
2862     return 0;
2863   if (load_needed (p->left))
2864     return 1;
2865   if (load_needed (p->right))
2866     return 1;
2867
2868   if (p->type != P_SYMBOL || p->u.rsym.state != NEEDED)
2869     return 0;
2870
2871   p->u.rsym.state = USED;
2872
2873   set_module_locus (&p->u.rsym.where);
2874
2875   sym = p->u.rsym.sym;
2876   if (sym == NULL)
2877     {
2878       q = get_integer (p->u.rsym.ns);
2879
2880       ns = (gfc_namespace *) q->u.pointer;
2881       if (ns == NULL)
2882         {
2883           /* Create an interface namespace if necessary.  These are
2884              the namespaces that hold the formal parameters of module
2885              procedures.  */
2886
2887           ns = gfc_get_namespace (NULL);
2888           associate_integer_pointer (q, ns);
2889         }
2890
2891       sym = gfc_new_symbol (p->u.rsym.true_name, ns);
2892       strcpy (sym->module, p->u.rsym.module);
2893
2894       associate_integer_pointer (p, sym);
2895     }
2896
2897   mio_symbol (sym);
2898   sym->attr.use_assoc = 1;
2899
2900   return 1;
2901 }
2902
2903
2904 /* Recursive function for cleaning up things after a module has been
2905    read.  */
2906
2907 static void
2908 read_cleanup (pointer_info * p)
2909 {
2910   gfc_symtree *st;
2911   pointer_info *q;
2912
2913   if (p == NULL)
2914     return;
2915
2916   read_cleanup (p->left);
2917   read_cleanup (p->right);
2918
2919   if (p->type == P_SYMBOL && p->u.rsym.state == USED && !p->u.rsym.referenced)
2920     {
2921       /* Add hidden symbols to the symtree.  */
2922       q = get_integer (p->u.rsym.ns);
2923       st = get_unique_symtree ((gfc_namespace *) q->u.pointer);
2924
2925       st->n.sym = p->u.rsym.sym;
2926       st->n.sym->refs++;
2927
2928       /* Fixup any symtree references.  */
2929       p->u.rsym.symtree = st;
2930       resolve_fixups (p->u.rsym.stfixup, st);
2931       p->u.rsym.stfixup = NULL;
2932     }
2933
2934   /* Free unused symbols.  */
2935   if (p->type == P_SYMBOL && p->u.rsym.state == UNUSED)
2936     gfc_free_symbol (p->u.rsym.sym);
2937 }
2938
2939
2940 /* Read a module file.  */
2941
2942 static void
2943 read_module (void)
2944 {
2945   module_locus operator_interfaces, user_operators;
2946   const char *p;
2947   char name[GFC_MAX_SYMBOL_LEN + 1];
2948   gfc_intrinsic_op i;
2949   int ambiguous, symbol;
2950   pointer_info *info;
2951   gfc_use_rename *u;
2952   gfc_symtree *st;
2953   gfc_symbol *sym;
2954
2955   get_module_locus (&operator_interfaces);      /* Skip these for now */
2956   skip_list ();
2957
2958   get_module_locus (&user_operators);
2959   skip_list ();
2960   skip_list ();
2961   skip_list ();
2962
2963   mio_lparen ();
2964
2965   /* Create the fixup nodes for all the symbols.  */
2966
2967   while (peek_atom () != ATOM_RPAREN)
2968     {
2969       require_atom (ATOM_INTEGER);
2970       info = get_integer (atom_int);
2971
2972       info->type = P_SYMBOL;
2973       info->u.rsym.state = UNUSED;
2974
2975       mio_internal_string (info->u.rsym.true_name);
2976       mio_internal_string (info->u.rsym.module);
2977
2978       require_atom (ATOM_INTEGER);
2979       info->u.rsym.ns = atom_int;
2980
2981       get_module_locus (&info->u.rsym.where);
2982       skip_list ();
2983
2984       /* See if the symbol has already been loaded by a previous module.
2985          If so, we reference the existing symbol and prevent it from
2986          being loaded again.  */
2987
2988       sym = find_true_name (info->u.rsym.true_name, info->u.rsym.module);
2989       if (sym == NULL)
2990         continue;
2991
2992       info->u.rsym.state = USED;
2993       info->u.rsym.referenced = 1;
2994       info->u.rsym.sym = sym;
2995     }
2996
2997   mio_rparen ();
2998
2999   /* Parse the symtree lists.  This lets us mark which symbols need to
3000      be loaded.  Renaming is also done at this point by replacing the
3001      symtree name.  */
3002
3003   mio_lparen ();
3004
3005   while (peek_atom () != ATOM_RPAREN)
3006     {
3007       mio_internal_string (name);
3008       mio_integer (&ambiguous);
3009       mio_integer (&symbol);
3010
3011       info = get_integer (symbol);
3012
3013       /* Get the local name for this symbol.  */
3014       p = find_use_name (name);
3015
3016       /* Skip symtree nodes not in an ONLY caluse.  */
3017       if (p == NULL)
3018         continue;
3019
3020       /* Check for ambiguous symbols.  */
3021       st = gfc_find_symtree (gfc_current_ns->sym_root, p);
3022
3023       if (st != NULL)
3024         {
3025           if (st->n.sym != info->u.rsym.sym)
3026             st->ambiguous = 1;
3027           info->u.rsym.symtree = st;
3028         }
3029       else
3030         {
3031           /* Create a symtree node in the current namespace for this symbol.  */
3032           st = check_unique_name (p) ? get_unique_symtree (gfc_current_ns) :
3033             gfc_new_symtree (&gfc_current_ns->sym_root, p);
3034
3035           st->ambiguous = ambiguous;
3036
3037           sym = info->u.rsym.sym;
3038
3039           /* Create a symbol node if it doesn't already exist.  */
3040           if (sym == NULL)
3041             {
3042               sym = info->u.rsym.sym =
3043                 gfc_new_symbol (info->u.rsym.true_name, gfc_current_ns);
3044
3045               strcpy (sym->module, info->u.rsym.module);
3046             }
3047
3048           st->n.sym = sym;
3049           st->n.sym->refs++;
3050
3051           /* Store the symtree pointing to this symbol.  */
3052           info->u.rsym.symtree = st;
3053
3054           if (info->u.rsym.state == UNUSED)
3055             info->u.rsym.state = NEEDED;
3056           info->u.rsym.referenced = 1;
3057         }
3058     }
3059
3060   mio_rparen ();
3061
3062   /* Load intrinsic operator interfaces.  */
3063   set_module_locus (&operator_interfaces);
3064   mio_lparen ();
3065
3066   for (i = GFC_INTRINSIC_BEGIN; i != GFC_INTRINSIC_END; i++)
3067     {
3068       if (i == INTRINSIC_USER)
3069         continue;
3070
3071       if (only_flag)
3072         {
3073           u = find_use_operator (i);
3074
3075           if (u == NULL)
3076             {
3077               skip_list ();
3078               continue;
3079             }
3080
3081           u->found = 1;
3082         }
3083
3084       mio_interface (&gfc_current_ns->operator[i]);
3085     }
3086
3087   mio_rparen ();
3088
3089   /* Load generic and user operator interfaces.  These must follow the
3090      loading of symtree because otherwise symbols can be marked as
3091      ambiguous.  */
3092
3093   set_module_locus (&user_operators);
3094
3095   load_operator_interfaces ();
3096   load_generic_interfaces ();
3097
3098   load_commons ();
3099
3100   /* At this point, we read those symbols that are needed but haven't
3101      been loaded yet.  If one symbol requires another, the other gets
3102      marked as NEEDED if its previous state was UNUSED.  */
3103
3104   while (load_needed (pi_root));
3105
3106   /* Make sure all elements of the rename-list were found in the
3107      module.  */
3108
3109   for (u = gfc_rename_list; u; u = u->next)
3110     {
3111       if (u->found)
3112         continue;
3113
3114       if (u->operator == INTRINSIC_NONE)
3115         {
3116           gfc_error ("Symbol '%s' referenced at %L not found in module '%s'",
3117                      u->use_name, &u->where, module_name);
3118           continue;
3119         }
3120
3121       if (u->operator == INTRINSIC_USER)
3122         {
3123           gfc_error
3124             ("User operator '%s' referenced at %L not found in module '%s'",
3125              u->use_name, &u->where, module_name);
3126           continue;
3127         }
3128
3129       gfc_error
3130         ("Intrinsic operator '%s' referenced at %L not found in module "
3131          "'%s'", gfc_op2string (u->operator), &u->where, module_name);
3132     }
3133
3134   gfc_check_interfaces (gfc_current_ns);
3135
3136   /* Clean up symbol nodes that were never loaded, create references
3137      to hidden symbols.  */
3138
3139   read_cleanup (pi_root);
3140 }
3141
3142
3143 /* Given an access type that is specific to an entity and the default
3144    access, return nonzero if we should write the entity.  */
3145
3146 static int
3147 check_access (gfc_access specific_access, gfc_access default_access)
3148 {
3149
3150   if (specific_access == ACCESS_PUBLIC)
3151     return 1;
3152   if (specific_access == ACCESS_PRIVATE)
3153     return 0;
3154
3155   if (gfc_option.flag_module_access_private)
3156     {
3157       if (default_access == ACCESS_PUBLIC)
3158         return 1;
3159     }
3160   else
3161     {
3162       if (default_access != ACCESS_PRIVATE)
3163         return 1;
3164     }
3165
3166   return 0;
3167 }
3168
3169
3170 /* Write a common block to the module */
3171
3172 static void
3173 write_common (gfc_symtree *st)
3174 {
3175   gfc_common_head *p;
3176
3177   if (st == NULL)
3178     return;
3179
3180   write_common(st->left);
3181   write_common(st->right);
3182
3183   mio_lparen();
3184   mio_internal_string(st->name);
3185
3186   p = st->n.common;
3187   mio_symbol_ref(&p->head);
3188   mio_integer(&p->saved);
3189
3190   mio_rparen();
3191 }
3192
3193
3194 /* Write a symbol to the module.  */
3195
3196 static void
3197 write_symbol (int n, gfc_symbol * sym)
3198 {
3199
3200   if (sym->attr.flavor == FL_UNKNOWN || sym->attr.flavor == FL_LABEL)
3201     gfc_internal_error ("write_symbol(): bad module symbol '%s'", sym->name);
3202
3203   mio_integer (&n);
3204   mio_internal_string (sym->name);
3205
3206   mio_internal_string (sym->module);
3207   mio_pointer_ref (&sym->ns);
3208
3209   mio_symbol (sym);
3210   write_char ('\n');
3211 }
3212
3213
3214 /* Recursive traversal function to write the initial set of symbols to
3215    the module.  We check to see if the symbol should be written
3216    according to the access specification.  */
3217
3218 static void
3219 write_symbol0 (gfc_symtree * st)
3220 {
3221   gfc_symbol *sym;
3222   pointer_info *p;
3223
3224   if (st == NULL)
3225     return;
3226
3227   write_symbol0 (st->left);
3228   write_symbol0 (st->right);
3229
3230   sym = st->n.sym;
3231   if (sym->module[0] == '\0')
3232     strcpy (sym->module, module_name);
3233
3234   if (sym->attr.flavor == FL_PROCEDURE && sym->attr.generic
3235       && !sym->attr.subroutine && !sym->attr.function)
3236     return;
3237
3238   if (!check_access (sym->attr.access, sym->ns->default_access))
3239     return;
3240
3241   p = get_pointer (sym);
3242   if (p->type == P_UNKNOWN)
3243     p->type = P_SYMBOL;
3244
3245   if (p->u.wsym.state == WRITTEN)
3246     return;
3247
3248   write_symbol (p->integer, sym);
3249   p->u.wsym.state = WRITTEN;
3250
3251   return;
3252 }
3253
3254
3255 /* Recursive traversal function to write the secondary set of symbols
3256    to the module file.  These are symbols that were not public yet are
3257    needed by the public symbols or another dependent symbol.  The act
3258    of writing a symbol can modify the pointer_info tree, so we cease
3259    traversal if we find a symbol to write.  We return nonzero if a
3260    symbol was written and pass that information upwards.  */
3261
3262 static int
3263 write_symbol1 (pointer_info * p)
3264 {
3265
3266   if (p == NULL)
3267     return 0;
3268
3269   if (write_symbol1 (p->left))
3270     return 1;
3271   if (write_symbol1 (p->right))
3272     return 1;
3273
3274   if (p->type != P_SYMBOL || p->u.wsym.state != NEEDS_WRITE)
3275     return 0;
3276
3277   /* FIXME: This shouldn't be necessary, but it works around
3278      deficiencies in the module loader or/and symbol handling.  */
3279   if (p->u.wsym.sym->module[0] == '\0' && p->u.wsym.sym->attr.dummy)
3280     strcpy (p->u.wsym.sym->module, module_name);
3281
3282   p->u.wsym.state = WRITTEN;
3283   write_symbol (p->integer, p->u.wsym.sym);
3284
3285   return 1;
3286 }
3287
3288
3289 /* Write operator interfaces associated with a symbol.  */
3290
3291 static void
3292 write_operator (gfc_user_op * uop)
3293 {
3294   static char nullstring[] = "";
3295
3296   if (uop->operator == NULL
3297       || !check_access (uop->access, uop->ns->default_access))
3298     return;
3299
3300   mio_symbol_interface (uop->name, nullstring, &uop->operator);
3301 }
3302
3303
3304 /* Write generic interfaces associated with a symbol.  */
3305
3306 static void
3307 write_generic (gfc_symbol * sym)
3308 {
3309
3310   if (sym->generic == NULL
3311       || !check_access (sym->attr.access, sym->ns->default_access))
3312     return;
3313
3314   mio_symbol_interface (sym->name, sym->module, &sym->generic);
3315 }
3316
3317
3318 static void
3319 write_symtree (gfc_symtree * st)
3320 {
3321   gfc_symbol *sym;
3322   pointer_info *p;
3323
3324   sym = st->n.sym;
3325   if (!check_access (sym->attr.access, sym->ns->default_access)
3326       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.generic
3327           && !sym->attr.subroutine && !sym->attr.function))
3328     return;
3329
3330   if (check_unique_name (st->name))
3331     return;
3332
3333   p = find_pointer (sym);
3334   if (p == NULL)
3335     gfc_internal_error ("write_symtree(): Symbol not written");
3336
3337   mio_internal_string (st->name);
3338   mio_integer (&st->ambiguous);
3339   mio_integer (&p->integer);
3340 }
3341
3342
3343 static void
3344 write_module (void)
3345 {
3346   gfc_intrinsic_op i;
3347
3348   /* Write the operator interfaces.  */
3349   mio_lparen ();
3350
3351   for (i = GFC_INTRINSIC_BEGIN; i != GFC_INTRINSIC_END; i++)
3352     {
3353       if (i == INTRINSIC_USER)
3354         continue;
3355
3356       mio_interface (check_access (gfc_current_ns->operator_access[i],
3357                                    gfc_current_ns->default_access)
3358                      ? &gfc_current_ns->operator[i] : NULL);
3359     }
3360
3361   mio_rparen ();
3362   write_char ('\n');
3363   write_char ('\n');
3364
3365   mio_lparen ();
3366   gfc_traverse_user_op (gfc_current_ns, write_operator);
3367   mio_rparen ();
3368   write_char ('\n');
3369   write_char ('\n');
3370
3371   mio_lparen ();
3372   gfc_traverse_ns (gfc_current_ns, write_generic);
3373   mio_rparen ();
3374   write_char ('\n');
3375   write_char ('\n');
3376
3377   mio_lparen ();
3378   write_common (gfc_current_ns->common_root);
3379   mio_rparen ();
3380   write_char ('\n');
3381   write_char ('\n');
3382
3383   /* Write symbol information.  First we traverse all symbols in the
3384      primary namespace, writing those that need to be written.
3385      Sometimes writing one symbol will cause another to need to be
3386      written.  A list of these symbols ends up on the write stack, and
3387      we end by popping the bottom of the stack and writing the symbol
3388      until the stack is empty.  */
3389
3390   mio_lparen ();
3391
3392   write_symbol0 (gfc_current_ns->sym_root);
3393   while (write_symbol1 (pi_root));
3394
3395   mio_rparen ();
3396
3397   write_char ('\n');
3398   write_char ('\n');
3399
3400   mio_lparen ();
3401   gfc_traverse_symtree (gfc_current_ns->sym_root, write_symtree);
3402   mio_rparen ();
3403 }
3404
3405
3406 /* Given module, dump it to disk.  If there was an error while
3407    processing the module, dump_flag will be set to zero and we delete
3408    the module file, even if it was already there.  */
3409
3410 void
3411 gfc_dump_module (const char *name, int dump_flag)
3412 {
3413   char filename[PATH_MAX], *p;
3414   time_t now;
3415
3416   filename[0] = '\0';
3417   if (gfc_option.module_dir != NULL)
3418     strcpy (filename, gfc_option.module_dir);
3419
3420   strcat (filename, name);
3421   strcat (filename, MODULE_EXTENSION);
3422
3423   if (!dump_flag)
3424     {
3425       unlink (filename);
3426       return;
3427     }
3428
3429   module_fp = fopen (filename, "w");
3430   if (module_fp == NULL)
3431     gfc_fatal_error ("Can't open module file '%s' for writing at %C: %s",
3432                      filename, strerror (errno));
3433
3434   now = time (NULL);
3435   p = ctime (&now);
3436
3437   *strchr (p, '\n') = '\0';
3438
3439   fprintf (module_fp, "GFORTRAN module created from %s on %s\n", 
3440            gfc_source_file, p);
3441   fputs ("If you edit this, you'll get what you deserve.\n\n", module_fp);
3442
3443   iomode = IO_OUTPUT;
3444   strcpy (module_name, name);
3445
3446   init_pi_tree ();
3447
3448   write_module ();
3449
3450   free_pi_tree (pi_root);
3451   pi_root = NULL;
3452
3453   write_char ('\n');
3454
3455   if (fclose (module_fp))
3456     gfc_fatal_error ("Error writing module file '%s' for writing: %s",
3457                      filename, strerror (errno));
3458 }
3459
3460
3461 /* Process a USE directive.  */
3462
3463 void
3464 gfc_use_module (void)
3465 {
3466   char filename[GFC_MAX_SYMBOL_LEN + 5];
3467   gfc_state_data *p;
3468   int c, line;
3469
3470   strcpy (filename, module_name);
3471   strcat (filename, MODULE_EXTENSION);
3472
3473   module_fp = gfc_open_included_file (filename);
3474   if (module_fp == NULL)
3475     gfc_fatal_error ("Can't open module file '%s' for reading at %C: %s",
3476                      filename, strerror (errno));
3477
3478   iomode = IO_INPUT;
3479   module_line = 1;
3480   module_column = 1;
3481
3482   /* Skip the first two lines of the module.  */
3483   /* FIXME: Could also check for valid two lines here, instead.  */
3484   line = 0;
3485   while (line < 2)
3486     {
3487       c = module_char ();
3488       if (c == EOF)
3489         bad_module ("Unexpected end of module");
3490       if (c == '\n')
3491         line++;
3492     }
3493
3494   /* Make sure we're not reading the same module that we may be building.  */
3495   for (p = gfc_state_stack; p; p = p->previous)
3496     if (p->state == COMP_MODULE && strcmp (p->sym->name, module_name) == 0)
3497       gfc_fatal_error ("Can't USE the same module we're building!");
3498
3499   init_pi_tree ();
3500   init_true_name_tree ();
3501
3502   read_module ();
3503
3504   free_true_name (true_name_root);
3505   true_name_root = NULL;
3506
3507   free_pi_tree (pi_root);
3508   pi_root = NULL;
3509
3510   fclose (module_fp);
3511 }
3512
3513
3514 void
3515 gfc_module_init_2 (void)
3516 {
3517
3518   last_atom = ATOM_LPAREN;
3519 }
3520
3521
3522 void
3523 gfc_module_done_2 (void)
3524 {
3525
3526   free_rename ();
3527 }