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