OSDN Git Service

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