OSDN Git Service

2007-09-13 Tobias Burnus <burnus@net-b.de>
[pf3gnuchains/gcc-fork.git] / gcc / fortran / expr.c
1 /* Routines for manipulation of expression nodes.
2    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
3    Free Software Foundation, Inc.
4    Contributed by Andy Vaught
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "gfortran.h"
25 #include "arith.h"
26 #include "match.h"
27
28 /* Get a new expr node.  */
29
30 gfc_expr *
31 gfc_get_expr (void)
32 {
33   gfc_expr *e;
34
35   e = gfc_getmem (sizeof (gfc_expr));
36   gfc_clear_ts (&e->ts);
37   e->shape = NULL;
38   e->ref = NULL;
39   e->symtree = NULL;
40   e->con_by_offset = NULL;
41   return e;
42 }
43
44
45 /* Free an argument list and everything below it.  */
46
47 void
48 gfc_free_actual_arglist (gfc_actual_arglist *a1)
49 {
50   gfc_actual_arglist *a2;
51
52   while (a1)
53     {
54       a2 = a1->next;
55       gfc_free_expr (a1->expr);
56       gfc_free (a1);
57       a1 = a2;
58     }
59 }
60
61
62 /* Copy an arglist structure and all of the arguments.  */
63
64 gfc_actual_arglist *
65 gfc_copy_actual_arglist (gfc_actual_arglist *p)
66 {
67   gfc_actual_arglist *head, *tail, *new;
68
69   head = tail = NULL;
70
71   for (; p; p = p->next)
72     {
73       new = gfc_get_actual_arglist ();
74       *new = *p;
75
76       new->expr = gfc_copy_expr (p->expr);
77       new->next = NULL;
78
79       if (head == NULL)
80         head = new;
81       else
82         tail->next = new;
83
84       tail = new;
85     }
86
87   return head;
88 }
89
90
91 /* Free a list of reference structures.  */
92
93 void
94 gfc_free_ref_list (gfc_ref *p)
95 {
96   gfc_ref *q;
97   int i;
98
99   for (; p; p = q)
100     {
101       q = p->next;
102
103       switch (p->type)
104         {
105         case REF_ARRAY:
106           for (i = 0; i < GFC_MAX_DIMENSIONS; i++)
107             {
108               gfc_free_expr (p->u.ar.start[i]);
109               gfc_free_expr (p->u.ar.end[i]);
110               gfc_free_expr (p->u.ar.stride[i]);
111             }
112
113           break;
114
115         case REF_SUBSTRING:
116           gfc_free_expr (p->u.ss.start);
117           gfc_free_expr (p->u.ss.end);
118           break;
119
120         case REF_COMPONENT:
121           break;
122         }
123
124       gfc_free (p);
125     }
126 }
127
128
129 /* Workhorse function for gfc_free_expr() that frees everything
130    beneath an expression node, but not the node itself.  This is
131    useful when we want to simplify a node and replace it with
132    something else or the expression node belongs to another structure.  */
133
134 static void
135 free_expr0 (gfc_expr *e)
136 {
137   int n;
138
139   switch (e->expr_type)
140     {
141     case EXPR_CONSTANT:
142       /* Free any parts of the value that need freeing.  */
143       switch (e->ts.type)
144         {
145         case BT_INTEGER:
146           mpz_clear (e->value.integer);
147           break;
148
149         case BT_REAL:
150           mpfr_clear (e->value.real);
151           break;
152
153         case BT_CHARACTER:
154           gfc_free (e->value.character.string);
155           break;
156
157         case BT_COMPLEX:
158           mpfr_clear (e->value.complex.r);
159           mpfr_clear (e->value.complex.i);
160           break;
161
162         default:
163           break;
164         }
165
166       /* Free the representation, except in character constants where it
167          is the same as value.character.string and thus already freed.  */
168       if (e->representation.string && e->ts.type != BT_CHARACTER)
169         gfc_free (e->representation.string);
170
171       break;
172
173     case EXPR_OP:
174       if (e->value.op.op1 != NULL)
175         gfc_free_expr (e->value.op.op1);
176       if (e->value.op.op2 != NULL)
177         gfc_free_expr (e->value.op.op2);
178       break;
179
180     case EXPR_FUNCTION:
181       gfc_free_actual_arglist (e->value.function.actual);
182       break;
183
184     case EXPR_VARIABLE:
185       break;
186
187     case EXPR_ARRAY:
188     case EXPR_STRUCTURE:
189       gfc_free_constructor (e->value.constructor);
190       break;
191
192     case EXPR_SUBSTRING:
193       gfc_free (e->value.character.string);
194       break;
195
196     case EXPR_NULL:
197       break;
198
199     default:
200       gfc_internal_error ("free_expr0(): Bad expr type");
201     }
202
203   /* Free a shape array.  */
204   if (e->shape != NULL)
205     {
206       for (n = 0; n < e->rank; n++)
207         mpz_clear (e->shape[n]);
208
209       gfc_free (e->shape);
210     }
211
212   gfc_free_ref_list (e->ref);
213
214   memset (e, '\0', sizeof (gfc_expr));
215 }
216
217
218 /* Free an expression node and everything beneath it.  */
219
220 void
221 gfc_free_expr (gfc_expr *e)
222 {
223   if (e == NULL)
224     return;
225   if (e->con_by_offset)
226     splay_tree_delete (e->con_by_offset); 
227   free_expr0 (e);
228   gfc_free (e);
229 }
230
231
232 /* Graft the *src expression onto the *dest subexpression.  */
233
234 void
235 gfc_replace_expr (gfc_expr *dest, gfc_expr *src)
236 {
237   free_expr0 (dest);
238   *dest = *src;
239   gfc_free (src);
240 }
241
242
243 /* Try to extract an integer constant from the passed expression node.
244    Returns an error message or NULL if the result is set.  It is
245    tempting to generate an error and return SUCCESS or FAILURE, but
246    failure is OK for some callers.  */
247
248 const char *
249 gfc_extract_int (gfc_expr *expr, int *result)
250 {
251   if (expr->expr_type != EXPR_CONSTANT)
252     return _("Constant expression required at %C");
253
254   if (expr->ts.type != BT_INTEGER)
255     return _("Integer expression required at %C");
256
257   if ((mpz_cmp_si (expr->value.integer, INT_MAX) > 0)
258       || (mpz_cmp_si (expr->value.integer, INT_MIN) < 0))
259     {
260       return _("Integer value too large in expression at %C");
261     }
262
263   *result = (int) mpz_get_si (expr->value.integer);
264
265   return NULL;
266 }
267
268
269 /* Recursively copy a list of reference structures.  */
270
271 static gfc_ref *
272 copy_ref (gfc_ref *src)
273 {
274   gfc_array_ref *ar;
275   gfc_ref *dest;
276
277   if (src == NULL)
278     return NULL;
279
280   dest = gfc_get_ref ();
281   dest->type = src->type;
282
283   switch (src->type)
284     {
285     case REF_ARRAY:
286       ar = gfc_copy_array_ref (&src->u.ar);
287       dest->u.ar = *ar;
288       gfc_free (ar);
289       break;
290
291     case REF_COMPONENT:
292       dest->u.c = src->u.c;
293       break;
294
295     case REF_SUBSTRING:
296       dest->u.ss = src->u.ss;
297       dest->u.ss.start = gfc_copy_expr (src->u.ss.start);
298       dest->u.ss.end = gfc_copy_expr (src->u.ss.end);
299       break;
300     }
301
302   dest->next = copy_ref (src->next);
303
304   return dest;
305 }
306
307
308 /* Detect whether an expression has any vector index array references.  */
309
310 int
311 gfc_has_vector_index (gfc_expr *e)
312 {
313   gfc_ref *ref;
314   int i;
315   for (ref = e->ref; ref; ref = ref->next)
316     if (ref->type == REF_ARRAY)
317       for (i = 0; i < ref->u.ar.dimen; i++)
318         if (ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
319           return 1;
320   return 0;
321 }
322
323
324 /* Copy a shape array.  */
325
326 mpz_t *
327 gfc_copy_shape (mpz_t *shape, int rank)
328 {
329   mpz_t *new_shape;
330   int n;
331
332   if (shape == NULL)
333     return NULL;
334
335   new_shape = gfc_get_shape (rank);
336
337   for (n = 0; n < rank; n++)
338     mpz_init_set (new_shape[n], shape[n]);
339
340   return new_shape;
341 }
342
343
344 /* Copy a shape array excluding dimension N, where N is an integer
345    constant expression.  Dimensions are numbered in fortran style --
346    starting with ONE.
347
348    So, if the original shape array contains R elements
349       { s1 ... sN-1  sN  sN+1 ... sR-1 sR}
350    the result contains R-1 elements:
351       { s1 ... sN-1  sN+1    ...  sR-1}
352
353    If anything goes wrong -- N is not a constant, its value is out
354    of range -- or anything else, just returns NULL.  */
355
356 mpz_t *
357 gfc_copy_shape_excluding (mpz_t *shape, int rank, gfc_expr *dim)
358 {
359   mpz_t *new_shape, *s;
360   int i, n;
361
362   if (shape == NULL 
363       || rank <= 1
364       || dim == NULL
365       || dim->expr_type != EXPR_CONSTANT 
366       || dim->ts.type != BT_INTEGER)
367     return NULL;
368
369   n = mpz_get_si (dim->value.integer);
370   n--; /* Convert to zero based index.  */
371   if (n < 0 || n >= rank)
372     return NULL;
373
374   s = new_shape = gfc_get_shape (rank - 1);
375
376   for (i = 0; i < rank; i++)
377     {
378       if (i == n)
379         continue;
380       mpz_init_set (*s, shape[i]);
381       s++;
382     }
383
384   return new_shape;
385 }
386
387
388 /* Given an expression pointer, return a copy of the expression.  This
389    subroutine is recursive.  */
390
391 gfc_expr *
392 gfc_copy_expr (gfc_expr *p)
393 {
394   gfc_expr *q;
395   char *s;
396
397   if (p == NULL)
398     return NULL;
399
400   q = gfc_get_expr ();
401   *q = *p;
402
403   switch (q->expr_type)
404     {
405     case EXPR_SUBSTRING:
406       s = gfc_getmem (p->value.character.length + 1);
407       q->value.character.string = s;
408
409       memcpy (s, p->value.character.string, p->value.character.length + 1);
410       break;
411
412     case EXPR_CONSTANT:
413       /* Copy target representation, if it exists.  */
414       if (p->representation.string)
415         {
416           s = gfc_getmem (p->representation.length + 1);
417           q->representation.string = s;
418
419           memcpy (s, p->representation.string, p->representation.length + 1);
420         }
421
422       /* Copy the values of any pointer components of p->value.  */
423       switch (q->ts.type)
424         {
425         case BT_INTEGER:
426           mpz_init_set (q->value.integer, p->value.integer);
427           break;
428
429         case BT_REAL:
430           gfc_set_model_kind (q->ts.kind);
431           mpfr_init (q->value.real);
432           mpfr_set (q->value.real, p->value.real, GFC_RND_MODE);
433           break;
434
435         case BT_COMPLEX:
436           gfc_set_model_kind (q->ts.kind);
437           mpfr_init (q->value.complex.r);
438           mpfr_init (q->value.complex.i);
439           mpfr_set (q->value.complex.r, p->value.complex.r, GFC_RND_MODE);
440           mpfr_set (q->value.complex.i, p->value.complex.i, GFC_RND_MODE);
441           break;
442
443         case BT_CHARACTER:
444           if (p->representation.string)
445             q->value.character.string = q->representation.string;
446           else
447             {
448               s = gfc_getmem (p->value.character.length + 1);
449               q->value.character.string = s;
450
451               /* This is the case for the C_NULL_CHAR named constant.  */
452               if (p->value.character.length == 0
453                   && (p->ts.is_c_interop || p->ts.is_iso_c))
454                 {
455                   *s = '\0';
456                   /* Need to set the length to 1 to make sure the NUL
457                      terminator is copied.  */
458                   q->value.character.length = 1;
459                 }
460               else
461                 memcpy (s, p->value.character.string,
462                         p->value.character.length + 1);
463             }
464           break;
465
466         case BT_HOLLERITH:
467         case BT_LOGICAL:
468         case BT_DERIVED:
469           break;                /* Already done.  */
470
471         case BT_PROCEDURE:
472         case BT_VOID:
473            /* Should never be reached.  */
474         case BT_UNKNOWN:
475           gfc_internal_error ("gfc_copy_expr(): Bad expr node");
476           /* Not reached.  */
477         }
478
479       break;
480
481     case EXPR_OP:
482       switch (q->value.op.operator)
483         {
484         case INTRINSIC_NOT:
485         case INTRINSIC_PARENTHESES:
486         case INTRINSIC_UPLUS:
487         case INTRINSIC_UMINUS:
488           q->value.op.op1 = gfc_copy_expr (p->value.op.op1);
489           break;
490
491         default:                /* Binary operators.  */
492           q->value.op.op1 = gfc_copy_expr (p->value.op.op1);
493           q->value.op.op2 = gfc_copy_expr (p->value.op.op2);
494           break;
495         }
496
497       break;
498
499     case EXPR_FUNCTION:
500       q->value.function.actual =
501         gfc_copy_actual_arglist (p->value.function.actual);
502       break;
503
504     case EXPR_STRUCTURE:
505     case EXPR_ARRAY:
506       q->value.constructor = gfc_copy_constructor (p->value.constructor);
507       break;
508
509     case EXPR_VARIABLE:
510     case EXPR_NULL:
511       break;
512     }
513
514   q->shape = gfc_copy_shape (p->shape, p->rank);
515
516   q->ref = copy_ref (p->ref);
517
518   return q;
519 }
520
521
522 /* Return the maximum kind of two expressions.  In general, higher
523    kind numbers mean more precision for numeric types.  */
524
525 int
526 gfc_kind_max (gfc_expr *e1, gfc_expr *e2)
527 {
528   return (e1->ts.kind > e2->ts.kind) ? e1->ts.kind : e2->ts.kind;
529 }
530
531
532 /* Returns nonzero if the type is numeric, zero otherwise.  */
533
534 static int
535 numeric_type (bt type)
536 {
537   return type == BT_COMPLEX || type == BT_REAL || type == BT_INTEGER;
538 }
539
540
541 /* Returns nonzero if the typespec is a numeric type, zero otherwise.  */
542
543 int
544 gfc_numeric_ts (gfc_typespec *ts)
545 {
546   return numeric_type (ts->type);
547 }
548
549
550 /* Returns an expression node that is an integer constant.  */
551
552 gfc_expr *
553 gfc_int_expr (int i)
554 {
555   gfc_expr *p;
556
557   p = gfc_get_expr ();
558
559   p->expr_type = EXPR_CONSTANT;
560   p->ts.type = BT_INTEGER;
561   p->ts.kind = gfc_default_integer_kind;
562
563   p->where = gfc_current_locus;
564   mpz_init_set_si (p->value.integer, i);
565
566   return p;
567 }
568
569
570 /* Returns an expression node that is a logical constant.  */
571
572 gfc_expr *
573 gfc_logical_expr (int i, locus *where)
574 {
575   gfc_expr *p;
576
577   p = gfc_get_expr ();
578
579   p->expr_type = EXPR_CONSTANT;
580   p->ts.type = BT_LOGICAL;
581   p->ts.kind = gfc_default_logical_kind;
582
583   if (where == NULL)
584     where = &gfc_current_locus;
585   p->where = *where;
586   p->value.logical = i;
587
588   return p;
589 }
590
591
592 /* Return an expression node with an optional argument list attached.
593    A variable number of gfc_expr pointers are strung together in an
594    argument list with a NULL pointer terminating the list.  */
595
596 gfc_expr *
597 gfc_build_conversion (gfc_expr *e)
598 {
599   gfc_expr *p;
600
601   p = gfc_get_expr ();
602   p->expr_type = EXPR_FUNCTION;
603   p->symtree = NULL;
604   p->value.function.actual = NULL;
605
606   p->value.function.actual = gfc_get_actual_arglist ();
607   p->value.function.actual->expr = e;
608
609   return p;
610 }
611
612
613 /* Given an expression node with some sort of numeric binary
614    expression, insert type conversions required to make the operands
615    have the same type.
616
617    The exception is that the operands of an exponential don't have to
618    have the same type.  If possible, the base is promoted to the type
619    of the exponent.  For example, 1**2.3 becomes 1.0**2.3, but
620    1.0**2 stays as it is.  */
621
622 void
623 gfc_type_convert_binary (gfc_expr *e)
624 {
625   gfc_expr *op1, *op2;
626
627   op1 = e->value.op.op1;
628   op2 = e->value.op.op2;
629
630   if (op1->ts.type == BT_UNKNOWN || op2->ts.type == BT_UNKNOWN)
631     {
632       gfc_clear_ts (&e->ts);
633       return;
634     }
635
636   /* Kind conversions of same type.  */
637   if (op1->ts.type == op2->ts.type)
638     {
639       if (op1->ts.kind == op2->ts.kind)
640         {
641           /* No type conversions.  */
642           e->ts = op1->ts;
643           goto done;
644         }
645
646       if (op1->ts.kind > op2->ts.kind)
647         gfc_convert_type (op2, &op1->ts, 2);
648       else
649         gfc_convert_type (op1, &op2->ts, 2);
650
651       e->ts = op1->ts;
652       goto done;
653     }
654
655   /* Integer combined with real or complex.  */
656   if (op2->ts.type == BT_INTEGER)
657     {
658       e->ts = op1->ts;
659
660       /* Special case for ** operator.  */
661       if (e->value.op.operator == INTRINSIC_POWER)
662         goto done;
663
664       gfc_convert_type (e->value.op.op2, &e->ts, 2);
665       goto done;
666     }
667
668   if (op1->ts.type == BT_INTEGER)
669     {
670       e->ts = op2->ts;
671       gfc_convert_type (e->value.op.op1, &e->ts, 2);
672       goto done;
673     }
674
675   /* Real combined with complex.  */
676   e->ts.type = BT_COMPLEX;
677   if (op1->ts.kind > op2->ts.kind)
678     e->ts.kind = op1->ts.kind;
679   else
680     e->ts.kind = op2->ts.kind;
681   if (op1->ts.type != BT_COMPLEX || op1->ts.kind != e->ts.kind)
682     gfc_convert_type (e->value.op.op1, &e->ts, 2);
683   if (op2->ts.type != BT_COMPLEX || op2->ts.kind != e->ts.kind)
684     gfc_convert_type (e->value.op.op2, &e->ts, 2);
685
686 done:
687   return;
688 }
689
690
691 static match
692 check_specification_function (gfc_expr *e)
693 {
694   gfc_symbol *sym;
695
696   if (!e->symtree)
697     return MATCH_NO;
698
699   sym = e->symtree->n.sym;
700
701   /* F95, 7.1.6.2; F2003, 7.1.7  */
702   if (sym
703       && sym->attr.function
704       && sym->attr.pure
705       && !sym->attr.intrinsic
706       && !sym->attr.recursive
707       && sym->attr.proc != PROC_INTERNAL
708       && sym->attr.proc != PROC_ST_FUNCTION
709       && sym->attr.proc != PROC_UNKNOWN
710       && sym->formal == NULL)
711     return MATCH_YES;
712
713   return MATCH_NO;
714 }
715
716 /* Function to determine if an expression is constant or not.  This
717    function expects that the expression has already been simplified.  */
718
719 int
720 gfc_is_constant_expr (gfc_expr *e)
721 {
722   gfc_constructor *c;
723   gfc_actual_arglist *arg;
724   int rv;
725
726   if (e == NULL)
727     return 1;
728
729   switch (e->expr_type)
730     {
731     case EXPR_OP:
732       rv = (gfc_is_constant_expr (e->value.op.op1)
733             && (e->value.op.op2 == NULL
734                 || gfc_is_constant_expr (e->value.op.op2)));
735       break;
736
737     case EXPR_VARIABLE:
738       rv = 0;
739       break;
740
741     case EXPR_FUNCTION:
742       /* Specification functions are constant.  */
743       if (check_specification_function (e) == MATCH_YES)
744         {
745           rv = 1;
746           break;
747         }
748
749       /* Call to intrinsic with at least one argument.  */
750       rv = 0;
751       if (e->value.function.isym && e->value.function.actual)
752         {
753           for (arg = e->value.function.actual; arg; arg = arg->next)
754             {
755               if (!gfc_is_constant_expr (arg->expr))
756                 break;
757             }
758           if (arg == NULL)
759             rv = 1;
760         }
761       break;
762
763     case EXPR_CONSTANT:
764     case EXPR_NULL:
765       rv = 1;
766       break;
767
768     case EXPR_SUBSTRING:
769       rv = e->ref == NULL || (gfc_is_constant_expr (e->ref->u.ss.start)
770                               && gfc_is_constant_expr (e->ref->u.ss.end));
771       break;
772
773     case EXPR_STRUCTURE:
774       rv = 0;
775       for (c = e->value.constructor; c; c = c->next)
776         if (!gfc_is_constant_expr (c->expr))
777           break;
778
779       if (c == NULL)
780         rv = 1;
781       break;
782
783     case EXPR_ARRAY:
784       rv = gfc_constant_ac (e);
785       break;
786
787     default:
788       gfc_internal_error ("gfc_is_constant_expr(): Unknown expression type");
789     }
790
791   return rv;
792 }
793
794
795 /* Try to collapse intrinsic expressions.  */
796
797 static try
798 simplify_intrinsic_op (gfc_expr *p, int type)
799 {
800   gfc_intrinsic_op op;
801   gfc_expr *op1, *op2, *result;
802
803   if (p->value.op.operator == INTRINSIC_USER)
804     return SUCCESS;
805
806   op1 = p->value.op.op1;
807   op2 = p->value.op.op2;
808   op  = p->value.op.operator;
809
810   if (gfc_simplify_expr (op1, type) == FAILURE)
811     return FAILURE;
812   if (gfc_simplify_expr (op2, type) == FAILURE)
813     return FAILURE;
814
815   if (!gfc_is_constant_expr (op1)
816       || (op2 != NULL && !gfc_is_constant_expr (op2)))
817     return SUCCESS;
818
819   /* Rip p apart.  */
820   p->value.op.op1 = NULL;
821   p->value.op.op2 = NULL;
822
823   switch (op)
824     {
825     case INTRINSIC_PARENTHESES:
826       result = gfc_parentheses (op1);
827       break;
828
829     case INTRINSIC_UPLUS:
830       result = gfc_uplus (op1);
831       break;
832
833     case INTRINSIC_UMINUS:
834       result = gfc_uminus (op1);
835       break;
836
837     case INTRINSIC_PLUS:
838       result = gfc_add (op1, op2);
839       break;
840
841     case INTRINSIC_MINUS:
842       result = gfc_subtract (op1, op2);
843       break;
844
845     case INTRINSIC_TIMES:
846       result = gfc_multiply (op1, op2);
847       break;
848
849     case INTRINSIC_DIVIDE:
850       result = gfc_divide (op1, op2);
851       break;
852
853     case INTRINSIC_POWER:
854       result = gfc_power (op1, op2);
855       break;
856
857     case INTRINSIC_CONCAT:
858       result = gfc_concat (op1, op2);
859       break;
860
861     case INTRINSIC_EQ:
862     case INTRINSIC_EQ_OS:
863       result = gfc_eq (op1, op2, op);
864       break;
865
866     case INTRINSIC_NE:
867     case INTRINSIC_NE_OS:
868       result = gfc_ne (op1, op2, op);
869       break;
870
871     case INTRINSIC_GT:
872     case INTRINSIC_GT_OS:
873       result = gfc_gt (op1, op2, op);
874       break;
875
876     case INTRINSIC_GE:
877     case INTRINSIC_GE_OS:
878       result = gfc_ge (op1, op2, op);
879       break;
880
881     case INTRINSIC_LT:
882     case INTRINSIC_LT_OS:
883       result = gfc_lt (op1, op2, op);
884       break;
885
886     case INTRINSIC_LE:
887     case INTRINSIC_LE_OS:
888       result = gfc_le (op1, op2, op);
889       break;
890
891     case INTRINSIC_NOT:
892       result = gfc_not (op1);
893       break;
894
895     case INTRINSIC_AND:
896       result = gfc_and (op1, op2);
897       break;
898
899     case INTRINSIC_OR:
900       result = gfc_or (op1, op2);
901       break;
902
903     case INTRINSIC_EQV:
904       result = gfc_eqv (op1, op2);
905       break;
906
907     case INTRINSIC_NEQV:
908       result = gfc_neqv (op1, op2);
909       break;
910
911     default:
912       gfc_internal_error ("simplify_intrinsic_op(): Bad operator");
913     }
914
915   if (result == NULL)
916     {
917       gfc_free_expr (op1);
918       gfc_free_expr (op2);
919       return FAILURE;
920     }
921
922   result->rank = p->rank;
923   result->where = p->where;
924   gfc_replace_expr (p, result);
925
926   return SUCCESS;
927 }
928
929
930 /* Subroutine to simplify constructor expressions.  Mutually recursive
931    with gfc_simplify_expr().  */
932
933 static try
934 simplify_constructor (gfc_constructor *c, int type)
935 {
936   for (; c; c = c->next)
937     {
938       if (c->iterator
939           && (gfc_simplify_expr (c->iterator->start, type) == FAILURE
940               || gfc_simplify_expr (c->iterator->end, type) == FAILURE
941               || gfc_simplify_expr (c->iterator->step, type) == FAILURE))
942         return FAILURE;
943
944       if (c->expr && gfc_simplify_expr (c->expr, type) == FAILURE)
945         return FAILURE;
946     }
947
948   return SUCCESS;
949 }
950
951
952 /* Pull a single array element out of an array constructor.  */
953
954 static try
955 find_array_element (gfc_constructor *cons, gfc_array_ref *ar,
956                     gfc_constructor **rval)
957 {
958   unsigned long nelemen;
959   int i;
960   mpz_t delta;
961   mpz_t offset;
962   mpz_t span;
963   mpz_t tmp;
964   gfc_expr *e;
965   try t;
966
967   t = SUCCESS;
968   e = NULL;
969
970   mpz_init_set_ui (offset, 0);
971   mpz_init (delta);
972   mpz_init (tmp);
973   mpz_init_set_ui (span, 1);
974   for (i = 0; i < ar->dimen; i++)
975     {
976       e = gfc_copy_expr (ar->start[i]);
977       if (e->expr_type != EXPR_CONSTANT)
978         {
979           cons = NULL;
980           goto depart;
981         }
982
983       /* Check the bounds.  */
984       if (ar->as->upper[i]
985           && (mpz_cmp (e->value.integer, ar->as->upper[i]->value.integer) > 0
986               || mpz_cmp (e->value.integer,
987                           ar->as->lower[i]->value.integer) < 0))
988         {
989           gfc_error ("index in dimension %d is out of bounds "
990                      "at %L", i + 1, &ar->c_where[i]);
991           cons = NULL;
992           t = FAILURE;
993           goto depart;
994         }
995
996       mpz_sub (delta, e->value.integer, ar->as->lower[i]->value.integer);
997       mpz_mul (delta, delta, span);
998       mpz_add (offset, offset, delta);
999
1000       mpz_set_ui (tmp, 1);
1001       mpz_add (tmp, tmp, ar->as->upper[i]->value.integer);
1002       mpz_sub (tmp, tmp, ar->as->lower[i]->value.integer);
1003       mpz_mul (span, span, tmp);
1004     }
1005
1006   if (cons)
1007     {
1008       for (nelemen = mpz_get_ui (offset); nelemen > 0; nelemen--)
1009         {
1010           if (cons->iterator)
1011             {
1012               cons = NULL;
1013               goto depart;
1014             }
1015           cons = cons->next;
1016         }
1017     }
1018
1019 depart:
1020   mpz_clear (delta);
1021   mpz_clear (offset);
1022   mpz_clear (span);
1023   mpz_clear (tmp);
1024   if (e)
1025     gfc_free_expr (e);
1026   *rval = cons;
1027   return t;
1028 }
1029
1030
1031 /* Find a component of a structure constructor.  */
1032
1033 static gfc_constructor *
1034 find_component_ref (gfc_constructor *cons, gfc_ref *ref)
1035 {
1036   gfc_component *comp;
1037   gfc_component *pick;
1038
1039   comp = ref->u.c.sym->components;
1040   pick = ref->u.c.component;
1041   while (comp != pick)
1042     {
1043       comp = comp->next;
1044       cons = cons->next;
1045     }
1046
1047   return cons;
1048 }
1049
1050
1051 /* Replace an expression with the contents of a constructor, removing
1052    the subobject reference in the process.  */
1053
1054 static void
1055 remove_subobject_ref (gfc_expr *p, gfc_constructor *cons)
1056 {
1057   gfc_expr *e;
1058
1059   e = cons->expr;
1060   cons->expr = NULL;
1061   e->ref = p->ref->next;
1062   p->ref->next =  NULL;
1063   gfc_replace_expr (p, e);
1064 }
1065
1066
1067 /* Pull an array section out of an array constructor.  */
1068
1069 static try
1070 find_array_section (gfc_expr *expr, gfc_ref *ref)
1071 {
1072   int idx;
1073   int rank;
1074   int d;
1075   int shape_i;
1076   long unsigned one = 1;
1077   bool incr_ctr;
1078   mpz_t start[GFC_MAX_DIMENSIONS];
1079   mpz_t end[GFC_MAX_DIMENSIONS];
1080   mpz_t stride[GFC_MAX_DIMENSIONS];
1081   mpz_t delta[GFC_MAX_DIMENSIONS];
1082   mpz_t ctr[GFC_MAX_DIMENSIONS];
1083   mpz_t delta_mpz;
1084   mpz_t tmp_mpz;
1085   mpz_t nelts;
1086   mpz_t ptr;
1087   mpz_t index;
1088   gfc_constructor *cons;
1089   gfc_constructor *base;
1090   gfc_expr *begin;
1091   gfc_expr *finish;
1092   gfc_expr *step;
1093   gfc_expr *upper;
1094   gfc_expr *lower;
1095   gfc_constructor *vecsub[GFC_MAX_DIMENSIONS], *c;
1096   try t;
1097
1098   t = SUCCESS;
1099
1100   base = expr->value.constructor;
1101   expr->value.constructor = NULL;
1102
1103   rank = ref->u.ar.as->rank;
1104
1105   if (expr->shape == NULL)
1106     expr->shape = gfc_get_shape (rank);
1107
1108   mpz_init_set_ui (delta_mpz, one);
1109   mpz_init_set_ui (nelts, one);
1110   mpz_init (tmp_mpz);
1111
1112   /* Do the initialization now, so that we can cleanup without
1113      keeping track of where we were.  */
1114   for (d = 0; d < rank; d++)
1115     {
1116       mpz_init (delta[d]);
1117       mpz_init (start[d]);
1118       mpz_init (end[d]);
1119       mpz_init (ctr[d]);
1120       mpz_init (stride[d]);
1121       vecsub[d] = NULL;
1122     }
1123
1124   /* Build the counters to clock through the array reference.  */
1125   shape_i = 0;
1126   for (d = 0; d < rank; d++)
1127     {
1128       /* Make this stretch of code easier on the eye!  */
1129       begin = ref->u.ar.start[d];
1130       finish = ref->u.ar.end[d];
1131       step = ref->u.ar.stride[d];
1132       lower = ref->u.ar.as->lower[d];
1133       upper = ref->u.ar.as->upper[d];
1134
1135       if (ref->u.ar.dimen_type[d] == DIMEN_VECTOR)  /* Vector subscript.  */
1136         {
1137           gcc_assert (begin);
1138
1139           if (begin->expr_type != EXPR_ARRAY)
1140             {
1141               t = FAILURE;
1142               goto cleanup;
1143             }
1144
1145           gcc_assert (begin->rank == 1);
1146           gcc_assert (begin->shape);
1147
1148           vecsub[d] = begin->value.constructor;
1149           mpz_set (ctr[d], vecsub[d]->expr->value.integer);
1150           mpz_mul (nelts, nelts, begin->shape[0]);
1151           mpz_set (expr->shape[shape_i++], begin->shape[0]);
1152
1153           /* Check bounds.  */
1154           for (c = vecsub[d]; c; c = c->next)
1155             {
1156               if (mpz_cmp (c->expr->value.integer, upper->value.integer) > 0
1157                   || mpz_cmp (c->expr->value.integer,
1158                               lower->value.integer) < 0)
1159                 {
1160                   gfc_error ("index in dimension %d is out of bounds "
1161                              "at %L", d + 1, &ref->u.ar.c_where[d]);
1162                   t = FAILURE;
1163                   goto cleanup;
1164                 }
1165             }
1166         }
1167       else
1168         {
1169           if ((begin && begin->expr_type != EXPR_CONSTANT)
1170               || (finish && finish->expr_type != EXPR_CONSTANT)
1171               || (step && step->expr_type != EXPR_CONSTANT))
1172             {
1173               t = FAILURE;
1174               goto cleanup;
1175             }
1176
1177           /* Obtain the stride.  */
1178           if (step)
1179             mpz_set (stride[d], step->value.integer);
1180           else
1181             mpz_set_ui (stride[d], one);
1182
1183           if (mpz_cmp_ui (stride[d], 0) == 0)
1184             mpz_set_ui (stride[d], one);
1185
1186           /* Obtain the start value for the index.  */
1187           if (begin)
1188             mpz_set (start[d], begin->value.integer);
1189           else
1190             mpz_set (start[d], lower->value.integer);
1191
1192           mpz_set (ctr[d], start[d]);
1193
1194           /* Obtain the end value for the index.  */
1195           if (finish)
1196             mpz_set (end[d], finish->value.integer);
1197           else
1198             mpz_set (end[d], upper->value.integer);
1199
1200           /* Separate 'if' because elements sometimes arrive with
1201              non-null end.  */
1202           if (ref->u.ar.dimen_type[d] == DIMEN_ELEMENT)
1203             mpz_set (end [d], begin->value.integer);
1204
1205           /* Check the bounds.  */
1206           if (mpz_cmp (ctr[d], upper->value.integer) > 0
1207               || mpz_cmp (end[d], upper->value.integer) > 0
1208               || mpz_cmp (ctr[d], lower->value.integer) < 0
1209               || mpz_cmp (end[d], lower->value.integer) < 0)
1210             {
1211               gfc_error ("index in dimension %d is out of bounds "
1212                          "at %L", d + 1, &ref->u.ar.c_where[d]);
1213               t = FAILURE;
1214               goto cleanup;
1215             }
1216
1217           /* Calculate the number of elements and the shape.  */
1218           mpz_set (tmp_mpz, stride[d]);
1219           mpz_add (tmp_mpz, end[d], tmp_mpz);
1220           mpz_sub (tmp_mpz, tmp_mpz, ctr[d]);
1221           mpz_div (tmp_mpz, tmp_mpz, stride[d]);
1222           mpz_mul (nelts, nelts, tmp_mpz);
1223
1224           /* An element reference reduces the rank of the expression; don't
1225              add anything to the shape array.  */
1226           if (ref->u.ar.dimen_type[d] != DIMEN_ELEMENT) 
1227             mpz_set (expr->shape[shape_i++], tmp_mpz);
1228         }
1229
1230       /* Calculate the 'stride' (=delta) for conversion of the
1231          counter values into the index along the constructor.  */
1232       mpz_set (delta[d], delta_mpz);
1233       mpz_sub (tmp_mpz, upper->value.integer, lower->value.integer);
1234       mpz_add_ui (tmp_mpz, tmp_mpz, one);
1235       mpz_mul (delta_mpz, delta_mpz, tmp_mpz);
1236     }
1237
1238   mpz_init (index);
1239   mpz_init (ptr);
1240   cons = base;
1241
1242   /* Now clock through the array reference, calculating the index in
1243      the source constructor and transferring the elements to the new
1244      constructor.  */  
1245   for (idx = 0; idx < (int) mpz_get_si (nelts); idx++)
1246     {
1247       if (ref->u.ar.offset)
1248         mpz_set (ptr, ref->u.ar.offset->value.integer);
1249       else
1250         mpz_init_set_ui (ptr, 0);
1251
1252       incr_ctr = true;
1253       for (d = 0; d < rank; d++)
1254         {
1255           mpz_set (tmp_mpz, ctr[d]);
1256           mpz_sub (tmp_mpz, tmp_mpz, ref->u.ar.as->lower[d]->value.integer);
1257           mpz_mul (tmp_mpz, tmp_mpz, delta[d]);
1258           mpz_add (ptr, ptr, tmp_mpz);
1259
1260           if (!incr_ctr) continue;
1261
1262           if (ref->u.ar.dimen_type[d] == DIMEN_VECTOR) /* Vector subscript.  */
1263             {
1264               gcc_assert(vecsub[d]);
1265
1266               if (!vecsub[d]->next)
1267                 vecsub[d] = ref->u.ar.start[d]->value.constructor;
1268               else
1269                 {
1270                   vecsub[d] = vecsub[d]->next;
1271                   incr_ctr = false;
1272                 }
1273               mpz_set (ctr[d], vecsub[d]->expr->value.integer);
1274             }
1275           else
1276             {
1277               mpz_add (ctr[d], ctr[d], stride[d]); 
1278
1279               if (mpz_cmp_ui (stride[d], 0) > 0
1280                   ? mpz_cmp (ctr[d], end[d]) > 0
1281                   : mpz_cmp (ctr[d], end[d]) < 0)
1282                 mpz_set (ctr[d], start[d]);
1283               else
1284                 incr_ctr = false;
1285             }
1286         }
1287
1288       /* There must be a better way of dealing with negative strides
1289          than resetting the index and the constructor pointer!  */ 
1290       if (mpz_cmp (ptr, index) < 0)
1291         {
1292           mpz_set_ui (index, 0);
1293           cons = base;
1294         }
1295
1296       while (mpz_cmp (ptr, index) > 0)
1297         {
1298           mpz_add_ui (index, index, one);
1299           cons = cons->next;
1300         }
1301
1302       gfc_append_constructor (expr, gfc_copy_expr (cons->expr));
1303     }
1304
1305   mpz_clear (ptr);
1306   mpz_clear (index);
1307
1308 cleanup:
1309
1310   mpz_clear (delta_mpz);
1311   mpz_clear (tmp_mpz);
1312   mpz_clear (nelts);
1313   for (d = 0; d < rank; d++)
1314     {
1315       mpz_clear (delta[d]);
1316       mpz_clear (start[d]);
1317       mpz_clear (end[d]);
1318       mpz_clear (ctr[d]);
1319       mpz_clear (stride[d]);
1320     }
1321   gfc_free_constructor (base);
1322   return t;
1323 }
1324
1325 /* Pull a substring out of an expression.  */
1326
1327 static try
1328 find_substring_ref (gfc_expr *p, gfc_expr **newp)
1329 {
1330   int end;
1331   int start;
1332   int length;
1333   char *chr;
1334
1335   if (p->ref->u.ss.start->expr_type != EXPR_CONSTANT
1336       || p->ref->u.ss.end->expr_type != EXPR_CONSTANT)
1337     return FAILURE;
1338
1339   *newp = gfc_copy_expr (p);
1340   gfc_free ((*newp)->value.character.string);
1341
1342   end = (int) mpz_get_ui (p->ref->u.ss.end->value.integer);
1343   start = (int) mpz_get_ui (p->ref->u.ss.start->value.integer);
1344   length = end - start + 1;
1345
1346   chr = (*newp)->value.character.string = gfc_getmem (length + 1);
1347   (*newp)->value.character.length = length;
1348   memcpy (chr, &p->value.character.string[start - 1], length);
1349   chr[length] = '\0';
1350   return SUCCESS;
1351 }
1352
1353
1354
1355 /* Simplify a subobject reference of a constructor.  This occurs when
1356    parameter variable values are substituted.  */
1357
1358 static try
1359 simplify_const_ref (gfc_expr *p)
1360 {
1361   gfc_constructor *cons;
1362   gfc_expr *newp;
1363
1364   while (p->ref)
1365     {
1366       switch (p->ref->type)
1367         {
1368         case REF_ARRAY:
1369           switch (p->ref->u.ar.type)
1370             {
1371             case AR_ELEMENT:
1372               if (find_array_element (p->value.constructor, &p->ref->u.ar,
1373                                       &cons) == FAILURE)
1374                 return FAILURE;
1375
1376               if (!cons)
1377                 return SUCCESS;
1378
1379               remove_subobject_ref (p, cons);
1380               break;
1381
1382             case AR_SECTION:
1383               if (find_array_section (p, p->ref) == FAILURE)
1384                 return FAILURE;
1385               p->ref->u.ar.type = AR_FULL;
1386
1387             /* Fall through.  */
1388
1389             case AR_FULL:
1390               if (p->ref->next != NULL
1391                   && (p->ts.type == BT_CHARACTER || p->ts.type == BT_DERIVED))
1392                 {
1393                   cons = p->value.constructor;
1394                   for (; cons; cons = cons->next)
1395                     {
1396                       cons->expr->ref = copy_ref (p->ref->next);
1397                       simplify_const_ref (cons->expr);
1398                     }
1399                 }
1400               gfc_free_ref_list (p->ref);
1401               p->ref = NULL;
1402               break;
1403
1404             default:
1405               return SUCCESS;
1406             }
1407
1408           break;
1409
1410         case REF_COMPONENT:
1411           cons = find_component_ref (p->value.constructor, p->ref);
1412           remove_subobject_ref (p, cons);
1413           break;
1414
1415         case REF_SUBSTRING:
1416           if (find_substring_ref (p, &newp) == FAILURE)
1417             return FAILURE;
1418
1419           gfc_replace_expr (p, newp);
1420           gfc_free_ref_list (p->ref);
1421           p->ref = NULL;
1422           break;
1423         }
1424     }
1425
1426   return SUCCESS;
1427 }
1428
1429
1430 /* Simplify a chain of references.  */
1431
1432 static try
1433 simplify_ref_chain (gfc_ref *ref, int type)
1434 {
1435   int n;
1436
1437   for (; ref; ref = ref->next)
1438     {
1439       switch (ref->type)
1440         {
1441         case REF_ARRAY:
1442           for (n = 0; n < ref->u.ar.dimen; n++)
1443             {
1444               if (gfc_simplify_expr (ref->u.ar.start[n], type) == FAILURE)
1445                 return FAILURE;
1446               if (gfc_simplify_expr (ref->u.ar.end[n], type) == FAILURE)
1447                 return FAILURE;
1448               if (gfc_simplify_expr (ref->u.ar.stride[n], type) == FAILURE)
1449                 return FAILURE;
1450             }
1451           break;
1452
1453         case REF_SUBSTRING:
1454           if (gfc_simplify_expr (ref->u.ss.start, type) == FAILURE)
1455             return FAILURE;
1456           if (gfc_simplify_expr (ref->u.ss.end, type) == FAILURE)
1457             return FAILURE;
1458           break;
1459
1460         default:
1461           break;
1462         }
1463     }
1464   return SUCCESS;
1465 }
1466
1467
1468 /* Try to substitute the value of a parameter variable.  */
1469
1470 static try
1471 simplify_parameter_variable (gfc_expr *p, int type)
1472 {
1473   gfc_expr *e;
1474   try t;
1475
1476   e = gfc_copy_expr (p->symtree->n.sym->value);
1477   if (e == NULL)
1478     return FAILURE;
1479
1480   e->rank = p->rank;
1481
1482   /* Do not copy subobject refs for constant.  */
1483   if (e->expr_type != EXPR_CONSTANT && p->ref != NULL)
1484     e->ref = copy_ref (p->ref);
1485   t = gfc_simplify_expr (e, type);
1486
1487   /* Only use the simplification if it eliminated all subobject references.  */
1488   if (t == SUCCESS && !e->ref)
1489     gfc_replace_expr (p, e);
1490   else
1491     gfc_free_expr (e);
1492
1493   return t;
1494 }
1495
1496 /* Given an expression, simplify it by collapsing constant
1497    expressions.  Most simplification takes place when the expression
1498    tree is being constructed.  If an intrinsic function is simplified
1499    at some point, we get called again to collapse the result against
1500    other constants.
1501
1502    We work by recursively simplifying expression nodes, simplifying
1503    intrinsic functions where possible, which can lead to further
1504    constant collapsing.  If an operator has constant operand(s), we
1505    rip the expression apart, and rebuild it, hoping that it becomes
1506    something simpler.
1507
1508    The expression type is defined for:
1509      0   Basic expression parsing
1510      1   Simplifying array constructors -- will substitute
1511          iterator values.
1512    Returns FAILURE on error, SUCCESS otherwise.
1513    NOTE: Will return SUCCESS even if the expression can not be simplified.  */
1514
1515 try
1516 gfc_simplify_expr (gfc_expr *p, int type)
1517 {
1518   gfc_actual_arglist *ap;
1519
1520   if (p == NULL)
1521     return SUCCESS;
1522
1523   switch (p->expr_type)
1524     {
1525     case EXPR_CONSTANT:
1526     case EXPR_NULL:
1527       break;
1528
1529     case EXPR_FUNCTION:
1530       for (ap = p->value.function.actual; ap; ap = ap->next)
1531         if (gfc_simplify_expr (ap->expr, type) == FAILURE)
1532           return FAILURE;
1533
1534       if (p->value.function.isym != NULL
1535           && gfc_intrinsic_func_interface (p, 1) == MATCH_ERROR)
1536         return FAILURE;
1537
1538       break;
1539
1540     case EXPR_SUBSTRING:
1541       if (simplify_ref_chain (p->ref, type) == FAILURE)
1542         return FAILURE;
1543
1544       if (gfc_is_constant_expr (p))
1545         {
1546           char *s;
1547           int start, end;
1548
1549           if (p->ref && p->ref->u.ss.start)
1550             {
1551               gfc_extract_int (p->ref->u.ss.start, &start);
1552               start--;  /* Convert from one-based to zero-based.  */
1553             }
1554           else
1555             start = 0;
1556
1557           if (p->ref && p->ref->u.ss.end)
1558             gfc_extract_int (p->ref->u.ss.end, &end);
1559           else
1560             end = p->value.character.length;
1561
1562           s = gfc_getmem (end - start + 2);
1563           memcpy (s, p->value.character.string + start, end - start);
1564           s[end - start + 1] = '\0';  /* TODO: C-style string.  */
1565           gfc_free (p->value.character.string);
1566           p->value.character.string = s;
1567           p->value.character.length = end - start;
1568           p->ts.cl = gfc_get_charlen ();
1569           p->ts.cl->next = gfc_current_ns->cl_list;
1570           gfc_current_ns->cl_list = p->ts.cl;
1571           p->ts.cl->length = gfc_int_expr (p->value.character.length);
1572           gfc_free_ref_list (p->ref);
1573           p->ref = NULL;
1574           p->expr_type = EXPR_CONSTANT;
1575         }
1576       break;
1577
1578     case EXPR_OP:
1579       if (simplify_intrinsic_op (p, type) == FAILURE)
1580         return FAILURE;
1581       break;
1582
1583     case EXPR_VARIABLE:
1584       /* Only substitute array parameter variables if we are in an
1585          initialization expression, or we want a subsection.  */
1586       if (p->symtree->n.sym->attr.flavor == FL_PARAMETER
1587           && (gfc_init_expr || p->ref
1588               || p->symtree->n.sym->value->expr_type != EXPR_ARRAY))
1589         {
1590           if (simplify_parameter_variable (p, type) == FAILURE)
1591             return FAILURE;
1592           break;
1593         }
1594
1595       if (type == 1)
1596         {
1597           gfc_simplify_iterator_var (p);
1598         }
1599
1600       /* Simplify subcomponent references.  */
1601       if (simplify_ref_chain (p->ref, type) == FAILURE)
1602         return FAILURE;
1603
1604       break;
1605
1606     case EXPR_STRUCTURE:
1607     case EXPR_ARRAY:
1608       if (simplify_ref_chain (p->ref, type) == FAILURE)
1609         return FAILURE;
1610
1611       if (simplify_constructor (p->value.constructor, type) == FAILURE)
1612         return FAILURE;
1613
1614       if (p->expr_type == EXPR_ARRAY && p->ref && p->ref->type == REF_ARRAY
1615           && p->ref->u.ar.type == AR_FULL)
1616           gfc_expand_constructor (p);
1617
1618       if (simplify_const_ref (p) == FAILURE)
1619         return FAILURE;
1620
1621       break;
1622     }
1623
1624   return SUCCESS;
1625 }
1626
1627
1628 /* Returns the type of an expression with the exception that iterator
1629    variables are automatically integers no matter what else they may
1630    be declared as.  */
1631
1632 static bt
1633 et0 (gfc_expr *e)
1634 {
1635   if (e->expr_type == EXPR_VARIABLE && gfc_check_iter_variable (e) == SUCCESS)
1636     return BT_INTEGER;
1637
1638   return e->ts.type;
1639 }
1640
1641
1642 /* Check an intrinsic arithmetic operation to see if it is consistent
1643    with some type of expression.  */
1644
1645 static try check_init_expr (gfc_expr *);
1646
1647
1648 /* Scalarize an expression for an elemental intrinsic call.  */
1649
1650 static try
1651 scalarize_intrinsic_call (gfc_expr *e)
1652 {
1653   gfc_actual_arglist *a, *b;
1654   gfc_constructor *args[5], *ctor, *new_ctor;
1655   gfc_expr *expr, *old;
1656   int n, i, rank[5];
1657
1658   old = gfc_copy_expr (e);
1659
1660 /* Assume that the old expression carries the type information and
1661    that the first arg carries all the shape information.  */
1662   expr = gfc_copy_expr (old->value.function.actual->expr);
1663   gfc_free_constructor (expr->value.constructor);
1664   expr->value.constructor = NULL;
1665
1666   expr->ts = old->ts;
1667   expr->expr_type = EXPR_ARRAY;
1668
1669   /* Copy the array argument constructors into an array, with nulls
1670      for the scalars.  */
1671   n = 0;
1672   a = old->value.function.actual;
1673   for (; a; a = a->next)
1674     {
1675       /* Check that this is OK for an initialization expression.  */
1676       if (a->expr && check_init_expr (a->expr) == FAILURE)
1677         goto cleanup;
1678
1679       rank[n] = 0;
1680       if (a->expr && a->expr->rank && a->expr->expr_type == EXPR_VARIABLE)
1681         {
1682           rank[n] = a->expr->rank;
1683           ctor = a->expr->symtree->n.sym->value->value.constructor;
1684           args[n] = gfc_copy_constructor (ctor);
1685         }
1686       else if (a->expr && a->expr->expr_type == EXPR_ARRAY)
1687         {
1688           if (a->expr->rank)
1689             rank[n] = a->expr->rank;
1690           else
1691             rank[n] = 1;
1692           args[n] = gfc_copy_constructor (a->expr->value.constructor);
1693         }
1694       else
1695         args[n] = NULL;
1696       n++;
1697     }
1698
1699   for (i = 1; i < n; i++)
1700     if (rank[i] && rank[i] != rank[0])
1701       goto compliance;
1702
1703   /* Using the first argument as the master, step through the array
1704      calling the function for each element and advancing the array
1705      constructors together.  */
1706   ctor = args[0];
1707   new_ctor = NULL;
1708   for (; ctor; ctor = ctor->next)
1709     {
1710           if (expr->value.constructor == NULL)
1711             expr->value.constructor
1712                 = new_ctor = gfc_get_constructor ();
1713           else
1714             {
1715               new_ctor->next = gfc_get_constructor ();
1716               new_ctor = new_ctor->next;
1717             }
1718           new_ctor->expr = gfc_copy_expr (old);
1719           gfc_free_actual_arglist (new_ctor->expr->value.function.actual);
1720           a = NULL;
1721           b = old->value.function.actual;
1722           for (i = 0; i < n; i++)
1723             {
1724               if (a == NULL)
1725                 new_ctor->expr->value.function.actual
1726                         = a = gfc_get_actual_arglist ();
1727               else
1728                 {
1729                   a->next = gfc_get_actual_arglist ();
1730                   a = a->next;
1731                 }
1732               if (args[i])
1733                 a->expr = gfc_copy_expr (args[i]->expr);
1734               else
1735                 a->expr = gfc_copy_expr (b->expr);
1736
1737               b = b->next;
1738             }
1739
1740           /* Simplify the function calls.  */
1741           if (gfc_simplify_expr (new_ctor->expr, 0) == FAILURE)
1742             goto cleanup;
1743
1744           for (i = 0; i < n; i++)
1745             if (args[i])
1746               args[i] = args[i]->next;
1747
1748           for (i = 1; i < n; i++)
1749             if (rank[i] && ((args[i] != NULL && args[0] == NULL)
1750                          || (args[i] == NULL && args[0] != NULL)))
1751               goto compliance;
1752     }
1753
1754   free_expr0 (e);
1755   *e = *expr;
1756   gfc_free_expr (old);
1757   return SUCCESS;
1758
1759 compliance:
1760   gfc_error_now ("elemental function arguments at %C are not compliant");
1761
1762 cleanup:
1763   gfc_free_expr (expr);
1764   gfc_free_expr (old);
1765   return FAILURE;
1766 }
1767
1768
1769 static try
1770 check_intrinsic_op (gfc_expr *e, try (*check_function) (gfc_expr *))
1771 {
1772   gfc_expr *op1 = e->value.op.op1;
1773   gfc_expr *op2 = e->value.op.op2;
1774
1775   if ((*check_function) (op1) == FAILURE)
1776     return FAILURE;
1777
1778   switch (e->value.op.operator)
1779     {
1780     case INTRINSIC_UPLUS:
1781     case INTRINSIC_UMINUS:
1782       if (!numeric_type (et0 (op1)))
1783         goto not_numeric;
1784       break;
1785
1786     case INTRINSIC_EQ:
1787     case INTRINSIC_EQ_OS:
1788     case INTRINSIC_NE:
1789     case INTRINSIC_NE_OS:
1790     case INTRINSIC_GT:
1791     case INTRINSIC_GT_OS:
1792     case INTRINSIC_GE:
1793     case INTRINSIC_GE_OS:
1794     case INTRINSIC_LT:
1795     case INTRINSIC_LT_OS:
1796     case INTRINSIC_LE:
1797     case INTRINSIC_LE_OS:
1798       if ((*check_function) (op2) == FAILURE)
1799         return FAILURE;
1800       
1801       if (!(et0 (op1) == BT_CHARACTER && et0 (op2) == BT_CHARACTER)
1802           && !(numeric_type (et0 (op1)) && numeric_type (et0 (op2))))
1803         {
1804           gfc_error ("Numeric or CHARACTER operands are required in "
1805                      "expression at %L", &e->where);
1806          return FAILURE;
1807         }
1808       break;
1809
1810     case INTRINSIC_PLUS:
1811     case INTRINSIC_MINUS:
1812     case INTRINSIC_TIMES:
1813     case INTRINSIC_DIVIDE:
1814     case INTRINSIC_POWER:
1815       if ((*check_function) (op2) == FAILURE)
1816         return FAILURE;
1817
1818       if (!numeric_type (et0 (op1)) || !numeric_type (et0 (op2)))
1819         goto not_numeric;
1820
1821       if (e->value.op.operator == INTRINSIC_POWER
1822           && check_function == check_init_expr && et0 (op2) != BT_INTEGER)
1823         {
1824           if (gfc_notify_std (GFC_STD_F2003,"Fortran 2003: Noninteger "
1825                               "exponent in an initialization "
1826                               "expression at %L", &op2->where)
1827               == FAILURE)
1828             return FAILURE;
1829         }
1830
1831       break;
1832
1833     case INTRINSIC_CONCAT:
1834       if ((*check_function) (op2) == FAILURE)
1835         return FAILURE;
1836
1837       if (et0 (op1) != BT_CHARACTER || et0 (op2) != BT_CHARACTER)
1838         {
1839           gfc_error ("Concatenation operator in expression at %L "
1840                      "must have two CHARACTER operands", &op1->where);
1841           return FAILURE;
1842         }
1843
1844       if (op1->ts.kind != op2->ts.kind)
1845         {
1846           gfc_error ("Concat operator at %L must concatenate strings of the "
1847                      "same kind", &e->where);
1848           return FAILURE;
1849         }
1850
1851       break;
1852
1853     case INTRINSIC_NOT:
1854       if (et0 (op1) != BT_LOGICAL)
1855         {
1856           gfc_error (".NOT. operator in expression at %L must have a LOGICAL "
1857                      "operand", &op1->where);
1858           return FAILURE;
1859         }
1860
1861       break;
1862
1863     case INTRINSIC_AND:
1864     case INTRINSIC_OR:
1865     case INTRINSIC_EQV:
1866     case INTRINSIC_NEQV:
1867       if ((*check_function) (op2) == FAILURE)
1868         return FAILURE;
1869
1870       if (et0 (op1) != BT_LOGICAL || et0 (op2) != BT_LOGICAL)
1871         {
1872           gfc_error ("LOGICAL operands are required in expression at %L",
1873                      &e->where);
1874           return FAILURE;
1875         }
1876
1877       break;
1878
1879     case INTRINSIC_PARENTHESES:
1880       break;
1881
1882     default:
1883       gfc_error ("Only intrinsic operators can be used in expression at %L",
1884                  &e->where);
1885       return FAILURE;
1886     }
1887
1888   return SUCCESS;
1889
1890 not_numeric:
1891   gfc_error ("Numeric operands are required in expression at %L", &e->where);
1892
1893   return FAILURE;
1894 }
1895
1896
1897 static match
1898 check_init_expr_arguments (gfc_expr *e)
1899 {
1900   gfc_actual_arglist *ap;
1901
1902   for (ap = e->value.function.actual; ap; ap = ap->next)
1903     if (check_init_expr (ap->expr) == FAILURE)
1904       return MATCH_ERROR;
1905
1906   return MATCH_YES;
1907 }
1908
1909 /* F95, 7.1.6.1, Initialization expressions, (7)
1910    F2003, 7.1.7 Initialization expression, (8)  */
1911
1912 static match
1913 check_inquiry (gfc_expr *e, int not_restricted)
1914 {
1915   const char *name;
1916   const char *const *functions;
1917
1918   static const char *const inquiry_func_f95[] = {
1919     "lbound", "shape", "size", "ubound",
1920     "bit_size", "len", "kind",
1921     "digits", "epsilon", "huge", "maxexponent", "minexponent",
1922     "precision", "radix", "range", "tiny",
1923     NULL
1924   };
1925
1926   static const char *const inquiry_func_f2003[] = {
1927     "lbound", "shape", "size", "ubound",
1928     "bit_size", "len", "kind",
1929     "digits", "epsilon", "huge", "maxexponent", "minexponent",
1930     "precision", "radix", "range", "tiny",
1931     "new_line", NULL
1932   };
1933
1934   int i;
1935   gfc_actual_arglist *ap;
1936
1937   if (!e->value.function.isym
1938       || !e->value.function.isym->inquiry)
1939     return MATCH_NO;
1940
1941   /* An undeclared parameter will get us here (PR25018).  */
1942   if (e->symtree == NULL)
1943     return MATCH_NO;
1944
1945   name = e->symtree->n.sym->name;
1946
1947   functions = (gfc_option.warn_std & GFC_STD_F2003) 
1948                 ? inquiry_func_f2003 : inquiry_func_f95;
1949
1950   for (i = 0; functions[i]; i++)
1951     if (strcmp (functions[i], name) == 0)
1952       break;
1953
1954   if (functions[i] == NULL)
1955     {
1956       gfc_error ("Inquiry function '%s' at %L is not permitted "
1957                  "in an initialization expression", name, &e->where);
1958       return MATCH_ERROR;
1959     }
1960
1961   /* At this point we have an inquiry function with a variable argument.  The
1962      type of the variable might be undefined, but we need it now, because the
1963      arguments of these functions are not allowed to be undefined.  */
1964
1965   for (ap = e->value.function.actual; ap; ap = ap->next)
1966     {
1967       if (!ap->expr)
1968         continue;
1969
1970       if (ap->expr->ts.type == BT_UNKNOWN)
1971         {
1972           if (ap->expr->symtree->n.sym->ts.type == BT_UNKNOWN
1973               && gfc_set_default_type (ap->expr->symtree->n.sym, 0, gfc_current_ns)
1974               == FAILURE)
1975             return MATCH_NO;
1976
1977           ap->expr->ts = ap->expr->symtree->n.sym->ts;
1978         }
1979
1980         /* Assumed character length will not reduce to a constant expression
1981            with LEN, as required by the standard.  */
1982         if (i == 5 && not_restricted
1983             && ap->expr->symtree->n.sym->ts.type == BT_CHARACTER
1984             && ap->expr->symtree->n.sym->ts.cl->length == NULL)
1985           {
1986             gfc_error ("assumed character length variable '%s' in constant "
1987                        "expression at %L", e->symtree->n.sym->name, &e->where);
1988               return MATCH_ERROR;
1989           }
1990         else if (not_restricted && check_init_expr (ap->expr) == FAILURE)
1991           return MATCH_ERROR;
1992     }
1993
1994   return MATCH_YES;
1995 }
1996
1997
1998 /* F95, 7.1.6.1, Initialization expressions, (5)
1999    F2003, 7.1.7 Initialization expression, (5)  */
2000
2001 static match
2002 check_transformational (gfc_expr *e)
2003 {
2004   static const char * const trans_func_f95[] = {
2005     "repeat", "reshape", "selected_int_kind",
2006     "selected_real_kind", "transfer", "trim", NULL
2007   };
2008
2009   int i;
2010   const char *name;
2011
2012   if (!e->value.function.isym
2013       || !e->value.function.isym->transformational)
2014     return MATCH_NO;
2015
2016   name = e->symtree->n.sym->name;
2017
2018   /* NULL() is dealt with below.  */
2019   if (strcmp ("null", name) == 0)
2020     return MATCH_NO;
2021
2022   for (i = 0; trans_func_f95[i]; i++)
2023     if (strcmp (trans_func_f95[i], name) == 0)
2024       break;
2025
2026   /* FIXME, F2003: implement translation of initialization
2027      expressions before enabling this check. For F95, error
2028      out if the transformational function is not in the list.  */
2029 #if 0
2030   if (trans_func_f95[i] == NULL
2031       && gfc_notify_std (GFC_STD_F2003, 
2032                          "transformational intrinsic '%s' at %L is not permitted "
2033                          "in an initialization expression", name, &e->where) == FAILURE)
2034     return MATCH_ERROR;
2035 #else
2036   if (trans_func_f95[i] == NULL)
2037     {
2038       gfc_error("transformational intrinsic '%s' at %L is not permitted "
2039                 "in an initialization expression", name, &e->where);
2040       return MATCH_ERROR;
2041     }
2042 #endif
2043
2044   return check_init_expr_arguments (e);
2045 }
2046
2047
2048 /* F95, 7.1.6.1, Initialization expressions, (6)
2049    F2003, 7.1.7 Initialization expression, (6)  */
2050
2051 static match
2052 check_null (gfc_expr *e)
2053 {
2054   if (strcmp ("null", e->symtree->n.sym->name) != 0)
2055     return MATCH_NO;
2056
2057   return check_init_expr_arguments (e);
2058 }
2059
2060
2061 static match
2062 check_elemental (gfc_expr *e)
2063 {
2064   if (!e->value.function.isym
2065       || !e->value.function.isym->elemental)
2066     return MATCH_NO;
2067
2068   if ((e->ts.type != BT_INTEGER || e->ts.type != BT_CHARACTER)
2069       && gfc_notify_std (GFC_STD_F2003, "Extension: Evaluation of "
2070                         "nonstandard initialization expression at %L",
2071                         &e->where) == FAILURE)
2072     return MATCH_ERROR;
2073
2074   return check_init_expr_arguments (e);
2075 }
2076
2077
2078 static match
2079 check_conversion (gfc_expr *e)
2080 {
2081   if (!e->value.function.isym
2082       || !e->value.function.isym->conversion)
2083     return MATCH_NO;
2084
2085   return check_init_expr_arguments (e);
2086 }
2087
2088
2089 /* Verify that an expression is an initialization expression.  A side
2090    effect is that the expression tree is reduced to a single constant
2091    node if all goes well.  This would normally happen when the
2092    expression is constructed but function references are assumed to be
2093    intrinsics in the context of initialization expressions.  If
2094    FAILURE is returned an error message has been generated.  */
2095
2096 static try
2097 check_init_expr (gfc_expr *e)
2098 {
2099   match m;
2100   try t;
2101   gfc_intrinsic_sym *isym;
2102
2103   if (e == NULL)
2104     return SUCCESS;
2105
2106   switch (e->expr_type)
2107     {
2108     case EXPR_OP:
2109       t = check_intrinsic_op (e, check_init_expr);
2110       if (t == SUCCESS)
2111         t = gfc_simplify_expr (e, 0);
2112
2113       break;
2114
2115     case EXPR_FUNCTION:
2116       t = FAILURE;
2117
2118       if ((m = check_specification_function (e)) != MATCH_YES)
2119         {
2120           if ((m = gfc_intrinsic_func_interface (e, 0)) != MATCH_YES)
2121             {
2122               gfc_error ("Function '%s' in initialization expression at %L "
2123                          "must be an intrinsic or a specification function",
2124                          e->symtree->n.sym->name, &e->where);
2125               break;
2126             }
2127
2128           if ((m = check_conversion (e)) == MATCH_NO
2129               && (m = check_inquiry (e, 1)) == MATCH_NO
2130               && (m = check_null (e)) == MATCH_NO
2131               && (m = check_transformational (e)) == MATCH_NO
2132               && (m = check_elemental (e)) == MATCH_NO)
2133             {
2134               gfc_error ("Intrinsic function '%s' at %L is not permitted "
2135                          "in an initialization expression",
2136                          e->symtree->n.sym->name, &e->where);
2137               m = MATCH_ERROR;
2138             }
2139
2140           /* Try to scalarize an elemental intrinsic function that has an
2141              array argument.  */
2142           isym = gfc_find_function (e->symtree->n.sym->name);
2143           if (isym && isym->elemental
2144               && e->value.function.actual->expr->expr_type == EXPR_ARRAY)
2145             {
2146                 if ((t = scalarize_intrinsic_call (e)) == SUCCESS)
2147                 break;
2148             }
2149         }
2150
2151       if (m == MATCH_YES)
2152         t = gfc_simplify_expr (e, 0);
2153
2154       break;
2155
2156     case EXPR_VARIABLE:
2157       t = SUCCESS;
2158
2159       if (gfc_check_iter_variable (e) == SUCCESS)
2160         break;
2161
2162       if (e->symtree->n.sym->attr.flavor == FL_PARAMETER)
2163         {
2164           t = simplify_parameter_variable (e, 0);
2165           break;
2166         }
2167
2168       if (gfc_in_match_data ())
2169         break;
2170
2171       t = FAILURE;
2172
2173       if (e->symtree->n.sym->as)
2174         {
2175           switch (e->symtree->n.sym->as->type)
2176             {
2177               case AS_ASSUMED_SIZE:
2178                 gfc_error ("assumed size array '%s' at %L is not permitted "
2179                            "in an initialization expression",
2180                            e->symtree->n.sym->name, &e->where);
2181                 break;
2182
2183               case AS_ASSUMED_SHAPE:
2184                 gfc_error ("assumed shape array '%s' at %L is not permitted "
2185                            "in an initialization expression",
2186                            e->symtree->n.sym->name, &e->where);
2187                 break;
2188
2189               case AS_DEFERRED:
2190                 gfc_error ("deferred array '%s' at %L is not permitted "
2191                            "in an initialization expression",
2192                            e->symtree->n.sym->name, &e->where);
2193                 break;
2194
2195               default:
2196                 gcc_unreachable();
2197           }
2198         }
2199       else
2200         gfc_error ("Parameter '%s' at %L has not been declared or is "
2201                    "a variable, which does not reduce to a constant "
2202                    "expression", e->symtree->n.sym->name, &e->where);
2203
2204       break;
2205
2206     case EXPR_CONSTANT:
2207     case EXPR_NULL:
2208       t = SUCCESS;
2209       break;
2210
2211     case EXPR_SUBSTRING:
2212       t = check_init_expr (e->ref->u.ss.start);
2213       if (t == FAILURE)
2214         break;
2215
2216       t = check_init_expr (e->ref->u.ss.end);
2217       if (t == SUCCESS)
2218         t = gfc_simplify_expr (e, 0);
2219
2220       break;
2221
2222     case EXPR_STRUCTURE:
2223       t = gfc_check_constructor (e, check_init_expr);
2224       break;
2225
2226     case EXPR_ARRAY:
2227       t = gfc_check_constructor (e, check_init_expr);
2228       if (t == FAILURE)
2229         break;
2230
2231       t = gfc_expand_constructor (e);
2232       if (t == FAILURE)
2233         break;
2234
2235       t = gfc_check_constructor_type (e);
2236       break;
2237
2238     default:
2239       gfc_internal_error ("check_init_expr(): Unknown expression type");
2240     }
2241
2242   return t;
2243 }
2244
2245
2246 /* Match an initialization expression.  We work by first matching an
2247    expression, then reducing it to a constant.  */
2248
2249 match
2250 gfc_match_init_expr (gfc_expr **result)
2251 {
2252   gfc_expr *expr;
2253   match m;
2254   try t;
2255
2256   m = gfc_match_expr (&expr);
2257   if (m != MATCH_YES)
2258     return m;
2259
2260   gfc_init_expr = 1;
2261   t = gfc_resolve_expr (expr);
2262   if (t == SUCCESS)
2263     t = check_init_expr (expr);
2264   gfc_init_expr = 0;
2265
2266   if (t == FAILURE)
2267     {
2268       gfc_free_expr (expr);
2269       return MATCH_ERROR;
2270     }
2271
2272   if (expr->expr_type == EXPR_ARRAY
2273       && (gfc_check_constructor_type (expr) == FAILURE
2274           || gfc_expand_constructor (expr) == FAILURE))
2275     {
2276       gfc_free_expr (expr);
2277       return MATCH_ERROR;
2278     }
2279
2280   /* Not all inquiry functions are simplified to constant expressions
2281      so it is necessary to call check_inquiry again.  */ 
2282   if (!gfc_is_constant_expr (expr) && check_inquiry (expr, 1) != MATCH_YES
2283       && !gfc_in_match_data ())
2284     {
2285       gfc_error ("Initialization expression didn't reduce %C");
2286       return MATCH_ERROR;
2287     }
2288
2289   *result = expr;
2290
2291   return MATCH_YES;
2292 }
2293
2294
2295 static try check_restricted (gfc_expr *);
2296
2297 /* Given an actual argument list, test to see that each argument is a
2298    restricted expression and optionally if the expression type is
2299    integer or character.  */
2300
2301 static try
2302 restricted_args (gfc_actual_arglist *a)
2303 {
2304   for (; a; a = a->next)
2305     {
2306       if (check_restricted (a->expr) == FAILURE)
2307         return FAILURE;
2308     }
2309
2310   return SUCCESS;
2311 }
2312
2313
2314 /************* Restricted/specification expressions *************/
2315
2316
2317 /* Make sure a non-intrinsic function is a specification function.  */
2318
2319 static try
2320 external_spec_function (gfc_expr *e)
2321 {
2322   gfc_symbol *f;
2323
2324   f = e->value.function.esym;
2325
2326   if (f->attr.proc == PROC_ST_FUNCTION)
2327     {
2328       gfc_error ("Specification function '%s' at %L cannot be a statement "
2329                  "function", f->name, &e->where);
2330       return FAILURE;
2331     }
2332
2333   if (f->attr.proc == PROC_INTERNAL)
2334     {
2335       gfc_error ("Specification function '%s' at %L cannot be an internal "
2336                  "function", f->name, &e->where);
2337       return FAILURE;
2338     }
2339
2340   if (!f->attr.pure && !f->attr.elemental)
2341     {
2342       gfc_error ("Specification function '%s' at %L must be PURE", f->name,
2343                  &e->where);
2344       return FAILURE;
2345     }
2346
2347   if (f->attr.recursive)
2348     {
2349       gfc_error ("Specification function '%s' at %L cannot be RECURSIVE",
2350                  f->name, &e->where);
2351       return FAILURE;
2352     }
2353
2354   return restricted_args (e->value.function.actual);
2355 }
2356
2357
2358 /* Check to see that a function reference to an intrinsic is a
2359    restricted expression.  */
2360
2361 static try
2362 restricted_intrinsic (gfc_expr *e)
2363 {
2364   /* TODO: Check constraints on inquiry functions.  7.1.6.2 (7).  */
2365   if (check_inquiry (e, 0) == MATCH_YES)
2366     return SUCCESS;
2367
2368   return restricted_args (e->value.function.actual);
2369 }
2370
2371
2372 /* Verify that an expression is a restricted expression.  Like its
2373    cousin check_init_expr(), an error message is generated if we
2374    return FAILURE.  */
2375
2376 static try
2377 check_restricted (gfc_expr *e)
2378 {
2379   gfc_symbol *sym;
2380   try t;
2381
2382   if (e == NULL)
2383     return SUCCESS;
2384
2385   switch (e->expr_type)
2386     {
2387     case EXPR_OP:
2388       t = check_intrinsic_op (e, check_restricted);
2389       if (t == SUCCESS)
2390         t = gfc_simplify_expr (e, 0);
2391
2392       break;
2393
2394     case EXPR_FUNCTION:
2395       t = e->value.function.esym ? external_spec_function (e)
2396                                  : restricted_intrinsic (e);
2397       break;
2398
2399     case EXPR_VARIABLE:
2400       sym = e->symtree->n.sym;
2401       t = FAILURE;
2402
2403       if (sym->attr.optional)
2404         {
2405           gfc_error ("Dummy argument '%s' at %L cannot be OPTIONAL",
2406                      sym->name, &e->where);
2407           break;
2408         }
2409
2410       if (sym->attr.intent == INTENT_OUT)
2411         {
2412           gfc_error ("Dummy argument '%s' at %L cannot be INTENT(OUT)",
2413                      sym->name, &e->where);
2414           break;
2415         }
2416
2417       /* gfc_is_formal_arg broadcasts that a formal argument list is being
2418          processed in resolve.c(resolve_formal_arglist).  This is done so
2419          that host associated dummy array indices are accepted (PR23446).
2420          This mechanism also does the same for the specification expressions
2421          of array-valued functions.  */
2422       if (sym->attr.in_common
2423           || sym->attr.use_assoc
2424           || sym->attr.dummy
2425           || sym->ns != gfc_current_ns
2426           || (sym->ns->proc_name != NULL
2427               && sym->ns->proc_name->attr.flavor == FL_MODULE)
2428           || (gfc_is_formal_arg () && (sym->ns == gfc_current_ns)))
2429         {
2430           t = SUCCESS;
2431           break;
2432         }
2433
2434       gfc_error ("Variable '%s' cannot appear in the expression at %L",
2435                  sym->name, &e->where);
2436
2437       break;
2438
2439     case EXPR_NULL:
2440     case EXPR_CONSTANT:
2441       t = SUCCESS;
2442       break;
2443
2444     case EXPR_SUBSTRING:
2445       t = gfc_specification_expr (e->ref->u.ss.start);
2446       if (t == FAILURE)
2447         break;
2448
2449       t = gfc_specification_expr (e->ref->u.ss.end);
2450       if (t == SUCCESS)
2451         t = gfc_simplify_expr (e, 0);
2452
2453       break;
2454
2455     case EXPR_STRUCTURE:
2456       t = gfc_check_constructor (e, check_restricted);
2457       break;
2458
2459     case EXPR_ARRAY:
2460       t = gfc_check_constructor (e, check_restricted);
2461       break;
2462
2463     default:
2464       gfc_internal_error ("check_restricted(): Unknown expression type");
2465     }
2466
2467   return t;
2468 }
2469
2470
2471 /* Check to see that an expression is a specification expression.  If
2472    we return FAILURE, an error has been generated.  */
2473
2474 try
2475 gfc_specification_expr (gfc_expr *e)
2476 {
2477
2478   if (e == NULL)
2479     return SUCCESS;
2480
2481   if (e->ts.type != BT_INTEGER)
2482     {
2483       gfc_error ("Expression at %L must be of INTEGER type", &e->where);
2484       return FAILURE;
2485     }
2486
2487   if (e->rank != 0)
2488     {
2489       gfc_error ("Expression at %L must be scalar", &e->where);
2490       return FAILURE;
2491     }
2492
2493   if (gfc_simplify_expr (e, 0) == FAILURE)
2494     return FAILURE;
2495
2496   return check_restricted (e);
2497 }
2498
2499
2500 /************** Expression conformance checks.  *************/
2501
2502 /* Given two expressions, make sure that the arrays are conformable.  */
2503
2504 try
2505 gfc_check_conformance (const char *optype_msgid, gfc_expr *op1, gfc_expr *op2)
2506 {
2507   int op1_flag, op2_flag, d;
2508   mpz_t op1_size, op2_size;
2509   try t;
2510
2511   if (op1->rank == 0 || op2->rank == 0)
2512     return SUCCESS;
2513
2514   if (op1->rank != op2->rank)
2515     {
2516       gfc_error ("Incompatible ranks in %s (%d and %d) at %L", _(optype_msgid),
2517                  op1->rank, op2->rank, &op1->where);
2518       return FAILURE;
2519     }
2520
2521   t = SUCCESS;
2522
2523   for (d = 0; d < op1->rank; d++)
2524     {
2525       op1_flag = gfc_array_dimen_size (op1, d, &op1_size) == SUCCESS;
2526       op2_flag = gfc_array_dimen_size (op2, d, &op2_size) == SUCCESS;
2527
2528       if (op1_flag && op2_flag && mpz_cmp (op1_size, op2_size) != 0)
2529         {
2530           gfc_error ("different shape for %s at %L on dimension %d (%d and %d)",
2531                      _(optype_msgid), &op1->where, d + 1,
2532                      (int) mpz_get_si (op1_size),
2533                      (int) mpz_get_si (op2_size));
2534
2535           t = FAILURE;
2536         }
2537
2538       if (op1_flag)
2539         mpz_clear (op1_size);
2540       if (op2_flag)
2541         mpz_clear (op2_size);
2542
2543       if (t == FAILURE)
2544         return FAILURE;
2545     }
2546
2547   return SUCCESS;
2548 }
2549
2550
2551 /* Given an assignable expression and an arbitrary expression, make
2552    sure that the assignment can take place.  */
2553
2554 try
2555 gfc_check_assign (gfc_expr *lvalue, gfc_expr *rvalue, int conform)
2556 {
2557   gfc_symbol *sym;
2558   gfc_ref *ref;
2559   int has_pointer;
2560
2561   sym = lvalue->symtree->n.sym;
2562
2563   /* Check INTENT(IN), unless the object itself is the component or
2564      sub-component of a pointer.  */
2565   has_pointer = sym->attr.pointer;
2566
2567   for (ref = lvalue->ref; ref; ref = ref->next)
2568     if (ref->type == REF_COMPONENT && ref->u.c.component->pointer)
2569       {
2570         has_pointer = 1;
2571         break;
2572       }
2573
2574   if (!has_pointer && sym->attr.intent == INTENT_IN)
2575     {
2576       gfc_error ("Cannot assign to INTENT(IN) variable '%s' at %L",
2577                  sym->name, &lvalue->where);
2578       return FAILURE;
2579     }
2580
2581   /* 12.5.2.2, Note 12.26: The result variable is very similar to any other
2582      variable local to a function subprogram.  Its existence begins when
2583      execution of the function is initiated and ends when execution of the
2584      function is terminated...
2585      Therefore, the left hand side is no longer a variable, when it is:  */
2586   if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_ST_FUNCTION
2587       && !sym->attr.external)
2588     {
2589       bool bad_proc;
2590       bad_proc = false;
2591
2592       /* (i) Use associated;  */
2593       if (sym->attr.use_assoc)
2594         bad_proc = true;
2595
2596       /* (ii) The assignment is in the main program; or  */
2597       if (gfc_current_ns->proc_name->attr.is_main_program)
2598         bad_proc = true;
2599
2600       /* (iii) A module or internal procedure...  */
2601       if ((gfc_current_ns->proc_name->attr.proc == PROC_INTERNAL
2602            || gfc_current_ns->proc_name->attr.proc == PROC_MODULE)
2603           && gfc_current_ns->parent
2604           && (!(gfc_current_ns->parent->proc_name->attr.function
2605                 || gfc_current_ns->parent->proc_name->attr.subroutine)
2606               || gfc_current_ns->parent->proc_name->attr.is_main_program))
2607         {
2608           /* ... that is not a function...  */ 
2609           if (!gfc_current_ns->proc_name->attr.function)
2610             bad_proc = true;
2611
2612           /* ... or is not an entry and has a different name.  */
2613           if (!sym->attr.entry && sym->name != gfc_current_ns->proc_name->name)
2614             bad_proc = true;
2615         }
2616
2617       if (bad_proc)
2618         {
2619           gfc_error ("'%s' at %L is not a VALUE", sym->name, &lvalue->where);
2620           return FAILURE;
2621         }
2622     }
2623
2624   if (rvalue->rank != 0 && lvalue->rank != rvalue->rank)
2625     {
2626       gfc_error ("Incompatible ranks %d and %d in assignment at %L",
2627                  lvalue->rank, rvalue->rank, &lvalue->where);
2628       return FAILURE;
2629     }
2630
2631   if (lvalue->ts.type == BT_UNKNOWN)
2632     {
2633       gfc_error ("Variable type is UNKNOWN in assignment at %L",
2634                  &lvalue->where);
2635       return FAILURE;
2636     }
2637
2638   if (rvalue->expr_type == EXPR_NULL)
2639     {  
2640       if (lvalue->symtree->n.sym->attr.pointer
2641           && lvalue->symtree->n.sym->attr.data)
2642         return SUCCESS;
2643       else
2644         {
2645           gfc_error ("NULL appears on right-hand side in assignment at %L",
2646                      &rvalue->where);
2647           return FAILURE;
2648         }
2649     }
2650
2651    if (sym->attr.cray_pointee
2652        && lvalue->ref != NULL
2653        && lvalue->ref->u.ar.type == AR_FULL
2654        && lvalue->ref->u.ar.as->cp_was_assumed)
2655      {
2656        gfc_error ("Vector assignment to assumed-size Cray Pointee at %L "
2657                   "is illegal", &lvalue->where);
2658        return FAILURE;
2659      }
2660
2661   /* This is possibly a typo: x = f() instead of x => f().  */
2662   if (gfc_option.warn_surprising 
2663       && rvalue->expr_type == EXPR_FUNCTION
2664       && rvalue->symtree->n.sym->attr.pointer)
2665     gfc_warning ("POINTER valued function appears on right-hand side of "
2666                  "assignment at %L", &rvalue->where);
2667
2668   /* Check size of array assignments.  */
2669   if (lvalue->rank != 0 && rvalue->rank != 0
2670       && gfc_check_conformance ("Array assignment", lvalue, rvalue) != SUCCESS)
2671     return FAILURE;
2672
2673   if (gfc_compare_types (&lvalue->ts, &rvalue->ts))
2674     return SUCCESS;
2675
2676   if (!conform)
2677     {
2678       /* Numeric can be converted to any other numeric. And Hollerith can be
2679          converted to any other type.  */
2680       if ((gfc_numeric_ts (&lvalue->ts) && gfc_numeric_ts (&rvalue->ts))
2681           || rvalue->ts.type == BT_HOLLERITH)
2682         return SUCCESS;
2683
2684       if (lvalue->ts.type == BT_LOGICAL && rvalue->ts.type == BT_LOGICAL)
2685         return SUCCESS;
2686
2687       gfc_error ("Incompatible types in assignment at %L, %s to %s",
2688                  &rvalue->where, gfc_typename (&rvalue->ts),
2689                  gfc_typename (&lvalue->ts));
2690
2691       return FAILURE;
2692     }
2693
2694   return gfc_convert_type (rvalue, &lvalue->ts, 1);
2695 }
2696
2697
2698 /* Check that a pointer assignment is OK.  We first check lvalue, and
2699    we only check rvalue if it's not an assignment to NULL() or a
2700    NULLIFY statement.  */
2701
2702 try
2703 gfc_check_pointer_assign (gfc_expr *lvalue, gfc_expr *rvalue)
2704 {
2705   symbol_attribute attr;
2706   gfc_ref *ref;
2707   int is_pure;
2708   int pointer, check_intent_in;
2709
2710   if (lvalue->symtree->n.sym->ts.type == BT_UNKNOWN)
2711     {
2712       gfc_error ("Pointer assignment target is not a POINTER at %L",
2713                  &lvalue->where);
2714       return FAILURE;
2715     }
2716
2717   if (lvalue->symtree->n.sym->attr.flavor == FL_PROCEDURE
2718       && lvalue->symtree->n.sym->attr.use_assoc)
2719     {
2720       gfc_error ("'%s' in the pointer assignment at %L cannot be an "
2721                  "l-value since it is a procedure",
2722                  lvalue->symtree->n.sym->name, &lvalue->where);
2723       return FAILURE;
2724     }
2725
2726
2727   /* Check INTENT(IN), unless the object itself is the component or
2728      sub-component of a pointer.  */
2729   check_intent_in = 1;
2730   pointer = lvalue->symtree->n.sym->attr.pointer;
2731
2732   for (ref = lvalue->ref; ref; ref = ref->next)
2733     {
2734       if (pointer)
2735         check_intent_in = 0;
2736
2737       if (ref->type == REF_COMPONENT && ref->u.c.component->pointer)
2738         pointer = 1;
2739     }
2740
2741   if (check_intent_in && lvalue->symtree->n.sym->attr.intent == INTENT_IN)
2742     {
2743       gfc_error ("Cannot assign to INTENT(IN) variable '%s' at %L",
2744                  lvalue->symtree->n.sym->name, &lvalue->where);
2745       return FAILURE;
2746     }
2747
2748   if (!pointer)
2749     {
2750       gfc_error ("Pointer assignment to non-POINTER at %L", &lvalue->where);
2751       return FAILURE;
2752     }
2753
2754   is_pure = gfc_pure (NULL);
2755
2756   if (is_pure && gfc_impure_variable (lvalue->symtree->n.sym)
2757         && lvalue->symtree->n.sym->value != rvalue)
2758     {
2759       gfc_error ("Bad pointer object in PURE procedure at %L", &lvalue->where);
2760       return FAILURE;
2761     }
2762
2763   /* If rvalue is a NULL() or NULLIFY, we're done. Otherwise the type,
2764      kind, etc for lvalue and rvalue must match, and rvalue must be a
2765      pure variable if we're in a pure function.  */
2766   if (rvalue->expr_type == EXPR_NULL && rvalue->ts.type == BT_UNKNOWN)
2767     return SUCCESS;
2768
2769   if (!gfc_compare_types (&lvalue->ts, &rvalue->ts))
2770     {
2771       gfc_error ("Different types in pointer assignment at %L",
2772                  &lvalue->where);
2773       return FAILURE;
2774     }
2775
2776   if (lvalue->ts.kind != rvalue->ts.kind)
2777     {
2778       gfc_error ("Different kind type parameters in pointer "
2779                  "assignment at %L", &lvalue->where);
2780       return FAILURE;
2781     }
2782
2783   if (lvalue->rank != rvalue->rank)
2784     {
2785       gfc_error ("Different ranks in pointer assignment at %L",
2786                  &lvalue->where);
2787       return FAILURE;
2788     }
2789
2790   /* Now punt if we are dealing with a NULLIFY(X) or X = NULL(X).  */
2791   if (rvalue->expr_type == EXPR_NULL)
2792     return SUCCESS;
2793
2794   if (lvalue->ts.type == BT_CHARACTER
2795       && lvalue->ts.cl && rvalue->ts.cl
2796       && lvalue->ts.cl->length && rvalue->ts.cl->length
2797       && abs (gfc_dep_compare_expr (lvalue->ts.cl->length,
2798                                     rvalue->ts.cl->length)) == 1)
2799     {
2800       gfc_error ("Different character lengths in pointer "
2801                  "assignment at %L", &lvalue->where);
2802       return FAILURE;
2803     }
2804
2805   attr = gfc_expr_attr (rvalue);
2806   if (!attr.target && !attr.pointer)
2807     {
2808       gfc_error ("Pointer assignment target is neither TARGET "
2809                  "nor POINTER at %L", &rvalue->where);
2810       return FAILURE;
2811     }
2812
2813   if (is_pure && gfc_impure_variable (rvalue->symtree->n.sym))
2814     {
2815       gfc_error ("Bad target in pointer assignment in PURE "
2816                  "procedure at %L", &rvalue->where);
2817     }
2818
2819   if (gfc_has_vector_index (rvalue))
2820     {
2821       gfc_error ("Pointer assignment with vector subscript "
2822                  "on rhs at %L", &rvalue->where);
2823       return FAILURE;
2824     }
2825
2826   if (attr.protected && attr.use_assoc)
2827     {
2828       gfc_error ("Pointer assigment target has PROTECTED "
2829                  "attribute at %L", &rvalue->where);
2830       return FAILURE;
2831     }
2832
2833   return SUCCESS;
2834 }
2835
2836
2837 /* Relative of gfc_check_assign() except that the lvalue is a single
2838    symbol.  Used for initialization assignments.  */
2839
2840 try
2841 gfc_check_assign_symbol (gfc_symbol *sym, gfc_expr *rvalue)
2842 {
2843   gfc_expr lvalue;
2844   try r;
2845
2846   memset (&lvalue, '\0', sizeof (gfc_expr));
2847
2848   lvalue.expr_type = EXPR_VARIABLE;
2849   lvalue.ts = sym->ts;
2850   if (sym->as)
2851     lvalue.rank = sym->as->rank;
2852   lvalue.symtree = (gfc_symtree *) gfc_getmem (sizeof (gfc_symtree));
2853   lvalue.symtree->n.sym = sym;
2854   lvalue.where = sym->declared_at;
2855
2856   if (sym->attr.pointer)
2857     r = gfc_check_pointer_assign (&lvalue, rvalue);
2858   else
2859     r = gfc_check_assign (&lvalue, rvalue, 1);
2860
2861   gfc_free (lvalue.symtree);
2862
2863   return r;
2864 }
2865
2866
2867 /* Get an expression for a default initializer.  */
2868
2869 gfc_expr *
2870 gfc_default_initializer (gfc_typespec *ts)
2871 {
2872   gfc_constructor *tail;
2873   gfc_expr *init;
2874   gfc_component *c;
2875
2876   init = NULL;
2877
2878   /* See if we have a default initializer.  */
2879   for (c = ts->derived->components; c; c = c->next)
2880     {
2881       if ((c->initializer || c->allocatable) && init == NULL)
2882         init = gfc_get_expr ();
2883     }
2884
2885   if (init == NULL)
2886     return NULL;
2887
2888   /* Build the constructor.  */
2889   init->expr_type = EXPR_STRUCTURE;
2890   init->ts = *ts;
2891   init->where = ts->derived->declared_at;
2892   tail = NULL;
2893   for (c = ts->derived->components; c; c = c->next)
2894     {
2895       if (tail == NULL)
2896         init->value.constructor = tail = gfc_get_constructor ();
2897       else
2898         {
2899           tail->next = gfc_get_constructor ();
2900           tail = tail->next;
2901         }
2902
2903       if (c->initializer)
2904         tail->expr = gfc_copy_expr (c->initializer);
2905
2906       if (c->allocatable)
2907         {
2908           tail->expr = gfc_get_expr ();
2909           tail->expr->expr_type = EXPR_NULL;
2910           tail->expr->ts = c->ts;
2911         }
2912     }
2913   return init;
2914 }
2915
2916
2917 /* Given a symbol, create an expression node with that symbol as a
2918    variable. If the symbol is array valued, setup a reference of the
2919    whole array.  */
2920
2921 gfc_expr *
2922 gfc_get_variable_expr (gfc_symtree *var)
2923 {
2924   gfc_expr *e;
2925
2926   e = gfc_get_expr ();
2927   e->expr_type = EXPR_VARIABLE;
2928   e->symtree = var;
2929   e->ts = var->n.sym->ts;
2930
2931   if (var->n.sym->as != NULL)
2932     {
2933       e->rank = var->n.sym->as->rank;
2934       e->ref = gfc_get_ref ();
2935       e->ref->type = REF_ARRAY;
2936       e->ref->u.ar.type = AR_FULL;
2937     }
2938
2939   return e;
2940 }
2941
2942
2943 /* Traverse expr, marking all EXPR_VARIABLE symbols referenced.  */
2944
2945 void
2946 gfc_expr_set_symbols_referenced (gfc_expr *expr)
2947 {
2948   gfc_actual_arglist *arg;
2949   gfc_constructor *c;
2950   gfc_ref *ref;
2951   int i;
2952
2953   if (!expr) return;
2954
2955   switch (expr->expr_type)
2956     {
2957     case EXPR_OP:
2958       gfc_expr_set_symbols_referenced (expr->value.op.op1);
2959       gfc_expr_set_symbols_referenced (expr->value.op.op2);
2960       break;
2961
2962     case EXPR_FUNCTION:
2963       for (arg = expr->value.function.actual; arg; arg = arg->next)
2964         gfc_expr_set_symbols_referenced (arg->expr);
2965       break;
2966
2967     case EXPR_VARIABLE:
2968       gfc_set_sym_referenced (expr->symtree->n.sym);
2969       break;
2970
2971     case EXPR_CONSTANT:
2972     case EXPR_NULL:
2973     case EXPR_SUBSTRING:
2974       break;
2975
2976     case EXPR_STRUCTURE:
2977     case EXPR_ARRAY:
2978       for (c = expr->value.constructor; c; c = c->next)
2979         gfc_expr_set_symbols_referenced (c->expr);
2980       break;
2981
2982     default:
2983       gcc_unreachable ();
2984       break;
2985     }
2986
2987     for (ref = expr->ref; ref; ref = ref->next)
2988       switch (ref->type)
2989         {
2990         case REF_ARRAY:
2991           for (i = 0; i < ref->u.ar.dimen; i++)
2992             {
2993               gfc_expr_set_symbols_referenced (ref->u.ar.start[i]);
2994               gfc_expr_set_symbols_referenced (ref->u.ar.end[i]);
2995               gfc_expr_set_symbols_referenced (ref->u.ar.stride[i]);
2996             }
2997           break;
2998            
2999         case REF_COMPONENT:
3000           break;
3001            
3002         case REF_SUBSTRING:
3003           gfc_expr_set_symbols_referenced (ref->u.ss.start);
3004           gfc_expr_set_symbols_referenced (ref->u.ss.end);
3005           break;
3006            
3007         default:
3008           gcc_unreachable ();
3009           break;
3010         }
3011 }