OSDN Git Service

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