OSDN Git Service

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