OSDN Git Service

2007-09-04 Janus Weil <jaydub66@gmail.com>
[pf3gnuchains/gcc-fork.git] / gcc / fortran / symbol.c
1 /* Maintain binary trees of symbols.
2    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
3    Free Software Foundation, Inc.
4    Contributed by Andy Vaught
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22
23 #include "config.h"
24 #include "system.h"
25 #include "flags.h"
26 #include "gfortran.h"
27 #include "parse.h"
28
29
30 /* Strings for all symbol attributes.  We use these for dumping the
31    parse tree, in error messages, and also when reading and writing
32    modules.  */
33
34 const mstring flavors[] =
35 {
36   minit ("UNKNOWN-FL", FL_UNKNOWN), minit ("PROGRAM", FL_PROGRAM),
37   minit ("BLOCK-DATA", FL_BLOCK_DATA), minit ("MODULE", FL_MODULE),
38   minit ("VARIABLE", FL_VARIABLE), minit ("PARAMETER", FL_PARAMETER),
39   minit ("LABEL", FL_LABEL), minit ("PROCEDURE", FL_PROCEDURE),
40   minit ("DERIVED", FL_DERIVED), minit ("NAMELIST", FL_NAMELIST),
41   minit (NULL, -1)
42 };
43
44 const mstring procedures[] =
45 {
46     minit ("UNKNOWN-PROC", PROC_UNKNOWN),
47     minit ("MODULE-PROC", PROC_MODULE),
48     minit ("INTERNAL-PROC", PROC_INTERNAL),
49     minit ("DUMMY-PROC", PROC_DUMMY),
50     minit ("INTRINSIC-PROC", PROC_INTRINSIC),
51     minit ("EXTERNAL-PROC", PROC_EXTERNAL),
52     minit ("STATEMENT-PROC", PROC_ST_FUNCTION),
53     minit (NULL, -1)
54 };
55
56 const mstring intents[] =
57 {
58     minit ("UNKNOWN-INTENT", INTENT_UNKNOWN),
59     minit ("IN", INTENT_IN),
60     minit ("OUT", INTENT_OUT),
61     minit ("INOUT", INTENT_INOUT),
62     minit (NULL, -1)
63 };
64
65 const mstring access_types[] =
66 {
67     minit ("UNKNOWN-ACCESS", ACCESS_UNKNOWN),
68     minit ("PUBLIC", ACCESS_PUBLIC),
69     minit ("PRIVATE", ACCESS_PRIVATE),
70     minit (NULL, -1)
71 };
72
73 const mstring ifsrc_types[] =
74 {
75     minit ("UNKNOWN", IFSRC_UNKNOWN),
76     minit ("DECL", IFSRC_DECL),
77     minit ("BODY", IFSRC_IFBODY),
78     minit ("USAGE", IFSRC_USAGE)
79 };
80
81 const mstring save_status[] =
82 {
83     minit ("UNKNOWN", SAVE_NONE),
84     minit ("EXPLICIT-SAVE", SAVE_EXPLICIT),
85     minit ("IMPLICIT-SAVE", SAVE_IMPLICIT),
86 };
87
88 /* This is to make sure the backend generates setup code in the correct
89    order.  */
90
91 static int next_dummy_order = 1;
92
93
94 gfc_namespace *gfc_current_ns;
95
96 gfc_gsymbol *gfc_gsym_root = NULL;
97
98 static gfc_symbol *changed_syms = NULL;
99
100 gfc_dt_list *gfc_derived_types;
101
102
103 /*********** IMPLICIT NONE and IMPLICIT statement handlers ***********/
104
105 /* The following static variable indicates whether a particular element has
106    been explicitly set or not.  */
107
108 static int new_flag[GFC_LETTERS];
109
110
111 /* Handle a correctly parsed IMPLICIT NONE.  */
112
113 void
114 gfc_set_implicit_none (void)
115 {
116   int i;
117
118   if (gfc_current_ns->seen_implicit_none)
119     {
120       gfc_error ("Duplicate IMPLICIT NONE statement at %C");
121       return;
122     }
123
124   gfc_current_ns->seen_implicit_none = 1;
125
126   for (i = 0; i < GFC_LETTERS; i++)
127     {
128       gfc_clear_ts (&gfc_current_ns->default_type[i]);
129       gfc_current_ns->set_flag[i] = 1;
130     }
131 }
132
133
134 /* Reset the implicit range flags.  */
135
136 void
137 gfc_clear_new_implicit (void)
138 {
139   int i;
140
141   for (i = 0; i < GFC_LETTERS; i++)
142     new_flag[i] = 0;
143 }
144
145
146 /* Prepare for a new implicit range.  Sets flags in new_flag[].  */
147
148 try
149 gfc_add_new_implicit_range (int c1, int c2)
150 {
151   int i;
152
153   c1 -= 'a';
154   c2 -= 'a';
155
156   for (i = c1; i <= c2; i++)
157     {
158       if (new_flag[i])
159         {
160           gfc_error ("Letter '%c' already set in IMPLICIT statement at %C",
161                      i + 'A');
162           return FAILURE;
163         }
164
165       new_flag[i] = 1;
166     }
167
168   return SUCCESS;
169 }
170
171
172 /* Add a matched implicit range for gfc_set_implicit().  Check if merging
173    the new implicit types back into the existing types will work.  */
174
175 try
176 gfc_merge_new_implicit (gfc_typespec *ts)
177 {
178   int i;
179
180   if (gfc_current_ns->seen_implicit_none)
181     {
182       gfc_error ("Cannot specify IMPLICIT at %C after IMPLICIT NONE");
183       return FAILURE;
184     }
185
186   for (i = 0; i < GFC_LETTERS; i++)
187     {
188       if (new_flag[i])
189         {
190
191           if (gfc_current_ns->set_flag[i])
192             {
193               gfc_error ("Letter %c already has an IMPLICIT type at %C",
194                          i + 'A');
195               return FAILURE;
196             }
197           gfc_current_ns->default_type[i] = *ts;
198           gfc_current_ns->set_flag[i] = 1;
199         }
200     }
201   return SUCCESS;
202 }
203
204
205 /* Given a symbol, return a pointer to the typespec for its default type.  */
206
207 gfc_typespec *
208 gfc_get_default_type (gfc_symbol *sym, gfc_namespace *ns)
209 {
210   char letter;
211
212   letter = sym->name[0];
213
214   if (gfc_option.flag_allow_leading_underscore && letter == '_')
215     gfc_internal_error ("Option -fallow_leading_underscore is for use only by "
216                         "gfortran developers, and should not be used for "
217                         "implicitly typed variables");
218
219   if (letter < 'a' || letter > 'z')
220     gfc_internal_error ("gfc_get_default_type(): Bad symbol");
221
222   if (ns == NULL)
223     ns = gfc_current_ns;
224
225   return &ns->default_type[letter - 'a'];
226 }
227
228
229 /* Given a pointer to a symbol, set its type according to the first
230    letter of its name.  Fails if the letter in question has no default
231    type.  */
232
233 try
234 gfc_set_default_type (gfc_symbol *sym, int error_flag, gfc_namespace *ns)
235 {
236   gfc_typespec *ts;
237
238   if (sym->ts.type != BT_UNKNOWN)
239     gfc_internal_error ("gfc_set_default_type(): symbol already has a type");
240
241   ts = gfc_get_default_type (sym, ns);
242
243   if (ts->type == BT_UNKNOWN)
244     {
245       if (error_flag && !sym->attr.untyped)
246         {
247           gfc_error ("Symbol '%s' at %L has no IMPLICIT type",
248                      sym->name, &sym->declared_at);
249           sym->attr.untyped = 1; /* Ensure we only give an error once.  */
250         }
251
252       return FAILURE;
253     }
254
255   sym->ts = *ts;
256   sym->attr.implicit_type = 1;
257
258   if (sym->attr.is_bind_c == 1)
259     {
260       /* BIND(C) variables should not be implicitly declared.  */
261       gfc_warning_now ("Implicitly declared BIND(C) variable '%s' at %L may "
262                        "not be C interoperable", sym->name, &sym->declared_at);
263       sym->ts.f90_type = sym->ts.type;
264     }
265
266   if (sym->attr.dummy != 0)
267     {
268       if (sym->ns->proc_name != NULL
269           && (sym->ns->proc_name->attr.subroutine != 0
270               || sym->ns->proc_name->attr.function != 0)
271           && sym->ns->proc_name->attr.is_bind_c != 0)
272         {
273           /* Dummy args to a BIND(C) routine may not be interoperable if
274              they are implicitly typed.  */
275           gfc_warning_now ("Implicity declared variable '%s' at %L may not "
276                            "be C interoperable but it is a dummy argument to "
277                            "the BIND(C) procedure '%s' at %L", sym->name,
278                            &(sym->declared_at), sym->ns->proc_name->name,
279                            &(sym->ns->proc_name->declared_at));
280           sym->ts.f90_type = sym->ts.type;
281         }
282     }
283   
284   return SUCCESS;
285 }
286
287
288 /* This function is called from parse.c(parse_progunit) to check the
289    type of the function is not implicitly typed in the host namespace
290    and to implicitly type the function result, if necessary.  */
291
292 void
293 gfc_check_function_type (gfc_namespace *ns)
294 {
295   gfc_symbol *proc = ns->proc_name;
296
297   if (!proc->attr.contained || proc->result->attr.implicit_type)
298     return;
299
300   if (proc->result->ts.type == BT_UNKNOWN)
301     {
302       if (gfc_set_default_type (proc->result, 0, gfc_current_ns)
303                 == SUCCESS)
304         {
305           if (proc->result != proc)
306             {
307               proc->ts = proc->result->ts;
308               proc->as = gfc_copy_array_spec (proc->result->as);
309               proc->attr.dimension = proc->result->attr.dimension;
310               proc->attr.pointer = proc->result->attr.pointer;
311               proc->attr.allocatable = proc->result->attr.allocatable;
312             }
313         }
314       else
315         {
316           gfc_error ("Function result '%s' at %L has no IMPLICIT type",
317                      proc->result->name, &proc->result->declared_at);
318           proc->result->attr.untyped = 1;
319         }
320     }
321 }
322
323
324 /******************** Symbol attribute stuff *********************/
325
326 /* This is a generic conflict-checker.  We do this to avoid having a
327    single conflict in two places.  */
328
329 #define conf(a, b) if (attr->a && attr->b) { a1 = a; a2 = b; goto conflict; }
330 #define conf2(a) if (attr->a) { a2 = a; goto conflict; }
331 #define conf_std(a, b, std) if (attr->a && attr->b)\
332                               {\
333                                 a1 = a;\
334                                 a2 = b;\
335                                 standard = std;\
336                                 goto conflict_std;\
337                               }
338
339 static try
340 check_conflict (symbol_attribute *attr, const char *name, locus *where)
341 {
342   static const char *dummy = "DUMMY", *save = "SAVE", *pointer = "POINTER",
343     *target = "TARGET", *external = "EXTERNAL", *intent = "INTENT",
344     *intent_in = "INTENT(IN)", *intrinsic = "INTRINSIC",
345     *intent_out = "INTENT(OUT)", *intent_inout = "INTENT(INOUT)",
346     *allocatable = "ALLOCATABLE", *elemental = "ELEMENTAL",
347     *private = "PRIVATE", *recursive = "RECURSIVE",
348     *in_common = "COMMON", *result = "RESULT", *in_namelist = "NAMELIST",
349     *public = "PUBLIC", *optional = "OPTIONAL", *entry = "ENTRY",
350     *function = "FUNCTION", *subroutine = "SUBROUTINE",
351     *dimension = "DIMENSION", *in_equivalence = "EQUIVALENCE",
352     *use_assoc = "USE ASSOCIATED", *cray_pointer = "CRAY POINTER",
353     *cray_pointee = "CRAY POINTEE", *data = "DATA", *value = "VALUE",
354     *volatile_ = "VOLATILE", *protected = "PROTECTED",
355     *is_bind_c = "BIND(C)", *procedure = "PROCEDURE";
356   static const char *threadprivate = "THREADPRIVATE";
357
358   const char *a1, *a2;
359   int standard;
360
361   if (where == NULL)
362     where = &gfc_current_locus;
363
364   if (attr->pointer && attr->intent != INTENT_UNKNOWN)
365     {
366       a1 = pointer;
367       a2 = intent;
368       standard = GFC_STD_F2003;
369       goto conflict_std;
370     }
371
372   /* Check for attributes not allowed in a BLOCK DATA.  */
373   if (gfc_current_state () == COMP_BLOCK_DATA)
374     {
375       a1 = NULL;
376
377       if (attr->in_namelist)
378         a1 = in_namelist;
379       if (attr->allocatable)
380         a1 = allocatable;
381       if (attr->external)
382         a1 = external;
383       if (attr->optional)
384         a1 = optional;
385       if (attr->access == ACCESS_PRIVATE)
386         a1 = private;
387       if (attr->access == ACCESS_PUBLIC)
388         a1 = public;
389       if (attr->intent != INTENT_UNKNOWN)
390         a1 = intent;
391
392       if (a1 != NULL)
393         {
394           gfc_error
395             ("%s attribute not allowed in BLOCK DATA program unit at %L",
396              a1, where);
397           return FAILURE;
398         }
399     }
400
401   if (attr->save == SAVE_EXPLICIT)
402     {
403       conf (dummy, save);
404       conf (in_common, save);
405       conf (result, save);
406
407       switch (attr->flavor)
408         {
409           case FL_PROGRAM:
410           case FL_BLOCK_DATA:
411           case FL_MODULE:
412           case FL_LABEL:
413           case FL_PROCEDURE:
414           case FL_DERIVED:
415           case FL_PARAMETER:
416             a1 = gfc_code2string (flavors, attr->flavor);
417             a2 = save;
418             goto conflict;
419
420           case FL_VARIABLE:
421           case FL_NAMELIST:
422           default:
423             break;
424         }
425     }
426
427   conf (dummy, entry);
428   conf (dummy, intrinsic);
429   conf (dummy, threadprivate);
430   conf (pointer, target);
431   conf (pointer, intrinsic);
432   conf (pointer, elemental);
433   conf (allocatable, elemental);
434
435   conf (target, external);
436   conf (target, intrinsic);
437   conf (external, dimension);   /* See Fortran 95's R504.  */
438
439   conf (external, intrinsic);
440
441   if ((attr->if_source && !attr->procedure) || attr->contained)
442     {
443       conf (external, subroutine);
444       conf (external, function);
445     }
446
447   conf (allocatable, pointer);
448   conf_std (allocatable, dummy, GFC_STD_F2003);
449   conf_std (allocatable, function, GFC_STD_F2003);
450   conf_std (allocatable, result, GFC_STD_F2003);
451   conf (elemental, recursive);
452
453   conf (in_common, dummy);
454   conf (in_common, allocatable);
455   conf (in_common, result);
456
457   conf (dummy, result);
458
459   conf (in_equivalence, use_assoc);
460   conf (in_equivalence, dummy);
461   conf (in_equivalence, target);
462   conf (in_equivalence, pointer);
463   conf (in_equivalence, function);
464   conf (in_equivalence, result);
465   conf (in_equivalence, entry);
466   conf (in_equivalence, allocatable);
467   conf (in_equivalence, threadprivate);
468
469   conf (in_namelist, pointer);
470   conf (in_namelist, allocatable);
471
472   conf (entry, result);
473
474   conf (function, subroutine);
475
476   if (!function && !subroutine)
477     conf (is_bind_c, dummy);
478
479   conf (is_bind_c, cray_pointer);
480   conf (is_bind_c, cray_pointee);
481   conf (is_bind_c, allocatable);
482
483   /* Need to also get volatile attr, according to 5.1 of F2003 draft.
484      Parameter conflict caught below.  Also, value cannot be specified
485      for a dummy procedure.  */
486
487   /* Cray pointer/pointee conflicts.  */
488   conf (cray_pointer, cray_pointee);
489   conf (cray_pointer, dimension);
490   conf (cray_pointer, pointer);
491   conf (cray_pointer, target);
492   conf (cray_pointer, allocatable);
493   conf (cray_pointer, external);
494   conf (cray_pointer, intrinsic);
495   conf (cray_pointer, in_namelist);
496   conf (cray_pointer, function);
497   conf (cray_pointer, subroutine);
498   conf (cray_pointer, entry);
499
500   conf (cray_pointee, allocatable);
501   conf (cray_pointee, intent);
502   conf (cray_pointee, optional);
503   conf (cray_pointee, dummy);
504   conf (cray_pointee, target);
505   conf (cray_pointee, intrinsic);
506   conf (cray_pointee, pointer);
507   conf (cray_pointee, entry);
508   conf (cray_pointee, in_common);
509   conf (cray_pointee, in_equivalence);
510   conf (cray_pointee, threadprivate);
511
512   conf (data, dummy);
513   conf (data, function);
514   conf (data, result);
515   conf (data, allocatable);
516   conf (data, use_assoc);
517
518   conf (value, pointer)
519   conf (value, allocatable)
520   conf (value, subroutine)
521   conf (value, function)
522   conf (value, volatile_)
523   conf (value, dimension)
524   conf (value, external)
525
526   if (attr->value
527       && (attr->intent == INTENT_OUT || attr->intent == INTENT_INOUT))
528     {
529       a1 = value;
530       a2 = attr->intent == INTENT_OUT ? intent_out : intent_inout;
531       goto conflict;
532     }
533
534   conf (protected, intrinsic)
535   conf (protected, external)
536   conf (protected, in_common)
537
538   conf (volatile_, intrinsic)
539   conf (volatile_, external)
540
541   if (attr->volatile_ && attr->intent == INTENT_IN)
542     {
543       a1 = volatile_;
544       a2 = intent_in;
545       goto conflict;
546     }
547
548   conf (procedure, allocatable)
549   conf (procedure, dimension)
550   conf (procedure, intrinsic)
551   conf (procedure, protected)
552   conf (procedure, target)
553   conf (procedure, value)
554   conf (procedure, volatile_)
555   conf (procedure, entry)
556   /* TODO: Implement procedure pointers.  */
557   if (attr->procedure && attr->pointer)
558     {
559       gfc_error ("Fortran 2003: Procedure pointers at %L are "
560                  "not yet implemented in gfortran", where);
561       return FAILURE;
562     }
563
564   a1 = gfc_code2string (flavors, attr->flavor);
565
566   if (attr->in_namelist
567       && attr->flavor != FL_VARIABLE
568       && attr->flavor != FL_PROCEDURE
569       && attr->flavor != FL_UNKNOWN)
570     {
571       a2 = in_namelist;
572       goto conflict;
573     }
574
575   switch (attr->flavor)
576     {
577     case FL_PROGRAM:
578     case FL_BLOCK_DATA:
579     case FL_MODULE:
580     case FL_LABEL:
581       conf2 (dimension);
582       conf2 (dummy);
583       conf2 (volatile_);
584       conf2 (pointer);
585       conf2 (protected);
586       conf2 (target);
587       conf2 (external);
588       conf2 (intrinsic);
589       conf2 (allocatable);
590       conf2 (result);
591       conf2 (in_namelist);
592       conf2 (optional);
593       conf2 (function);
594       conf2 (subroutine);
595       conf2 (threadprivate);
596       break;
597
598     case FL_VARIABLE:
599     case FL_NAMELIST:
600       break;
601
602     case FL_PROCEDURE:
603       conf2 (intent);
604
605       if (attr->subroutine)
606         {
607           conf2 (pointer);
608           conf2 (target);
609           conf2 (allocatable);
610           conf2 (result);
611           conf2 (in_namelist);
612           conf2 (dimension);
613           conf2 (function);
614           conf2 (threadprivate);
615         }
616
617       switch (attr->proc)
618         {
619         case PROC_ST_FUNCTION:
620           conf2 (in_common);
621           conf2 (dummy);
622           break;
623
624         case PROC_MODULE:
625           conf2 (dummy);
626           break;
627
628         case PROC_DUMMY:
629           conf2 (result);
630           conf2 (in_common);
631           conf2 (threadprivate);
632           break;
633
634         default:
635           break;
636         }
637
638       break;
639
640     case FL_DERIVED:
641       conf2 (dummy);
642       conf2 (pointer);
643       conf2 (target);
644       conf2 (external);
645       conf2 (intrinsic);
646       conf2 (allocatable);
647       conf2 (optional);
648       conf2 (entry);
649       conf2 (function);
650       conf2 (subroutine);
651       conf2 (threadprivate);
652
653       if (attr->intent != INTENT_UNKNOWN)
654         {
655           a2 = intent;
656           goto conflict;
657         }
658       break;
659
660     case FL_PARAMETER:
661       conf2 (external);
662       conf2 (intrinsic);
663       conf2 (optional);
664       conf2 (allocatable);
665       conf2 (function);
666       conf2 (subroutine);
667       conf2 (entry);
668       conf2 (pointer);
669       conf2 (protected);
670       conf2 (target);
671       conf2 (dummy);
672       conf2 (in_common);
673       conf2 (value);
674       conf2 (volatile_);
675       conf2 (threadprivate);
676       /* TODO: hmm, double check this.  */
677       conf2 (value);
678       break;
679
680     default:
681       break;
682     }
683
684   return SUCCESS;
685
686 conflict:
687   if (name == NULL)
688     gfc_error ("%s attribute conflicts with %s attribute at %L",
689                a1, a2, where);
690   else
691     gfc_error ("%s attribute conflicts with %s attribute in '%s' at %L",
692                a1, a2, name, where);
693
694   return FAILURE;
695
696 conflict_std:
697   if (name == NULL)
698     {
699       return gfc_notify_std (standard, "Fortran 2003: %s attribute "
700                              "with %s attribute at %L", a1, a2,
701                              where);
702     }
703   else
704     {
705       return gfc_notify_std (standard, "Fortran 2003: %s attribute "
706                              "with %s attribute in '%s' at %L",
707                              a1, a2, name, where);
708     }
709 }
710
711 #undef conf
712 #undef conf2
713 #undef conf_std
714
715
716 /* Mark a symbol as referenced.  */
717
718 void
719 gfc_set_sym_referenced (gfc_symbol *sym)
720 {
721
722   if (sym->attr.referenced)
723     return;
724
725   sym->attr.referenced = 1;
726
727   /* Remember which order dummy variables are accessed in.  */
728   if (sym->attr.dummy)
729     sym->dummy_order = next_dummy_order++;
730 }
731
732
733 /* Common subroutine called by attribute changing subroutines in order
734    to prevent them from changing a symbol that has been
735    use-associated.  Returns zero if it is OK to change the symbol,
736    nonzero if not.  */
737
738 static int
739 check_used (symbol_attribute *attr, const char *name, locus *where)
740 {
741
742   if (attr->use_assoc == 0)
743     return 0;
744
745   if (where == NULL)
746     where = &gfc_current_locus;
747
748   if (name == NULL)
749     gfc_error ("Cannot change attributes of USE-associated symbol at %L",
750                where);
751   else
752     gfc_error ("Cannot change attributes of USE-associated symbol %s at %L",
753                name, where);
754
755   return 1;
756 }
757
758
759 /* Generate an error because of a duplicate attribute.  */
760
761 static void
762 duplicate_attr (const char *attr, locus *where)
763 {
764
765   if (where == NULL)
766     where = &gfc_current_locus;
767
768   gfc_error ("Duplicate %s attribute specified at %L", attr, where);
769 }
770
771
772 /* Called from decl.c (attr_decl1) to check attributes, when declared
773    separately.  */
774
775 try
776 gfc_add_attribute (symbol_attribute *attr, locus *where)
777 {
778
779   if (check_used (attr, NULL, where))
780     return FAILURE;
781
782   return check_conflict (attr, NULL, where);
783 }
784
785 try
786 gfc_add_allocatable (symbol_attribute *attr, locus *where)
787 {
788
789   if (check_used (attr, NULL, where))
790     return FAILURE;
791
792   if (attr->allocatable)
793     {
794       duplicate_attr ("ALLOCATABLE", where);
795       return FAILURE;
796     }
797
798   attr->allocatable = 1;
799   return check_conflict (attr, NULL, where);
800 }
801
802
803 try
804 gfc_add_dimension (symbol_attribute *attr, const char *name, locus *where)
805 {
806
807   if (check_used (attr, name, where))
808     return FAILURE;
809
810   if (attr->dimension)
811     {
812       duplicate_attr ("DIMENSION", where);
813       return FAILURE;
814     }
815
816   attr->dimension = 1;
817   return check_conflict (attr, name, where);
818 }
819
820
821 try
822 gfc_add_external (symbol_attribute *attr, locus *where)
823 {
824
825   if (check_used (attr, NULL, where))
826     return FAILURE;
827
828   if (attr->external)
829     {
830       duplicate_attr ("EXTERNAL", where);
831       return FAILURE;
832     }
833
834   attr->external = 1;
835
836   return check_conflict (attr, NULL, where);
837 }
838
839
840 try
841 gfc_add_intrinsic (symbol_attribute *attr, locus *where)
842 {
843
844   if (check_used (attr, NULL, where))
845     return FAILURE;
846
847   if (attr->intrinsic)
848     {
849       duplicate_attr ("INTRINSIC", where);
850       return FAILURE;
851     }
852
853   attr->intrinsic = 1;
854
855   return check_conflict (attr, NULL, where);
856 }
857
858
859 try
860 gfc_add_optional (symbol_attribute *attr, locus *where)
861 {
862
863   if (check_used (attr, NULL, where))
864     return FAILURE;
865
866   if (attr->optional)
867     {
868       duplicate_attr ("OPTIONAL", where);
869       return FAILURE;
870     }
871
872   attr->optional = 1;
873   return check_conflict (attr, NULL, where);
874 }
875
876
877 try
878 gfc_add_pointer (symbol_attribute *attr, locus *where)
879 {
880
881   if (check_used (attr, NULL, where))
882     return FAILURE;
883
884   attr->pointer = 1;
885   return check_conflict (attr, NULL, where);
886 }
887
888
889 try
890 gfc_add_cray_pointer (symbol_attribute *attr, locus *where)
891 {
892
893   if (check_used (attr, NULL, where))
894     return FAILURE;
895
896   attr->cray_pointer = 1;
897   return check_conflict (attr, NULL, where);
898 }
899
900
901 try
902 gfc_add_cray_pointee (symbol_attribute *attr, locus *where)
903 {
904
905   if (check_used (attr, NULL, where))
906     return FAILURE;
907
908   if (attr->cray_pointee)
909     {
910       gfc_error ("Cray Pointee at %L appears in multiple pointer()"
911                  " statements", where);
912       return FAILURE;
913     }
914
915   attr->cray_pointee = 1;
916   return check_conflict (attr, NULL, where);
917 }
918
919
920 try
921 gfc_add_protected (symbol_attribute *attr, const char *name, locus *where)
922 {
923   if (check_used (attr, name, where))
924     return FAILURE;
925
926   if (attr->protected)
927     {
928         if (gfc_notify_std (GFC_STD_LEGACY, 
929                             "Duplicate PROTECTED attribute specified at %L",
930                             where) 
931             == FAILURE)
932           return FAILURE;
933     }
934
935   attr->protected = 1;
936   return check_conflict (attr, name, where);
937 }
938
939
940 try
941 gfc_add_result (symbol_attribute *attr, const char *name, locus *where)
942 {
943
944   if (check_used (attr, name, where))
945     return FAILURE;
946
947   attr->result = 1;
948   return check_conflict (attr, name, where);
949 }
950
951
952 try
953 gfc_add_save (symbol_attribute *attr, const char *name, locus *where)
954 {
955
956   if (check_used (attr, name, where))
957     return FAILURE;
958
959   if (gfc_pure (NULL))
960     {
961       gfc_error
962         ("SAVE attribute at %L cannot be specified in a PURE procedure",
963          where);
964       return FAILURE;
965     }
966
967   if (attr->save == SAVE_EXPLICIT)
968     {
969         if (gfc_notify_std (GFC_STD_LEGACY, 
970                             "Duplicate SAVE attribute specified at %L",
971                             where) 
972             == FAILURE)
973           return FAILURE;
974     }
975
976   attr->save = SAVE_EXPLICIT;
977   return check_conflict (attr, name, where);
978 }
979
980
981 try
982 gfc_add_value (symbol_attribute *attr, const char *name, locus *where)
983 {
984
985   if (check_used (attr, name, where))
986     return FAILURE;
987
988   if (attr->value)
989     {
990         if (gfc_notify_std (GFC_STD_LEGACY, 
991                             "Duplicate VALUE attribute specified at %L",
992                             where) 
993             == FAILURE)
994           return FAILURE;
995     }
996
997   attr->value = 1;
998   return check_conflict (attr, name, where);
999 }
1000
1001
1002 try
1003 gfc_add_volatile (symbol_attribute *attr, const char *name, locus *where)
1004 {
1005   /* No check_used needed as 11.2.1 of the F2003 standard allows
1006      that the local identifier made accessible by a use statement can be
1007      given a VOLATILE attribute.  */
1008
1009   if (attr->volatile_ && attr->volatile_ns == gfc_current_ns)
1010     if (gfc_notify_std (GFC_STD_LEGACY, 
1011                         "Duplicate VOLATILE attribute specified at %L", where)
1012         == FAILURE)
1013       return FAILURE;
1014
1015   attr->volatile_ = 1;
1016   attr->volatile_ns = gfc_current_ns;
1017   return check_conflict (attr, name, where);
1018 }
1019
1020
1021 try
1022 gfc_add_threadprivate (symbol_attribute *attr, const char *name, locus *where)
1023 {
1024
1025   if (check_used (attr, name, where))
1026     return FAILURE;
1027
1028   if (attr->threadprivate)
1029     {
1030       duplicate_attr ("THREADPRIVATE", where);
1031       return FAILURE;
1032     }
1033
1034   attr->threadprivate = 1;
1035   return check_conflict (attr, name, where);
1036 }
1037
1038
1039 try
1040 gfc_add_target (symbol_attribute *attr, locus *where)
1041 {
1042
1043   if (check_used (attr, NULL, where))
1044     return FAILURE;
1045
1046   if (attr->target)
1047     {
1048       duplicate_attr ("TARGET", where);
1049       return FAILURE;
1050     }
1051
1052   attr->target = 1;
1053   return check_conflict (attr, NULL, where);
1054 }
1055
1056
1057 try
1058 gfc_add_dummy (symbol_attribute *attr, const char *name, locus *where)
1059 {
1060
1061   if (check_used (attr, name, where))
1062     return FAILURE;
1063
1064   /* Duplicate dummy arguments are allowed due to ENTRY statements.  */
1065   attr->dummy = 1;
1066   return check_conflict (attr, name, where);
1067 }
1068
1069
1070 try
1071 gfc_add_in_common (symbol_attribute *attr, const char *name, locus *where)
1072 {
1073
1074   if (check_used (attr, name, where))
1075     return FAILURE;
1076
1077   /* Duplicate attribute already checked for.  */
1078   attr->in_common = 1;
1079   if (check_conflict (attr, name, where) == FAILURE)
1080     return FAILURE;
1081
1082   if (attr->flavor == FL_VARIABLE)
1083     return SUCCESS;
1084
1085   return gfc_add_flavor (attr, FL_VARIABLE, name, where);
1086 }
1087
1088
1089 try
1090 gfc_add_in_equivalence (symbol_attribute *attr, const char *name, locus *where)
1091 {
1092
1093   /* Duplicate attribute already checked for.  */
1094   attr->in_equivalence = 1;
1095   if (check_conflict (attr, name, where) == FAILURE)
1096     return FAILURE;
1097
1098   if (attr->flavor == FL_VARIABLE)
1099     return SUCCESS;
1100
1101   return gfc_add_flavor (attr, FL_VARIABLE, name, where);
1102 }
1103
1104
1105 try
1106 gfc_add_data (symbol_attribute *attr, const char *name, locus *where)
1107 {
1108
1109   if (check_used (attr, name, where))
1110     return FAILURE;
1111
1112   attr->data = 1;
1113   return check_conflict (attr, name, where);
1114 }
1115
1116
1117 try
1118 gfc_add_in_namelist (symbol_attribute *attr, const char *name, locus *where)
1119 {
1120
1121   attr->in_namelist = 1;
1122   return check_conflict (attr, name, where);
1123 }
1124
1125
1126 try
1127 gfc_add_sequence (symbol_attribute *attr, const char *name, locus *where)
1128 {
1129
1130   if (check_used (attr, name, where))
1131     return FAILURE;
1132
1133   attr->sequence = 1;
1134   return check_conflict (attr, name, where);
1135 }
1136
1137
1138 try
1139 gfc_add_elemental (symbol_attribute *attr, locus *where)
1140 {
1141
1142   if (check_used (attr, NULL, where))
1143     return FAILURE;
1144
1145   attr->elemental = 1;
1146   return check_conflict (attr, NULL, where);
1147 }
1148
1149
1150 try
1151 gfc_add_pure (symbol_attribute *attr, locus *where)
1152 {
1153
1154   if (check_used (attr, NULL, where))
1155     return FAILURE;
1156
1157   attr->pure = 1;
1158   return check_conflict (attr, NULL, where);
1159 }
1160
1161
1162 try
1163 gfc_add_recursive (symbol_attribute *attr, locus *where)
1164 {
1165
1166   if (check_used (attr, NULL, where))
1167     return FAILURE;
1168
1169   attr->recursive = 1;
1170   return check_conflict (attr, NULL, where);
1171 }
1172
1173
1174 try
1175 gfc_add_entry (symbol_attribute *attr, const char *name, locus *where)
1176 {
1177
1178   if (check_used (attr, name, where))
1179     return FAILURE;
1180
1181   if (attr->entry)
1182     {
1183       duplicate_attr ("ENTRY", where);
1184       return FAILURE;
1185     }
1186
1187   attr->entry = 1;
1188   return check_conflict (attr, name, where);
1189 }
1190
1191
1192 try
1193 gfc_add_function (symbol_attribute *attr, const char *name, locus *where)
1194 {
1195
1196   if (attr->flavor != FL_PROCEDURE
1197       && gfc_add_flavor (attr, FL_PROCEDURE, name, where) == FAILURE)
1198     return FAILURE;
1199
1200   attr->function = 1;
1201   return check_conflict (attr, name, where);
1202 }
1203
1204
1205 try
1206 gfc_add_subroutine (symbol_attribute *attr, const char *name, locus *where)
1207 {
1208
1209   if (attr->flavor != FL_PROCEDURE
1210       && gfc_add_flavor (attr, FL_PROCEDURE, name, where) == FAILURE)
1211     return FAILURE;
1212
1213   attr->subroutine = 1;
1214   return check_conflict (attr, name, where);
1215 }
1216
1217
1218 try
1219 gfc_add_generic (symbol_attribute *attr, const char *name, locus *where)
1220 {
1221
1222   if (attr->flavor != FL_PROCEDURE
1223       && gfc_add_flavor (attr, FL_PROCEDURE, name, where) == FAILURE)
1224     return FAILURE;
1225
1226   attr->generic = 1;
1227   return check_conflict (attr, name, where);
1228 }
1229
1230
1231 try
1232 gfc_add_proc (symbol_attribute *attr, const char *name, locus *where)
1233 {
1234
1235   if (check_used (attr, NULL, where))
1236     return FAILURE;
1237
1238   if (attr->flavor != FL_PROCEDURE
1239       && gfc_add_flavor (attr, FL_PROCEDURE, name, where) == FAILURE)
1240     return FAILURE;
1241
1242   if (attr->procedure)
1243     {
1244       duplicate_attr ("PROCEDURE", where);
1245       return FAILURE;
1246     }
1247
1248   attr->procedure = 1;
1249
1250   return check_conflict (attr, NULL, where);
1251 }
1252
1253
1254 /* Flavors are special because some flavors are not what Fortran
1255    considers attributes and can be reaffirmed multiple times.  */
1256
1257 try
1258 gfc_add_flavor (symbol_attribute *attr, sym_flavor f, const char *name,
1259                 locus *where)
1260 {
1261
1262   if ((f == FL_PROGRAM || f == FL_BLOCK_DATA || f == FL_MODULE
1263        || f == FL_PARAMETER || f == FL_LABEL || f == FL_DERIVED
1264        || f == FL_NAMELIST) && check_used (attr, name, where))
1265     return FAILURE;
1266
1267   if (attr->flavor == f && f == FL_VARIABLE)
1268     return SUCCESS;
1269
1270   if (attr->flavor != FL_UNKNOWN)
1271     {
1272       if (where == NULL)
1273         where = &gfc_current_locus;
1274
1275       if (name)
1276         gfc_error ("%s attribute of '%s' conflicts with %s attribute at %L",
1277                    gfc_code2string (flavors, attr->flavor), name,
1278                    gfc_code2string (flavors, f), where);
1279       else
1280         gfc_error ("%s attribute conflicts with %s attribute at %L",
1281                    gfc_code2string (flavors, attr->flavor),
1282                    gfc_code2string (flavors, f), where);
1283
1284       return FAILURE;
1285     }
1286
1287   attr->flavor = f;
1288
1289   return check_conflict (attr, name, where);
1290 }
1291
1292
1293 try
1294 gfc_add_procedure (symbol_attribute *attr, procedure_type t,
1295                    const char *name, locus *where)
1296 {
1297
1298   if (check_used (attr, name, where))
1299     return FAILURE;
1300
1301   if (attr->flavor != FL_PROCEDURE
1302       && gfc_add_flavor (attr, FL_PROCEDURE, name, where) == FAILURE)
1303     return FAILURE;
1304
1305   if (where == NULL)
1306     where = &gfc_current_locus;
1307
1308   if (attr->proc != PROC_UNKNOWN)
1309     {
1310       gfc_error ("%s procedure at %L is already declared as %s procedure",
1311                  gfc_code2string (procedures, t), where,
1312                  gfc_code2string (procedures, attr->proc));
1313
1314       return FAILURE;
1315     }
1316
1317   attr->proc = t;
1318
1319   /* Statement functions are always scalar and functions.  */
1320   if (t == PROC_ST_FUNCTION
1321       && ((!attr->function && gfc_add_function (attr, name, where) == FAILURE)
1322           || attr->dimension))
1323     return FAILURE;
1324
1325   return check_conflict (attr, name, where);
1326 }
1327
1328
1329 try
1330 gfc_add_intent (symbol_attribute *attr, sym_intent intent, locus *where)
1331 {
1332
1333   if (check_used (attr, NULL, where))
1334     return FAILURE;
1335
1336   if (attr->intent == INTENT_UNKNOWN)
1337     {
1338       attr->intent = intent;
1339       return check_conflict (attr, NULL, where);
1340     }
1341
1342   if (where == NULL)
1343     where = &gfc_current_locus;
1344
1345   gfc_error ("INTENT (%s) conflicts with INTENT(%s) at %L",
1346              gfc_intent_string (attr->intent),
1347              gfc_intent_string (intent), where);
1348
1349   return FAILURE;
1350 }
1351
1352
1353 /* No checks for use-association in public and private statements.  */
1354
1355 try
1356 gfc_add_access (symbol_attribute *attr, gfc_access access,
1357                 const char *name, locus *where)
1358 {
1359
1360   if (attr->access == ACCESS_UNKNOWN)
1361     {
1362       attr->access = access;
1363       return check_conflict (attr, name, where);
1364     }
1365
1366   if (where == NULL)
1367     where = &gfc_current_locus;
1368   gfc_error ("ACCESS specification at %L was already specified", where);
1369
1370   return FAILURE;
1371 }
1372
1373
1374 /* Set the is_bind_c field for the given symbol_attribute.  */
1375
1376 try
1377 gfc_add_is_bind_c (symbol_attribute *attr, const char *name, locus *where,
1378                    int is_proc_lang_bind_spec)
1379 {
1380
1381   if (is_proc_lang_bind_spec == 0 && attr->flavor == FL_PROCEDURE)
1382     gfc_error_now ("BIND(C) attribute at %L can only be used for "
1383                    "variables or common blocks", where);
1384   else if (attr->is_bind_c)
1385     gfc_error_now ("Duplicate BIND attribute specified at %L", where);
1386   else
1387     attr->is_bind_c = 1;
1388   
1389   if (where == NULL)
1390     where = &gfc_current_locus;
1391    
1392   if (gfc_notify_std (GFC_STD_F2003, "Fortran 2003: BIND(C) at %L", where)
1393       == FAILURE)
1394     return FAILURE;
1395
1396   return check_conflict (attr, name, where);
1397 }
1398
1399
1400 try
1401 gfc_add_explicit_interface (gfc_symbol *sym, ifsrc source,
1402                             gfc_formal_arglist * formal, locus *where)
1403 {
1404
1405   if (check_used (&sym->attr, sym->name, where))
1406     return FAILURE;
1407
1408   if (where == NULL)
1409     where = &gfc_current_locus;
1410
1411   if (sym->attr.if_source != IFSRC_UNKNOWN
1412       && sym->attr.if_source != IFSRC_DECL)
1413     {
1414       gfc_error ("Symbol '%s' at %L already has an explicit interface",
1415                  sym->name, where);
1416       return FAILURE;
1417     }
1418
1419   sym->formal = formal;
1420   sym->attr.if_source = source;
1421
1422   return SUCCESS;
1423 }
1424
1425
1426 /* Add a type to a symbol.  */
1427
1428 try
1429 gfc_add_type (gfc_symbol *sym, gfc_typespec *ts, locus *where)
1430 {
1431   sym_flavor flavor;
1432
1433   if (where == NULL)
1434     where = &gfc_current_locus;
1435
1436   if (sym->ts.type != BT_UNKNOWN)
1437     {
1438       const char *msg = "Symbol '%s' at %L already has basic type of %s";
1439       if (!(sym->ts.type == ts->type
1440             && (sym->attr.flavor == FL_PROCEDURE || sym->attr.result))
1441           || gfc_notification_std (GFC_STD_GNU) == ERROR
1442           || pedantic)
1443         {
1444           gfc_error (msg, sym->name, where, gfc_basic_typename (sym->ts.type));
1445           return FAILURE;
1446         }
1447       else if (gfc_notify_std (GFC_STD_GNU, msg, sym->name, where,
1448                                gfc_basic_typename (sym->ts.type)) == FAILURE)
1449         return FAILURE;
1450     }
1451
1452   flavor = sym->attr.flavor;
1453
1454   if (flavor == FL_PROGRAM || flavor == FL_BLOCK_DATA || flavor == FL_MODULE
1455       || flavor == FL_LABEL
1456       || (flavor == FL_PROCEDURE && sym->attr.subroutine)
1457       || flavor == FL_DERIVED || flavor == FL_NAMELIST)
1458     {
1459       gfc_error ("Symbol '%s' at %L cannot have a type", sym->name, where);
1460       return FAILURE;
1461     }
1462
1463   sym->ts = *ts;
1464   return SUCCESS;
1465 }
1466
1467
1468 /* Clears all attributes.  */
1469
1470 void
1471 gfc_clear_attr (symbol_attribute *attr)
1472 {
1473   memset (attr, 0, sizeof (symbol_attribute));
1474 }
1475
1476
1477 /* Check for missing attributes in the new symbol.  Currently does
1478    nothing, but it's not clear that it is unnecessary yet.  */
1479
1480 try
1481 gfc_missing_attr (symbol_attribute *attr ATTRIBUTE_UNUSED,
1482                   locus *where ATTRIBUTE_UNUSED)
1483 {
1484
1485   return SUCCESS;
1486 }
1487
1488
1489 /* Copy an attribute to a symbol attribute, bit by bit.  Some
1490    attributes have a lot of side-effects but cannot be present given
1491    where we are called from, so we ignore some bits.  */
1492
1493 try
1494 gfc_copy_attr (symbol_attribute *dest, symbol_attribute *src, locus *where)
1495 {
1496   int is_proc_lang_bind_spec;
1497   
1498   if (src->allocatable && gfc_add_allocatable (dest, where) == FAILURE)
1499     goto fail;
1500
1501   if (src->dimension && gfc_add_dimension (dest, NULL, where) == FAILURE)
1502     goto fail;
1503   if (src->optional && gfc_add_optional (dest, where) == FAILURE)
1504     goto fail;
1505   if (src->pointer && gfc_add_pointer (dest, where) == FAILURE)
1506     goto fail;
1507   if (src->protected && gfc_add_protected (dest, NULL, where) == FAILURE)
1508     goto fail;
1509   if (src->save && gfc_add_save (dest, NULL, where) == FAILURE)
1510     goto fail;
1511   if (src->value && gfc_add_value (dest, NULL, where) == FAILURE)
1512     goto fail;
1513   if (src->volatile_ && gfc_add_volatile (dest, NULL, where) == FAILURE)
1514     goto fail;
1515   if (src->threadprivate
1516       && gfc_add_threadprivate (dest, NULL, where) == FAILURE)
1517     goto fail;
1518   if (src->target && gfc_add_target (dest, where) == FAILURE)
1519     goto fail;
1520   if (src->dummy && gfc_add_dummy (dest, NULL, where) == FAILURE)
1521     goto fail;
1522   if (src->result && gfc_add_result (dest, NULL, where) == FAILURE)
1523     goto fail;
1524   if (src->entry)
1525     dest->entry = 1;
1526
1527   if (src->in_namelist && gfc_add_in_namelist (dest, NULL, where) == FAILURE)
1528     goto fail;
1529
1530   if (src->in_common && gfc_add_in_common (dest, NULL, where) == FAILURE)
1531     goto fail;
1532
1533   if (src->generic && gfc_add_generic (dest, NULL, where) == FAILURE)
1534     goto fail;
1535   if (src->function && gfc_add_function (dest, NULL, where) == FAILURE)
1536     goto fail;
1537   if (src->subroutine && gfc_add_subroutine (dest, NULL, where) == FAILURE)
1538     goto fail;
1539
1540   if (src->sequence && gfc_add_sequence (dest, NULL, where) == FAILURE)
1541     goto fail;
1542   if (src->elemental && gfc_add_elemental (dest, where) == FAILURE)
1543     goto fail;
1544   if (src->pure && gfc_add_pure (dest, where) == FAILURE)
1545     goto fail;
1546   if (src->recursive && gfc_add_recursive (dest, where) == FAILURE)
1547     goto fail;
1548
1549   if (src->flavor != FL_UNKNOWN
1550       && gfc_add_flavor (dest, src->flavor, NULL, where) == FAILURE)
1551     goto fail;
1552
1553   if (src->intent != INTENT_UNKNOWN
1554       && gfc_add_intent (dest, src->intent, where) == FAILURE)
1555     goto fail;
1556
1557   if (src->access != ACCESS_UNKNOWN
1558       && gfc_add_access (dest, src->access, NULL, where) == FAILURE)
1559     goto fail;
1560
1561   if (gfc_missing_attr (dest, where) == FAILURE)
1562     goto fail;
1563
1564   if (src->cray_pointer && gfc_add_cray_pointer (dest, where) == FAILURE)
1565     goto fail;
1566   if (src->cray_pointee && gfc_add_cray_pointee (dest, where) == FAILURE)
1567     goto fail;    
1568
1569   is_proc_lang_bind_spec = (src->flavor == FL_PROCEDURE ? 1 : 0);
1570   if (src->is_bind_c
1571       && gfc_add_is_bind_c (dest, NULL, where, is_proc_lang_bind_spec)
1572          != SUCCESS)
1573     return FAILURE;
1574
1575   if (src->is_c_interop)
1576     dest->is_c_interop = 1;
1577   if (src->is_iso_c)
1578     dest->is_iso_c = 1;
1579   
1580   if (src->external && gfc_add_external (dest, where) == FAILURE)
1581     goto fail;
1582   if (src->intrinsic && gfc_add_intrinsic (dest, where) == FAILURE)
1583     goto fail;
1584
1585   return SUCCESS;
1586
1587 fail:
1588   return FAILURE;
1589 }
1590
1591
1592 /************** Component name management ************/
1593
1594 /* Component names of a derived type form their own little namespaces
1595    that are separate from all other spaces.  The space is composed of
1596    a singly linked list of gfc_component structures whose head is
1597    located in the parent symbol.  */
1598
1599
1600 /* Add a component name to a symbol.  The call fails if the name is
1601    already present.  On success, the component pointer is modified to
1602    point to the additional component structure.  */
1603
1604 try
1605 gfc_add_component (gfc_symbol *sym, const char *name,
1606                    gfc_component **component)
1607 {
1608   gfc_component *p, *tail;
1609
1610   tail = NULL;
1611
1612   for (p = sym->components; p; p = p->next)
1613     {
1614       if (strcmp (p->name, name) == 0)
1615         {
1616           gfc_error ("Component '%s' at %C already declared at %L",
1617                      name, &p->loc);
1618           return FAILURE;
1619         }
1620
1621       tail = p;
1622     }
1623
1624   /* Allocate a new component.  */
1625   p = gfc_get_component ();
1626
1627   if (tail == NULL)
1628     sym->components = p;
1629   else
1630     tail->next = p;
1631
1632   p->name = gfc_get_string (name);
1633   p->loc = gfc_current_locus;
1634
1635   *component = p;
1636   return SUCCESS;
1637 }
1638
1639
1640 /* Recursive function to switch derived types of all symbol in a
1641    namespace.  */
1642
1643 static void
1644 switch_types (gfc_symtree *st, gfc_symbol *from, gfc_symbol *to)
1645 {
1646   gfc_symbol *sym;
1647
1648   if (st == NULL)
1649     return;
1650
1651   sym = st->n.sym;
1652   if (sym->ts.type == BT_DERIVED && sym->ts.derived == from)
1653     sym->ts.derived = to;
1654
1655   switch_types (st->left, from, to);
1656   switch_types (st->right, from, to);
1657 }
1658
1659
1660 /* This subroutine is called when a derived type is used in order to
1661    make the final determination about which version to use.  The
1662    standard requires that a type be defined before it is 'used', but
1663    such types can appear in IMPLICIT statements before the actual
1664    definition.  'Using' in this context means declaring a variable to
1665    be that type or using the type constructor.
1666
1667    If a type is used and the components haven't been defined, then we
1668    have to have a derived type in a parent unit.  We find the node in
1669    the other namespace and point the symtree node in this namespace to
1670    that node.  Further reference to this name point to the correct
1671    node.  If we can't find the node in a parent namespace, then we have
1672    an error.
1673
1674    This subroutine takes a pointer to a symbol node and returns a
1675    pointer to the translated node or NULL for an error.  Usually there
1676    is no translation and we return the node we were passed.  */
1677
1678 gfc_symbol *
1679 gfc_use_derived (gfc_symbol *sym)
1680 {
1681   gfc_symbol *s;
1682   gfc_typespec *t;
1683   gfc_symtree *st;
1684   int i;
1685
1686   if (sym->components != NULL)
1687     return sym;               /* Already defined.  */
1688
1689   if (sym->ns->parent == NULL)
1690     goto bad;
1691
1692   if (gfc_find_symbol (sym->name, sym->ns->parent, 1, &s))
1693     {
1694       gfc_error ("Symbol '%s' at %C is ambiguous", sym->name);
1695       return NULL;
1696     }
1697
1698   if (s == NULL || s->attr.flavor != FL_DERIVED)
1699     goto bad;
1700
1701   /* Get rid of symbol sym, translating all references to s.  */
1702   for (i = 0; i < GFC_LETTERS; i++)
1703     {
1704       t = &sym->ns->default_type[i];
1705       if (t->derived == sym)
1706         t->derived = s;
1707     }
1708
1709   st = gfc_find_symtree (sym->ns->sym_root, sym->name);
1710   st->n.sym = s;
1711
1712   s->refs++;
1713
1714   /* Unlink from list of modified symbols.  */
1715   gfc_commit_symbol (sym);
1716
1717   switch_types (sym->ns->sym_root, sym, s);
1718
1719   /* TODO: Also have to replace sym -> s in other lists like
1720      namelists, common lists and interface lists.  */
1721   gfc_free_symbol (sym);
1722
1723   return s;
1724
1725 bad:
1726   gfc_error ("Derived type '%s' at %C is being used before it is defined",
1727              sym->name);
1728   return NULL;
1729 }
1730
1731
1732 /* Given a derived type node and a component name, try to locate the
1733    component structure.  Returns the NULL pointer if the component is
1734    not found or the components are private.  */
1735
1736 gfc_component *
1737 gfc_find_component (gfc_symbol *sym, const char *name)
1738 {
1739   gfc_component *p;
1740
1741   if (name == NULL)
1742     return NULL;
1743
1744   sym = gfc_use_derived (sym);
1745
1746   if (sym == NULL)
1747     return NULL;
1748
1749   for (p = sym->components; p; p = p->next)
1750     if (strcmp (p->name, name) == 0)
1751       break;
1752
1753   if (p == NULL)
1754     gfc_error ("'%s' at %C is not a member of the '%s' structure",
1755                name, sym->name);
1756   else
1757     {
1758       if (sym->attr.use_assoc && (sym->component_access == ACCESS_PRIVATE
1759                                   || p->access == ACCESS_PRIVATE))
1760         {
1761           gfc_error ("Component '%s' at %C is a PRIVATE component of '%s'",
1762                      name, sym->name);
1763           p = NULL;
1764         }
1765     }
1766
1767   return p;
1768 }
1769
1770
1771 /* Given a symbol, free all of the component structures and everything
1772    they point to.  */
1773
1774 static void
1775 free_components (gfc_component *p)
1776 {
1777   gfc_component *q;
1778
1779   for (; p; p = q)
1780     {
1781       q = p->next;
1782
1783       gfc_free_array_spec (p->as);
1784       gfc_free_expr (p->initializer);
1785
1786       gfc_free (p);
1787     }
1788 }
1789
1790
1791 /* Set component attributes from a standard symbol attribute structure.  */
1792
1793 void
1794 gfc_set_component_attr (gfc_component *c, symbol_attribute *attr)
1795 {
1796
1797   c->dimension = attr->dimension;
1798   c->pointer = attr->pointer;
1799   c->allocatable = attr->allocatable;
1800   c->access = attr->access;
1801 }
1802
1803
1804 /* Get a standard symbol attribute structure given the component
1805    structure.  */
1806
1807 void
1808 gfc_get_component_attr (symbol_attribute *attr, gfc_component *c)
1809 {
1810
1811   gfc_clear_attr (attr);
1812   attr->dimension = c->dimension;
1813   attr->pointer = c->pointer;
1814   attr->allocatable = c->allocatable;
1815   attr->access = c->access;
1816 }
1817
1818
1819 /******************** Statement label management ********************/
1820
1821 /* Comparison function for statement labels, used for managing the
1822    binary tree.  */
1823
1824 static int
1825 compare_st_labels (void *a1, void *b1)
1826 {
1827   int a = ((gfc_st_label *) a1)->value;
1828   int b = ((gfc_st_label *) b1)->value;
1829
1830   return (b - a);
1831 }
1832
1833
1834 /* Free a single gfc_st_label structure, making sure the tree is not
1835    messed up.  This function is called only when some parse error
1836    occurs.  */
1837
1838 void
1839 gfc_free_st_label (gfc_st_label *label)
1840 {
1841
1842   if (label == NULL)
1843     return;
1844
1845   gfc_delete_bbt (&gfc_current_ns->st_labels, label, compare_st_labels);
1846
1847   if (label->format != NULL)
1848     gfc_free_expr (label->format);
1849
1850   gfc_free (label);
1851 }
1852
1853
1854 /* Free a whole tree of gfc_st_label structures.  */
1855
1856 static void
1857 free_st_labels (gfc_st_label *label)
1858 {
1859
1860   if (label == NULL)
1861     return;
1862
1863   free_st_labels (label->left);
1864   free_st_labels (label->right);
1865   
1866   if (label->format != NULL)
1867     gfc_free_expr (label->format);
1868   gfc_free (label);
1869 }
1870
1871
1872 /* Given a label number, search for and return a pointer to the label
1873    structure, creating it if it does not exist.  */
1874
1875 gfc_st_label *
1876 gfc_get_st_label (int labelno)
1877 {
1878   gfc_st_label *lp;
1879
1880   /* First see if the label is already in this namespace.  */
1881   lp = gfc_current_ns->st_labels;
1882   while (lp)
1883     {
1884       if (lp->value == labelno)
1885         return lp;
1886
1887       if (lp->value < labelno)
1888         lp = lp->left;
1889       else
1890         lp = lp->right;
1891     }
1892
1893   lp = gfc_getmem (sizeof (gfc_st_label));
1894
1895   lp->value = labelno;
1896   lp->defined = ST_LABEL_UNKNOWN;
1897   lp->referenced = ST_LABEL_UNKNOWN;
1898
1899   gfc_insert_bbt (&gfc_current_ns->st_labels, lp, compare_st_labels);
1900
1901   return lp;
1902 }
1903
1904
1905 /* Called when a statement with a statement label is about to be
1906    accepted.  We add the label to the list of the current namespace,
1907    making sure it hasn't been defined previously and referenced
1908    correctly.  */
1909
1910 void
1911 gfc_define_st_label (gfc_st_label *lp, gfc_sl_type type, locus *label_locus)
1912 {
1913   int labelno;
1914
1915   labelno = lp->value;
1916
1917   if (lp->defined != ST_LABEL_UNKNOWN)
1918     gfc_error ("Duplicate statement label %d at %L and %L", labelno,
1919                &lp->where, label_locus);
1920   else
1921     {
1922       lp->where = *label_locus;
1923
1924       switch (type)
1925         {
1926         case ST_LABEL_FORMAT:
1927           if (lp->referenced == ST_LABEL_TARGET)
1928             gfc_error ("Label %d at %C already referenced as branch target",
1929                        labelno);
1930           else
1931             lp->defined = ST_LABEL_FORMAT;
1932
1933           break;
1934
1935         case ST_LABEL_TARGET:
1936           if (lp->referenced == ST_LABEL_FORMAT)
1937             gfc_error ("Label %d at %C already referenced as a format label",
1938                        labelno);
1939           else
1940             lp->defined = ST_LABEL_TARGET;
1941
1942           break;
1943
1944         default:
1945           lp->defined = ST_LABEL_BAD_TARGET;
1946           lp->referenced = ST_LABEL_BAD_TARGET;
1947         }
1948     }
1949 }
1950
1951
1952 /* Reference a label.  Given a label and its type, see if that
1953    reference is consistent with what is known about that label,
1954    updating the unknown state.  Returns FAILURE if something goes
1955    wrong.  */
1956
1957 try
1958 gfc_reference_st_label (gfc_st_label *lp, gfc_sl_type type)
1959 {
1960   gfc_sl_type label_type;
1961   int labelno;
1962   try rc;
1963
1964   if (lp == NULL)
1965     return SUCCESS;
1966
1967   labelno = lp->value;
1968
1969   if (lp->defined != ST_LABEL_UNKNOWN)
1970     label_type = lp->defined;
1971   else
1972     {
1973       label_type = lp->referenced;
1974       lp->where = gfc_current_locus;
1975     }
1976
1977   if (label_type == ST_LABEL_FORMAT && type == ST_LABEL_TARGET)
1978     {
1979       gfc_error ("Label %d at %C previously used as a FORMAT label", labelno);
1980       rc = FAILURE;
1981       goto done;
1982     }
1983
1984   if ((label_type == ST_LABEL_TARGET || label_type == ST_LABEL_BAD_TARGET)
1985       && type == ST_LABEL_FORMAT)
1986     {
1987       gfc_error ("Label %d at %C previously used as branch target", labelno);
1988       rc = FAILURE;
1989       goto done;
1990     }
1991
1992   lp->referenced = type;
1993   rc = SUCCESS;
1994
1995 done:
1996   return rc;
1997 }
1998
1999
2000 /*******A helper function for creating new expressions*************/
2001
2002
2003 gfc_expr *
2004 gfc_lval_expr_from_sym (gfc_symbol *sym)
2005 {
2006   gfc_expr *lval;
2007   lval = gfc_get_expr ();
2008   lval->expr_type = EXPR_VARIABLE;
2009   lval->where = sym->declared_at;
2010   lval->ts = sym->ts;
2011   lval->symtree = gfc_find_symtree (sym->ns->sym_root, sym->name);
2012
2013   /* It will always be a full array.  */
2014   lval->rank = sym->as ? sym->as->rank : 0;
2015   if (lval->rank)
2016     {
2017       lval->ref = gfc_get_ref ();
2018       lval->ref->type = REF_ARRAY;
2019       lval->ref->u.ar.type = AR_FULL;
2020       lval->ref->u.ar.dimen = lval->rank;
2021       lval->ref->u.ar.where = sym->declared_at;
2022       lval->ref->u.ar.as = sym->as;
2023     }
2024
2025   return lval;
2026 }
2027
2028
2029 /************** Symbol table management subroutines ****************/
2030
2031 /* Basic details: Fortran 95 requires a potentially unlimited number
2032    of distinct namespaces when compiling a program unit.  This case
2033    occurs during a compilation of internal subprograms because all of
2034    the internal subprograms must be read before we can start
2035    generating code for the host.
2036
2037    Given the tricky nature of the Fortran grammar, we must be able to
2038    undo changes made to a symbol table if the current interpretation
2039    of a statement is found to be incorrect.  Whenever a symbol is
2040    looked up, we make a copy of it and link to it.  All of these
2041    symbols are kept in a singly linked list so that we can commit or
2042    undo the changes at a later time.
2043
2044    A symtree may point to a symbol node outside of its namespace.  In
2045    this case, that symbol has been used as a host associated variable
2046    at some previous time.  */
2047
2048 /* Allocate a new namespace structure.  Copies the implicit types from
2049    PARENT if PARENT_TYPES is set.  */
2050
2051 gfc_namespace *
2052 gfc_get_namespace (gfc_namespace *parent, int parent_types)
2053 {
2054   gfc_namespace *ns;
2055   gfc_typespec *ts;
2056   gfc_intrinsic_op in;
2057   int i;
2058
2059   ns = gfc_getmem (sizeof (gfc_namespace));
2060   ns->sym_root = NULL;
2061   ns->uop_root = NULL;
2062   ns->default_access = ACCESS_UNKNOWN;
2063   ns->parent = parent;
2064
2065   for (in = GFC_INTRINSIC_BEGIN; in != GFC_INTRINSIC_END; in++)
2066     ns->operator_access[in] = ACCESS_UNKNOWN;
2067
2068   /* Initialize default implicit types.  */
2069   for (i = 'a'; i <= 'z'; i++)
2070     {
2071       ns->set_flag[i - 'a'] = 0;
2072       ts = &ns->default_type[i - 'a'];
2073
2074       if (parent_types && ns->parent != NULL)
2075         {
2076           /* Copy parent settings.  */
2077           *ts = ns->parent->default_type[i - 'a'];
2078           continue;
2079         }
2080
2081       if (gfc_option.flag_implicit_none != 0)
2082         {
2083           gfc_clear_ts (ts);
2084           continue;
2085         }
2086
2087       if ('i' <= i && i <= 'n')
2088         {
2089           ts->type = BT_INTEGER;
2090           ts->kind = gfc_default_integer_kind;
2091         }
2092       else
2093         {
2094           ts->type = BT_REAL;
2095           ts->kind = gfc_default_real_kind;
2096         }
2097     }
2098
2099   ns->refs = 1;
2100
2101   return ns;
2102 }
2103
2104
2105 /* Comparison function for symtree nodes.  */
2106
2107 static int
2108 compare_symtree (void *_st1, void *_st2)
2109 {
2110   gfc_symtree *st1, *st2;
2111
2112   st1 = (gfc_symtree *) _st1;
2113   st2 = (gfc_symtree *) _st2;
2114
2115   return strcmp (st1->name, st2->name);
2116 }
2117
2118
2119 /* Allocate a new symtree node and associate it with the new symbol.  */
2120
2121 gfc_symtree *
2122 gfc_new_symtree (gfc_symtree **root, const char *name)
2123 {
2124   gfc_symtree *st;
2125
2126   st = gfc_getmem (sizeof (gfc_symtree));
2127   st->name = gfc_get_string (name);
2128
2129   gfc_insert_bbt (root, st, compare_symtree);
2130   return st;
2131 }
2132
2133
2134 /* Delete a symbol from the tree.  Does not free the symbol itself!  */
2135
2136 static void
2137 delete_symtree (gfc_symtree **root, const char *name)
2138 {
2139   gfc_symtree st, *st0;
2140
2141   st0 = gfc_find_symtree (*root, name);
2142
2143   st.name = gfc_get_string (name);
2144   gfc_delete_bbt (root, &st, compare_symtree);
2145
2146   gfc_free (st0);
2147 }
2148
2149
2150 /* Given a root symtree node and a name, try to find the symbol within
2151    the namespace.  Returns NULL if the symbol is not found.  */
2152
2153 gfc_symtree *
2154 gfc_find_symtree (gfc_symtree *st, const char *name)
2155 {
2156   int c;
2157
2158   while (st != NULL)
2159     {
2160       c = strcmp (name, st->name);
2161       if (c == 0)
2162         return st;
2163
2164       st = (c < 0) ? st->left : st->right;
2165     }
2166
2167   return NULL;
2168 }
2169
2170
2171 /* Return a symtree node with a name that is guaranteed to be unique
2172    within the namespace and corresponds to an illegal fortran name.  */
2173
2174 gfc_symtree *
2175 gfc_get_unique_symtree (gfc_namespace *ns)
2176 {
2177   char name[GFC_MAX_SYMBOL_LEN + 1];
2178   static int serial = 0;
2179
2180   sprintf (name, "@%d", serial++);
2181   return gfc_new_symtree (&ns->sym_root, name);
2182 }
2183
2184
2185 /* Given a name find a user operator node, creating it if it doesn't
2186    exist.  These are much simpler than symbols because they can't be
2187    ambiguous with one another.  */
2188
2189 gfc_user_op *
2190 gfc_get_uop (const char *name)
2191 {
2192   gfc_user_op *uop;
2193   gfc_symtree *st;
2194
2195   st = gfc_find_symtree (gfc_current_ns->uop_root, name);
2196   if (st != NULL)
2197     return st->n.uop;
2198
2199   st = gfc_new_symtree (&gfc_current_ns->uop_root, name);
2200
2201   uop = st->n.uop = gfc_getmem (sizeof (gfc_user_op));
2202   uop->name = gfc_get_string (name);
2203   uop->access = ACCESS_UNKNOWN;
2204   uop->ns = gfc_current_ns;
2205
2206   return uop;
2207 }
2208
2209
2210 /* Given a name find the user operator node.  Returns NULL if it does
2211    not exist.  */
2212
2213 gfc_user_op *
2214 gfc_find_uop (const char *name, gfc_namespace *ns)
2215 {
2216   gfc_symtree *st;
2217
2218   if (ns == NULL)
2219     ns = gfc_current_ns;
2220
2221   st = gfc_find_symtree (ns->uop_root, name);
2222   return (st == NULL) ? NULL : st->n.uop;
2223 }
2224
2225
2226 /* Remove a gfc_symbol structure and everything it points to.  */
2227
2228 void
2229 gfc_free_symbol (gfc_symbol *sym)
2230 {
2231
2232   if (sym == NULL)
2233     return;
2234
2235   gfc_free_array_spec (sym->as);
2236
2237   free_components (sym->components);
2238
2239   gfc_free_expr (sym->value);
2240
2241   gfc_free_namelist (sym->namelist);
2242
2243   gfc_free_namespace (sym->formal_ns);
2244
2245   if (!sym->attr.generic_copy)
2246     gfc_free_interface (sym->generic);
2247
2248   gfc_free_formal_arglist (sym->formal);
2249
2250   gfc_free (sym);
2251 }
2252
2253
2254 /* Allocate and initialize a new symbol node.  */
2255
2256 gfc_symbol *
2257 gfc_new_symbol (const char *name, gfc_namespace *ns)
2258 {
2259   gfc_symbol *p;
2260
2261   p = gfc_getmem (sizeof (gfc_symbol));
2262
2263   gfc_clear_ts (&p->ts);
2264   gfc_clear_attr (&p->attr);
2265   p->ns = ns;
2266
2267   p->declared_at = gfc_current_locus;
2268
2269   if (strlen (name) > GFC_MAX_SYMBOL_LEN)
2270     gfc_internal_error ("new_symbol(): Symbol name too long");
2271
2272   p->name = gfc_get_string (name);
2273
2274   /* Make sure flags for symbol being C bound are clear initially.  */
2275   p->attr.is_bind_c = 0;
2276   p->attr.is_iso_c = 0;
2277   /* Make sure the binding label field has a Nul char to start.  */
2278   p->binding_label[0] = '\0';
2279
2280   /* Clear the ptrs we may need.  */
2281   p->common_block = NULL;
2282   
2283   return p;
2284 }
2285
2286
2287 /* Generate an error if a symbol is ambiguous.  */
2288
2289 static void
2290 ambiguous_symbol (const char *name, gfc_symtree *st)
2291 {
2292
2293   if (st->n.sym->module)
2294     gfc_error ("Name '%s' at %C is an ambiguous reference to '%s' "
2295                "from module '%s'", name, st->n.sym->name, st->n.sym->module);
2296   else
2297     gfc_error ("Name '%s' at %C is an ambiguous reference to '%s' "
2298                "from current program unit", name, st->n.sym->name);
2299 }
2300
2301
2302 /* Search for a symtree starting in the current namespace, resorting to
2303    any parent namespaces if requested by a nonzero parent_flag.
2304    Returns nonzero if the name is ambiguous.  */
2305
2306 int
2307 gfc_find_sym_tree (const char *name, gfc_namespace *ns, int parent_flag,
2308                    gfc_symtree **result)
2309 {
2310   gfc_symtree *st;
2311
2312   if (ns == NULL)
2313     ns = gfc_current_ns;
2314
2315   do
2316     {
2317       st = gfc_find_symtree (ns->sym_root, name);
2318       if (st != NULL)
2319         {
2320           *result = st;
2321           /* Ambiguous generic interfaces are permitted, as long
2322              as the specific interfaces are different.  */
2323           if (st->ambiguous && !st->n.sym->attr.generic)
2324             {
2325               ambiguous_symbol (name, st);
2326               return 1;
2327             }
2328
2329           return 0;
2330         }
2331
2332       if (!parent_flag)
2333         break;
2334
2335       ns = ns->parent;
2336     }
2337   while (ns != NULL);
2338
2339   *result = NULL;
2340   return 0;
2341 }
2342
2343
2344 /* Same, but returns the symbol instead.  */
2345
2346 int
2347 gfc_find_symbol (const char *name, gfc_namespace *ns, int parent_flag,
2348                  gfc_symbol **result)
2349 {
2350   gfc_symtree *st;
2351   int i;
2352
2353   i = gfc_find_sym_tree (name, ns, parent_flag, &st);
2354
2355   if (st == NULL)
2356     *result = NULL;
2357   else
2358     *result = st->n.sym;
2359
2360   return i;
2361 }
2362
2363
2364 /* Save symbol with the information necessary to back it out.  */
2365
2366 static void
2367 save_symbol_data (gfc_symbol *sym)
2368 {
2369
2370   if (sym->new || sym->old_symbol != NULL)
2371     return;
2372
2373   sym->old_symbol = gfc_getmem (sizeof (gfc_symbol));
2374   *(sym->old_symbol) = *sym;
2375
2376   sym->tlink = changed_syms;
2377   changed_syms = sym;
2378 }
2379
2380
2381 /* Given a name, find a symbol, or create it if it does not exist yet
2382    in the current namespace.  If the symbol is found we make sure that
2383    it's OK.
2384
2385    The integer return code indicates
2386      0   All OK
2387      1   The symbol name was ambiguous
2388      2   The name meant to be established was already host associated.
2389
2390    So if the return value is nonzero, then an error was issued.  */
2391
2392 int
2393 gfc_get_sym_tree (const char *name, gfc_namespace *ns, gfc_symtree **result)
2394 {
2395   gfc_symtree *st;
2396   gfc_symbol *p;
2397
2398   /* This doesn't usually happen during resolution.  */
2399   if (ns == NULL)
2400     ns = gfc_current_ns;
2401
2402   /* Try to find the symbol in ns.  */
2403   st = gfc_find_symtree (ns->sym_root, name);
2404
2405   if (st == NULL)
2406     {
2407       /* If not there, create a new symbol.  */
2408       p = gfc_new_symbol (name, ns);
2409
2410       /* Add to the list of tentative symbols.  */
2411       p->old_symbol = NULL;
2412       p->tlink = changed_syms;
2413       p->mark = 1;
2414       p->new = 1;
2415       changed_syms = p;
2416
2417       st = gfc_new_symtree (&ns->sym_root, name);
2418       st->n.sym = p;
2419       p->refs++;
2420
2421     }
2422   else
2423     {
2424       /* Make sure the existing symbol is OK.  Ambiguous
2425          generic interfaces are permitted, as long as the
2426          specific interfaces are different.  */
2427       if (st->ambiguous && !st->n.sym->attr.generic)
2428         {
2429           ambiguous_symbol (name, st);
2430           return 1;
2431         }
2432
2433       p = st->n.sym;
2434
2435       if (p->ns != ns && (!p->attr.function || ns->proc_name != p)
2436             && !(ns->proc_name
2437                    && ns->proc_name->attr.if_source == IFSRC_IFBODY
2438                    && (ns->has_import_set || p->attr.imported)))
2439         {
2440           /* Symbol is from another namespace.  */
2441           gfc_error ("Symbol '%s' at %C has already been host associated",
2442                      name);
2443           return 2;
2444         }
2445
2446       p->mark = 1;
2447
2448       /* Copy in case this symbol is changed.  */
2449       save_symbol_data (p);
2450     }
2451
2452   *result = st;
2453   return 0;
2454 }
2455
2456
2457 int
2458 gfc_get_symbol (const char *name, gfc_namespace *ns, gfc_symbol **result)
2459 {
2460   gfc_symtree *st;
2461   int i;
2462
2463   i = gfc_get_sym_tree (name, ns, &st);
2464   if (i != 0)
2465     return i;
2466
2467   if (st)
2468     *result = st->n.sym;
2469   else
2470     *result = NULL;
2471   return i;
2472 }
2473
2474
2475 /* Subroutine that searches for a symbol, creating it if it doesn't
2476    exist, but tries to host-associate the symbol if possible.  */
2477
2478 int
2479 gfc_get_ha_sym_tree (const char *name, gfc_symtree **result)
2480 {
2481   gfc_symtree *st;
2482   int i;
2483
2484   i = gfc_find_sym_tree (name, gfc_current_ns, 0, &st);
2485   if (st != NULL)
2486     {
2487       save_symbol_data (st->n.sym);
2488       *result = st;
2489       return i;
2490     }
2491
2492   if (gfc_current_ns->parent != NULL)
2493     {
2494       i = gfc_find_sym_tree (name, gfc_current_ns->parent, 1, &st);
2495       if (i)
2496         return i;
2497
2498       if (st != NULL)
2499         {
2500           *result = st;
2501           return 0;
2502         }
2503     }
2504
2505   return gfc_get_sym_tree (name, gfc_current_ns, result);
2506 }
2507
2508
2509 int
2510 gfc_get_ha_symbol (const char *name, gfc_symbol **result)
2511 {
2512   int i;
2513   gfc_symtree *st;
2514
2515   i = gfc_get_ha_sym_tree (name, &st);
2516
2517   if (st)
2518     *result = st->n.sym;
2519   else
2520     *result = NULL;
2521
2522   return i;
2523 }
2524
2525 /* Return true if both symbols could refer to the same data object.  Does
2526    not take account of aliasing due to equivalence statements.  */
2527
2528 int
2529 gfc_symbols_could_alias (gfc_symbol *lsym, gfc_symbol *rsym)
2530 {
2531   /* Aliasing isn't possible if the symbols have different base types.  */
2532   if (gfc_compare_types (&lsym->ts, &rsym->ts) == 0)
2533     return 0;
2534
2535   /* Pointers can point to other pointers, target objects and allocatable
2536      objects.  Two allocatable objects cannot share the same storage.  */
2537   if (lsym->attr.pointer
2538       && (rsym->attr.pointer || rsym->attr.allocatable || rsym->attr.target))
2539     return 1;
2540   if (lsym->attr.target && rsym->attr.pointer)
2541     return 1;
2542   if (lsym->attr.allocatable && rsym->attr.pointer)
2543     return 1;
2544
2545   return 0;
2546 }
2547
2548
2549 /* Undoes all the changes made to symbols in the current statement.
2550    This subroutine is made simpler due to the fact that attributes are
2551    never removed once added.  */
2552
2553 void
2554 gfc_undo_symbols (void)
2555 {
2556   gfc_symbol *p, *q, *old;
2557
2558   for (p = changed_syms; p; p = q)
2559     {
2560       q = p->tlink;
2561
2562       if (p->new)
2563         {
2564           /* Symbol was new.  */
2565           delete_symtree (&p->ns->sym_root, p->name);
2566
2567           p->refs--;
2568           if (p->refs < 0)
2569             gfc_internal_error ("gfc_undo_symbols(): Negative refs");
2570           if (p->refs == 0)
2571             gfc_free_symbol (p);
2572           continue;
2573         }
2574
2575       /* Restore previous state of symbol.  Just copy simple stuff.  */
2576       p->mark = 0;
2577       old = p->old_symbol;
2578
2579       p->ts.type = old->ts.type;
2580       p->ts.kind = old->ts.kind;
2581
2582       p->attr = old->attr;
2583
2584       if (p->value != old->value)
2585         {
2586           gfc_free_expr (old->value);
2587           p->value = NULL;
2588         }
2589
2590       if (p->as != old->as)
2591         {
2592           if (p->as)
2593             gfc_free_array_spec (p->as);
2594           p->as = old->as;
2595         }
2596
2597       p->generic = old->generic;
2598       p->component_access = old->component_access;
2599
2600       if (p->namelist != NULL && old->namelist == NULL)
2601         {
2602           gfc_free_namelist (p->namelist);
2603           p->namelist = NULL;
2604         }
2605       else
2606         {
2607           if (p->namelist_tail != old->namelist_tail)
2608             {
2609               gfc_free_namelist (old->namelist_tail);
2610               old->namelist_tail->next = NULL;
2611             }
2612         }
2613
2614       p->namelist_tail = old->namelist_tail;
2615
2616       if (p->formal != old->formal)
2617         {
2618           gfc_free_formal_arglist (p->formal);
2619           p->formal = old->formal;
2620         }
2621
2622       gfc_free (p->old_symbol);
2623       p->old_symbol = NULL;
2624       p->tlink = NULL;
2625     }
2626
2627   changed_syms = NULL;
2628 }
2629
2630
2631 /* Free sym->old_symbol. sym->old_symbol is mostly a shallow copy of sym; the
2632    components of old_symbol that might need deallocation are the "allocatables"
2633    that are restored in gfc_undo_symbols(), with two exceptions: namelist and
2634    namelist_tail.  In case these differ between old_symbol and sym, it's just
2635    because sym->namelist has gotten a few more items.  */
2636
2637 static void
2638 free_old_symbol (gfc_symbol *sym)
2639 {
2640
2641   if (sym->old_symbol == NULL)
2642     return;
2643
2644   if (sym->old_symbol->as != sym->as) 
2645     gfc_free_array_spec (sym->old_symbol->as);
2646
2647   if (sym->old_symbol->value != sym->value) 
2648     gfc_free_expr (sym->old_symbol->value);
2649
2650   if (sym->old_symbol->formal != sym->formal)
2651     gfc_free_formal_arglist (sym->old_symbol->formal);
2652
2653   gfc_free (sym->old_symbol);
2654   sym->old_symbol = NULL;
2655 }
2656
2657
2658 /* Makes the changes made in the current statement permanent-- gets
2659    rid of undo information.  */
2660
2661 void
2662 gfc_commit_symbols (void)
2663 {
2664   gfc_symbol *p, *q;
2665
2666   for (p = changed_syms; p; p = q)
2667     {
2668       q = p->tlink;
2669       p->tlink = NULL;
2670       p->mark = 0;
2671       p->new = 0;
2672       free_old_symbol (p);
2673     }
2674   changed_syms = NULL;
2675 }
2676
2677
2678 /* Makes the changes made in one symbol permanent -- gets rid of undo
2679    information.  */
2680
2681 void
2682 gfc_commit_symbol (gfc_symbol *sym)
2683 {
2684   gfc_symbol *p;
2685
2686   if (changed_syms == sym)
2687     changed_syms = sym->tlink;
2688   else
2689     {
2690       for (p = changed_syms; p; p = p->tlink)
2691         if (p->tlink == sym)
2692           {
2693             p->tlink = sym->tlink;
2694             break;
2695           }
2696     }
2697
2698   sym->tlink = NULL;
2699   sym->mark = 0;
2700   sym->new = 0;
2701
2702   free_old_symbol (sym);
2703 }
2704
2705
2706 /* Recursive function that deletes an entire tree and all the common
2707    head structures it points to.  */
2708
2709 static void
2710 free_common_tree (gfc_symtree * common_tree)
2711 {
2712   if (common_tree == NULL)
2713     return;
2714
2715   free_common_tree (common_tree->left);
2716   free_common_tree (common_tree->right);
2717
2718   gfc_free (common_tree);
2719 }  
2720
2721
2722 /* Recursive function that deletes an entire tree and all the user
2723    operator nodes that it contains.  */
2724
2725 static void
2726 free_uop_tree (gfc_symtree *uop_tree)
2727 {
2728
2729   if (uop_tree == NULL)
2730     return;
2731
2732   free_uop_tree (uop_tree->left);
2733   free_uop_tree (uop_tree->right);
2734
2735   gfc_free_interface (uop_tree->n.uop->operator);
2736
2737   gfc_free (uop_tree->n.uop);
2738   gfc_free (uop_tree);
2739 }
2740
2741
2742 /* Recursive function that deletes an entire tree and all the symbols
2743    that it contains.  */
2744
2745 static void
2746 free_sym_tree (gfc_symtree *sym_tree)
2747 {
2748   gfc_namespace *ns;
2749   gfc_symbol *sym;
2750
2751   if (sym_tree == NULL)
2752     return;
2753
2754   free_sym_tree (sym_tree->left);
2755   free_sym_tree (sym_tree->right);
2756
2757   sym = sym_tree->n.sym;
2758
2759   sym->refs--;
2760   if (sym->refs < 0)
2761     gfc_internal_error ("free_sym_tree(): Negative refs");
2762
2763   if (sym->formal_ns != NULL && sym->refs == 1)
2764     {
2765       /* As formal_ns contains a reference to sym, delete formal_ns just
2766          before the deletion of sym.  */
2767       ns = sym->formal_ns;
2768       sym->formal_ns = NULL;
2769       gfc_free_namespace (ns);
2770     }
2771   else if (sym->refs == 0)
2772     {
2773       /* Go ahead and delete the symbol.  */
2774       gfc_free_symbol (sym);
2775     }
2776
2777   gfc_free (sym_tree);
2778 }
2779
2780
2781 /* Free the derived type list.  */
2782
2783 static void
2784 gfc_free_dt_list (void)
2785 {
2786   gfc_dt_list *dt, *n;
2787
2788   for (dt = gfc_derived_types; dt; dt = n)
2789     {
2790       n = dt->next;
2791       gfc_free (dt);
2792     }
2793
2794   gfc_derived_types = NULL;
2795 }
2796
2797
2798 /* Free the gfc_equiv_info's.  */
2799
2800 static void
2801 gfc_free_equiv_infos (gfc_equiv_info *s)
2802 {
2803   if (s == NULL)
2804     return;
2805   gfc_free_equiv_infos (s->next);
2806   gfc_free (s);
2807 }
2808
2809
2810 /* Free the gfc_equiv_lists.  */
2811
2812 static void
2813 gfc_free_equiv_lists (gfc_equiv_list *l)
2814 {
2815   if (l == NULL)
2816     return;
2817   gfc_free_equiv_lists (l->next);
2818   gfc_free_equiv_infos (l->equiv);
2819   gfc_free (l);
2820 }
2821
2822
2823 /* Free a namespace structure and everything below it.  Interface
2824    lists associated with intrinsic operators are not freed.  These are
2825    taken care of when a specific name is freed.  */
2826
2827 void
2828 gfc_free_namespace (gfc_namespace *ns)
2829 {
2830   gfc_charlen *cl, *cl2;
2831   gfc_namespace *p, *q;
2832   gfc_intrinsic_op i;
2833
2834   if (ns == NULL)
2835     return;
2836
2837   ns->refs--;
2838   if (ns->refs > 0)
2839     return;
2840   gcc_assert (ns->refs == 0);
2841
2842   gfc_free_statements (ns->code);
2843
2844   free_sym_tree (ns->sym_root);
2845   free_uop_tree (ns->uop_root);
2846   free_common_tree (ns->common_root);
2847
2848   for (cl = ns->cl_list; cl; cl = cl2)
2849     {
2850       cl2 = cl->next;
2851       gfc_free_expr (cl->length);
2852       gfc_free (cl);
2853     }
2854
2855   free_st_labels (ns->st_labels);
2856
2857   gfc_free_equiv (ns->equiv);
2858   gfc_free_equiv_lists (ns->equiv_lists);
2859
2860   for (i = GFC_INTRINSIC_BEGIN; i != GFC_INTRINSIC_END; i++)
2861     gfc_free_interface (ns->operator[i]);
2862
2863   gfc_free_data (ns->data);
2864   p = ns->contained;
2865   gfc_free (ns);
2866
2867   /* Recursively free any contained namespaces.  */
2868   while (p != NULL)
2869     {
2870       q = p;
2871       p = p->sibling;
2872       gfc_free_namespace (q);
2873     }
2874 }
2875
2876
2877 void
2878 gfc_symbol_init_2 (void)
2879 {
2880
2881   gfc_current_ns = gfc_get_namespace (NULL, 0);
2882 }
2883
2884
2885 void
2886 gfc_symbol_done_2 (void)
2887 {
2888
2889   gfc_free_namespace (gfc_current_ns);
2890   gfc_current_ns = NULL;
2891   gfc_free_dt_list ();
2892 }
2893
2894
2895 /* Clear mark bits from symbol nodes associated with a symtree node.  */
2896
2897 static void
2898 clear_sym_mark (gfc_symtree *st)
2899 {
2900
2901   st->n.sym->mark = 0;
2902 }
2903
2904
2905 /* Recursively traverse the symtree nodes.  */
2906
2907 void
2908 gfc_traverse_symtree (gfc_symtree *st, void (*func) (gfc_symtree *))
2909 {
2910   if (st != NULL)
2911     {
2912       (*func) (st);
2913
2914       gfc_traverse_symtree (st->left, func);
2915       gfc_traverse_symtree (st->right, func);
2916     }
2917 }
2918
2919
2920 /* Recursive namespace traversal function.  */
2921
2922 static void
2923 traverse_ns (gfc_symtree *st, void (*func) (gfc_symbol *))
2924 {
2925
2926   if (st == NULL)
2927     return;
2928
2929   if (st->n.sym->mark == 0)
2930     (*func) (st->n.sym);
2931   st->n.sym->mark = 1;
2932
2933   traverse_ns (st->left, func);
2934   traverse_ns (st->right, func);
2935 }
2936
2937
2938 /* Call a given function for all symbols in the namespace.  We take
2939    care that each gfc_symbol node is called exactly once.  */
2940
2941 void
2942 gfc_traverse_ns (gfc_namespace *ns, void (*func) (gfc_symbol *))
2943 {
2944
2945   gfc_traverse_symtree (ns->sym_root, clear_sym_mark);
2946
2947   traverse_ns (ns->sym_root, func);
2948 }
2949
2950
2951 /* Return TRUE when name is the name of an intrinsic type.  */
2952
2953 bool
2954 gfc_is_intrinsic_typename (const char *name)
2955 {
2956   if (strcmp (name, "integer") == 0
2957       || strcmp (name, "real") == 0
2958       || strcmp (name, "character") == 0
2959       || strcmp (name, "logical") == 0
2960       || strcmp (name, "complex") == 0
2961       || strcmp (name, "doubleprecision") == 0
2962       || strcmp (name, "doublecomplex") == 0)
2963     return true;
2964   else
2965     return false;
2966 }
2967
2968
2969 /* Return TRUE if the symbol is an automatic variable.  */
2970
2971 static bool
2972 gfc_is_var_automatic (gfc_symbol *sym)
2973 {
2974   /* Pointer and allocatable variables are never automatic.  */
2975   if (sym->attr.pointer || sym->attr.allocatable)
2976     return false;
2977   /* Check for arrays with non-constant size.  */
2978   if (sym->attr.dimension && sym->as
2979       && !gfc_is_compile_time_shape (sym->as))
2980     return true;
2981   /* Check for non-constant length character variables.  */
2982   if (sym->ts.type == BT_CHARACTER
2983       && sym->ts.cl
2984       && !gfc_is_constant_expr (sym->ts.cl->length))
2985     return true;
2986   return false;
2987 }
2988
2989 /* Given a symbol, mark it as SAVEd if it is allowed.  */
2990
2991 static void
2992 save_symbol (gfc_symbol *sym)
2993 {
2994
2995   if (sym->attr.use_assoc)
2996     return;
2997
2998   if (sym->attr.in_common
2999       || sym->attr.dummy
3000       || sym->attr.flavor != FL_VARIABLE)
3001     return;
3002   /* Automatic objects are not saved.  */
3003   if (gfc_is_var_automatic (sym))
3004     return;
3005   gfc_add_save (&sym->attr, sym->name, &sym->declared_at);
3006 }
3007
3008
3009 /* Mark those symbols which can be SAVEd as such.  */
3010
3011 void
3012 gfc_save_all (gfc_namespace *ns)
3013 {
3014
3015   gfc_traverse_ns (ns, save_symbol);
3016 }
3017
3018
3019 #ifdef GFC_DEBUG
3020 /* Make sure that no changes to symbols are pending.  */
3021
3022 void
3023 gfc_symbol_state(void) {
3024
3025   if (changed_syms != NULL)
3026     gfc_internal_error("Symbol changes still pending!");
3027 }
3028 #endif
3029
3030
3031 /************** Global symbol handling ************/
3032
3033
3034 /* Search a tree for the global symbol.  */
3035
3036 gfc_gsymbol *
3037 gfc_find_gsymbol (gfc_gsymbol *symbol, const char *name)
3038 {
3039   int c;
3040
3041   if (symbol == NULL)
3042     return NULL;
3043
3044   while (symbol)
3045     {
3046       c = strcmp (name, symbol->name);
3047       if (!c)
3048         return symbol;
3049
3050       symbol = (c < 0) ? symbol->left : symbol->right;
3051     }
3052
3053   return NULL;
3054 }
3055
3056
3057 /* Compare two global symbols. Used for managing the BB tree.  */
3058
3059 static int
3060 gsym_compare (void *_s1, void *_s2)
3061 {
3062   gfc_gsymbol *s1, *s2;
3063
3064   s1 = (gfc_gsymbol *) _s1;
3065   s2 = (gfc_gsymbol *) _s2;
3066   return strcmp (s1->name, s2->name);
3067 }
3068
3069
3070 /* Get a global symbol, creating it if it doesn't exist.  */
3071
3072 gfc_gsymbol *
3073 gfc_get_gsymbol (const char *name)
3074 {
3075   gfc_gsymbol *s;
3076
3077   s = gfc_find_gsymbol (gfc_gsym_root, name);
3078   if (s != NULL)
3079     return s;
3080
3081   s = gfc_getmem (sizeof (gfc_gsymbol));
3082   s->type = GSYM_UNKNOWN;
3083   s->name = gfc_get_string (name);
3084
3085   gfc_insert_bbt (&gfc_gsym_root, s, gsym_compare);
3086
3087   return s;
3088 }
3089
3090
3091 static gfc_symbol *
3092 get_iso_c_binding_dt (int sym_id)
3093 {
3094   gfc_dt_list *dt_list;
3095
3096   dt_list = gfc_derived_types;
3097
3098   /* Loop through the derived types in the name list, searching for
3099      the desired symbol from iso_c_binding.  Search the parent namespaces
3100      if necessary and requested to (parent_flag).  */
3101   while (dt_list != NULL)
3102     {
3103       if (dt_list->derived->from_intmod != INTMOD_NONE
3104           && dt_list->derived->intmod_sym_id == sym_id)
3105         return dt_list->derived;
3106
3107       dt_list = dt_list->next;
3108     }
3109
3110   return NULL;
3111 }
3112
3113
3114 /* Verifies that the given derived type symbol, derived_sym, is interoperable
3115    with C.  This is necessary for any derived type that is BIND(C) and for
3116    derived types that are parameters to functions that are BIND(C).  All
3117    fields of the derived type are required to be interoperable, and are tested
3118    for such.  If an error occurs, the errors are reported here, allowing for
3119    multiple errors to be handled for a single derived type.  */
3120
3121 try
3122 verify_bind_c_derived_type (gfc_symbol *derived_sym)
3123 {
3124   gfc_component *curr_comp = NULL;
3125   try is_c_interop = FAILURE;
3126   try retval = SUCCESS;
3127    
3128   if (derived_sym == NULL)
3129     gfc_internal_error ("verify_bind_c_derived_type(): Given symbol is "
3130                         "unexpectedly NULL");
3131
3132   /* If we've already looked at this derived symbol, do not look at it again
3133      so we don't repeat warnings/errors.  */
3134   if (derived_sym->ts.is_c_interop)
3135     return SUCCESS;
3136   
3137   /* The derived type must have the BIND attribute to be interoperable
3138      J3/04-007, Section 15.2.3.  */
3139   if (derived_sym->attr.is_bind_c != 1)
3140     {
3141       derived_sym->ts.is_c_interop = 0;
3142       gfc_error_now ("Derived type '%s' declared at %L must have the BIND "
3143                      "attribute to be C interoperable", derived_sym->name,
3144                      &(derived_sym->declared_at));
3145       retval = FAILURE;
3146     }
3147   
3148   curr_comp = derived_sym->components;
3149
3150   /* TODO: is this really an error?  */
3151   if (curr_comp == NULL)
3152     {
3153       gfc_error ("Derived type '%s' at %L is empty",
3154                  derived_sym->name, &(derived_sym->declared_at));
3155       return FAILURE;
3156     }
3157
3158   /* Initialize the derived type as being C interoperable.
3159      If we find an error in the components, this will be set false.  */
3160   derived_sym->ts.is_c_interop = 1;
3161   
3162   /* Loop through the list of components to verify that the kind of
3163      each is a C interoperable type.  */
3164   do
3165     {
3166       /* The components cannot be pointers (fortran sense).  
3167          J3/04-007, Section 15.2.3, C1505.      */
3168       if (curr_comp->pointer != 0)
3169         {
3170           gfc_error ("Component '%s' at %L cannot have the "
3171                      "POINTER attribute because it is a member "
3172                      "of the BIND(C) derived type '%s' at %L",
3173                      curr_comp->name, &(curr_comp->loc),
3174                      derived_sym->name, &(derived_sym->declared_at));
3175           retval = FAILURE;
3176         }
3177
3178       /* The components cannot be allocatable.
3179          J3/04-007, Section 15.2.3, C1505.      */
3180       if (curr_comp->allocatable != 0)
3181         {
3182           gfc_error ("Component '%s' at %L cannot have the "
3183                      "ALLOCATABLE attribute because it is a member "
3184                      "of the BIND(C) derived type '%s' at %L",
3185                      curr_comp->name, &(curr_comp->loc),
3186                      derived_sym->name, &(derived_sym->declared_at));
3187           retval = FAILURE;
3188         }
3189       
3190       /* BIND(C) derived types must have interoperable components.  */
3191       if (curr_comp->ts.type == BT_DERIVED
3192           && curr_comp->ts.derived->ts.is_iso_c != 1 
3193           && curr_comp->ts.derived != derived_sym)
3194         {
3195           /* This should be allowed; the draft says a derived-type can not
3196              have type parameters if it is has the BIND attribute.  Type
3197              parameters seem to be for making parameterized derived types.
3198              There's no need to verify the type if it is c_ptr/c_funptr.  */
3199           retval = verify_bind_c_derived_type (curr_comp->ts.derived);
3200         }
3201       else
3202         {
3203           /* Grab the typespec for the given component and test the kind.  */ 
3204           is_c_interop = verify_c_interop (&(curr_comp->ts), curr_comp->name,
3205                                            &(curr_comp->loc));
3206           
3207           if (is_c_interop != SUCCESS)
3208             {
3209               /* Report warning and continue since not fatal.  The
3210                  draft does specify a constraint that requires all fields
3211                  to interoperate, but if the user says real(4), etc., it
3212                  may interoperate with *something* in C, but the compiler
3213                  most likely won't know exactly what.  Further, it may not
3214                  interoperate with the same data type(s) in C if the user
3215                  recompiles with different flags (e.g., -m32 and -m64 on
3216                  x86_64 and using integer(4) to claim interop with a
3217                  C_LONG).  */
3218               if (derived_sym->attr.is_bind_c == 1)
3219                 /* If the derived type is bind(c), all fields must be
3220                    interop.  */
3221                 gfc_warning ("Component '%s' in derived type '%s' at %L "
3222                              "may not be C interoperable, even though "
3223                              "derived type '%s' is BIND(C)",
3224                              curr_comp->name, derived_sym->name,
3225                              &(curr_comp->loc), derived_sym->name);
3226               else
3227                 /* If derived type is param to bind(c) routine, or to one
3228                    of the iso_c_binding procs, it must be interoperable, so
3229                    all fields must interop too.  */
3230                 gfc_warning ("Component '%s' in derived type '%s' at %L "
3231                              "may not be C interoperable",
3232                              curr_comp->name, derived_sym->name,
3233                              &(curr_comp->loc));
3234             }
3235         }
3236       
3237       curr_comp = curr_comp->next;
3238     } while (curr_comp != NULL); 
3239
3240
3241   /* Make sure we don't have conflicts with the attributes.  */
3242   if (derived_sym->attr.access == ACCESS_PRIVATE)
3243     {
3244       gfc_error ("Derived type '%s' at %L cannot be declared with both "
3245                  "PRIVATE and BIND(C) attributes", derived_sym->name,
3246                  &(derived_sym->declared_at));
3247       retval = FAILURE;
3248     }
3249
3250   if (derived_sym->attr.sequence != 0)
3251     {
3252       gfc_error ("Derived type '%s' at %L cannot have the SEQUENCE "
3253                  "attribute because it is BIND(C)", derived_sym->name,
3254                  &(derived_sym->declared_at));
3255       retval = FAILURE;
3256     }
3257
3258   /* Mark the derived type as not being C interoperable if we found an
3259      error.  If there were only warnings, proceed with the assumption
3260      it's interoperable.  */
3261   if (retval == FAILURE)
3262     derived_sym->ts.is_c_interop = 0;
3263   
3264   return retval;
3265 }
3266
3267
3268 /* Generate symbols for the named constants c_null_ptr and c_null_funptr.  */
3269
3270 static try
3271 gen_special_c_interop_ptr (int ptr_id, const char *ptr_name,
3272                            const char *module_name)
3273 {
3274   gfc_symtree *tmp_symtree;
3275   gfc_symbol *tmp_sym;
3276
3277   tmp_symtree = gfc_find_symtree (gfc_current_ns->sym_root, ptr_name);
3278          
3279   if (tmp_symtree != NULL)
3280     tmp_sym = tmp_symtree->n.sym;
3281   else
3282     {
3283       tmp_sym = NULL;
3284       gfc_internal_error ("gen_special_c_interop_ptr(): Unable to "
3285                           "create symbol for %s", ptr_name);
3286     }
3287
3288   /* Set up the symbol's important fields.  Save attr required so we can
3289      initialize the ptr to NULL.  */
3290   tmp_sym->attr.save = SAVE_EXPLICIT;
3291   tmp_sym->ts.is_c_interop = 1;
3292   tmp_sym->attr.is_c_interop = 1;
3293   tmp_sym->ts.is_iso_c = 1;
3294   tmp_sym->ts.type = BT_DERIVED;
3295
3296   /* The c_ptr and c_funptr derived types will provide the
3297      definition for c_null_ptr and c_null_funptr, respectively.  */
3298   if (ptr_id == ISOCBINDING_NULL_PTR)
3299     tmp_sym->ts.derived = get_iso_c_binding_dt (ISOCBINDING_PTR);
3300   else
3301     tmp_sym->ts.derived = get_iso_c_binding_dt (ISOCBINDING_FUNPTR);
3302   if (tmp_sym->ts.derived == NULL)
3303     {
3304       /* This can occur if the user forgot to declare c_ptr or
3305          c_funptr and they're trying to use one of the procedures
3306          that has arg(s) of the missing type.  In this case, a
3307          regular version of the thing should have been put in the
3308          current ns.  */
3309       generate_isocbinding_symbol (module_name, ptr_id == ISOCBINDING_NULL_PTR 
3310                                    ? ISOCBINDING_PTR : ISOCBINDING_FUNPTR,
3311                                    (const char *) (ptr_id == ISOCBINDING_NULL_PTR 
3312                                    ? "_gfortran_iso_c_binding_c_ptr"
3313                                    : "_gfortran_iso_c_binding_c_funptr"));
3314
3315       tmp_sym->ts.derived =
3316         get_iso_c_binding_dt (ptr_id == ISOCBINDING_NULL_PTR
3317                               ? ISOCBINDING_PTR : ISOCBINDING_FUNPTR);
3318     }
3319
3320   /* Module name is some mangled version of iso_c_binding.  */
3321   tmp_sym->module = gfc_get_string (module_name);
3322   
3323   /* Say it's from the iso_c_binding module.  */
3324   tmp_sym->attr.is_iso_c = 1;
3325   
3326   tmp_sym->attr.use_assoc = 1;
3327   tmp_sym->attr.is_bind_c = 1;
3328   /* Set the binding_label.  */
3329   sprintf (tmp_sym->binding_label, "%s_%s", module_name, tmp_sym->name);
3330   
3331   /* Set the c_address field of c_null_ptr and c_null_funptr to
3332      the value of NULL.  */
3333   tmp_sym->value = gfc_get_expr ();
3334   tmp_sym->value->expr_type = EXPR_STRUCTURE;
3335   tmp_sym->value->ts.type = BT_DERIVED;
3336   tmp_sym->value->ts.derived = tmp_sym->ts.derived;
3337   tmp_sym->value->value.constructor = gfc_get_constructor ();
3338   /* This line will initialize the c_null_ptr/c_null_funptr
3339      c_address field to NULL.  */
3340   tmp_sym->value->value.constructor->expr = gfc_int_expr (0);
3341   /* Must declare c_null_ptr and c_null_funptr as having the
3342      PARAMETER attribute so they can be used in init expressions.  */
3343   tmp_sym->attr.flavor = FL_PARAMETER;
3344
3345   return SUCCESS;
3346 }
3347
3348
3349 /* Add a formal argument, gfc_formal_arglist, to the
3350    end of the given list of arguments.  Set the reference to the
3351    provided symbol, param_sym, in the argument.  */
3352
3353 static void
3354 add_formal_arg (gfc_formal_arglist **head,
3355                 gfc_formal_arglist **tail,
3356                 gfc_formal_arglist *formal_arg,
3357                 gfc_symbol *param_sym)
3358 {
3359   /* Put in list, either as first arg or at the tail (curr arg).  */
3360   if (*head == NULL)
3361     *head = *tail = formal_arg;
3362   else
3363     {
3364       (*tail)->next = formal_arg;
3365       (*tail) = formal_arg;
3366     }
3367    
3368   (*tail)->sym = param_sym;
3369   (*tail)->next = NULL;
3370    
3371   return;
3372 }
3373
3374
3375 /* Generates a symbol representing the CPTR argument to an
3376    iso_c_binding procedure.  Also, create a gfc_formal_arglist for the
3377    CPTR and add it to the provided argument list.  */
3378
3379 static void
3380 gen_cptr_param (gfc_formal_arglist **head,
3381                 gfc_formal_arglist **tail,
3382                 const char *module_name,
3383                 gfc_namespace *ns, const char *c_ptr_name,
3384                 int iso_c_sym_id)
3385 {
3386   gfc_symbol *param_sym = NULL;
3387   gfc_symbol *c_ptr_sym = NULL;
3388   gfc_symtree *param_symtree = NULL;
3389   gfc_formal_arglist *formal_arg = NULL;
3390   const char *c_ptr_in;
3391   const char *c_ptr_type = NULL;
3392
3393   if (iso_c_sym_id == ISOCBINDING_F_PROCPOINTER)
3394     c_ptr_type = "_gfortran_iso_c_binding_c_funptr";
3395   else
3396     c_ptr_type = "_gfortran_iso_c_binding_c_ptr";
3397
3398   if(c_ptr_name == NULL)
3399     c_ptr_in = "gfc_cptr__";
3400   else
3401     c_ptr_in = c_ptr_name;
3402   gfc_get_sym_tree (c_ptr_in, ns, &param_symtree);
3403   if (param_symtree != NULL)
3404     param_sym = param_symtree->n.sym;
3405   else
3406     gfc_internal_error ("gen_cptr_param(): Unable to "
3407                         "create symbol for %s", c_ptr_in);
3408
3409   /* Set up the appropriate fields for the new c_ptr param sym.  */
3410   param_sym->refs++;
3411   param_sym->attr.flavor = FL_DERIVED;
3412   param_sym->ts.type = BT_DERIVED;
3413   param_sym->attr.intent = INTENT_IN;
3414   param_sym->attr.dummy = 1;
3415
3416   /* This will pass the ptr to the iso_c routines as a (void *).  */
3417   param_sym->attr.value = 1;
3418   param_sym->attr.use_assoc = 1;
3419
3420   /* Get the symbol for c_ptr or c_funptr, no matter what it's name is 
3421      (user renamed).  */
3422   if (iso_c_sym_id == ISOCBINDING_F_PROCPOINTER)
3423     c_ptr_sym = get_iso_c_binding_dt (ISOCBINDING_FUNPTR);
3424   else
3425     c_ptr_sym = get_iso_c_binding_dt (ISOCBINDING_PTR);
3426   if (c_ptr_sym == NULL)
3427     {
3428       /* This can happen if the user did not define c_ptr but they are
3429          trying to use one of the iso_c_binding functions that need it.  */
3430       if (iso_c_sym_id == ISOCBINDING_F_PROCPOINTER)
3431         generate_isocbinding_symbol (module_name, ISOCBINDING_FUNPTR,
3432                                      (const char *)c_ptr_type);
3433       else
3434         generate_isocbinding_symbol (module_name, ISOCBINDING_PTR,
3435                                      (const char *)c_ptr_type);
3436
3437       gfc_get_ha_symbol (c_ptr_type, &(c_ptr_sym));
3438     }
3439
3440   param_sym->ts.derived = c_ptr_sym;
3441   param_sym->module = gfc_get_string (module_name);
3442
3443   /* Make new formal arg.  */
3444   formal_arg = gfc_get_formal_arglist ();
3445   /* Add arg to list of formal args (the CPTR arg).  */
3446   add_formal_arg (head, tail, formal_arg, param_sym);
3447 }
3448
3449
3450 /* Generates a symbol representing the FPTR argument to an
3451    iso_c_binding procedure.  Also, create a gfc_formal_arglist for the
3452    FPTR and add it to the provided argument list.  */
3453
3454 static void
3455 gen_fptr_param (gfc_formal_arglist **head,
3456                 gfc_formal_arglist **tail,
3457                 const char *module_name,
3458                 gfc_namespace *ns, const char *f_ptr_name)
3459 {
3460   gfc_symbol *param_sym = NULL;
3461   gfc_symtree *param_symtree = NULL;
3462   gfc_formal_arglist *formal_arg = NULL;
3463   const char *f_ptr_out = "gfc_fptr__";
3464
3465   if (f_ptr_name != NULL)
3466     f_ptr_out = f_ptr_name;
3467
3468   gfc_get_sym_tree (f_ptr_out, ns, &param_symtree);
3469   if (param_symtree != NULL)
3470     param_sym = param_symtree->n.sym;
3471   else
3472     gfc_internal_error ("generateFPtrParam(): Unable to "
3473                         "create symbol for %s", f_ptr_out);
3474
3475   /* Set up the necessary fields for the fptr output param sym.  */
3476   param_sym->refs++;
3477   param_sym->attr.pointer = 1;
3478   param_sym->attr.dummy = 1;
3479   param_sym->attr.use_assoc = 1;
3480
3481   /* ISO C Binding type to allow any pointer type as actual param.  */
3482   param_sym->ts.type = BT_VOID;
3483   param_sym->module = gfc_get_string (module_name);
3484    
3485   /* Make the arg.  */
3486   formal_arg = gfc_get_formal_arglist ();
3487   /* Add arg to list of formal args.  */
3488   add_formal_arg (head, tail, formal_arg, param_sym);
3489 }
3490
3491
3492 /* Generates a symbol representing the optional SHAPE argument for the
3493    iso_c_binding c_f_pointer() procedure.  Also, create a
3494    gfc_formal_arglist for the SHAPE and add it to the provided
3495    argument list.  */
3496
3497 static void
3498 gen_shape_param (gfc_formal_arglist **head,
3499                  gfc_formal_arglist **tail,
3500                  const char *module_name,
3501                  gfc_namespace *ns, const char *shape_param_name)
3502 {
3503   gfc_symbol *param_sym = NULL;
3504   gfc_symtree *param_symtree = NULL;
3505   gfc_formal_arglist *formal_arg = NULL;
3506   const char *shape_param = "gfc_shape_array__";
3507   int i;
3508
3509   if (shape_param_name != NULL)
3510     shape_param = shape_param_name;
3511
3512   gfc_get_sym_tree (shape_param, ns, &param_symtree);
3513   if (param_symtree != NULL)
3514     param_sym = param_symtree->n.sym;
3515   else
3516     gfc_internal_error ("generateShapeParam(): Unable to "
3517                         "create symbol for %s", shape_param);
3518    
3519   /* Set up the necessary fields for the shape input param sym.  */
3520   param_sym->refs++;
3521   param_sym->attr.dummy = 1;
3522   param_sym->attr.use_assoc = 1;
3523
3524   /* Integer array, rank 1, describing the shape of the object.  Make it's
3525      type BT_VOID initially so we can accept any type/kind combination of
3526      integer.  During gfc_iso_c_sub_interface (resolve.c), we'll make it
3527      of BT_INTEGER type.  */
3528   param_sym->ts.type = BT_VOID;
3529
3530   /* Initialize the kind to default integer.  However, it will be overridden
3531      during resolution to match the kind of the SHAPE parameter given as
3532      the actual argument (to allow for any valid integer kind).  */
3533   param_sym->ts.kind = gfc_default_integer_kind;   
3534   param_sym->as = gfc_get_array_spec ();
3535
3536   /* Clear out the dimension info for the array.  */
3537   for (i = 0; i < GFC_MAX_DIMENSIONS; i++)
3538     {
3539       param_sym->as->lower[i] = NULL;
3540       param_sym->as->upper[i] = NULL;
3541     }
3542   param_sym->as->rank = 1;
3543   param_sym->as->lower[0] = gfc_int_expr (1);
3544
3545   /* The extent is unknown until we get it.  The length give us
3546      the rank the incoming pointer.  */
3547   param_sym->as->type = AS_ASSUMED_SHAPE;
3548
3549   /* The arg is also optional; it is required iff the second arg
3550      (fptr) is to an array, otherwise, it's ignored.  */
3551   param_sym->attr.optional = 1;
3552   param_sym->attr.intent = INTENT_IN;
3553   param_sym->attr.dimension = 1;
3554   param_sym->module = gfc_get_string (module_name);
3555    
3556   /* Make the arg.  */
3557   formal_arg = gfc_get_formal_arglist ();
3558   /* Add arg to list of formal args.  */
3559   add_formal_arg (head, tail, formal_arg, param_sym);
3560 }
3561
3562 /* Add a procedure interface to the given symbol (i.e., store a
3563    reference to the list of formal arguments).  */
3564
3565 static void
3566 add_proc_interface (gfc_symbol *sym, ifsrc source,
3567                     gfc_formal_arglist *formal)
3568 {
3569
3570   sym->formal = formal;
3571   sym->attr.if_source = source;
3572 }
3573
3574 /* Copy the formal args from an existing symbol, src, into a new
3575    symbol, dest.  New formal args are created, and the description of
3576    each arg is set according to the existing ones.  This function is
3577    used when creating procedure declaration variables from a procedure
3578    declaration statement (see match_proc_decl()) to create the formal
3579    args based on the args of a given named interface.  */
3580
3581 void copy_formal_args (gfc_symbol *dest, gfc_symbol *src)
3582 {
3583   gfc_formal_arglist *head = NULL;
3584   gfc_formal_arglist *tail = NULL;
3585   gfc_formal_arglist *formal_arg = NULL;
3586   gfc_formal_arglist *curr_arg = NULL;
3587   gfc_formal_arglist *formal_prev = NULL;
3588   /* Save current namespace so we can change it for formal args.  */
3589   gfc_namespace *parent_ns = gfc_current_ns;
3590
3591   /* Create a new namespace, which will be the formal ns (namespace
3592      of the formal args).  */
3593   gfc_current_ns = gfc_get_namespace (parent_ns, 0);
3594   gfc_current_ns->proc_name = dest;
3595
3596   for (curr_arg = src->formal; curr_arg; curr_arg = curr_arg->next)
3597     {
3598       formal_arg = gfc_get_formal_arglist ();
3599       gfc_get_symbol (curr_arg->sym->name, gfc_current_ns, &(formal_arg->sym));
3600
3601       /* May need to copy more info for the symbol.  */
3602       formal_arg->sym->attr = curr_arg->sym->attr;
3603       formal_arg->sym->ts = curr_arg->sym->ts;
3604
3605       /* If this isn't the first arg, set up the next ptr.  For the
3606         last arg built, the formal_arg->next will never get set to
3607         anything other than NULL.  */
3608       if (formal_prev != NULL)
3609         formal_prev->next = formal_arg;
3610       else
3611         formal_arg->next = NULL;
3612
3613       formal_prev = formal_arg;
3614
3615       /* Add arg to list of formal args.  */
3616       add_formal_arg (&head, &tail, formal_arg, formal_arg->sym);
3617     }
3618
3619   /* Add the interface to the symbol.  */
3620   add_proc_interface (dest, IFSRC_DECL, head);
3621
3622   /* Store the formal namespace information.  */
3623   if (dest->formal != NULL)
3624     /* The current ns should be that for the dest proc.  */
3625     dest->formal_ns = gfc_current_ns;
3626   /* Restore the current namespace to what it was on entry.  */
3627   gfc_current_ns = parent_ns;
3628 }
3629
3630 /* Builds the parameter list for the iso_c_binding procedure
3631    c_f_pointer or c_f_procpointer.  The old_sym typically refers to a
3632    generic version of either the c_f_pointer or c_f_procpointer
3633    functions.  The new_proc_sym represents a "resolved" version of the
3634    symbol.  The functions are resolved to match the types of their
3635    parameters; for example, c_f_pointer(cptr, fptr) would resolve to
3636    something similar to c_f_pointer_i4 if the type of data object fptr
3637    pointed to was a default integer.  The actual name of the resolved
3638    procedure symbol is further mangled with the module name, etc., but
3639    the idea holds true.  */
3640
3641 static void
3642 build_formal_args (gfc_symbol *new_proc_sym,
3643                    gfc_symbol *old_sym, int add_optional_arg)
3644 {
3645   gfc_formal_arglist *head = NULL, *tail = NULL;
3646   gfc_namespace *parent_ns = NULL;
3647
3648   parent_ns = gfc_current_ns;
3649   /* Create a new namespace, which will be the formal ns (namespace
3650      of the formal args).  */
3651   gfc_current_ns = gfc_get_namespace(parent_ns, 0);
3652   gfc_current_ns->proc_name = new_proc_sym;
3653
3654   /* Generate the params.  */
3655   if ((old_sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
3656       (old_sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
3657     {
3658       gen_cptr_param (&head, &tail, (const char *) new_proc_sym->module,
3659                       gfc_current_ns, "cptr", old_sym->intmod_sym_id);
3660       gen_fptr_param (&head, &tail, (const char *) new_proc_sym->module,
3661                       gfc_current_ns, "fptr");
3662
3663       /* If we're dealing with c_f_pointer, it has an optional third arg.  */
3664       if (old_sym->intmod_sym_id == ISOCBINDING_F_POINTER)
3665         {
3666           gen_shape_param (&head, &tail,
3667                            (const char *) new_proc_sym->module,
3668                            gfc_current_ns, "shape");
3669         }
3670     }
3671   else if (old_sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
3672     {
3673       /* c_associated has one required arg and one optional; both
3674          are c_ptrs.  */
3675       gen_cptr_param (&head, &tail, (const char *) new_proc_sym->module,
3676                       gfc_current_ns, "c_ptr_1", ISOCBINDING_ASSOCIATED);
3677       if (add_optional_arg)
3678         {
3679           gen_cptr_param (&head, &tail, (const char *) new_proc_sym->module,
3680                           gfc_current_ns, "c_ptr_2", ISOCBINDING_ASSOCIATED);
3681           /* The last param is optional so mark it as such.  */
3682           tail->sym->attr.optional = 1;
3683         }
3684     }
3685
3686   /* Add the interface (store formal args to new_proc_sym).  */
3687   add_proc_interface (new_proc_sym, IFSRC_DECL, head);
3688
3689   /* Set up the formal_ns pointer to the one created for the
3690      new procedure so it'll get cleaned up during gfc_free_symbol().  */
3691   new_proc_sym->formal_ns = gfc_current_ns;
3692
3693   gfc_current_ns = parent_ns;
3694 }
3695
3696
3697 /* Generate the given set of C interoperable kind objects, or all
3698    interoperable kinds.  This function will only be given kind objects
3699    for valid iso_c_binding defined types because this is verified when
3700    the 'use' statement is parsed.  If the user gives an 'only' clause,
3701    the specific kinds are looked up; if they don't exist, an error is
3702    reported.  If the user does not give an 'only' clause, all
3703    iso_c_binding symbols are generated.  If a list of specific kinds
3704    is given, it must have a NULL in the first empty spot to mark the
3705    end of the list.  */
3706
3707
3708 void
3709 generate_isocbinding_symbol (const char *mod_name, iso_c_binding_symbol s,
3710                              const char *local_name)
3711 {
3712   const char *const name = (local_name && local_name[0]) ? local_name
3713                                              : c_interop_kinds_table[s].name;
3714   gfc_symtree *tmp_symtree = NULL;
3715   gfc_symbol *tmp_sym = NULL;
3716   gfc_dt_list **dt_list_ptr = NULL;
3717   gfc_component *tmp_comp = NULL;
3718   char comp_name[(GFC_MAX_SYMBOL_LEN * 2) + 1];
3719   int index;
3720
3721   tmp_symtree = gfc_find_symtree (gfc_current_ns->sym_root, name);
3722
3723   /* Already exists in this scope so don't re-add it.
3724      TODO: we should probably check that it's really the same symbol.  */
3725   if (tmp_symtree != NULL)
3726     return;
3727
3728   /* Create the sym tree in the current ns.  */
3729   gfc_get_sym_tree (name, gfc_current_ns, &tmp_symtree);
3730   if (tmp_symtree)
3731     tmp_sym = tmp_symtree->n.sym;
3732   else
3733     gfc_internal_error ("generate_isocbinding_symbol(): Unable to "
3734                         "create symbol");
3735
3736   /* Say what module this symbol belongs to.  */
3737   tmp_sym->module = gfc_get_string (mod_name);
3738   tmp_sym->from_intmod = INTMOD_ISO_C_BINDING;
3739   tmp_sym->intmod_sym_id = s;
3740
3741   switch (s)
3742     {
3743
3744 #define NAMED_INTCST(a,b,c) case a :
3745 #define NAMED_REALCST(a,b,c) case a :
3746 #define NAMED_CMPXCST(a,b,c) case a :
3747 #define NAMED_LOGCST(a,b,c) case a :
3748 #define NAMED_CHARKNDCST(a,b,c) case a :
3749 #include "iso-c-binding.def"
3750
3751         tmp_sym->value = gfc_int_expr (c_interop_kinds_table[s].value);
3752
3753         /* Initialize an integer constant expression node.  */
3754         tmp_sym->attr.flavor = FL_PARAMETER;
3755         tmp_sym->ts.type = BT_INTEGER;
3756         tmp_sym->ts.kind = gfc_default_integer_kind;
3757
3758         /* Mark this type as a C interoperable one.  */
3759         tmp_sym->ts.is_c_interop = 1;
3760         tmp_sym->ts.is_iso_c = 1;
3761         tmp_sym->value->ts.is_c_interop = 1;
3762         tmp_sym->value->ts.is_iso_c = 1;
3763         tmp_sym->attr.is_c_interop = 1;
3764
3765         /* Tell what f90 type this c interop kind is valid.  */
3766         tmp_sym->ts.f90_type = c_interop_kinds_table[s].f90_type;
3767
3768         /* Say it's from the iso_c_binding module.  */
3769         tmp_sym->attr.is_iso_c = 1;
3770
3771         /* Make it use associated.  */
3772         tmp_sym->attr.use_assoc = 1;
3773         break;
3774
3775
3776 #define NAMED_CHARCST(a,b,c) case a :
3777 #include "iso-c-binding.def"
3778
3779         /* Initialize an integer constant expression node for the
3780            length of the character.  */
3781         tmp_sym->value = gfc_get_expr (); 
3782         tmp_sym->value->expr_type = EXPR_CONSTANT;
3783         tmp_sym->value->ts.type = BT_CHARACTER;
3784         tmp_sym->value->ts.kind = gfc_default_character_kind;
3785         tmp_sym->value->where = gfc_current_locus;
3786         tmp_sym->value->ts.is_c_interop = 1;
3787         tmp_sym->value->ts.is_iso_c = 1;
3788         tmp_sym->value->value.character.length = 1;
3789         tmp_sym->value->value.character.string = gfc_getmem (2);
3790         tmp_sym->value->value.character.string[0]
3791           = (char) c_interop_kinds_table[s].value;
3792         tmp_sym->value->value.character.string[1] = '\0';
3793
3794         /* May not need this in both attr and ts, but do need in
3795            attr for writing module file.  */
3796         tmp_sym->attr.is_c_interop = 1;
3797
3798         tmp_sym->attr.flavor = FL_PARAMETER;
3799         tmp_sym->ts.type = BT_CHARACTER;
3800
3801         /* Need to set it to the C_CHAR kind.  */
3802         tmp_sym->ts.kind = gfc_default_character_kind;
3803
3804         /* Mark this type as a C interoperable one.  */
3805         tmp_sym->ts.is_c_interop = 1;
3806         tmp_sym->ts.is_iso_c = 1;
3807
3808         /* Tell what f90 type this c interop kind is valid.  */
3809         tmp_sym->ts.f90_type = BT_CHARACTER;
3810
3811         /* Say it's from the iso_c_binding module.  */
3812         tmp_sym->attr.is_iso_c = 1;
3813
3814         /* Make it use associated.  */
3815         tmp_sym->attr.use_assoc = 1;
3816         break;
3817
3818       case ISOCBINDING_PTR:
3819       case ISOCBINDING_FUNPTR:
3820
3821         /* Initialize an integer constant expression node.  */
3822         tmp_sym->attr.flavor = FL_DERIVED;
3823         tmp_sym->ts.is_c_interop = 1;
3824         tmp_sym->attr.is_c_interop = 1;
3825         tmp_sym->attr.is_iso_c = 1;
3826         tmp_sym->ts.is_iso_c = 1;
3827         tmp_sym->ts.type = BT_DERIVED;
3828
3829         /* A derived type must have the bind attribute to be
3830            interoperable (J3/04-007, Section 15.2.3), even though
3831            the binding label is not used.  */
3832         tmp_sym->attr.is_bind_c = 1;
3833
3834         tmp_sym->attr.referenced = 1;
3835
3836         tmp_sym->ts.derived = tmp_sym;
3837
3838         /* Add the symbol created for the derived type to the current ns.  */
3839         dt_list_ptr = &(gfc_derived_types);
3840         while (*dt_list_ptr != NULL && (*dt_list_ptr)->next != NULL)
3841           dt_list_ptr = &((*dt_list_ptr)->next);
3842
3843         /* There is already at least one derived type in the list, so append
3844            the one we're currently building for c_ptr or c_funptr.  */
3845         if (*dt_list_ptr != NULL)
3846           dt_list_ptr = &((*dt_list_ptr)->next);
3847         (*dt_list_ptr) = gfc_get_dt_list ();
3848         (*dt_list_ptr)->derived = tmp_sym;
3849         (*dt_list_ptr)->next = NULL;
3850
3851         /* Set up the component of the derived type, which will be
3852            an integer with kind equal to c_ptr_size.  Mangle the name of
3853            the field for the c_address to prevent the curious user from
3854            trying to access it from Fortran.  */
3855         sprintf (comp_name, "__%s_%s", tmp_sym->name, "c_address");
3856         gfc_add_component (tmp_sym, comp_name, &tmp_comp);
3857         if (tmp_comp == NULL)
3858           gfc_internal_error ("generate_isocbinding_symbol(): Unable to "
3859                               "create component for c_address");
3860
3861         tmp_comp->ts.type = BT_INTEGER;
3862
3863         /* Set this because the module will need to read/write this field.  */
3864         tmp_comp->ts.f90_type = BT_INTEGER;
3865
3866         /* The kinds for c_ptr and c_funptr are the same.  */
3867         index = get_c_kind ("c_ptr", c_interop_kinds_table);
3868         tmp_comp->ts.kind = c_interop_kinds_table[index].value;
3869
3870         tmp_comp->pointer = 0;
3871         tmp_comp->dimension = 0;
3872
3873         /* Mark the component as C interoperable.  */
3874         tmp_comp->ts.is_c_interop = 1;
3875
3876         /* Make it use associated (iso_c_binding module).  */
3877         tmp_sym->attr.use_assoc = 1;
3878         break;
3879
3880       case ISOCBINDING_NULL_PTR:
3881       case ISOCBINDING_NULL_FUNPTR:
3882         gen_special_c_interop_ptr (s, name, mod_name);
3883         break;
3884
3885       case ISOCBINDING_F_POINTER:
3886       case ISOCBINDING_ASSOCIATED:
3887       case ISOCBINDING_LOC:
3888       case ISOCBINDING_FUNLOC:
3889       case ISOCBINDING_F_PROCPOINTER:
3890
3891         tmp_sym->attr.proc = PROC_MODULE;
3892
3893         /* Use the procedure's name as it is in the iso_c_binding module for
3894            setting the binding label in case the user renamed the symbol.  */
3895         sprintf (tmp_sym->binding_label, "%s_%s", mod_name,
3896                  c_interop_kinds_table[s].name);
3897         tmp_sym->attr.is_iso_c = 1;
3898         if (s == ISOCBINDING_F_POINTER || s == ISOCBINDING_F_PROCPOINTER)
3899           tmp_sym->attr.subroutine = 1;
3900         else
3901           {
3902             /* TODO!  This needs to be finished more for the expr of the
3903                function or something!
3904                This may not need to be here, because trying to do c_loc
3905                as an external.  */
3906             if (s == ISOCBINDING_ASSOCIATED)
3907               {
3908                 tmp_sym->attr.function = 1;
3909                 tmp_sym->ts.type = BT_LOGICAL;
3910                 tmp_sym->ts.kind = gfc_default_logical_kind;
3911                 tmp_sym->result = tmp_sym;
3912               }
3913             else
3914               {
3915                /* Here, we're taking the simple approach.  We're defining
3916                   c_loc as an external identifier so the compiler will put
3917                   what we expect on the stack for the address we want the
3918                   C address of.  */
3919                 tmp_sym->ts.type = BT_DERIVED;
3920                 if (s == ISOCBINDING_LOC)
3921                   tmp_sym->ts.derived =
3922                     get_iso_c_binding_dt (ISOCBINDING_PTR);
3923                 else
3924                   tmp_sym->ts.derived =
3925                     get_iso_c_binding_dt (ISOCBINDING_FUNPTR);
3926
3927                 if (tmp_sym->ts.derived == NULL)
3928                   {
3929                     /* Create the necessary derived type so we can continue
3930                        processing the file.  */
3931                     generate_isocbinding_symbol
3932                       (mod_name, s == ISOCBINDING_FUNLOC
3933                                  ? ISOCBINDING_FUNPTR : ISOCBINDING_PTR,
3934                        (const char *)(s == ISOCBINDING_FUNLOC
3935                                 ? "_gfortran_iso_c_binding_c_funptr"
3936                                 : "_gfortran_iso_c_binding_c_ptr"));
3937                     tmp_sym->ts.derived =
3938                       get_iso_c_binding_dt (s == ISOCBINDING_FUNLOC
3939                                             ? ISOCBINDING_FUNPTR
3940                                             : ISOCBINDING_PTR);
3941                   }
3942
3943                 /* The function result is itself (no result clause).  */
3944                 tmp_sym->result = tmp_sym;
3945                 tmp_sym->attr.external = 1;
3946                 tmp_sym->attr.use_assoc = 0;
3947                 tmp_sym->attr.if_source = IFSRC_UNKNOWN;
3948                 tmp_sym->attr.proc = PROC_UNKNOWN;
3949               }
3950           }
3951
3952         tmp_sym->attr.flavor = FL_PROCEDURE;
3953         tmp_sym->attr.contained = 0;
3954         
3955        /* Try using this builder routine, with the new and old symbols
3956           both being the generic iso_c proc sym being created.  This
3957           will create the formal args (and the new namespace for them).
3958           Don't build an arg list for c_loc because we're going to treat
3959           c_loc as an external procedure.  */
3960         if (s != ISOCBINDING_LOC && s != ISOCBINDING_FUNLOC)
3961           /* The 1 says to add any optional args, if applicable.  */
3962           build_formal_args (tmp_sym, tmp_sym, 1);
3963
3964         /* Set this after setting up the symbol, to prevent error messages.  */
3965         tmp_sym->attr.use_assoc = 1;
3966
3967         /* This symbol will not be referenced directly.  It will be
3968            resolved to the implementation for the given f90 kind.  */
3969         tmp_sym->attr.referenced = 0;
3970
3971         break;
3972
3973       default:
3974         gcc_unreachable ();
3975     }
3976 }
3977
3978
3979 /* Creates a new symbol based off of an old iso_c symbol, with a new
3980    binding label.  This function can be used to create a new,
3981    resolved, version of a procedure symbol for c_f_pointer or
3982    c_f_procpointer that is based on the generic symbols.  A new
3983    parameter list is created for the new symbol using
3984    build_formal_args().  The add_optional_flag specifies whether the
3985    to add the optional SHAPE argument.  The new symbol is
3986    returned.  */
3987
3988 gfc_symbol *
3989 get_iso_c_sym (gfc_symbol *old_sym, char *new_name,
3990                char *new_binding_label, int add_optional_arg)
3991 {
3992   gfc_symtree *new_symtree = NULL;
3993
3994   /* See if we have a symbol by that name already available, looking
3995      through any parent namespaces.  */
3996   gfc_find_sym_tree (new_name, gfc_current_ns, 1, &new_symtree);
3997   if (new_symtree != NULL)
3998     /* Return the existing symbol.  */
3999     return new_symtree->n.sym;
4000
4001   /* Create the symtree/symbol, with attempted host association.  */
4002   gfc_get_ha_sym_tree (new_name, &new_symtree);
4003   if (new_symtree == NULL)
4004     gfc_internal_error ("get_iso_c_sym(): Unable to create "
4005                         "symtree for '%s'", new_name);
4006
4007   /* Now fill in the fields of the resolved symbol with the old sym.  */
4008   strcpy (new_symtree->n.sym->binding_label, new_binding_label);
4009   new_symtree->n.sym->attr = old_sym->attr;
4010   new_symtree->n.sym->ts = old_sym->ts;
4011   new_symtree->n.sym->module = gfc_get_string (old_sym->module);
4012   /* Build the formal arg list.  */
4013   build_formal_args (new_symtree->n.sym, old_sym, add_optional_arg);
4014
4015   gfc_commit_symbol (new_symtree->n.sym);
4016
4017   return new_symtree->n.sym;
4018 }
4019