OSDN Git Service

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