OSDN Git Service

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