OSDN Git Service

2010-04-09 Tobias Burnus <burnus@net-b.de>
[pf3gnuchains/gcc-fork.git] / gcc / fortran / array.c
1 /* Array things
2    Copyright (C) 2000, 2001, 2002, 2004, 2005, 2006, 2007, 2008, 2009, 2010
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 "match.h"
26
27 /**************** Array reference matching subroutines *****************/
28
29 /* Copy an array reference structure.  */
30
31 gfc_array_ref *
32 gfc_copy_array_ref (gfc_array_ref *src)
33 {
34   gfc_array_ref *dest;
35   int i;
36
37   if (src == NULL)
38     return NULL;
39
40   dest = gfc_get_array_ref ();
41
42   *dest = *src;
43
44   for (i = 0; i < GFC_MAX_DIMENSIONS; i++)
45     {
46       dest->start[i] = gfc_copy_expr (src->start[i]);
47       dest->end[i] = gfc_copy_expr (src->end[i]);
48       dest->stride[i] = gfc_copy_expr (src->stride[i]);
49     }
50
51   dest->offset = gfc_copy_expr (src->offset);
52
53   return dest;
54 }
55
56
57 /* Match a single dimension of an array reference.  This can be a
58    single element or an array section.  Any modifications we've made
59    to the ar structure are cleaned up by the caller.  If the init
60    is set, we require the subscript to be a valid initialization
61    expression.  */
62
63 static match
64 match_subscript (gfc_array_ref *ar, int init, bool match_star)
65 {
66   match m;
67   bool star = false;
68   int i;
69
70   i = ar->dimen + ar->codimen;
71
72   ar->c_where[i] = gfc_current_locus;
73   ar->start[i] = ar->end[i] = ar->stride[i] = NULL;
74
75   /* We can't be sure of the difference between DIMEN_ELEMENT and
76      DIMEN_VECTOR until we know the type of the element itself at
77      resolution time.  */
78
79   ar->dimen_type[i] = DIMEN_UNKNOWN;
80
81   if (gfc_match_char (':') == MATCH_YES)
82     goto end_element;
83
84   /* Get start element.  */
85   if (match_star && (m = gfc_match_char ('*')) == MATCH_YES)
86     star = true;
87
88   if (!star && init)
89     m = gfc_match_init_expr (&ar->start[i]);
90   else if (!star)
91     m = gfc_match_expr (&ar->start[i]);
92
93   if (m == MATCH_NO)
94     gfc_error ("Expected array subscript at %C");
95   if (m != MATCH_YES)
96     return MATCH_ERROR;
97
98   if (gfc_match_char (':') == MATCH_NO)
99     goto matched;
100
101   if (star)
102     {
103       gfc_error ("Unexpected '*' in coarray subscript at %C");
104       return MATCH_ERROR;
105     }
106
107   /* Get an optional end element.  Because we've seen the colon, we
108      definitely have a range along this dimension.  */
109 end_element:
110   ar->dimen_type[i] = DIMEN_RANGE;
111
112   if (match_star && (m = gfc_match_char ('*')) == MATCH_YES)
113     star = true;
114   else if (init)
115     m = gfc_match_init_expr (&ar->end[i]);
116   else
117     m = gfc_match_expr (&ar->end[i]);
118
119   if (m == MATCH_ERROR)
120     return MATCH_ERROR;
121
122   /* See if we have an optional stride.  */
123   if (gfc_match_char (':') == MATCH_YES)
124     {
125       if (star)
126         {
127           gfc_error ("Strides not allowed in coarray subscript at %C");
128           return MATCH_ERROR;
129         }
130
131       m = init ? gfc_match_init_expr (&ar->stride[i])
132                : gfc_match_expr (&ar->stride[i]);
133
134       if (m == MATCH_NO)
135         gfc_error ("Expected array subscript stride at %C");
136       if (m != MATCH_YES)
137         return MATCH_ERROR;
138     }
139
140 matched:
141   if (star)
142     ar->dimen_type[i] = DIMEN_STAR;
143
144   return MATCH_YES;
145 }
146
147
148 /* Match an array reference, whether it is the whole array or a
149    particular elements or a section. If init is set, the reference has
150    to consist of init expressions.  */
151
152 match
153 gfc_match_array_ref (gfc_array_ref *ar, gfc_array_spec *as, int init,
154                      int corank)
155 {
156   match m;
157   bool matched_bracket = false;
158
159   memset (ar, '\0', sizeof (ar));
160
161   ar->where = gfc_current_locus;
162   ar->as = as;
163   ar->type = AR_UNKNOWN;
164
165   if (gfc_match_char ('[') == MATCH_YES)
166     {
167        matched_bracket = true;
168        goto coarray;
169     }
170
171   if (gfc_match_char ('(') != MATCH_YES)
172     {
173       ar->type = AR_FULL;
174       ar->dimen = 0;
175       return MATCH_YES;
176     }
177
178   for (ar->dimen = 0; ar->dimen < GFC_MAX_DIMENSIONS; ar->dimen++)
179     {
180       m = match_subscript (ar, init, false);
181       if (m == MATCH_ERROR)
182         return MATCH_ERROR;
183
184       if (gfc_match_char (')') == MATCH_YES)
185         {
186           ar->dimen++;
187           goto coarray;
188         }
189
190       if (gfc_match_char (',') != MATCH_YES)
191         {
192           gfc_error ("Invalid form of array reference at %C");
193           return MATCH_ERROR;
194         }
195     }
196
197   gfc_error ("Array reference at %C cannot have more than %d dimensions",
198              GFC_MAX_DIMENSIONS);
199   return MATCH_ERROR;
200
201 coarray:
202   if (!matched_bracket && gfc_match_char ('[') != MATCH_YES)
203     {
204       if (ar->dimen > 0)
205         return MATCH_YES;
206       else
207         return MATCH_ERROR;
208     }
209
210   if (gfc_option.coarray == GFC_FCOARRAY_NONE)
211     {
212       gfc_error ("Coarrays disabled at %C, use -fcoarray= to enable");
213       return MATCH_ERROR;
214     }
215
216   if (corank == 0)
217     {
218         gfc_error ("Unexpected coarray designator at %C");
219         return MATCH_ERROR;
220     }
221
222   for (ar->codimen = 0; ar->codimen + ar->dimen < GFC_MAX_DIMENSIONS; ar->codimen++)
223     {
224       m = match_subscript (ar, init, ar->codimen == (corank - 1));
225       if (m == MATCH_ERROR)
226         return MATCH_ERROR;
227
228       if (gfc_match_char (']') == MATCH_YES)
229         {
230           ar->codimen++;
231           return MATCH_YES;
232         }
233
234       if (gfc_match_char (',') != MATCH_YES)
235         {
236           gfc_error ("Invalid form of coarray reference at %C");
237           return MATCH_ERROR;
238         }
239     }
240
241   gfc_error ("Array reference at %C cannot have more than %d dimensions",
242              GFC_MAX_DIMENSIONS);
243   return MATCH_ERROR;
244
245 }
246
247
248 /************** Array specification matching subroutines ***************/
249
250 /* Free all of the expressions associated with array bounds
251    specifications.  */
252
253 void
254 gfc_free_array_spec (gfc_array_spec *as)
255 {
256   int i;
257
258   if (as == NULL)
259     return;
260
261   for (i = 0; i < as->rank + as->corank; i++)
262     {
263       gfc_free_expr (as->lower[i]);
264       gfc_free_expr (as->upper[i]);
265     }
266
267   gfc_free (as);
268 }
269
270
271 /* Take an array bound, resolves the expression, that make up the
272    shape and check associated constraints.  */
273
274 static gfc_try
275 resolve_array_bound (gfc_expr *e, int check_constant)
276 {
277   if (e == NULL)
278     return SUCCESS;
279
280   if (gfc_resolve_expr (e) == FAILURE
281       || gfc_specification_expr (e) == FAILURE)
282     return FAILURE;
283
284   if (check_constant && gfc_is_constant_expr (e) == 0)
285     {
286       gfc_error ("Variable '%s' at %L in this context must be constant",
287                  e->symtree->n.sym->name, &e->where);
288       return FAILURE;
289     }
290
291   return SUCCESS;
292 }
293
294
295 /* Takes an array specification, resolves the expressions that make up
296    the shape and make sure everything is integral.  */
297
298 gfc_try
299 gfc_resolve_array_spec (gfc_array_spec *as, int check_constant)
300 {
301   gfc_expr *e;
302   int i;
303
304   if (as == NULL)
305     return SUCCESS;
306
307   for (i = 0; i < as->rank + as->corank; i++)
308     {
309       e = as->lower[i];
310       if (resolve_array_bound (e, check_constant) == FAILURE)
311         return FAILURE;
312
313       e = as->upper[i];
314       if (resolve_array_bound (e, check_constant) == FAILURE)
315         return FAILURE;
316
317       if ((as->lower[i] == NULL) || (as->upper[i] == NULL))
318         continue;
319
320       /* If the size is negative in this dimension, set it to zero.  */
321       if (as->lower[i]->expr_type == EXPR_CONSTANT
322             && as->upper[i]->expr_type == EXPR_CONSTANT
323             && mpz_cmp (as->upper[i]->value.integer,
324                         as->lower[i]->value.integer) < 0)
325         {
326           gfc_free_expr (as->upper[i]);
327           as->upper[i] = gfc_copy_expr (as->lower[i]);
328           mpz_sub_ui (as->upper[i]->value.integer,
329                       as->upper[i]->value.integer, 1);
330         }
331     }
332
333   return SUCCESS;
334 }
335
336
337 /* Match a single array element specification.  The return values as
338    well as the upper and lower bounds of the array spec are filled
339    in according to what we see on the input.  The caller makes sure
340    individual specifications make sense as a whole.
341
342
343         Parsed       Lower   Upper  Returned
344         ------------------------------------
345           :           NULL    NULL   AS_DEFERRED (*)
346           x            1       x     AS_EXPLICIT
347           x:           x      NULL   AS_ASSUMED_SHAPE
348           x:y          x       y     AS_EXPLICIT
349           x:*          x      NULL   AS_ASSUMED_SIZE
350           *            1      NULL   AS_ASSUMED_SIZE
351
352   (*) For non-pointer dummy arrays this is AS_ASSUMED_SHAPE.  This
353   is fixed during the resolution of formal interfaces.
354
355    Anything else AS_UNKNOWN.  */
356
357 static array_type
358 match_array_element_spec (gfc_array_spec *as)
359 {
360   gfc_expr **upper, **lower;
361   match m;
362
363   lower = &as->lower[as->rank + as->corank - 1];
364   upper = &as->upper[as->rank + as->corank - 1];
365
366   if (gfc_match_char ('*') == MATCH_YES)
367     {
368       *lower = gfc_int_expr (1);
369       return AS_ASSUMED_SIZE;
370     }
371
372   if (gfc_match_char (':') == MATCH_YES)
373     return AS_DEFERRED;
374
375   m = gfc_match_expr (upper);
376   if (m == MATCH_NO)
377     gfc_error ("Expected expression in array specification at %C");
378   if (m != MATCH_YES)
379     return AS_UNKNOWN;
380   if (gfc_expr_check_typed (*upper, gfc_current_ns, false) == FAILURE)
381     return AS_UNKNOWN;
382
383   if (gfc_match_char (':') == MATCH_NO)
384     {
385       *lower = gfc_int_expr (1);
386       return AS_EXPLICIT;
387     }
388
389   *lower = *upper;
390   *upper = NULL;
391
392   if (gfc_match_char ('*') == MATCH_YES)
393     return AS_ASSUMED_SIZE;
394
395   m = gfc_match_expr (upper);
396   if (m == MATCH_ERROR)
397     return AS_UNKNOWN;
398   if (m == MATCH_NO)
399     return AS_ASSUMED_SHAPE;
400   if (gfc_expr_check_typed (*upper, gfc_current_ns, false) == FAILURE)
401     return AS_UNKNOWN;
402
403   return AS_EXPLICIT;
404 }
405
406
407 /* Matches an array specification, incidentally figuring out what sort
408    it is. Match either a normal array specification, or a coarray spec
409    or both. Optionally allow [:] for coarrays.  */
410
411 match
412 gfc_match_array_spec (gfc_array_spec **asp, bool match_dim, bool match_codim)
413 {
414   array_type current_type;
415   gfc_array_spec *as;
416   int i;
417  
418   as = gfc_get_array_spec ();
419   as->corank = 0;
420   as->rank = 0;
421
422   for (i = 0; i < GFC_MAX_DIMENSIONS; i++)
423     {
424       as->lower[i] = NULL;
425       as->upper[i] = NULL;
426     }
427
428   if (!match_dim)
429     goto coarray;
430
431   if (gfc_match_char ('(') != MATCH_YES)
432     {
433       if (!match_codim)
434         goto done;
435       goto coarray;
436     }
437
438   for (;;)
439     {
440       as->rank++;
441       current_type = match_array_element_spec (as);
442
443       if (as->rank == 1)
444         {
445           if (current_type == AS_UNKNOWN)
446             goto cleanup;
447           as->type = current_type;
448         }
449       else
450         switch (as->type)
451           {             /* See how current spec meshes with the existing.  */
452           case AS_UNKNOWN:
453             goto cleanup;
454
455           case AS_EXPLICIT:
456             if (current_type == AS_ASSUMED_SIZE)
457               {
458                 as->type = AS_ASSUMED_SIZE;
459                 break;
460               }
461
462             if (current_type == AS_EXPLICIT)
463               break;
464
465             gfc_error ("Bad array specification for an explicitly shaped "
466                        "array at %C");
467
468             goto cleanup;
469
470           case AS_ASSUMED_SHAPE:
471             if ((current_type == AS_ASSUMED_SHAPE)
472                 || (current_type == AS_DEFERRED))
473               break;
474
475             gfc_error ("Bad array specification for assumed shape "
476                        "array at %C");
477             goto cleanup;
478
479           case AS_DEFERRED:
480             if (current_type == AS_DEFERRED)
481               break;
482
483             if (current_type == AS_ASSUMED_SHAPE)
484               {
485                 as->type = AS_ASSUMED_SHAPE;
486                 break;
487               }
488
489             gfc_error ("Bad specification for deferred shape array at %C");
490             goto cleanup;
491
492           case AS_ASSUMED_SIZE:
493             gfc_error ("Bad specification for assumed size array at %C");
494             goto cleanup;
495           }
496
497       if (gfc_match_char (')') == MATCH_YES)
498         break;
499
500       if (gfc_match_char (',') != MATCH_YES)
501         {
502           gfc_error ("Expected another dimension in array declaration at %C");
503           goto cleanup;
504         }
505
506       if (as->rank + as->corank >= GFC_MAX_DIMENSIONS)
507         {
508           gfc_error ("Array specification at %C has more than %d dimensions",
509                      GFC_MAX_DIMENSIONS);
510           goto cleanup;
511         }
512
513       if (as->corank + as->rank >= 7
514           && gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Array "
515                              "specification at %C with more than 7 dimensions")
516              == FAILURE)
517         goto cleanup;
518     }
519
520   if (!match_codim)
521     goto done;
522
523 coarray:
524   if (gfc_match_char ('[')  != MATCH_YES)
525     goto done;
526
527   if (gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Coarray declaration at %C")
528       == FAILURE)
529     goto cleanup;
530
531   if (gfc_option.coarray == GFC_FCOARRAY_NONE)
532     {
533       gfc_error ("Coarrays disabled at %C, use -fcoarray= to enable");
534       goto cleanup;
535     }
536
537   for (;;)
538     {
539       as->corank++;
540       current_type = match_array_element_spec (as);
541
542       if (current_type == AS_UNKNOWN)
543         goto cleanup;
544
545       if (as->corank == 1)
546         as->cotype = current_type;
547       else
548         switch (as->cotype)
549           { /* See how current spec meshes with the existing.  */
550             case AS_UNKNOWN:
551               goto cleanup;
552
553             case AS_EXPLICIT:
554               if (current_type == AS_ASSUMED_SIZE)
555                 {
556                   as->cotype = AS_ASSUMED_SIZE;
557                   break;
558                 }
559
560               if (current_type == AS_EXPLICIT)
561                 break;
562
563               gfc_error ("Bad array specification for an explicitly "
564                          "shaped array at %C");
565
566               goto cleanup;
567
568             case AS_ASSUMED_SHAPE:
569               if ((current_type == AS_ASSUMED_SHAPE)
570                   || (current_type == AS_DEFERRED))
571                 break;
572
573               gfc_error ("Bad array specification for assumed shape "
574                          "array at %C");
575               goto cleanup;
576
577             case AS_DEFERRED:
578               if (current_type == AS_DEFERRED)
579                 break;
580
581               if (current_type == AS_ASSUMED_SHAPE)
582                 {
583                   as->cotype = AS_ASSUMED_SHAPE;
584                   break;
585                 }
586
587               gfc_error ("Bad specification for deferred shape array at %C");
588               goto cleanup;
589
590             case AS_ASSUMED_SIZE:
591               gfc_error ("Bad specification for assumed size array at %C");
592               goto cleanup;
593           }
594
595       if (gfc_match_char (']') == MATCH_YES)
596         break;
597
598       if (gfc_match_char (',') != MATCH_YES)
599         {
600           gfc_error ("Expected another dimension in array declaration at %C");
601           goto cleanup;
602         }
603
604       if (as->corank >= GFC_MAX_DIMENSIONS)
605         {
606           gfc_error ("Array specification at %C has more than %d "
607                      "dimensions", GFC_MAX_DIMENSIONS);
608           goto cleanup;
609         }
610     }
611
612   if (current_type == AS_EXPLICIT)
613     {
614       gfc_error ("Upper bound of last coarray dimension must be '*' at %C");
615       goto cleanup;
616     }
617
618   if (as->cotype == AS_ASSUMED_SIZE)
619     as->cotype = AS_EXPLICIT;
620
621   if (as->rank == 0)
622     as->type = as->cotype;
623
624 done:
625   if (as->rank == 0 && as->corank == 0)
626     {
627       *asp = NULL;
628       gfc_free_array_spec (as);
629       return MATCH_NO;
630     }
631
632   /* If a lower bounds of an assumed shape array is blank, put in one.  */
633   if (as->type == AS_ASSUMED_SHAPE)
634     {
635       for (i = 0; i < as->rank + as->corank; i++)
636         {
637           if (as->lower[i] == NULL)
638             as->lower[i] = gfc_int_expr (1);
639         }
640     }
641
642   *asp = as;
643
644   return MATCH_YES;
645
646 cleanup:
647   /* Something went wrong.  */
648   gfc_free_array_spec (as);
649   return MATCH_ERROR;
650 }
651
652
653 /* Given a symbol and an array specification, modify the symbol to
654    have that array specification.  The error locus is needed in case
655    something goes wrong.  On failure, the caller must free the spec.  */
656
657 gfc_try
658 gfc_set_array_spec (gfc_symbol *sym, gfc_array_spec *as, locus *error_loc)
659 {
660   int i;
661
662   if (as == NULL)
663     return SUCCESS;
664
665   if (as->rank
666       && gfc_add_dimension (&sym->attr, sym->name, error_loc) == FAILURE)
667     return FAILURE;
668
669   if (as->corank
670       && gfc_add_codimension (&sym->attr, sym->name, error_loc) == FAILURE)
671     return FAILURE;
672
673   if (sym->as == NULL)
674     {
675       sym->as = as;
676       return SUCCESS;
677     }
678
679   if (as->corank)
680     {
681       /* The "sym" has no corank (checked via gfc_add_codimension). Thus
682          the codimension is simply added.  */
683       gcc_assert (as->rank == 0 && sym->as->corank == 0);
684
685       sym->as->cotype = as->cotype;
686       sym->as->corank = as->corank;
687       for (i = 0; i < as->corank; i++)
688         {
689           sym->as->lower[sym->as->rank + i] = as->lower[i];
690           sym->as->upper[sym->as->rank + i] = as->upper[i];
691         }
692     }
693   else
694     {
695       /* The "sym" has no rank (checked via gfc_add_dimension). Thus
696          the dimension is added - but first the codimensions (if existing
697          need to be shifted to make space for the dimension.  */
698       gcc_assert (as->corank == 0 && sym->as->rank == 0);
699
700       sym->as->rank = as->rank;
701       sym->as->type = as->type;
702       sym->as->cray_pointee = as->cray_pointee;
703       sym->as->cp_was_assumed = as->cp_was_assumed;
704
705       for (i = 0; i < sym->as->corank; i++)
706         {
707           sym->as->lower[as->rank + i] = sym->as->lower[i];
708           sym->as->upper[as->rank + i] = sym->as->upper[i];
709         }
710       for (i = 0; i < as->rank; i++)
711         {
712           sym->as->lower[i] = as->lower[i];
713           sym->as->upper[i] = as->upper[i];
714         }
715     }
716
717   gfc_free (as);
718   return SUCCESS;
719 }
720
721
722 /* Copy an array specification.  */
723
724 gfc_array_spec *
725 gfc_copy_array_spec (gfc_array_spec *src)
726 {
727   gfc_array_spec *dest;
728   int i;
729
730   if (src == NULL)
731     return NULL;
732
733   dest = gfc_get_array_spec ();
734
735   *dest = *src;
736
737   for (i = 0; i < dest->rank + dest->corank; i++)
738     {
739       dest->lower[i] = gfc_copy_expr (dest->lower[i]);
740       dest->upper[i] = gfc_copy_expr (dest->upper[i]);
741     }
742
743   return dest;
744 }
745
746
747 /* Returns nonzero if the two expressions are equal.  Only handles integer
748    constants.  */
749
750 static int
751 compare_bounds (gfc_expr *bound1, gfc_expr *bound2)
752 {
753   if (bound1 == NULL || bound2 == NULL
754       || bound1->expr_type != EXPR_CONSTANT
755       || bound2->expr_type != EXPR_CONSTANT
756       || bound1->ts.type != BT_INTEGER
757       || bound2->ts.type != BT_INTEGER)
758     gfc_internal_error ("gfc_compare_array_spec(): Array spec clobbered");
759
760   if (mpz_cmp (bound1->value.integer, bound2->value.integer) == 0)
761     return 1;
762   else
763     return 0;
764 }
765
766
767 /* Compares two array specifications.  They must be constant or deferred
768    shape.  */
769
770 int
771 gfc_compare_array_spec (gfc_array_spec *as1, gfc_array_spec *as2)
772 {
773   int i;
774
775   if (as1 == NULL && as2 == NULL)
776     return 1;
777
778   if (as1 == NULL || as2 == NULL)
779     return 0;
780
781   if (as1->rank != as2->rank)
782     return 0;
783
784   if (as1->corank != as2->corank)
785     return 0;
786
787   if (as1->rank == 0)
788     return 1;
789
790   if (as1->type != as2->type)
791     return 0;
792
793   if (as1->type == AS_EXPLICIT)
794     for (i = 0; i < as1->rank + as1->corank; i++)
795       {
796         if (compare_bounds (as1->lower[i], as2->lower[i]) == 0)
797           return 0;
798
799         if (compare_bounds (as1->upper[i], as2->upper[i]) == 0)
800           return 0;
801       }
802
803   return 1;
804 }
805
806
807 /****************** Array constructor functions ******************/
808
809 /* Start an array constructor.  The constructor starts with zero
810    elements and should be appended to by gfc_append_constructor().  */
811
812 gfc_expr *
813 gfc_start_constructor (bt type, int kind, locus *where)
814 {
815   gfc_expr *result;
816
817   result = gfc_get_expr ();
818
819   result->expr_type = EXPR_ARRAY;
820   result->rank = 1;
821
822   result->ts.type = type;
823   result->ts.kind = kind;
824   result->where = *where;
825   return result;
826 }
827
828
829 /* Given an array constructor expression, append the new expression
830    node onto the constructor.  */
831
832 void
833 gfc_append_constructor (gfc_expr *base, gfc_expr *new_expr)
834 {
835   gfc_constructor *c;
836
837   if (base->value.constructor == NULL)
838     base->value.constructor = c = gfc_get_constructor ();
839   else
840     {
841       c = base->value.constructor;
842       while (c->next)
843         c = c->next;
844
845       c->next = gfc_get_constructor ();
846       c = c->next;
847     }
848
849   c->expr = new_expr;
850
851   if (new_expr
852       && (new_expr->ts.type != base->ts.type || new_expr->ts.kind != base->ts.kind))
853     gfc_internal_error ("gfc_append_constructor(): New node has wrong kind");
854 }
855
856
857 /* Given an array constructor expression, insert the new expression's
858    constructor onto the base's one according to the offset.  */
859
860 void
861 gfc_insert_constructor (gfc_expr *base, gfc_constructor *c1)
862 {
863   gfc_constructor *c, *pre;
864   expr_t type;
865   int t;
866
867   type = base->expr_type;
868
869   if (base->value.constructor == NULL)
870     base->value.constructor = c1;
871   else
872     {
873       c = pre = base->value.constructor;
874       while (c)
875         {
876           if (type == EXPR_ARRAY)
877             {
878               t = mpz_cmp (c->n.offset, c1->n.offset);
879               if (t < 0)
880                 {
881                   pre = c;
882                   c = c->next;
883                 }
884               else if (t == 0)
885                 {
886                   gfc_error ("duplicated initializer");
887                   break;
888                 }
889               else
890                 break;
891             }
892           else
893             {
894               pre = c;
895               c = c->next;
896             }
897         }
898
899       if (pre != c)
900         {
901           pre->next = c1;
902           c1->next = c;
903         }
904       else
905         {
906           c1->next = c;
907           base->value.constructor = c1;
908         }
909     }
910 }
911
912
913 /* Get a new constructor.  */
914
915 gfc_constructor *
916 gfc_get_constructor (void)
917 {
918   gfc_constructor *c;
919
920   c = XCNEW (gfc_constructor);
921   c->expr = NULL;
922   c->iterator = NULL;
923   c->next = NULL;
924   mpz_init_set_si (c->n.offset, 0);
925   mpz_init_set_si (c->repeat, 0);
926   return c;
927 }
928
929
930 /* Free chains of gfc_constructor structures.  */
931
932 void
933 gfc_free_constructor (gfc_constructor *p)
934 {
935   gfc_constructor *next;
936
937   if (p == NULL)
938     return;
939
940   for (; p; p = next)
941     {
942       next = p->next;
943
944       if (p->expr)
945         gfc_free_expr (p->expr);
946       if (p->iterator != NULL)
947         gfc_free_iterator (p->iterator, 1);
948       mpz_clear (p->n.offset);
949       mpz_clear (p->repeat);
950       gfc_free (p);
951     }
952 }
953
954
955 /* Given an expression node that might be an array constructor and a
956    symbol, make sure that no iterators in this or child constructors
957    use the symbol as an implied-DO iterator.  Returns nonzero if a
958    duplicate was found.  */
959
960 static int
961 check_duplicate_iterator (gfc_constructor *c, gfc_symbol *master)
962 {
963   gfc_expr *e;
964
965   for (; c; c = c->next)
966     {
967       e = c->expr;
968
969       if (e->expr_type == EXPR_ARRAY
970           && check_duplicate_iterator (e->value.constructor, master))
971         return 1;
972
973       if (c->iterator == NULL)
974         continue;
975
976       if (c->iterator->var->symtree->n.sym == master)
977         {
978           gfc_error ("DO-iterator '%s' at %L is inside iterator of the "
979                      "same name", master->name, &c->where);
980
981           return 1;
982         }
983     }
984
985   return 0;
986 }
987
988
989 /* Forward declaration because these functions are mutually recursive.  */
990 static match match_array_cons_element (gfc_constructor **);
991
992 /* Match a list of array elements.  */
993
994 static match
995 match_array_list (gfc_constructor **result)
996 {
997   gfc_constructor *p, *head, *tail, *new_cons;
998   gfc_iterator iter;
999   locus old_loc;
1000   gfc_expr *e;
1001   match m;
1002   int n;
1003
1004   old_loc = gfc_current_locus;
1005
1006   if (gfc_match_char ('(') == MATCH_NO)
1007     return MATCH_NO;
1008
1009   memset (&iter, '\0', sizeof (gfc_iterator));
1010   head = NULL;
1011
1012   m = match_array_cons_element (&head);
1013   if (m != MATCH_YES)
1014     goto cleanup;
1015
1016   tail = head;
1017
1018   if (gfc_match_char (',') != MATCH_YES)
1019     {
1020       m = MATCH_NO;
1021       goto cleanup;
1022     }
1023
1024   for (n = 1;; n++)
1025     {
1026       m = gfc_match_iterator (&iter, 0);
1027       if (m == MATCH_YES)
1028         break;
1029       if (m == MATCH_ERROR)
1030         goto cleanup;
1031
1032       m = match_array_cons_element (&new_cons);
1033       if (m == MATCH_ERROR)
1034         goto cleanup;
1035       if (m == MATCH_NO)
1036         {
1037           if (n > 2)
1038             goto syntax;
1039           m = MATCH_NO;
1040           goto cleanup;         /* Could be a complex constant */
1041         }
1042
1043       tail->next = new_cons;
1044       tail = new_cons;
1045
1046       if (gfc_match_char (',') != MATCH_YES)
1047         {
1048           if (n > 2)
1049             goto syntax;
1050           m = MATCH_NO;
1051           goto cleanup;
1052         }
1053     }
1054
1055   if (gfc_match_char (')') != MATCH_YES)
1056     goto syntax;
1057
1058   if (check_duplicate_iterator (head, iter.var->symtree->n.sym))
1059     {
1060       m = MATCH_ERROR;
1061       goto cleanup;
1062     }
1063
1064   e = gfc_get_expr ();
1065   e->expr_type = EXPR_ARRAY;
1066   e->where = old_loc;
1067   e->value.constructor = head;
1068
1069   p = gfc_get_constructor ();
1070   p->where = gfc_current_locus;
1071   p->iterator = gfc_get_iterator ();
1072   *p->iterator = iter;
1073
1074   p->expr = e;
1075   *result = p;
1076
1077   return MATCH_YES;
1078
1079 syntax:
1080   gfc_error ("Syntax error in array constructor at %C");
1081   m = MATCH_ERROR;
1082
1083 cleanup:
1084   gfc_free_constructor (head);
1085   gfc_free_iterator (&iter, 0);
1086   gfc_current_locus = old_loc;
1087   return m;
1088 }
1089
1090
1091 /* Match a single element of an array constructor, which can be a
1092    single expression or a list of elements.  */
1093
1094 static match
1095 match_array_cons_element (gfc_constructor **result)
1096 {
1097   gfc_constructor *p;
1098   gfc_expr *expr;
1099   match m;
1100
1101   m = match_array_list (result);
1102   if (m != MATCH_NO)
1103     return m;
1104
1105   m = gfc_match_expr (&expr);
1106   if (m != MATCH_YES)
1107     return m;
1108
1109   p = gfc_get_constructor ();
1110   p->where = gfc_current_locus;
1111   p->expr = expr;
1112
1113   *result = p;
1114   return MATCH_YES;
1115 }
1116
1117
1118 /* Match an array constructor.  */
1119
1120 match
1121 gfc_match_array_constructor (gfc_expr **result)
1122 {
1123   gfc_constructor *head, *tail, *new_cons;
1124   gfc_expr *expr;
1125   gfc_typespec ts;
1126   locus where;
1127   match m;
1128   const char *end_delim;
1129   bool seen_ts;
1130
1131   if (gfc_match (" (/") == MATCH_NO)
1132     {
1133       if (gfc_match (" [") == MATCH_NO)
1134         return MATCH_NO;
1135       else
1136         {
1137           if (gfc_notify_std (GFC_STD_F2003, "Fortran 2003: [...] "
1138                               "style array constructors at %C") == FAILURE)
1139             return MATCH_ERROR;
1140           end_delim = " ]";
1141         }
1142     }
1143   else
1144     end_delim = " /)";
1145
1146   where = gfc_current_locus;
1147   head = tail = NULL;
1148   seen_ts = false;
1149
1150   /* Try to match an optional "type-spec ::"  */
1151   if (gfc_match_decl_type_spec (&ts, 0) == MATCH_YES)
1152     {
1153       seen_ts = (gfc_match (" ::") == MATCH_YES);
1154
1155       if (seen_ts)
1156         {
1157           if (gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Array constructor "
1158                               "including type specification at %C") == FAILURE)
1159             goto cleanup;
1160         }
1161     }
1162
1163   if (! seen_ts)
1164     gfc_current_locus = where;
1165
1166   if (gfc_match (end_delim) == MATCH_YES)
1167     {
1168       if (seen_ts)
1169         goto done;
1170       else
1171         {
1172           gfc_error ("Empty array constructor at %C is not allowed");
1173           goto cleanup;
1174         }
1175     }
1176
1177   for (;;)
1178     {
1179       m = match_array_cons_element (&new_cons);
1180       if (m == MATCH_ERROR)
1181         goto cleanup;
1182       if (m == MATCH_NO)
1183         goto syntax;
1184
1185       if (head == NULL)
1186         head = new_cons;
1187       else
1188         tail->next = new_cons;
1189
1190       tail = new_cons;
1191
1192       if (gfc_match_char (',') == MATCH_NO)
1193         break;
1194     }
1195
1196   if (gfc_match (end_delim) == MATCH_NO)
1197     goto syntax;
1198
1199 done:
1200   expr = gfc_get_expr ();
1201
1202   expr->expr_type = EXPR_ARRAY;
1203
1204   expr->value.constructor = head;
1205   /* Size must be calculated at resolution time.  */
1206
1207   if (seen_ts)
1208     expr->ts = ts;
1209   else
1210     expr->ts.type = BT_UNKNOWN;
1211   
1212   if (expr->ts.u.cl)
1213     expr->ts.u.cl->length_from_typespec = seen_ts;
1214
1215   expr->where = where;
1216   expr->rank = 1;
1217
1218   *result = expr;
1219   return MATCH_YES;
1220
1221 syntax:
1222   gfc_error ("Syntax error in array constructor at %C");
1223
1224 cleanup:
1225   gfc_free_constructor (head);
1226   return MATCH_ERROR;
1227 }
1228
1229
1230
1231 /************** Check array constructors for correctness **************/
1232
1233 /* Given an expression, compare it's type with the type of the current
1234    constructor.  Returns nonzero if an error was issued.  The
1235    cons_state variable keeps track of whether the type of the
1236    constructor being read or resolved is known to be good, bad or just
1237    starting out.  */
1238
1239 static gfc_typespec constructor_ts;
1240 static enum
1241 { CONS_START, CONS_GOOD, CONS_BAD }
1242 cons_state;
1243
1244 static int
1245 check_element_type (gfc_expr *expr, bool convert)
1246 {
1247   if (cons_state == CONS_BAD)
1248     return 0;                   /* Suppress further errors */
1249
1250   if (cons_state == CONS_START)
1251     {
1252       if (expr->ts.type == BT_UNKNOWN)
1253         cons_state = CONS_BAD;
1254       else
1255         {
1256           cons_state = CONS_GOOD;
1257           constructor_ts = expr->ts;
1258         }
1259
1260       return 0;
1261     }
1262
1263   if (gfc_compare_types (&constructor_ts, &expr->ts))
1264     return 0;
1265
1266   if (convert)
1267     return gfc_convert_type (expr, &constructor_ts, 1) == SUCCESS ? 0 : 1;
1268
1269   gfc_error ("Element in %s array constructor at %L is %s",
1270              gfc_typename (&constructor_ts), &expr->where,
1271              gfc_typename (&expr->ts));
1272
1273   cons_state = CONS_BAD;
1274   return 1;
1275 }
1276
1277
1278 /* Recursive work function for gfc_check_constructor_type().  */
1279
1280 static gfc_try
1281 check_constructor_type (gfc_constructor *c, bool convert)
1282 {
1283   gfc_expr *e;
1284
1285   for (; c; c = c->next)
1286     {
1287       e = c->expr;
1288
1289       if (e->expr_type == EXPR_ARRAY)
1290         {
1291           if (check_constructor_type (e->value.constructor, convert) == FAILURE)
1292             return FAILURE;
1293
1294           continue;
1295         }
1296
1297       if (check_element_type (e, convert))
1298         return FAILURE;
1299     }
1300
1301   return SUCCESS;
1302 }
1303
1304
1305 /* Check that all elements of an array constructor are the same type.
1306    On FAILURE, an error has been generated.  */
1307
1308 gfc_try
1309 gfc_check_constructor_type (gfc_expr *e)
1310 {
1311   gfc_try t;
1312
1313   if (e->ts.type != BT_UNKNOWN)
1314     {
1315       cons_state = CONS_GOOD;
1316       constructor_ts = e->ts;
1317     }
1318   else
1319     {
1320       cons_state = CONS_START;
1321       gfc_clear_ts (&constructor_ts);
1322     }
1323
1324   /* If e->ts.type != BT_UNKNOWN, the array constructor included a
1325      typespec, and we will now convert the values on the fly.  */
1326   t = check_constructor_type (e->value.constructor, e->ts.type != BT_UNKNOWN);
1327   if (t == SUCCESS && e->ts.type == BT_UNKNOWN)
1328     e->ts = constructor_ts;
1329
1330   return t;
1331 }
1332
1333
1334
1335 typedef struct cons_stack
1336 {
1337   gfc_iterator *iterator;
1338   struct cons_stack *previous;
1339 }
1340 cons_stack;
1341
1342 static cons_stack *base;
1343
1344 static gfc_try check_constructor (gfc_constructor *, gfc_try (*) (gfc_expr *));
1345
1346 /* Check an EXPR_VARIABLE expression in a constructor to make sure
1347    that that variable is an iteration variables.  */
1348
1349 gfc_try
1350 gfc_check_iter_variable (gfc_expr *expr)
1351 {
1352   gfc_symbol *sym;
1353   cons_stack *c;
1354
1355   sym = expr->symtree->n.sym;
1356
1357   for (c = base; c; c = c->previous)
1358     if (sym == c->iterator->var->symtree->n.sym)
1359       return SUCCESS;
1360
1361   return FAILURE;
1362 }
1363
1364
1365 /* Recursive work function for gfc_check_constructor().  This amounts
1366    to calling the check function for each expression in the
1367    constructor, giving variables with the names of iterators a pass.  */
1368
1369 static gfc_try
1370 check_constructor (gfc_constructor *c, gfc_try (*check_function) (gfc_expr *))
1371 {
1372   cons_stack element;
1373   gfc_expr *e;
1374   gfc_try t;
1375
1376   for (; c; c = c->next)
1377     {
1378       e = c->expr;
1379
1380       if (e->expr_type != EXPR_ARRAY)
1381         {
1382           if ((*check_function) (e) == FAILURE)
1383             return FAILURE;
1384           continue;
1385         }
1386
1387       element.previous = base;
1388       element.iterator = c->iterator;
1389
1390       base = &element;
1391       t = check_constructor (e->value.constructor, check_function);
1392       base = element.previous;
1393
1394       if (t == FAILURE)
1395         return FAILURE;
1396     }
1397
1398   /* Nothing went wrong, so all OK.  */
1399   return SUCCESS;
1400 }
1401
1402
1403 /* Checks a constructor to see if it is a particular kind of
1404    expression -- specification, restricted, or initialization as
1405    determined by the check_function.  */
1406
1407 gfc_try
1408 gfc_check_constructor (gfc_expr *expr, gfc_try (*check_function) (gfc_expr *))
1409 {
1410   cons_stack *base_save;
1411   gfc_try t;
1412
1413   base_save = base;
1414   base = NULL;
1415
1416   t = check_constructor (expr->value.constructor, check_function);
1417   base = base_save;
1418
1419   return t;
1420 }
1421
1422
1423
1424 /**************** Simplification of array constructors ****************/
1425
1426 iterator_stack *iter_stack;
1427
1428 typedef struct
1429 {
1430   gfc_constructor *new_head, *new_tail;
1431   int extract_count, extract_n;
1432   gfc_expr *extracted;
1433   mpz_t *count;
1434
1435   mpz_t *offset;
1436   gfc_component *component;
1437   mpz_t *repeat;
1438
1439   gfc_try (*expand_work_function) (gfc_expr *);
1440 }
1441 expand_info;
1442
1443 static expand_info current_expand;
1444
1445 static gfc_try expand_constructor (gfc_constructor *);
1446
1447
1448 /* Work function that counts the number of elements present in a
1449    constructor.  */
1450
1451 static gfc_try
1452 count_elements (gfc_expr *e)
1453 {
1454   mpz_t result;
1455
1456   if (e->rank == 0)
1457     mpz_add_ui (*current_expand.count, *current_expand.count, 1);
1458   else
1459     {
1460       if (gfc_array_size (e, &result) == FAILURE)
1461         {
1462           gfc_free_expr (e);
1463           return FAILURE;
1464         }
1465
1466       mpz_add (*current_expand.count, *current_expand.count, result);
1467       mpz_clear (result);
1468     }
1469
1470   gfc_free_expr (e);
1471   return SUCCESS;
1472 }
1473
1474
1475 /* Work function that extracts a particular element from an array
1476    constructor, freeing the rest.  */
1477
1478 static gfc_try
1479 extract_element (gfc_expr *e)
1480 {
1481   if (e->rank != 0)
1482     {                           /* Something unextractable */
1483       gfc_free_expr (e);
1484       return FAILURE;
1485     }
1486
1487   if (current_expand.extract_count == current_expand.extract_n)
1488     current_expand.extracted = e;
1489   else
1490     gfc_free_expr (e);
1491
1492   current_expand.extract_count++;
1493   
1494   return SUCCESS;
1495 }
1496
1497
1498 /* Work function that constructs a new constructor out of the old one,
1499    stringing new elements together.  */
1500
1501 static gfc_try
1502 expand (gfc_expr *e)
1503 {
1504   if (current_expand.new_head == NULL)
1505     current_expand.new_head = current_expand.new_tail =
1506       gfc_get_constructor ();
1507   else
1508     {
1509       current_expand.new_tail->next = gfc_get_constructor ();
1510       current_expand.new_tail = current_expand.new_tail->next;
1511     }
1512
1513   current_expand.new_tail->where = e->where;
1514   current_expand.new_tail->expr = e;
1515
1516   mpz_set (current_expand.new_tail->n.offset, *current_expand.offset);
1517   current_expand.new_tail->n.component = current_expand.component;
1518   mpz_set (current_expand.new_tail->repeat, *current_expand.repeat);
1519   return SUCCESS;
1520 }
1521
1522
1523 /* Given an initialization expression that is a variable reference,
1524    substitute the current value of the iteration variable.  */
1525
1526 void
1527 gfc_simplify_iterator_var (gfc_expr *e)
1528 {
1529   iterator_stack *p;
1530
1531   for (p = iter_stack; p; p = p->prev)
1532     if (e->symtree == p->variable)
1533       break;
1534
1535   if (p == NULL)
1536     return;             /* Variable not found */
1537
1538   gfc_replace_expr (e, gfc_int_expr (0));
1539
1540   mpz_set (e->value.integer, p->value);
1541
1542   return;
1543 }
1544
1545
1546 /* Expand an expression with that is inside of a constructor,
1547    recursing into other constructors if present.  */
1548
1549 static gfc_try
1550 expand_expr (gfc_expr *e)
1551 {
1552   if (e->expr_type == EXPR_ARRAY)
1553     return expand_constructor (e->value.constructor);
1554
1555   e = gfc_copy_expr (e);
1556
1557   if (gfc_simplify_expr (e, 1) == FAILURE)
1558     {
1559       gfc_free_expr (e);
1560       return FAILURE;
1561     }
1562
1563   return current_expand.expand_work_function (e);
1564 }
1565
1566
1567 static gfc_try
1568 expand_iterator (gfc_constructor *c)
1569 {
1570   gfc_expr *start, *end, *step;
1571   iterator_stack frame;
1572   mpz_t trip;
1573   gfc_try t;
1574
1575   end = step = NULL;
1576
1577   t = FAILURE;
1578
1579   mpz_init (trip);
1580   mpz_init (frame.value);
1581   frame.prev = NULL;
1582
1583   start = gfc_copy_expr (c->iterator->start);
1584   if (gfc_simplify_expr (start, 1) == FAILURE)
1585     goto cleanup;
1586
1587   if (start->expr_type != EXPR_CONSTANT || start->ts.type != BT_INTEGER)
1588     goto cleanup;
1589
1590   end = gfc_copy_expr (c->iterator->end);
1591   if (gfc_simplify_expr (end, 1) == FAILURE)
1592     goto cleanup;
1593
1594   if (end->expr_type != EXPR_CONSTANT || end->ts.type != BT_INTEGER)
1595     goto cleanup;
1596
1597   step = gfc_copy_expr (c->iterator->step);
1598   if (gfc_simplify_expr (step, 1) == FAILURE)
1599     goto cleanup;
1600
1601   if (step->expr_type != EXPR_CONSTANT || step->ts.type != BT_INTEGER)
1602     goto cleanup;
1603
1604   if (mpz_sgn (step->value.integer) == 0)
1605     {
1606       gfc_error ("Iterator step at %L cannot be zero", &step->where);
1607       goto cleanup;
1608     }
1609
1610   /* Calculate the trip count of the loop.  */
1611   mpz_sub (trip, end->value.integer, start->value.integer);
1612   mpz_add (trip, trip, step->value.integer);
1613   mpz_tdiv_q (trip, trip, step->value.integer);
1614
1615   mpz_set (frame.value, start->value.integer);
1616
1617   frame.prev = iter_stack;
1618   frame.variable = c->iterator->var->symtree;
1619   iter_stack = &frame;
1620
1621   while (mpz_sgn (trip) > 0)
1622     {
1623       if (expand_expr (c->expr) == FAILURE)
1624         goto cleanup;
1625
1626       mpz_add (frame.value, frame.value, step->value.integer);
1627       mpz_sub_ui (trip, trip, 1);
1628     }
1629
1630   t = SUCCESS;
1631
1632 cleanup:
1633   gfc_free_expr (start);
1634   gfc_free_expr (end);
1635   gfc_free_expr (step);
1636
1637   mpz_clear (trip);
1638   mpz_clear (frame.value);
1639
1640   iter_stack = frame.prev;
1641
1642   return t;
1643 }
1644
1645
1646 /* Expand a constructor into constant constructors without any
1647    iterators, calling the work function for each of the expanded
1648    expressions.  The work function needs to either save or free the
1649    passed expression.  */
1650
1651 static gfc_try
1652 expand_constructor (gfc_constructor *c)
1653 {
1654   gfc_expr *e;
1655
1656   for (; c; c = c->next)
1657     {
1658       if (c->iterator != NULL)
1659         {
1660           if (expand_iterator (c) == FAILURE)
1661             return FAILURE;
1662           continue;
1663         }
1664
1665       e = c->expr;
1666
1667       if (e->expr_type == EXPR_ARRAY)
1668         {
1669           if (expand_constructor (e->value.constructor) == FAILURE)
1670             return FAILURE;
1671
1672           continue;
1673         }
1674
1675       e = gfc_copy_expr (e);
1676       if (gfc_simplify_expr (e, 1) == FAILURE)
1677         {
1678           gfc_free_expr (e);
1679           return FAILURE;
1680         }
1681       current_expand.offset = &c->n.offset;
1682       current_expand.component = c->n.component;
1683       current_expand.repeat = &c->repeat;
1684       if (current_expand.expand_work_function (e) == FAILURE)
1685         return FAILURE;
1686     }
1687   return SUCCESS;
1688 }
1689
1690
1691 /* Top level subroutine for expanding constructors.  We only expand
1692    constructor if they are small enough.  */
1693
1694 gfc_try
1695 gfc_expand_constructor (gfc_expr *e)
1696 {
1697   expand_info expand_save;
1698   gfc_expr *f;
1699   gfc_try rc;
1700
1701   f = gfc_get_array_element (e, gfc_option.flag_max_array_constructor);
1702   if (f != NULL)
1703     {
1704       gfc_free_expr (f);
1705       return SUCCESS;
1706     }
1707
1708   expand_save = current_expand;
1709   current_expand.new_head = current_expand.new_tail = NULL;
1710
1711   iter_stack = NULL;
1712
1713   current_expand.expand_work_function = expand;
1714
1715   if (expand_constructor (e->value.constructor) == FAILURE)
1716     {
1717       gfc_free_constructor (current_expand.new_head);
1718       rc = FAILURE;
1719       goto done;
1720     }
1721
1722   gfc_free_constructor (e->value.constructor);
1723   e->value.constructor = current_expand.new_head;
1724
1725   rc = SUCCESS;
1726
1727 done:
1728   current_expand = expand_save;
1729
1730   return rc;
1731 }
1732
1733
1734 /* Work function for checking that an element of a constructor is a
1735    constant, after removal of any iteration variables.  We return
1736    FAILURE if not so.  */
1737
1738 static gfc_try
1739 is_constant_element (gfc_expr *e)
1740 {
1741   int rv;
1742
1743   rv = gfc_is_constant_expr (e);
1744   gfc_free_expr (e);
1745
1746   return rv ? SUCCESS : FAILURE;
1747 }
1748
1749
1750 /* Given an array constructor, determine if the constructor is
1751    constant or not by expanding it and making sure that all elements
1752    are constants.  This is a bit of a hack since something like (/ (i,
1753    i=1,100000000) /) will take a while as* opposed to a more clever
1754    function that traverses the expression tree. FIXME.  */
1755
1756 int
1757 gfc_constant_ac (gfc_expr *e)
1758 {
1759   expand_info expand_save;
1760   gfc_try rc;
1761   gfc_constructor * con;
1762   
1763   rc = SUCCESS;
1764
1765   if (e->value.constructor
1766       && e->value.constructor->expr->expr_type == EXPR_ARRAY)
1767     {
1768       /* Expand the constructor.  */
1769       iter_stack = NULL;
1770       expand_save = current_expand;
1771       current_expand.expand_work_function = is_constant_element;
1772
1773       rc = expand_constructor (e->value.constructor);
1774
1775       current_expand = expand_save;
1776     }
1777   else
1778     {
1779       /* No need to expand this further.  */
1780       for (con = e->value.constructor; con; con = con->next)
1781         {
1782           if (con->expr->expr_type == EXPR_CONSTANT)
1783             continue;
1784           else
1785             {
1786               if (!gfc_is_constant_expr (con->expr))
1787                 rc = FAILURE;
1788             }
1789         }
1790     }
1791
1792   if (rc == FAILURE)
1793     return 0;
1794
1795   return 1;
1796 }
1797
1798
1799 /* Returns nonzero if an array constructor has been completely
1800    expanded (no iterators) and zero if iterators are present.  */
1801
1802 int
1803 gfc_expanded_ac (gfc_expr *e)
1804 {
1805   gfc_constructor *p;
1806
1807   if (e->expr_type == EXPR_ARRAY)
1808     for (p = e->value.constructor; p; p = p->next)
1809       if (p->iterator != NULL || !gfc_expanded_ac (p->expr))
1810         return 0;
1811
1812   return 1;
1813 }
1814
1815
1816 /*************** Type resolution of array constructors ***************/
1817
1818 /* Recursive array list resolution function.  All of the elements must
1819    be of the same type.  */
1820
1821 static gfc_try
1822 resolve_array_list (gfc_constructor *p)
1823 {
1824   gfc_try t;
1825
1826   t = SUCCESS;
1827
1828   for (; p; p = p->next)
1829     {
1830       if (p->iterator != NULL
1831           && gfc_resolve_iterator (p->iterator, false) == FAILURE)
1832         t = FAILURE;
1833
1834       if (gfc_resolve_expr (p->expr) == FAILURE)
1835         t = FAILURE;
1836     }
1837
1838   return t;
1839 }
1840
1841 /* Resolve character array constructor. If it has a specified constant character
1842    length, pad/truncate the elements here; if the length is not specified and
1843    all elements are of compile-time known length, emit an error as this is
1844    invalid.  */
1845
1846 gfc_try
1847 gfc_resolve_character_array_constructor (gfc_expr *expr)
1848 {
1849   gfc_constructor *p;
1850   int found_length;
1851
1852   gcc_assert (expr->expr_type == EXPR_ARRAY);
1853   gcc_assert (expr->ts.type == BT_CHARACTER);
1854
1855   if (expr->ts.u.cl == NULL)
1856     {
1857       for (p = expr->value.constructor; p; p = p->next)
1858         if (p->expr->ts.u.cl != NULL)
1859           {
1860             /* Ensure that if there is a char_len around that it is
1861                used; otherwise the middle-end confuses them!  */
1862             expr->ts.u.cl = p->expr->ts.u.cl;
1863             goto got_charlen;
1864           }
1865
1866       expr->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
1867     }
1868
1869 got_charlen:
1870
1871   found_length = -1;
1872
1873   if (expr->ts.u.cl->length == NULL)
1874     {
1875       /* Check that all constant string elements have the same length until
1876          we reach the end or find a variable-length one.  */
1877
1878       for (p = expr->value.constructor; p; p = p->next)
1879         {
1880           int current_length = -1;
1881           gfc_ref *ref;
1882           for (ref = p->expr->ref; ref; ref = ref->next)
1883             if (ref->type == REF_SUBSTRING
1884                 && ref->u.ss.start->expr_type == EXPR_CONSTANT
1885                 && ref->u.ss.end->expr_type == EXPR_CONSTANT)
1886               break;
1887
1888           if (p->expr->expr_type == EXPR_CONSTANT)
1889             current_length = p->expr->value.character.length;
1890           else if (ref)
1891             {
1892               long j;
1893               j = mpz_get_ui (ref->u.ss.end->value.integer)
1894                 - mpz_get_ui (ref->u.ss.start->value.integer) + 1;
1895               current_length = (int) j;
1896             }
1897           else if (p->expr->ts.u.cl && p->expr->ts.u.cl->length
1898                    && p->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT)
1899             {
1900               long j;
1901               j = mpz_get_si (p->expr->ts.u.cl->length->value.integer);
1902               current_length = (int) j;
1903             }
1904           else
1905             return SUCCESS;
1906
1907           gcc_assert (current_length != -1);
1908
1909           if (found_length == -1)
1910             found_length = current_length;
1911           else if (found_length != current_length)
1912             {
1913               gfc_error ("Different CHARACTER lengths (%d/%d) in array"
1914                          " constructor at %L", found_length, current_length,
1915                          &p->expr->where);
1916               return FAILURE;
1917             }
1918
1919           gcc_assert (found_length == current_length);
1920         }
1921
1922       gcc_assert (found_length != -1);
1923
1924       /* Update the character length of the array constructor.  */
1925       expr->ts.u.cl->length = gfc_int_expr (found_length);
1926     }
1927   else 
1928     {
1929       /* We've got a character length specified.  It should be an integer,
1930          otherwise an error is signalled elsewhere.  */
1931       gcc_assert (expr->ts.u.cl->length);
1932
1933       /* If we've got a constant character length, pad according to this.
1934          gfc_extract_int does check for BT_INTEGER and EXPR_CONSTANT and sets
1935          max_length only if they pass.  */
1936       gfc_extract_int (expr->ts.u.cl->length, &found_length);
1937
1938       /* Now pad/truncate the elements accordingly to the specified character
1939          length.  This is ok inside this conditional, as in the case above
1940          (without typespec) all elements are verified to have the same length
1941          anyway.  */
1942       if (found_length != -1)
1943         for (p = expr->value.constructor; p; p = p->next)
1944           if (p->expr->expr_type == EXPR_CONSTANT)
1945             {
1946               gfc_expr *cl = NULL;
1947               int current_length = -1;
1948               bool has_ts;
1949
1950               if (p->expr->ts.u.cl && p->expr->ts.u.cl->length)
1951               {
1952                 cl = p->expr->ts.u.cl->length;
1953                 gfc_extract_int (cl, &current_length);
1954               }
1955
1956               /* If gfc_extract_int above set current_length, we implicitly
1957                  know the type is BT_INTEGER and it's EXPR_CONSTANT.  */
1958
1959               has_ts = (expr->ts.u.cl && expr->ts.u.cl->length_from_typespec);
1960
1961               if (! cl
1962                   || (current_length != -1 && current_length < found_length))
1963                 gfc_set_constant_character_len (found_length, p->expr,
1964                                                 has_ts ? -1 : found_length);
1965             }
1966     }
1967
1968   return SUCCESS;
1969 }
1970
1971
1972 /* Resolve all of the expressions in an array list.  */
1973
1974 gfc_try
1975 gfc_resolve_array_constructor (gfc_expr *expr)
1976 {
1977   gfc_try t;
1978
1979   t = resolve_array_list (expr->value.constructor);
1980   if (t == SUCCESS)
1981     t = gfc_check_constructor_type (expr);
1982
1983   /* gfc_resolve_character_array_constructor is called in gfc_resolve_expr after
1984      the call to this function, so we don't need to call it here; if it was
1985      called twice, an error message there would be duplicated.  */
1986
1987   return t;
1988 }
1989
1990
1991 /* Copy an iterator structure.  */
1992
1993 static gfc_iterator *
1994 copy_iterator (gfc_iterator *src)
1995 {
1996   gfc_iterator *dest;
1997
1998   if (src == NULL)
1999     return NULL;
2000
2001   dest = gfc_get_iterator ();
2002
2003   dest->var = gfc_copy_expr (src->var);
2004   dest->start = gfc_copy_expr (src->start);
2005   dest->end = gfc_copy_expr (src->end);
2006   dest->step = gfc_copy_expr (src->step);
2007
2008   return dest;
2009 }
2010
2011
2012 /* Copy a constructor structure.  */
2013
2014 gfc_constructor *
2015 gfc_copy_constructor (gfc_constructor *src)
2016 {
2017   gfc_constructor *dest;
2018   gfc_constructor *tail;
2019
2020   if (src == NULL)
2021     return NULL;
2022
2023   dest = tail = NULL;
2024   while (src)
2025     {
2026       if (dest == NULL)
2027         dest = tail = gfc_get_constructor ();
2028       else
2029         {
2030           tail->next = gfc_get_constructor ();
2031           tail = tail->next;
2032         }
2033       tail->where = src->where;
2034       tail->expr = gfc_copy_expr (src->expr);
2035       tail->iterator = copy_iterator (src->iterator);
2036       mpz_set (tail->n.offset, src->n.offset);
2037       tail->n.component = src->n.component;
2038       mpz_set (tail->repeat, src->repeat);
2039       src = src->next;
2040     }
2041
2042   return dest;
2043 }
2044
2045
2046 /* Given an array expression and an element number (starting at zero),
2047    return a pointer to the array element.  NULL is returned if the
2048    size of the array has been exceeded.  The expression node returned
2049    remains a part of the array and should not be freed.  Access is not
2050    efficient at all, but this is another place where things do not
2051    have to be particularly fast.  */
2052
2053 gfc_expr *
2054 gfc_get_array_element (gfc_expr *array, int element)
2055 {
2056   expand_info expand_save;
2057   gfc_expr *e;
2058   gfc_try rc;
2059
2060   expand_save = current_expand;
2061   current_expand.extract_n = element;
2062   current_expand.expand_work_function = extract_element;
2063   current_expand.extracted = NULL;
2064   current_expand.extract_count = 0;
2065
2066   iter_stack = NULL;
2067
2068   rc = expand_constructor (array->value.constructor);
2069   e = current_expand.extracted;
2070   current_expand = expand_save;
2071
2072   if (rc == FAILURE)
2073     return NULL;
2074
2075   return e;
2076 }
2077
2078
2079 /********* Subroutines for determining the size of an array *********/
2080
2081 /* These are needed just to accommodate RESHAPE().  There are no
2082    diagnostics here, we just return a negative number if something
2083    goes wrong.  */
2084
2085
2086 /* Get the size of single dimension of an array specification.  The
2087    array is guaranteed to be one dimensional.  */
2088
2089 gfc_try
2090 spec_dimen_size (gfc_array_spec *as, int dimen, mpz_t *result)
2091 {
2092   if (as == NULL)
2093     return FAILURE;
2094
2095   if (dimen < 0 || dimen > as->rank - 1)
2096     gfc_internal_error ("spec_dimen_size(): Bad dimension");
2097
2098   if (as->type != AS_EXPLICIT
2099       || as->lower[dimen]->expr_type != EXPR_CONSTANT
2100       || as->upper[dimen]->expr_type != EXPR_CONSTANT
2101       || as->lower[dimen]->ts.type != BT_INTEGER
2102       || as->upper[dimen]->ts.type != BT_INTEGER)
2103     return FAILURE;
2104
2105   mpz_init (*result);
2106
2107   mpz_sub (*result, as->upper[dimen]->value.integer,
2108            as->lower[dimen]->value.integer);
2109
2110   mpz_add_ui (*result, *result, 1);
2111
2112   return SUCCESS;
2113 }
2114
2115
2116 gfc_try
2117 spec_size (gfc_array_spec *as, mpz_t *result)
2118 {
2119   mpz_t size;
2120   int d;
2121
2122   mpz_init_set_ui (*result, 1);
2123
2124   for (d = 0; d < as->rank; d++)
2125     {
2126       if (spec_dimen_size (as, d, &size) == FAILURE)
2127         {
2128           mpz_clear (*result);
2129           return FAILURE;
2130         }
2131
2132       mpz_mul (*result, *result, size);
2133       mpz_clear (size);
2134     }
2135
2136   return SUCCESS;
2137 }
2138
2139
2140 /* Get the number of elements in an array section.  */
2141
2142 gfc_try
2143 gfc_ref_dimen_size (gfc_array_ref *ar, int dimen, mpz_t *result)
2144 {
2145   mpz_t upper, lower, stride;
2146   gfc_try t;
2147
2148   if (dimen < 0 || ar == NULL || dimen > ar->dimen - 1)
2149     gfc_internal_error ("gfc_ref_dimen_size(): Bad dimension");
2150
2151   switch (ar->dimen_type[dimen])
2152     {
2153     case DIMEN_ELEMENT:
2154       mpz_init (*result);
2155       mpz_set_ui (*result, 1);
2156       t = SUCCESS;
2157       break;
2158
2159     case DIMEN_VECTOR:
2160       t = gfc_array_size (ar->start[dimen], result);    /* Recurse! */
2161       break;
2162
2163     case DIMEN_RANGE:
2164       mpz_init (upper);
2165       mpz_init (lower);
2166       mpz_init (stride);
2167       t = FAILURE;
2168
2169       if (ar->start[dimen] == NULL)
2170         {
2171           if (ar->as->lower[dimen] == NULL
2172               || ar->as->lower[dimen]->expr_type != EXPR_CONSTANT)
2173             goto cleanup;
2174           mpz_set (lower, ar->as->lower[dimen]->value.integer);
2175         }
2176       else
2177         {
2178           if (ar->start[dimen]->expr_type != EXPR_CONSTANT)
2179             goto cleanup;
2180           mpz_set (lower, ar->start[dimen]->value.integer);
2181         }
2182
2183       if (ar->end[dimen] == NULL)
2184         {
2185           if (ar->as->upper[dimen] == NULL
2186               || ar->as->upper[dimen]->expr_type != EXPR_CONSTANT)
2187             goto cleanup;
2188           mpz_set (upper, ar->as->upper[dimen]->value.integer);
2189         }
2190       else
2191         {
2192           if (ar->end[dimen]->expr_type != EXPR_CONSTANT)
2193             goto cleanup;
2194           mpz_set (upper, ar->end[dimen]->value.integer);
2195         }
2196
2197       if (ar->stride[dimen] == NULL)
2198         mpz_set_ui (stride, 1);
2199       else
2200         {
2201           if (ar->stride[dimen]->expr_type != EXPR_CONSTANT)
2202             goto cleanup;
2203           mpz_set (stride, ar->stride[dimen]->value.integer);
2204         }
2205
2206       mpz_init (*result);
2207       mpz_sub (*result, upper, lower);
2208       mpz_add (*result, *result, stride);
2209       mpz_div (*result, *result, stride);
2210
2211       /* Zero stride caught earlier.  */
2212       if (mpz_cmp_ui (*result, 0) < 0)
2213         mpz_set_ui (*result, 0);
2214       t = SUCCESS;
2215
2216     cleanup:
2217       mpz_clear (upper);
2218       mpz_clear (lower);
2219       mpz_clear (stride);
2220       return t;
2221
2222     default:
2223       gfc_internal_error ("gfc_ref_dimen_size(): Bad dimen_type");
2224     }
2225
2226   return t;
2227 }
2228
2229
2230 static gfc_try
2231 ref_size (gfc_array_ref *ar, mpz_t *result)
2232 {
2233   mpz_t size;
2234   int d;
2235
2236   mpz_init_set_ui (*result, 1);
2237
2238   for (d = 0; d < ar->dimen; d++)
2239     {
2240       if (gfc_ref_dimen_size (ar, d, &size) == FAILURE)
2241         {
2242           mpz_clear (*result);
2243           return FAILURE;
2244         }
2245
2246       mpz_mul (*result, *result, size);
2247       mpz_clear (size);
2248     }
2249
2250   return SUCCESS;
2251 }
2252
2253
2254 /* Given an array expression and a dimension, figure out how many
2255    elements it has along that dimension.  Returns SUCCESS if we were
2256    able to return a result in the 'result' variable, FAILURE
2257    otherwise.  */
2258
2259 gfc_try
2260 gfc_array_dimen_size (gfc_expr *array, int dimen, mpz_t *result)
2261 {
2262   gfc_ref *ref;
2263   int i;
2264
2265   if (dimen < 0 || array == NULL || dimen > array->rank - 1)
2266     gfc_internal_error ("gfc_array_dimen_size(): Bad dimension");
2267
2268   switch (array->expr_type)
2269     {
2270     case EXPR_VARIABLE:
2271     case EXPR_FUNCTION:
2272       for (ref = array->ref; ref; ref = ref->next)
2273         {
2274           if (ref->type != REF_ARRAY)
2275             continue;
2276
2277           if (ref->u.ar.type == AR_FULL)
2278             return spec_dimen_size (ref->u.ar.as, dimen, result);
2279
2280           if (ref->u.ar.type == AR_SECTION)
2281             {
2282               for (i = 0; dimen >= 0; i++)
2283                 if (ref->u.ar.dimen_type[i] != DIMEN_ELEMENT)
2284                   dimen--;
2285
2286               return gfc_ref_dimen_size (&ref->u.ar, i - 1, result);
2287             }
2288         }
2289
2290       if (array->shape && array->shape[dimen])
2291         {
2292           mpz_init_set (*result, array->shape[dimen]);
2293           return SUCCESS;
2294         }
2295
2296       if (array->symtree->n.sym->attr.generic
2297           && array->value.function.esym != NULL)
2298         {
2299           if (spec_dimen_size (array->value.function.esym->as, dimen, result)
2300               == FAILURE)
2301             return FAILURE;
2302         }
2303       else if (spec_dimen_size (array->symtree->n.sym->as, dimen, result)
2304                == FAILURE)
2305         return FAILURE;
2306
2307       break;
2308
2309     case EXPR_ARRAY:
2310       if (array->shape == NULL) {
2311         /* Expressions with rank > 1 should have "shape" properly set */
2312         if ( array->rank != 1 )
2313           gfc_internal_error ("gfc_array_dimen_size(): Bad EXPR_ARRAY expr");
2314         return gfc_array_size(array, result);
2315       }
2316
2317       /* Fall through */
2318     default:
2319       if (array->shape == NULL)
2320         return FAILURE;
2321
2322       mpz_init_set (*result, array->shape[dimen]);
2323
2324       break;
2325     }
2326
2327   return SUCCESS;
2328 }
2329
2330
2331 /* Given an array expression, figure out how many elements are in the
2332    array.  Returns SUCCESS if this is possible, and sets the 'result'
2333    variable.  Otherwise returns FAILURE.  */
2334
2335 gfc_try
2336 gfc_array_size (gfc_expr *array, mpz_t *result)
2337 {
2338   expand_info expand_save;
2339   gfc_ref *ref;
2340   int i;
2341   gfc_try t;
2342
2343   switch (array->expr_type)
2344     {
2345     case EXPR_ARRAY:
2346       gfc_push_suppress_errors ();
2347
2348       expand_save = current_expand;
2349
2350       current_expand.count = result;
2351       mpz_init_set_ui (*result, 0);
2352
2353       current_expand.expand_work_function = count_elements;
2354       iter_stack = NULL;
2355
2356       t = expand_constructor (array->value.constructor);
2357
2358       gfc_pop_suppress_errors ();
2359
2360       if (t == FAILURE)
2361         mpz_clear (*result);
2362       current_expand = expand_save;
2363       return t;
2364
2365     case EXPR_VARIABLE:
2366       for (ref = array->ref; ref; ref = ref->next)
2367         {
2368           if (ref->type != REF_ARRAY)
2369             continue;
2370
2371           if (ref->u.ar.type == AR_FULL)
2372             return spec_size (ref->u.ar.as, result);
2373
2374           if (ref->u.ar.type == AR_SECTION)
2375             return ref_size (&ref->u.ar, result);
2376         }
2377
2378       return spec_size (array->symtree->n.sym->as, result);
2379
2380
2381     default:
2382       if (array->rank == 0 || array->shape == NULL)
2383         return FAILURE;
2384
2385       mpz_init_set_ui (*result, 1);
2386
2387       for (i = 0; i < array->rank; i++)
2388         mpz_mul (*result, *result, array->shape[i]);
2389
2390       break;
2391     }
2392
2393   return SUCCESS;
2394 }
2395
2396
2397 /* Given an array reference, return the shape of the reference in an
2398    array of mpz_t integers.  */
2399
2400 gfc_try
2401 gfc_array_ref_shape (gfc_array_ref *ar, mpz_t *shape)
2402 {
2403   int d;
2404   int i;
2405
2406   d = 0;
2407
2408   switch (ar->type)
2409     {
2410     case AR_FULL:
2411       for (; d < ar->as->rank; d++)
2412         if (spec_dimen_size (ar->as, d, &shape[d]) == FAILURE)
2413           goto cleanup;
2414
2415       return SUCCESS;
2416
2417     case AR_SECTION:
2418       for (i = 0; i < ar->dimen; i++)
2419         {
2420           if (ar->dimen_type[i] != DIMEN_ELEMENT)
2421             {
2422               if (gfc_ref_dimen_size (ar, i, &shape[d]) == FAILURE)
2423                 goto cleanup;
2424               d++;
2425             }
2426         }
2427
2428       return SUCCESS;
2429
2430     default:
2431       break;
2432     }
2433
2434 cleanup:
2435   for (d--; d >= 0; d--)
2436     mpz_clear (shape[d]);
2437
2438   return FAILURE;
2439 }
2440
2441
2442 /* Given an array expression, find the array reference structure that
2443    characterizes the reference.  */
2444
2445 gfc_array_ref *
2446 gfc_find_array_ref (gfc_expr *e)
2447 {
2448   gfc_ref *ref;
2449
2450   for (ref = e->ref; ref; ref = ref->next)
2451     if (ref->type == REF_ARRAY
2452         && (ref->u.ar.type == AR_FULL || ref->u.ar.type == AR_SECTION))
2453       break;
2454
2455   if (ref == NULL)
2456     gfc_internal_error ("gfc_find_array_ref(): No ref found");
2457
2458   return &ref->u.ar;
2459 }
2460
2461
2462 /* Find out if an array shape is known at compile time.  */
2463
2464 int
2465 gfc_is_compile_time_shape (gfc_array_spec *as)
2466 {
2467   int i;
2468
2469   if (as->type != AS_EXPLICIT)
2470     return 0;
2471
2472   for (i = 0; i < as->rank; i++)
2473     if (!gfc_is_constant_expr (as->lower[i])
2474         || !gfc_is_constant_expr (as->upper[i]))
2475       return 0;
2476
2477   return 1;
2478 }