OSDN Git Service

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