OSDN Git Service

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