OSDN Git Service

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