OSDN Git Service

gcc/fortran/:
[pf3gnuchains/gcc-fork.git] / gcc / fortran / interface.c
1 /* Deal with interfaces.
2    Copyright (C) 2000, 2001, 2002, 2004, 2005, 2006, 2007, 2008, 2009,
3    2010
4    Free Software Foundation, Inc.
5    Contributed by Andy Vaught
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23
24 /* Deal with interfaces.  An explicit interface is represented as a
25    singly linked list of formal argument structures attached to the
26    relevant symbols.  For an implicit interface, the arguments don't
27    point to symbols.  Explicit interfaces point to namespaces that
28    contain the symbols within that interface.
29
30    Implicit interfaces are linked together in a singly linked list
31    along the next_if member of symbol nodes.  Since a particular
32    symbol can only have a single explicit interface, the symbol cannot
33    be part of multiple lists and a single next-member suffices.
34
35    This is not the case for general classes, though.  An operator
36    definition is independent of just about all other uses and has it's
37    own head pointer.
38
39    Nameless interfaces:
40      Nameless interfaces create symbols with explicit interfaces within
41      the current namespace.  They are otherwise unlinked.
42
43    Generic interfaces:
44      The generic name points to a linked list of symbols.  Each symbol
45      has an explicit interface.  Each explicit interface has its own
46      namespace containing the arguments.  Module procedures are symbols in
47      which the interface is added later when the module procedure is parsed.
48
49    User operators:
50      User-defined operators are stored in a their own set of symtrees
51      separate from regular symbols.  The symtrees point to gfc_user_op
52      structures which in turn head up a list of relevant interfaces.
53
54    Extended intrinsics and assignment:
55      The head of these interface lists are stored in the containing namespace.
56
57    Implicit interfaces:
58      An implicit interface is represented as a singly linked list of
59      formal argument list structures that don't point to any symbol
60      nodes -- they just contain types.
61
62
63    When a subprogram is defined, the program unit's name points to an
64    interface as usual, but the link to the namespace is NULL and the
65    formal argument list points to symbols within the same namespace as
66    the program unit name.  */
67
68 #include "config.h"
69 #include "system.h"
70 #include "gfortran.h"
71 #include "match.h"
72
73 /* The current_interface structure holds information about the
74    interface currently being parsed.  This structure is saved and
75    restored during recursive interfaces.  */
76
77 gfc_interface_info current_interface;
78
79
80 /* Free a singly linked list of gfc_interface structures.  */
81
82 void
83 gfc_free_interface (gfc_interface *intr)
84 {
85   gfc_interface *next;
86
87   for (; intr; intr = next)
88     {
89       next = intr->next;
90       gfc_free (intr);
91     }
92 }
93
94
95 /* Change the operators unary plus and minus into binary plus and
96    minus respectively, leaving the rest unchanged.  */
97
98 static gfc_intrinsic_op
99 fold_unary_intrinsic (gfc_intrinsic_op op)
100 {
101   switch (op)
102     {
103     case INTRINSIC_UPLUS:
104       op = INTRINSIC_PLUS;
105       break;
106     case INTRINSIC_UMINUS:
107       op = INTRINSIC_MINUS;
108       break;
109     default:
110       break;
111     }
112
113   return op;
114 }
115
116
117 /* Match a generic specification.  Depending on which type of
118    interface is found, the 'name' or 'op' pointers may be set.
119    This subroutine doesn't return MATCH_NO.  */
120
121 match
122 gfc_match_generic_spec (interface_type *type,
123                         char *name,
124                         gfc_intrinsic_op *op)
125 {
126   char buffer[GFC_MAX_SYMBOL_LEN + 1];
127   match m;
128   gfc_intrinsic_op i;
129
130   if (gfc_match (" assignment ( = )") == MATCH_YES)
131     {
132       *type = INTERFACE_INTRINSIC_OP;
133       *op = INTRINSIC_ASSIGN;
134       return MATCH_YES;
135     }
136
137   if (gfc_match (" operator ( %o )", &i) == MATCH_YES)
138     {                           /* Operator i/f */
139       *type = INTERFACE_INTRINSIC_OP;
140       *op = fold_unary_intrinsic (i);
141       return MATCH_YES;
142     }
143
144   *op = INTRINSIC_NONE;
145   if (gfc_match (" operator ( ") == MATCH_YES)
146     {
147       m = gfc_match_defined_op_name (buffer, 1);
148       if (m == MATCH_NO)
149         goto syntax;
150       if (m != MATCH_YES)
151         return MATCH_ERROR;
152
153       m = gfc_match_char (')');
154       if (m == MATCH_NO)
155         goto syntax;
156       if (m != MATCH_YES)
157         return MATCH_ERROR;
158
159       strcpy (name, buffer);
160       *type = INTERFACE_USER_OP;
161       return MATCH_YES;
162     }
163
164   if (gfc_match_name (buffer) == MATCH_YES)
165     {
166       strcpy (name, buffer);
167       *type = INTERFACE_GENERIC;
168       return MATCH_YES;
169     }
170
171   *type = INTERFACE_NAMELESS;
172   return MATCH_YES;
173
174 syntax:
175   gfc_error ("Syntax error in generic specification at %C");
176   return MATCH_ERROR;
177 }
178
179
180 /* Match one of the five F95 forms of an interface statement.  The
181    matcher for the abstract interface follows.  */
182
183 match
184 gfc_match_interface (void)
185 {
186   char name[GFC_MAX_SYMBOL_LEN + 1];
187   interface_type type;
188   gfc_symbol *sym;
189   gfc_intrinsic_op op;
190   match m;
191
192   m = gfc_match_space ();
193
194   if (gfc_match_generic_spec (&type, name, &op) == MATCH_ERROR)
195     return MATCH_ERROR;
196
197   /* If we're not looking at the end of the statement now, or if this
198      is not a nameless interface but we did not see a space, punt.  */
199   if (gfc_match_eos () != MATCH_YES
200       || (type != INTERFACE_NAMELESS && m != MATCH_YES))
201     {
202       gfc_error ("Syntax error: Trailing garbage in INTERFACE statement "
203                  "at %C");
204       return MATCH_ERROR;
205     }
206
207   current_interface.type = type;
208
209   switch (type)
210     {
211     case INTERFACE_GENERIC:
212       if (gfc_get_symbol (name, NULL, &sym))
213         return MATCH_ERROR;
214
215       if (!sym->attr.generic 
216           && gfc_add_generic (&sym->attr, sym->name, NULL) == FAILURE)
217         return MATCH_ERROR;
218
219       if (sym->attr.dummy)
220         {
221           gfc_error ("Dummy procedure '%s' at %C cannot have a "
222                      "generic interface", sym->name);
223           return MATCH_ERROR;
224         }
225
226       current_interface.sym = gfc_new_block = sym;
227       break;
228
229     case INTERFACE_USER_OP:
230       current_interface.uop = gfc_get_uop (name);
231       break;
232
233     case INTERFACE_INTRINSIC_OP:
234       current_interface.op = op;
235       break;
236
237     case INTERFACE_NAMELESS:
238     case INTERFACE_ABSTRACT:
239       break;
240     }
241
242   return MATCH_YES;
243 }
244
245
246
247 /* Match a F2003 abstract interface.  */
248
249 match
250 gfc_match_abstract_interface (void)
251 {
252   match m;
253
254   if (gfc_notify_std (GFC_STD_F2003, "Fortran 2003: ABSTRACT INTERFACE at %C")
255                       == FAILURE)
256     return MATCH_ERROR;
257
258   m = gfc_match_eos ();
259
260   if (m != MATCH_YES)
261     {
262       gfc_error ("Syntax error in ABSTRACT INTERFACE statement at %C");
263       return MATCH_ERROR;
264     }
265
266   current_interface.type = INTERFACE_ABSTRACT;
267
268   return m;
269 }
270
271
272 /* Match the different sort of generic-specs that can be present after
273    the END INTERFACE itself.  */
274
275 match
276 gfc_match_end_interface (void)
277 {
278   char name[GFC_MAX_SYMBOL_LEN + 1];
279   interface_type type;
280   gfc_intrinsic_op op;
281   match m;
282
283   m = gfc_match_space ();
284
285   if (gfc_match_generic_spec (&type, name, &op) == MATCH_ERROR)
286     return MATCH_ERROR;
287
288   /* If we're not looking at the end of the statement now, or if this
289      is not a nameless interface but we did not see a space, punt.  */
290   if (gfc_match_eos () != MATCH_YES
291       || (type != INTERFACE_NAMELESS && m != MATCH_YES))
292     {
293       gfc_error ("Syntax error: Trailing garbage in END INTERFACE "
294                  "statement at %C");
295       return MATCH_ERROR;
296     }
297
298   m = MATCH_YES;
299
300   switch (current_interface.type)
301     {
302     case INTERFACE_NAMELESS:
303     case INTERFACE_ABSTRACT:
304       if (type != INTERFACE_NAMELESS)
305         {
306           gfc_error ("Expected a nameless interface at %C");
307           m = MATCH_ERROR;
308         }
309
310       break;
311
312     case INTERFACE_INTRINSIC_OP:
313       if (type != current_interface.type || op != current_interface.op)
314         {
315
316           if (current_interface.op == INTRINSIC_ASSIGN)
317             {
318               m = MATCH_ERROR;
319               gfc_error ("Expected 'END INTERFACE ASSIGNMENT (=)' at %C");
320             }
321           else
322             {
323               const char *s1, *s2;
324               s1 = gfc_op2string (current_interface.op);
325               s2 = gfc_op2string (op);
326
327               /* The following if-statements are used to enforce C1202
328                  from F2003.  */
329               if ((strcmp(s1, "==") == 0 && strcmp(s2, ".eq.") == 0)
330                   || (strcmp(s1, ".eq.") == 0 && strcmp(s2, "==") == 0))
331                 break;
332               if ((strcmp(s1, "/=") == 0 && strcmp(s2, ".ne.") == 0)
333                   || (strcmp(s1, ".ne.") == 0 && strcmp(s2, "/=") == 0))
334                 break;
335               if ((strcmp(s1, "<=") == 0 && strcmp(s2, ".le.") == 0)
336                   || (strcmp(s1, ".le.") == 0 && strcmp(s2, "<=") == 0))
337                 break;
338               if ((strcmp(s1, "<") == 0 && strcmp(s2, ".lt.") == 0)
339                   || (strcmp(s1, ".lt.") == 0 && strcmp(s2, "<") == 0))
340                 break;
341               if ((strcmp(s1, ">=") == 0 && strcmp(s2, ".ge.") == 0)
342                   || (strcmp(s1, ".ge.") == 0 && strcmp(s2, ">=") == 0))
343                 break;
344               if ((strcmp(s1, ">") == 0 && strcmp(s2, ".gt.") == 0)
345                   || (strcmp(s1, ".gt.") == 0 && strcmp(s2, ">") == 0))
346                 break;
347
348               m = MATCH_ERROR;
349               gfc_error ("Expecting 'END INTERFACE OPERATOR (%s)' at %C, "
350                          "but got %s", s1, s2);
351             }
352                 
353         }
354
355       break;
356
357     case INTERFACE_USER_OP:
358       /* Comparing the symbol node names is OK because only use-associated
359          symbols can be renamed.  */
360       if (type != current_interface.type
361           || strcmp (current_interface.uop->name, name) != 0)
362         {
363           gfc_error ("Expecting 'END INTERFACE OPERATOR (.%s.)' at %C",
364                      current_interface.uop->name);
365           m = MATCH_ERROR;
366         }
367
368       break;
369
370     case INTERFACE_GENERIC:
371       if (type != current_interface.type
372           || strcmp (current_interface.sym->name, name) != 0)
373         {
374           gfc_error ("Expecting 'END INTERFACE %s' at %C",
375                      current_interface.sym->name);
376           m = MATCH_ERROR;
377         }
378
379       break;
380     }
381
382   return m;
383 }
384
385
386 /* Compare two derived types using the criteria in 4.4.2 of the standard,
387    recursing through gfc_compare_types for the components.  */
388
389 int
390 gfc_compare_derived_types (gfc_symbol *derived1, gfc_symbol *derived2)
391 {
392   gfc_component *dt1, *dt2;
393
394   if (derived1 == derived2)
395     return 1;
396
397   /* Special case for comparing derived types across namespaces.  If the
398      true names and module names are the same and the module name is
399      nonnull, then they are equal.  */
400   if (derived1 != NULL && derived2 != NULL
401       && strcmp (derived1->name, derived2->name) == 0
402       && derived1->module != NULL && derived2->module != NULL
403       && strcmp (derived1->module, derived2->module) == 0)
404     return 1;
405
406   /* Compare type via the rules of the standard.  Both types must have
407      the SEQUENCE attribute to be equal.  */
408
409   if (strcmp (derived1->name, derived2->name))
410     return 0;
411
412   if (derived1->component_access == ACCESS_PRIVATE
413       || derived2->component_access == ACCESS_PRIVATE)
414     return 0;
415
416   if (derived1->attr.sequence == 0 || derived2->attr.sequence == 0)
417     return 0;
418
419   dt1 = derived1->components;
420   dt2 = derived2->components;
421
422   /* Since subtypes of SEQUENCE types must be SEQUENCE types as well, a
423      simple test can speed things up.  Otherwise, lots of things have to
424      match.  */
425   for (;;)
426     {
427       if (strcmp (dt1->name, dt2->name) != 0)
428         return 0;
429
430       if (dt1->attr.access != dt2->attr.access)
431         return 0;
432
433       if (dt1->attr.pointer != dt2->attr.pointer)
434         return 0;
435
436       if (dt1->attr.dimension != dt2->attr.dimension)
437         return 0;
438
439      if (dt1->attr.allocatable != dt2->attr.allocatable)
440         return 0;
441
442       if (dt1->attr.dimension && gfc_compare_array_spec (dt1->as, dt2->as) == 0)
443         return 0;
444
445       /* Make sure that link lists do not put this function into an 
446          endless recursive loop!  */
447       if (!(dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived)
448             && !(dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived)
449             && gfc_compare_types (&dt1->ts, &dt2->ts) == 0)
450         return 0;
451
452       else if ((dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived)
453                 && !(dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived))
454         return 0;
455
456       else if (!(dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived)
457                 && (dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived))
458         return 0;
459
460       dt1 = dt1->next;
461       dt2 = dt2->next;
462
463       if (dt1 == NULL && dt2 == NULL)
464         break;
465       if (dt1 == NULL || dt2 == NULL)
466         return 0;
467     }
468
469   return 1;
470 }
471
472
473 /* Compare two typespecs, recursively if necessary.  */
474
475 int
476 gfc_compare_types (gfc_typespec *ts1, gfc_typespec *ts2)
477 {
478   /* See if one of the typespecs is a BT_VOID, which is what is being used
479      to allow the funcs like c_f_pointer to accept any pointer type.
480      TODO: Possibly should narrow this to just the one typespec coming in
481      that is for the formal arg, but oh well.  */
482   if (ts1->type == BT_VOID || ts2->type == BT_VOID)
483     return 1;
484    
485   if (ts1->type != ts2->type
486       && ((ts1->type != BT_DERIVED && ts1->type != BT_CLASS)
487           || (ts2->type != BT_DERIVED && ts2->type != BT_CLASS)))
488     return 0;
489   if (ts1->type != BT_DERIVED && ts1->type != BT_CLASS)
490     return (ts1->kind == ts2->kind);
491
492   /* Compare derived types.  */
493   if (gfc_type_compatible (ts1, ts2))
494     return 1;
495
496   return gfc_compare_derived_types (ts1->u.derived ,ts2->u.derived);
497 }
498
499
500 /* Given two symbols that are formal arguments, compare their ranks
501    and types.  Returns nonzero if they have the same rank and type,
502    zero otherwise.  */
503
504 static int
505 compare_type_rank (gfc_symbol *s1, gfc_symbol *s2)
506 {
507   int r1, r2;
508
509   r1 = (s1->as != NULL) ? s1->as->rank : 0;
510   r2 = (s2->as != NULL) ? s2->as->rank : 0;
511
512   if (r1 != r2)
513     return 0;                   /* Ranks differ.  */
514
515   return gfc_compare_types (&s1->ts, &s2->ts);
516 }
517
518
519 /* Given two symbols that are formal arguments, compare their types
520    and rank and their formal interfaces if they are both dummy
521    procedures.  Returns nonzero if the same, zero if different.  */
522
523 static int
524 compare_type_rank_if (gfc_symbol *s1, gfc_symbol *s2)
525 {
526   if (s1 == NULL || s2 == NULL)
527     return s1 == s2 ? 1 : 0;
528
529   if (s1 == s2)
530     return 1;
531
532   if (s1->attr.flavor != FL_PROCEDURE && s2->attr.flavor != FL_PROCEDURE)
533     return compare_type_rank (s1, s2);
534
535   if (s1->attr.flavor != FL_PROCEDURE || s2->attr.flavor != FL_PROCEDURE)
536     return 0;
537
538   /* At this point, both symbols are procedures.  It can happen that
539      external procedures are compared, where one is identified by usage
540      to be a function or subroutine but the other is not.  Check TKR
541      nonetheless for these cases.  */
542   if (s1->attr.function == 0 && s1->attr.subroutine == 0)
543     return s1->attr.external == 1 ? compare_type_rank (s1, s2) : 0;
544
545   if (s2->attr.function == 0 && s2->attr.subroutine == 0)
546     return s2->attr.external == 1 ? compare_type_rank (s1, s2) : 0;
547
548   /* Now the type of procedure has been identified.  */
549   if (s1->attr.function != s2->attr.function
550       || s1->attr.subroutine != s2->attr.subroutine)
551     return 0;
552
553   if (s1->attr.function && compare_type_rank (s1, s2) == 0)
554     return 0;
555
556   /* Originally, gfortran recursed here to check the interfaces of passed
557      procedures.  This is explicitly not required by the standard.  */
558   return 1;
559 }
560
561
562 /* Given a formal argument list and a keyword name, search the list
563    for that keyword.  Returns the correct symbol node if found, NULL
564    if not found.  */
565
566 static gfc_symbol *
567 find_keyword_arg (const char *name, gfc_formal_arglist *f)
568 {
569   for (; f; f = f->next)
570     if (strcmp (f->sym->name, name) == 0)
571       return f->sym;
572
573   return NULL;
574 }
575
576
577 /******** Interface checking subroutines **********/
578
579
580 /* Given an operator interface and the operator, make sure that all
581    interfaces for that operator are legal.  */
582
583 bool
584 gfc_check_operator_interface (gfc_symbol *sym, gfc_intrinsic_op op,
585                               locus opwhere)
586 {
587   gfc_formal_arglist *formal;
588   sym_intent i1, i2;
589   bt t1, t2;
590   int args, r1, r2, k1, k2;
591
592   gcc_assert (sym);
593
594   args = 0;
595   t1 = t2 = BT_UNKNOWN;
596   i1 = i2 = INTENT_UNKNOWN;
597   r1 = r2 = -1;
598   k1 = k2 = -1;
599
600   for (formal = sym->formal; formal; formal = formal->next)
601     {
602       gfc_symbol *fsym = formal->sym;
603       if (fsym == NULL)
604         {
605           gfc_error ("Alternate return cannot appear in operator "
606                      "interface at %L", &sym->declared_at);
607           return false;
608         }
609       if (args == 0)
610         {
611           t1 = fsym->ts.type;
612           i1 = fsym->attr.intent;
613           r1 = (fsym->as != NULL) ? fsym->as->rank : 0;
614           k1 = fsym->ts.kind;
615         }
616       if (args == 1)
617         {
618           t2 = fsym->ts.type;
619           i2 = fsym->attr.intent;
620           r2 = (fsym->as != NULL) ? fsym->as->rank : 0;
621           k2 = fsym->ts.kind;
622         }
623       args++;
624     }
625
626   /* Only +, - and .not. can be unary operators.
627      .not. cannot be a binary operator.  */
628   if (args == 0 || args > 2 || (args == 1 && op != INTRINSIC_PLUS
629                                 && op != INTRINSIC_MINUS
630                                 && op != INTRINSIC_NOT)
631       || (args == 2 && op == INTRINSIC_NOT))
632     {
633       gfc_error ("Operator interface at %L has the wrong number of arguments",
634                  &sym->declared_at);
635       return false;
636     }
637
638   /* Check that intrinsics are mapped to functions, except
639      INTRINSIC_ASSIGN which should map to a subroutine.  */
640   if (op == INTRINSIC_ASSIGN)
641     {
642       if (!sym->attr.subroutine)
643         {
644           gfc_error ("Assignment operator interface at %L must be "
645                      "a SUBROUTINE", &sym->declared_at);
646           return false;
647         }
648       if (args != 2)
649         {
650           gfc_error ("Assignment operator interface at %L must have "
651                      "two arguments", &sym->declared_at);
652           return false;
653         }
654
655       /* Allowed are (per F2003, 12.3.2.1.2 Defined assignments):
656          - First argument an array with different rank than second,
657          - Types and kinds do not conform, and
658          - First argument is of derived type.  */
659       if (sym->formal->sym->ts.type != BT_DERIVED
660           && sym->formal->sym->ts.type != BT_CLASS
661           && (r1 == 0 || r1 == r2)
662           && (sym->formal->sym->ts.type == sym->formal->next->sym->ts.type
663               || (gfc_numeric_ts (&sym->formal->sym->ts)
664                   && gfc_numeric_ts (&sym->formal->next->sym->ts))))
665         {
666           gfc_error ("Assignment operator interface at %L must not redefine "
667                      "an INTRINSIC type assignment", &sym->declared_at);
668           return false;
669         }
670     }
671   else
672     {
673       if (!sym->attr.function)
674         {
675           gfc_error ("Intrinsic operator interface at %L must be a FUNCTION",
676                      &sym->declared_at);
677           return false;
678         }
679     }
680
681   /* Check intents on operator interfaces.  */
682   if (op == INTRINSIC_ASSIGN)
683     {
684       if (i1 != INTENT_OUT && i1 != INTENT_INOUT)
685         {
686           gfc_error ("First argument of defined assignment at %L must be "
687                      "INTENT(OUT) or INTENT(INOUT)", &sym->declared_at);
688           return false;
689         }
690
691       if (i2 != INTENT_IN)
692         {
693           gfc_error ("Second argument of defined assignment at %L must be "
694                      "INTENT(IN)", &sym->declared_at);
695           return false;
696         }
697     }
698   else
699     {
700       if (i1 != INTENT_IN)
701         {
702           gfc_error ("First argument of operator interface at %L must be "
703                      "INTENT(IN)", &sym->declared_at);
704           return false;
705         }
706
707       if (args == 2 && i2 != INTENT_IN)
708         {
709           gfc_error ("Second argument of operator interface at %L must be "
710                      "INTENT(IN)", &sym->declared_at);
711           return false;
712         }
713     }
714
715   /* From now on, all we have to do is check that the operator definition
716      doesn't conflict with an intrinsic operator. The rules for this
717      game are defined in 7.1.2 and 7.1.3 of both F95 and F2003 standards,
718      as well as 12.3.2.1.1 of Fortran 2003:
719
720      "If the operator is an intrinsic-operator (R310), the number of
721      function arguments shall be consistent with the intrinsic uses of
722      that operator, and the types, kind type parameters, or ranks of the
723      dummy arguments shall differ from those required for the intrinsic
724      operation (7.1.2)."  */
725
726 #define IS_NUMERIC_TYPE(t) \
727   ((t) == BT_INTEGER || (t) == BT_REAL || (t) == BT_COMPLEX)
728
729   /* Unary ops are easy, do them first.  */
730   if (op == INTRINSIC_NOT)
731     {
732       if (t1 == BT_LOGICAL)
733         goto bad_repl;
734       else
735         return true;
736     }
737
738   if (args == 1 && (op == INTRINSIC_PLUS || op == INTRINSIC_MINUS))
739     {
740       if (IS_NUMERIC_TYPE (t1))
741         goto bad_repl;
742       else
743         return true;
744     }
745
746   /* Character intrinsic operators have same character kind, thus
747      operator definitions with operands of different character kinds
748      are always safe.  */
749   if (t1 == BT_CHARACTER && t2 == BT_CHARACTER && k1 != k2)
750     return true;
751
752   /* Intrinsic operators always perform on arguments of same rank,
753      so different ranks is also always safe.  (rank == 0) is an exception
754      to that, because all intrinsic operators are elemental.  */
755   if (r1 != r2 && r1 != 0 && r2 != 0)
756     return true;
757
758   switch (op)
759   {
760     case INTRINSIC_EQ:
761     case INTRINSIC_EQ_OS:
762     case INTRINSIC_NE:
763     case INTRINSIC_NE_OS:
764       if (t1 == BT_CHARACTER && t2 == BT_CHARACTER)
765         goto bad_repl;
766       /* Fall through.  */
767
768     case INTRINSIC_PLUS:
769     case INTRINSIC_MINUS:
770     case INTRINSIC_TIMES:
771     case INTRINSIC_DIVIDE:
772     case INTRINSIC_POWER:
773       if (IS_NUMERIC_TYPE (t1) && IS_NUMERIC_TYPE (t2))
774         goto bad_repl;
775       break;
776
777     case INTRINSIC_GT:
778     case INTRINSIC_GT_OS:
779     case INTRINSIC_GE:
780     case INTRINSIC_GE_OS:
781     case INTRINSIC_LT:
782     case INTRINSIC_LT_OS:
783     case INTRINSIC_LE:
784     case INTRINSIC_LE_OS:
785       if (t1 == BT_CHARACTER && t2 == BT_CHARACTER)
786         goto bad_repl;
787       if ((t1 == BT_INTEGER || t1 == BT_REAL)
788           && (t2 == BT_INTEGER || t2 == BT_REAL))
789         goto bad_repl;
790       break;
791
792     case INTRINSIC_CONCAT:
793       if (t1 == BT_CHARACTER && t2 == BT_CHARACTER)
794         goto bad_repl;
795       break;
796
797     case INTRINSIC_AND:
798     case INTRINSIC_OR:
799     case INTRINSIC_EQV:
800     case INTRINSIC_NEQV:
801       if (t1 == BT_LOGICAL && t2 == BT_LOGICAL)
802         goto bad_repl;
803       break;
804
805     default:
806       break;
807   }
808
809   return true;
810
811 #undef IS_NUMERIC_TYPE
812
813 bad_repl:
814   gfc_error ("Operator interface at %L conflicts with intrinsic interface",
815              &opwhere);
816   return false;
817 }
818
819
820 /* Given a pair of formal argument lists, we see if the two lists can
821    be distinguished by counting the number of nonoptional arguments of
822    a given type/rank in f1 and seeing if there are less then that
823    number of those arguments in f2 (including optional arguments).
824    Since this test is asymmetric, it has to be called twice to make it
825    symmetric.  Returns nonzero if the argument lists are incompatible
826    by this test.  This subroutine implements rule 1 of section
827    14.1.2.3 in the Fortran 95 standard.  */
828
829 static int
830 count_types_test (gfc_formal_arglist *f1, gfc_formal_arglist *f2)
831 {
832   int rc, ac1, ac2, i, j, k, n1;
833   gfc_formal_arglist *f;
834
835   typedef struct
836   {
837     int flag;
838     gfc_symbol *sym;
839   }
840   arginfo;
841
842   arginfo *arg;
843
844   n1 = 0;
845
846   for (f = f1; f; f = f->next)
847     n1++;
848
849   /* Build an array of integers that gives the same integer to
850      arguments of the same type/rank.  */
851   arg = XCNEWVEC (arginfo, n1);
852
853   f = f1;
854   for (i = 0; i < n1; i++, f = f->next)
855     {
856       arg[i].flag = -1;
857       arg[i].sym = f->sym;
858     }
859
860   k = 0;
861
862   for (i = 0; i < n1; i++)
863     {
864       if (arg[i].flag != -1)
865         continue;
866
867       if (arg[i].sym && arg[i].sym->attr.optional)
868         continue;               /* Skip optional arguments.  */
869
870       arg[i].flag = k;
871
872       /* Find other nonoptional arguments of the same type/rank.  */
873       for (j = i + 1; j < n1; j++)
874         if ((arg[j].sym == NULL || !arg[j].sym->attr.optional)
875             && (compare_type_rank_if (arg[i].sym, arg[j].sym)
876                 || compare_type_rank_if (arg[j].sym, arg[i].sym)))
877           arg[j].flag = k;
878
879       k++;
880     }
881
882   /* Now loop over each distinct type found in f1.  */
883   k = 0;
884   rc = 0;
885
886   for (i = 0; i < n1; i++)
887     {
888       if (arg[i].flag != k)
889         continue;
890
891       ac1 = 1;
892       for (j = i + 1; j < n1; j++)
893         if (arg[j].flag == k)
894           ac1++;
895
896       /* Count the number of arguments in f2 with that type, including
897          those that are optional.  */
898       ac2 = 0;
899
900       for (f = f2; f; f = f->next)
901         if (compare_type_rank_if (arg[i].sym, f->sym)
902             || compare_type_rank_if (f->sym, arg[i].sym))
903           ac2++;
904
905       if (ac1 > ac2)
906         {
907           rc = 1;
908           break;
909         }
910
911       k++;
912     }
913
914   gfc_free (arg);
915
916   return rc;
917 }
918
919
920 /* Perform the correspondence test in rule 2 of section 14.1.2.3.
921    Returns zero if no argument is found that satisfies rule 2, nonzero
922    otherwise.
923
924    This test is also not symmetric in f1 and f2 and must be called
925    twice.  This test finds problems caused by sorting the actual
926    argument list with keywords.  For example:
927
928    INTERFACE FOO
929        SUBROUTINE F1(A, B)
930            INTEGER :: A ; REAL :: B
931        END SUBROUTINE F1
932
933        SUBROUTINE F2(B, A)
934            INTEGER :: A ; REAL :: B
935        END SUBROUTINE F1
936    END INTERFACE FOO
937
938    At this point, 'CALL FOO(A=1, B=1.0)' is ambiguous.  */
939
940 static int
941 generic_correspondence (gfc_formal_arglist *f1, gfc_formal_arglist *f2)
942 {
943   gfc_formal_arglist *f2_save, *g;
944   gfc_symbol *sym;
945
946   f2_save = f2;
947
948   while (f1)
949     {
950       if (f1->sym->attr.optional)
951         goto next;
952
953       if (f2 != NULL && (compare_type_rank (f1->sym, f2->sym)
954                          || compare_type_rank (f2->sym, f1->sym)))
955         goto next;
956
957       /* Now search for a disambiguating keyword argument starting at
958          the current non-match.  */
959       for (g = f1; g; g = g->next)
960         {
961           if (g->sym->attr.optional)
962             continue;
963
964           sym = find_keyword_arg (g->sym->name, f2_save);
965           if (sym == NULL || !compare_type_rank (g->sym, sym))
966             return 1;
967         }
968
969     next:
970       f1 = f1->next;
971       if (f2 != NULL)
972         f2 = f2->next;
973     }
974
975   return 0;
976 }
977
978
979 /* 'Compare' two formal interfaces associated with a pair of symbols.
980    We return nonzero if there exists an actual argument list that
981    would be ambiguous between the two interfaces, zero otherwise.
982    'intent_flag' specifies whether INTENT and OPTIONAL of the arguments are
983    required to match, which is not the case for ambiguity checks.*/
984
985 int
986 gfc_compare_interfaces (gfc_symbol *s1, gfc_symbol *s2, const char *name2,
987                         int generic_flag, int intent_flag,
988                         char *errmsg, int err_len)
989 {
990   gfc_formal_arglist *f1, *f2;
991
992   gcc_assert (name2 != NULL);
993
994   if (s1->attr.function && (s2->attr.subroutine
995       || (!s2->attr.function && s2->ts.type == BT_UNKNOWN
996           && gfc_get_default_type (name2, s2->ns)->type == BT_UNKNOWN)))
997     {
998       if (errmsg != NULL)
999         snprintf (errmsg, err_len, "'%s' is not a function", name2);
1000       return 0;
1001     }
1002
1003   if (s1->attr.subroutine && s2->attr.function)
1004     {
1005       if (errmsg != NULL)
1006         snprintf (errmsg, err_len, "'%s' is not a subroutine", name2);
1007       return 0;
1008     }
1009
1010   /* If the arguments are functions, check type and kind
1011      (only for dummy procedures and procedure pointer assignments).  */
1012   if (!generic_flag && intent_flag && s1->attr.function && s2->attr.function)
1013     {
1014       if (s1->ts.type == BT_UNKNOWN)
1015         return 1;
1016       if ((s1->ts.type != s2->ts.type) || (s1->ts.kind != s2->ts.kind))
1017         {
1018           if (errmsg != NULL)
1019             snprintf (errmsg, err_len, "Type/kind mismatch in return value "
1020                       "of '%s'", name2);
1021           return 0;
1022         }
1023     }
1024
1025   if (s1->attr.if_source == IFSRC_UNKNOWN
1026       || s2->attr.if_source == IFSRC_UNKNOWN)
1027     return 1;
1028
1029   f1 = s1->formal;
1030   f2 = s2->formal;
1031
1032   if (f1 == NULL && f2 == NULL)
1033     return 1;                   /* Special case: No arguments.  */
1034
1035   if (generic_flag)
1036     {
1037       if (count_types_test (f1, f2) || count_types_test (f2, f1))
1038         return 0;
1039       if (generic_correspondence (f1, f2) || generic_correspondence (f2, f1))
1040         return 0;
1041     }
1042   else
1043     /* Perform the abbreviated correspondence test for operators (the
1044        arguments cannot be optional and are always ordered correctly).
1045        This is also done when comparing interfaces for dummy procedures and in
1046        procedure pointer assignments.  */
1047
1048     for (;;)
1049       {
1050         /* Check existence.  */
1051         if (f1 == NULL && f2 == NULL)
1052           break;
1053         if (f1 == NULL || f2 == NULL)
1054           {
1055             if (errmsg != NULL)
1056               snprintf (errmsg, err_len, "'%s' has the wrong number of "
1057                         "arguments", name2);
1058             return 0;
1059           }
1060
1061         /* Check type and rank.  */
1062         if (!compare_type_rank (f2->sym, f1->sym))
1063           {
1064             if (errmsg != NULL)
1065               snprintf (errmsg, err_len, "Type/rank mismatch in argument '%s'",
1066                         f1->sym->name);
1067             return 0;
1068           }
1069
1070         /* Check INTENT.  */
1071         if (intent_flag && (f1->sym->attr.intent != f2->sym->attr.intent))
1072           {
1073             snprintf (errmsg, err_len, "INTENT mismatch in argument '%s'",
1074                       f1->sym->name);
1075             return 0;
1076           }
1077
1078         /* Check OPTIONAL.  */
1079         if (intent_flag && (f1->sym->attr.optional != f2->sym->attr.optional))
1080           {
1081             snprintf (errmsg, err_len, "OPTIONAL mismatch in argument '%s'",
1082                       f1->sym->name);
1083             return 0;
1084           }
1085
1086         f1 = f1->next;
1087         f2 = f2->next;
1088       }
1089
1090   return 1;
1091 }
1092
1093
1094 /* Given a pointer to an interface pointer, remove duplicate
1095    interfaces and make sure that all symbols are either functions
1096    or subroutines, and all of the same kind.  Returns nonzero if
1097    something goes wrong.  */
1098
1099 static int
1100 check_interface0 (gfc_interface *p, const char *interface_name)
1101 {
1102   gfc_interface *psave, *q, *qlast;
1103
1104   psave = p;
1105   for (; p; p = p->next)
1106     {
1107       /* Make sure all symbols in the interface have been defined as
1108          functions or subroutines.  */
1109       if ((!p->sym->attr.function && !p->sym->attr.subroutine)
1110           || !p->sym->attr.if_source)
1111         {
1112           if (p->sym->attr.external)
1113             gfc_error ("Procedure '%s' in %s at %L has no explicit interface",
1114                        p->sym->name, interface_name, &p->sym->declared_at);
1115           else
1116             gfc_error ("Procedure '%s' in %s at %L is neither function nor "
1117                        "subroutine", p->sym->name, interface_name,
1118                       &p->sym->declared_at);
1119           return 1;
1120         }
1121
1122       /* Verify that procedures are either all SUBROUTINEs or all FUNCTIONs.  */
1123       if ((psave->sym->attr.function && !p->sym->attr.function)
1124           || (psave->sym->attr.subroutine && !p->sym->attr.subroutine))
1125         {
1126           gfc_error ("In %s at %L procedures must be either all SUBROUTINEs"
1127                      " or all FUNCTIONs", interface_name, &p->sym->declared_at);
1128           return 1;
1129         }
1130     }
1131   p = psave;
1132
1133   /* Remove duplicate interfaces in this interface list.  */
1134   for (; p; p = p->next)
1135     {
1136       qlast = p;
1137
1138       for (q = p->next; q;)
1139         {
1140           if (p->sym != q->sym)
1141             {
1142               qlast = q;
1143               q = q->next;
1144             }
1145           else
1146             {
1147               /* Duplicate interface.  */
1148               qlast->next = q->next;
1149               gfc_free (q);
1150               q = qlast->next;
1151             }
1152         }
1153     }
1154
1155   return 0;
1156 }
1157
1158
1159 /* Check lists of interfaces to make sure that no two interfaces are
1160    ambiguous.  Duplicate interfaces (from the same symbol) are OK here.  */
1161
1162 static int
1163 check_interface1 (gfc_interface *p, gfc_interface *q0,
1164                   int generic_flag, const char *interface_name,
1165                   bool referenced)
1166 {
1167   gfc_interface *q;
1168   for (; p; p = p->next)
1169     for (q = q0; q; q = q->next)
1170       {
1171         if (p->sym == q->sym)
1172           continue;             /* Duplicates OK here.  */
1173
1174         if (p->sym->name == q->sym->name && p->sym->module == q->sym->module)
1175           continue;
1176
1177         if (gfc_compare_interfaces (p->sym, q->sym, q->sym->name, generic_flag,
1178                                     0, NULL, 0))
1179           {
1180             if (referenced)
1181               gfc_error ("Ambiguous interfaces '%s' and '%s' in %s at %L",
1182                          p->sym->name, q->sym->name, interface_name,
1183                          &p->where);
1184             else if (!p->sym->attr.use_assoc && q->sym->attr.use_assoc)
1185               gfc_warning ("Ambiguous interfaces '%s' and '%s' in %s at %L",
1186                            p->sym->name, q->sym->name, interface_name,
1187                            &p->where);
1188             else
1189               gfc_warning ("Although not referenced, '%s' has ambiguous "
1190                            "interfaces at %L", interface_name, &p->where);
1191             return 1;
1192           }
1193       }
1194   return 0;
1195 }
1196
1197
1198 /* Check the generic and operator interfaces of symbols to make sure
1199    that none of the interfaces conflict.  The check has to be done
1200    after all of the symbols are actually loaded.  */
1201
1202 static void
1203 check_sym_interfaces (gfc_symbol *sym)
1204 {
1205   char interface_name[100];
1206   gfc_interface *p;
1207
1208   if (sym->ns != gfc_current_ns)
1209     return;
1210
1211   if (sym->generic != NULL)
1212     {
1213       sprintf (interface_name, "generic interface '%s'", sym->name);
1214       if (check_interface0 (sym->generic, interface_name))
1215         return;
1216
1217       for (p = sym->generic; p; p = p->next)
1218         {
1219           if (p->sym->attr.mod_proc
1220               && (p->sym->attr.if_source != IFSRC_DECL
1221                   || p->sym->attr.procedure))
1222             {
1223               gfc_error ("'%s' at %L is not a module procedure",
1224                          p->sym->name, &p->where);
1225               return;
1226             }
1227         }
1228
1229       /* Originally, this test was applied to host interfaces too;
1230          this is incorrect since host associated symbols, from any
1231          source, cannot be ambiguous with local symbols.  */
1232       check_interface1 (sym->generic, sym->generic, 1, interface_name,
1233                         sym->attr.referenced || !sym->attr.use_assoc);
1234     }
1235 }
1236
1237
1238 static void
1239 check_uop_interfaces (gfc_user_op *uop)
1240 {
1241   char interface_name[100];
1242   gfc_user_op *uop2;
1243   gfc_namespace *ns;
1244
1245   sprintf (interface_name, "operator interface '%s'", uop->name);
1246   if (check_interface0 (uop->op, interface_name))
1247     return;
1248
1249   for (ns = gfc_current_ns; ns; ns = ns->parent)
1250     {
1251       uop2 = gfc_find_uop (uop->name, ns);
1252       if (uop2 == NULL)
1253         continue;
1254
1255       check_interface1 (uop->op, uop2->op, 0,
1256                         interface_name, true);
1257     }
1258 }
1259
1260
1261 /* For the namespace, check generic, user operator and intrinsic
1262    operator interfaces for consistency and to remove duplicate
1263    interfaces.  We traverse the whole namespace, counting on the fact
1264    that most symbols will not have generic or operator interfaces.  */
1265
1266 void
1267 gfc_check_interfaces (gfc_namespace *ns)
1268 {
1269   gfc_namespace *old_ns, *ns2;
1270   char interface_name[100];
1271   int i;
1272
1273   old_ns = gfc_current_ns;
1274   gfc_current_ns = ns;
1275
1276   gfc_traverse_ns (ns, check_sym_interfaces);
1277
1278   gfc_traverse_user_op (ns, check_uop_interfaces);
1279
1280   for (i = GFC_INTRINSIC_BEGIN; i != GFC_INTRINSIC_END; i++)
1281     {
1282       if (i == INTRINSIC_USER)
1283         continue;
1284
1285       if (i == INTRINSIC_ASSIGN)
1286         strcpy (interface_name, "intrinsic assignment operator");
1287       else
1288         sprintf (interface_name, "intrinsic '%s' operator",
1289                  gfc_op2string ((gfc_intrinsic_op) i));
1290
1291       if (check_interface0 (ns->op[i], interface_name))
1292         continue;
1293
1294       if (ns->op[i])
1295         gfc_check_operator_interface (ns->op[i]->sym, (gfc_intrinsic_op) i,
1296                                       ns->op[i]->where);
1297
1298       for (ns2 = ns; ns2; ns2 = ns2->parent)
1299         {
1300           if (check_interface1 (ns->op[i], ns2->op[i], 0,
1301                                 interface_name, true))
1302             goto done;
1303
1304           switch (i)
1305             {
1306               case INTRINSIC_EQ:
1307                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_EQ_OS],
1308                                       0, interface_name, true)) goto done;
1309                 break;
1310
1311               case INTRINSIC_EQ_OS:
1312                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_EQ],
1313                                       0, interface_name, true)) goto done;
1314                 break;
1315
1316               case INTRINSIC_NE:
1317                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_NE_OS],
1318                                       0, interface_name, true)) goto done;
1319                 break;
1320
1321               case INTRINSIC_NE_OS:
1322                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_NE],
1323                                       0, interface_name, true)) goto done;
1324                 break;
1325
1326               case INTRINSIC_GT:
1327                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_GT_OS],
1328                                       0, interface_name, true)) goto done;
1329                 break;
1330
1331               case INTRINSIC_GT_OS:
1332                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_GT],
1333                                       0, interface_name, true)) goto done;
1334                 break;
1335
1336               case INTRINSIC_GE:
1337                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_GE_OS],
1338                                       0, interface_name, true)) goto done;
1339                 break;
1340
1341               case INTRINSIC_GE_OS:
1342                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_GE],
1343                                       0, interface_name, true)) goto done;
1344                 break;
1345
1346               case INTRINSIC_LT:
1347                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_LT_OS],
1348                                       0, interface_name, true)) goto done;
1349                 break;
1350
1351               case INTRINSIC_LT_OS:
1352                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_LT],
1353                                       0, interface_name, true)) goto done;
1354                 break;
1355
1356               case INTRINSIC_LE:
1357                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_LE_OS],
1358                                       0, interface_name, true)) goto done;
1359                 break;
1360
1361               case INTRINSIC_LE_OS:
1362                 if (check_interface1 (ns->op[i], ns2->op[INTRINSIC_LE],
1363                                       0, interface_name, true)) goto done;
1364                 break;
1365
1366               default:
1367                 break;
1368             }
1369         }
1370     }
1371
1372 done:
1373   gfc_current_ns = old_ns;
1374 }
1375
1376
1377 static int
1378 symbol_rank (gfc_symbol *sym)
1379 {
1380   return (sym->as == NULL) ? 0 : sym->as->rank;
1381 }
1382
1383
1384 /* Given a symbol of a formal argument list and an expression, if the
1385    formal argument is allocatable, check that the actual argument is
1386    allocatable. Returns nonzero if compatible, zero if not compatible.  */
1387
1388 static int
1389 compare_allocatable (gfc_symbol *formal, gfc_expr *actual)
1390 {
1391   symbol_attribute attr;
1392
1393   if (formal->attr.allocatable
1394       || (formal->ts.type == BT_CLASS && CLASS_DATA (formal)->attr.allocatable))
1395     {
1396       attr = gfc_expr_attr (actual);
1397       if (!attr.allocatable)
1398         return 0;
1399     }
1400
1401   return 1;
1402 }
1403
1404
1405 /* Given a symbol of a formal argument list and an expression, if the
1406    formal argument is a pointer, see if the actual argument is a
1407    pointer. Returns nonzero if compatible, zero if not compatible.  */
1408
1409 static int
1410 compare_pointer (gfc_symbol *formal, gfc_expr *actual)
1411 {
1412   symbol_attribute attr;
1413
1414   if (formal->attr.pointer)
1415     {
1416       attr = gfc_expr_attr (actual);
1417
1418       /* Fortran 2008 allows non-pointer actual arguments.  */
1419       if (!attr.pointer && attr.target && formal->attr.intent == INTENT_IN)
1420         return 2;
1421
1422       if (!attr.pointer)
1423         return 0;
1424     }
1425
1426   return 1;
1427 }
1428
1429
1430 /* Emit clear error messages for rank mismatch.  */
1431
1432 static void
1433 argument_rank_mismatch (const char *name, locus *where,
1434                         int rank1, int rank2)
1435 {
1436   if (rank1 == 0)
1437     {
1438       gfc_error ("Rank mismatch in argument '%s' at %L "
1439                  "(scalar and rank-%d)", name, where, rank2);
1440     }
1441   else if (rank2 == 0)
1442     {
1443       gfc_error ("Rank mismatch in argument '%s' at %L "
1444                  "(rank-%d and scalar)", name, where, rank1);
1445     }
1446   else
1447     {    
1448       gfc_error ("Rank mismatch in argument '%s' at %L "
1449                  "(rank-%d and rank-%d)", name, where, rank1, rank2);
1450     }
1451 }
1452
1453
1454 /* Given a symbol of a formal argument list and an expression, see if
1455    the two are compatible as arguments.  Returns nonzero if
1456    compatible, zero if not compatible.  */
1457
1458 static int
1459 compare_parameter (gfc_symbol *formal, gfc_expr *actual,
1460                    int ranks_must_agree, int is_elemental, locus *where)
1461 {
1462   gfc_ref *ref;
1463   bool rank_check;
1464
1465   /* If the formal arg has type BT_VOID, it's to one of the iso_c_binding
1466      procs c_f_pointer or c_f_procpointer, and we need to accept most
1467      pointers the user could give us.  This should allow that.  */
1468   if (formal->ts.type == BT_VOID)
1469     return 1;
1470
1471   if (formal->ts.type == BT_DERIVED
1472       && formal->ts.u.derived && formal->ts.u.derived->ts.is_iso_c
1473       && actual->ts.type == BT_DERIVED
1474       && actual->ts.u.derived && actual->ts.u.derived->ts.is_iso_c)
1475     return 1;
1476
1477   if (formal->ts.type == BT_CLASS && actual->ts.type == BT_DERIVED)
1478     /* Make sure the vtab symbol is present when
1479        the module variables are generated.  */
1480     gfc_find_derived_vtab (actual->ts.u.derived);
1481
1482   if (actual->ts.type == BT_PROCEDURE)
1483     {
1484       char err[200];
1485       gfc_symbol *act_sym = actual->symtree->n.sym;
1486
1487       if (formal->attr.flavor != FL_PROCEDURE)
1488         {
1489           if (where)
1490             gfc_error ("Invalid procedure argument at %L", &actual->where);
1491           return 0;
1492         }
1493
1494       if (!gfc_compare_interfaces (formal, act_sym, act_sym->name, 0, 1, err,
1495                                    sizeof(err)))
1496         {
1497           if (where)
1498             gfc_error ("Interface mismatch in dummy procedure '%s' at %L: %s",
1499                        formal->name, &actual->where, err);
1500           return 0;
1501         }
1502
1503       if (formal->attr.function && !act_sym->attr.function)
1504         {
1505           gfc_add_function (&act_sym->attr, act_sym->name,
1506           &act_sym->declared_at);
1507           if (act_sym->ts.type == BT_UNKNOWN
1508               && gfc_set_default_type (act_sym, 1, act_sym->ns) == FAILURE)
1509             return 0;
1510         }
1511       else if (formal->attr.subroutine && !act_sym->attr.subroutine)
1512         gfc_add_subroutine (&act_sym->attr, act_sym->name,
1513                             &act_sym->declared_at);
1514
1515       return 1;
1516     }
1517
1518   /* F2008, C1241.  */
1519   if (formal->attr.pointer && formal->attr.contiguous
1520       && !gfc_is_simply_contiguous (actual, true))
1521     {
1522       if (where)
1523         gfc_error ("Actual argument to contiguous pointer dummy '%s' at %L "
1524                    "must be simply contigous", formal->name, &actual->where);
1525       return 0;
1526     }
1527
1528   if ((actual->expr_type != EXPR_NULL || actual->ts.type != BT_UNKNOWN)
1529       && actual->ts.type != BT_HOLLERITH
1530       && !gfc_compare_types (&formal->ts, &actual->ts))
1531     {
1532       if (where)
1533         gfc_error ("Type mismatch in argument '%s' at %L; passed %s to %s",
1534                    formal->name, &actual->where, gfc_typename (&actual->ts),
1535                    gfc_typename (&formal->ts));
1536       return 0;
1537     }
1538     
1539   /* F2003, 12.5.2.5.  */
1540   if (formal->ts.type == BT_CLASS
1541       && (CLASS_DATA (formal)->attr.class_pointer
1542           || CLASS_DATA (formal)->attr.allocatable))
1543     {
1544       if (actual->ts.type != BT_CLASS)
1545         {
1546           if (where)
1547             gfc_error ("Actual argument to '%s' at %L must be polymorphic",
1548                         formal->name, &actual->where);
1549           return 0;
1550         }
1551       if (CLASS_DATA (actual)->ts.u.derived
1552           != CLASS_DATA (formal)->ts.u.derived)
1553         {
1554           if (where)
1555             gfc_error ("Actual argument to '%s' at %L must have the same "
1556                        "declared type", formal->name, &actual->where);
1557           return 0;
1558         }
1559     }
1560
1561   if (formal->attr.codimension)
1562     {
1563       gfc_ref *last = NULL;
1564
1565       if (actual->expr_type != EXPR_VARIABLE
1566           || (actual->ref == NULL
1567               && !actual->symtree->n.sym->attr.codimension))
1568         {
1569           if (where)
1570             gfc_error ("Actual argument to '%s' at %L must be a coarray",
1571                        formal->name, &actual->where);
1572           return 0;
1573         }
1574
1575       for (ref = actual->ref; ref; ref = ref->next)
1576         {
1577           if (ref->type == REF_ARRAY && ref->u.ar.codimen != 0)
1578             {
1579               if (where)
1580                 gfc_error ("Actual argument to '%s' at %L must be a coarray "
1581                            "and not coindexed", formal->name, &ref->u.ar.where);
1582               return 0;
1583             }
1584           if (ref->type == REF_ARRAY && ref->u.ar.as->corank
1585               && ref->u.ar.type != AR_FULL && ref->u.ar.dimen != 0)
1586             {
1587               if (where)
1588                 gfc_error ("Actual argument to '%s' at %L must be a coarray "
1589                            "and thus shall not have an array designator",
1590                            formal->name, &ref->u.ar.where);
1591               return 0;
1592             }
1593           if (ref->type == REF_COMPONENT)
1594             last = ref;
1595         }
1596
1597       if (last && !last->u.c.component->attr.codimension)
1598         {
1599           if (where)
1600             gfc_error ("Actual argument to '%s' at %L must be a coarray",
1601                        formal->name, &actual->where);
1602           return 0;
1603         }
1604
1605       /* F2008, 12.5.2.6.  */
1606       if (formal->attr.allocatable &&
1607           ((last && last->u.c.component->as->corank != formal->as->corank)
1608            || (!last
1609                && actual->symtree->n.sym->as->corank != formal->as->corank)))
1610         {
1611           if (where)
1612             gfc_error ("Corank mismatch in argument '%s' at %L (%d and %d)",
1613                    formal->name, &actual->where, formal->as->corank,
1614                    last ? last->u.c.component->as->corank
1615                         : actual->symtree->n.sym->as->corank);
1616           return 0;
1617         }
1618
1619       /* F2008, 12.5.2.8.  */
1620       if (formal->attr.dimension
1621           && (formal->attr.contiguous || formal->as->type != AS_ASSUMED_SHAPE)
1622           && !gfc_is_simply_contiguous (actual, true))
1623         {
1624           if (where)
1625             gfc_error ("Actual argument to '%s' at %L must be simply "
1626                        "contiguous", formal->name, &actual->where);
1627           return 0;
1628         }
1629     }
1630
1631   /* F2008, C1239/C1240.  */
1632   if (actual->expr_type == EXPR_VARIABLE
1633       && (actual->symtree->n.sym->attr.asynchronous
1634          || actual->symtree->n.sym->attr.volatile_)
1635       &&  (formal->attr.asynchronous || formal->attr.volatile_)
1636       && actual->rank && !gfc_is_simply_contiguous (actual, true)
1637       && ((formal->as->type != AS_ASSUMED_SHAPE && !formal->attr.pointer)
1638           || formal->attr.contiguous))
1639     {
1640       if (where)
1641         gfc_error ("Dummy argument '%s' has to be a pointer or assumed-shape "
1642                    "array without CONTIGUOUS attribute - as actual argument at"
1643                    " %L is not simply contiguous and both are ASYNCHRONOUS "
1644                    "or VOLATILE", formal->name, &actual->where);
1645       return 0;
1646     }
1647
1648   if (symbol_rank (formal) == actual->rank)
1649     return 1;
1650
1651   rank_check = where != NULL && !is_elemental && formal->as
1652                && (formal->as->type == AS_ASSUMED_SHAPE
1653                    || formal->as->type == AS_DEFERRED)
1654                && actual->expr_type != EXPR_NULL;
1655
1656   /* Scalar & coindexed, see: F2008, Section 12.5.2.4.  */
1657   if (rank_check || ranks_must_agree
1658       || (formal->attr.pointer && actual->expr_type != EXPR_NULL)
1659       || (actual->rank != 0 && !(is_elemental || formal->attr.dimension))
1660       || (actual->rank == 0 && formal->as->type == AS_ASSUMED_SHAPE
1661           && actual->expr_type != EXPR_NULL)
1662       || (actual->rank == 0 && formal->attr.dimension
1663           && gfc_is_coindexed (actual)))
1664     {
1665       if (where)
1666         argument_rank_mismatch (formal->name, &actual->where,
1667                                 symbol_rank (formal), actual->rank);
1668       return 0;
1669     }
1670   else if (actual->rank != 0 && (is_elemental || formal->attr.dimension))
1671     return 1;
1672
1673   /* At this point, we are considering a scalar passed to an array.   This
1674      is valid (cf. F95 12.4.1.1; F2003 12.4.1.2),
1675      - if the actual argument is (a substring of) an element of a
1676        non-assumed-shape/non-pointer array;
1677      - (F2003) if the actual argument is of type character.  */
1678
1679   for (ref = actual->ref; ref; ref = ref->next)
1680     if (ref->type == REF_ARRAY && ref->u.ar.type == AR_ELEMENT
1681         && ref->u.ar.dimen > 0)
1682       break;
1683
1684   /* Not an array element.  */
1685   if (formal->ts.type == BT_CHARACTER
1686       && (ref == NULL
1687           || (actual->expr_type == EXPR_VARIABLE
1688               && (actual->symtree->n.sym->as->type == AS_ASSUMED_SHAPE
1689                   || actual->symtree->n.sym->attr.pointer))))
1690     {
1691       if (where && (gfc_option.allow_std & GFC_STD_F2003) == 0)
1692         {
1693           gfc_error ("Fortran 2003: Scalar CHARACTER actual argument with "
1694                      "array dummy argument '%s' at %L",
1695                      formal->name, &actual->where);
1696           return 0;
1697         }
1698       else if ((gfc_option.allow_std & GFC_STD_F2003) == 0)
1699         return 0;
1700       else
1701         return 1;
1702     }
1703   else if (ref == NULL && actual->expr_type != EXPR_NULL)
1704     {
1705       if (where)
1706         argument_rank_mismatch (formal->name, &actual->where,
1707                                 symbol_rank (formal), actual->rank);
1708       return 0;
1709     }
1710
1711   if (actual->expr_type == EXPR_VARIABLE
1712       && actual->symtree->n.sym->as
1713       && (actual->symtree->n.sym->as->type == AS_ASSUMED_SHAPE
1714           || actual->symtree->n.sym->attr.pointer))
1715     {
1716       if (where)
1717         gfc_error ("Element of assumed-shaped array passed to dummy "
1718                    "argument '%s' at %L", formal->name, &actual->where);
1719       return 0;
1720     }
1721
1722   return 1;
1723 }
1724
1725
1726 /* Returns the storage size of a symbol (formal argument) or
1727    zero if it cannot be determined.  */
1728
1729 static unsigned long
1730 get_sym_storage_size (gfc_symbol *sym)
1731 {
1732   int i;
1733   unsigned long strlen, elements;
1734
1735   if (sym->ts.type == BT_CHARACTER)
1736     {
1737       if (sym->ts.u.cl && sym->ts.u.cl->length
1738           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
1739         strlen = mpz_get_ui (sym->ts.u.cl->length->value.integer);
1740       else
1741         return 0;
1742     }
1743   else
1744     strlen = 1; 
1745
1746   if (symbol_rank (sym) == 0)
1747     return strlen;
1748
1749   elements = 1;
1750   if (sym->as->type != AS_EXPLICIT)
1751     return 0;
1752   for (i = 0; i < sym->as->rank; i++)
1753     {
1754       if (!sym->as || sym->as->upper[i]->expr_type != EXPR_CONSTANT
1755           || sym->as->lower[i]->expr_type != EXPR_CONSTANT)
1756         return 0;
1757
1758       elements *= mpz_get_si (sym->as->upper[i]->value.integer)
1759                   - mpz_get_si (sym->as->lower[i]->value.integer) + 1L;
1760     }
1761
1762   return strlen*elements;
1763 }
1764
1765
1766 /* Returns the storage size of an expression (actual argument) or
1767    zero if it cannot be determined. For an array element, it returns
1768    the remaining size as the element sequence consists of all storage
1769    units of the actual argument up to the end of the array.  */
1770
1771 static unsigned long
1772 get_expr_storage_size (gfc_expr *e)
1773 {
1774   int i;
1775   long int strlen, elements;
1776   long int substrlen = 0;
1777   bool is_str_storage = false;
1778   gfc_ref *ref;
1779
1780   if (e == NULL)
1781     return 0;
1782   
1783   if (e->ts.type == BT_CHARACTER)
1784     {
1785       if (e->ts.u.cl && e->ts.u.cl->length
1786           && e->ts.u.cl->length->expr_type == EXPR_CONSTANT)
1787         strlen = mpz_get_si (e->ts.u.cl->length->value.integer);
1788       else if (e->expr_type == EXPR_CONSTANT
1789                && (e->ts.u.cl == NULL || e->ts.u.cl->length == NULL))
1790         strlen = e->value.character.length;
1791       else
1792         return 0;
1793     }
1794   else
1795     strlen = 1; /* Length per element.  */
1796
1797   if (e->rank == 0 && !e->ref)
1798     return strlen;
1799
1800   elements = 1;
1801   if (!e->ref)
1802     {
1803       if (!e->shape)
1804         return 0;
1805       for (i = 0; i < e->rank; i++)
1806         elements *= mpz_get_si (e->shape[i]);
1807       return elements*strlen;
1808     }
1809
1810   for (ref = e->ref; ref; ref = ref->next)
1811     {
1812       if (ref->type == REF_SUBSTRING && ref->u.ss.start
1813           && ref->u.ss.start->expr_type == EXPR_CONSTANT)
1814         {
1815           if (is_str_storage)
1816             {
1817               /* The string length is the substring length.
1818                  Set now to full string length.  */
1819               if (ref->u.ss.length == NULL
1820                   || ref->u.ss.length->length->expr_type != EXPR_CONSTANT)
1821                 return 0;
1822
1823               strlen = mpz_get_ui (ref->u.ss.length->length->value.integer);
1824             }
1825           substrlen = strlen - mpz_get_ui (ref->u.ss.start->value.integer) + 1;
1826           continue;
1827         }
1828
1829       if (ref->type == REF_ARRAY && ref->u.ar.type == AR_SECTION
1830           && ref->u.ar.start && ref->u.ar.end && ref->u.ar.stride
1831           && ref->u.ar.as->upper)
1832         for (i = 0; i < ref->u.ar.dimen; i++)
1833           {
1834             long int start, end, stride;
1835             stride = 1;
1836
1837             if (ref->u.ar.stride[i])
1838               {
1839                 if (ref->u.ar.stride[i]->expr_type == EXPR_CONSTANT)
1840                   stride = mpz_get_si (ref->u.ar.stride[i]->value.integer);
1841                 else
1842                   return 0;
1843               }
1844
1845             if (ref->u.ar.start[i])
1846               {
1847                 if (ref->u.ar.start[i]->expr_type == EXPR_CONSTANT)
1848                   start = mpz_get_si (ref->u.ar.start[i]->value.integer);
1849                 else
1850                   return 0;
1851               }
1852             else if (ref->u.ar.as->lower[i]
1853                      && ref->u.ar.as->lower[i]->expr_type == EXPR_CONSTANT)
1854               start = mpz_get_si (ref->u.ar.as->lower[i]->value.integer);
1855             else
1856               return 0;
1857
1858             if (ref->u.ar.end[i])
1859               {
1860                 if (ref->u.ar.end[i]->expr_type == EXPR_CONSTANT)
1861                   end = mpz_get_si (ref->u.ar.end[i]->value.integer);
1862                 else
1863                   return 0;
1864               }
1865             else if (ref->u.ar.as->upper[i]
1866                      && ref->u.ar.as->upper[i]->expr_type == EXPR_CONSTANT)
1867               end = mpz_get_si (ref->u.ar.as->upper[i]->value.integer);
1868             else
1869               return 0;
1870
1871             elements *= (end - start)/stride + 1L;
1872           }
1873       else if (ref->type == REF_ARRAY && ref->u.ar.type == AR_FULL
1874                && ref->u.ar.as->lower && ref->u.ar.as->upper)
1875         for (i = 0; i < ref->u.ar.as->rank; i++)
1876           {
1877             if (ref->u.ar.as->lower[i] && ref->u.ar.as->upper[i]
1878                 && ref->u.ar.as->lower[i]->expr_type == EXPR_CONSTANT
1879                 && ref->u.ar.as->upper[i]->expr_type == EXPR_CONSTANT)
1880               elements *= mpz_get_si (ref->u.ar.as->upper[i]->value.integer)
1881                           - mpz_get_si (ref->u.ar.as->lower[i]->value.integer)
1882                           + 1L;
1883             else
1884               return 0;
1885           }
1886       else if (ref->type == REF_ARRAY && ref->u.ar.type == AR_ELEMENT
1887                && e->expr_type == EXPR_VARIABLE)
1888         {
1889           if (e->symtree->n.sym->as->type == AS_ASSUMED_SHAPE
1890               || e->symtree->n.sym->attr.pointer)
1891             {
1892               elements = 1;
1893               continue;
1894             }
1895
1896           /* Determine the number of remaining elements in the element
1897              sequence for array element designators.  */
1898           is_str_storage = true;
1899           for (i = ref->u.ar.dimen - 1; i >= 0; i--)
1900             {
1901               if (ref->u.ar.start[i] == NULL
1902                   || ref->u.ar.start[i]->expr_type != EXPR_CONSTANT
1903                   || ref->u.ar.as->upper[i] == NULL
1904                   || ref->u.ar.as->lower[i] == NULL
1905                   || ref->u.ar.as->upper[i]->expr_type != EXPR_CONSTANT
1906                   || ref->u.ar.as->lower[i]->expr_type != EXPR_CONSTANT)
1907                 return 0;
1908
1909               elements
1910                    = elements
1911                      * (mpz_get_si (ref->u.ar.as->upper[i]->value.integer)
1912                         - mpz_get_si (ref->u.ar.as->lower[i]->value.integer)
1913                         + 1L)
1914                      - (mpz_get_si (ref->u.ar.start[i]->value.integer)
1915                         - mpz_get_si (ref->u.ar.as->lower[i]->value.integer));
1916             }
1917         }
1918       else
1919         return 0;
1920     }
1921
1922   if (substrlen)
1923     return (is_str_storage) ? substrlen + (elements-1)*strlen
1924                             : elements*strlen;
1925   else
1926     return elements*strlen;
1927 }
1928
1929
1930 /* Given an expression, check whether it is an array section
1931    which has a vector subscript. If it has, one is returned,
1932    otherwise zero.  */
1933
1934 int
1935 gfc_has_vector_subscript (gfc_expr *e)
1936 {
1937   int i;
1938   gfc_ref *ref;
1939
1940   if (e == NULL || e->rank == 0 || e->expr_type != EXPR_VARIABLE)
1941     return 0;
1942
1943   for (ref = e->ref; ref; ref = ref->next)
1944     if (ref->type == REF_ARRAY && ref->u.ar.type == AR_SECTION)
1945       for (i = 0; i < ref->u.ar.dimen; i++)
1946         if (ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
1947           return 1;
1948
1949   return 0;
1950 }
1951
1952
1953 /* Given formal and actual argument lists, see if they are compatible.
1954    If they are compatible, the actual argument list is sorted to
1955    correspond with the formal list, and elements for missing optional
1956    arguments are inserted. If WHERE pointer is nonnull, then we issue
1957    errors when things don't match instead of just returning the status
1958    code.  */
1959
1960 static int
1961 compare_actual_formal (gfc_actual_arglist **ap, gfc_formal_arglist *formal,
1962                        int ranks_must_agree, int is_elemental, locus *where)
1963 {
1964   gfc_actual_arglist **new_arg, *a, *actual, temp;
1965   gfc_formal_arglist *f;
1966   int i, n, na;
1967   unsigned long actual_size, formal_size;
1968
1969   actual = *ap;
1970
1971   if (actual == NULL && formal == NULL)
1972     return 1;
1973
1974   n = 0;
1975   for (f = formal; f; f = f->next)
1976     n++;
1977
1978   new_arg = XALLOCAVEC (gfc_actual_arglist *, n);
1979
1980   for (i = 0; i < n; i++)
1981     new_arg[i] = NULL;
1982
1983   na = 0;
1984   f = formal;
1985   i = 0;
1986
1987   for (a = actual; a; a = a->next, f = f->next)
1988     {
1989       /* Look for keywords but ignore g77 extensions like %VAL.  */
1990       if (a->name != NULL && a->name[0] != '%')
1991         {
1992           i = 0;
1993           for (f = formal; f; f = f->next, i++)
1994             {
1995               if (f->sym == NULL)
1996                 continue;
1997               if (strcmp (f->sym->name, a->name) == 0)
1998                 break;
1999             }
2000
2001           if (f == NULL)
2002             {
2003               if (where)
2004                 gfc_error ("Keyword argument '%s' at %L is not in "
2005                            "the procedure", a->name, &a->expr->where);
2006               return 0;
2007             }
2008
2009           if (new_arg[i] != NULL)
2010             {
2011               if (where)
2012                 gfc_error ("Keyword argument '%s' at %L is already associated "
2013                            "with another actual argument", a->name,
2014                            &a->expr->where);
2015               return 0;
2016             }
2017         }
2018
2019       if (f == NULL)
2020         {
2021           if (where)
2022             gfc_error ("More actual than formal arguments in procedure "
2023                        "call at %L", where);
2024
2025           return 0;
2026         }
2027
2028       if (f->sym == NULL && a->expr == NULL)
2029         goto match;
2030
2031       if (f->sym == NULL)
2032         {
2033           if (where)
2034             gfc_error ("Missing alternate return spec in subroutine call "
2035                        "at %L", where);
2036           return 0;
2037         }
2038
2039       if (a->expr == NULL)
2040         {
2041           if (where)
2042             gfc_error ("Unexpected alternate return spec in subroutine "
2043                        "call at %L", where);
2044           return 0;
2045         }
2046
2047       if (a->expr->expr_type == EXPR_NULL && !f->sym->attr.pointer
2048           && (f->sym->attr.allocatable || !f->sym->attr.optional
2049               || (gfc_option.allow_std & GFC_STD_F2008) == 0))
2050         {
2051           if (where && (f->sym->attr.allocatable || !f->sym->attr.optional))
2052             gfc_error ("Unexpected NULL() intrinsic at %L to dummy '%s'",
2053                        where, f->sym->name);
2054           else if (where)
2055             gfc_error ("Fortran 2008: Null pointer at %L to non-pointer "
2056                        "dummy '%s'", where, f->sym->name);
2057
2058           return 0;
2059         }
2060       
2061       if (!compare_parameter (f->sym, a->expr, ranks_must_agree,
2062                               is_elemental, where))
2063         return 0;
2064
2065       /* Special case for character arguments.  For allocatable, pointer
2066          and assumed-shape dummies, the string length needs to match
2067          exactly.  */
2068       if (a->expr->ts.type == BT_CHARACTER
2069            && a->expr->ts.u.cl && a->expr->ts.u.cl->length
2070            && a->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT
2071            && f->sym->ts.u.cl && f->sym->ts.u.cl && f->sym->ts.u.cl->length
2072            && f->sym->ts.u.cl->length->expr_type == EXPR_CONSTANT
2073            && (f->sym->attr.pointer || f->sym->attr.allocatable
2074                || (f->sym->as && f->sym->as->type == AS_ASSUMED_SHAPE))
2075            && (mpz_cmp (a->expr->ts.u.cl->length->value.integer,
2076                         f->sym->ts.u.cl->length->value.integer) != 0))
2077          {
2078            if (where && (f->sym->attr.pointer || f->sym->attr.allocatable))
2079              gfc_warning ("Character length mismatch (%ld/%ld) between actual "
2080                           "argument and pointer or allocatable dummy argument "
2081                           "'%s' at %L",
2082                           mpz_get_si (a->expr->ts.u.cl->length->value.integer),
2083                           mpz_get_si (f->sym->ts.u.cl->length->value.integer),
2084                           f->sym->name, &a->expr->where);
2085            else if (where)
2086              gfc_warning ("Character length mismatch (%ld/%ld) between actual "
2087                           "argument and assumed-shape dummy argument '%s' "
2088                           "at %L",
2089                           mpz_get_si (a->expr->ts.u.cl->length->value.integer),
2090                           mpz_get_si (f->sym->ts.u.cl->length->value.integer),
2091                           f->sym->name, &a->expr->where);
2092            return 0;
2093          }
2094
2095       actual_size = get_expr_storage_size (a->expr);
2096       formal_size = get_sym_storage_size (f->sym);
2097       if (actual_size != 0
2098             && actual_size < formal_size
2099             && a->expr->ts.type != BT_PROCEDURE)
2100         {
2101           if (a->expr->ts.type == BT_CHARACTER && !f->sym->as && where)
2102             gfc_warning ("Character length of actual argument shorter "
2103                         "than of dummy argument '%s' (%lu/%lu) at %L",
2104                         f->sym->name, actual_size, formal_size,
2105                         &a->expr->where);
2106           else if (where)
2107             gfc_warning ("Actual argument contains too few "
2108                         "elements for dummy argument '%s' (%lu/%lu) at %L",
2109                         f->sym->name, actual_size, formal_size,
2110                         &a->expr->where);
2111           return  0;
2112         }
2113
2114       /* Satisfy 12.4.1.3 by ensuring that a procedure pointer actual argument
2115          is provided for a procedure pointer formal argument.  */
2116       if (f->sym->attr.proc_pointer
2117           && !((a->expr->expr_type == EXPR_VARIABLE
2118                 && a->expr->symtree->n.sym->attr.proc_pointer)
2119                || (a->expr->expr_type == EXPR_FUNCTION
2120                    && a->expr->symtree->n.sym->result->attr.proc_pointer)
2121                || gfc_is_proc_ptr_comp (a->expr, NULL)))
2122         {
2123           if (where)
2124             gfc_error ("Expected a procedure pointer for argument '%s' at %L",
2125                        f->sym->name, &a->expr->where);
2126           return 0;
2127         }
2128
2129       /* Satisfy 12.4.1.2 by ensuring that a procedure actual argument is
2130          provided for a procedure formal argument.  */
2131       if (a->expr->ts.type != BT_PROCEDURE && !gfc_is_proc_ptr_comp (a->expr, NULL)
2132           && a->expr->expr_type == EXPR_VARIABLE
2133           && f->sym->attr.flavor == FL_PROCEDURE)
2134         {
2135           if (where)
2136             gfc_error ("Expected a procedure for argument '%s' at %L",
2137                        f->sym->name, &a->expr->where);
2138           return 0;
2139         }
2140
2141       if (f->sym->attr.flavor == FL_PROCEDURE && f->sym->attr.pure
2142           && a->expr->ts.type == BT_PROCEDURE
2143           && !a->expr->symtree->n.sym->attr.pure)
2144         {
2145           if (where)
2146             gfc_error ("Expected a PURE procedure for argument '%s' at %L",
2147                        f->sym->name, &a->expr->where);
2148           return 0;
2149         }
2150
2151       if (f->sym->as && f->sym->as->type == AS_ASSUMED_SHAPE
2152           && a->expr->expr_type == EXPR_VARIABLE
2153           && a->expr->symtree->n.sym->as
2154           && a->expr->symtree->n.sym->as->type == AS_ASSUMED_SIZE
2155           && (a->expr->ref == NULL
2156               || (a->expr->ref->type == REF_ARRAY
2157                   && a->expr->ref->u.ar.type == AR_FULL)))
2158         {
2159           if (where)
2160             gfc_error ("Actual argument for '%s' cannot be an assumed-size"
2161                        " array at %L", f->sym->name, where);
2162           return 0;
2163         }
2164
2165       if (a->expr->expr_type != EXPR_NULL
2166           && compare_pointer (f->sym, a->expr) == 0)
2167         {
2168           if (where)
2169             gfc_error ("Actual argument for '%s' must be a pointer at %L",
2170                        f->sym->name, &a->expr->where);
2171           return 0;
2172         }
2173
2174       if (a->expr->expr_type != EXPR_NULL
2175           && (gfc_option.allow_std & GFC_STD_F2008) == 0
2176           && compare_pointer (f->sym, a->expr) == 2)
2177         {
2178           if (where)
2179             gfc_error ("Fortran 2008: Non-pointer actual argument at %L to "
2180                        "pointer dummy '%s'", &a->expr->where,f->sym->name);
2181           return 0;
2182         }
2183         
2184
2185       /* Fortran 2008, C1242.  */
2186       if (f->sym->attr.pointer && gfc_is_coindexed (a->expr))
2187         {
2188           if (where)
2189             gfc_error ("Coindexed actual argument at %L to pointer "
2190                        "dummy '%s'",
2191                        &a->expr->where, f->sym->name);
2192           return 0;
2193         }
2194
2195       /* Fortran 2008, 12.5.2.5 (no constraint).  */
2196       if (a->expr->expr_type == EXPR_VARIABLE
2197           && f->sym->attr.intent != INTENT_IN
2198           && f->sym->attr.allocatable
2199           && gfc_is_coindexed (a->expr))
2200         {
2201           if (where)
2202             gfc_error ("Coindexed actual argument at %L to allocatable "
2203                        "dummy '%s' requires INTENT(IN)",
2204                        &a->expr->where, f->sym->name);
2205           return 0;
2206         }
2207
2208       /* Fortran 2008, C1237.  */
2209       if (a->expr->expr_type == EXPR_VARIABLE
2210           && (f->sym->attr.asynchronous || f->sym->attr.volatile_)
2211           && gfc_is_coindexed (a->expr)
2212           && (a->expr->symtree->n.sym->attr.volatile_
2213               || a->expr->symtree->n.sym->attr.asynchronous))
2214         {
2215           if (where)
2216             gfc_error ("Coindexed ASYNCHRONOUS or VOLATILE actual argument at "
2217                        "at %L requires that dummy %s' has neither "
2218                        "ASYNCHRONOUS nor VOLATILE", &a->expr->where,
2219                        f->sym->name);
2220           return 0;
2221         }
2222
2223       /* Fortran 2008, 12.5.2.4 (no constraint).  */
2224       if (a->expr->expr_type == EXPR_VARIABLE
2225           && f->sym->attr.intent != INTENT_IN && !f->sym->attr.value
2226           && gfc_is_coindexed (a->expr)
2227           && gfc_has_ultimate_allocatable (a->expr))
2228         {
2229           if (where)
2230             gfc_error ("Coindexed actual argument at %L with allocatable "
2231                        "ultimate component to dummy '%s' requires either VALUE "
2232                        "or INTENT(IN)", &a->expr->where, f->sym->name);
2233           return 0;
2234         }
2235
2236       if (a->expr->expr_type != EXPR_NULL
2237           && compare_allocatable (f->sym, a->expr) == 0)
2238         {
2239           if (where)
2240             gfc_error ("Actual argument for '%s' must be ALLOCATABLE at %L",
2241                        f->sym->name, &a->expr->where);
2242           return 0;
2243         }
2244
2245       /* Check intent = OUT/INOUT for definable actual argument.  */
2246       if ((f->sym->attr.intent == INTENT_OUT
2247           || f->sym->attr.intent == INTENT_INOUT))
2248         {
2249           const char* context = (where
2250                                  ? _("actual argument to INTENT = OUT/INOUT")
2251                                  : NULL);
2252
2253           if (f->sym->attr.pointer
2254               && gfc_check_vardef_context (a->expr, true, context)
2255                    == FAILURE)
2256             return 0;
2257           if (gfc_check_vardef_context (a->expr, false, context)
2258                 == FAILURE)
2259             return 0;
2260         }
2261
2262       if ((f->sym->attr.intent == INTENT_OUT
2263            || f->sym->attr.intent == INTENT_INOUT
2264            || f->sym->attr.volatile_
2265            || f->sym->attr.asynchronous)
2266           && gfc_has_vector_subscript (a->expr))
2267         {
2268           if (where)
2269             gfc_error ("Array-section actual argument with vector "
2270                        "subscripts at %L is incompatible with INTENT(OUT), "
2271                        "INTENT(INOUT), VOLATILE or ASYNCHRONOUS attribute "
2272                        "of the dummy argument '%s'",
2273                        &a->expr->where, f->sym->name);
2274           return 0;
2275         }
2276
2277       /* C1232 (R1221) For an actual argument which is an array section or
2278          an assumed-shape array, the dummy argument shall be an assumed-
2279          shape array, if the dummy argument has the VOLATILE attribute.  */
2280
2281       if (f->sym->attr.volatile_
2282           && a->expr->symtree->n.sym->as
2283           && a->expr->symtree->n.sym->as->type == AS_ASSUMED_SHAPE
2284           && !(f->sym->as && f->sym->as->type == AS_ASSUMED_SHAPE))
2285         {
2286           if (where)
2287             gfc_error ("Assumed-shape actual argument at %L is "
2288                        "incompatible with the non-assumed-shape "
2289                        "dummy argument '%s' due to VOLATILE attribute",
2290                        &a->expr->where,f->sym->name);
2291           return 0;
2292         }
2293
2294       if (f->sym->attr.volatile_
2295           && a->expr->ref && a->expr->ref->u.ar.type == AR_SECTION
2296           && !(f->sym->as && f->sym->as->type == AS_ASSUMED_SHAPE))
2297         {
2298           if (where)
2299             gfc_error ("Array-section actual argument at %L is "
2300                        "incompatible with the non-assumed-shape "
2301                        "dummy argument '%s' due to VOLATILE attribute",
2302                        &a->expr->where,f->sym->name);
2303           return 0;
2304         }
2305
2306       /* C1233 (R1221) For an actual argument which is a pointer array, the
2307          dummy argument shall be an assumed-shape or pointer array, if the
2308          dummy argument has the VOLATILE attribute.  */
2309
2310       if (f->sym->attr.volatile_
2311           && a->expr->symtree->n.sym->attr.pointer
2312           && a->expr->symtree->n.sym->as
2313           && !(f->sym->as
2314                && (f->sym->as->type == AS_ASSUMED_SHAPE
2315                    || f->sym->attr.pointer)))
2316         {
2317           if (where)
2318             gfc_error ("Pointer-array actual argument at %L requires "
2319                        "an assumed-shape or pointer-array dummy "
2320                        "argument '%s' due to VOLATILE attribute",
2321                        &a->expr->where,f->sym->name);
2322           return 0;
2323         }
2324
2325     match:
2326       if (a == actual)
2327         na = i;
2328
2329       new_arg[i++] = a;
2330     }
2331
2332   /* Make sure missing actual arguments are optional.  */
2333   i = 0;
2334   for (f = formal; f; f = f->next, i++)
2335     {
2336       if (new_arg[i] != NULL)
2337         continue;
2338       if (f->sym == NULL)
2339         {
2340           if (where)
2341             gfc_error ("Missing alternate return spec in subroutine call "
2342                        "at %L", where);
2343           return 0;
2344         }
2345       if (!f->sym->attr.optional)
2346         {
2347           if (where)
2348             gfc_error ("Missing actual argument for argument '%s' at %L",
2349                        f->sym->name, where);
2350           return 0;
2351         }
2352     }
2353
2354   /* The argument lists are compatible.  We now relink a new actual
2355      argument list with null arguments in the right places.  The head
2356      of the list remains the head.  */
2357   for (i = 0; i < n; i++)
2358     if (new_arg[i] == NULL)
2359       new_arg[i] = gfc_get_actual_arglist ();
2360
2361   if (na != 0)
2362     {
2363       temp = *new_arg[0];
2364       *new_arg[0] = *actual;
2365       *actual = temp;
2366
2367       a = new_arg[0];
2368       new_arg[0] = new_arg[na];
2369       new_arg[na] = a;
2370     }
2371
2372   for (i = 0; i < n - 1; i++)
2373     new_arg[i]->next = new_arg[i + 1];
2374
2375   new_arg[i]->next = NULL;
2376
2377   if (*ap == NULL && n > 0)
2378     *ap = new_arg[0];
2379
2380   /* Note the types of omitted optional arguments.  */
2381   for (a = *ap, f = formal; a; a = a->next, f = f->next)
2382     if (a->expr == NULL && a->label == NULL)
2383       a->missing_arg_type = f->sym->ts.type;
2384
2385   return 1;
2386 }
2387
2388
2389 typedef struct
2390 {
2391   gfc_formal_arglist *f;
2392   gfc_actual_arglist *a;
2393 }
2394 argpair;
2395
2396 /* qsort comparison function for argument pairs, with the following
2397    order:
2398     - p->a->expr == NULL
2399     - p->a->expr->expr_type != EXPR_VARIABLE
2400     - growing p->a->expr->symbol.  */
2401
2402 static int
2403 pair_cmp (const void *p1, const void *p2)
2404 {
2405   const gfc_actual_arglist *a1, *a2;
2406
2407   /* *p1 and *p2 are elements of the to-be-sorted array.  */
2408   a1 = ((const argpair *) p1)->a;
2409   a2 = ((const argpair *) p2)->a;
2410   if (!a1->expr)
2411     {
2412       if (!a2->expr)
2413         return 0;
2414       return -1;
2415     }
2416   if (!a2->expr)
2417     return 1;
2418   if (a1->expr->expr_type != EXPR_VARIABLE)
2419     {
2420       if (a2->expr->expr_type != EXPR_VARIABLE)
2421         return 0;
2422       return -1;
2423     }
2424   if (a2->expr->expr_type != EXPR_VARIABLE)
2425     return 1;
2426   return a1->expr->symtree->n.sym < a2->expr->symtree->n.sym;
2427 }
2428
2429
2430 /* Given two expressions from some actual arguments, test whether they
2431    refer to the same expression. The analysis is conservative.
2432    Returning FAILURE will produce no warning.  */
2433
2434 static gfc_try
2435 compare_actual_expr (gfc_expr *e1, gfc_expr *e2)
2436 {
2437   const gfc_ref *r1, *r2;
2438
2439   if (!e1 || !e2
2440       || e1->expr_type != EXPR_VARIABLE
2441       || e2->expr_type != EXPR_VARIABLE
2442       || e1->symtree->n.sym != e2->symtree->n.sym)
2443     return FAILURE;
2444
2445   /* TODO: improve comparison, see expr.c:show_ref().  */
2446   for (r1 = e1->ref, r2 = e2->ref; r1 && r2; r1 = r1->next, r2 = r2->next)
2447     {
2448       if (r1->type != r2->type)
2449         return FAILURE;
2450       switch (r1->type)
2451         {
2452         case REF_ARRAY:
2453           if (r1->u.ar.type != r2->u.ar.type)
2454             return FAILURE;
2455           /* TODO: At the moment, consider only full arrays;
2456              we could do better.  */
2457           if (r1->u.ar.type != AR_FULL || r2->u.ar.type != AR_FULL)
2458             return FAILURE;
2459           break;
2460
2461         case REF_COMPONENT:
2462           if (r1->u.c.component != r2->u.c.component)
2463             return FAILURE;
2464           break;
2465
2466         case REF_SUBSTRING:
2467           return FAILURE;
2468
2469         default:
2470           gfc_internal_error ("compare_actual_expr(): Bad component code");
2471         }
2472     }
2473   if (!r1 && !r2)
2474     return SUCCESS;
2475   return FAILURE;
2476 }
2477
2478
2479 /* Given formal and actual argument lists that correspond to one
2480    another, check that identical actual arguments aren't not
2481    associated with some incompatible INTENTs.  */
2482
2483 static gfc_try
2484 check_some_aliasing (gfc_formal_arglist *f, gfc_actual_arglist *a)
2485 {
2486   sym_intent f1_intent, f2_intent;
2487   gfc_formal_arglist *f1;
2488   gfc_actual_arglist *a1;
2489   size_t n, i, j;
2490   argpair *p;
2491   gfc_try t = SUCCESS;
2492
2493   n = 0;
2494   for (f1 = f, a1 = a;; f1 = f1->next, a1 = a1->next)
2495     {
2496       if (f1 == NULL && a1 == NULL)
2497         break;
2498       if (f1 == NULL || a1 == NULL)
2499         gfc_internal_error ("check_some_aliasing(): List mismatch");
2500       n++;
2501     }
2502   if (n == 0)
2503     return t;
2504   p = XALLOCAVEC (argpair, n);
2505
2506   for (i = 0, f1 = f, a1 = a; i < n; i++, f1 = f1->next, a1 = a1->next)
2507     {
2508       p[i].f = f1;
2509       p[i].a = a1;
2510     }
2511
2512   qsort (p, n, sizeof (argpair), pair_cmp);
2513
2514   for (i = 0; i < n; i++)
2515     {
2516       if (!p[i].a->expr
2517           || p[i].a->expr->expr_type != EXPR_VARIABLE
2518           || p[i].a->expr->ts.type == BT_PROCEDURE)
2519         continue;
2520       f1_intent = p[i].f->sym->attr.intent;
2521       for (j = i + 1; j < n; j++)
2522         {
2523           /* Expected order after the sort.  */
2524           if (!p[j].a->expr || p[j].a->expr->expr_type != EXPR_VARIABLE)
2525             gfc_internal_error ("check_some_aliasing(): corrupted data");
2526
2527           /* Are the expression the same?  */
2528           if (compare_actual_expr (p[i].a->expr, p[j].a->expr) == FAILURE)
2529             break;
2530           f2_intent = p[j].f->sym->attr.intent;
2531           if ((f1_intent == INTENT_IN && f2_intent == INTENT_OUT)
2532               || (f1_intent == INTENT_OUT && f2_intent == INTENT_IN))
2533             {
2534               gfc_warning ("Same actual argument associated with INTENT(%s) "
2535                            "argument '%s' and INTENT(%s) argument '%s' at %L",
2536                            gfc_intent_string (f1_intent), p[i].f->sym->name,
2537                            gfc_intent_string (f2_intent), p[j].f->sym->name,
2538                            &p[i].a->expr->where);
2539               t = FAILURE;
2540             }
2541         }
2542     }
2543
2544   return t;
2545 }
2546
2547
2548 /* Given a symbol of a formal argument list and an expression,
2549    return nonzero if their intents are compatible, zero otherwise.  */
2550
2551 static int
2552 compare_parameter_intent (gfc_symbol *formal, gfc_expr *actual)
2553 {
2554   if (actual->symtree->n.sym->attr.pointer && !formal->attr.pointer)
2555     return 1;
2556
2557   if (actual->symtree->n.sym->attr.intent != INTENT_IN)
2558     return 1;
2559
2560   if (formal->attr.intent == INTENT_INOUT || formal->attr.intent == INTENT_OUT)
2561     return 0;
2562
2563   return 1;
2564 }
2565
2566
2567 /* Given formal and actual argument lists that correspond to one
2568    another, check that they are compatible in the sense that intents
2569    are not mismatched.  */
2570
2571 static gfc_try
2572 check_intents (gfc_formal_arglist *f, gfc_actual_arglist *a)
2573 {
2574   sym_intent f_intent;
2575
2576   for (;; f = f->next, a = a->next)
2577     {
2578       if (f == NULL && a == NULL)
2579         break;
2580       if (f == NULL || a == NULL)
2581         gfc_internal_error ("check_intents(): List mismatch");
2582
2583       if (a->expr == NULL || a->expr->expr_type != EXPR_VARIABLE)
2584         continue;
2585
2586       f_intent = f->sym->attr.intent;
2587
2588       if (!compare_parameter_intent(f->sym, a->expr))
2589         {
2590           gfc_error ("Procedure argument at %L is INTENT(IN) while interface "
2591                      "specifies INTENT(%s)", &a->expr->where,
2592                      gfc_intent_string (f_intent));
2593           return FAILURE;
2594         }
2595
2596       if (gfc_pure (NULL) && gfc_impure_variable (a->expr->symtree->n.sym))
2597         {
2598           if (f_intent == INTENT_INOUT || f_intent == INTENT_OUT)
2599             {
2600               gfc_error ("Procedure argument at %L is local to a PURE "
2601                          "procedure and is passed to an INTENT(%s) argument",
2602                          &a->expr->where, gfc_intent_string (f_intent));
2603               return FAILURE;
2604             }
2605
2606           if (f->sym->attr.pointer)
2607             {
2608               gfc_error ("Procedure argument at %L is local to a PURE "
2609                          "procedure and has the POINTER attribute",
2610                          &a->expr->where);
2611               return FAILURE;
2612             }
2613         }
2614
2615        /* Fortran 2008, C1283.  */
2616        if (gfc_pure (NULL) && gfc_is_coindexed (a->expr))
2617         {
2618           if (f_intent == INTENT_INOUT || f_intent == INTENT_OUT)
2619             {
2620               gfc_error ("Coindexed actual argument at %L in PURE procedure "
2621                          "is passed to an INTENT(%s) argument",
2622                          &a->expr->where, gfc_intent_string (f_intent));
2623               return FAILURE;
2624             }
2625
2626           if (f->sym->attr.pointer)
2627             {
2628               gfc_error ("Coindexed actual argument at %L in PURE procedure "
2629                          "is passed to a POINTER dummy argument",
2630                          &a->expr->where);
2631               return FAILURE;
2632             }
2633         }
2634
2635        /* F2008, Section 12.5.2.4.  */
2636        if (a->expr->ts.type == BT_CLASS && f->sym->ts.type == BT_CLASS
2637            && gfc_is_coindexed (a->expr))
2638          {
2639            gfc_error ("Coindexed polymorphic actual argument at %L is passed "
2640                       "polymorphic dummy argument '%s'",
2641                          &a->expr->where, f->sym->name);
2642            return FAILURE;
2643          }
2644     }
2645
2646   return SUCCESS;
2647 }
2648
2649
2650 /* Check how a procedure is used against its interface.  If all goes
2651    well, the actual argument list will also end up being properly
2652    sorted.  */
2653
2654 void
2655 gfc_procedure_use (gfc_symbol *sym, gfc_actual_arglist **ap, locus *where)
2656 {
2657
2658   /* Warn about calls with an implicit interface.  Special case
2659      for calling a ISO_C_BINDING becase c_loc and c_funloc
2660      are pseudo-unknown.  Additionally, warn about procedures not
2661      explicitly declared at all if requested.  */
2662   if (sym->attr.if_source == IFSRC_UNKNOWN && ! sym->attr.is_iso_c)
2663     {
2664       if (gfc_option.warn_implicit_interface)
2665         gfc_warning ("Procedure '%s' called with an implicit interface at %L",
2666                      sym->name, where);
2667       else if (gfc_option.warn_implicit_procedure
2668                && sym->attr.proc == PROC_UNKNOWN)
2669         gfc_warning ("Procedure '%s' called at %L is not explicitly declared",
2670                      sym->name, where);
2671     }
2672
2673   if (sym->attr.if_source == IFSRC_UNKNOWN)
2674     {
2675       gfc_actual_arglist *a;
2676       for (a = *ap; a; a = a->next)
2677         {
2678           /* Skip g77 keyword extensions like %VAL, %REF, %LOC.  */
2679           if (a->name != NULL && a->name[0] != '%')
2680             {
2681               gfc_error("Keyword argument requires explicit interface "
2682                         "for procedure '%s' at %L", sym->name, &a->expr->where);
2683               break;
2684             }
2685         }
2686
2687       return;
2688     }
2689
2690   if (!compare_actual_formal (ap, sym->formal, 0, sym->attr.elemental, where))
2691     return;
2692
2693   check_intents (sym->formal, *ap);
2694   if (gfc_option.warn_aliasing)
2695     check_some_aliasing (sym->formal, *ap);
2696 }
2697
2698
2699 /* Check how a procedure pointer component is used against its interface.
2700    If all goes well, the actual argument list will also end up being properly
2701    sorted. Completely analogous to gfc_procedure_use.  */
2702
2703 void
2704 gfc_ppc_use (gfc_component *comp, gfc_actual_arglist **ap, locus *where)
2705 {
2706
2707   /* Warn about calls with an implicit interface.  Special case
2708      for calling a ISO_C_BINDING becase c_loc and c_funloc
2709      are pseudo-unknown.  */
2710   if (gfc_option.warn_implicit_interface
2711       && comp->attr.if_source == IFSRC_UNKNOWN
2712       && !comp->attr.is_iso_c)
2713     gfc_warning ("Procedure pointer component '%s' called with an implicit "
2714                  "interface at %L", comp->name, where);
2715
2716   if (comp->attr.if_source == IFSRC_UNKNOWN)
2717     {
2718       gfc_actual_arglist *a;
2719       for (a = *ap; a; a = a->next)
2720         {
2721           /* Skip g77 keyword extensions like %VAL, %REF, %LOC.  */
2722           if (a->name != NULL && a->name[0] != '%')
2723             {
2724               gfc_error("Keyword argument requires explicit interface "
2725                         "for procedure pointer component '%s' at %L",
2726                         comp->name, &a->expr->where);
2727               break;
2728             }
2729         }
2730
2731       return;
2732     }
2733
2734   if (!compare_actual_formal (ap, comp->formal, 0, comp->attr.elemental, where))
2735     return;
2736
2737   check_intents (comp->formal, *ap);
2738   if (gfc_option.warn_aliasing)
2739     check_some_aliasing (comp->formal, *ap);
2740 }
2741
2742
2743 /* Try if an actual argument list matches the formal list of a symbol,
2744    respecting the symbol's attributes like ELEMENTAL.  This is used for
2745    GENERIC resolution.  */
2746
2747 bool
2748 gfc_arglist_matches_symbol (gfc_actual_arglist** args, gfc_symbol* sym)
2749 {
2750   bool r;
2751
2752   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
2753
2754   r = !sym->attr.elemental;
2755   if (compare_actual_formal (args, sym->formal, r, !r, NULL))
2756     {
2757       check_intents (sym->formal, *args);
2758       if (gfc_option.warn_aliasing)
2759         check_some_aliasing (sym->formal, *args);
2760       return true;
2761     }
2762
2763   return false;
2764 }
2765
2766
2767 /* Given an interface pointer and an actual argument list, search for
2768    a formal argument list that matches the actual.  If found, returns
2769    a pointer to the symbol of the correct interface.  Returns NULL if
2770    not found.  */
2771
2772 gfc_symbol *
2773 gfc_search_interface (gfc_interface *intr, int sub_flag,
2774                       gfc_actual_arglist **ap)
2775 {
2776   gfc_symbol *elem_sym = NULL;
2777   for (; intr; intr = intr->next)
2778     {
2779       if (sub_flag && intr->sym->attr.function)
2780         continue;
2781       if (!sub_flag && intr->sym->attr.subroutine)
2782         continue;
2783
2784       if (gfc_arglist_matches_symbol (ap, intr->sym))
2785         {
2786           /* Satisfy 12.4.4.1 such that an elemental match has lower
2787              weight than a non-elemental match.  */ 
2788           if (intr->sym->attr.elemental)
2789             {
2790               elem_sym = intr->sym;
2791               continue;
2792             }
2793           return intr->sym;
2794         }
2795     }
2796
2797   return elem_sym ? elem_sym : NULL;
2798 }
2799
2800
2801 /* Do a brute force recursive search for a symbol.  */
2802
2803 static gfc_symtree *
2804 find_symtree0 (gfc_symtree *root, gfc_symbol *sym)
2805 {
2806   gfc_symtree * st;
2807
2808   if (root->n.sym == sym)
2809     return root;
2810
2811   st = NULL;
2812   if (root->left)
2813     st = find_symtree0 (root->left, sym);
2814   if (root->right && ! st)
2815     st = find_symtree0 (root->right, sym);
2816   return st;
2817 }
2818
2819
2820 /* Find a symtree for a symbol.  */
2821
2822 gfc_symtree *
2823 gfc_find_sym_in_symtree (gfc_symbol *sym)
2824 {
2825   gfc_symtree *st;
2826   gfc_namespace *ns;
2827
2828   /* First try to find it by name.  */
2829   gfc_find_sym_tree (sym->name, gfc_current_ns, 1, &st);
2830   if (st && st->n.sym == sym)
2831     return st;
2832
2833   /* If it's been renamed, resort to a brute-force search.  */
2834   /* TODO: avoid having to do this search.  If the symbol doesn't exist
2835      in the symtree for the current namespace, it should probably be added.  */
2836   for (ns = gfc_current_ns; ns; ns = ns->parent)
2837     {
2838       st = find_symtree0 (ns->sym_root, sym);
2839       if (st)
2840         return st;
2841     }
2842   gfc_internal_error ("Unable to find symbol %s", sym->name);
2843   /* Not reached.  */
2844 }
2845
2846
2847 /* See if the arglist to an operator-call contains a derived-type argument
2848    with a matching type-bound operator.  If so, return the matching specific
2849    procedure defined as operator-target as well as the base-object to use
2850    (which is the found derived-type argument with operator).  The generic
2851    name, if any, is transmitted to the final expression via 'gname'.  */
2852
2853 static gfc_typebound_proc*
2854 matching_typebound_op (gfc_expr** tb_base,
2855                        gfc_actual_arglist* args,
2856                        gfc_intrinsic_op op, const char* uop,
2857                        const char ** gname)
2858 {
2859   gfc_actual_arglist* base;
2860
2861   for (base = args; base; base = base->next)
2862     if (base->expr->ts.type == BT_DERIVED || base->expr->ts.type == BT_CLASS)
2863       {
2864         gfc_typebound_proc* tb;
2865         gfc_symbol* derived;
2866         gfc_try result;
2867
2868         if (base->expr->ts.type == BT_CLASS)
2869           derived = CLASS_DATA (base->expr)->ts.u.derived;
2870         else
2871           derived = base->expr->ts.u.derived;
2872
2873         if (op == INTRINSIC_USER)
2874           {
2875             gfc_symtree* tb_uop;
2876
2877             gcc_assert (uop);
2878             tb_uop = gfc_find_typebound_user_op (derived, &result, uop,
2879                                                  false, NULL);
2880
2881             if (tb_uop)
2882               tb = tb_uop->n.tb;
2883             else
2884               tb = NULL;
2885           }
2886         else
2887           tb = gfc_find_typebound_intrinsic_op (derived, &result, op,
2888                                                 false, NULL);
2889
2890         /* This means we hit a PRIVATE operator which is use-associated and
2891            should thus not be seen.  */
2892         if (result == FAILURE)
2893           tb = NULL;
2894
2895         /* Look through the super-type hierarchy for a matching specific
2896            binding.  */
2897         for (; tb; tb = tb->overridden)
2898           {
2899             gfc_tbp_generic* g;
2900
2901             gcc_assert (tb->is_generic);
2902             for (g = tb->u.generic; g; g = g->next)
2903               {
2904                 gfc_symbol* target;
2905                 gfc_actual_arglist* argcopy;
2906                 bool matches;
2907
2908                 gcc_assert (g->specific);
2909                 if (g->specific->error)
2910                   continue;
2911
2912                 target = g->specific->u.specific->n.sym;
2913
2914                 /* Check if this arglist matches the formal.  */
2915                 argcopy = gfc_copy_actual_arglist (args);
2916                 matches = gfc_arglist_matches_symbol (&argcopy, target);
2917                 gfc_free_actual_arglist (argcopy);
2918
2919                 /* Return if we found a match.  */
2920                 if (matches)
2921                   {
2922                     *tb_base = base->expr;
2923                     *gname = g->specific_st->name;
2924                     return g->specific;
2925                   }
2926               }
2927           }
2928       }
2929
2930   return NULL;
2931 }
2932
2933
2934 /* For the 'actual arglist' of an operator call and a specific typebound
2935    procedure that has been found the target of a type-bound operator, build the
2936    appropriate EXPR_COMPCALL and resolve it.  We take this indirection over
2937    type-bound procedures rather than resolving type-bound operators 'directly'
2938    so that we can reuse the existing logic.  */
2939
2940 static void
2941 build_compcall_for_operator (gfc_expr* e, gfc_actual_arglist* actual,
2942                              gfc_expr* base, gfc_typebound_proc* target,
2943                              const char *gname)
2944 {
2945   e->expr_type = EXPR_COMPCALL;
2946   e->value.compcall.tbp = target;
2947   e->value.compcall.name = gname ? gname : "$op";
2948   e->value.compcall.actual = actual;
2949   e->value.compcall.base_object = base;
2950   e->value.compcall.ignore_pass = 1;
2951   e->value.compcall.assign = 0;
2952 }
2953
2954
2955 /* This subroutine is called when an expression is being resolved.
2956    The expression node in question is either a user defined operator
2957    or an intrinsic operator with arguments that aren't compatible
2958    with the operator.  This subroutine builds an actual argument list
2959    corresponding to the operands, then searches for a compatible
2960    interface.  If one is found, the expression node is replaced with
2961    the appropriate function call.
2962    real_error is an additional output argument that specifies if FAILURE
2963    is because of some real error and not because no match was found.  */
2964
2965 gfc_try
2966 gfc_extend_expr (gfc_expr *e, bool *real_error)
2967 {
2968   gfc_actual_arglist *actual;
2969   gfc_symbol *sym;
2970   gfc_namespace *ns;
2971   gfc_user_op *uop;
2972   gfc_intrinsic_op i;
2973   const char *gname;
2974
2975   sym = NULL;
2976
2977   actual = gfc_get_actual_arglist ();
2978   actual->expr = e->value.op.op1;
2979
2980   *real_error = false;
2981   gname = NULL;
2982
2983   if (e->value.op.op2 != NULL)
2984     {
2985       actual->next = gfc_get_actual_arglist ();
2986       actual->next->expr = e->value.op.op2;
2987     }
2988
2989   i = fold_unary_intrinsic (e->value.op.op);
2990
2991   if (i == INTRINSIC_USER)
2992     {
2993       for (ns = gfc_current_ns; ns; ns = ns->parent)
2994         {
2995           uop = gfc_find_uop (e->value.op.uop->name, ns);
2996           if (uop == NULL)
2997             continue;
2998
2999           sym = gfc_search_interface (uop->op, 0, &actual);
3000           if (sym != NULL)
3001             break;
3002         }
3003     }
3004   else
3005     {
3006       for (ns = gfc_current_ns; ns; ns = ns->parent)
3007         {
3008           /* Due to the distinction between '==' and '.eq.' and friends, one has
3009              to check if either is defined.  */
3010           switch (i)
3011             {
3012 #define CHECK_OS_COMPARISON(comp) \
3013   case INTRINSIC_##comp: \
3014   case INTRINSIC_##comp##_OS: \
3015     sym = gfc_search_interface (ns->op[INTRINSIC_##comp], 0, &actual); \
3016     if (!sym) \
3017       sym = gfc_search_interface (ns->op[INTRINSIC_##comp##_OS], 0, &actual); \
3018     break;
3019               CHECK_OS_COMPARISON(EQ)
3020               CHECK_OS_COMPARISON(NE)
3021               CHECK_OS_COMPARISON(GT)
3022               CHECK_OS_COMPARISON(GE)
3023               CHECK_OS_COMPARISON(LT)
3024               CHECK_OS_COMPARISON(LE)
3025 #undef CHECK_OS_COMPARISON
3026
3027               default:
3028                 sym = gfc_search_interface (ns->op[i], 0, &actual);
3029             }
3030
3031           if (sym != NULL)
3032             break;
3033         }
3034     }
3035
3036   /* TODO: Do an ambiguity-check and error if multiple matching interfaces are
3037      found rather than just taking the first one and not checking further.  */
3038
3039   if (sym == NULL)
3040     {
3041       gfc_typebound_proc* tbo;
3042       gfc_expr* tb_base;
3043
3044       /* See if we find a matching type-bound operator.  */
3045       if (i == INTRINSIC_USER)
3046         tbo = matching_typebound_op (&tb_base, actual,
3047                                      i, e->value.op.uop->name, &gname);
3048       else
3049         switch (i)
3050           {
3051 #define CHECK_OS_COMPARISON(comp) \
3052   case INTRINSIC_##comp: \
3053   case INTRINSIC_##comp##_OS: \
3054     tbo = matching_typebound_op (&tb_base, actual, \
3055                                  INTRINSIC_##comp, NULL, &gname); \
3056     if (!tbo) \
3057       tbo = matching_typebound_op (&tb_base, actual, \
3058                                    INTRINSIC_##comp##_OS, NULL, &gname); \
3059     break;
3060             CHECK_OS_COMPARISON(EQ)
3061             CHECK_OS_COMPARISON(NE)
3062             CHECK_OS_COMPARISON(GT)
3063             CHECK_OS_COMPARISON(GE)
3064             CHECK_OS_COMPARISON(LT)
3065             CHECK_OS_COMPARISON(LE)
3066 #undef CHECK_OS_COMPARISON
3067
3068             default:
3069               tbo = matching_typebound_op (&tb_base, actual, i, NULL, &gname);
3070               break;
3071           }
3072               
3073       /* If there is a matching typebound-operator, replace the expression with
3074          a call to it and succeed.  */
3075       if (tbo)
3076         {
3077           gfc_try result;
3078
3079           gcc_assert (tb_base);
3080           build_compcall_for_operator (e, actual, tb_base, tbo, gname);
3081
3082           result = gfc_resolve_expr (e);
3083           if (result == FAILURE)
3084             *real_error = true;
3085
3086           return result;
3087         }
3088
3089       /* Don't use gfc_free_actual_arglist().  */
3090       if (actual->next != NULL)
3091         gfc_free (actual->next);
3092       gfc_free (actual);
3093
3094       return FAILURE;
3095     }
3096
3097   /* Change the expression node to a function call.  */
3098   e->expr_type = EXPR_FUNCTION;
3099   e->symtree = gfc_find_sym_in_symtree (sym);
3100   e->value.function.actual = actual;
3101   e->value.function.esym = NULL;
3102   e->value.function.isym = NULL;
3103   e->value.function.name = NULL;
3104   e->user_operator = 1;
3105
3106   if (gfc_resolve_expr (e) == FAILURE)
3107     {
3108       *real_error = true;
3109       return FAILURE;
3110     }
3111
3112   return SUCCESS;
3113 }
3114
3115
3116 /* Tries to replace an assignment code node with a subroutine call to
3117    the subroutine associated with the assignment operator.  Return
3118    SUCCESS if the node was replaced.  On FAILURE, no error is
3119    generated.  */
3120
3121 gfc_try
3122 gfc_extend_assign (gfc_code *c, gfc_namespace *ns)
3123 {
3124   gfc_actual_arglist *actual;
3125   gfc_expr *lhs, *rhs;
3126   gfc_symbol *sym;
3127   const char *gname;
3128
3129   gname = NULL;
3130
3131   lhs = c->expr1;
3132   rhs = c->expr2;
3133
3134   /* Don't allow an intrinsic assignment to be replaced.  */
3135   if (lhs->ts.type != BT_DERIVED && lhs->ts.type != BT_CLASS
3136       && (rhs->rank == 0 || rhs->rank == lhs->rank)
3137       && (lhs->ts.type == rhs->ts.type
3138           || (gfc_numeric_ts (&lhs->ts) && gfc_numeric_ts (&rhs->ts))))
3139     return FAILURE;
3140
3141   actual = gfc_get_actual_arglist ();
3142   actual->expr = lhs;
3143
3144   actual->next = gfc_get_actual_arglist ();
3145   actual->next->expr = rhs;
3146
3147   sym = NULL;
3148
3149   for (; ns; ns = ns->parent)
3150     {
3151       sym = gfc_search_interface (ns->op[INTRINSIC_ASSIGN], 1, &actual);
3152       if (sym != NULL)
3153         break;
3154     }
3155
3156   /* TODO: Ambiguity-check, see above for gfc_extend_expr.  */
3157
3158   if (sym == NULL)
3159     {
3160       gfc_typebound_proc* tbo;
3161       gfc_expr* tb_base;
3162
3163       /* See if we find a matching type-bound assignment.  */
3164       tbo = matching_typebound_op (&tb_base, actual,
3165                                    INTRINSIC_ASSIGN, NULL, &gname);
3166               
3167       /* If there is one, replace the expression with a call to it and
3168          succeed.  */
3169       if (tbo)
3170         {
3171           gcc_assert (tb_base);
3172           c->expr1 = gfc_get_expr ();
3173           build_compcall_for_operator (c->expr1, actual, tb_base, tbo, gname);
3174           c->expr1->value.compcall.assign = 1;
3175           c->expr2 = NULL;
3176           c->op = EXEC_COMPCALL;
3177
3178           /* c is resolved from the caller, so no need to do it here.  */
3179
3180           return SUCCESS;
3181         }
3182
3183       gfc_free (actual->next);
3184       gfc_free (actual);
3185       return FAILURE;
3186     }
3187
3188   /* Replace the assignment with the call.  */
3189   c->op = EXEC_ASSIGN_CALL;
3190   c->symtree = gfc_find_sym_in_symtree (sym);
3191   c->expr1 = NULL;
3192   c->expr2 = NULL;
3193   c->ext.actual = actual;
3194
3195   return SUCCESS;
3196 }
3197
3198
3199 /* Make sure that the interface just parsed is not already present in
3200    the given interface list.  Ambiguity isn't checked yet since module
3201    procedures can be present without interfaces.  */
3202
3203 static gfc_try
3204 check_new_interface (gfc_interface *base, gfc_symbol *new_sym)
3205 {
3206   gfc_interface *ip;
3207
3208   for (ip = base; ip; ip = ip->next)
3209     {
3210       if (ip->sym == new_sym)
3211         {
3212           gfc_error ("Entity '%s' at %C is already present in the interface",
3213                      new_sym->name);
3214           return FAILURE;
3215         }
3216     }
3217
3218   return SUCCESS;
3219 }
3220
3221
3222 /* Add a symbol to the current interface.  */
3223
3224 gfc_try
3225 gfc_add_interface (gfc_symbol *new_sym)
3226 {
3227   gfc_interface **head, *intr;
3228   gfc_namespace *ns;
3229   gfc_symbol *sym;
3230
3231   switch (current_interface.type)
3232     {
3233     case INTERFACE_NAMELESS:
3234     case INTERFACE_ABSTRACT:
3235       return SUCCESS;
3236
3237     case INTERFACE_INTRINSIC_OP:
3238       for (ns = current_interface.ns; ns; ns = ns->parent)
3239         switch (current_interface.op)
3240           {
3241             case INTRINSIC_EQ:
3242             case INTRINSIC_EQ_OS:
3243               if (check_new_interface (ns->op[INTRINSIC_EQ], new_sym) == FAILURE ||
3244                   check_new_interface (ns->op[INTRINSIC_EQ_OS], new_sym) == FAILURE)
3245                 return FAILURE;
3246               break;
3247
3248             case INTRINSIC_NE:
3249             case INTRINSIC_NE_OS:
3250               if (check_new_interface (ns->op[INTRINSIC_NE], new_sym) == FAILURE ||
3251                   check_new_interface (ns->op[INTRINSIC_NE_OS], new_sym) == FAILURE)
3252                 return FAILURE;
3253               break;
3254
3255             case INTRINSIC_GT:
3256             case INTRINSIC_GT_OS:
3257               if (check_new_interface (ns->op[INTRINSIC_GT], new_sym) == FAILURE ||
3258                   check_new_interface (ns->op[INTRINSIC_GT_OS], new_sym) == FAILURE)
3259                 return FAILURE;
3260               break;
3261
3262             case INTRINSIC_GE:
3263             case INTRINSIC_GE_OS:
3264               if (check_new_interface (ns->op[INTRINSIC_GE], new_sym) == FAILURE ||
3265                   check_new_interface (ns->op[INTRINSIC_GE_OS], new_sym) == FAILURE)
3266                 return FAILURE;
3267               break;
3268
3269             case INTRINSIC_LT:
3270             case INTRINSIC_LT_OS:
3271               if (check_new_interface (ns->op[INTRINSIC_LT], new_sym) == FAILURE ||
3272                   check_new_interface (ns->op[INTRINSIC_LT_OS], new_sym) == FAILURE)
3273                 return FAILURE;
3274               break;
3275
3276             case INTRINSIC_LE:
3277             case INTRINSIC_LE_OS:
3278               if (check_new_interface (ns->op[INTRINSIC_LE], new_sym) == FAILURE ||
3279                   check_new_interface (ns->op[INTRINSIC_LE_OS], new_sym) == FAILURE)
3280                 return FAILURE;
3281               break;
3282
3283             default:
3284               if (check_new_interface (ns->op[current_interface.op], new_sym) == FAILURE)
3285                 return FAILURE;
3286           }
3287
3288       head = &current_interface.ns->op[current_interface.op];
3289       break;
3290
3291     case INTERFACE_GENERIC:
3292       for (ns = current_interface.ns; ns; ns = ns->parent)
3293         {
3294           gfc_find_symbol (current_interface.sym->name, ns, 0, &sym);
3295           if (sym == NULL)
3296             continue;
3297
3298           if (check_new_interface (sym->generic, new_sym) == FAILURE)
3299             return FAILURE;
3300         }
3301
3302       head = &current_interface.sym->generic;
3303       break;
3304
3305     case INTERFACE_USER_OP:
3306       if (check_new_interface (current_interface.uop->op, new_sym)
3307           == FAILURE)
3308         return FAILURE;
3309
3310       head = &current_interface.uop->op;
3311       break;
3312
3313     default:
3314       gfc_internal_error ("gfc_add_interface(): Bad interface type");
3315     }
3316
3317   intr = gfc_get_interface ();
3318   intr->sym = new_sym;
3319   intr->where = gfc_current_locus;
3320
3321   intr->next = *head;
3322   *head = intr;
3323
3324   return SUCCESS;
3325 }
3326
3327
3328 gfc_interface *
3329 gfc_current_interface_head (void)
3330 {
3331   switch (current_interface.type)
3332     {
3333       case INTERFACE_INTRINSIC_OP:
3334         return current_interface.ns->op[current_interface.op];
3335         break;
3336
3337       case INTERFACE_GENERIC:
3338         return current_interface.sym->generic;
3339         break;
3340
3341       case INTERFACE_USER_OP:
3342         return current_interface.uop->op;
3343         break;
3344
3345       default:
3346         gcc_unreachable ();
3347     }
3348 }
3349
3350
3351 void
3352 gfc_set_current_interface_head (gfc_interface *i)
3353 {
3354   switch (current_interface.type)
3355     {
3356       case INTERFACE_INTRINSIC_OP:
3357         current_interface.ns->op[current_interface.op] = i;
3358         break;
3359
3360       case INTERFACE_GENERIC:
3361         current_interface.sym->generic = i;
3362         break;
3363
3364       case INTERFACE_USER_OP:
3365         current_interface.uop->op = i;
3366         break;
3367
3368       default:
3369         gcc_unreachable ();
3370     }
3371 }
3372
3373
3374 /* Gets rid of a formal argument list.  We do not free symbols.
3375    Symbols are freed when a namespace is freed.  */
3376
3377 void
3378 gfc_free_formal_arglist (gfc_formal_arglist *p)
3379 {
3380   gfc_formal_arglist *q;
3381
3382   for (; p; p = q)
3383     {
3384       q = p->next;
3385       gfc_free (p);
3386     }
3387 }