OSDN Git Service

8fce458a65545949749161ce8301ccce52d3703c
[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 g95 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 "match.h"
75 #include "parse.h" /* FIXME */
76
77 #define MODULE_EXTENSION ".mod"
78
79
80 /* Structure that descibes a position within a module file */
81
82 typedef struct
83 {
84   int column, line;
85   fpos_t pos;
86 }
87 module_locus;
88
89
90 typedef enum
91 {
92   P_UNKNOWN = 0, P_OTHER, P_NAMESPACE, P_COMPONENT, P_SYMBOL
93 }
94 pointer_t;
95
96 /* The fixup structure lists pointers to pointers that have to
97    be updated when a pointer value becomes known.  */
98
99 typedef struct fixup_t
100 {
101   void **pointer;
102   struct fixup_t *next;
103 }
104 fixup_t;
105
106
107 /* Structure for holding extra info needed for pointers being read */
108
109 typedef struct pointer_info
110 {
111   BBT_HEADER (pointer_info);
112   int integer;
113   pointer_t type;
114
115   /* The first component of each member of the union is the pointer
116      being stored */
117
118   fixup_t *fixup;
119
120   union
121   {
122     void *pointer;      /* Member for doing pointer searches */
123
124     struct
125     {
126       gfc_symbol *sym;
127       char true_name[GFC_MAX_SYMBOL_LEN + 1], module[GFC_MAX_SYMBOL_LEN + 1];
128       enum
129       { UNUSED, NEEDED, USED }
130       state;
131       int ns, referenced;
132       module_locus where;
133       fixup_t *stfixup;
134       gfc_symtree *symtree;
135     }
136     rsym;
137
138     struct
139     {
140       gfc_symbol *sym;
141       enum
142       { UNREFERENCED = 0, NEEDS_WRITE, WRITTEN }
143       state;
144     }
145     wsym;
146   }
147   u;
148
149 }
150 pointer_info;
151
152 #define gfc_get_pointer_info() gfc_getmem(sizeof(pointer_info))
153
154
155 /* Lists of rename info for the USE statement */
156
157 typedef struct gfc_use_rename
158 {
159   char local_name[GFC_MAX_SYMBOL_LEN + 1], use_name[GFC_MAX_SYMBOL_LEN + 1];
160   struct gfc_use_rename *next;
161   int found;
162   gfc_intrinsic_op operator;
163   locus where;
164 }
165 gfc_use_rename;
166
167 #define gfc_get_use_rename() gfc_getmem(sizeof(gfc_use_rename))
168
169 /* Local variables */
170
171 /* The FILE for the module we're reading or writing.  */
172 static FILE *module_fp;
173
174 /* The name of the module we're reading (USE'ing) or writing.  */
175 static char module_name[GFC_MAX_SYMBOL_LEN + 1];
176
177 static int module_line, module_column, only_flag;
178 static enum
179 { IO_INPUT, IO_OUTPUT }
180 iomode;
181
182 static gfc_use_rename *gfc_rename_list;
183 static pointer_info *pi_root;
184 static int symbol_number;       /* Counter for assigning symbol numbers */
185
186
187
188 /*****************************************************************/
189
190 /* Pointer/integer conversion.  Pointers between structures are stored
191    as integers in the module file.  The next couple of subroutines
192    handle this translation for reading and writing.  */
193
194 /* Recursively free the tree of pointer structures.  */
195
196 static void
197 free_pi_tree (pointer_info * p)
198 {
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.  Asusume 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 void
1334 mio_allocated_string (char **sp)
1335 {
1336
1337   if (iomode == IO_OUTPUT)
1338     write_atom (ATOM_STRING, *sp);
1339   else
1340     {
1341       require_atom (ATOM_STRING);
1342       *sp = atom_string;
1343     }
1344 }
1345
1346
1347 /* Read or write a string that is in static memory or inside of some
1348    already-allocated structure.  */
1349
1350 static void
1351 mio_internal_string (char *string)
1352 {
1353
1354   if (iomode == IO_OUTPUT)
1355     write_atom (ATOM_STRING, string);
1356   else
1357     {
1358       require_atom (ATOM_STRING);
1359       strcpy (string, atom_string);
1360       gfc_free (atom_string);
1361     }
1362 }
1363
1364
1365
1366 typedef enum
1367 { AB_ALLOCATABLE, AB_DIMENSION, AB_EXTERNAL, AB_INTRINSIC, AB_OPTIONAL,
1368   AB_POINTER, AB_SAVE, AB_TARGET, AB_DUMMY, AB_RESULT,
1369   AB_ENTRY, AB_DATA, AB_IN_NAMELIST, AB_IN_COMMON, 
1370   AB_FUNCTION, AB_SUBROUTINE, AB_SEQUENCE, AB_ELEMENTAL, AB_PURE,
1371   AB_RECURSIVE, AB_GENERIC, AB_ALWAYS_EXPLICIT
1372 }
1373 ab_attribute;
1374
1375 static const mstring attr_bits[] =
1376 {
1377     minit ("ALLOCATABLE", AB_ALLOCATABLE),
1378     minit ("DIMENSION", AB_DIMENSION),
1379     minit ("EXTERNAL", AB_EXTERNAL),
1380     minit ("INTRINSIC", AB_INTRINSIC),
1381     minit ("OPTIONAL", AB_OPTIONAL),
1382     minit ("POINTER", AB_POINTER),
1383     minit ("SAVE", AB_SAVE),
1384     minit ("TARGET", AB_TARGET),
1385     minit ("DUMMY", AB_DUMMY),
1386     minit ("RESULT", AB_RESULT),
1387     minit ("ENTRY", AB_ENTRY),
1388     minit ("DATA", AB_DATA),
1389     minit ("IN_NAMELIST", AB_IN_NAMELIST),
1390     minit ("IN_COMMON", AB_IN_COMMON),
1391     minit ("FUNCTION", AB_FUNCTION),
1392     minit ("SUBROUTINE", AB_SUBROUTINE),
1393     minit ("SEQUENCE", AB_SEQUENCE),
1394     minit ("ELEMENTAL", AB_ELEMENTAL),
1395     minit ("PURE", AB_PURE),
1396     minit ("RECURSIVE", AB_RECURSIVE),
1397     minit ("GENERIC", AB_GENERIC),
1398     minit ("ALWAYS_EXPLICIT", AB_ALWAYS_EXPLICIT),
1399     minit (NULL, -1)
1400 };
1401
1402 /* Specialisation of mio_name. */
1403 DECL_MIO_NAME(ab_attribute)
1404 DECL_MIO_NAME(ar_type)
1405 DECL_MIO_NAME(array_type)
1406 DECL_MIO_NAME(bt)
1407 DECL_MIO_NAME(expr_t)
1408 DECL_MIO_NAME(gfc_access)
1409 DECL_MIO_NAME(gfc_intrinsic_op)
1410 DECL_MIO_NAME(ifsrc)
1411 DECL_MIO_NAME(procedure_type)
1412 DECL_MIO_NAME(ref_type)
1413 DECL_MIO_NAME(sym_flavor)
1414 DECL_MIO_NAME(sym_intent)
1415 #undef DECL_MIO_NAME
1416
1417 /* Symbol attributes are stored in list with the first three elements
1418    being the enumerated fields, while the remaining elements (if any)
1419    indicate the individual attribute bits.  The access field is not
1420    saved-- it controls what symbols are exported when a module is
1421    written.  */
1422
1423 static void
1424 mio_symbol_attribute (symbol_attribute * attr)
1425 {
1426   atom_type t;
1427
1428   mio_lparen ();
1429
1430   attr->flavor = MIO_NAME(sym_flavor) (attr->flavor, flavors);
1431   attr->intent = MIO_NAME(sym_intent) (attr->intent, intents);
1432   attr->proc = MIO_NAME(procedure_type) (attr->proc, procedures);
1433   attr->if_source = MIO_NAME(ifsrc) (attr->if_source, ifsrc_types);
1434
1435   if (iomode == IO_OUTPUT)
1436     {
1437       if (attr->allocatable)
1438         MIO_NAME(ab_attribute) (AB_ALLOCATABLE, attr_bits);
1439       if (attr->dimension)
1440         MIO_NAME(ab_attribute) (AB_DIMENSION, attr_bits);
1441       if (attr->external)
1442         MIO_NAME(ab_attribute) (AB_EXTERNAL, attr_bits);
1443       if (attr->intrinsic)
1444         MIO_NAME(ab_attribute) (AB_INTRINSIC, attr_bits);
1445       if (attr->optional)
1446         MIO_NAME(ab_attribute) (AB_OPTIONAL, attr_bits);
1447       if (attr->pointer)
1448         MIO_NAME(ab_attribute) (AB_POINTER, attr_bits);
1449       if (attr->save)
1450         MIO_NAME(ab_attribute) (AB_SAVE, attr_bits);
1451       if (attr->target)
1452         MIO_NAME(ab_attribute) (AB_TARGET, attr_bits);
1453       if (attr->dummy)
1454         MIO_NAME(ab_attribute) (AB_DUMMY, attr_bits);
1455       if (attr->result)
1456         MIO_NAME(ab_attribute) (AB_RESULT, attr_bits);
1457       if (attr->entry)
1458         MIO_NAME(ab_attribute) (AB_ENTRY, attr_bits);
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_ENTRY:
1532               attr->entry = 1;
1533               break;
1534             case AB_DATA:
1535               attr->data = 1;
1536               break;
1537             case AB_IN_NAMELIST:
1538               attr->in_namelist = 1;
1539               break;
1540             case AB_IN_COMMON:
1541               attr->in_common = 1;
1542               break;
1543             case AB_FUNCTION:
1544               attr->function = 1;
1545               break;
1546             case AB_SUBROUTINE:
1547               attr->subroutine = 1;
1548               break;
1549             case AB_GENERIC:
1550               attr->generic = 1;
1551               break;
1552             case AB_SEQUENCE:
1553               attr->sequence = 1;
1554               break;
1555             case AB_ELEMENTAL:
1556               attr->elemental = 1;
1557               break;
1558             case AB_PURE:
1559               attr->pure = 1;
1560               break;
1561             case AB_RECURSIVE:
1562               attr->recursive = 1;
1563               break;
1564             case AB_ALWAYS_EXPLICIT:
1565               attr->always_explicit = 1;
1566               break;
1567             }
1568         }
1569     }
1570 }
1571
1572
1573 static const mstring bt_types[] = {
1574     minit ("INTEGER", BT_INTEGER),
1575     minit ("REAL", BT_REAL),
1576     minit ("COMPLEX", BT_COMPLEX),
1577     minit ("LOGICAL", BT_LOGICAL),
1578     minit ("CHARACTER", BT_CHARACTER),
1579     minit ("DERIVED", BT_DERIVED),
1580     minit ("PROCEDURE", BT_PROCEDURE),
1581     minit ("UNKNOWN", BT_UNKNOWN),
1582     minit (NULL, -1)
1583 };
1584
1585
1586 static void
1587 mio_charlen (gfc_charlen ** clp)
1588 {
1589   gfc_charlen *cl;
1590
1591   mio_lparen ();
1592
1593   if (iomode == IO_OUTPUT)
1594     {
1595       cl = *clp;
1596       if (cl != NULL)
1597         mio_expr (&cl->length);
1598     }
1599   else
1600     {
1601
1602       if (peek_atom () != ATOM_RPAREN)
1603         {
1604           cl = gfc_get_charlen ();
1605           mio_expr (&cl->length);
1606
1607           *clp = cl;
1608
1609           cl->next = gfc_current_ns->cl_list;
1610           gfc_current_ns->cl_list = cl;
1611         }
1612     }
1613
1614   mio_rparen ();
1615 }
1616
1617
1618 /* Return a symtree node with a name that is guaranteed to be unique
1619    within the namespace and corresponds to an illegal fortran name.  */
1620
1621 static gfc_symtree *
1622 get_unique_symtree (gfc_namespace * ns)
1623 {
1624   char name[GFC_MAX_SYMBOL_LEN + 1];
1625   static int serial = 0;
1626
1627   sprintf (name, "@%d", serial++);
1628   return gfc_new_symtree (&ns->sym_root, name);
1629 }
1630
1631
1632 /* See if a name is a generated name.  */
1633
1634 static int
1635 check_unique_name (const char *name)
1636 {
1637
1638   return *name == '@';
1639 }
1640
1641
1642 static void
1643 mio_typespec (gfc_typespec * ts)
1644 {
1645
1646   mio_lparen ();
1647
1648   ts->type = MIO_NAME(bt) (ts->type, bt_types);
1649
1650   if (ts->type != BT_DERIVED)
1651     mio_integer (&ts->kind);
1652   else
1653     mio_symbol_ref (&ts->derived);
1654
1655   mio_charlen (&ts->cl);
1656
1657   mio_rparen ();
1658 }
1659
1660
1661 static const mstring array_spec_types[] = {
1662     minit ("EXPLICIT", AS_EXPLICIT),
1663     minit ("ASSUMED_SHAPE", AS_ASSUMED_SHAPE),
1664     minit ("DEFERRED", AS_DEFERRED),
1665     minit ("ASSUMED_SIZE", AS_ASSUMED_SIZE),
1666     minit (NULL, -1)
1667 };
1668
1669
1670 static void
1671 mio_array_spec (gfc_array_spec ** asp)
1672 {
1673   gfc_array_spec *as;
1674   int i;
1675
1676   mio_lparen ();
1677
1678   if (iomode == IO_OUTPUT)
1679     {
1680       if (*asp == NULL)
1681         goto done;
1682       as = *asp;
1683     }
1684   else
1685     {
1686       if (peek_atom () == ATOM_RPAREN)
1687         {
1688           *asp = NULL;
1689           goto done;
1690         }
1691
1692       *asp = as = gfc_get_array_spec ();
1693     }
1694
1695   mio_integer (&as->rank);
1696   as->type = MIO_NAME(array_type) (as->type, array_spec_types);
1697
1698   for (i = 0; i < as->rank; i++)
1699     {
1700       mio_expr (&as->lower[i]);
1701       mio_expr (&as->upper[i]);
1702     }
1703
1704 done:
1705   mio_rparen ();
1706 }
1707
1708
1709 /* Given a pointer to an array reference structure (which lives in a
1710    gfc_ref structure), find the corresponding array specification
1711    structure.  Storing the pointer in the ref structure doesn't quite
1712    work when loading from a module. Generating code for an array
1713    reference also needs more infomation than just the array spec.  */
1714
1715 static const mstring array_ref_types[] = {
1716     minit ("FULL", AR_FULL),
1717     minit ("ELEMENT", AR_ELEMENT),
1718     minit ("SECTION", AR_SECTION),
1719     minit (NULL, -1)
1720 };
1721
1722 static void
1723 mio_array_ref (gfc_array_ref * ar)
1724 {
1725   int i;
1726
1727   mio_lparen ();
1728   ar->type = MIO_NAME(ar_type) (ar->type, array_ref_types);
1729   mio_integer (&ar->dimen);
1730
1731   switch (ar->type)
1732     {
1733     case AR_FULL:
1734       break;
1735
1736     case AR_ELEMENT:
1737       for (i = 0; i < ar->dimen; i++)
1738         mio_expr (&ar->start[i]);
1739
1740       break;
1741
1742     case AR_SECTION:
1743       for (i = 0; i < ar->dimen; i++)
1744         {
1745           mio_expr (&ar->start[i]);
1746           mio_expr (&ar->end[i]);
1747           mio_expr (&ar->stride[i]);
1748         }
1749
1750       break;
1751
1752     case AR_UNKNOWN:
1753       gfc_internal_error ("mio_array_ref(): Unknown array ref");
1754     }
1755
1756   for (i = 0; i < ar->dimen; i++)
1757     mio_integer ((int *) &ar->dimen_type[i]);
1758
1759   if (iomode == IO_INPUT)
1760     {
1761       ar->where = gfc_current_locus;
1762
1763       for (i = 0; i < ar->dimen; i++)
1764         ar->c_where[i] = gfc_current_locus;
1765     }
1766
1767   mio_rparen ();
1768 }
1769
1770
1771 /* Saves or restores a pointer.  The pointer is converted back and
1772    forth from an integer.  We return the pointer_info pointer so that
1773    the caller can take additional action based on the pointer type.  */
1774
1775 static pointer_info *
1776 mio_pointer_ref (void *gp)
1777 {
1778   pointer_info *p;
1779
1780   if (iomode == IO_OUTPUT)
1781     {
1782       p = get_pointer (*((char **) gp));
1783       write_atom (ATOM_INTEGER, &p->integer);
1784     }
1785   else
1786     {
1787       require_atom (ATOM_INTEGER);
1788       p = add_fixup (atom_int, gp);
1789     }
1790
1791   return p;
1792 }
1793
1794
1795 /* Save and load references to components that occur within
1796    expressions.  We have to describe these references by a number and
1797    by name.  The number is necessary for forward references during
1798    reading, and the name is necessary if the symbol already exists in
1799    the namespace and is not loaded again.  */
1800
1801 static void
1802 mio_component_ref (gfc_component ** cp, gfc_symbol * sym)
1803 {
1804   char name[GFC_MAX_SYMBOL_LEN + 1];
1805   gfc_component *q;
1806   pointer_info *p;
1807
1808   p = mio_pointer_ref (cp);
1809   if (p->type == P_UNKNOWN)
1810     p->type = P_COMPONENT;
1811
1812   if (iomode == IO_OUTPUT)
1813     mio_internal_string ((*cp)->name);
1814   else
1815     {
1816       mio_internal_string (name);
1817
1818       if (sym->components != NULL && p->u.pointer == NULL)
1819         {
1820           /* Symbol already loaded, so search by name.  */
1821           for (q = sym->components; q; q = q->next)
1822             if (strcmp (q->name, name) == 0)
1823               break;
1824
1825           if (q == NULL)
1826             gfc_internal_error ("mio_component_ref(): Component not found");
1827
1828           associate_integer_pointer (p, q);
1829         }
1830
1831       /* Make sure this symbol will eventually be loaded.  */
1832       p = find_pointer2 (sym);
1833       if (p->u.rsym.state == UNUSED)
1834         p->u.rsym.state = NEEDED;
1835     }
1836 }
1837
1838
1839 static void
1840 mio_component (gfc_component * c)
1841 {
1842   pointer_info *p;
1843   int n;
1844
1845   mio_lparen ();
1846
1847   if (iomode == IO_OUTPUT)
1848     {
1849       p = get_pointer (c);
1850       mio_integer (&p->integer);
1851     }
1852   else
1853     {
1854       mio_integer (&n);
1855       p = get_integer (n);
1856       associate_integer_pointer (p, c);
1857     }
1858
1859   if (p->type == P_UNKNOWN)
1860     p->type = P_COMPONENT;
1861
1862   mio_internal_string (c->name);
1863   mio_typespec (&c->ts);
1864   mio_array_spec (&c->as);
1865
1866   mio_integer (&c->dimension);
1867   mio_integer (&c->pointer);
1868
1869   mio_expr (&c->initializer);
1870   mio_rparen ();
1871 }
1872
1873
1874 static void
1875 mio_component_list (gfc_component ** cp)
1876 {
1877   gfc_component *c, *tail;
1878
1879   mio_lparen ();
1880
1881   if (iomode == IO_OUTPUT)
1882     {
1883       for (c = *cp; c; c = c->next)
1884         mio_component (c);
1885     }
1886   else
1887     {
1888
1889       *cp = NULL;
1890       tail = NULL;
1891
1892       for (;;)
1893         {
1894           if (peek_atom () == ATOM_RPAREN)
1895             break;
1896
1897           c = gfc_get_component ();
1898           mio_component (c);
1899
1900           if (tail == NULL)
1901             *cp = c;
1902           else
1903             tail->next = c;
1904
1905           tail = c;
1906         }
1907     }
1908
1909   mio_rparen ();
1910 }
1911
1912
1913 static void
1914 mio_actual_arg (gfc_actual_arglist * a)
1915 {
1916
1917   mio_lparen ();
1918   mio_internal_string (a->name);
1919   mio_expr (&a->expr);
1920   mio_rparen ();
1921 }
1922
1923
1924 static void
1925 mio_actual_arglist (gfc_actual_arglist ** ap)
1926 {
1927   gfc_actual_arglist *a, *tail;
1928
1929   mio_lparen ();
1930
1931   if (iomode == IO_OUTPUT)
1932     {
1933       for (a = *ap; a; a = a->next)
1934         mio_actual_arg (a);
1935
1936     }
1937   else
1938     {
1939       tail = NULL;
1940
1941       for (;;)
1942         {
1943           if (peek_atom () != ATOM_LPAREN)
1944             break;
1945
1946           a = gfc_get_actual_arglist ();
1947
1948           if (tail == NULL)
1949             *ap = a;
1950           else
1951             tail->next = a;
1952
1953           tail = a;
1954           mio_actual_arg (a);
1955         }
1956     }
1957
1958   mio_rparen ();
1959 }
1960
1961
1962 /* Read and write formal argument lists.  */
1963
1964 static void
1965 mio_formal_arglist (gfc_symbol * sym)
1966 {
1967   gfc_formal_arglist *f, *tail;
1968
1969   mio_lparen ();
1970
1971   if (iomode == IO_OUTPUT)
1972     {
1973       for (f = sym->formal; f; f = f->next)
1974         mio_symbol_ref (&f->sym);
1975
1976     }
1977   else
1978     {
1979       sym->formal = tail = NULL;
1980
1981       while (peek_atom () != ATOM_RPAREN)
1982         {
1983           f = gfc_get_formal_arglist ();
1984           mio_symbol_ref (&f->sym);
1985
1986           if (sym->formal == NULL)
1987             sym->formal = f;
1988           else
1989             tail->next = f;
1990
1991           tail = f;
1992         }
1993     }
1994
1995   mio_rparen ();
1996 }
1997
1998
1999 /* Save or restore a reference to a symbol node.  */
2000
2001 void
2002 mio_symbol_ref (gfc_symbol ** symp)
2003 {
2004   pointer_info *p;
2005
2006   p = mio_pointer_ref (symp);
2007   if (p->type == P_UNKNOWN)
2008     p->type = P_SYMBOL;
2009
2010   if (iomode == IO_OUTPUT)
2011     {
2012       if (p->u.wsym.state == UNREFERENCED)
2013         p->u.wsym.state = NEEDS_WRITE;
2014     }
2015   else
2016     {
2017       if (p->u.rsym.state == UNUSED)
2018         p->u.rsym.state = NEEDED;
2019     }
2020 }
2021
2022
2023 /* Save or restore a reference to a symtree node.  */
2024
2025 static void
2026 mio_symtree_ref (gfc_symtree ** stp)
2027 {
2028   pointer_info *p;
2029   fixup_t *f;
2030
2031   if (iomode == IO_OUTPUT)
2032     {
2033       mio_symbol_ref (&(*stp)->n.sym);
2034     }
2035   else
2036     {
2037       require_atom (ATOM_INTEGER);
2038       p = get_integer (atom_int);
2039       if (p->type == P_UNKNOWN)
2040         p->type = P_SYMBOL;
2041
2042       if (p->u.rsym.state == UNUSED)
2043         p->u.rsym.state = NEEDED;
2044
2045       if (p->u.rsym.symtree != NULL)
2046         {
2047           *stp = p->u.rsym.symtree;
2048         }
2049       else
2050         {
2051           f = gfc_getmem (sizeof (fixup_t));
2052
2053           f->next = p->u.rsym.stfixup;
2054           p->u.rsym.stfixup = f;
2055
2056           f->pointer = (void **)stp;
2057         }
2058     }
2059 }
2060
2061 static void
2062 mio_iterator (gfc_iterator ** ip)
2063 {
2064   gfc_iterator *iter;
2065
2066   mio_lparen ();
2067
2068   if (iomode == IO_OUTPUT)
2069     {
2070       if (*ip == NULL)
2071         goto done;
2072     }
2073   else
2074     {
2075       if (peek_atom () == ATOM_RPAREN)
2076         {
2077           *ip = NULL;
2078           goto done;
2079         }
2080
2081       *ip = gfc_get_iterator ();
2082     }
2083
2084   iter = *ip;
2085
2086   mio_expr (&iter->var);
2087   mio_expr (&iter->start);
2088   mio_expr (&iter->end);
2089   mio_expr (&iter->step);
2090
2091 done:
2092   mio_rparen ();
2093 }
2094
2095
2096
2097 static void
2098 mio_constructor (gfc_constructor ** cp)
2099 {
2100   gfc_constructor *c, *tail;
2101
2102   mio_lparen ();
2103
2104   if (iomode == IO_OUTPUT)
2105     {
2106       for (c = *cp; c; c = c->next)
2107         {
2108           mio_lparen ();
2109           mio_expr (&c->expr);
2110           mio_iterator (&c->iterator);
2111           mio_rparen ();
2112         }
2113     }
2114   else
2115     {
2116
2117       *cp = NULL;
2118       tail = NULL;
2119
2120       while (peek_atom () != ATOM_RPAREN)
2121         {
2122           c = gfc_get_constructor ();
2123
2124           if (tail == NULL)
2125             *cp = c;
2126           else
2127             tail->next = c;
2128
2129           tail = c;
2130
2131           mio_lparen ();
2132           mio_expr (&c->expr);
2133           mio_iterator (&c->iterator);
2134           mio_rparen ();
2135         }
2136     }
2137
2138   mio_rparen ();
2139 }
2140
2141
2142
2143 static const mstring ref_types[] = {
2144     minit ("ARRAY", REF_ARRAY),
2145     minit ("COMPONENT", REF_COMPONENT),
2146     minit ("SUBSTRING", REF_SUBSTRING),
2147     minit (NULL, -1)
2148 };
2149
2150
2151 static void
2152 mio_ref (gfc_ref ** rp)
2153 {
2154   gfc_ref *r;
2155
2156   mio_lparen ();
2157
2158   r = *rp;
2159   r->type = MIO_NAME(ref_type) (r->type, ref_types);
2160
2161   switch (r->type)
2162     {
2163     case REF_ARRAY:
2164       mio_array_ref (&r->u.ar);
2165       break;
2166
2167     case REF_COMPONENT:
2168       mio_symbol_ref (&r->u.c.sym);
2169       mio_component_ref (&r->u.c.component, r->u.c.sym);
2170       break;
2171
2172     case REF_SUBSTRING:
2173       mio_expr (&r->u.ss.start);
2174       mio_expr (&r->u.ss.end);
2175       mio_charlen (&r->u.ss.length);
2176       break;
2177     }
2178
2179   mio_rparen ();
2180 }
2181
2182
2183 static void
2184 mio_ref_list (gfc_ref ** rp)
2185 {
2186   gfc_ref *ref, *head, *tail;
2187
2188   mio_lparen ();
2189
2190   if (iomode == IO_OUTPUT)
2191     {
2192       for (ref = *rp; ref; ref = ref->next)
2193         mio_ref (&ref);
2194     }
2195   else
2196     {
2197       head = tail = NULL;
2198
2199       while (peek_atom () != ATOM_RPAREN)
2200         {
2201           if (head == NULL)
2202             head = tail = gfc_get_ref ();
2203           else
2204             {
2205               tail->next = gfc_get_ref ();
2206               tail = tail->next;
2207             }
2208
2209           mio_ref (&tail);
2210         }
2211
2212       *rp = head;
2213     }
2214
2215   mio_rparen ();
2216 }
2217
2218
2219 /* Read and write an integer value.  */
2220
2221 static void
2222 mio_gmp_integer (mpz_t * integer)
2223 {
2224   char *p;
2225
2226   if (iomode == IO_INPUT)
2227     {
2228       if (parse_atom () != ATOM_STRING)
2229         bad_module ("Expected integer string");
2230
2231       mpz_init (*integer);
2232       if (mpz_set_str (*integer, atom_string, 10))
2233         bad_module ("Error converting integer");
2234
2235       gfc_free (atom_string);
2236
2237     }
2238   else
2239     {
2240       p = mpz_get_str (NULL, 10, *integer);
2241       write_atom (ATOM_STRING, p);
2242       gfc_free (p);
2243     }
2244 }
2245
2246
2247 static void
2248 mio_gmp_real (mpf_t * real)
2249 {
2250   mp_exp_t exponent;
2251   char *p;
2252
2253   if (iomode == IO_INPUT)
2254     {
2255       if (parse_atom () != ATOM_STRING)
2256         bad_module ("Expected real string");
2257
2258       mpf_init (*real);
2259       mpf_set_str (*real, atom_string, -16);
2260       gfc_free (atom_string);
2261
2262     }
2263   else
2264     {
2265       p = mpf_get_str (NULL, &exponent, 16, 0, *real);
2266       atom_string = gfc_getmem (strlen (p) + 20);
2267
2268       sprintf (atom_string, "0.%s@%ld", p, exponent);
2269
2270       /* Fix negative numbers.  */
2271       if (atom_string[2] == '-')
2272         {
2273           atom_string[0] = '-';
2274           atom_string[1] = '0';
2275           atom_string[2] = '.';
2276         }
2277
2278       write_atom (ATOM_STRING, atom_string);
2279
2280       gfc_free (atom_string);
2281       gfc_free (p);
2282     }
2283 }
2284
2285
2286 /* Save and restore the shape of an array constructor.  */
2287
2288 static void
2289 mio_shape (mpz_t ** pshape, int rank)
2290 {
2291   mpz_t *shape;
2292   atom_type t;
2293   int n;
2294
2295   /* A NULL shape is represented by ().  */
2296   mio_lparen ();
2297
2298   if (iomode == IO_OUTPUT)
2299     {
2300       shape = *pshape;
2301       if (!shape)
2302         {
2303           mio_rparen ();
2304           return;
2305         }
2306     }
2307   else
2308     {
2309       t = peek_atom ();
2310       if (t == ATOM_RPAREN)
2311         {
2312           *pshape = NULL;
2313           mio_rparen ();
2314           return;
2315         }
2316
2317       shape = gfc_get_shape (rank);
2318       *pshape = shape;
2319     }
2320
2321   for (n = 0; n < rank; n++)
2322     mio_gmp_integer (&shape[n]);
2323
2324   mio_rparen ();
2325 }
2326
2327
2328 static const mstring expr_types[] = {
2329     minit ("OP", EXPR_OP),
2330     minit ("FUNCTION", EXPR_FUNCTION),
2331     minit ("CONSTANT", EXPR_CONSTANT),
2332     minit ("VARIABLE", EXPR_VARIABLE),
2333     minit ("SUBSTRING", EXPR_SUBSTRING),
2334     minit ("STRUCTURE", EXPR_STRUCTURE),
2335     minit ("ARRAY", EXPR_ARRAY),
2336     minit ("NULL", EXPR_NULL),
2337     minit (NULL, -1)
2338 };
2339
2340 /* INTRINSIC_ASSIGN is missing because it is used as an index for
2341    generic operators, not in expressions.  INTRINSIC_USER is also
2342    replaced by the correct function name by the time we see it. */
2343
2344 static const mstring intrinsics[] =
2345 {
2346     minit ("UPLUS", INTRINSIC_UPLUS),
2347     minit ("UMINUS", INTRINSIC_UMINUS),
2348     minit ("PLUS", INTRINSIC_PLUS),
2349     minit ("MINUS", INTRINSIC_MINUS),
2350     minit ("TIMES", INTRINSIC_TIMES),
2351     minit ("DIVIDE", INTRINSIC_DIVIDE),
2352     minit ("POWER", INTRINSIC_POWER),
2353     minit ("CONCAT", INTRINSIC_CONCAT),
2354     minit ("AND", INTRINSIC_AND),
2355     minit ("OR", INTRINSIC_OR),
2356     minit ("EQV", INTRINSIC_EQV),
2357     minit ("NEQV", INTRINSIC_NEQV),
2358     minit ("EQ", INTRINSIC_EQ),
2359     minit ("NE", INTRINSIC_NE),
2360     minit ("GT", INTRINSIC_GT),
2361     minit ("GE", INTRINSIC_GE),
2362     minit ("LT", INTRINSIC_LT),
2363     minit ("LE", INTRINSIC_LE),
2364     minit ("NOT", INTRINSIC_NOT),
2365     minit (NULL, -1)
2366 };
2367
2368 /* Read and write expressions.  The form "()" is allowed to indicate a
2369    NULL expression.  */
2370
2371 static void
2372 mio_expr (gfc_expr ** ep)
2373 {
2374   gfc_expr *e;
2375   atom_type t;
2376   int flag;
2377
2378   mio_lparen ();
2379
2380   if (iomode == IO_OUTPUT)
2381     {
2382       if (*ep == NULL)
2383         {
2384           mio_rparen ();
2385           return;
2386         }
2387
2388       e = *ep;
2389       MIO_NAME(expr_t) (e->expr_type, expr_types);
2390
2391     }
2392   else
2393     {
2394       t = parse_atom ();
2395       if (t == ATOM_RPAREN)
2396         {
2397           *ep = NULL;
2398           return;
2399         }
2400
2401       if (t != ATOM_NAME)
2402         bad_module ("Expected expression type");
2403
2404       e = *ep = gfc_get_expr ();
2405       e->where = gfc_current_locus;
2406       e->expr_type = (expr_t) find_enum (expr_types);
2407     }
2408
2409   mio_typespec (&e->ts);
2410   mio_integer (&e->rank);
2411
2412   switch (e->expr_type)
2413     {
2414     case EXPR_OP:
2415       e->operator = MIO_NAME(gfc_intrinsic_op) (e->operator, intrinsics);
2416
2417       switch (e->operator)
2418         {
2419         case INTRINSIC_UPLUS:
2420         case INTRINSIC_UMINUS:
2421         case INTRINSIC_NOT:
2422           mio_expr (&e->op1);
2423           break;
2424
2425         case INTRINSIC_PLUS:
2426         case INTRINSIC_MINUS:
2427         case INTRINSIC_TIMES:
2428         case INTRINSIC_DIVIDE:
2429         case INTRINSIC_POWER:
2430         case INTRINSIC_CONCAT:
2431         case INTRINSIC_AND:
2432         case INTRINSIC_OR:
2433         case INTRINSIC_EQV:
2434         case INTRINSIC_NEQV:
2435         case INTRINSIC_EQ:
2436         case INTRINSIC_NE:
2437         case INTRINSIC_GT:
2438         case INTRINSIC_GE:
2439         case INTRINSIC_LT:
2440         case INTRINSIC_LE:
2441           mio_expr (&e->op1);
2442           mio_expr (&e->op2);
2443           break;
2444
2445         default:
2446           bad_module ("Bad operator");
2447         }
2448
2449       break;
2450
2451     case EXPR_FUNCTION:
2452       mio_symtree_ref (&e->symtree);
2453       mio_actual_arglist (&e->value.function.actual);
2454
2455       if (iomode == IO_OUTPUT)
2456         {
2457           mio_allocated_string (&e->value.function.name);
2458           flag = e->value.function.esym != NULL;
2459           mio_integer (&flag);
2460           if (flag)
2461             mio_symbol_ref (&e->value.function.esym);
2462           else
2463             write_atom (ATOM_STRING, e->value.function.isym->name);
2464
2465         }
2466       else
2467         {
2468           require_atom (ATOM_STRING);
2469           e->value.function.name = gfc_get_string (atom_string);
2470           gfc_free (atom_string);
2471
2472           mio_integer (&flag);
2473           if (flag)
2474             mio_symbol_ref (&e->value.function.esym);
2475           else
2476             {
2477               require_atom (ATOM_STRING);
2478               e->value.function.isym = gfc_find_function (atom_string);
2479               gfc_free (atom_string);
2480             }
2481         }
2482
2483       break;
2484
2485     case EXPR_VARIABLE:
2486       mio_symtree_ref (&e->symtree);
2487       mio_ref_list (&e->ref);
2488       break;
2489
2490     case EXPR_SUBSTRING:
2491       mio_allocated_string (&e->value.character.string);
2492       mio_expr (&e->op1);
2493       mio_expr (&e->op2);
2494       break;
2495
2496     case EXPR_STRUCTURE:
2497     case EXPR_ARRAY:
2498       mio_constructor (&e->value.constructor);
2499       mio_shape (&e->shape, e->rank);
2500       break;
2501
2502     case EXPR_CONSTANT:
2503       switch (e->ts.type)
2504         {
2505         case BT_INTEGER:
2506           mio_gmp_integer (&e->value.integer);
2507           break;
2508
2509         case BT_REAL:
2510           mio_gmp_real (&e->value.real);
2511           break;
2512
2513         case BT_COMPLEX:
2514           mio_gmp_real (&e->value.complex.r);
2515           mio_gmp_real (&e->value.complex.i);
2516           break;
2517
2518         case BT_LOGICAL:
2519           mio_integer (&e->value.logical);
2520           break;
2521
2522         case BT_CHARACTER:
2523           mio_integer (&e->value.character.length);
2524           mio_allocated_string (&e->value.character.string);
2525           break;
2526
2527         default:
2528           bad_module ("Bad type in constant expression");
2529         }
2530
2531       break;
2532
2533     case EXPR_NULL:
2534       break;
2535     }
2536
2537   mio_rparen ();
2538 }
2539
2540
2541 /* Save/restore lists of gfc_interface stuctures.  When loading an
2542    interface, we are really appending to the existing list of
2543    interfaces.  Checking for duplicate and ambiguous interfaces has to
2544    be done later when all symbols have been loaded.  */
2545
2546 static void
2547 mio_interface_rest (gfc_interface ** ip)
2548 {
2549   gfc_interface *tail, *p;
2550
2551   if (iomode == IO_OUTPUT)
2552     {
2553       if (ip != NULL)
2554         for (p = *ip; p; p = p->next)
2555           mio_symbol_ref (&p->sym);
2556     }
2557   else
2558     {
2559
2560       if (*ip == NULL)
2561         tail = NULL;
2562       else
2563         {
2564           tail = *ip;
2565           while (tail->next)
2566             tail = tail->next;
2567         }
2568
2569       for (;;)
2570         {
2571           if (peek_atom () == ATOM_RPAREN)
2572             break;
2573
2574           p = gfc_get_interface ();
2575           mio_symbol_ref (&p->sym);
2576
2577           if (tail == NULL)
2578             *ip = p;
2579           else
2580             tail->next = p;
2581
2582           tail = p;
2583         }
2584     }
2585
2586   mio_rparen ();
2587 }
2588
2589
2590 /* Save/restore a nameless operator interface.  */
2591
2592 static void
2593 mio_interface (gfc_interface ** ip)
2594 {
2595
2596   mio_lparen ();
2597   mio_interface_rest (ip);
2598 }
2599
2600
2601 /* Save/restore a named operator interface.  */
2602
2603 static void
2604 mio_symbol_interface (char *name, char *module,
2605                       gfc_interface ** ip)
2606 {
2607
2608   mio_lparen ();
2609
2610   mio_internal_string (name);
2611   mio_internal_string (module);
2612
2613   mio_interface_rest (ip);
2614 }
2615
2616
2617 static void
2618 mio_namespace_ref (gfc_namespace ** nsp)
2619 {
2620   gfc_namespace *ns;
2621   pointer_info *p;
2622
2623   p = mio_pointer_ref (nsp);
2624
2625   if (p->type == P_UNKNOWN)
2626     p->type = P_NAMESPACE;
2627
2628   if (iomode == IO_INPUT && p->integer != 0 && p->u.pointer == NULL)
2629     {
2630       ns = gfc_get_namespace (NULL);
2631       associate_integer_pointer (p, ns);
2632     }
2633 }
2634
2635
2636 /* Unlike most other routines, the address of the symbol node is
2637    already fixed on input and the name/module has already been filled
2638    in.  */
2639
2640 static void
2641 mio_symbol (gfc_symbol * sym)
2642 {
2643   gfc_formal_arglist *formal;
2644
2645   mio_lparen ();
2646
2647   mio_symbol_attribute (&sym->attr);
2648   mio_typespec (&sym->ts);
2649
2650   /* Contained procedures don't have formal namespaces.  Instead we output the
2651      procedure namespace.  The will contain the formal arguments.  */
2652   if (iomode == IO_OUTPUT)
2653     {
2654       formal = sym->formal;
2655       while (formal && !formal->sym)
2656         formal = formal->next;
2657
2658       if (formal)
2659         mio_namespace_ref (&formal->sym->ns);
2660       else
2661         mio_namespace_ref (&sym->formal_ns);
2662     }
2663   else
2664     {
2665       mio_namespace_ref (&sym->formal_ns);
2666       if (sym->formal_ns)
2667         {
2668           sym->formal_ns->proc_name = sym;
2669           sym->refs++;
2670         }
2671     }
2672
2673   /* Save/restore common block links */
2674   mio_symbol_ref (&sym->common_next);
2675
2676   mio_formal_arglist (sym);
2677
2678   if (sym->attr.flavor == FL_PARAMETER)
2679     mio_expr (&sym->value);
2680
2681   mio_array_spec (&sym->as);
2682
2683   mio_symbol_ref (&sym->result);
2684
2685   /* Note that components are always saved, even if they are supposed
2686      to be private.  Component access is checked during searching.  */
2687
2688   mio_component_list (&sym->components);
2689
2690   if (sym->components != NULL)
2691     sym->component_access =
2692       MIO_NAME(gfc_access) (sym->component_access, access_types);
2693
2694   mio_rparen ();
2695 }
2696
2697
2698 /************************* Top level subroutines *************************/
2699
2700 /* Skip a list between balanced left and right parens.  */
2701
2702 static void
2703 skip_list (void)
2704 {
2705   int level;
2706
2707   level = 0;
2708   do
2709     {
2710       switch (parse_atom ())
2711         {
2712         case ATOM_LPAREN:
2713           level++;
2714           break;
2715
2716         case ATOM_RPAREN:
2717           level--;
2718           break;
2719
2720         case ATOM_STRING:
2721           gfc_free (atom_string);
2722           break;
2723
2724         case ATOM_NAME:
2725         case ATOM_INTEGER:
2726           break;
2727         }
2728     }
2729   while (level > 0);
2730 }
2731
2732
2733 /* Load operator interfaces from the module.  Interfaces are unusual
2734    in that they attach themselves to existing symbols.  */
2735
2736 static void
2737 load_operator_interfaces (void)
2738 {
2739   const char *p;
2740   char name[GFC_MAX_SYMBOL_LEN + 1], module[GFC_MAX_SYMBOL_LEN + 1];
2741   gfc_user_op *uop;
2742
2743   mio_lparen ();
2744
2745   while (peek_atom () != ATOM_RPAREN)
2746     {
2747       mio_lparen ();
2748
2749       mio_internal_string (name);
2750       mio_internal_string (module);
2751
2752       /* Decide if we need to load this one or not.  */
2753       p = find_use_name (name);
2754       if (p == NULL)
2755         {
2756           while (parse_atom () != ATOM_RPAREN);
2757         }
2758       else
2759         {
2760           uop = gfc_get_uop (p);
2761           mio_interface_rest (&uop->operator);
2762         }
2763     }
2764
2765   mio_rparen ();
2766 }
2767
2768
2769 /* Load interfaces from the module.  Interfaces are unusual in that
2770    they attach themselves to existing symbols.  */
2771
2772 static void
2773 load_generic_interfaces (void)
2774 {
2775   const char *p;
2776   char name[GFC_MAX_SYMBOL_LEN + 1], module[GFC_MAX_SYMBOL_LEN + 1];
2777   gfc_symbol *sym;
2778
2779   mio_lparen ();
2780
2781   while (peek_atom () != ATOM_RPAREN)
2782     {
2783       mio_lparen ();
2784
2785       mio_internal_string (name);
2786       mio_internal_string (module);
2787
2788       /* Decide if we need to load this one or not.  */
2789       p = find_use_name (name);
2790
2791       if (p == NULL || gfc_find_symbol (p, NULL, 0, &sym))
2792         {
2793           while (parse_atom () != ATOM_RPAREN);
2794           continue;
2795         }
2796
2797       if (sym == NULL)
2798         {
2799           gfc_get_symbol (p, NULL, &sym);
2800
2801           sym->attr.flavor = FL_PROCEDURE;
2802           sym->attr.generic = 1;
2803           sym->attr.use_assoc = 1;
2804         }
2805
2806       mio_interface_rest (&sym->generic);
2807     }
2808
2809   mio_rparen ();
2810 }
2811
2812
2813 /* Load common blocks.  */
2814
2815 static void
2816 load_commons(void)
2817 {
2818   char name[GFC_MAX_SYMBOL_LEN+1];
2819   gfc_common_head *p;
2820
2821   mio_lparen ();
2822
2823   while (peek_atom () != ATOM_RPAREN)
2824     {
2825       mio_lparen ();
2826       mio_internal_string (name);
2827
2828       p = gfc_get_common (name);
2829
2830       mio_symbol_ref (&p->head);
2831       mio_integer (&p->saved);
2832       p->use_assoc = 1;
2833
2834       mio_rparen();
2835     }
2836
2837   mio_rparen();
2838 }
2839
2840
2841 /* Recursive function to traverse the pointer_info tree and load a
2842    needed symbol.  We return nonzero if we load a symbol and stop the
2843    traversal, because the act of loading can alter the tree.  */
2844
2845 static int
2846 load_needed (pointer_info * p)
2847 {
2848   gfc_namespace *ns;
2849   pointer_info *q;
2850   gfc_symbol *sym;
2851
2852   if (p == NULL)
2853     return 0;
2854   if (load_needed (p->left))
2855     return 1;
2856   if (load_needed (p->right))
2857     return 1;
2858
2859   if (p->type != P_SYMBOL || p->u.rsym.state != NEEDED)
2860     return 0;
2861
2862   p->u.rsym.state = USED;
2863
2864   set_module_locus (&p->u.rsym.where);
2865
2866   sym = p->u.rsym.sym;
2867   if (sym == NULL)
2868     {
2869       q = get_integer (p->u.rsym.ns);
2870
2871       ns = (gfc_namespace *) q->u.pointer;
2872       if (ns == NULL)
2873         {
2874           /* Create an interface namespace if necessary.  These are
2875              the namespaces that hold the formal parameters of module
2876              procedures.  */
2877
2878           ns = gfc_get_namespace (NULL);
2879           associate_integer_pointer (q, ns);
2880         }
2881
2882       sym = gfc_new_symbol (p->u.rsym.true_name, ns);
2883       strcpy (sym->module, p->u.rsym.module);
2884
2885       associate_integer_pointer (p, sym);
2886     }
2887
2888   mio_symbol (sym);
2889   sym->attr.use_assoc = 1;
2890
2891   return 1;
2892 }
2893
2894
2895 /* Recursive function for cleaning up things after a module has been
2896    read.  */
2897
2898 static void
2899 read_cleanup (pointer_info * p)
2900 {
2901   gfc_symtree *st;
2902   pointer_info *q;
2903
2904   if (p == NULL)
2905     return;
2906
2907   read_cleanup (p->left);
2908   read_cleanup (p->right);
2909
2910   if (p->type == P_SYMBOL && p->u.rsym.state == USED && !p->u.rsym.referenced)
2911     {
2912       /* Add hidden symbols to the symtree.  */
2913       q = get_integer (p->u.rsym.ns);
2914       st = get_unique_symtree ((gfc_namespace *) q->u.pointer);
2915
2916       st->n.sym = p->u.rsym.sym;
2917       st->n.sym->refs++;
2918
2919       /* Fixup any symtree references.  */
2920       p->u.rsym.symtree = st;
2921       resolve_fixups (p->u.rsym.stfixup, st);
2922       p->u.rsym.stfixup = NULL;
2923     }
2924
2925   /* Free unused symbols.  */
2926   if (p->type == P_SYMBOL && p->u.rsym.state == UNUSED)
2927     gfc_free_symbol (p->u.rsym.sym);
2928 }
2929
2930
2931 /* Read a module file.  */
2932
2933 static void
2934 read_module (void)
2935 {
2936   module_locus operator_interfaces, user_operators;
2937   const char *p;
2938   char name[GFC_MAX_SYMBOL_LEN + 1];
2939   gfc_intrinsic_op i;
2940   int ambiguous, symbol;
2941   pointer_info *info;
2942   gfc_use_rename *u;
2943   gfc_symtree *st;
2944   gfc_symbol *sym;
2945
2946   get_module_locus (&operator_interfaces);      /* Skip these for now */
2947   skip_list ();
2948
2949   get_module_locus (&user_operators);
2950   skip_list ();
2951   skip_list ();
2952   skip_list ();
2953
2954   mio_lparen ();
2955
2956   /* Create the fixup nodes for all the symbols.  */
2957
2958   while (peek_atom () != ATOM_RPAREN)
2959     {
2960       require_atom (ATOM_INTEGER);
2961       info = get_integer (atom_int);
2962
2963       info->type = P_SYMBOL;
2964       info->u.rsym.state = UNUSED;
2965
2966       mio_internal_string (info->u.rsym.true_name);
2967       mio_internal_string (info->u.rsym.module);
2968
2969       require_atom (ATOM_INTEGER);
2970       info->u.rsym.ns = atom_int;
2971
2972       get_module_locus (&info->u.rsym.where);
2973       skip_list ();
2974
2975       /* See if the symbol has already been loaded by a previous module.
2976          If so, we reference the existing symbol and prevent it from
2977          being loaded again.  */
2978
2979       sym = find_true_name (info->u.rsym.true_name, info->u.rsym.module);
2980       if (sym == NULL)
2981         continue;
2982
2983       info->u.rsym.state = USED;
2984       info->u.rsym.referenced = 1;
2985       info->u.rsym.sym = sym;
2986     }
2987
2988   mio_rparen ();
2989
2990   /* Parse the symtree lists.  This lets us mark which symbols need to
2991      be loaded.  Renaming is also done at this point by replacing the
2992      symtree name.  */
2993
2994   mio_lparen ();
2995
2996   while (peek_atom () != ATOM_RPAREN)
2997     {
2998       mio_internal_string (name);
2999       mio_integer (&ambiguous);
3000       mio_integer (&symbol);
3001
3002       info = get_integer (symbol);
3003
3004       /* Get the local name for this symbol.  */
3005       p = find_use_name (name);
3006
3007       /* Skip symtree nodes not in an ONLY caluse.  */
3008       if (p == NULL)
3009         continue;
3010
3011       /* Check for ambiguous symbols.  */
3012       st = gfc_find_symtree (gfc_current_ns->sym_root, p);
3013
3014       if (st != NULL)
3015         {
3016           if (st->n.sym != info->u.rsym.sym)
3017             st->ambiguous = 1;
3018           info->u.rsym.symtree = st;
3019         }
3020       else
3021         {
3022           /* Create a symtree node in the current namespace for this symbol.  */
3023           st = check_unique_name (p) ? get_unique_symtree (gfc_current_ns) :
3024             gfc_new_symtree (&gfc_current_ns->sym_root, p);
3025
3026           st->ambiguous = ambiguous;
3027
3028           sym = info->u.rsym.sym;
3029
3030           /* Create a symbol node if it doesn't already exist.  */
3031           if (sym == NULL)
3032             {
3033               sym = info->u.rsym.sym =
3034                 gfc_new_symbol (info->u.rsym.true_name, gfc_current_ns);
3035
3036               strcpy (sym->module, info->u.rsym.module);
3037             }
3038
3039           st->n.sym = sym;
3040           st->n.sym->refs++;
3041
3042           /* Store the symtree pointing to this symbol.  */
3043           info->u.rsym.symtree = st;
3044
3045           if (info->u.rsym.state == UNUSED)
3046             info->u.rsym.state = NEEDED;
3047           info->u.rsym.referenced = 1;
3048         }
3049     }
3050
3051   mio_rparen ();
3052
3053   /* Load intrinsic operator interfaces.  */
3054   set_module_locus (&operator_interfaces);
3055   mio_lparen ();
3056
3057   for (i = GFC_INTRINSIC_BEGIN; i != GFC_INTRINSIC_END; i++)
3058     {
3059       if (i == INTRINSIC_USER)
3060         continue;
3061
3062       if (only_flag)
3063         {
3064           u = find_use_operator (i);
3065
3066           if (u == NULL)
3067             {
3068               skip_list ();
3069               continue;
3070             }
3071
3072           u->found = 1;
3073         }
3074
3075       mio_interface (&gfc_current_ns->operator[i]);
3076     }
3077
3078   mio_rparen ();
3079
3080   /* Load generic and user operator interfaces.  These must follow the
3081      loading of symtree because otherwise symbols can be marked as
3082      ambiguous.  */
3083
3084   set_module_locus (&user_operators);
3085
3086   load_operator_interfaces ();
3087   load_generic_interfaces ();
3088
3089   load_commons ();
3090
3091   /* At this point, we read those symbols that are needed but haven't
3092      been loaded yet.  If one symbol requires another, the other gets
3093      marked as NEEDED if its previous state was UNUSED.  */
3094
3095   while (load_needed (pi_root));
3096
3097   /* Make sure all elements of the rename-list were found in the
3098      module.  */
3099
3100   for (u = gfc_rename_list; u; u = u->next)
3101     {
3102       if (u->found)
3103         continue;
3104
3105       if (u->operator == INTRINSIC_NONE)
3106         {
3107           gfc_error ("Symbol '%s' referenced at %L not found in module '%s'",
3108                      u->use_name, &u->where, module_name);
3109           continue;
3110         }
3111
3112       if (u->operator == INTRINSIC_USER)
3113         {
3114           gfc_error
3115             ("User operator '%s' referenced at %L not found in module '%s'",
3116              u->use_name, &u->where, module_name);
3117           continue;
3118         }
3119
3120       gfc_error
3121         ("Intrinsic operator '%s' referenced at %L not found in module "
3122          "'%s'", gfc_op2string (u->operator), &u->where, module_name);
3123     }
3124
3125   gfc_check_interfaces (gfc_current_ns);
3126
3127   /* Clean up symbol nodes that were never loaded, create references
3128      to hidden symbols.  */
3129
3130   read_cleanup (pi_root);
3131 }
3132
3133
3134 /* Given an access type that is specific to an entity and the default
3135    access, return nonzero if we should write the entity.  */
3136
3137 static int
3138 check_access (gfc_access specific_access, gfc_access default_access)
3139 {
3140
3141   if (specific_access == ACCESS_PUBLIC)
3142     return 1;
3143   if (specific_access == ACCESS_PRIVATE)
3144     return 0;
3145
3146   if (gfc_option.flag_module_access_private)
3147     {
3148       if (default_access == ACCESS_PUBLIC)
3149         return 1;
3150     }
3151   else
3152     {
3153       if (default_access != ACCESS_PRIVATE)
3154         return 1;
3155     }
3156
3157   return 0;
3158 }
3159
3160
3161 /* Write a common block to the module */
3162
3163 static void
3164 write_common (gfc_symtree *st)
3165 {
3166   gfc_common_head *p;
3167
3168   if (st == NULL)
3169     return;
3170
3171   write_common(st->left);
3172   write_common(st->right);
3173
3174   mio_lparen();
3175   mio_internal_string(st->name);
3176
3177   p = st->n.common;
3178   mio_symbol_ref(&p->head);
3179   mio_integer(&p->saved);
3180
3181   mio_rparen();
3182 }
3183
3184
3185 /* Write a symbol to the module.  */
3186
3187 static void
3188 write_symbol (int n, gfc_symbol * sym)
3189 {
3190
3191   if (sym->attr.flavor == FL_UNKNOWN || sym->attr.flavor == FL_LABEL)
3192     gfc_internal_error ("write_symbol(): bad module symbol '%s'", sym->name);
3193
3194   mio_integer (&n);
3195   mio_internal_string (sym->name);
3196
3197   if (sym->module[0] == '\0')
3198     strcpy (sym->module, module_name);
3199
3200   mio_internal_string (sym->module);
3201   mio_pointer_ref (&sym->ns);
3202
3203   mio_symbol (sym);
3204   write_char ('\n');
3205 }
3206
3207
3208 /* Recursive traversal function to write the initial set of symbols to
3209    the module.  We check to see if the symbol should be written
3210    according to the access specification.  */
3211
3212 static void
3213 write_symbol0 (gfc_symtree * st)
3214 {
3215   gfc_symbol *sym;
3216   pointer_info *p;
3217
3218   if (st == NULL)
3219     return;
3220
3221   write_symbol0 (st->left);
3222   write_symbol0 (st->right);
3223
3224   sym = st->n.sym;
3225
3226   if (sym->attr.flavor == FL_PROCEDURE && sym->attr.generic
3227       && !sym->attr.subroutine && !sym->attr.function)
3228     return;
3229
3230   if (!check_access (sym->attr.access, sym->ns->default_access))
3231     return;
3232
3233   p = get_pointer (sym);
3234   if (p->type == P_UNKNOWN)
3235     p->type = P_SYMBOL;
3236
3237   if (p->u.wsym.state == WRITTEN)
3238     return;
3239
3240   write_symbol (p->integer, sym);
3241   p->u.wsym.state = WRITTEN;
3242
3243   return;
3244 }
3245
3246
3247 /* Recursive traversal function to write the secondary set of symbols
3248    to the module file.  These are symbols that were not public yet are
3249    needed by the public symbols or another dependent symbol.  The act
3250    of writing a symbol can modify the pointer_info tree, so we cease
3251    traversal if we find a symbol to write.  We return nonzero if a
3252    symbol was written and pass that information upwards.  */
3253
3254 static int
3255 write_symbol1 (pointer_info * p)
3256 {
3257
3258   if (p == NULL)
3259     return 0;
3260
3261   if (write_symbol1 (p->left))
3262     return 1;
3263   if (write_symbol1 (p->right))
3264     return 1;
3265
3266   if (p->type != P_SYMBOL || p->u.wsym.state != NEEDS_WRITE)
3267     return 0;
3268
3269   p->u.wsym.state = WRITTEN;
3270   write_symbol (p->integer, p->u.wsym.sym);
3271
3272   return 1;
3273 }
3274
3275
3276 /* Write operator interfaces associated with a symbol.  */
3277
3278 static void
3279 write_operator (gfc_user_op * uop)
3280 {
3281   static char nullstring[] = "";
3282
3283   if (uop->operator == NULL
3284       || !check_access (uop->access, uop->ns->default_access))
3285     return;
3286
3287   mio_symbol_interface (uop->name, nullstring, &uop->operator);
3288 }
3289
3290
3291 /* Write generic interfaces associated with a symbol.  */
3292
3293 static void
3294 write_generic (gfc_symbol * sym)
3295 {
3296
3297   if (sym->generic == NULL
3298       || !check_access (sym->attr.access, sym->ns->default_access))
3299     return;
3300
3301   mio_symbol_interface (sym->name, sym->module, &sym->generic);
3302 }
3303
3304
3305 static void
3306 write_symtree (gfc_symtree * st)
3307 {
3308   gfc_symbol *sym;
3309   pointer_info *p;
3310
3311   sym = st->n.sym;
3312   if (!check_access (sym->attr.access, sym->ns->default_access)
3313       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.generic
3314           && !sym->attr.subroutine && !sym->attr.function))
3315     return;
3316
3317   if (check_unique_name (st->name))
3318     return;
3319
3320   p = find_pointer (sym);
3321   if (p == NULL)
3322     gfc_internal_error ("write_symtree(): Symbol not written");
3323
3324   mio_internal_string (st->name);
3325   mio_integer (&st->ambiguous);
3326   mio_integer (&p->integer);
3327 }
3328
3329
3330 static void
3331 write_module (void)
3332 {
3333   gfc_intrinsic_op i;
3334
3335   /* Write the operator interfaces.  */
3336   mio_lparen ();
3337
3338   for (i = GFC_INTRINSIC_BEGIN; i != GFC_INTRINSIC_END; i++)
3339     {
3340       if (i == INTRINSIC_USER)
3341         continue;
3342
3343       mio_interface (check_access (gfc_current_ns->operator_access[i],
3344                                    gfc_current_ns->default_access)
3345                      ? &gfc_current_ns->operator[i] : NULL);
3346     }
3347
3348   mio_rparen ();
3349   write_char ('\n');
3350   write_char ('\n');
3351
3352   mio_lparen ();
3353   gfc_traverse_user_op (gfc_current_ns, write_operator);
3354   mio_rparen ();
3355   write_char ('\n');
3356   write_char ('\n');
3357
3358   mio_lparen ();
3359   gfc_traverse_ns (gfc_current_ns, write_generic);
3360   mio_rparen ();
3361   write_char ('\n');
3362   write_char ('\n');
3363
3364   mio_lparen ();
3365   write_common (gfc_current_ns->common_root);
3366   mio_rparen ();
3367   write_char ('\n');
3368   write_char ('\n');
3369
3370   /* Write symbol information.  First we traverse all symbols in the
3371      primary namespace, writing those that need to be written.
3372      Sometimes writing one symbol will cause another to need to be
3373      written.  A list of these symbols ends up on the write stack, and
3374      we end by popping the bottom of the stack and writing the symbol
3375      until the stack is empty.  */
3376
3377   mio_lparen ();
3378
3379   write_symbol0 (gfc_current_ns->sym_root);
3380   while (write_symbol1 (pi_root));
3381
3382   mio_rparen ();
3383
3384   write_char ('\n');
3385   write_char ('\n');
3386
3387   mio_lparen ();
3388   gfc_traverse_symtree (gfc_current_ns->sym_root, write_symtree);
3389   mio_rparen ();
3390 }
3391
3392
3393 /* Given module, dump it to disk.  If there was an error while
3394    processing the module, dump_flag will be set to zero and we delete
3395    the module file, even if it was already there.  */
3396
3397 void
3398 gfc_dump_module (const char *name, int dump_flag)
3399 {
3400   char filename[PATH_MAX], *p;
3401   time_t now;
3402
3403   filename[0] = '\0';
3404   if (gfc_option.module_dir != NULL)
3405     strcpy (filename, gfc_option.module_dir);
3406
3407   strcat (filename, name);
3408   strcat (filename, MODULE_EXTENSION);
3409
3410   if (!dump_flag)
3411     {
3412       unlink (filename);
3413       return;
3414     }
3415
3416   module_fp = fopen (filename, "w");
3417   if (module_fp == NULL)
3418     gfc_fatal_error ("Can't open module file '%s' for writing: %s",
3419                      filename, strerror (errno));
3420
3421   now = time (NULL);
3422   p = ctime (&now);
3423
3424   *strchr (p, '\n') = '\0';
3425
3426   fprintf (module_fp, "GFORTRAN module created from %s on %s\n", 
3427            gfc_source_file, p);
3428   fputs ("If you edit this, you'll get what you deserve.\n\n", module_fp);
3429
3430   iomode = IO_OUTPUT;
3431   strcpy (module_name, name);
3432
3433   init_pi_tree ();
3434
3435   write_module ();
3436
3437   free_pi_tree (pi_root);
3438   pi_root = NULL;
3439
3440   write_char ('\n');
3441
3442   if (fclose (module_fp))
3443     gfc_fatal_error ("Error writing module file '%s' for writing: %s",
3444                      filename, strerror (errno));
3445 }
3446
3447
3448 /* Process a USE directive.  */
3449
3450 void
3451 gfc_use_module (void)
3452 {
3453   char filename[GFC_MAX_SYMBOL_LEN + 5];
3454   gfc_state_data *p;
3455   int c, line;
3456
3457   strcpy (filename, module_name);
3458   strcat (filename, MODULE_EXTENSION);
3459
3460   module_fp = gfc_open_included_file (filename);
3461   if (module_fp == NULL)
3462     gfc_fatal_error ("Can't open module file '%s' for reading: %s",
3463                      filename, strerror (errno));
3464
3465   iomode = IO_INPUT;
3466   module_line = 1;
3467   module_column = 1;
3468
3469   /* Skip the first two lines of the module.  */
3470   /* FIXME: Could also check for valid two lines here, instead.  */
3471   line = 0;
3472   while (line < 2)
3473     {
3474       c = module_char ();
3475       if (c == EOF)
3476         bad_module ("Unexpected end of module");
3477       if (c == '\n')
3478         line++;
3479     }
3480
3481   /* Make sure we're not reading the same module that we may be building.  */
3482   for (p = gfc_state_stack; p; p = p->previous)
3483     if (p->state == COMP_MODULE && strcmp (p->sym->name, module_name) == 0)
3484       gfc_fatal_error ("Can't USE the same module we're building!");
3485
3486   init_pi_tree ();
3487   init_true_name_tree ();
3488
3489   read_module ();
3490
3491   free_true_name (true_name_root);
3492   true_name_root = NULL;
3493
3494   free_pi_tree (pi_root);
3495   pi_root = NULL;
3496
3497   fclose (module_fp);
3498 }
3499
3500
3501 void
3502 gfc_module_init_2 (void)
3503 {
3504
3505   last_atom = ATOM_LPAREN;
3506 }
3507
3508
3509 void
3510 gfc_module_done_2 (void)
3511 {
3512
3513   free_rename ();
3514 }