OSDN Git Service

gcc/fortran/
[pf3gnuchains/gcc-fork.git] / gcc / fortran / resolve.c
1 /* Perform type resolution on the various stuctures.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3    Contributed by Andy Vaught
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 51 Franklin Street, Fifth Floor,Boston, MA
20 02110-1301, USA.  */
21
22
23 #include "config.h"
24 #include "system.h"
25 #include "gfortran.h"
26 #include "arith.h"  /* For gfc_compare_expr().  */
27 #include "dependency.h"
28
29 /* Types used in equivalence statements.  */
30
31 typedef enum seq_type
32 {
33   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
34 }
35 seq_type;
36
37 /* Stack to push the current if we descend into a block during
38    resolution.  See resolve_branch() and resolve_code().  */
39
40 typedef struct code_stack
41 {
42   struct gfc_code *head, *current;
43   struct code_stack *prev;
44 }
45 code_stack;
46
47 static code_stack *cs_base = NULL;
48
49
50 /* Nonzero if we're inside a FORALL block */
51
52 static int forall_flag;
53
54 /* Nonzero if we are processing a formal arglist. The corresponding function
55    resets the flag each time that it is read.  */
56 static int formal_arg_flag = 0;
57
58 int
59 gfc_is_formal_arg (void)
60 {
61   return formal_arg_flag;
62 }
63
64 /* Resolve types of formal argument lists.  These have to be done early so that
65    the formal argument lists of module procedures can be copied to the
66    containing module before the individual procedures are resolved
67    individually.  We also resolve argument lists of procedures in interface
68    blocks because they are self-contained scoping units.
69
70    Since a dummy argument cannot be a non-dummy procedure, the only
71    resort left for untyped names are the IMPLICIT types.  */
72
73 static void
74 resolve_formal_arglist (gfc_symbol * proc)
75 {
76   gfc_formal_arglist *f;
77   gfc_symbol *sym;
78   int i;
79
80   /* TODO: Procedures whose return character length parameter is not constant
81      or assumed must also have explicit interfaces.  */
82   if (proc->result != NULL)
83     sym = proc->result;
84   else
85     sym = proc;
86
87   if (gfc_elemental (proc)
88       || sym->attr.pointer || sym->attr.allocatable
89       || (sym->as && sym->as->rank > 0))
90     proc->attr.always_explicit = 1;
91
92   formal_arg_flag = 1;
93
94   for (f = proc->formal; f; f = f->next)
95     {
96       sym = f->sym;
97
98       if (sym == NULL)
99         {
100           /* Alternate return placeholder.  */
101           if (gfc_elemental (proc))
102             gfc_error ("Alternate return specifier in elemental subroutine "
103                        "'%s' at %L is not allowed", proc->name,
104                        &proc->declared_at);
105           if (proc->attr.function)
106             gfc_error ("Alternate return specifier in function "
107                        "'%s' at %L is not allowed", proc->name,
108                        &proc->declared_at);
109           continue;
110         }
111
112       if (sym->attr.if_source != IFSRC_UNKNOWN)
113         resolve_formal_arglist (sym);
114
115       if (sym->attr.subroutine || sym->attr.external || sym->attr.intrinsic)
116         {
117           if (gfc_pure (proc) && !gfc_pure (sym))
118             {
119               gfc_error
120                 ("Dummy procedure '%s' of PURE procedure at %L must also "
121                  "be PURE", sym->name, &sym->declared_at);
122               continue;
123             }
124
125           if (gfc_elemental (proc))
126             {
127               gfc_error
128                 ("Dummy procedure at %L not allowed in ELEMENTAL procedure",
129                  &sym->declared_at);
130               continue;
131             }
132
133           continue;
134         }
135
136       if (sym->ts.type == BT_UNKNOWN)
137         {
138           if (!sym->attr.function || sym->result == sym)
139             gfc_set_default_type (sym, 1, sym->ns);
140           else
141             {
142               /* Set the type of the RESULT, then copy.  */
143               if (sym->result->ts.type == BT_UNKNOWN)
144                 gfc_set_default_type (sym->result, 1, sym->result->ns);
145
146               sym->ts = sym->result->ts;
147               if (sym->as == NULL)
148                 sym->as = gfc_copy_array_spec (sym->result->as);
149             }
150         }
151
152       gfc_resolve_array_spec (sym->as, 0);
153
154       /* We can't tell if an array with dimension (:) is assumed or deferred
155          shape until we know if it has the pointer or allocatable attributes.
156       */
157       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
158           && !(sym->attr.pointer || sym->attr.allocatable))
159         {
160           sym->as->type = AS_ASSUMED_SHAPE;
161           for (i = 0; i < sym->as->rank; i++)
162             sym->as->lower[i] = gfc_int_expr (1);
163         }
164
165       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
166           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
167           || sym->attr.optional)
168         proc->attr.always_explicit = 1;
169
170       /* If the flavor is unknown at this point, it has to be a variable.
171          A procedure specification would have already set the type.  */
172
173       if (sym->attr.flavor == FL_UNKNOWN)
174         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
175
176       if (gfc_pure (proc))
177         {
178           if (proc->attr.function && !sym->attr.pointer
179               && sym->attr.flavor != FL_PROCEDURE
180               && sym->attr.intent != INTENT_IN)
181
182             gfc_error ("Argument '%s' of pure function '%s' at %L must be "
183                        "INTENT(IN)", sym->name, proc->name,
184                        &sym->declared_at);
185
186           if (proc->attr.subroutine && !sym->attr.pointer
187               && sym->attr.intent == INTENT_UNKNOWN)
188
189             gfc_error
190               ("Argument '%s' of pure subroutine '%s' at %L must have "
191                "its INTENT specified", sym->name, proc->name,
192                &sym->declared_at);
193         }
194
195
196       if (gfc_elemental (proc))
197         {
198           if (sym->as != NULL)
199             {
200               gfc_error
201                 ("Argument '%s' of elemental procedure at %L must be scalar",
202                  sym->name, &sym->declared_at);
203               continue;
204             }
205
206           if (sym->attr.pointer)
207             {
208               gfc_error
209                 ("Argument '%s' of elemental procedure at %L cannot have "
210                  "the POINTER attribute", sym->name, &sym->declared_at);
211               continue;
212             }
213         }
214
215       /* Each dummy shall be specified to be scalar.  */
216       if (proc->attr.proc == PROC_ST_FUNCTION)
217         {
218           if (sym->as != NULL)
219             {
220               gfc_error
221                 ("Argument '%s' of statement function at %L must be scalar",
222                  sym->name, &sym->declared_at);
223               continue;
224             }
225
226           if (sym->ts.type == BT_CHARACTER)
227             {
228               gfc_charlen *cl = sym->ts.cl;
229               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
230                 {
231                   gfc_error
232                     ("Character-valued argument '%s' of statement function at "
233                      "%L must has constant length",
234                      sym->name, &sym->declared_at);
235                   continue;
236                 }
237             }
238         }
239     }
240   formal_arg_flag = 0;
241 }
242
243
244 /* Work function called when searching for symbols that have argument lists
245    associated with them.  */
246
247 static void
248 find_arglists (gfc_symbol * sym)
249 {
250
251   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns)
252     return;
253
254   resolve_formal_arglist (sym);
255 }
256
257
258 /* Given a namespace, resolve all formal argument lists within the namespace.
259  */
260
261 static void
262 resolve_formal_arglists (gfc_namespace * ns)
263 {
264
265   if (ns == NULL)
266     return;
267
268   gfc_traverse_ns (ns, find_arglists);
269 }
270
271
272 static void
273 resolve_contained_fntype (gfc_symbol * sym, gfc_namespace * ns)
274 {
275   try t;
276   
277   /* If this namespace is not a function, ignore it.  */
278   if (! sym
279       || !(sym->attr.function
280            || sym->attr.flavor == FL_VARIABLE))
281     return;
282
283   /* Try to find out of what the return type is.  */
284   if (sym->result != NULL)
285     sym = sym->result;
286
287   if (sym->ts.type == BT_UNKNOWN)
288     {
289       t = gfc_set_default_type (sym, 0, ns);
290
291       if (t == FAILURE && !sym->attr.untyped)
292         {
293           gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
294                      sym->name, &sym->declared_at); /* FIXME */
295           sym->attr.untyped = 1;
296         }
297     }
298
299   /*Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character type,
300     lists the only ways a character length value of * can be used: dummy arguments
301     of proceedures, named constants, and function results in external functions.
302     Internal function results are not on that list; ergo, not permitted.  */
303
304   if (sym->ts.type == BT_CHARACTER)
305     {
306       gfc_charlen *cl = sym->ts.cl;
307       if (!cl || !cl->length)
308         gfc_error ("Character-valued internal function '%s' at %L must "
309                    "not be assumed length", sym->name, &sym->declared_at);
310     }
311 }
312
313
314 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
315    introduce duplicates.  */
316
317 static void
318 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
319 {
320   gfc_formal_arglist *f, *new_arglist;
321   gfc_symbol *new_sym;
322
323   for (; new_args != NULL; new_args = new_args->next)
324     {
325       new_sym = new_args->sym;
326       /* See if ths arg is already in the formal argument list.  */
327       for (f = proc->formal; f; f = f->next)
328         {
329           if (new_sym == f->sym)
330             break;
331         }
332
333       if (f)
334         continue;
335
336       /* Add a new argument.  Argument order is not important.  */
337       new_arglist = gfc_get_formal_arglist ();
338       new_arglist->sym = new_sym;
339       new_arglist->next = proc->formal;
340       proc->formal  = new_arglist;
341     }
342 }
343
344
345 /* Resolve alternate entry points.  If a symbol has multiple entry points we
346    create a new master symbol for the main routine, and turn the existing
347    symbol into an entry point.  */
348
349 static void
350 resolve_entries (gfc_namespace * ns)
351 {
352   gfc_namespace *old_ns;
353   gfc_code *c;
354   gfc_symbol *proc;
355   gfc_entry_list *el;
356   char name[GFC_MAX_SYMBOL_LEN + 1];
357   static int master_count = 0;
358
359   if (ns->proc_name == NULL)
360     return;
361
362   /* No need to do anything if this procedure doesn't have alternate entry
363      points.  */
364   if (!ns->entries)
365     return;
366
367   /* We may already have resolved alternate entry points.  */
368   if (ns->proc_name->attr.entry_master)
369     return;
370
371   /* If this isn't a procedure something has gone horribly wrong.  */
372   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
373   
374   /* Remember the current namespace.  */
375   old_ns = gfc_current_ns;
376
377   gfc_current_ns = ns;
378
379   /* Add the main entry point to the list of entry points.  */
380   el = gfc_get_entry_list ();
381   el->sym = ns->proc_name;
382   el->id = 0;
383   el->next = ns->entries;
384   ns->entries = el;
385   ns->proc_name->attr.entry = 1;
386
387   /* Add an entry statement for it.  */
388   c = gfc_get_code ();
389   c->op = EXEC_ENTRY;
390   c->ext.entry = el;
391   c->next = ns->code;
392   ns->code = c;
393
394   /* Create a new symbol for the master function.  */
395   /* Give the internal function a unique name (within this file).
396      Also include the function name so the user has some hope of figuring
397      out what is going on.  */
398   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
399             master_count++, ns->proc_name->name);
400   gfc_get_ha_symbol (name, &proc);
401   gcc_assert (proc != NULL);
402
403   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
404   if (ns->proc_name->attr.subroutine)
405     gfc_add_subroutine (&proc->attr, proc->name, NULL);
406   else
407     {
408       gfc_symbol *sym;
409       gfc_typespec *ts, *fts;
410
411       gfc_add_function (&proc->attr, proc->name, NULL);
412       proc->result = proc;
413       fts = &ns->entries->sym->result->ts;
414       if (fts->type == BT_UNKNOWN)
415         fts = gfc_get_default_type (ns->entries->sym->result, NULL);
416       for (el = ns->entries->next; el; el = el->next)
417         {
418           ts = &el->sym->result->ts;
419           if (ts->type == BT_UNKNOWN)
420             ts = gfc_get_default_type (el->sym->result, NULL);
421           if (! gfc_compare_types (ts, fts)
422               || (el->sym->result->attr.dimension
423                   != ns->entries->sym->result->attr.dimension)
424               || (el->sym->result->attr.pointer
425                   != ns->entries->sym->result->attr.pointer))
426             break;
427         }
428
429       if (el == NULL)
430         {
431           sym = ns->entries->sym->result;
432           /* All result types the same.  */
433           proc->ts = *fts;
434           if (sym->attr.dimension)
435             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
436           if (sym->attr.pointer)
437             gfc_add_pointer (&proc->attr, NULL);
438         }
439       else
440         {
441           /* Otherwise the result will be passed through a union by
442              reference.  */
443           proc->attr.mixed_entry_master = 1;
444           for (el = ns->entries; el; el = el->next)
445             {
446               sym = el->sym->result;
447               if (sym->attr.dimension)
448               {
449                 if (el == ns->entries)
450                   gfc_error
451                   ("FUNCTION result %s can't be an array in FUNCTION %s at %L",
452                    sym->name, ns->entries->sym->name, &sym->declared_at);
453                 else
454                   gfc_error
455                     ("ENTRY result %s can't be an array in FUNCTION %s at %L",
456                      sym->name, ns->entries->sym->name, &sym->declared_at);
457               }
458               else if (sym->attr.pointer)
459               {
460                 if (el == ns->entries)
461                   gfc_error
462                   ("FUNCTION result %s can't be a POINTER in FUNCTION %s at %L",
463                    sym->name, ns->entries->sym->name, &sym->declared_at);
464                 else
465                   gfc_error
466                     ("ENTRY result %s can't be a POINTER in FUNCTION %s at %L",
467                      sym->name, ns->entries->sym->name, &sym->declared_at);
468               }
469               else
470                 {
471                   ts = &sym->ts;
472                   if (ts->type == BT_UNKNOWN)
473                     ts = gfc_get_default_type (sym, NULL);
474                   switch (ts->type)
475                     {
476                     case BT_INTEGER:
477                       if (ts->kind == gfc_default_integer_kind)
478                         sym = NULL;
479                       break;
480                     case BT_REAL:
481                       if (ts->kind == gfc_default_real_kind
482                           || ts->kind == gfc_default_double_kind)
483                         sym = NULL;
484                       break;
485                     case BT_COMPLEX:
486                       if (ts->kind == gfc_default_complex_kind)
487                         sym = NULL;
488                       break;
489                     case BT_LOGICAL:
490                       if (ts->kind == gfc_default_logical_kind)
491                         sym = NULL;
492                       break;
493                     case BT_UNKNOWN:
494                       /* We will issue error elsewhere.  */
495                       sym = NULL;
496                       break;
497                     default:
498                       break;
499                     }
500                   if (sym)
501                   {
502                     if (el == ns->entries)
503                       gfc_error
504                         ("FUNCTION result %s can't be of type %s in FUNCTION %s at %L",
505                          sym->name, gfc_typename (ts), ns->entries->sym->name,
506                          &sym->declared_at);
507                     else
508                       gfc_error
509                         ("ENTRY result %s can't be of type %s in FUNCTION %s at %L",
510                          sym->name, gfc_typename (ts), ns->entries->sym->name,
511                          &sym->declared_at);
512                   }
513                 }
514             }
515         }
516     }
517   proc->attr.access = ACCESS_PRIVATE;
518   proc->attr.entry_master = 1;
519
520   /* Merge all the entry point arguments.  */
521   for (el = ns->entries; el; el = el->next)
522     merge_argument_lists (proc, el->sym->formal);
523
524   /* Use the master function for the function body.  */
525   ns->proc_name = proc;
526
527   /* Finalize the new symbols.  */
528   gfc_commit_symbols ();
529
530   /* Restore the original namespace.  */
531   gfc_current_ns = old_ns;
532 }
533
534
535 /* Resolve contained function types.  Because contained functions can call one
536    another, they have to be worked out before any of the contained procedures
537    can be resolved.
538
539    The good news is that if a function doesn't already have a type, the only
540    way it can get one is through an IMPLICIT type or a RESULT variable, because
541    by definition contained functions are contained namespace they're contained
542    in, not in a sibling or parent namespace.  */
543
544 static void
545 resolve_contained_functions (gfc_namespace * ns)
546 {
547   gfc_namespace *child;
548   gfc_entry_list *el;
549
550   resolve_formal_arglists (ns);
551
552   for (child = ns->contained; child; child = child->sibling)
553     {
554       /* Resolve alternate entry points first.  */
555       resolve_entries (child); 
556
557       /* Then check function return types.  */
558       resolve_contained_fntype (child->proc_name, child);
559       for (el = child->entries; el; el = el->next)
560         resolve_contained_fntype (el->sym, child);
561     }
562 }
563
564
565 /* Resolve all of the elements of a structure constructor and make sure that
566    the types are correct.  */
567
568 static try
569 resolve_structure_cons (gfc_expr * expr)
570 {
571   gfc_constructor *cons;
572   gfc_component *comp;
573   try t;
574
575   t = SUCCESS;
576   cons = expr->value.constructor;
577   /* A constructor may have references if it is the result of substituting a
578      parameter variable.  In this case we just pull out the component we
579      want.  */
580   if (expr->ref)
581     comp = expr->ref->u.c.sym->components;
582   else
583     comp = expr->ts.derived->components;
584
585   for (; comp; comp = comp->next, cons = cons->next)
586     {
587       if (! cons->expr)
588         {
589           t = FAILURE;
590           continue;
591         }
592
593       if (gfc_resolve_expr (cons->expr) == FAILURE)
594         {
595           t = FAILURE;
596           continue;
597         }
598
599       /* If we don't have the right type, try to convert it.  */
600
601       if (!gfc_compare_types (&cons->expr->ts, &comp->ts)
602           && gfc_convert_type (cons->expr, &comp->ts, 1) == FAILURE)
603         t = FAILURE;
604     }
605
606   return t;
607 }
608
609
610
611 /****************** Expression name resolution ******************/
612
613 /* Returns 0 if a symbol was not declared with a type or
614    attribute declaration statement, nonzero otherwise.  */
615
616 static int
617 was_declared (gfc_symbol * sym)
618 {
619   symbol_attribute a;
620
621   a = sym->attr;
622
623   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
624     return 1;
625
626   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
627       || a.optional || a.pointer || a.save || a.target
628       || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN)
629     return 1;
630
631   return 0;
632 }
633
634
635 /* Determine if a symbol is generic or not.  */
636
637 static int
638 generic_sym (gfc_symbol * sym)
639 {
640   gfc_symbol *s;
641
642   if (sym->attr.generic ||
643       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
644     return 1;
645
646   if (was_declared (sym) || sym->ns->parent == NULL)
647     return 0;
648
649   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
650
651   return (s == NULL) ? 0 : generic_sym (s);
652 }
653
654
655 /* Determine if a symbol is specific or not.  */
656
657 static int
658 specific_sym (gfc_symbol * sym)
659 {
660   gfc_symbol *s;
661
662   if (sym->attr.if_source == IFSRC_IFBODY
663       || sym->attr.proc == PROC_MODULE
664       || sym->attr.proc == PROC_INTERNAL
665       || sym->attr.proc == PROC_ST_FUNCTION
666       || (sym->attr.intrinsic &&
667           gfc_specific_intrinsic (sym->name))
668       || sym->attr.external)
669     return 1;
670
671   if (was_declared (sym) || sym->ns->parent == NULL)
672     return 0;
673
674   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
675
676   return (s == NULL) ? 0 : specific_sym (s);
677 }
678
679
680 /* Figure out if the procedure is specific, generic or unknown.  */
681
682 typedef enum
683 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
684 proc_type;
685
686 static proc_type
687 procedure_kind (gfc_symbol * sym)
688 {
689
690   if (generic_sym (sym))
691     return PTYPE_GENERIC;
692
693   if (specific_sym (sym))
694     return PTYPE_SPECIFIC;
695
696   return PTYPE_UNKNOWN;
697 }
698
699
700 /* Resolve an actual argument list.  Most of the time, this is just
701    resolving the expressions in the list.
702    The exception is that we sometimes have to decide whether arguments
703    that look like procedure arguments are really simple variable
704    references.  */
705
706 static try
707 resolve_actual_arglist (gfc_actual_arglist * arg)
708 {
709   gfc_symbol *sym;
710   gfc_symtree *parent_st;
711   gfc_expr *e;
712
713   for (; arg; arg = arg->next)
714     {
715
716       e = arg->expr;
717       if (e == NULL)
718         {
719           /* Check the label is a valid branching target.  */
720           if (arg->label)
721             {
722               if (arg->label->defined == ST_LABEL_UNKNOWN)
723                 {
724                   gfc_error ("Label %d referenced at %L is never defined",
725                              arg->label->value, &arg->label->where);
726                   return FAILURE;
727                 }
728             }
729           continue;
730         }
731
732       if (e->ts.type != BT_PROCEDURE)
733         {
734           if (gfc_resolve_expr (e) != SUCCESS)
735             return FAILURE;
736           continue;
737         }
738
739       /* See if the expression node should really be a variable
740          reference.  */
741
742       sym = e->symtree->n.sym;
743
744       if (sym->attr.flavor == FL_PROCEDURE
745           || sym->attr.intrinsic
746           || sym->attr.external)
747         {
748
749           if (sym->attr.proc == PROC_ST_FUNCTION)
750             {
751               gfc_error ("Statement function '%s' at %L is not allowed as an "
752                          "actual argument", sym->name, &e->where);
753             }
754
755           /* If the symbol is the function that names the current (or
756              parent) scope, then we really have a variable reference.  */
757
758           if (sym->attr.function && sym->result == sym
759               && (sym->ns->proc_name == sym
760                   || (sym->ns->parent != NULL
761                       && sym->ns->parent->proc_name == sym)))
762             goto got_variable;
763
764           continue;
765         }
766
767       /* See if the name is a module procedure in a parent unit.  */
768
769       if (was_declared (sym) || sym->ns->parent == NULL)
770         goto got_variable;
771
772       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
773         {
774           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
775           return FAILURE;
776         }
777
778       if (parent_st == NULL)
779         goto got_variable;
780
781       sym = parent_st->n.sym;
782       e->symtree = parent_st;           /* Point to the right thing.  */
783
784       if (sym->attr.flavor == FL_PROCEDURE
785           || sym->attr.intrinsic
786           || sym->attr.external)
787         {
788           continue;
789         }
790
791     got_variable:
792       e->expr_type = EXPR_VARIABLE;
793       e->ts = sym->ts;
794       if (sym->as != NULL)
795         {
796           e->rank = sym->as->rank;
797           e->ref = gfc_get_ref ();
798           e->ref->type = REF_ARRAY;
799           e->ref->u.ar.type = AR_FULL;
800           e->ref->u.ar.as = sym->as;
801         }
802     }
803
804   return SUCCESS;
805 }
806
807
808 /* Go through each actual argument in ACTUAL and see if it can be
809    implemented as an inlined, non-copying intrinsic.  FNSYM is the
810    function being called, or NULL if not known.  */
811
812 static void
813 find_noncopying_intrinsics (gfc_symbol * fnsym, gfc_actual_arglist * actual)
814 {
815   gfc_actual_arglist *ap;
816   gfc_expr *expr;
817
818   for (ap = actual; ap; ap = ap->next)
819     if (ap->expr
820         && (expr = gfc_get_noncopying_intrinsic_argument (ap->expr))
821         && !gfc_check_fncall_dependency (expr, INTENT_IN, fnsym, actual))
822       ap->expr->inline_noncopying_intrinsic = 1;
823 }
824
825
826 /************* Function resolution *************/
827
828 /* Resolve a function call known to be generic.
829    Section 14.1.2.4.1.  */
830
831 static match
832 resolve_generic_f0 (gfc_expr * expr, gfc_symbol * sym)
833 {
834   gfc_symbol *s;
835
836   if (sym->attr.generic)
837     {
838       s =
839         gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
840       if (s != NULL)
841         {
842           expr->value.function.name = s->name;
843           expr->value.function.esym = s;
844           expr->ts = s->ts;
845           if (s->as != NULL)
846             expr->rank = s->as->rank;
847           return MATCH_YES;
848         }
849
850       /* TODO: Need to search for elemental references in generic interface */
851     }
852
853   if (sym->attr.intrinsic)
854     return gfc_intrinsic_func_interface (expr, 0);
855
856   return MATCH_NO;
857 }
858
859
860 static try
861 resolve_generic_f (gfc_expr * expr)
862 {
863   gfc_symbol *sym;
864   match m;
865
866   sym = expr->symtree->n.sym;
867
868   for (;;)
869     {
870       m = resolve_generic_f0 (expr, sym);
871       if (m == MATCH_YES)
872         return SUCCESS;
873       else if (m == MATCH_ERROR)
874         return FAILURE;
875
876 generic:
877       if (sym->ns->parent == NULL)
878         break;
879       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
880
881       if (sym == NULL)
882         break;
883       if (!generic_sym (sym))
884         goto generic;
885     }
886
887   /* Last ditch attempt.  */
888
889   if (!gfc_generic_intrinsic (expr->symtree->n.sym->name))
890     {
891       gfc_error ("Generic function '%s' at %L is not an intrinsic function",
892                  expr->symtree->n.sym->name, &expr->where);
893       return FAILURE;
894     }
895
896   m = gfc_intrinsic_func_interface (expr, 0);
897   if (m == MATCH_YES)
898     return SUCCESS;
899   if (m == MATCH_NO)
900     gfc_error
901       ("Generic function '%s' at %L is not consistent with a specific "
902        "intrinsic interface", expr->symtree->n.sym->name, &expr->where);
903
904   return FAILURE;
905 }
906
907
908 /* Resolve a function call known to be specific.  */
909
910 static match
911 resolve_specific_f0 (gfc_symbol * sym, gfc_expr * expr)
912 {
913   match m;
914
915   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
916     {
917       if (sym->attr.dummy)
918         {
919           sym->attr.proc = PROC_DUMMY;
920           goto found;
921         }
922
923       sym->attr.proc = PROC_EXTERNAL;
924       goto found;
925     }
926
927   if (sym->attr.proc == PROC_MODULE
928       || sym->attr.proc == PROC_ST_FUNCTION
929       || sym->attr.proc == PROC_INTERNAL)
930     goto found;
931
932   if (sym->attr.intrinsic)
933     {
934       m = gfc_intrinsic_func_interface (expr, 1);
935       if (m == MATCH_YES)
936         return MATCH_YES;
937       if (m == MATCH_NO)
938         gfc_error
939           ("Function '%s' at %L is INTRINSIC but is not compatible with "
940            "an intrinsic", sym->name, &expr->where);
941
942       return MATCH_ERROR;
943     }
944
945   return MATCH_NO;
946
947 found:
948   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
949
950   expr->ts = sym->ts;
951   expr->value.function.name = sym->name;
952   expr->value.function.esym = sym;
953   if (sym->as != NULL)
954     expr->rank = sym->as->rank;
955
956   return MATCH_YES;
957 }
958
959
960 static try
961 resolve_specific_f (gfc_expr * expr)
962 {
963   gfc_symbol *sym;
964   match m;
965
966   sym = expr->symtree->n.sym;
967
968   for (;;)
969     {
970       m = resolve_specific_f0 (sym, expr);
971       if (m == MATCH_YES)
972         return SUCCESS;
973       if (m == MATCH_ERROR)
974         return FAILURE;
975
976       if (sym->ns->parent == NULL)
977         break;
978
979       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
980
981       if (sym == NULL)
982         break;
983     }
984
985   gfc_error ("Unable to resolve the specific function '%s' at %L",
986              expr->symtree->n.sym->name, &expr->where);
987
988   return SUCCESS;
989 }
990
991
992 /* Resolve a procedure call not known to be generic nor specific.  */
993
994 static try
995 resolve_unknown_f (gfc_expr * expr)
996 {
997   gfc_symbol *sym;
998   gfc_typespec *ts;
999
1000   sym = expr->symtree->n.sym;
1001
1002   if (sym->attr.dummy)
1003     {
1004       sym->attr.proc = PROC_DUMMY;
1005       expr->value.function.name = sym->name;
1006       goto set_type;
1007     }
1008
1009   /* See if we have an intrinsic function reference.  */
1010
1011   if (gfc_intrinsic_name (sym->name, 0))
1012     {
1013       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
1014         return SUCCESS;
1015       return FAILURE;
1016     }
1017
1018   /* The reference is to an external name.  */
1019
1020   sym->attr.proc = PROC_EXTERNAL;
1021   expr->value.function.name = sym->name;
1022   expr->value.function.esym = expr->symtree->n.sym;
1023
1024   if (sym->as != NULL)
1025     expr->rank = sym->as->rank;
1026
1027   /* Type of the expression is either the type of the symbol or the
1028      default type of the symbol.  */
1029
1030 set_type:
1031   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
1032
1033   if (sym->ts.type != BT_UNKNOWN)
1034     expr->ts = sym->ts;
1035   else
1036     {
1037       ts = gfc_get_default_type (sym, sym->ns);
1038
1039       if (ts->type == BT_UNKNOWN)
1040         {
1041           gfc_error ("Function '%s' at %L has no IMPLICIT type",
1042                      sym->name, &expr->where);
1043           return FAILURE;
1044         }
1045       else
1046         expr->ts = *ts;
1047     }
1048
1049   return SUCCESS;
1050 }
1051
1052
1053 /* Figure out if a function reference is pure or not.  Also set the name
1054    of the function for a potential error message.  Return nonzero if the
1055    function is PURE, zero if not.  */
1056
1057 static int
1058 pure_function (gfc_expr * e, const char **name)
1059 {
1060   int pure;
1061
1062   if (e->value.function.esym)
1063     {
1064       pure = gfc_pure (e->value.function.esym);
1065       *name = e->value.function.esym->name;
1066     }
1067   else if (e->value.function.isym)
1068     {
1069       pure = e->value.function.isym->pure
1070         || e->value.function.isym->elemental;
1071       *name = e->value.function.isym->name;
1072     }
1073   else
1074     {
1075       /* Implicit functions are not pure.  */
1076       pure = 0;
1077       *name = e->value.function.name;
1078     }
1079
1080   return pure;
1081 }
1082
1083
1084 /* Resolve a function call, which means resolving the arguments, then figuring
1085    out which entity the name refers to.  */
1086 /* TODO: Check procedure arguments so that an INTENT(IN) isn't passed
1087    to INTENT(OUT) or INTENT(INOUT).  */
1088
1089 static try
1090 resolve_function (gfc_expr * expr)
1091 {
1092   gfc_actual_arglist *arg;
1093   const char *name;
1094   try t;
1095
1096   if (resolve_actual_arglist (expr->value.function.actual) == FAILURE)
1097     return FAILURE;
1098
1099 /* See if function is already resolved.  */
1100
1101   if (expr->value.function.name != NULL)
1102     {
1103       if (expr->ts.type == BT_UNKNOWN)
1104         expr->ts = expr->symtree->n.sym->ts;
1105       t = SUCCESS;
1106     }
1107   else
1108     {
1109       /* Apply the rules of section 14.1.2.  */
1110
1111       switch (procedure_kind (expr->symtree->n.sym))
1112         {
1113         case PTYPE_GENERIC:
1114           t = resolve_generic_f (expr);
1115           break;
1116
1117         case PTYPE_SPECIFIC:
1118           t = resolve_specific_f (expr);
1119           break;
1120
1121         case PTYPE_UNKNOWN:
1122           t = resolve_unknown_f (expr);
1123           break;
1124
1125         default:
1126           gfc_internal_error ("resolve_function(): bad function type");
1127         }
1128     }
1129
1130   /* If the expression is still a function (it might have simplified),
1131      then we check to see if we are calling an elemental function.  */
1132
1133   if (expr->expr_type != EXPR_FUNCTION)
1134     return t;
1135
1136   if (expr->value.function.actual != NULL
1137       && ((expr->value.function.esym != NULL
1138            && expr->value.function.esym->attr.elemental)
1139           || (expr->value.function.isym != NULL
1140               && expr->value.function.isym->elemental)))
1141     {
1142
1143       /* The rank of an elemental is the rank of its array argument(s).  */
1144
1145       for (arg = expr->value.function.actual; arg; arg = arg->next)
1146         {
1147           if (arg->expr != NULL && arg->expr->rank > 0)
1148             {
1149               expr->rank = arg->expr->rank;
1150               break;
1151             }
1152         }
1153     }
1154
1155   if (!pure_function (expr, &name))
1156     {
1157       if (forall_flag)
1158         {
1159           gfc_error
1160             ("Function reference to '%s' at %L is inside a FORALL block",
1161              name, &expr->where);
1162           t = FAILURE;
1163         }
1164       else if (gfc_pure (NULL))
1165         {
1166           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
1167                      "procedure within a PURE procedure", name, &expr->where);
1168           t = FAILURE;
1169         }
1170     }
1171
1172   if (t == SUCCESS)
1173     find_noncopying_intrinsics (expr->value.function.esym,
1174                                 expr->value.function.actual);
1175   return t;
1176 }
1177
1178
1179 /************* Subroutine resolution *************/
1180
1181 static void
1182 pure_subroutine (gfc_code * c, gfc_symbol * sym)
1183 {
1184
1185   if (gfc_pure (sym))
1186     return;
1187
1188   if (forall_flag)
1189     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
1190                sym->name, &c->loc);
1191   else if (gfc_pure (NULL))
1192     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
1193                &c->loc);
1194 }
1195
1196
1197 static match
1198 resolve_generic_s0 (gfc_code * c, gfc_symbol * sym)
1199 {
1200   gfc_symbol *s;
1201
1202   if (sym->attr.generic)
1203     {
1204       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
1205       if (s != NULL)
1206         {
1207           c->resolved_sym = s;
1208           pure_subroutine (c, s);
1209           return MATCH_YES;
1210         }
1211
1212       /* TODO: Need to search for elemental references in generic interface.  */
1213     }
1214
1215   if (sym->attr.intrinsic)
1216     return gfc_intrinsic_sub_interface (c, 0);
1217
1218   return MATCH_NO;
1219 }
1220
1221
1222 static try
1223 resolve_generic_s (gfc_code * c)
1224 {
1225   gfc_symbol *sym;
1226   match m;
1227
1228   sym = c->symtree->n.sym;
1229
1230   m = resolve_generic_s0 (c, sym);
1231   if (m == MATCH_YES)
1232     return SUCCESS;
1233   if (m == MATCH_ERROR)
1234     return FAILURE;
1235
1236   if (sym->ns->parent != NULL)
1237     {
1238       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1239       if (sym != NULL)
1240         {
1241           m = resolve_generic_s0 (c, sym);
1242           if (m == MATCH_YES)
1243             return SUCCESS;
1244           if (m == MATCH_ERROR)
1245             return FAILURE;
1246         }
1247     }
1248
1249   /* Last ditch attempt.  */
1250
1251   if (!gfc_generic_intrinsic (sym->name))
1252     {
1253       gfc_error
1254         ("Generic subroutine '%s' at %L is not an intrinsic subroutine",
1255          sym->name, &c->loc);
1256       return FAILURE;
1257     }
1258
1259   m = gfc_intrinsic_sub_interface (c, 0);
1260   if (m == MATCH_YES)
1261     return SUCCESS;
1262   if (m == MATCH_NO)
1263     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
1264                "intrinsic subroutine interface", sym->name, &c->loc);
1265
1266   return FAILURE;
1267 }
1268
1269
1270 /* Resolve a subroutine call known to be specific.  */
1271
1272 static match
1273 resolve_specific_s0 (gfc_code * c, gfc_symbol * sym)
1274 {
1275   match m;
1276
1277   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
1278     {
1279       if (sym->attr.dummy)
1280         {
1281           sym->attr.proc = PROC_DUMMY;
1282           goto found;
1283         }
1284
1285       sym->attr.proc = PROC_EXTERNAL;
1286       goto found;
1287     }
1288
1289   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
1290     goto found;
1291
1292   if (sym->attr.intrinsic)
1293     {
1294       m = gfc_intrinsic_sub_interface (c, 1);
1295       if (m == MATCH_YES)
1296         return MATCH_YES;
1297       if (m == MATCH_NO)
1298         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
1299                    "with an intrinsic", sym->name, &c->loc);
1300
1301       return MATCH_ERROR;
1302     }
1303
1304   return MATCH_NO;
1305
1306 found:
1307   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
1308
1309   c->resolved_sym = sym;
1310   pure_subroutine (c, sym);
1311
1312   return MATCH_YES;
1313 }
1314
1315
1316 static try
1317 resolve_specific_s (gfc_code * c)
1318 {
1319   gfc_symbol *sym;
1320   match m;
1321
1322   sym = c->symtree->n.sym;
1323
1324   m = resolve_specific_s0 (c, sym);
1325   if (m == MATCH_YES)
1326     return SUCCESS;
1327   if (m == MATCH_ERROR)
1328     return FAILURE;
1329
1330   gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1331
1332   if (sym != NULL)
1333     {
1334       m = resolve_specific_s0 (c, sym);
1335       if (m == MATCH_YES)
1336         return SUCCESS;
1337       if (m == MATCH_ERROR)
1338         return FAILURE;
1339     }
1340
1341   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
1342              sym->name, &c->loc);
1343
1344   return FAILURE;
1345 }
1346
1347
1348 /* Resolve a subroutine call not known to be generic nor specific.  */
1349
1350 static try
1351 resolve_unknown_s (gfc_code * c)
1352 {
1353   gfc_symbol *sym;
1354
1355   sym = c->symtree->n.sym;
1356
1357   if (sym->attr.dummy)
1358     {
1359       sym->attr.proc = PROC_DUMMY;
1360       goto found;
1361     }
1362
1363   /* See if we have an intrinsic function reference.  */
1364
1365   if (gfc_intrinsic_name (sym->name, 1))
1366     {
1367       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
1368         return SUCCESS;
1369       return FAILURE;
1370     }
1371
1372   /* The reference is to an external name.  */
1373
1374 found:
1375   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
1376
1377   c->resolved_sym = sym;
1378
1379   pure_subroutine (c, sym);
1380
1381   return SUCCESS;
1382 }
1383
1384
1385 /* Resolve a subroutine call.  Although it was tempting to use the same code
1386    for functions, subroutines and functions are stored differently and this
1387    makes things awkward.  */
1388
1389 static try
1390 resolve_call (gfc_code * c)
1391 {
1392   try t;
1393
1394   if (resolve_actual_arglist (c->ext.actual) == FAILURE)
1395     return FAILURE;
1396
1397   t = SUCCESS;
1398   if (c->resolved_sym == NULL)
1399     switch (procedure_kind (c->symtree->n.sym))
1400       {
1401       case PTYPE_GENERIC:
1402         t = resolve_generic_s (c);
1403         break;
1404
1405       case PTYPE_SPECIFIC:
1406         t = resolve_specific_s (c);
1407         break;
1408
1409       case PTYPE_UNKNOWN:
1410         t = resolve_unknown_s (c);
1411         break;
1412
1413       default:
1414         gfc_internal_error ("resolve_subroutine(): bad function type");
1415       }
1416
1417   if (t == SUCCESS)
1418     find_noncopying_intrinsics (c->resolved_sym, c->ext.actual);
1419   return t;
1420 }
1421
1422 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
1423    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
1424    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
1425    if their shapes do not match.  If either op1->shape or op2->shape is
1426    NULL, return SUCCESS.  */
1427
1428 static try
1429 compare_shapes (gfc_expr * op1, gfc_expr * op2)
1430 {
1431   try t;
1432   int i;
1433
1434   t = SUCCESS;
1435                   
1436   if (op1->shape != NULL && op2->shape != NULL)
1437     {
1438       for (i = 0; i < op1->rank; i++)
1439         {
1440           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
1441            {
1442              gfc_error ("Shapes for operands at %L and %L are not conformable",
1443                          &op1->where, &op2->where);
1444              t = FAILURE;
1445              break;
1446            }
1447         }
1448     }
1449
1450   return t;
1451 }
1452
1453 /* Resolve an operator expression node.  This can involve replacing the
1454    operation with a user defined function call.  */
1455
1456 static try
1457 resolve_operator (gfc_expr * e)
1458 {
1459   gfc_expr *op1, *op2;
1460   char msg[200];
1461   try t;
1462
1463   /* Resolve all subnodes-- give them types.  */
1464
1465   switch (e->value.op.operator)
1466     {
1467     default:
1468       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
1469         return FAILURE;
1470
1471     /* Fall through...  */
1472
1473     case INTRINSIC_NOT:
1474     case INTRINSIC_UPLUS:
1475     case INTRINSIC_UMINUS:
1476       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
1477         return FAILURE;
1478       break;
1479     }
1480
1481   /* Typecheck the new node.  */
1482
1483   op1 = e->value.op.op1;
1484   op2 = e->value.op.op2;
1485
1486   switch (e->value.op.operator)
1487     {
1488     case INTRINSIC_UPLUS:
1489     case INTRINSIC_UMINUS:
1490       if (op1->ts.type == BT_INTEGER
1491           || op1->ts.type == BT_REAL
1492           || op1->ts.type == BT_COMPLEX)
1493         {
1494           e->ts = op1->ts;
1495           break;
1496         }
1497
1498       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
1499                gfc_op2string (e->value.op.operator), gfc_typename (&e->ts));
1500       goto bad_op;
1501
1502     case INTRINSIC_PLUS:
1503     case INTRINSIC_MINUS:
1504     case INTRINSIC_TIMES:
1505     case INTRINSIC_DIVIDE:
1506     case INTRINSIC_POWER:
1507       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
1508         {
1509           gfc_type_convert_binary (e);
1510           break;
1511         }
1512
1513       sprintf (msg,
1514                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
1515                gfc_op2string (e->value.op.operator), gfc_typename (&op1->ts),
1516                gfc_typename (&op2->ts));
1517       goto bad_op;
1518
1519     case INTRINSIC_CONCAT:
1520       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER)
1521         {
1522           e->ts.type = BT_CHARACTER;
1523           e->ts.kind = op1->ts.kind;
1524           break;
1525         }
1526
1527       sprintf (msg,
1528                _("Operands of string concatenation operator at %%L are %s/%s"),
1529                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
1530       goto bad_op;
1531
1532     case INTRINSIC_AND:
1533     case INTRINSIC_OR:
1534     case INTRINSIC_EQV:
1535     case INTRINSIC_NEQV:
1536       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
1537         {
1538           e->ts.type = BT_LOGICAL;
1539           e->ts.kind = gfc_kind_max (op1, op2);
1540           if (op1->ts.kind < e->ts.kind)
1541             gfc_convert_type (op1, &e->ts, 2);
1542           else if (op2->ts.kind < e->ts.kind)
1543             gfc_convert_type (op2, &e->ts, 2);
1544           break;
1545         }
1546
1547       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
1548                gfc_op2string (e->value.op.operator), gfc_typename (&op1->ts),
1549                gfc_typename (&op2->ts));
1550
1551       goto bad_op;
1552
1553     case INTRINSIC_NOT:
1554       if (op1->ts.type == BT_LOGICAL)
1555         {
1556           e->ts.type = BT_LOGICAL;
1557           e->ts.kind = op1->ts.kind;
1558           break;
1559         }
1560
1561       sprintf (msg, _("Operand of .NOT. operator at %%L is %s"),
1562                gfc_typename (&op1->ts));
1563       goto bad_op;
1564
1565     case INTRINSIC_GT:
1566     case INTRINSIC_GE:
1567     case INTRINSIC_LT:
1568     case INTRINSIC_LE:
1569       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
1570         {
1571           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
1572           goto bad_op;
1573         }
1574
1575       /* Fall through...  */
1576
1577     case INTRINSIC_EQ:
1578     case INTRINSIC_NE:
1579       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER)
1580         {
1581           e->ts.type = BT_LOGICAL;
1582           e->ts.kind = gfc_default_logical_kind;
1583           break;
1584         }
1585
1586       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
1587         {
1588           gfc_type_convert_binary (e);
1589
1590           e->ts.type = BT_LOGICAL;
1591           e->ts.kind = gfc_default_logical_kind;
1592           break;
1593         }
1594
1595       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
1596         sprintf (msg,
1597                  _("Logicals at %%L must be compared with %s instead of %s"),
1598                  e->value.op.operator == INTRINSIC_EQ ? ".EQV." : ".NEQV.",
1599                  gfc_op2string (e->value.op.operator));
1600       else
1601         sprintf (msg,
1602                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
1603                  gfc_op2string (e->value.op.operator), gfc_typename (&op1->ts),
1604                  gfc_typename (&op2->ts));
1605
1606       goto bad_op;
1607
1608     case INTRINSIC_USER:
1609       if (op2 == NULL)
1610         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
1611                  e->value.op.uop->name, gfc_typename (&op1->ts));
1612       else
1613         sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
1614                  e->value.op.uop->name, gfc_typename (&op1->ts),
1615                  gfc_typename (&op2->ts));
1616
1617       goto bad_op;
1618
1619     default:
1620       gfc_internal_error ("resolve_operator(): Bad intrinsic");
1621     }
1622
1623   /* Deal with arrayness of an operand through an operator.  */
1624
1625   t = SUCCESS;
1626
1627   switch (e->value.op.operator)
1628     {
1629     case INTRINSIC_PLUS:
1630     case INTRINSIC_MINUS:
1631     case INTRINSIC_TIMES:
1632     case INTRINSIC_DIVIDE:
1633     case INTRINSIC_POWER:
1634     case INTRINSIC_CONCAT:
1635     case INTRINSIC_AND:
1636     case INTRINSIC_OR:
1637     case INTRINSIC_EQV:
1638     case INTRINSIC_NEQV:
1639     case INTRINSIC_EQ:
1640     case INTRINSIC_NE:
1641     case INTRINSIC_GT:
1642     case INTRINSIC_GE:
1643     case INTRINSIC_LT:
1644     case INTRINSIC_LE:
1645
1646       if (op1->rank == 0 && op2->rank == 0)
1647         e->rank = 0;
1648
1649       if (op1->rank == 0 && op2->rank != 0)
1650         {
1651           e->rank = op2->rank;
1652
1653           if (e->shape == NULL)
1654             e->shape = gfc_copy_shape (op2->shape, op2->rank);
1655         }
1656
1657       if (op1->rank != 0 && op2->rank == 0)
1658         {
1659           e->rank = op1->rank;
1660
1661           if (e->shape == NULL)
1662             e->shape = gfc_copy_shape (op1->shape, op1->rank);
1663         }
1664
1665       if (op1->rank != 0 && op2->rank != 0)
1666         {
1667           if (op1->rank == op2->rank)
1668             {
1669               e->rank = op1->rank;
1670               if (e->shape == NULL)
1671                 {
1672                   t = compare_shapes(op1, op2);
1673                   if (t == FAILURE)
1674                     e->shape = NULL;
1675                   else
1676                 e->shape = gfc_copy_shape (op1->shape, op1->rank);
1677                 }
1678             }
1679           else
1680             {
1681               gfc_error ("Inconsistent ranks for operator at %L and %L",
1682                          &op1->where, &op2->where);
1683               t = FAILURE;
1684
1685               /* Allow higher level expressions to work.  */
1686               e->rank = 0;
1687             }
1688         }
1689
1690       break;
1691
1692     case INTRINSIC_NOT:
1693     case INTRINSIC_UPLUS:
1694     case INTRINSIC_UMINUS:
1695       e->rank = op1->rank;
1696
1697       if (e->shape == NULL)
1698         e->shape = gfc_copy_shape (op1->shape, op1->rank);
1699
1700       /* Simply copy arrayness attribute */
1701       break;
1702
1703     default:
1704       break;
1705     }
1706
1707   /* Attempt to simplify the expression.  */
1708   if (t == SUCCESS)
1709     t = gfc_simplify_expr (e, 0);
1710   return t;
1711
1712 bad_op:
1713
1714   if (gfc_extend_expr (e) == SUCCESS)
1715     return SUCCESS;
1716
1717   gfc_error (msg, &e->where);
1718
1719   return FAILURE;
1720 }
1721
1722
1723 /************** Array resolution subroutines **************/
1724
1725
1726 typedef enum
1727 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
1728 comparison;
1729
1730 /* Compare two integer expressions.  */
1731
1732 static comparison
1733 compare_bound (gfc_expr * a, gfc_expr * b)
1734 {
1735   int i;
1736
1737   if (a == NULL || a->expr_type != EXPR_CONSTANT
1738       || b == NULL || b->expr_type != EXPR_CONSTANT)
1739     return CMP_UNKNOWN;
1740
1741   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
1742     gfc_internal_error ("compare_bound(): Bad expression");
1743
1744   i = mpz_cmp (a->value.integer, b->value.integer);
1745
1746   if (i < 0)
1747     return CMP_LT;
1748   if (i > 0)
1749     return CMP_GT;
1750   return CMP_EQ;
1751 }
1752
1753
1754 /* Compare an integer expression with an integer.  */
1755
1756 static comparison
1757 compare_bound_int (gfc_expr * a, int b)
1758 {
1759   int i;
1760
1761   if (a == NULL || a->expr_type != EXPR_CONSTANT)
1762     return CMP_UNKNOWN;
1763
1764   if (a->ts.type != BT_INTEGER)
1765     gfc_internal_error ("compare_bound_int(): Bad expression");
1766
1767   i = mpz_cmp_si (a->value.integer, b);
1768
1769   if (i < 0)
1770     return CMP_LT;
1771   if (i > 0)
1772     return CMP_GT;
1773   return CMP_EQ;
1774 }
1775
1776
1777 /* Compare a single dimension of an array reference to the array
1778    specification.  */
1779
1780 static try
1781 check_dimension (int i, gfc_array_ref * ar, gfc_array_spec * as)
1782 {
1783
1784 /* Given start, end and stride values, calculate the minimum and
1785    maximum referenced indexes.  */
1786
1787   switch (ar->type)
1788     {
1789     case AR_FULL:
1790       break;
1791
1792     case AR_ELEMENT:
1793       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
1794         goto bound;
1795       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
1796         goto bound;
1797
1798       break;
1799
1800     case AR_SECTION:
1801       if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
1802         {
1803           gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
1804           return FAILURE;
1805         }
1806
1807       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
1808         goto bound;
1809       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
1810         goto bound;
1811
1812       /* TODO: Possibly, we could warn about end[i] being out-of-bound although
1813          it is legal (see 6.2.2.3.1).  */
1814
1815       break;
1816
1817     default:
1818       gfc_internal_error ("check_dimension(): Bad array reference");
1819     }
1820
1821   return SUCCESS;
1822
1823 bound:
1824   gfc_warning ("Array reference at %L is out of bounds", &ar->c_where[i]);
1825   return SUCCESS;
1826 }
1827
1828
1829 /* Compare an array reference with an array specification.  */
1830
1831 static try
1832 compare_spec_to_ref (gfc_array_ref * ar)
1833 {
1834   gfc_array_spec *as;
1835   int i;
1836
1837   as = ar->as;
1838   i = as->rank - 1;
1839   /* TODO: Full array sections are only allowed as actual parameters.  */
1840   if (as->type == AS_ASSUMED_SIZE
1841       && (/*ar->type == AR_FULL
1842           ||*/ (ar->type == AR_SECTION
1843               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
1844     {
1845       gfc_error ("Rightmost upper bound of assumed size array section"
1846                  " not specified at %L", &ar->where);
1847       return FAILURE;
1848     }
1849
1850   if (ar->type == AR_FULL)
1851     return SUCCESS;
1852
1853   if (as->rank != ar->dimen)
1854     {
1855       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
1856                  &ar->where, ar->dimen, as->rank);
1857       return FAILURE;
1858     }
1859
1860   for (i = 0; i < as->rank; i++)
1861     if (check_dimension (i, ar, as) == FAILURE)
1862       return FAILURE;
1863
1864   return SUCCESS;
1865 }
1866
1867
1868 /* Resolve one part of an array index.  */
1869
1870 try
1871 gfc_resolve_index (gfc_expr * index, int check_scalar)
1872 {
1873   gfc_typespec ts;
1874
1875   if (index == NULL)
1876     return SUCCESS;
1877
1878   if (gfc_resolve_expr (index) == FAILURE)
1879     return FAILURE;
1880
1881   if (check_scalar && index->rank != 0)
1882     {
1883       gfc_error ("Array index at %L must be scalar", &index->where);
1884       return FAILURE;
1885     }
1886
1887   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
1888     {
1889       gfc_error ("Array index at %L must be of INTEGER type",
1890                  &index->where);
1891       return FAILURE;
1892     }
1893
1894   if (index->ts.type == BT_REAL)
1895     if (gfc_notify_std (GFC_STD_GNU, "Extension: REAL array index at %L",
1896                         &index->where) == FAILURE)
1897       return FAILURE;
1898
1899   if (index->ts.kind != gfc_index_integer_kind
1900       || index->ts.type != BT_INTEGER)
1901     {
1902       ts.type = BT_INTEGER;
1903       ts.kind = gfc_index_integer_kind;
1904
1905       gfc_convert_type_warn (index, &ts, 2, 0);
1906     }
1907
1908   return SUCCESS;
1909 }
1910
1911 /* Resolve a dim argument to an intrinsic function.  */
1912
1913 try
1914 gfc_resolve_dim_arg (gfc_expr *dim)
1915 {
1916   if (dim == NULL)
1917     return SUCCESS;
1918
1919   if (gfc_resolve_expr (dim) == FAILURE)
1920     return FAILURE;
1921
1922   if (dim->rank != 0)
1923     {
1924       gfc_error ("Argument dim at %L must be scalar", &dim->where);
1925       return FAILURE;
1926   
1927     }
1928   if (dim->ts.type != BT_INTEGER)
1929     {
1930       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
1931       return FAILURE;
1932     }
1933   if (dim->ts.kind != gfc_index_integer_kind)
1934     {
1935       gfc_typespec ts;
1936
1937       ts.type = BT_INTEGER;
1938       ts.kind = gfc_index_integer_kind;
1939
1940       gfc_convert_type_warn (dim, &ts, 2, 0);
1941     }
1942
1943   return SUCCESS;
1944 }
1945
1946 /* Given an expression that contains array references, update those array
1947    references to point to the right array specifications.  While this is
1948    filled in during matching, this information is difficult to save and load
1949    in a module, so we take care of it here.
1950
1951    The idea here is that the original array reference comes from the
1952    base symbol.  We traverse the list of reference structures, setting
1953    the stored reference to references.  Component references can
1954    provide an additional array specification.  */
1955
1956 static void
1957 find_array_spec (gfc_expr * e)
1958 {
1959   gfc_array_spec *as;
1960   gfc_component *c;
1961   gfc_ref *ref;
1962
1963   as = e->symtree->n.sym->as;
1964
1965   for (ref = e->ref; ref; ref = ref->next)
1966     switch (ref->type)
1967       {
1968       case REF_ARRAY:
1969         if (as == NULL)
1970           gfc_internal_error ("find_array_spec(): Missing spec");
1971
1972         ref->u.ar.as = as;
1973         as = NULL;
1974         break;
1975
1976       case REF_COMPONENT:
1977         for (c = e->symtree->n.sym->ts.derived->components; c; c = c->next)
1978           if (c == ref->u.c.component)
1979             break;
1980
1981         if (c == NULL)
1982           gfc_internal_error ("find_array_spec(): Component not found");
1983
1984         if (c->dimension)
1985           {
1986             if (as != NULL)
1987               gfc_internal_error ("find_array_spec(): unused as(1)");
1988             as = c->as;
1989           }
1990
1991         break;
1992
1993       case REF_SUBSTRING:
1994         break;
1995       }
1996
1997   if (as != NULL)
1998     gfc_internal_error ("find_array_spec(): unused as(2)");
1999 }
2000
2001
2002 /* Resolve an array reference.  */
2003
2004 static try
2005 resolve_array_ref (gfc_array_ref * ar)
2006 {
2007   int i, check_scalar;
2008
2009   for (i = 0; i < ar->dimen; i++)
2010     {
2011       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
2012
2013       if (gfc_resolve_index (ar->start[i], check_scalar) == FAILURE)
2014         return FAILURE;
2015       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
2016         return FAILURE;
2017       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
2018         return FAILURE;
2019
2020       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
2021         switch (ar->start[i]->rank)
2022           {
2023           case 0:
2024             ar->dimen_type[i] = DIMEN_ELEMENT;
2025             break;
2026
2027           case 1:
2028             ar->dimen_type[i] = DIMEN_VECTOR;
2029             break;
2030
2031           default:
2032             gfc_error ("Array index at %L is an array of rank %d",
2033                        &ar->c_where[i], ar->start[i]->rank);
2034             return FAILURE;
2035           }
2036     }
2037
2038   /* If the reference type is unknown, figure out what kind it is.  */
2039
2040   if (ar->type == AR_UNKNOWN)
2041     {
2042       ar->type = AR_ELEMENT;
2043       for (i = 0; i < ar->dimen; i++)
2044         if (ar->dimen_type[i] == DIMEN_RANGE
2045             || ar->dimen_type[i] == DIMEN_VECTOR)
2046           {
2047             ar->type = AR_SECTION;
2048             break;
2049           }
2050     }
2051
2052   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
2053     return FAILURE;
2054
2055   return SUCCESS;
2056 }
2057
2058
2059 static try
2060 resolve_substring (gfc_ref * ref)
2061 {
2062
2063   if (ref->u.ss.start != NULL)
2064     {
2065       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
2066         return FAILURE;
2067
2068       if (ref->u.ss.start->ts.type != BT_INTEGER)
2069         {
2070           gfc_error ("Substring start index at %L must be of type INTEGER",
2071                      &ref->u.ss.start->where);
2072           return FAILURE;
2073         }
2074
2075       if (ref->u.ss.start->rank != 0)
2076         {
2077           gfc_error ("Substring start index at %L must be scalar",
2078                      &ref->u.ss.start->where);
2079           return FAILURE;
2080         }
2081
2082       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT)
2083         {
2084           gfc_error ("Substring start index at %L is less than one",
2085                      &ref->u.ss.start->where);
2086           return FAILURE;
2087         }
2088     }
2089
2090   if (ref->u.ss.end != NULL)
2091     {
2092       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
2093         return FAILURE;
2094
2095       if (ref->u.ss.end->ts.type != BT_INTEGER)
2096         {
2097           gfc_error ("Substring end index at %L must be of type INTEGER",
2098                      &ref->u.ss.end->where);
2099           return FAILURE;
2100         }
2101
2102       if (ref->u.ss.end->rank != 0)
2103         {
2104           gfc_error ("Substring end index at %L must be scalar",
2105                      &ref->u.ss.end->where);
2106           return FAILURE;
2107         }
2108
2109       if (ref->u.ss.length != NULL
2110           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT)
2111         {
2112           gfc_error ("Substring end index at %L is out of bounds",
2113                      &ref->u.ss.start->where);
2114           return FAILURE;
2115         }
2116     }
2117
2118   return SUCCESS;
2119 }
2120
2121
2122 /* Resolve subtype references.  */
2123
2124 static try
2125 resolve_ref (gfc_expr * expr)
2126 {
2127   int current_part_dimension, n_components, seen_part_dimension;
2128   gfc_ref *ref;
2129
2130   for (ref = expr->ref; ref; ref = ref->next)
2131     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
2132       {
2133         find_array_spec (expr);
2134         break;
2135       }
2136
2137   for (ref = expr->ref; ref; ref = ref->next)
2138     switch (ref->type)
2139       {
2140       case REF_ARRAY:
2141         if (resolve_array_ref (&ref->u.ar) == FAILURE)
2142           return FAILURE;
2143         break;
2144
2145       case REF_COMPONENT:
2146         break;
2147
2148       case REF_SUBSTRING:
2149         resolve_substring (ref);
2150         break;
2151       }
2152
2153   /* Check constraints on part references.  */
2154
2155   current_part_dimension = 0;
2156   seen_part_dimension = 0;
2157   n_components = 0;
2158
2159   for (ref = expr->ref; ref; ref = ref->next)
2160     {
2161       switch (ref->type)
2162         {
2163         case REF_ARRAY:
2164           switch (ref->u.ar.type)
2165             {
2166             case AR_FULL:
2167             case AR_SECTION:
2168               current_part_dimension = 1;
2169               break;
2170
2171             case AR_ELEMENT:
2172               current_part_dimension = 0;
2173               break;
2174
2175             case AR_UNKNOWN:
2176               gfc_internal_error ("resolve_ref(): Bad array reference");
2177             }
2178
2179           break;
2180
2181         case REF_COMPONENT:
2182           if ((current_part_dimension || seen_part_dimension)
2183               && ref->u.c.component->pointer)
2184             {
2185               gfc_error
2186                 ("Component to the right of a part reference with nonzero "
2187                  "rank must not have the POINTER attribute at %L",
2188                  &expr->where);
2189               return FAILURE;
2190             }
2191
2192           n_components++;
2193           break;
2194
2195         case REF_SUBSTRING:
2196           break;
2197         }
2198
2199       if (((ref->type == REF_COMPONENT && n_components > 1)
2200            || ref->next == NULL)
2201           && current_part_dimension
2202           && seen_part_dimension)
2203         {
2204
2205           gfc_error ("Two or more part references with nonzero rank must "
2206                      "not be specified at %L", &expr->where);
2207           return FAILURE;
2208         }
2209
2210       if (ref->type == REF_COMPONENT)
2211         {
2212           if (current_part_dimension)
2213             seen_part_dimension = 1;
2214
2215           /* reset to make sure */
2216           current_part_dimension = 0;
2217         }
2218     }
2219
2220   return SUCCESS;
2221 }
2222
2223
2224 /* Given an expression, determine its shape.  This is easier than it sounds.
2225    Leaves the shape array NULL if it is not possible to determine the shape.  */
2226
2227 static void
2228 expression_shape (gfc_expr * e)
2229 {
2230   mpz_t array[GFC_MAX_DIMENSIONS];
2231   int i;
2232
2233   if (e->rank == 0 || e->shape != NULL)
2234     return;
2235
2236   for (i = 0; i < e->rank; i++)
2237     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
2238       goto fail;
2239
2240   e->shape = gfc_get_shape (e->rank);
2241
2242   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
2243
2244   return;
2245
2246 fail:
2247   for (i--; i >= 0; i--)
2248     mpz_clear (array[i]);
2249 }
2250
2251
2252 /* Given a variable expression node, compute the rank of the expression by
2253    examining the base symbol and any reference structures it may have.  */
2254
2255 static void
2256 expression_rank (gfc_expr * e)
2257 {
2258   gfc_ref *ref;
2259   int i, rank;
2260
2261   if (e->ref == NULL)
2262     {
2263       if (e->expr_type == EXPR_ARRAY)
2264         goto done;
2265       /* Constructors can have a rank different from one via RESHAPE().  */
2266
2267       if (e->symtree == NULL)
2268         {
2269           e->rank = 0;
2270           goto done;
2271         }
2272
2273       e->rank = (e->symtree->n.sym->as == NULL)
2274                   ? 0 : e->symtree->n.sym->as->rank;
2275       goto done;
2276     }
2277
2278   rank = 0;
2279
2280   for (ref = e->ref; ref; ref = ref->next)
2281     {
2282       if (ref->type != REF_ARRAY)
2283         continue;
2284
2285       if (ref->u.ar.type == AR_FULL)
2286         {
2287           rank = ref->u.ar.as->rank;
2288           break;
2289         }
2290
2291       if (ref->u.ar.type == AR_SECTION)
2292         {
2293           /* Figure out the rank of the section.  */
2294           if (rank != 0)
2295             gfc_internal_error ("expression_rank(): Two array specs");
2296
2297           for (i = 0; i < ref->u.ar.dimen; i++)
2298             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
2299                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
2300               rank++;
2301
2302           break;
2303         }
2304     }
2305
2306   e->rank = rank;
2307
2308 done:
2309   expression_shape (e);
2310 }
2311
2312
2313 /* Resolve a variable expression.  */
2314
2315 static try
2316 resolve_variable (gfc_expr * e)
2317 {
2318   gfc_symbol *sym;
2319
2320   if (e->ref && resolve_ref (e) == FAILURE)
2321     return FAILURE;
2322
2323   if (e->symtree == NULL)
2324     return FAILURE;
2325
2326   sym = e->symtree->n.sym;
2327   if (sym->attr.flavor == FL_PROCEDURE && !sym->attr.function)
2328     {
2329       e->ts.type = BT_PROCEDURE;
2330       return SUCCESS;
2331     }
2332
2333   if (sym->ts.type != BT_UNKNOWN)
2334     gfc_variable_attr (e, &e->ts);
2335   else
2336     {
2337       /* Must be a simple variable reference.  */
2338       if (gfc_set_default_type (sym, 1, NULL) == FAILURE)
2339         return FAILURE;
2340       e->ts = sym->ts;
2341     }
2342
2343   return SUCCESS;
2344 }
2345
2346
2347 /* Resolve an expression.  That is, make sure that types of operands agree
2348    with their operators, intrinsic operators are converted to function calls
2349    for overloaded types and unresolved function references are resolved.  */
2350
2351 try
2352 gfc_resolve_expr (gfc_expr * e)
2353 {
2354   try t;
2355
2356   if (e == NULL)
2357     return SUCCESS;
2358
2359   switch (e->expr_type)
2360     {
2361     case EXPR_OP:
2362       t = resolve_operator (e);
2363       break;
2364
2365     case EXPR_FUNCTION:
2366       t = resolve_function (e);
2367       break;
2368
2369     case EXPR_VARIABLE:
2370       t = resolve_variable (e);
2371       if (t == SUCCESS)
2372         expression_rank (e);
2373       break;
2374
2375     case EXPR_SUBSTRING:
2376       t = resolve_ref (e);
2377       break;
2378
2379     case EXPR_CONSTANT:
2380     case EXPR_NULL:
2381       t = SUCCESS;
2382       break;
2383
2384     case EXPR_ARRAY:
2385       t = FAILURE;
2386       if (resolve_ref (e) == FAILURE)
2387         break;
2388
2389       t = gfc_resolve_array_constructor (e);
2390       /* Also try to expand a constructor.  */
2391       if (t == SUCCESS)
2392         {
2393           expression_rank (e);
2394           gfc_expand_constructor (e);
2395         }
2396
2397       break;
2398
2399     case EXPR_STRUCTURE:
2400       t = resolve_ref (e);
2401       if (t == FAILURE)
2402         break;
2403
2404       t = resolve_structure_cons (e);
2405       if (t == FAILURE)
2406         break;
2407
2408       t = gfc_simplify_expr (e, 0);
2409       break;
2410
2411     default:
2412       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
2413     }
2414
2415   return t;
2416 }
2417
2418
2419 /* Resolve an expression from an iterator.  They must be scalar and have
2420    INTEGER or (optionally) REAL type.  */
2421
2422 static try
2423 gfc_resolve_iterator_expr (gfc_expr * expr, bool real_ok,
2424                            const char * name_msgid)
2425 {
2426   if (gfc_resolve_expr (expr) == FAILURE)
2427     return FAILURE;
2428
2429   if (expr->rank != 0)
2430     {
2431       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
2432       return FAILURE;
2433     }
2434
2435   if (!(expr->ts.type == BT_INTEGER
2436         || (expr->ts.type == BT_REAL && real_ok)))
2437     {
2438       if (real_ok)
2439         gfc_error ("%s at %L must be INTEGER or REAL", _(name_msgid),
2440                    &expr->where);
2441       else
2442         gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
2443       return FAILURE;
2444     }
2445   return SUCCESS;
2446 }
2447
2448
2449 /* Resolve the expressions in an iterator structure.  If REAL_OK is
2450    false allow only INTEGER type iterators, otherwise allow REAL types.  */
2451
2452 try
2453 gfc_resolve_iterator (gfc_iterator * iter, bool real_ok)
2454 {
2455
2456   if (iter->var->ts.type == BT_REAL)
2457     gfc_notify_std (GFC_STD_F95_DEL,
2458                     "Obsolete: REAL DO loop iterator at %L",
2459                     &iter->var->where);
2460
2461   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
2462       == FAILURE)
2463     return FAILURE;
2464
2465   if (gfc_pure (NULL) && gfc_impure_variable (iter->var->symtree->n.sym))
2466     {
2467       gfc_error ("Cannot assign to loop variable in PURE procedure at %L",
2468                  &iter->var->where);
2469       return FAILURE;
2470     }
2471
2472   if (gfc_resolve_iterator_expr (iter->start, real_ok,
2473                                  "Start expression in DO loop") == FAILURE)
2474     return FAILURE;
2475
2476   if (gfc_resolve_iterator_expr (iter->end, real_ok,
2477                                  "End expression in DO loop") == FAILURE)
2478     return FAILURE;
2479
2480   if (gfc_resolve_iterator_expr (iter->step, real_ok,
2481                                  "Step expression in DO loop") == FAILURE)
2482     return FAILURE;
2483
2484   if (iter->step->expr_type == EXPR_CONSTANT)
2485     {
2486       if ((iter->step->ts.type == BT_INTEGER
2487            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
2488           || (iter->step->ts.type == BT_REAL
2489               && mpfr_sgn (iter->step->value.real) == 0))
2490         {
2491           gfc_error ("Step expression in DO loop at %L cannot be zero",
2492                      &iter->step->where);
2493           return FAILURE;
2494         }
2495     }
2496
2497   /* Convert start, end, and step to the same type as var.  */
2498   if (iter->start->ts.kind != iter->var->ts.kind
2499       || iter->start->ts.type != iter->var->ts.type)
2500     gfc_convert_type (iter->start, &iter->var->ts, 2);
2501
2502   if (iter->end->ts.kind != iter->var->ts.kind
2503       || iter->end->ts.type != iter->var->ts.type)
2504     gfc_convert_type (iter->end, &iter->var->ts, 2);
2505
2506   if (iter->step->ts.kind != iter->var->ts.kind
2507       || iter->step->ts.type != iter->var->ts.type)
2508     gfc_convert_type (iter->step, &iter->var->ts, 2);
2509
2510   return SUCCESS;
2511 }
2512
2513
2514 /* Resolve a list of FORALL iterators.  */
2515
2516 static void
2517 resolve_forall_iterators (gfc_forall_iterator * iter)
2518 {
2519
2520   while (iter)
2521     {
2522       if (gfc_resolve_expr (iter->var) == SUCCESS
2523           && iter->var->ts.type != BT_INTEGER)
2524         gfc_error ("FORALL Iteration variable at %L must be INTEGER",
2525                    &iter->var->where);
2526
2527       if (gfc_resolve_expr (iter->start) == SUCCESS
2528           && iter->start->ts.type != BT_INTEGER)
2529         gfc_error ("FORALL start expression at %L must be INTEGER",
2530                    &iter->start->where);
2531       if (iter->var->ts.kind != iter->start->ts.kind)
2532         gfc_convert_type (iter->start, &iter->var->ts, 2);
2533
2534       if (gfc_resolve_expr (iter->end) == SUCCESS
2535           && iter->end->ts.type != BT_INTEGER)
2536         gfc_error ("FORALL end expression at %L must be INTEGER",
2537                    &iter->end->where);
2538       if (iter->var->ts.kind != iter->end->ts.kind)
2539         gfc_convert_type (iter->end, &iter->var->ts, 2);
2540
2541       if (gfc_resolve_expr (iter->stride) == SUCCESS
2542           && iter->stride->ts.type != BT_INTEGER)
2543         gfc_error ("FORALL Stride expression at %L must be INTEGER",
2544                    &iter->stride->where);
2545       if (iter->var->ts.kind != iter->stride->ts.kind)
2546         gfc_convert_type (iter->stride, &iter->var->ts, 2);
2547
2548       iter = iter->next;
2549     }
2550 }
2551
2552
2553 /* Given a pointer to a symbol that is a derived type, see if any components
2554    have the POINTER attribute.  The search is recursive if necessary.
2555    Returns zero if no pointer components are found, nonzero otherwise.  */
2556
2557 static int
2558 derived_pointer (gfc_symbol * sym)
2559 {
2560   gfc_component *c;
2561
2562   for (c = sym->components; c; c = c->next)
2563     {
2564       if (c->pointer)
2565         return 1;
2566
2567       if (c->ts.type == BT_DERIVED && derived_pointer (c->ts.derived))
2568         return 1;
2569     }
2570
2571   return 0;
2572 }
2573
2574
2575 /* Given a pointer to a symbol that is a derived type, see if it's
2576    inaccessible, i.e. if it's defined in another module and the components are
2577    PRIVATE.  The search is recursive if necessary.  Returns zero if no
2578    inaccessible components are found, nonzero otherwise.  */
2579
2580 static int
2581 derived_inaccessible (gfc_symbol *sym)
2582 {
2583   gfc_component *c;
2584
2585   if (sym->attr.use_assoc && sym->component_access == ACCESS_PRIVATE)
2586     return 1;
2587
2588   for (c = sym->components; c; c = c->next)
2589     {
2590         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.derived))
2591           return 1;
2592     }
2593
2594   return 0;
2595 }
2596
2597
2598 /* Resolve the argument of a deallocate expression.  The expression must be
2599    a pointer or a full array.  */
2600
2601 static try
2602 resolve_deallocate_expr (gfc_expr * e)
2603 {
2604   symbol_attribute attr;
2605   int allocatable;
2606   gfc_ref *ref;
2607
2608   if (gfc_resolve_expr (e) == FAILURE)
2609     return FAILURE;
2610
2611   attr = gfc_expr_attr (e);
2612   if (attr.pointer)
2613     return SUCCESS;
2614
2615   if (e->expr_type != EXPR_VARIABLE)
2616     goto bad;
2617
2618   allocatable = e->symtree->n.sym->attr.allocatable;
2619   for (ref = e->ref; ref; ref = ref->next)
2620     switch (ref->type)
2621       {
2622       case REF_ARRAY:
2623         if (ref->u.ar.type != AR_FULL)
2624           allocatable = 0;
2625         break;
2626
2627       case REF_COMPONENT:
2628         allocatable = (ref->u.c.component->as != NULL
2629                        && ref->u.c.component->as->type == AS_DEFERRED);
2630         break;
2631
2632       case REF_SUBSTRING:
2633         allocatable = 0;
2634         break;
2635       }
2636
2637   if (allocatable == 0)
2638     {
2639     bad:
2640       gfc_error ("Expression in DEALLOCATE statement at %L must be "
2641                  "ALLOCATABLE or a POINTER", &e->where);
2642     }
2643
2644   return SUCCESS;
2645 }
2646
2647
2648 /* Given the expression node e for an allocatable/pointer of derived type to be
2649    allocated, get the expression node to be initialized afterwards (needed for
2650    derived types with default initializers).  */
2651
2652 static gfc_expr *
2653 expr_to_initialize (gfc_expr * e)
2654 {
2655   gfc_expr *result;
2656   gfc_ref *ref;
2657   int i;
2658
2659   result = gfc_copy_expr (e);
2660
2661   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
2662   for (ref = result->ref; ref; ref = ref->next)
2663     if (ref->type == REF_ARRAY && ref->next == NULL)
2664       {
2665         ref->u.ar.type = AR_FULL;
2666
2667         for (i = 0; i < ref->u.ar.dimen; i++)
2668           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
2669
2670         result->rank = ref->u.ar.dimen; 
2671         break;
2672       }
2673
2674   return result;
2675 }
2676
2677
2678 /* Resolve the expression in an ALLOCATE statement, doing the additional
2679    checks to see whether the expression is OK or not.  The expression must
2680    have a trailing array reference that gives the size of the array.  */
2681
2682 static try
2683 resolve_allocate_expr (gfc_expr * e, gfc_code * code)
2684 {
2685   int i, pointer, allocatable, dimension;
2686   symbol_attribute attr;
2687   gfc_ref *ref, *ref2;
2688   gfc_array_ref *ar;
2689   gfc_code *init_st;
2690   gfc_expr *init_e;
2691
2692   if (gfc_resolve_expr (e) == FAILURE)
2693     return FAILURE;
2694
2695   /* Make sure the expression is allocatable or a pointer.  If it is
2696      pointer, the next-to-last reference must be a pointer.  */
2697
2698   ref2 = NULL;
2699
2700   if (e->expr_type != EXPR_VARIABLE)
2701     {
2702       allocatable = 0;
2703
2704       attr = gfc_expr_attr (e);
2705       pointer = attr.pointer;
2706       dimension = attr.dimension;
2707
2708     }
2709   else
2710     {
2711       allocatable = e->symtree->n.sym->attr.allocatable;
2712       pointer = e->symtree->n.sym->attr.pointer;
2713       dimension = e->symtree->n.sym->attr.dimension;
2714
2715       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
2716         switch (ref->type)
2717           {
2718           case REF_ARRAY:
2719             if (ref->next != NULL)
2720               pointer = 0;
2721             break;
2722
2723           case REF_COMPONENT:
2724             allocatable = (ref->u.c.component->as != NULL
2725                            && ref->u.c.component->as->type == AS_DEFERRED);
2726
2727             pointer = ref->u.c.component->pointer;
2728             dimension = ref->u.c.component->dimension;
2729             break;
2730
2731           case REF_SUBSTRING:
2732             allocatable = 0;
2733             pointer = 0;
2734             break;
2735           }
2736     }
2737
2738   if (allocatable == 0 && pointer == 0)
2739     {
2740       gfc_error ("Expression in ALLOCATE statement at %L must be "
2741                  "ALLOCATABLE or a POINTER", &e->where);
2742       return FAILURE;
2743     }
2744
2745   /* Add default initializer for those derived types that need them.  */
2746   if (e->ts.type == BT_DERIVED && (init_e = gfc_default_initializer (&e->ts)))
2747     {
2748         init_st = gfc_get_code ();
2749         init_st->loc = code->loc;
2750         init_st->op = EXEC_ASSIGN;
2751         init_st->expr = expr_to_initialize (e);
2752         init_st->expr2 = init_e;
2753
2754         init_st->next = code->next;
2755         code->next = init_st;
2756     }
2757
2758   if (pointer && dimension == 0)
2759     return SUCCESS;
2760
2761   /* Make sure the next-to-last reference node is an array specification.  */
2762
2763   if (ref2 == NULL || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL)
2764     {
2765       gfc_error ("Array specification required in ALLOCATE statement "
2766                  "at %L", &e->where);
2767       return FAILURE;
2768     }
2769
2770   if (ref2->u.ar.type == AR_ELEMENT)
2771     return SUCCESS;
2772
2773   /* Make sure that the array section reference makes sense in the
2774     context of an ALLOCATE specification.  */
2775
2776   ar = &ref2->u.ar;
2777
2778   for (i = 0; i < ar->dimen; i++)
2779     switch (ar->dimen_type[i])
2780       {
2781       case DIMEN_ELEMENT:
2782         break;
2783
2784       case DIMEN_RANGE:
2785         if (ar->start[i] != NULL
2786             && ar->end[i] != NULL
2787             && ar->stride[i] == NULL)
2788           break;
2789
2790         /* Fall Through...  */
2791
2792       case DIMEN_UNKNOWN:
2793       case DIMEN_VECTOR:
2794         gfc_error ("Bad array specification in ALLOCATE statement at %L",
2795                    &e->where);
2796         return FAILURE;
2797       }
2798
2799   return SUCCESS;
2800 }
2801
2802
2803 /************ SELECT CASE resolution subroutines ************/
2804
2805 /* Callback function for our mergesort variant.  Determines interval
2806    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
2807    op1 > op2.  Assumes we're not dealing with the default case.  
2808    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
2809    There are nine situations to check.  */
2810
2811 static int
2812 compare_cases (const gfc_case * op1, const gfc_case * op2)
2813 {
2814   int retval;
2815
2816   if (op1->low == NULL) /* op1 = (:L)  */
2817     {
2818       /* op2 = (:N), so overlap.  */
2819       retval = 0;
2820       /* op2 = (M:) or (M:N),  L < M  */
2821       if (op2->low != NULL
2822           && gfc_compare_expr (op1->high, op2->low) < 0)
2823         retval = -1;
2824     }
2825   else if (op1->high == NULL) /* op1 = (K:)  */
2826     {
2827       /* op2 = (M:), so overlap.  */
2828       retval = 0;
2829       /* op2 = (:N) or (M:N), K > N  */
2830       if (op2->high != NULL
2831           && gfc_compare_expr (op1->low, op2->high) > 0)
2832         retval = 1;
2833     }
2834   else /* op1 = (K:L)  */
2835     {
2836       if (op2->low == NULL)       /* op2 = (:N), K > N  */
2837         retval = (gfc_compare_expr (op1->low, op2->high) > 0) ? 1 : 0;
2838       else if (op2->high == NULL) /* op2 = (M:), L < M  */
2839         retval = (gfc_compare_expr (op1->high, op2->low) < 0) ? -1 : 0;
2840       else                        /* op2 = (M:N)  */
2841         {
2842           retval =  0;
2843           /* L < M  */
2844           if (gfc_compare_expr (op1->high, op2->low) < 0)
2845             retval =  -1;
2846           /* K > N  */
2847           else if (gfc_compare_expr (op1->low, op2->high) > 0)
2848             retval =  1;
2849         }
2850     }
2851
2852   return retval;
2853 }
2854
2855
2856 /* Merge-sort a double linked case list, detecting overlap in the
2857    process.  LIST is the head of the double linked case list before it
2858    is sorted.  Returns the head of the sorted list if we don't see any
2859    overlap, or NULL otherwise.  */
2860
2861 static gfc_case *
2862 check_case_overlap (gfc_case * list)
2863 {
2864   gfc_case *p, *q, *e, *tail;
2865   int insize, nmerges, psize, qsize, cmp, overlap_seen;
2866
2867   /* If the passed list was empty, return immediately.  */
2868   if (!list)
2869     return NULL;
2870
2871   overlap_seen = 0;
2872   insize = 1;
2873
2874   /* Loop unconditionally.  The only exit from this loop is a return
2875      statement, when we've finished sorting the case list.  */
2876   for (;;)
2877     {
2878       p = list;
2879       list = NULL;
2880       tail = NULL;
2881
2882       /* Count the number of merges we do in this pass.  */
2883       nmerges = 0;
2884
2885       /* Loop while there exists a merge to be done.  */
2886       while (p)
2887         {
2888           int i;
2889
2890           /* Count this merge.  */
2891           nmerges++;
2892
2893           /* Cut the list in two pieces by stepping INSIZE places
2894              forward in the list, starting from P.  */
2895           psize = 0;
2896           q = p;
2897           for (i = 0; i < insize; i++)
2898             {
2899               psize++;
2900               q = q->right;
2901               if (!q)
2902                 break;
2903             }
2904           qsize = insize;
2905
2906           /* Now we have two lists.  Merge them!  */
2907           while (psize > 0 || (qsize > 0 && q != NULL))
2908             {
2909
2910               /* See from which the next case to merge comes from.  */
2911               if (psize == 0)
2912                 {
2913                   /* P is empty so the next case must come from Q.  */
2914                   e = q;
2915                   q = q->right;
2916                   qsize--;
2917                 }
2918               else if (qsize == 0 || q == NULL)
2919                 {
2920                   /* Q is empty.  */
2921                   e = p;
2922                   p = p->right;
2923                   psize--;
2924                 }
2925               else
2926                 {
2927                   cmp = compare_cases (p, q);
2928                   if (cmp < 0)
2929                     {
2930                       /* The whole case range for P is less than the
2931                          one for Q.  */
2932                       e = p;
2933                       p = p->right;
2934                       psize--;
2935                     }
2936                   else if (cmp > 0)
2937                     {
2938                       /* The whole case range for Q is greater than
2939                          the case range for P.  */
2940                       e = q;
2941                       q = q->right;
2942                       qsize--;
2943                     }
2944                   else
2945                     {
2946                       /* The cases overlap, or they are the same
2947                          element in the list.  Either way, we must
2948                          issue an error and get the next case from P.  */
2949                       /* FIXME: Sort P and Q by line number.  */
2950                       gfc_error ("CASE label at %L overlaps with CASE "
2951                                  "label at %L", &p->where, &q->where);
2952                       overlap_seen = 1;
2953                       e = p;
2954                       p = p->right;
2955                       psize--;
2956                     }
2957                 }
2958
2959                 /* Add the next element to the merged list.  */
2960               if (tail)
2961                 tail->right = e;
2962               else
2963                 list = e;
2964               e->left = tail;
2965               tail = e;
2966             }
2967
2968           /* P has now stepped INSIZE places along, and so has Q.  So
2969              they're the same.  */
2970           p = q;
2971         }
2972       tail->right = NULL;
2973
2974       /* If we have done only one merge or none at all, we've
2975          finished sorting the cases.  */
2976       if (nmerges <= 1)
2977         {
2978           if (!overlap_seen)
2979             return list;
2980           else
2981             return NULL;
2982         }
2983
2984       /* Otherwise repeat, merging lists twice the size.  */
2985       insize *= 2;
2986     }
2987 }
2988
2989
2990 /* Check to see if an expression is suitable for use in a CASE statement.
2991    Makes sure that all case expressions are scalar constants of the same
2992    type.  Return FAILURE if anything is wrong.  */
2993
2994 static try
2995 validate_case_label_expr (gfc_expr * e, gfc_expr * case_expr)
2996 {
2997   if (e == NULL) return SUCCESS;
2998
2999   if (e->ts.type != case_expr->ts.type)
3000     {
3001       gfc_error ("Expression in CASE statement at %L must be of type %s",
3002                  &e->where, gfc_basic_typename (case_expr->ts.type));
3003       return FAILURE;
3004     }
3005
3006   /* C805 (R808) For a given case-construct, each case-value shall be of
3007      the same type as case-expr.  For character type, length differences
3008      are allowed, but the kind type parameters shall be the same.  */
3009
3010   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
3011     {
3012       gfc_error("Expression in CASE statement at %L must be kind %d",
3013                 &e->where, case_expr->ts.kind);
3014       return FAILURE;
3015     }
3016
3017   /* Convert the case value kind to that of case expression kind, if needed.
3018      FIXME:  Should a warning be issued?  */
3019   if (e->ts.kind != case_expr->ts.kind)
3020     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
3021
3022   if (e->rank != 0)
3023     {
3024       gfc_error ("Expression in CASE statement at %L must be scalar",
3025                  &e->where);
3026       return FAILURE;
3027     }
3028
3029   return SUCCESS;
3030 }
3031
3032
3033 /* Given a completely parsed select statement, we:
3034
3035      - Validate all expressions and code within the SELECT.
3036      - Make sure that the selection expression is not of the wrong type.
3037      - Make sure that no case ranges overlap.
3038      - Eliminate unreachable cases and unreachable code resulting from
3039        removing case labels.
3040
3041    The standard does allow unreachable cases, e.g. CASE (5:3).  But
3042    they are a hassle for code generation, and to prevent that, we just
3043    cut them out here.  This is not necessary for overlapping cases
3044    because they are illegal and we never even try to generate code.
3045
3046    We have the additional caveat that a SELECT construct could have
3047    been a computed GOTO in the source code. Fortunately we can fairly
3048    easily work around that here: The case_expr for a "real" SELECT CASE
3049    is in code->expr1, but for a computed GOTO it is in code->expr2. All
3050    we have to do is make sure that the case_expr is a scalar integer
3051    expression.  */
3052
3053 static void
3054 resolve_select (gfc_code * code)
3055 {
3056   gfc_code *body;
3057   gfc_expr *case_expr;
3058   gfc_case *cp, *default_case, *tail, *head;
3059   int seen_unreachable;
3060   int ncases;
3061   bt type;
3062   try t;
3063
3064   if (code->expr == NULL)
3065     {
3066       /* This was actually a computed GOTO statement.  */
3067       case_expr = code->expr2;
3068       if (case_expr->ts.type != BT_INTEGER
3069           || case_expr->rank != 0)
3070         gfc_error ("Selection expression in computed GOTO statement "
3071                    "at %L must be a scalar integer expression",
3072                    &case_expr->where);
3073
3074       /* Further checking is not necessary because this SELECT was built
3075          by the compiler, so it should always be OK.  Just move the
3076          case_expr from expr2 to expr so that we can handle computed
3077          GOTOs as normal SELECTs from here on.  */
3078       code->expr = code->expr2;
3079       code->expr2 = NULL;
3080       return;
3081     }
3082
3083   case_expr = code->expr;
3084
3085   type = case_expr->ts.type;
3086   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
3087     {
3088       gfc_error ("Argument of SELECT statement at %L cannot be %s",
3089                  &case_expr->where, gfc_typename (&case_expr->ts));
3090
3091       /* Punt. Going on here just produce more garbage error messages.  */
3092       return;
3093     }
3094
3095   if (case_expr->rank != 0)
3096     {
3097       gfc_error ("Argument of SELECT statement at %L must be a scalar "
3098                  "expression", &case_expr->where);
3099
3100       /* Punt.  */
3101       return;
3102     }
3103
3104   /* PR 19168 has a long discussion concerning a mismatch of the kinds
3105      of the SELECT CASE expression and its CASE values.  Walk the lists
3106      of case values, and if we find a mismatch, promote case_expr to
3107      the appropriate kind.  */
3108
3109   if (type == BT_LOGICAL || type == BT_INTEGER)
3110     {
3111       for (body = code->block; body; body = body->block)
3112         {
3113           /* Walk the case label list.  */
3114           for (cp = body->ext.case_list; cp; cp = cp->next)
3115             {
3116               /* Intercept the DEFAULT case.  It does not have a kind.  */
3117               if (cp->low == NULL && cp->high == NULL)
3118                 continue;
3119
3120               /* Unreachable case ranges are discarded, so ignore.  */  
3121               if (cp->low != NULL && cp->high != NULL
3122                   && cp->low != cp->high
3123                   && gfc_compare_expr (cp->low, cp->high) > 0)
3124                 continue;
3125
3126               /* FIXME: Should a warning be issued?  */
3127               if (cp->low != NULL
3128                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
3129                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
3130
3131               if (cp->high != NULL
3132                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
3133                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
3134             }
3135          }
3136     }
3137
3138   /* Assume there is no DEFAULT case.  */
3139   default_case = NULL;
3140   head = tail = NULL;
3141   ncases = 0;
3142
3143   for (body = code->block; body; body = body->block)
3144     {
3145       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
3146       t = SUCCESS;
3147       seen_unreachable = 0;
3148
3149       /* Walk the case label list, making sure that all case labels
3150          are legal.  */
3151       for (cp = body->ext.case_list; cp; cp = cp->next)
3152         {
3153           /* Count the number of cases in the whole construct.  */
3154           ncases++;
3155
3156           /* Intercept the DEFAULT case.  */
3157           if (cp->low == NULL && cp->high == NULL)
3158             {
3159               if (default_case != NULL)
3160                 {
3161                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
3162                              "by a second DEFAULT CASE at %L",
3163                              &default_case->where, &cp->where);
3164                   t = FAILURE;
3165                   break;
3166                 }
3167               else
3168                 {
3169                   default_case = cp;
3170                   continue;
3171                 }
3172             }
3173
3174           /* Deal with single value cases and case ranges.  Errors are
3175              issued from the validation function.  */
3176           if(validate_case_label_expr (cp->low, case_expr) != SUCCESS
3177              || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
3178             {
3179               t = FAILURE;
3180               break;
3181             }
3182
3183           if (type == BT_LOGICAL
3184               && ((cp->low == NULL || cp->high == NULL)
3185                   || cp->low != cp->high))
3186             {
3187               gfc_error
3188                 ("Logical range in CASE statement at %L is not allowed",
3189                  &cp->low->where);
3190               t = FAILURE;
3191               break;
3192             }
3193
3194           if (cp->low != NULL && cp->high != NULL
3195               && cp->low != cp->high
3196               && gfc_compare_expr (cp->low, cp->high) > 0)
3197             {
3198               if (gfc_option.warn_surprising)
3199                 gfc_warning ("Range specification at %L can never "
3200                              "be matched", &cp->where);
3201
3202               cp->unreachable = 1;
3203               seen_unreachable = 1;
3204             }
3205           else
3206             {
3207               /* If the case range can be matched, it can also overlap with
3208                  other cases.  To make sure it does not, we put it in a
3209                  double linked list here.  We sort that with a merge sort
3210                  later on to detect any overlapping cases.  */
3211               if (!head)
3212                 {
3213                   head = tail = cp;
3214                   head->right = head->left = NULL;
3215                 }
3216               else
3217                 {
3218                   tail->right = cp;
3219                   tail->right->left = tail;
3220                   tail = tail->right;
3221                   tail->right = NULL;
3222                 }
3223             }
3224         }
3225
3226       /* It there was a failure in the previous case label, give up
3227          for this case label list.  Continue with the next block.  */
3228       if (t == FAILURE)
3229         continue;
3230
3231       /* See if any case labels that are unreachable have been seen.
3232          If so, we eliminate them.  This is a bit of a kludge because
3233          the case lists for a single case statement (label) is a
3234          single forward linked lists.  */
3235       if (seen_unreachable)
3236       {
3237         /* Advance until the first case in the list is reachable.  */
3238         while (body->ext.case_list != NULL
3239                && body->ext.case_list->unreachable)
3240           {
3241             gfc_case *n = body->ext.case_list;
3242             body->ext.case_list = body->ext.case_list->next;
3243             n->next = NULL;
3244             gfc_free_case_list (n);
3245           }
3246
3247         /* Strip all other unreachable cases.  */
3248         if (body->ext.case_list)
3249           {
3250             for (cp = body->ext.case_list; cp->next; cp = cp->next)
3251               {
3252                 if (cp->next->unreachable)
3253                   {
3254                     gfc_case *n = cp->next;
3255                     cp->next = cp->next->next;
3256                     n->next = NULL;
3257                     gfc_free_case_list (n);
3258                   }
3259               }
3260           }
3261       }
3262     }
3263
3264   /* See if there were overlapping cases.  If the check returns NULL,
3265      there was overlap.  In that case we don't do anything.  If head
3266      is non-NULL, we prepend the DEFAULT case.  The sorted list can
3267      then used during code generation for SELECT CASE constructs with
3268      a case expression of a CHARACTER type.  */
3269   if (head)
3270     {
3271       head = check_case_overlap (head);
3272
3273       /* Prepend the default_case if it is there.  */
3274       if (head != NULL && default_case)
3275         {
3276           default_case->left = NULL;
3277           default_case->right = head;
3278           head->left = default_case;
3279         }
3280     }
3281
3282   /* Eliminate dead blocks that may be the result if we've seen
3283      unreachable case labels for a block.  */
3284   for (body = code; body && body->block; body = body->block)
3285     {
3286       if (body->block->ext.case_list == NULL)
3287         {
3288           /* Cut the unreachable block from the code chain.  */
3289           gfc_code *c = body->block;
3290           body->block = c->block;
3291
3292           /* Kill the dead block, but not the blocks below it.  */
3293           c->block = NULL;
3294           gfc_free_statements (c);
3295         }
3296     }
3297
3298   /* More than two cases is legal but insane for logical selects.
3299      Issue a warning for it.  */
3300   if (gfc_option.warn_surprising && type == BT_LOGICAL
3301       && ncases > 2)
3302     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
3303                  &code->loc);
3304 }
3305
3306
3307 /* Resolve a transfer statement. This is making sure that:
3308    -- a derived type being transferred has only non-pointer components
3309    -- a derived type being transferred doesn't have private components, unless 
3310       it's being transferred from the module where the type was defined
3311    -- we're not trying to transfer a whole assumed size array.  */
3312
3313 static void
3314 resolve_transfer (gfc_code * code)
3315 {
3316   gfc_typespec *ts;
3317   gfc_symbol *sym;
3318   gfc_ref *ref;
3319   gfc_expr *exp;
3320
3321   exp = code->expr;
3322
3323   if (exp->expr_type != EXPR_VARIABLE)
3324     return;
3325
3326   sym = exp->symtree->n.sym;
3327   ts = &sym->ts;
3328
3329   /* Go to actual component transferred.  */
3330   for (ref = code->expr->ref; ref; ref = ref->next)
3331     if (ref->type == REF_COMPONENT)
3332       ts = &ref->u.c.component->ts;
3333
3334   if (ts->type == BT_DERIVED)
3335     {
3336       /* Check that transferred derived type doesn't contain POINTER
3337          components.  */
3338       if (derived_pointer (ts->derived))
3339         {
3340           gfc_error ("Data transfer element at %L cannot have "
3341                      "POINTER components", &code->loc);
3342           return;
3343         }
3344
3345       if (derived_inaccessible (ts->derived))
3346         {
3347           gfc_error ("Data transfer element at %L cannot have "
3348                      "PRIVATE components",&code->loc);
3349           return;
3350         }
3351     }
3352
3353   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
3354       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
3355     {
3356       gfc_error ("Data transfer element at %L cannot be a full reference to "
3357                  "an assumed-size array", &code->loc);
3358       return;
3359     }
3360 }
3361
3362
3363 /*********** Toplevel code resolution subroutines ***********/
3364
3365 /* Given a branch to a label and a namespace, if the branch is conforming.
3366    The code node described where the branch is located.  */
3367
3368 static void
3369 resolve_branch (gfc_st_label * label, gfc_code * code)
3370 {
3371   gfc_code *block, *found;
3372   code_stack *stack;
3373   gfc_st_label *lp;
3374
3375   if (label == NULL)
3376     return;
3377   lp = label;
3378
3379   /* Step one: is this a valid branching target?  */
3380
3381   if (lp->defined == ST_LABEL_UNKNOWN)
3382     {
3383       gfc_error ("Label %d referenced at %L is never defined", lp->value,
3384                  &lp->where);
3385       return;
3386     }
3387
3388   if (lp->defined != ST_LABEL_TARGET)
3389     {
3390       gfc_error ("Statement at %L is not a valid branch target statement "
3391                  "for the branch statement at %L", &lp->where, &code->loc);
3392       return;
3393     }
3394
3395   /* Step two: make sure this branch is not a branch to itself ;-)  */
3396
3397   if (code->here == label)
3398     {
3399       gfc_warning ("Branch at %L causes an infinite loop", &code->loc);
3400       return;
3401     }
3402
3403   /* Step three: Try to find the label in the parse tree. To do this,
3404      we traverse the tree block-by-block: first the block that
3405      contains this GOTO, then the block that it is nested in, etc.  We
3406      can ignore other blocks because branching into another block is
3407      not allowed.  */
3408
3409   found = NULL;
3410
3411   for (stack = cs_base; stack; stack = stack->prev)
3412     {
3413       for (block = stack->head; block; block = block->next)
3414         {
3415           if (block->here == label)
3416             {
3417               found = block;
3418               break;
3419             }
3420         }
3421
3422       if (found)
3423         break;
3424     }
3425
3426   if (found == NULL)
3427     {
3428       /* still nothing, so illegal.  */
3429       gfc_error_now ("Label at %L is not in the same block as the "
3430                      "GOTO statement at %L", &lp->where, &code->loc);
3431       return;
3432     }
3433
3434   /* Step four: Make sure that the branching target is legal if
3435      the statement is an END {SELECT,DO,IF}.  */
3436
3437   if (found->op == EXEC_NOP)
3438     {
3439       for (stack = cs_base; stack; stack = stack->prev)
3440         if (stack->current->next == found)
3441           break;
3442
3443       if (stack == NULL)
3444         gfc_notify_std (GFC_STD_F95_DEL,
3445                         "Obsolete: GOTO at %L jumps to END of construct at %L",
3446                         &code->loc, &found->loc);
3447     }
3448 }
3449
3450
3451 /* Check whether EXPR1 has the same shape as EXPR2.  */
3452
3453 static try
3454 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
3455 {
3456   mpz_t shape[GFC_MAX_DIMENSIONS];
3457   mpz_t shape2[GFC_MAX_DIMENSIONS];
3458   try result = FAILURE;
3459   int i;
3460
3461   /* Compare the rank.  */
3462   if (expr1->rank != expr2->rank)
3463     return result;
3464
3465   /* Compare the size of each dimension.  */
3466   for (i=0; i<expr1->rank; i++)
3467     {
3468       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
3469         goto ignore;
3470
3471       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
3472         goto ignore;
3473
3474       if (mpz_cmp (shape[i], shape2[i]))
3475         goto over;
3476     }
3477
3478   /* When either of the two expression is an assumed size array, we
3479      ignore the comparison of dimension sizes.  */
3480 ignore:
3481   result = SUCCESS;
3482
3483 over:
3484   for (i--; i>=0; i--)
3485     {
3486       mpz_clear (shape[i]);
3487       mpz_clear (shape2[i]);
3488     }
3489   return result;
3490 }
3491
3492
3493 /* Check whether a WHERE assignment target or a WHERE mask expression
3494    has the same shape as the outmost WHERE mask expression.  */
3495
3496 static void
3497 resolve_where (gfc_code *code, gfc_expr *mask)
3498 {
3499   gfc_code *cblock;
3500   gfc_code *cnext;
3501   gfc_expr *e = NULL;
3502
3503   cblock = code->block;
3504
3505   /* Store the first WHERE mask-expr of the WHERE statement or construct.
3506      In case of nested WHERE, only the outmost one is stored.  */
3507   if (mask == NULL) /* outmost WHERE */
3508     e = cblock->expr;
3509   else /* inner WHERE */
3510     e = mask;
3511
3512   while (cblock)
3513     {
3514       if (cblock->expr)
3515         {
3516           /* Check if the mask-expr has a consistent shape with the
3517              outmost WHERE mask-expr.  */
3518           if (resolve_where_shape (cblock->expr, e) == FAILURE)
3519             gfc_error ("WHERE mask at %L has inconsistent shape",
3520                        &cblock->expr->where);
3521          }
3522
3523       /* the assignment statement of a WHERE statement, or the first
3524          statement in where-body-construct of a WHERE construct */
3525       cnext = cblock->next;
3526       while (cnext)
3527         {
3528           switch (cnext->op)
3529             {
3530             /* WHERE assignment statement */
3531             case EXEC_ASSIGN:
3532
3533               /* Check shape consistent for WHERE assignment target.  */
3534               if (e && resolve_where_shape (cnext->expr, e) == FAILURE)
3535                gfc_error ("WHERE assignment target at %L has "
3536                           "inconsistent shape", &cnext->expr->where);
3537               break;
3538
3539             /* WHERE or WHERE construct is part of a where-body-construct */
3540             case EXEC_WHERE:
3541               resolve_where (cnext, e);
3542               break;
3543
3544             default:
3545               gfc_error ("Unsupported statement inside WHERE at %L",
3546                          &cnext->loc);
3547             }
3548          /* the next statement within the same where-body-construct */
3549          cnext = cnext->next;
3550        }
3551     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
3552     cblock = cblock->block;
3553   }
3554 }
3555
3556
3557 /* Check whether the FORALL index appears in the expression or not.  */
3558
3559 static try
3560 gfc_find_forall_index (gfc_expr *expr, gfc_symbol *symbol)
3561 {
3562   gfc_array_ref ar;
3563   gfc_ref *tmp;
3564   gfc_actual_arglist *args;
3565   int i;
3566
3567   switch (expr->expr_type)
3568     {
3569     case EXPR_VARIABLE:
3570       gcc_assert (expr->symtree->n.sym);
3571
3572       /* A scalar assignment  */
3573       if (!expr->ref)
3574         {
3575           if (expr->symtree->n.sym == symbol)
3576             return SUCCESS;
3577           else
3578             return FAILURE;
3579         }
3580
3581       /* the expr is array ref, substring or struct component.  */
3582       tmp = expr->ref;
3583       while (tmp != NULL)
3584         {
3585           switch (tmp->type)
3586             {
3587             case  REF_ARRAY:
3588               /* Check if the symbol appears in the array subscript.  */
3589               ar = tmp->u.ar;
3590               for (i = 0; i < GFC_MAX_DIMENSIONS; i++)
3591                 {
3592                   if (ar.start[i])
3593                     if (gfc_find_forall_index (ar.start[i], symbol) == SUCCESS)
3594                       return SUCCESS;
3595
3596                   if (ar.end[i])
3597                     if (gfc_find_forall_index (ar.end[i], symbol) == SUCCESS)
3598                       return SUCCESS;
3599
3600                   if (ar.stride[i])
3601                     if (gfc_find_forall_index (ar.stride[i], symbol) == SUCCESS)
3602                       return SUCCESS;
3603                 }  /* end for  */
3604               break;
3605
3606             case REF_SUBSTRING:
3607               if (expr->symtree->n.sym == symbol)
3608                 return SUCCESS;
3609               tmp = expr->ref;
3610               /* Check if the symbol appears in the substring section.  */
3611               if (gfc_find_forall_index (tmp->u.ss.start, symbol) == SUCCESS)
3612                 return SUCCESS;
3613               if (gfc_find_forall_index (tmp->u.ss.end, symbol) == SUCCESS)
3614                 return SUCCESS;
3615               break;
3616
3617             case REF_COMPONENT:
3618               break;
3619
3620             default:
3621               gfc_error("expresion reference type error at %L", &expr->where);
3622             }
3623           tmp = tmp->next;
3624         }
3625       break;
3626
3627     /* If the expression is a function call, then check if the symbol
3628        appears in the actual arglist of the function.  */
3629     case EXPR_FUNCTION:
3630       for (args = expr->value.function.actual; args; args = args->next)
3631         {
3632           if (gfc_find_forall_index(args->expr,symbol) == SUCCESS)
3633             return SUCCESS;
3634         }
3635       break;
3636
3637     /* It seems not to happen.  */
3638     case EXPR_SUBSTRING:
3639       if (expr->ref)
3640         {
3641           tmp = expr->ref;
3642           gcc_assert (expr->ref->type == REF_SUBSTRING);
3643           if (gfc_find_forall_index (tmp->u.ss.start, symbol) == SUCCESS)
3644             return SUCCESS;
3645           if (gfc_find_forall_index (tmp->u.ss.end, symbol) == SUCCESS)
3646             return SUCCESS;
3647         }
3648       break;
3649
3650     /* It seems not to happen.  */
3651     case EXPR_STRUCTURE:
3652     case EXPR_ARRAY:
3653       gfc_error ("Unsupported statement while finding forall index in "
3654                  "expression");
3655       break;
3656
3657     case EXPR_OP:
3658       /* Find the FORALL index in the first operand.  */
3659       if (expr->value.op.op1)
3660         {
3661           if (gfc_find_forall_index (expr->value.op.op1, symbol) == SUCCESS)
3662             return SUCCESS;
3663         }
3664
3665       /* Find the FORALL index in the second operand.  */
3666       if (expr->value.op.op2)
3667         {
3668           if (gfc_find_forall_index (expr->value.op.op2, symbol) == SUCCESS)
3669             return SUCCESS;
3670         }
3671       break;
3672
3673     default:
3674       break;
3675     }
3676
3677   return FAILURE;
3678 }
3679
3680
3681 /* Resolve assignment in FORALL construct.
3682    NVAR is the number of FORALL index variables, and VAR_EXPR records the
3683    FORALL index variables.  */
3684
3685 static void
3686 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
3687 {
3688   int n;
3689
3690   for (n = 0; n < nvar; n++)
3691     {
3692       gfc_symbol *forall_index;
3693
3694       forall_index = var_expr[n]->symtree->n.sym;
3695
3696       /* Check whether the assignment target is one of the FORALL index
3697          variable.  */
3698       if ((code->expr->expr_type == EXPR_VARIABLE)
3699           && (code->expr->symtree->n.sym == forall_index))
3700         gfc_error ("Assignment to a FORALL index variable at %L",
3701                    &code->expr->where);
3702       else
3703         {
3704           /* If one of the FORALL index variables doesn't appear in the
3705              assignment target, then there will be a many-to-one
3706              assignment.  */
3707           if (gfc_find_forall_index (code->expr, forall_index) == FAILURE)
3708             gfc_error ("The FORALL with index '%s' cause more than one "
3709                        "assignment to this object at %L",
3710                        var_expr[n]->symtree->name, &code->expr->where);
3711         }
3712     }
3713 }
3714
3715
3716 /* Resolve WHERE statement in FORALL construct.  */
3717
3718 static void
3719 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr){
3720   gfc_code *cblock;
3721   gfc_code *cnext;
3722
3723   cblock = code->block;
3724   while (cblock)
3725     {
3726       /* the assignment statement of a WHERE statement, or the first
3727          statement in where-body-construct of a WHERE construct */
3728       cnext = cblock->next;
3729       while (cnext)
3730         {
3731           switch (cnext->op)
3732             {
3733             /* WHERE assignment statement */
3734             case EXEC_ASSIGN:
3735               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
3736               break;
3737
3738             /* WHERE or WHERE construct is part of a where-body-construct */
3739             case EXEC_WHERE:
3740               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
3741               break;
3742
3743             default:
3744               gfc_error ("Unsupported statement inside WHERE at %L",
3745                          &cnext->loc);
3746             }
3747           /* the next statement within the same where-body-construct */
3748           cnext = cnext->next;
3749         }
3750       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
3751       cblock = cblock->block;
3752     }
3753 }
3754
3755
3756 /* Traverse the FORALL body to check whether the following errors exist:
3757    1. For assignment, check if a many-to-one assignment happens.
3758    2. For WHERE statement, check the WHERE body to see if there is any
3759       many-to-one assignment.  */
3760
3761 static void
3762 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
3763 {
3764   gfc_code *c;
3765
3766   c = code->block->next;
3767   while (c)
3768     {
3769       switch (c->op)
3770         {
3771         case EXEC_ASSIGN:
3772         case EXEC_POINTER_ASSIGN:
3773           gfc_resolve_assign_in_forall (c, nvar, var_expr);
3774           break;
3775
3776         /* Because the resolve_blocks() will handle the nested FORALL,
3777            there is no need to handle it here.  */
3778         case EXEC_FORALL:
3779           break;
3780         case EXEC_WHERE:
3781           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
3782           break;
3783         default:
3784           break;
3785         }
3786       /* The next statement in the FORALL body.  */
3787       c = c->next;
3788     }
3789 }
3790
3791
3792 /* Given a FORALL construct, first resolve the FORALL iterator, then call
3793    gfc_resolve_forall_body to resolve the FORALL body.  */
3794
3795 static void resolve_blocks (gfc_code *, gfc_namespace *);
3796
3797 static void
3798 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
3799 {
3800   static gfc_expr **var_expr;
3801   static int total_var = 0;
3802   static int nvar = 0;
3803   gfc_forall_iterator *fa;
3804   gfc_symbol *forall_index;
3805   gfc_code *next;
3806   int i;
3807
3808   /* Start to resolve a FORALL construct   */
3809   if (forall_save == 0)
3810     {
3811       /* Count the total number of FORALL index in the nested FORALL
3812          construct in order to allocate the VAR_EXPR with proper size.  */
3813       next = code;
3814       while ((next != NULL) && (next->op == EXEC_FORALL))
3815         {
3816           for (fa = next->ext.forall_iterator; fa; fa = fa->next)
3817             total_var ++;
3818           next = next->block->next;
3819         }
3820
3821       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
3822       var_expr = (gfc_expr **) gfc_getmem (total_var * sizeof (gfc_expr *));
3823     }
3824
3825   /* The information about FORALL iterator, including FORALL index start, end
3826      and stride. The FORALL index can not appear in start, end or stride.  */
3827   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
3828     {
3829       /* Check if any outer FORALL index name is the same as the current
3830          one.  */
3831       for (i = 0; i < nvar; i++)
3832         {
3833           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
3834             {
3835               gfc_error ("An outer FORALL construct already has an index "
3836                          "with this name %L", &fa->var->where);
3837             }
3838         }
3839
3840       /* Record the current FORALL index.  */
3841       var_expr[nvar] = gfc_copy_expr (fa->var);
3842
3843       forall_index = fa->var->symtree->n.sym;
3844
3845       /* Check if the FORALL index appears in start, end or stride.  */
3846       if (gfc_find_forall_index (fa->start, forall_index) == SUCCESS)
3847         gfc_error ("A FORALL index must not appear in a limit or stride "
3848                    "expression in the same FORALL at %L", &fa->start->where);
3849       if (gfc_find_forall_index (fa->end, forall_index) == SUCCESS)
3850         gfc_error ("A FORALL index must not appear in a limit or stride "
3851                    "expression in the same FORALL at %L", &fa->end->where);
3852       if (gfc_find_forall_index (fa->stride, forall_index) == SUCCESS)
3853         gfc_error ("A FORALL index must not appear in a limit or stride "
3854                    "expression in the same FORALL at %L", &fa->stride->where);
3855       nvar++;
3856     }
3857
3858   /* Resolve the FORALL body.  */
3859   gfc_resolve_forall_body (code, nvar, var_expr);
3860
3861   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
3862   resolve_blocks (code->block, ns);
3863
3864   /* Free VAR_EXPR after the whole FORALL construct resolved.  */
3865   for (i = 0; i < total_var; i++)
3866     gfc_free_expr (var_expr[i]);
3867
3868   /* Reset the counters.  */
3869   total_var = 0;
3870   nvar = 0;
3871 }
3872
3873
3874 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL ,GOTO and
3875    DO code nodes.  */
3876
3877 static void resolve_code (gfc_code *, gfc_namespace *);
3878
3879 static void
3880 resolve_blocks (gfc_code * b, gfc_namespace * ns)
3881 {
3882   try t;
3883
3884   for (; b; b = b->block)
3885     {
3886       t = gfc_resolve_expr (b->expr);
3887       if (gfc_resolve_expr (b->expr2) == FAILURE)
3888         t = FAILURE;
3889
3890       switch (b->op)
3891         {
3892         case EXEC_IF:
3893           if (t == SUCCESS && b->expr != NULL
3894               && (b->expr->ts.type != BT_LOGICAL || b->expr->rank != 0))
3895             gfc_error
3896               ("ELSE IF clause at %L requires a scalar LOGICAL expression",
3897                &b->expr->where);
3898           break;
3899
3900         case EXEC_WHERE:
3901           if (t == SUCCESS
3902               && b->expr != NULL
3903               && (b->expr->ts.type != BT_LOGICAL
3904                   || b->expr->rank == 0))
3905             gfc_error
3906               ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
3907                &b->expr->where);
3908           break;
3909
3910         case EXEC_GOTO:
3911           resolve_branch (b->label, b);
3912           break;
3913
3914         case EXEC_SELECT:
3915         case EXEC_FORALL:
3916         case EXEC_DO:
3917         case EXEC_DO_WHILE:
3918         case EXEC_READ:
3919         case EXEC_WRITE:
3920         case EXEC_IOLENGTH:
3921           break;
3922
3923         default:
3924           gfc_internal_error ("resolve_block(): Bad block type");
3925         }
3926
3927       resolve_code (b->next, ns);
3928     }
3929 }
3930
3931
3932 /* Given a block of code, recursively resolve everything pointed to by this
3933    code block.  */
3934
3935 static void
3936 resolve_code (gfc_code * code, gfc_namespace * ns)
3937 {
3938   int forall_save = 0;
3939   code_stack frame;
3940   gfc_alloc *a;
3941   try t;
3942
3943   frame.prev = cs_base;
3944   frame.head = code;
3945   cs_base = &frame;
3946
3947   for (; code; code = code->next)
3948     {
3949       frame.current = code;
3950
3951       if (code->op == EXEC_FORALL)
3952         {
3953           forall_save = forall_flag;
3954           forall_flag = 1;
3955           gfc_resolve_forall (code, ns, forall_save);
3956         }
3957       else
3958         resolve_blocks (code->block, ns);
3959
3960       if (code->op == EXEC_FORALL)
3961         forall_flag = forall_save;
3962
3963       t = gfc_resolve_expr (code->expr);
3964       if (gfc_resolve_expr (code->expr2) == FAILURE)
3965         t = FAILURE;
3966
3967       switch (code->op)
3968         {
3969         case EXEC_NOP:
3970         case EXEC_CYCLE:
3971         case EXEC_PAUSE:
3972         case EXEC_STOP:
3973         case EXEC_EXIT:
3974         case EXEC_CONTINUE:
3975         case EXEC_DT_END:
3976         case EXEC_ENTRY:
3977           break;
3978
3979         case EXEC_WHERE:
3980           resolve_where (code, NULL);
3981           break;
3982
3983         case EXEC_GOTO:
3984           if (code->expr != NULL)
3985             {
3986               if (code->expr->ts.type != BT_INTEGER)
3987                 gfc_error ("ASSIGNED GOTO statement at %L requires an INTEGER "
3988                        "variable", &code->expr->where);
3989               else if (code->expr->symtree->n.sym->attr.assign != 1)
3990                 gfc_error ("Variable '%s' has not been assigned a target label "
3991                         "at %L", code->expr->symtree->n.sym->name,
3992                         &code->expr->where);
3993             }
3994           else
3995             resolve_branch (code->label, code);
3996           break;
3997
3998         case EXEC_RETURN:
3999           if (code->expr != NULL && code->expr->ts.type != BT_INTEGER)
4000             gfc_error ("Alternate RETURN statement at %L requires an INTEGER "
4001                        "return specifier", &code->expr->where);
4002           break;
4003
4004         case EXEC_ASSIGN:
4005           if (t == FAILURE)
4006             break;
4007
4008           if (gfc_extend_assign (code, ns) == SUCCESS)
4009             goto call;
4010
4011           if (gfc_pure (NULL))
4012             {
4013               if (gfc_impure_variable (code->expr->symtree->n.sym))
4014                 {
4015                   gfc_error
4016                     ("Cannot assign to variable '%s' in PURE procedure at %L",
4017                      code->expr->symtree->n.sym->name, &code->expr->where);
4018                   break;
4019                 }
4020
4021               if (code->expr2->ts.type == BT_DERIVED
4022                   && derived_pointer (code->expr2->ts.derived))
4023                 {
4024                   gfc_error
4025                     ("Right side of assignment at %L is a derived type "
4026                      "containing a POINTER in a PURE procedure",
4027                      &code->expr2->where);
4028                   break;
4029                 }
4030             }
4031
4032           gfc_check_assign (code->expr, code->expr2, 1);
4033           break;
4034
4035         case EXEC_LABEL_ASSIGN:
4036           if (code->label->defined == ST_LABEL_UNKNOWN)
4037             gfc_error ("Label %d referenced at %L is never defined",
4038                        code->label->value, &code->label->where);
4039           if (t == SUCCESS
4040               && (code->expr->expr_type != EXPR_VARIABLE
4041                   || code->expr->symtree->n.sym->ts.type != BT_INTEGER
4042                   || code->expr->symtree->n.sym->ts.kind 
4043                         != gfc_default_integer_kind
4044                   || code->expr->symtree->n.sym->as != NULL))
4045             gfc_error ("ASSIGN statement at %L requires a scalar "
4046                        "default INTEGER variable", &code->expr->where);
4047           break;
4048
4049         case EXEC_POINTER_ASSIGN:
4050           if (t == FAILURE)
4051             break;
4052
4053           gfc_check_pointer_assign (code->expr, code->expr2);
4054           break;
4055
4056         case EXEC_ARITHMETIC_IF:
4057           if (t == SUCCESS
4058               && code->expr->ts.type != BT_INTEGER
4059               && code->expr->ts.type != BT_REAL)
4060             gfc_error ("Arithmetic IF statement at %L requires a numeric "
4061                        "expression", &code->expr->where);
4062
4063           resolve_branch (code->label, code);
4064           resolve_branch (code->label2, code);
4065           resolve_branch (code->label3, code);
4066           break;
4067
4068         case EXEC_IF:
4069           if (t == SUCCESS && code->expr != NULL
4070               && (code->expr->ts.type != BT_LOGICAL
4071                   || code->expr->rank != 0))
4072             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
4073                        &code->expr->where);
4074           break;
4075
4076         case EXEC_CALL:
4077         call:
4078           resolve_call (code);
4079           break;
4080
4081         case EXEC_SELECT:
4082           /* Select is complicated. Also, a SELECT construct could be
4083              a transformed computed GOTO.  */
4084           resolve_select (code);
4085           break;
4086
4087         case EXEC_DO:
4088           if (code->ext.iterator != NULL)
4089             gfc_resolve_iterator (code->ext.iterator, true);
4090           break;
4091
4092         case EXEC_DO_WHILE:
4093           if (code->expr == NULL)
4094             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
4095           if (t == SUCCESS
4096               && (code->expr->rank != 0
4097                   || code->expr->ts.type != BT_LOGICAL))
4098             gfc_error ("Exit condition of DO WHILE loop at %L must be "
4099                        "a scalar LOGICAL expression", &code->expr->where);
4100           break;
4101
4102         case EXEC_ALLOCATE:
4103           if (t == SUCCESS && code->expr != NULL
4104               && code->expr->ts.type != BT_INTEGER)
4105             gfc_error ("STAT tag in ALLOCATE statement at %L must be "
4106                        "of type INTEGER", &code->expr->where);
4107
4108           for (a = code->ext.alloc_list; a; a = a->next)
4109             resolve_allocate_expr (a->expr, code);
4110
4111           break;
4112
4113         case EXEC_DEALLOCATE:
4114           if (t == SUCCESS && code->expr != NULL
4115               && code->expr->ts.type != BT_INTEGER)
4116             gfc_error
4117               ("STAT tag in DEALLOCATE statement at %L must be of type "
4118                "INTEGER", &code->expr->where);
4119
4120           for (a = code->ext.alloc_list; a; a = a->next)
4121             resolve_deallocate_expr (a->expr);
4122
4123           break;
4124
4125         case EXEC_OPEN:
4126           if (gfc_resolve_open (code->ext.open) == FAILURE)
4127             break;
4128
4129           resolve_branch (code->ext.open->err, code);
4130           break;
4131
4132         case EXEC_CLOSE:
4133           if (gfc_resolve_close (code->ext.close) == FAILURE)
4134             break;
4135
4136           resolve_branch (code->ext.close->err, code);
4137           break;
4138
4139         case EXEC_BACKSPACE:
4140         case EXEC_ENDFILE:
4141         case EXEC_REWIND:
4142         case EXEC_FLUSH:
4143           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
4144             break;
4145
4146           resolve_branch (code->ext.filepos->err, code);
4147           break;
4148
4149         case EXEC_INQUIRE:
4150           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
4151               break;
4152
4153           resolve_branch (code->ext.inquire->err, code);
4154           break;
4155
4156         case EXEC_IOLENGTH:
4157           gcc_assert (code->ext.inquire != NULL);
4158           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
4159             break;
4160
4161           resolve_branch (code->ext.inquire->err, code);
4162           break;
4163
4164         case EXEC_READ:
4165         case EXEC_WRITE:
4166           if (gfc_resolve_dt (code->ext.dt) == FAILURE)
4167             break;
4168
4169           resolve_branch (code->ext.dt->err, code);
4170           resolve_branch (code->ext.dt->end, code);
4171           resolve_branch (code->ext.dt->eor, code);
4172           break;
4173
4174         case EXEC_TRANSFER:
4175           resolve_transfer (code);
4176           break;
4177
4178         case EXEC_FORALL:
4179           resolve_forall_iterators (code->ext.forall_iterator);
4180
4181           if (code->expr != NULL && code->expr->ts.type != BT_LOGICAL)
4182             gfc_error
4183               ("FORALL mask clause at %L requires a LOGICAL expression",
4184                &code->expr->where);
4185           break;
4186
4187         default:
4188           gfc_internal_error ("resolve_code(): Bad statement code");
4189         }
4190     }
4191
4192   cs_base = frame.prev;
4193 }
4194
4195
4196 /* Resolve initial values and make sure they are compatible with
4197    the variable.  */
4198
4199 static void
4200 resolve_values (gfc_symbol * sym)
4201 {
4202
4203   if (sym->value == NULL)
4204     return;
4205
4206   if (gfc_resolve_expr (sym->value) == FAILURE)
4207     return;
4208
4209   gfc_check_assign_symbol (sym, sym->value);
4210 }
4211
4212
4213 /* Do anything necessary to resolve a symbol.  Right now, we just
4214    assume that an otherwise unknown symbol is a variable.  This sort
4215    of thing commonly happens for symbols in module.  */
4216
4217 static void
4218 resolve_symbol (gfc_symbol * sym)
4219 {
4220   /* Zero if we are checking a formal namespace.  */
4221   static int formal_ns_flag = 1;
4222   int formal_ns_save, check_constant, mp_flag;
4223   int i, flag;
4224   gfc_namelist *nl;
4225   gfc_symtree * symtree;
4226   gfc_symtree * this_symtree;
4227   gfc_namespace * ns;
4228   gfc_component * c;
4229   gfc_formal_arglist * arg;
4230
4231   if (sym->attr.flavor == FL_UNKNOWN)
4232     {
4233
4234     /* If we find that a flavorless symbol is an interface in one of the
4235        parent namespaces, find its symtree in this namespace, free the
4236        symbol and set the symtree to point to the interface symbol.  */
4237       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
4238         {
4239           symtree = gfc_find_symtree (ns->sym_root, sym->name);
4240           if (symtree && symtree->n.sym->generic)
4241             {
4242               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
4243                                                sym->name);
4244               sym->refs--;
4245               if (!sym->refs)
4246                 gfc_free_symbol (sym);
4247               symtree->n.sym->refs++;
4248               this_symtree->n.sym = symtree->n.sym;
4249               return;
4250             }
4251         }
4252
4253       /* Otherwise give it a flavor according to such attributes as
4254          it has.  */
4255       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
4256         sym->attr.flavor = FL_VARIABLE;
4257       else
4258         {
4259           sym->attr.flavor = FL_PROCEDURE;
4260           if (sym->attr.dimension)
4261             sym->attr.function = 1;
4262         }
4263     }
4264
4265   /* Symbols that are module procedures with results (functions) have
4266      the types and array specification copied for type checking in
4267      procedures that call them, as well as for saving to a module
4268      file.  These symbols can't stand the scrutiny that their results
4269      can.  */
4270   mp_flag = (sym->result != NULL && sym->result != sym);
4271
4272   /* Assign default type to symbols that need one and don't have one.  */
4273   if (sym->ts.type == BT_UNKNOWN)
4274     {
4275       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
4276         gfc_set_default_type (sym, 1, NULL);
4277
4278       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
4279         {
4280           /* The specific case of an external procedure should emit an error
4281              in the case that there is no implicit type.  */
4282           if (!mp_flag)
4283             gfc_set_default_type (sym, sym->attr.external, NULL);
4284           else
4285             {
4286               /* Result may be in another namespace.  */
4287               resolve_symbol (sym->result);
4288
4289               sym->ts = sym->result->ts;
4290               sym->as = gfc_copy_array_spec (sym->result->as);
4291               sym->attr.dimension = sym->result->attr.dimension;
4292               sym->attr.pointer = sym->result->attr.pointer;
4293             }
4294         }
4295     }
4296
4297   /* Assumed size arrays and assumed shape arrays must be dummy
4298      arguments.  */ 
4299
4300   if (sym->as != NULL
4301       && (sym->as->type == AS_ASSUMED_SIZE
4302           || sym->as->type == AS_ASSUMED_SHAPE)
4303       && sym->attr.dummy == 0)
4304     {
4305       if (sym->as->type == AS_ASSUMED_SIZE)
4306         gfc_error ("Assumed size array at %L must be a dummy argument",
4307                    &sym->declared_at);
4308       else
4309         gfc_error ("Assumed shape array at %L must be a dummy argument",
4310                    &sym->declared_at);
4311       return;
4312     }
4313
4314   /* A parameter array's shape needs to be constant.  */
4315
4316   if (sym->attr.flavor == FL_PARAMETER && sym->as != NULL 
4317       && !gfc_is_compile_time_shape (sym->as))
4318     {
4319       gfc_error ("Parameter array '%s' at %L cannot be automatic "
4320                  "or assumed shape", sym->name, &sym->declared_at);
4321           return;
4322     }
4323
4324   /* A module array's shape needs to be constant.  */
4325
4326   if (sym->ns->proc_name
4327       && sym->attr.flavor == FL_VARIABLE
4328       && sym->ns->proc_name->attr.flavor == FL_MODULE
4329       && !sym->attr.use_assoc
4330       && !sym->attr.allocatable
4331       && !sym->attr.pointer
4332       && sym->as != NULL
4333       && !gfc_is_compile_time_shape (sym->as))
4334     {
4335       gfc_error ("Module array '%s' at %L cannot be automatic "
4336          "or assumed shape", sym->name, &sym->declared_at);
4337       return;
4338     }
4339
4340   /* Make sure that character string variables with assumed length are
4341      dummy arguments.  */
4342
4343   if (sym->attr.flavor == FL_VARIABLE && !sym->attr.result
4344       && sym->ts.type == BT_CHARACTER
4345       && sym->ts.cl->length == NULL && sym->attr.dummy == 0)
4346     {
4347       gfc_error ("Entity with assumed character length at %L must be a "
4348                  "dummy argument or a PARAMETER", &sym->declared_at);
4349       return;
4350     }
4351
4352   /* Make sure a parameter that has been implicitly typed still
4353      matches the implicit type, since PARAMETER statements can precede
4354      IMPLICIT statements.  */
4355
4356   if (sym->attr.flavor == FL_PARAMETER
4357       && sym->attr.implicit_type
4358       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym, sym->ns)))
4359     gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
4360                "later IMPLICIT type", sym->name, &sym->declared_at);
4361
4362   /* Make sure the types of derived parameters are consistent.  This
4363      type checking is deferred until resolution because the type may
4364      refer to a derived type from the host.  */
4365
4366   if (sym->attr.flavor == FL_PARAMETER
4367       && sym->ts.type == BT_DERIVED
4368       && !gfc_compare_types (&sym->ts, &sym->value->ts))
4369     gfc_error ("Incompatible derived type in PARAMETER at %L",
4370                &sym->value->where);
4371
4372   /* Make sure symbols with known intent or optional are really dummy
4373      variable.  Because of ENTRY statement, this has to be deferred
4374      until resolution time.  */
4375
4376   if (! sym->attr.dummy
4377       && (sym->attr.optional
4378           || sym->attr.intent != INTENT_UNKNOWN))
4379     {
4380       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
4381       return;
4382     }
4383
4384   if (sym->attr.proc == PROC_ST_FUNCTION)
4385     {
4386       if (sym->ts.type == BT_CHARACTER)
4387         {
4388           gfc_charlen *cl = sym->ts.cl;
4389           if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
4390             {
4391               gfc_error ("Character-valued statement function '%s' at %L must "
4392                          "have constant length", sym->name, &sym->declared_at);
4393               return;
4394             }
4395         }
4396     }
4397
4398   /* If a derived type symbol has reached this point, without its
4399      type being declared, we have an error.  Notice that most
4400      conditions that produce undefined derived types have already
4401      been dealt with.  However, the likes of:
4402      implicit type(t) (t) ..... call foo (t) will get us here if
4403      the type is not declared in the scope of the implicit
4404      statement. Change the type to BT_UNKNOWN, both because it is so
4405      and to prevent an ICE.  */
4406   if (sym->ts.type == BT_DERIVED
4407         && sym->ts.derived->components == NULL)
4408     {
4409       gfc_error ("The derived type '%s' at %L is of type '%s', "
4410                  "which has not been defined.", sym->name,
4411                   &sym->declared_at, sym->ts.derived->name);
4412       sym->ts.type = BT_UNKNOWN;
4413       return;
4414     }
4415
4416   /* If a component of a derived type is of a type declared to be private,
4417      either the derived type definition must contain the PRIVATE statement,
4418      or the derived type must be private.  (4.4.1 just after R427) */
4419   if (sym->attr.flavor == FL_DERIVED
4420         && sym->component_access != ACCESS_PRIVATE
4421         && gfc_check_access(sym->attr.access, sym->ns->default_access))
4422     {
4423       for (c = sym->components; c; c = c->next)
4424         {
4425           if (c->ts.type == BT_DERIVED
4426                 && !c->ts.derived->attr.use_assoc
4427                 && !gfc_check_access(c->ts.derived->attr.access,
4428                                      c->ts.derived->ns->default_access))
4429             {
4430               gfc_error ("The component '%s' is a PRIVATE type and cannot be "
4431                          "a component of '%s', which is PUBLIC at %L",
4432                          c->name, sym->name, &sym->declared_at);
4433               return;
4434             }
4435         }
4436     }
4437
4438   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
4439      default initialization is defined (5.1.2.4.4).  */
4440   if (sym->ts.type == BT_DERIVED
4441         && sym->attr.dummy
4442         && sym->attr.intent == INTENT_OUT
4443         && sym->as
4444         && sym->as->type == AS_ASSUMED_SIZE)
4445     {
4446       for (c = sym->ts.derived->components; c; c = c->next)
4447         {
4448           if (c->initializer)
4449             {
4450               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
4451                          "ASSUMED SIZE and so cannot have a default initializer",
4452                          sym->name, &sym->declared_at);
4453               return;
4454             }
4455         }
4456     }
4457
4458
4459   /* Ensure that derived type formal arguments of a public procedure
4460      are not of a private type.  */
4461   if (sym->attr.flavor == FL_PROCEDURE
4462         && gfc_check_access(sym->attr.access, sym->ns->default_access))
4463     {
4464       for (arg = sym->formal; arg; arg = arg->next)
4465         {
4466           if (arg->sym
4467                 && arg->sym->ts.type == BT_DERIVED
4468                 && !arg->sym->ts.derived->attr.use_assoc
4469                 && !gfc_check_access(arg->sym->ts.derived->attr.access,
4470                                      arg->sym->ts.derived->ns->default_access))
4471             {
4472               gfc_error_now ("'%s' is a PRIVATE type and cannot be "
4473                              "a dummy argument of '%s', which is PUBLIC at %L",
4474                              arg->sym->name, sym->name, &sym->declared_at);
4475               /* Stop this message from recurring.  */
4476               arg->sym->ts.derived->attr.access = ACCESS_PUBLIC;
4477               return;
4478             }
4479         }
4480     }
4481
4482   /* Constraints on deferred shape variable.  */
4483   if (sym->attr.flavor == FL_VARIABLE
4484       || (sym->attr.flavor == FL_PROCEDURE
4485           && sym->attr.function))
4486     {
4487       if (sym->as == NULL || sym->as->type != AS_DEFERRED)
4488         {
4489           if (sym->attr.allocatable)
4490             {
4491               if (sym->attr.dimension)
4492                 gfc_error ("Allocatable array '%s' at %L must have "
4493                            "a deferred shape", sym->name, &sym->declared_at);
4494               else
4495                 gfc_error ("Scalar object '%s' at %L may not be ALLOCATABLE",
4496                            sym->name, &sym->declared_at);
4497               return;
4498             }
4499
4500           if (sym->attr.pointer && sym->attr.dimension)
4501             {
4502               gfc_error ("Array pointer '%s' at %L must have a deferred shape",
4503                          sym->name, &sym->declared_at);
4504               return;
4505             }
4506
4507         }
4508       else
4509         {
4510           if (!mp_flag && !sym->attr.allocatable
4511               && !sym->attr.pointer && !sym->attr.dummy)
4512             {
4513               gfc_error ("Array '%s' at %L cannot have a deferred shape",
4514                          sym->name, &sym->declared_at);
4515               return;
4516             }
4517         }
4518     }
4519
4520   switch (sym->attr.flavor)
4521     {
4522     case FL_VARIABLE:
4523       /* Can the symbol have an initializer?  */
4524       flag = 0;
4525       if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
4526           || sym->attr.intrinsic || sym->attr.result)
4527         flag = 1;
4528       else if (sym->attr.dimension && !sym->attr.pointer)
4529         {
4530           /* Don't allow initialization of automatic arrays.  */
4531           for (i = 0; i < sym->as->rank; i++)
4532             {
4533               if (sym->as->lower[i] == NULL
4534                   || sym->as->lower[i]->expr_type != EXPR_CONSTANT
4535                   || sym->as->upper[i] == NULL
4536                   || sym->as->upper[i]->expr_type != EXPR_CONSTANT)
4537                 {
4538                   flag = 1;
4539                   break;
4540                 }
4541             }
4542         }
4543
4544       /* Reject illegal initializers.  */
4545       if (sym->value && flag)
4546         {
4547           if (sym->attr.allocatable)
4548             gfc_error ("Allocatable '%s' at %L cannot have an initializer",
4549                        sym->name, &sym->declared_at);
4550           else if (sym->attr.external)
4551             gfc_error ("External '%s' at %L cannot have an initializer",
4552                        sym->name, &sym->declared_at);
4553           else if (sym->attr.dummy)
4554             gfc_error ("Dummy '%s' at %L cannot have an initializer",
4555                        sym->name, &sym->declared_at);
4556           else if (sym->attr.intrinsic)
4557             gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
4558                        sym->name, &sym->declared_at);
4559           else if (sym->attr.result)
4560             gfc_error ("Function result '%s' at %L cannot have an initializer",
4561                        sym->name, &sym->declared_at);
4562           else
4563             gfc_error ("Automatic array '%s' at %L cannot have an initializer",
4564                        sym->name, &sym->declared_at);
4565           return;
4566         }
4567
4568       /* Assign default initializer.  */
4569       if (sym->ts.type == BT_DERIVED && !(sym->value || flag)
4570           && !sym->attr.pointer)
4571         sym->value = gfc_default_initializer (&sym->ts);
4572       break;
4573
4574     case FL_NAMELIST:
4575       /* Reject PRIVATE objects in a PUBLIC namelist.  */
4576       if (gfc_check_access(sym->attr.access, sym->ns->default_access))
4577         {
4578           for (nl = sym->namelist; nl; nl = nl->next)
4579             {
4580               if (!nl->sym->attr.use_assoc
4581                     &&
4582                   !(sym->ns->parent == nl->sym->ns)
4583                     &&
4584                   !gfc_check_access(nl->sym->attr.access,
4585                                     nl->sym->ns->default_access))
4586                 gfc_error ("PRIVATE symbol '%s' cannot be member of "
4587                            "PUBLIC namelist at %L", nl->sym->name,
4588                            &sym->declared_at);
4589             }
4590         }
4591       break;
4592
4593     default:
4594
4595       /* An external symbol falls through to here if it is not referenced.  */
4596       if (sym->attr.external && sym->value)
4597         {
4598           gfc_error ("External object '%s' at %L may not have an initializer",
4599                      sym->name, &sym->declared_at);
4600           return;
4601         }
4602
4603       break;
4604     }
4605
4606
4607   /* Make sure that intrinsic exist */
4608   if (sym->attr.intrinsic
4609       && ! gfc_intrinsic_name(sym->name, 0)
4610       && ! gfc_intrinsic_name(sym->name, 1))
4611     gfc_error("Intrinsic at %L does not exist", &sym->declared_at);
4612
4613   /* Resolve array specifier. Check as well some constraints
4614      on COMMON blocks.  */
4615
4616   check_constant = sym->attr.in_common && !sym->attr.pointer;
4617   gfc_resolve_array_spec (sym->as, check_constant);
4618
4619   /* Resolve formal namespaces.  */
4620
4621   if (formal_ns_flag && sym != NULL && sym->formal_ns != NULL)
4622     {
4623       formal_ns_save = formal_ns_flag;
4624       formal_ns_flag = 0;
4625       gfc_resolve (sym->formal_ns);
4626       formal_ns_flag = formal_ns_save;
4627     }
4628 }
4629
4630
4631
4632 /************* Resolve DATA statements *************/
4633
4634 static struct
4635 {
4636   gfc_data_value *vnode;
4637   unsigned int left;
4638 }
4639 values;
4640
4641
4642 /* Advance the values structure to point to the next value in the data list.  */
4643
4644 static try
4645 next_data_value (void)
4646 {
4647   while (values.left == 0)
4648     {
4649       if (values.vnode->next == NULL)
4650         return FAILURE;
4651
4652       values.vnode = values.vnode->next;
4653       values.left = values.vnode->repeat;
4654     }
4655
4656   return SUCCESS;
4657 }
4658
4659
4660 static try
4661 check_data_variable (gfc_data_variable * var, locus * where)
4662 {
4663   gfc_expr *e;
4664   mpz_t size;
4665   mpz_t offset;
4666   try t;
4667   ar_type mark = AR_UNKNOWN;
4668   int i;
4669   mpz_t section_index[GFC_MAX_DIMENSIONS];
4670   gfc_ref *ref;
4671   gfc_array_ref *ar;
4672
4673   if (gfc_resolve_expr (var->expr) == FAILURE)
4674     return FAILURE;
4675
4676   ar = NULL;
4677   mpz_init_set_si (offset, 0);
4678   e = var->expr;
4679
4680   if (e->expr_type != EXPR_VARIABLE)
4681     gfc_internal_error ("check_data_variable(): Bad expression");
4682
4683   if (e->rank == 0)
4684     {
4685       mpz_init_set_ui (size, 1);
4686       ref = NULL;
4687     }
4688   else
4689     {
4690       ref = e->ref;
4691
4692       /* Find the array section reference.  */
4693       for (ref = e->ref; ref; ref = ref->next)
4694         {
4695           if (ref->type != REF_ARRAY)
4696             continue;
4697           if (ref->u.ar.type == AR_ELEMENT)
4698             continue;
4699           break;
4700         }
4701       gcc_assert (ref);
4702
4703       /* Set marks according to the reference pattern.  */
4704       switch (ref->u.ar.type)
4705         {
4706         case AR_FULL:
4707           mark = AR_FULL;
4708           break;
4709
4710         case AR_SECTION:
4711           ar = &ref->u.ar;
4712           /* Get the start position of array section.  */
4713           gfc_get_section_index (ar, section_index, &offset);
4714           mark = AR_SECTION;
4715           break;
4716
4717         default:
4718           gcc_unreachable ();
4719         }
4720
4721       if (gfc_array_size (e, &size) == FAILURE)
4722         {
4723           gfc_error ("Nonconstant array section at %L in DATA statement",
4724                      &e->where);
4725           mpz_clear (offset);
4726           return FAILURE;
4727         }
4728     }
4729
4730   t = SUCCESS;
4731
4732   while (mpz_cmp_ui (size, 0) > 0)
4733     {
4734       if (next_data_value () == FAILURE)
4735         {
4736           gfc_error ("DATA statement at %L has more variables than values",
4737                      where);
4738           t = FAILURE;
4739           break;
4740         }
4741
4742       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
4743       if (t == FAILURE)
4744         break;
4745
4746       /* If we have more than one element left in the repeat count,
4747          and we have more than one element left in the target variable,
4748          then create a range assignment.  */
4749       /* ??? Only done for full arrays for now, since array sections
4750          seem tricky.  */
4751       if (mark == AR_FULL && ref && ref->next == NULL
4752           && values.left > 1 && mpz_cmp_ui (size, 1) > 0)
4753         {
4754           mpz_t range;
4755
4756           if (mpz_cmp_ui (size, values.left) >= 0)
4757             {
4758               mpz_init_set_ui (range, values.left);
4759               mpz_sub_ui (size, size, values.left);
4760               values.left = 0;
4761             }
4762           else
4763             {
4764               mpz_init_set (range, size);
4765               values.left -= mpz_get_ui (size);
4766               mpz_set_ui (size, 0);
4767             }
4768
4769           gfc_assign_data_value_range (var->expr, values.vnode->expr,
4770                                        offset, range);
4771
4772           mpz_add (offset, offset, range);
4773           mpz_clear (range);
4774         }
4775
4776       /* Assign initial value to symbol.  */
4777       else
4778         {
4779           values.left -= 1;
4780           mpz_sub_ui (size, size, 1);
4781
4782           gfc_assign_data_value (var->expr, values.vnode->expr, offset);
4783
4784           if (mark == AR_FULL)
4785             mpz_add_ui (offset, offset, 1);
4786
4787           /* Modify the array section indexes and recalculate the offset
4788              for next element.  */
4789           else if (mark == AR_SECTION)
4790             gfc_advance_section (section_index, ar, &offset);
4791         }
4792     }
4793
4794   if (mark == AR_SECTION)
4795     {
4796       for (i = 0; i < ar->dimen; i++)
4797         mpz_clear (section_index[i]);
4798     }
4799
4800   mpz_clear (size);
4801   mpz_clear (offset);
4802
4803   return t;
4804 }
4805
4806
4807 static try traverse_data_var (gfc_data_variable *, locus *);
4808
4809 /* Iterate over a list of elements in a DATA statement.  */
4810
4811 static try
4812 traverse_data_list (gfc_data_variable * var, locus * where)
4813 {
4814   mpz_t trip;
4815   iterator_stack frame;
4816   gfc_expr *e;
4817
4818   mpz_init (frame.value);
4819
4820   mpz_init_set (trip, var->iter.end->value.integer);
4821   mpz_sub (trip, trip, var->iter.start->value.integer);
4822   mpz_add (trip, trip, var->iter.step->value.integer);
4823
4824   mpz_div (trip, trip, var->iter.step->value.integer);
4825
4826   mpz_set (frame.value, var->iter.start->value.integer);
4827
4828   frame.prev = iter_stack;
4829   frame.variable = var->iter.var->symtree;
4830   iter_stack = &frame;
4831
4832   while (mpz_cmp_ui (trip, 0) > 0)
4833     {
4834       if (traverse_data_var (var->list, where) == FAILURE)
4835         {
4836           mpz_clear (trip);
4837           return FAILURE;
4838         }
4839
4840       e = gfc_copy_expr (var->expr);
4841       if (gfc_simplify_expr (e, 1) == FAILURE)
4842         {
4843           gfc_free_expr (e);
4844           return FAILURE;
4845         }
4846
4847       mpz_add (frame.value, frame.value, var->iter.step->value.integer);
4848
4849       mpz_sub_ui (trip, trip, 1);
4850     }
4851
4852   mpz_clear (trip);
4853   mpz_clear (frame.value);
4854
4855   iter_stack = frame.prev;
4856   return SUCCESS;
4857 }
4858
4859
4860 /* Type resolve variables in the variable list of a DATA statement.  */
4861
4862 static try
4863 traverse_data_var (gfc_data_variable * var, locus * where)
4864 {
4865   try t;
4866
4867   for (; var; var = var->next)
4868     {
4869       if (var->expr == NULL)
4870         t = traverse_data_list (var, where);
4871       else
4872         t = check_data_variable (var, where);
4873
4874       if (t == FAILURE)
4875         return FAILURE;
4876     }
4877
4878   return SUCCESS;
4879 }
4880
4881
4882 /* Resolve the expressions and iterators associated with a data statement.
4883    This is separate from the assignment checking because data lists should
4884    only be resolved once.  */
4885
4886 static try
4887 resolve_data_variables (gfc_data_variable * d)
4888 {
4889   for (; d; d = d->next)
4890     {
4891       if (d->list == NULL)
4892         {
4893           if (gfc_resolve_expr (d->expr) == FAILURE)
4894             return FAILURE;
4895         }
4896       else
4897         {
4898           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
4899             return FAILURE;
4900
4901           if (d->iter.start->expr_type != EXPR_CONSTANT
4902               || d->iter.end->expr_type != EXPR_CONSTANT
4903               || d->iter.step->expr_type != EXPR_CONSTANT)
4904             gfc_internal_error ("resolve_data_variables(): Bad iterator");
4905
4906           if (resolve_data_variables (d->list) == FAILURE)
4907             return FAILURE;
4908         }
4909     }
4910
4911   return SUCCESS;
4912 }
4913
4914
4915 /* Resolve a single DATA statement.  We implement this by storing a pointer to
4916    the value list into static variables, and then recursively traversing the
4917    variables list, expanding iterators and such.  */
4918
4919 static void
4920 resolve_data (gfc_data * d)
4921 {
4922   if (resolve_data_variables (d->var) == FAILURE)
4923     return;
4924
4925   values.vnode = d->value;
4926   values.left = (d->value == NULL) ? 0 : d->value->repeat;
4927
4928   if (traverse_data_var (d->var, &d->where) == FAILURE)
4929     return;
4930
4931   /* At this point, we better not have any values left.  */
4932
4933   if (next_data_value () == SUCCESS)
4934     gfc_error ("DATA statement at %L has more values than variables",
4935                &d->where);
4936 }
4937
4938
4939 /* Determines if a variable is not 'pure', ie not assignable within a pure
4940    procedure.  Returns zero if assignment is OK, nonzero if there is a problem.
4941  */
4942
4943 int
4944 gfc_impure_variable (gfc_symbol * sym)
4945 {
4946   if (sym->attr.use_assoc || sym->attr.in_common)
4947     return 1;
4948
4949   if (sym->ns != gfc_current_ns)
4950     return !sym->attr.function;
4951
4952   /* TODO: Check storage association through EQUIVALENCE statements */
4953
4954   return 0;
4955 }
4956
4957
4958 /* Test whether a symbol is pure or not.  For a NULL pointer, checks the
4959    symbol of the current procedure.  */
4960
4961 int
4962 gfc_pure (gfc_symbol * sym)
4963 {
4964   symbol_attribute attr;
4965
4966   if (sym == NULL)
4967     sym = gfc_current_ns->proc_name;
4968   if (sym == NULL)
4969     return 0;
4970
4971   attr = sym->attr;
4972
4973   return attr.flavor == FL_PROCEDURE && (attr.pure || attr.elemental);
4974 }
4975
4976
4977 /* Test whether the current procedure is elemental or not.  */
4978
4979 int
4980 gfc_elemental (gfc_symbol * sym)
4981 {
4982   symbol_attribute attr;
4983
4984   if (sym == NULL)
4985     sym = gfc_current_ns->proc_name;
4986   if (sym == NULL)
4987     return 0;
4988   attr = sym->attr;
4989
4990   return attr.flavor == FL_PROCEDURE && attr.elemental;
4991 }
4992
4993
4994 /* Warn about unused labels.  */
4995
4996 static void
4997 warn_unused_label (gfc_namespace * ns)
4998 {
4999   gfc_st_label *l;
5000
5001   l = ns->st_labels;
5002   if (l == NULL)
5003     return;
5004
5005   while (l->next)
5006     l = l->next;
5007
5008   for (; l; l = l->prev)
5009     {
5010       if (l->defined == ST_LABEL_UNKNOWN)
5011         continue;
5012
5013       switch (l->referenced)
5014         {
5015         case ST_LABEL_UNKNOWN:
5016           gfc_warning ("Label %d at %L defined but not used", l->value,
5017                        &l->where);
5018           break;
5019
5020         case ST_LABEL_BAD_TARGET:
5021           gfc_warning ("Label %d at %L defined but cannot be used", l->value,
5022                        &l->where);
5023           break;
5024
5025         default:
5026           break;
5027         }
5028     }
5029 }
5030
5031
5032 /* Returns the sequence type of a symbol or sequence.  */
5033
5034 static seq_type
5035 sequence_type (gfc_typespec ts)
5036 {
5037   seq_type result;
5038   gfc_component *c;
5039
5040   switch (ts.type)
5041   {
5042     case BT_DERIVED:
5043
5044       if (ts.derived->components == NULL)
5045         return SEQ_NONDEFAULT;
5046
5047       result = sequence_type (ts.derived->components->ts);
5048       for (c = ts.derived->components->next; c; c = c->next)
5049         if (sequence_type (c->ts) != result)
5050           return SEQ_MIXED;
5051
5052       return result;
5053
5054     case BT_CHARACTER:
5055       if (ts.kind != gfc_default_character_kind)
5056           return SEQ_NONDEFAULT;
5057
5058       return SEQ_CHARACTER;
5059
5060     case BT_INTEGER:
5061       if (ts.kind != gfc_default_integer_kind)
5062           return SEQ_NONDEFAULT;
5063
5064       return SEQ_NUMERIC;
5065
5066     case BT_REAL:
5067       if (!(ts.kind == gfc_default_real_kind
5068              || ts.kind == gfc_default_double_kind))
5069           return SEQ_NONDEFAULT;
5070
5071       return SEQ_NUMERIC;
5072
5073     case BT_COMPLEX:
5074       if (ts.kind != gfc_default_complex_kind)
5075           return SEQ_NONDEFAULT;
5076
5077       return SEQ_NUMERIC;
5078
5079     case BT_LOGICAL:
5080       if (ts.kind != gfc_default_logical_kind)
5081           return SEQ_NONDEFAULT;
5082
5083       return SEQ_NUMERIC;
5084
5085     default:
5086       return SEQ_NONDEFAULT;
5087   }
5088 }
5089
5090
5091 /* Resolve derived type EQUIVALENCE object.  */
5092
5093 static try
5094 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
5095 {
5096   gfc_symbol *d;
5097   gfc_component *c = derived->components;
5098
5099   if (!derived)
5100     return SUCCESS;
5101
5102   /* Shall not be an object of nonsequence derived type.  */
5103   if (!derived->attr.sequence)
5104     {
5105       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
5106                  "attribute to be an EQUIVALENCE object", sym->name, &e->where);
5107       return FAILURE;
5108     }
5109
5110   for (; c ; c = c->next)
5111     {
5112       d = c->ts.derived;
5113       if (d && (resolve_equivalence_derived (c->ts.derived, sym, e) == FAILURE))
5114         return FAILURE;
5115         
5116       /* Shall not be an object of sequence derived type containing a pointer
5117          in the structure.  */
5118       if (c->pointer)
5119         {
5120           gfc_error ("Derived type variable '%s' at %L with pointer component(s) "
5121                      "cannot be an EQUIVALENCE object", sym->name, &e->where);
5122           return FAILURE;
5123         }
5124
5125       if (c->initializer)
5126         {
5127           gfc_error ("Derived type variable '%s' at %L with default initializer "
5128                      "cannot be an EQUIVALENCE object", sym->name, &e->where);
5129           return FAILURE;
5130         }
5131     }
5132   return SUCCESS;
5133 }
5134
5135
5136 /* Resolve equivalence object. 
5137    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
5138    an allocatable array, an object of nonsequence derived type, an object of
5139    sequence derived type containing a pointer at any level of component
5140    selection, an automatic object, a function name, an entry name, a result
5141    name, a named constant, a structure component, or a subobject of any of
5142    the preceding objects.  A substring shall not have length zero.  A
5143    derived type shall not have components with default initialization nor
5144    shall two objects of an equivalence group be initialized.
5145    The simple constraints are done in symbol.c(check_conflict) and the rest
5146    are implemented here.  */
5147
5148 static void
5149 resolve_equivalence (gfc_equiv *eq)
5150 {
5151   gfc_symbol *sym;
5152   gfc_symbol *derived;
5153   gfc_symbol *first_sym;
5154   gfc_expr *e;
5155   gfc_ref *r;
5156   locus *last_where = NULL;
5157   seq_type eq_type, last_eq_type;
5158   gfc_typespec *last_ts;
5159   int object;
5160   const char *value_name;
5161   const char *msg;
5162
5163   value_name = NULL;
5164   last_ts = &eq->expr->symtree->n.sym->ts;
5165
5166   first_sym = eq->expr->symtree->n.sym;
5167
5168   for (object = 1; eq; eq = eq->eq, object++)
5169     {
5170       e = eq->expr;
5171
5172       e->ts = e->symtree->n.sym->ts;
5173       /* match_varspec might not know yet if it is seeing
5174          array reference or substring reference, as it doesn't
5175          know the types.  */
5176       if (e->ref && e->ref->type == REF_ARRAY)
5177         {
5178           gfc_ref *ref = e->ref;
5179           sym = e->symtree->n.sym;
5180
5181           if (sym->attr.dimension)
5182             {
5183               ref->u.ar.as = sym->as;
5184               ref = ref->next;
5185             }
5186
5187           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
5188           if (e->ts.type == BT_CHARACTER
5189               && ref
5190               && ref->type == REF_ARRAY
5191               && ref->u.ar.dimen == 1
5192               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
5193               && ref->u.ar.stride[0] == NULL)
5194             {
5195               gfc_expr *start = ref->u.ar.start[0];
5196               gfc_expr *end = ref->u.ar.end[0];
5197               void *mem = NULL;
5198
5199               /* Optimize away the (:) reference.  */
5200               if (start == NULL && end == NULL)
5201                 {
5202                   if (e->ref == ref)
5203                     e->ref = ref->next;
5204                   else
5205                     e->ref->next = ref->next;
5206                   mem = ref;
5207                 }
5208               else
5209                 {
5210                   ref->type = REF_SUBSTRING;
5211                   if (start == NULL)
5212                     start = gfc_int_expr (1);
5213                   ref->u.ss.start = start;
5214                   if (end == NULL && e->ts.cl)
5215                     end = gfc_copy_expr (e->ts.cl->length);
5216                   ref->u.ss.end = end;
5217                   ref->u.ss.length = e->ts.cl;
5218                   e->ts.cl = NULL;
5219                 }
5220               ref = ref->next;
5221               gfc_free (mem);
5222             }
5223
5224           /* Any further ref is an error.  */
5225           if (ref)
5226             {
5227               gcc_assert (ref->type == REF_ARRAY);
5228               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
5229                          &ref->u.ar.where);
5230               continue;
5231             }
5232         }
5233
5234       if (gfc_resolve_expr (e) == FAILURE)
5235         continue;
5236
5237       sym = e->symtree->n.sym;
5238
5239       /* An equivalence statement cannot have more than one initialized
5240          object.  */
5241       if (sym->value)
5242         {
5243           if (value_name != NULL)
5244             {
5245               gfc_error ("Initialized objects '%s' and '%s'  cannot both "
5246                          "be in the EQUIVALENCE statement at %L",
5247                          value_name, sym->name, &e->where);
5248               continue;
5249             }
5250           else
5251             value_name = sym->name;
5252         }
5253
5254       /* Shall not equivalence common block variables in a PURE procedure.  */
5255       if (sym->ns->proc_name 
5256             && sym->ns->proc_name->attr.pure
5257             && sym->attr.in_common)
5258         {
5259           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
5260                      "object in the pure procedure '%s'",
5261                      sym->name, &e->where, sym->ns->proc_name->name);
5262           break;
5263         }
5264  
5265       /* Shall not be a named constant.  */      
5266       if (e->expr_type == EXPR_CONSTANT)
5267         {
5268           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
5269                      "object", sym->name, &e->where);
5270           continue;
5271         }
5272
5273       derived = e->ts.derived;
5274       if (derived && resolve_equivalence_derived (derived, sym, e) == FAILURE)
5275         continue;
5276
5277       /* Check that the types correspond correctly:
5278          Note 5.28:
5279          A numeric sequence structure may be equivalenced to another sequence
5280          structure, an object of default integer type, default real type, double
5281          precision real type, default logical type such that components of the
5282          structure ultimately only become associated to objects of the same
5283          kind. A character sequence structure may be equivalenced to an object
5284          of default character kind or another character sequence structure.
5285          Other objects may be equivalenced only to objects of the same type and
5286          kind parameters.  */
5287
5288       /* Identical types are unconditionally OK.  */
5289       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
5290         goto identical_types;
5291
5292       last_eq_type = sequence_type (*last_ts);
5293       eq_type = sequence_type (sym->ts);
5294
5295       /* Since the pair of objects is not of the same type, mixed or
5296          non-default sequences can be rejected.  */
5297
5298       msg = "Sequence %s with mixed components in EQUIVALENCE "
5299             "statement at %L with different type objects";
5300       if ((object ==2
5301                && last_eq_type == SEQ_MIXED
5302                && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
5303                                   last_where) == FAILURE)
5304            ||  (eq_type == SEQ_MIXED
5305                && gfc_notify_std (GFC_STD_GNU, msg,sym->name,
5306                                   &e->where) == FAILURE))
5307         continue;
5308
5309       msg = "Non-default type object or sequence %s in EQUIVALENCE "
5310             "statement at %L with objects of different type";
5311       if ((object ==2
5312                && last_eq_type == SEQ_NONDEFAULT
5313                && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
5314                                   last_where) == FAILURE)
5315            ||  (eq_type == SEQ_NONDEFAULT
5316                && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
5317                                   &e->where) == FAILURE))
5318         continue;
5319
5320       msg ="Non-CHARACTER object '%s' in default CHARACTER "
5321            "EQUIVALENCE statement at %L";
5322       if (last_eq_type == SEQ_CHARACTER
5323             && eq_type != SEQ_CHARACTER
5324             && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
5325                                   &e->where) == FAILURE)
5326                 continue;
5327
5328       msg ="Non-NUMERIC object '%s' in default NUMERIC "
5329            "EQUIVALENCE statement at %L";
5330       if (last_eq_type == SEQ_NUMERIC
5331             && eq_type != SEQ_NUMERIC
5332             && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
5333                                   &e->where) == FAILURE)
5334                 continue;
5335
5336   identical_types:
5337       last_ts =&sym->ts;
5338       last_where = &e->where;
5339
5340       if (!e->ref)
5341         continue;
5342
5343       /* Shall not be an automatic array.  */
5344       if (e->ref->type == REF_ARRAY
5345           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
5346         {
5347           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
5348                      "an EQUIVALENCE object", sym->name, &e->where);
5349           continue;
5350         }
5351
5352       r = e->ref;
5353       while (r)
5354         {
5355           /* Shall not be a structure component.  */
5356           if (r->type == REF_COMPONENT)
5357             {
5358               gfc_error ("Structure component '%s' at %L cannot be an "
5359                          "EQUIVALENCE object",
5360                          r->u.c.component->name, &e->where);
5361               break;
5362             }
5363
5364           /* A substring shall not have length zero.  */
5365           if (r->type == REF_SUBSTRING)
5366             {
5367               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
5368                 {
5369                   gfc_error ("Substring at %L has length zero",
5370                              &r->u.ss.start->where);
5371                   break;
5372                 }
5373             }
5374           r = r->next;
5375         }
5376     }    
5377 }      
5378
5379
5380 /* Resolve function and ENTRY types, issue diagnostics if needed. */
5381
5382 static void
5383 resolve_fntype (gfc_namespace * ns)
5384 {
5385   gfc_entry_list *el;
5386   gfc_symbol *sym;
5387
5388   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
5389     return;
5390
5391   /* If there are any entries, ns->proc_name is the entry master
5392      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
5393   if (ns->entries)
5394     sym = ns->entries->sym;
5395   else
5396     sym = ns->proc_name;
5397   if (sym->result == sym
5398       && sym->ts.type == BT_UNKNOWN
5399       && gfc_set_default_type (sym, 0, NULL) == FAILURE
5400       && !sym->attr.untyped)
5401     {
5402       gfc_error ("Function '%s' at %L has no IMPLICIT type",
5403                  sym->name, &sym->declared_at);
5404       sym->attr.untyped = 1;
5405     }
5406
5407   if (ns->entries)
5408     for (el = ns->entries->next; el; el = el->next)
5409       {
5410         if (el->sym->result == el->sym
5411             && el->sym->ts.type == BT_UNKNOWN
5412             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
5413             && !el->sym->attr.untyped)
5414           {
5415             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
5416                        el->sym->name, &el->sym->declared_at);
5417             el->sym->attr.untyped = 1;
5418           }
5419       }
5420 }
5421
5422
5423 /* This function is called after a complete program unit has been compiled.
5424    Its purpose is to examine all of the expressions associated with a program
5425    unit, assign types to all intermediate expressions, make sure that all
5426    assignments are to compatible types and figure out which names refer to
5427    which functions or subroutines.  */
5428
5429 void
5430 gfc_resolve (gfc_namespace * ns)
5431 {
5432   gfc_namespace *old_ns, *n;
5433   gfc_charlen *cl;
5434   gfc_data *d;
5435   gfc_equiv *eq;
5436
5437   old_ns = gfc_current_ns;
5438   gfc_current_ns = ns;
5439
5440   resolve_entries (ns);
5441
5442   resolve_contained_functions (ns);
5443
5444   gfc_traverse_ns (ns, resolve_symbol);
5445
5446   resolve_fntype (ns);
5447
5448   for (n = ns->contained; n; n = n->sibling)
5449     {
5450       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
5451         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
5452                    "also be PURE", n->proc_name->name,
5453                    &n->proc_name->declared_at);
5454
5455       gfc_resolve (n);
5456     }
5457
5458   forall_flag = 0;
5459   gfc_check_interfaces (ns);
5460
5461   for (cl = ns->cl_list; cl; cl = cl->next)
5462     {
5463       if (cl->length == NULL || gfc_resolve_expr (cl->length) == FAILURE)
5464         continue;
5465
5466       if (gfc_simplify_expr (cl->length, 0) == FAILURE)
5467         continue;
5468
5469       if (gfc_specification_expr (cl->length) == FAILURE)
5470         continue;
5471     }
5472
5473   gfc_traverse_ns (ns, resolve_values);
5474
5475   if (ns->save_all)
5476     gfc_save_all (ns);
5477
5478   iter_stack = NULL;
5479   for (d = ns->data; d; d = d->next)
5480     resolve_data (d);
5481
5482   iter_stack = NULL;
5483   gfc_traverse_ns (ns, gfc_formalize_init_value);
5484
5485   for (eq = ns->equiv; eq; eq = eq->next)
5486     resolve_equivalence (eq);
5487
5488   cs_base = NULL;
5489   resolve_code (ns->code, ns);
5490
5491   /* Warn about unused labels.  */
5492   if (gfc_option.warn_unused_labels)
5493     warn_unused_label (ns);
5494
5495   gfc_current_ns = old_ns;
5496 }