Debian Codegraph @

gcc/ada/sem_ch5.adb

raw
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- S E M _ C H 5 --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2025, Free Software Foundation, Inc. --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING3. If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license. --
20 -- --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
23 -- --
24 ------------------------------------------------------------------------------
25
26 with Aspects; use Aspects;
27 with Atree; use Atree;
28 with Checks; use Checks;
29 with Debug; use Debug;
30 with Einfo; use Einfo;
31 with Einfo.Entities; use Einfo.Entities;
32 with Einfo.Utils; use Einfo.Utils;
33 with Errout; use Errout;
34 with Expander; use Expander;
35 with Exp_Ch6; use Exp_Ch6;
36 with Exp_Tss; use Exp_Tss;
37 with Exp_Util; use Exp_Util;
38 with Freeze; use Freeze;
39 with Ghost; use Ghost;
40 with Lib; use Lib;
41 with Lib.Xref; use Lib.Xref;
42 with Mutably_Tagged; use Mutably_Tagged;
43 with Namet; use Namet;
44 with Nlists; use Nlists;
45 with Nmake; use Nmake;
46 with Opt; use Opt;
47 with Sem; use Sem;
48 with Sem_Aux; use Sem_Aux;
49 with Sem_Case; use Sem_Case;
50 with Sem_Ch3; use Sem_Ch3;
51 with Sem_Ch6; use Sem_Ch6;
52 with Sem_Ch8; use Sem_Ch8;
53 with Sem_Dim; use Sem_Dim;
54 with Sem_Disp; use Sem_Disp;
55 with Sem_Elab; use Sem_Elab;
56 with Sem_Eval; use Sem_Eval;
57 with Sem_Res; use Sem_Res;
58 with Sem_Type; use Sem_Type;
59 with Sem_Util; use Sem_Util;
60 with Sem_Warn; use Sem_Warn;
61 with Snames; use Snames;
62 with Stand; use Stand;
63 with Sinfo; use Sinfo;
64 with Sinfo.Nodes; use Sinfo.Nodes;
65 with Sinfo.Utils; use Sinfo.Utils;
66 with Targparm; use Targparm;
67 with Tbuild; use Tbuild;
68 with Ttypes; use Ttypes;
69 with Uintp; use Uintp;
70 with Warnsw; use Warnsw;
71
72 package body Sem_Ch5 is
73
74 Current_Assignment : Node_Id := Empty;
75 -- This variable holds the node for an assignment that contains target
76 -- names. The corresponding flag has been set by the parser, and when
77 -- set the analysis of the RHS must be done with all expansion disabled,
78 -- because the assignment is reanalyzed after expansion has replaced all
79 -- occurrences of the target name appropriately.
80
81 Unblocked_Exit_Count : Nat := 0;
82 -- This variable is used when processing if statements, case statements,
83 -- and block statements. It counts the number of exit points that are not
84 -- blocked by unconditional transfer instructions: for IF and CASE, these
85 -- are the branches of the conditional; for a block, they are the statement
86 -- sequence of the block, and the statement sequences of any exception
87 -- handlers that are part of the block. When processing is complete, if
88 -- this count is zero, it means that control cannot fall through the IF,
89 -- CASE or block statement. This is used for the generation of warning
90 -- messages. This variable is recursively saved on entry to processing the
91 -- construct, and restored on exit.
92
93 function Has_Sec_Stack_Call (N : Node_Id) return Boolean;
94 -- N is the node for an arbitrary construct. This function searches the
95 -- construct N to see if it contains a function call that returns on the
96 -- secondary stack, returning True if any such call is found, and False
97 -- otherwise.
98
99 -- ??? The implementation invokes Sem_Util.Requires_Transient_Scope so it
100 -- will return True if N contains a function call that needs finalization,
101 -- in addition to the above specification. See Analyze_Loop_Statement for
102 -- a similar comment about this entanglement.
103
104 procedure Preanalyze_Range (R_Copy : Node_Id);
105 -- Determine expected type of range or domain of iteration of Ada 2012
106 -- loop by analyzing separate copy. Do the analysis and resolution of the
107 -- copy of the bound(s) with expansion disabled, to prevent the generation
108 -- of finalization actions. This prevents memory leaks when the bounds
109 -- contain calls to functions returning controlled arrays or when the
110 -- domain of iteration is a container.
111
112 ------------------------
113 -- Analyze_Assignment --
114 ------------------------
115
116 -- WARNING: This routine manages Ghost regions. Return statements must be
117 -- replaced by gotos which jump to the end of the routine and restore the
118 -- Ghost mode.
119
120 procedure Analyze_Assignment (N : Node_Id) is
121 Lhs : constant Node_Id := Name (N);
122 Rhs : constant Node_Id := Expression (N);
123
124 Save_Full_Analysis : Boolean := False;
125 -- Force initialization to facilitate static analysis
126
127 procedure Diagnose_Non_Variable_Lhs (N : Node_Id);
128 -- N is the node for the left hand side of an assignment, and it is not
129 -- a variable. This routine issues an appropriate diagnostic.
130
131 function Is_Protected_Part_Of_Constituent
132 (Nod : Node_Id) return Boolean;
133 -- Determine whether arbitrary node Nod denotes a Part_Of constituent of
134 -- a single protected type.
135
136 procedure Kill_Lhs;
137 -- This is called to kill current value settings of a simple variable
138 -- on the left hand side. We call it if we find any error in analyzing
139 -- the assignment, and at the end of processing before setting any new
140 -- current values in place.
141
142 procedure Set_Assignment_Type
143 (Opnd : Node_Id;
144 Opnd_Type : in out Entity_Id);
145 -- Opnd is either the Lhs or Rhs of the assignment, and Opnd_Type is the
146 -- nominal subtype. This procedure is used to deal with cases where the
147 -- nominal subtype must be replaced by the actual subtype.
148
149 function Within_Function return Boolean;
150 -- Determine whether the current scope is a function or appears within
151 -- one.
152
153 -------------------------------
154 -- Diagnose_Non_Variable_Lhs --
155 -------------------------------
156
157 procedure Diagnose_Non_Variable_Lhs (N : Node_Id) is
158 begin
159 -- Not worth posting another error if left hand side already flagged
160 -- as being illegal in some respect.
161
162 if Error_Posted (N) then
163 return;
164
165 -- Some special bad cases of entity names
166
167 elsif Is_Entity_Name (N) then
168 declare
169 Ent : constant Entity_Id := Entity (N);
170
171 begin
172 if Ekind (Ent) = E_Loop_Parameter
173 or else Is_Loop_Parameter (Ent)
174 then
175 Error_Msg_N ("assignment to loop parameter not allowed", N);
176 return;
177
178 elsif Ekind (Ent) = E_In_Parameter then
179 Error_Msg_N
180 ("assignment to IN mode parameter not allowed", N);
181 return;
182
183 -- Renamings of protected private components are turned into
184 -- constants when compiling a protected function. In the case
185 -- of single protected types, the private component appears
186 -- directly.
187
188 elsif (Is_Prival (Ent) and then Within_Function)
189 or else Is_Protected_Component (Ent)
190 then
191 Error_Msg_N
192 ("protected function cannot modify its protected object",
193 N);
194 return;
195 end if;
196 end;
197
198 -- For indexed components, test prefix if it is in array. We do not
199 -- want to recurse for cases where the prefix is a pointer, since we
200 -- may get a message confusing the pointer and what it references.
201
202 elsif Nkind (N) = N_Indexed_Component
203 and then Is_Array_Type (Etype (Prefix (N)))
204 then
205 Diagnose_Non_Variable_Lhs (Prefix (N));
206 return;
207
208 -- Another special case for assignment to discriminant
209
210 elsif Nkind (N) = N_Selected_Component then
211 if Present (Entity (Selector_Name (N)))
212 and then Ekind (Entity (Selector_Name (N))) = E_Discriminant
213 then
214 Error_Msg_N ("assignment to discriminant not allowed", N);
215 return;
216
217 -- For selection from record, diagnose prefix, but note that again
218 -- we only do this for a record, not e.g. for a pointer.
219
220 elsif Is_Record_Type (Etype (Prefix (N))) then
221 Diagnose_Non_Variable_Lhs (Prefix (N));
222 return;
223 end if;
224 end if;
225
226 -- If we fall through, we have no special message to issue
227
228 Error_Msg_N ("left hand side of assignment must be a variable", N);
229 end Diagnose_Non_Variable_Lhs;
230
231 --------------------------------------
232 -- Is_Protected_Part_Of_Constituent --
233 --------------------------------------
234
235 function Is_Protected_Part_Of_Constituent
236 (Nod : Node_Id) return Boolean
237 is
238 Encap_Id : Entity_Id;
239 Var_Id : Entity_Id;
240
241 begin
242 -- Abstract states and variables may act as Part_Of constituents of
243 -- single protected types, however only variables can be modified by
244 -- an assignment.
245
246 if Is_Entity_Name (Nod) then
247 Var_Id := Entity (Nod);
248
249 if Present (Var_Id) and then Ekind (Var_Id) = E_Variable then
250 Encap_Id := Encapsulating_State (Var_Id);
251
252 -- To qualify, the node must denote a reference to a variable
253 -- whose encapsulating state is a single protected object.
254
255 return
256 Present (Encap_Id)
257 and then Is_Single_Protected_Object (Encap_Id);
258 end if;
259 end if;
260
261 return False;
262 end Is_Protected_Part_Of_Constituent;
263
264 --------------
265 -- Kill_Lhs --
266 --------------
267
268 procedure Kill_Lhs is
269 begin
270 if Is_Entity_Name (Lhs) then
271 declare
272 Ent : constant Entity_Id := Entity (Lhs);
273 begin
274 if Present (Ent) then
275 Kill_Current_Values (Ent);
276 end if;
277 end;
278 end if;
279 end Kill_Lhs;
280
281 -------------------------
282 -- Set_Assignment_Type --
283 -------------------------
284
285 procedure Set_Assignment_Type
286 (Opnd : Node_Id;
287 Opnd_Type : in out Entity_Id)
288 is
289 Decl : Node_Id;
290
291 begin
292 Require_Entity (Opnd);
293
294 -- If the assignment operand is an in-out or out parameter, then we
295 -- get the actual subtype (needed for the unconstrained case). If the
296 -- operand is the actual in an entry declaration, then within the
297 -- accept statement it is replaced with a local renaming, which may
298 -- also have an actual subtype. Likewise for a return object that
299 -- lives on the secondary stack.
300
301 if Is_Entity_Name (Opnd)
302 and then (Ekind (Entity (Opnd)) in E_Out_Parameter
303 | E_In_Out_Parameter
304 | E_Generic_In_Out_Parameter
305 or else
306 (Ekind (Entity (Opnd)) = E_Variable
307 and then Nkind (Parent (Entity (Opnd))) =
308 N_Object_Renaming_Declaration
309 and then Nkind (Parent (Parent (Entity (Opnd)))) =
310 N_Accept_Statement)
311 or else Is_Secondary_Stack_Return_Object (Entity (Opnd)))
312 then
313 Opnd_Type := Get_Actual_Subtype (Opnd);
314
315 -- If the assignment operand is a component reference, then we build
316 -- the actual subtype of the component for the unconstrained case,
317 -- unless there is already one or the type is an unchecked union.
318
319 elsif (Nkind (Opnd) = N_Selected_Component
320 or else (Nkind (Opnd) = N_Explicit_Dereference
321 and then No (Actual_Designated_Subtype (Opnd))))
322 and then not Is_Unchecked_Union (Opnd_Type)
323 then
324 -- If the right-hand side contains target names, expansion has
325 -- been disabled to prevent expansion that might move target
326 -- names out of the context of the assignment statement. Restore
327 -- temporarily the current compilation mode so that the actual
328 -- subtype can be built.
329
330 if Nkind (N) = N_Assignment_Statement
331 and then Has_Target_Names (N)
332 and then Present (Current_Assignment)
333 then
334 Expander_Mode_Restore;
335 Full_Analysis := Save_Full_Analysis;
336 Decl := Build_Actual_Subtype_Of_Component (Opnd_Type, Opnd);
337 Expander_Mode_Save_And_Set (False);
338 Full_Analysis := False;
339 else
340 Decl := Build_Actual_Subtype_Of_Component (Opnd_Type, Opnd);
341 end if;
342
343 if Present (Decl) then
344 Insert_Action (N, Decl);
345 Mark_Rewrite_Insertion (Decl);
346 Analyze (Decl);
347 Opnd_Type := Defining_Identifier (Decl);
348 Set_Etype (Opnd, Opnd_Type);
349 Freeze_Itype (Opnd_Type, N);
350
351 elsif Is_Constrained (Etype (Opnd)) then
352 Opnd_Type := Etype (Opnd);
353 end if;
354
355 -- For slice, use the constrained subtype created for the slice
356
357 elsif Nkind (Opnd) = N_Slice then
358 Opnd_Type := Etype (Opnd);
359 end if;
360 end Set_Assignment_Type;
361
362 ---------------------
363 -- Within_Function --
364 ---------------------
365
366 function Within_Function return Boolean is
367 Scop_Id : constant Entity_Id := Current_Scope;
368
369 begin
370 if Ekind (Scop_Id) = E_Function then
371 return True;
372
373 elsif Ekind (Enclosing_Dynamic_Scope (Scop_Id)) = E_Function then
374 return True;
375 end if;
376
377 return False;
378 end Within_Function;
379
380 -- Local variables
381
382 Saved_GM : constant Ghost_Mode_Type := Ghost_Mode;
383 Saved_IGR : constant Node_Id := Ignored_Ghost_Region;
384 -- Save the Ghost-related attributes to restore on exit
385
386 T1 : Entity_Id;
387 T2 : Entity_Id;
388
389 -- Start of processing for Analyze_Assignment
390
391 begin
392 Mark_Coextensions (N, Rhs);
393
394 -- Preserve relevant elaboration-related attributes of the context which
395 -- are no longer available or very expensive to recompute once analysis,
396 -- resolution, and expansion are over.
397
398 Mark_Elaboration_Attributes
399 (N_Id => N,
400 Checks => True,
401 Modes => True);
402
403 -- An assignment statement is Ghost when the left hand side denotes a
404 -- Ghost entity. Set the mode now to ensure that any nodes generated
405 -- during analysis and expansion are properly marked as Ghost.
406
407 Mark_And_Set_Ghost_Assignment (N);
408
409 if Has_Target_Names (N) then
410 pragma Assert (No (Current_Assignment));
411 Current_Assignment := N;
412 Expander_Mode_Save_And_Set (False);
413 Save_Full_Analysis := Full_Analysis;
414 Full_Analysis := False;
415 end if;
416
417 Analyze (Lhs);
418 Analyze (Rhs);
419
420 -- Ensure that we never do an assignment on a variable marked as
421 -- Is_Safe_To_Reevaluate.
422
423 pragma Assert
424 (not Is_Entity_Name (Lhs)
425 or else Ekind (Entity (Lhs)) /= E_Variable
426 or else not Is_Safe_To_Reevaluate (Entity (Lhs)));
427
428 -- Start type analysis for assignment
429
430 T1 := Etype (Lhs);
431
432 -- In the most general case, both Lhs and Rhs can be overloaded, and we
433 -- must compute the intersection of the possible types on each side.
434
435 if Is_Overloaded (Lhs) then
436 declare
437 I : Interp_Index;
438 It : Interp;
439
440 begin
441 T1 := Any_Type;
442 Get_First_Interp (Lhs, I, It);
443
444 while Present (It.Typ) loop
445
446 -- An indexed component with generalized indexing is always
447 -- overloaded with the corresponding dereference. Discard the
448 -- interpretation that yields a reference type, which is not
449 -- assignable.
450
451 if Nkind (Lhs) = N_Indexed_Component
452 and then Present (Generalized_Indexing (Lhs))
453 and then Has_Implicit_Dereference (It.Typ)
454 then
455 null;
456
457 elsif Has_Compatible_Type (Rhs, It.Typ) then
458 if T1 = Any_Type then
459 T1 := It.Typ;
460 else
461 -- An explicit dereference is overloaded if the prefix
462 -- is. Try to remove the ambiguity on the prefix, the
463 -- error will be posted there if the ambiguity is real.
464
465 if Nkind (Lhs) = N_Explicit_Dereference then
466 declare
467 PI : Interp_Index;
468 PI1 : Interp_Index := 0;
469 PIt : Interp;
470 Found : Boolean;
471
472 begin
473 Found := False;
474 Get_First_Interp (Prefix (Lhs), PI, PIt);
475
476 while Present (PIt.Typ) loop
477 if Is_Access_Type (PIt.Typ)
478 and then Has_Compatible_Type
479 (Rhs, Designated_Type (PIt.Typ))
480 then
481 if Found then
482 PIt :=
483 Disambiguate (Prefix (Lhs),
484 PI1, PI, Any_Type);
485
486 if PIt = No_Interp then
487 Error_Msg_N
488 ("ambiguous left-hand side in "
489 & "assignment", Lhs);
490 exit;
491 else
492 Resolve (Prefix (Lhs), PIt.Typ);
493 end if;
494
495 exit;
496 else
497 Found := True;
498 PI1 := PI;
499 end if;
500 end if;
501
502 Get_Next_Interp (PI, PIt);
503 end loop;
504 end;
505
506 else
507 Error_Msg_N
508 ("ambiguous left-hand side in assignment", Lhs);
509 exit;
510 end if;
511 end if;
512 end if;
513
514 Get_Next_Interp (I, It);
515 end loop;
516 end;
517
518 if T1 = Any_Type then
519 Error_Msg_N
520 ("no valid types for left-hand side for assignment", Lhs);
521 Kill_Lhs;
522 goto Leave;
523 end if;
524 end if;
525
526 -- The resulting assignment type is T1, so now we will resolve the left
527 -- hand side of the assignment using this determined type.
528
529 Resolve (Lhs, T1);
530
531 -- Cases where Lhs is not a variable. In an instance or an inlined body
532 -- no need for further check because assignment was legal in template.
533
534 if In_Inlined_Body then
535 null;
536
537 elsif not Is_Variable (Lhs) then
538
539 -- Ada 2005 (AI-327): Check assignment to the attribute Priority of a
540 -- protected object.
541
542 declare
543 Ent : Entity_Id;
544 S : Entity_Id;
545
546 begin
547 if Ada_Version >= Ada_2005 then
548
549 -- Handle chains of renamings
550
551 Ent := Lhs;
552 while Nkind (Ent) in N_Has_Entity
553 and then Present (Entity (Ent))
554 and then Is_Object (Entity (Ent))
555 and then Present (Renamed_Object (Entity (Ent)))
556 loop
557 Ent := Renamed_Object (Entity (Ent));
558 end loop;
559
560 if (Nkind (Ent) = N_Attribute_Reference
561 and then Attribute_Name (Ent) = Name_Priority)
562
563 -- Renamings of the attribute Priority applied to protected
564 -- objects have been previously expanded into calls to the
565 -- Get_Ceiling run-time subprogram.
566
567 or else Is_Expanded_Priority_Attribute (Ent)
568 then
569 -- The enclosing subprogram cannot be a protected function
570
571 S := Current_Scope;
572 while not (Is_Subprogram (S)
573 and then Convention (S) = Convention_Protected)
574 and then S /= Standard_Standard
575 loop
576 S := Scope (S);
577 end loop;
578
579 if Ekind (S) = E_Function
580 and then Convention (S) = Convention_Protected
581 then
582 Error_Msg_N
583 ("protected function cannot modify its protected " &
584 "object",
585 Lhs);
586 end if;
587
588 -- Changes of the ceiling priority of the protected object
589 -- are only effective if the Ceiling_Locking policy is in
590 -- effect (AARM D.5.2 (5/2)).
591
592 if Locking_Policy /= 'C' then
593 Error_Msg_N
594 ("assignment to the attribute PRIORITY has no effect??",
595 Lhs);
596 Error_Msg_N
597 ("\since no Locking_Policy has been specified??", Lhs);
598 end if;
599
600 goto Leave;
601 end if;
602 end if;
603 end;
604
605 Diagnose_Non_Variable_Lhs (Lhs);
606 goto Leave;
607
608 -- Error of assigning to limited type. We do however allow this in
609 -- certain cases where the front end generates the assignments.
610 -- Comes_From_Source test is needed to allow compiler-generated
611 -- streaming/put_image subprograms, which may ignore privacy.
612
613 elsif Is_Limited_Type (T1)
614 and then not Assignment_OK (Lhs)
615 and then not Assignment_OK (Original_Node (Lhs))
616 and then (Comes_From_Source (N) or Is_Immutably_Limited_Type (T1))
617 then
618 -- CPP constructors can only be called in declarations
619
620 if Is_CPP_Constructor_Call (Rhs) then
621 Error_Msg_N ("invalid use of 'C'P'P constructor", Rhs);
622 else
623 Error_Msg_N
624 ("left hand of assignment must not be limited type", Lhs);
625 Explain_Limited_Type (T1, Lhs);
626 end if;
627
628 goto Leave;
629
630 -- A class-wide type may be a limited view. This illegal case is not
631 -- caught by previous checks.
632
633 elsif Ekind (T1) = E_Class_Wide_Type and then From_Limited_With (T1) then
634 Error_Msg_NE ("invalid use of limited view of&", Lhs, T1);
635 goto Leave;
636
637 -- Enforce RM 3.9.3 (8): the target of an assignment operation cannot be
638 -- abstract. This is only checked when the assignment Comes_From_Source,
639 -- because in some cases the expander generates such assignments (such
640 -- in the _assign operation for an abstract type).
641
642 elsif Is_Abstract_Type (T1) and then Comes_From_Source (N) then
643 Error_Msg_N
644 ("target of assignment operation must not be abstract", Lhs);
645 end if;
646
647 -- Variables which are Part_Of constituents of single protected types
648 -- behave in similar fashion to protected components. Such variables
649 -- cannot be modified by protected functions.
650
651 if Is_Protected_Part_Of_Constituent (Lhs) and then Within_Function then
652 Error_Msg_N
653 ("protected function cannot modify its protected object", Lhs);
654 end if;
655
656 -- Resolution may have updated the subtype, in case the left-hand side
657 -- is a private protected component. Use the correct subtype to avoid
658 -- scoping issues in the back-end.
659
660 T1 := Etype (Lhs);
661
662 -- Ada 2005 (AI-50217, AI-326): Check wrong dereference of incomplete
663 -- type. For example:
664
665 -- limited with P;
666 -- package Pkg is
667 -- type Acc is access P.T;
668 -- end Pkg;
669
670 -- with Pkg; use Acc;
671 -- procedure Example is
672 -- A, B : Acc;
673 -- begin
674 -- A.all := B.all; -- ERROR
675 -- end Example;
676
677 if Nkind (Lhs) = N_Explicit_Dereference
678 and then Ekind (T1) = E_Incomplete_Type
679 then
680 Error_Msg_N ("invalid use of incomplete type", Lhs);
681 Kill_Lhs;
682 goto Leave;
683 end if;
684
685 -- Now we can complete the resolution of the right hand side
686
687 Set_Assignment_Type (Lhs, T1);
688
689 -- When analyzing a mutably tagged class-wide equivalent type pretend we
690 -- are actually looking at the mutably tagged type itself for proper
691 -- analysis.
692
693 T1 := Get_Corresponding_Mutably_Tagged_Type_If_Present (T1);
694
695 -- If the target of the assignment is an entity of a mutably tagged type
696 -- and the expression is a conditional expression, its alternatives can
697 -- be of different subtypes of the nominal type of the LHS, so they must
698 -- be resolved with the base type, given that their subtype may differ
699 -- from that of the target mutable object.
700
701 if Is_Entity_Name (Lhs)
702 and then Is_Assignable (Entity (Lhs))
703 and then Is_Composite_Type (T1)
704 and then not Is_Constrained (Etype (Entity (Lhs)))
705 and then Nkind (Rhs) in N_If_Expression | N_Case_Expression
706 then
707 Resolve (Rhs, Base_Type (T1));
708
709 -- When the right hand side is a qualified expression and the left hand
710 -- side is mutably tagged we force the right hand side to be class-wide
711 -- so that they are compatible both for the purposes of checking
712 -- legality rules as well as assignment expansion.
713
714 elsif Is_Mutably_Tagged_Type (T1)
715 and then Nkind (Rhs) = N_Qualified_Expression
716 then
717 Make_Mutably_Tagged_Conversion (Rhs, T1);
718 Resolve (Rhs, T1);
719
720 -- Otherwise, resolve the right hand side normally
721
722 else
723 Resolve (Rhs, T1);
724 end if;
725
726 -- This is the point at which we check for an unset reference
727
728 Check_Unset_Reference (Rhs);
729 Check_Unprotected_Access (Lhs, Rhs);
730
731 -- Remaining steps are skipped if Rhs was syntactically in error
732
733 if Rhs = Error then
734 Kill_Lhs;
735 goto Leave;
736 end if;
737
738 T2 := Etype (Rhs);
739
740 if not Covers (T1, T2) then
741 Wrong_Type (Rhs, Etype (Lhs));
742 Kill_Lhs;
743 goto Leave;
744 end if;
745
746 -- Ada 2005 (AI-326): In case of explicit dereference of incomplete
747 -- types, use the non-limited view if available
748
749 if Nkind (Rhs) = N_Explicit_Dereference
750 and then Is_Tagged_Type (T2)
751 and then Has_Non_Limited_View (T2)
752 then
753 T2 := Non_Limited_View (T2);
754 end if;
755
756 Set_Assignment_Type (Rhs, T2);
757
758 if Total_Errors_Detected /= 0 then
759 if No (T1) then
760 T1 := Any_Type;
761 end if;
762
763 if No (T2) then
764 T2 := Any_Type;
765 end if;
766 end if;
767
768 if T1 = Any_Type or else T2 = Any_Type then
769 Kill_Lhs;
770 goto Leave;
771 end if;
772
773 -- If the rhs is class-wide or dynamically tagged, then require the lhs
774 -- to be class-wide. The case where the rhs is a dynamically tagged call
775 -- to a dispatching operation with a controlling access result is
776 -- excluded from this check, since the target has an access type (and
777 -- no tag propagation occurs in that case).
778
779 if (Is_Class_Wide_Type (T2)
780 or else (Is_Dynamically_Tagged (Rhs)
781 and then not Is_Access_Type (T1)))
782 and then not Is_Class_Wide_Type (T1)
783 then
784 Error_Msg_N ("dynamically tagged expression not allowed!", Rhs);
785
786 elsif Is_Class_Wide_Type (T1)
787 and then not Is_Class_Wide_Type (T2)
788 and then not Is_Tag_Indeterminate (Rhs)
789 and then not Is_Dynamically_Tagged (Rhs)
790 and then not Is_Mutably_Tagged_Type (T1)
791 then
792 Error_Msg_N ("dynamically tagged expression required!", Rhs);
793 end if;
794
795 -- Propagate the tag from a class-wide target to the rhs when the rhs
796 -- is a tag-indeterminate call.
797
798 if Is_Tag_Indeterminate (Rhs) then
799 if Is_Class_Wide_Type (T1) then
800 Propagate_Tag (Lhs, Rhs);
801
802 elsif Nkind (Rhs) = N_Function_Call
803 and then Is_Entity_Name (Name (Rhs))
804 and then Is_Abstract_Subprogram (Entity (Name (Rhs)))
805 then
806 Error_Msg_N
807 ("call to abstract function must be dispatching", Name (Rhs));
808
809 elsif Nkind (Rhs) = N_Qualified_Expression
810 and then Nkind (Expression (Rhs)) = N_Function_Call
811 and then Is_Entity_Name (Name (Expression (Rhs)))
812 and then
813 Is_Abstract_Subprogram (Entity (Name (Expression (Rhs))))
814 then
815 Error_Msg_N
816 ("call to abstract function must be dispatching",
817 Name (Expression (Rhs)));
818 end if;
819 end if;
820
821 -- Ada 2005 (AI-385): When the lhs type is an anonymous access type,
822 -- apply an implicit conversion of the rhs to that type to force
823 -- appropriate static and run-time accessibility checks. This applies
824 -- as well to anonymous access-to-subprogram types that are component
825 -- subtypes or formal parameters.
826
827 if Ada_Version >= Ada_2005 and then Is_Access_Type (T1) then
828 if Is_Local_Anonymous_Access (T1)
829 or else Ekind (T2) = E_Anonymous_Access_Subprogram_Type
830
831 -- Handle assignment to an Ada 2012 stand-alone object
832 -- of an anonymous access type.
833
834 or else (Ekind (T1) = E_Anonymous_Access_Type
835 and then Nkind (Associated_Node_For_Itype (T1)) =
836 N_Object_Declaration)
837
838 then
839 Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
840 Analyze_And_Resolve (Rhs, T1);
841 end if;
842 end if;
843
844 -- Ada 2005 (AI-231): Assignment to not null variable
845
846 if Ada_Version >= Ada_2005
847 and then Can_Never_Be_Null (T1)
848 and then not Assignment_OK (Lhs)
849 then
850 -- Case where we know the right hand side is null
851
852 if Known_Null (Rhs) then
853 Apply_Compile_Time_Constraint_Error
854 (N => Rhs,
855 Msg =>
856 "(Ada 2005) NULL not allowed in null-excluding objects??",
857 Reason => CE_Null_Not_Allowed);
858
859 -- We still mark this as a possible modification, that's necessary
860 -- to reset Is_True_Constant, and desirable for xref purposes.
861
862 Note_Possible_Modification (Lhs, Sure => True);
863 goto Leave;
864
865 -- If we know the right hand side is non-null, then we convert to the
866 -- target type, since we don't need a run time check in that case.
867
868 elsif not Can_Never_Be_Null (T2) then
869 Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
870 Analyze_And_Resolve (Rhs, T1);
871 end if;
872 end if;
873
874 if Is_Scalar_Type (T1) then
875 declare
876
877 function Omit_Range_Check_For_Streaming return Boolean;
878 -- Return True if this assignment statement is the expansion of
879 -- a Some_Scalar_Type'Read procedure call such that all conditions
880 -- of 13.3.2(35)'s "no check is made" rule are met.
881
882 ------------------------------------
883 -- Omit_Range_Check_For_Streaming --
884 ------------------------------------
885
886 function Omit_Range_Check_For_Streaming return Boolean is
887 begin
888 -- Have we got an implicitly generated assignment to a
889 -- component of a composite object? If not, return False.
890
891 if Comes_From_Source (N)
892 or else Serious_Errors_Detected > 0
893 or else Nkind (Lhs)
894 not in N_Selected_Component | N_Indexed_Component
895 then
896 return False;
897 end if;
898
899 declare
900 Pref : constant Node_Id := Prefix (Lhs);
901 begin
902 -- Are we in the implicitly-defined Read subprogram
903 -- for a composite type, reading the value of a scalar
904 -- component from the stream? If not, return False.
905
906 if Nkind (Pref) /= N_Identifier
907 or else not Is_TSS (Scope (Entity (Pref)), TSS_Stream_Read)
908 then
909 return False;
910 end if;
911
912 -- Return False if Default_Value or Default_Component_Value
913 -- aspect applies.
914
915 if Has_Default_Aspect (Etype (Lhs))
916 or else Has_Default_Aspect (Etype (Pref))
917 then
918 return False;
919
920 -- Are we assigning to a record component (as opposed to
921 -- an array component)?
922
923 elsif Nkind (Lhs) = N_Selected_Component then
924
925 -- Are we assigning to a nondiscriminant component
926 -- that lacks a default initial value expression?
927 -- If so, return True.
928
929 declare
930 Comp_Id : constant Entity_Id :=
931 Original_Record_Component
932 (Entity (Selector_Name (Lhs)));
933 begin
934 if Ekind (Comp_Id) = E_Component
935 and then Nkind (Parent (Comp_Id))
936 = N_Component_Declaration
937 and then No (Expression (Parent (Comp_Id)))
938 then
939 return True;
940 end if;
941 return False;
942 end;
943
944 -- We are assigning to a component of an array
945 -- (and we tested for both Default_Value and
946 -- Default_Component_Value above), so return True.
947
948 else
949 pragma Assert (Nkind (Lhs) = N_Indexed_Component);
950 return True;
951 end if;
952 end;
953 end Omit_Range_Check_For_Streaming;
954
955 begin
956 if not Omit_Range_Check_For_Streaming then
957 Apply_Scalar_Range_Check (Rhs, Etype (Lhs));
958 end if;
959 end;
960
961 -- For array types, verify that lengths match. If the right hand side
962 -- is a function call that has been inlined, the assignment has been
963 -- rewritten as a block, and the constraint check will be applied to the
964 -- assignment within the block.
965
966 elsif Is_Array_Type (T1)
967 and then (Nkind (Rhs) /= N_Type_Conversion
968 or else Is_Constrained (Etype (Rhs)))
969 and then (Nkind (Rhs) /= N_Function_Call
970 or else Nkind (N) /= N_Block_Statement)
971 then
972 -- Assignment verifies that the length of the Lhs and Rhs are equal,
973 -- but of course the indexes do not have to match. If the right-hand
974 -- side is a type conversion to an unconstrained type, a length check
975 -- is performed on the expression itself during expansion. In rare
976 -- cases, the redundant length check is computed on an index type
977 -- with a different representation, triggering incorrect code in the
978 -- back end.
979
980 Apply_Length_Check_On_Assignment (Rhs, Etype (Lhs), Lhs);
981
982 else
983 -- Discriminant checks are applied in the course of expansion
984
985 null;
986 end if;
987
988 -- Note: modifications of the Lhs may only be recorded after
989 -- checks have been applied.
990
991 Note_Possible_Modification (Lhs, Sure => True);
992
993 -- ??? a real accessibility check is needed when ???
994
995 -- Post warning for redundant assignment or variable to itself
996
997 if Warn_On_Redundant_Constructs
998
999 -- We only warn for source constructs
1000
1001 and then Comes_From_Source (N)
1002
1003 -- Where the object is the same on both sides
1004
1005 and then Same_Object (Lhs, Rhs)
1006
1007 -- But exclude the case where the right side was an operation that
1008 -- got rewritten (e.g. JUNK + K, where K was known to be zero). We
1009 -- don't want to warn in such a case, since it is reasonable to write
1010 -- such expressions especially when K is defined symbolically in some
1011 -- other package.
1012
1013 and then Nkind (Original_Node (Rhs)) not in N_Op
1014 then
1015 if Nkind (Lhs) in N_Has_Entity then
1016 Error_Msg_NE -- CODEFIX
1017 ("?r?useless assignment of & to itself!", N, Entity (Lhs));
1018 else
1019 Error_Msg_N -- CODEFIX
1020 ("?r?useless assignment of object to itself!", N);
1021 end if;
1022 end if;
1023
1024 -- Check for non-allowed composite assignment
1025
1026 if not Support_Composite_Assign_On_Target
1027 and then (Is_Array_Type (T1) or else Is_Record_Type (T1))
1028 and then (not Has_Size_Clause (T1)
1029 or else Esize (T1) > Ttypes.System_Max_Integer_Size)
1030 then
1031 Error_Msg_CRT ("composite assignment", N);
1032 end if;
1033
1034 -- Check elaboration warning for left side if not in elab code
1035
1036 if Legacy_Elaboration_Checks
1037 and not In_Subprogram_Or_Concurrent_Unit
1038 then
1039 Check_Elab_Assign (Lhs);
1040 end if;
1041
1042 -- Save the scenario for later examination by the ABE Processing phase
1043
1044 Record_Elaboration_Scenario (N);
1045
1046 -- Set Referenced_As_LHS if appropriate. We are not interested in
1047 -- compiler-generated assignment statements, nor in references outside
1048 -- the extended main source unit. We check whether the Original_Node is
1049 -- in the extended main source unit because in the case of a renaming of
1050 -- a component of a packed array, the Lhs itself has a Sloc from the
1051 -- place of the renaming.
1052
1053 if Comes_From_Source (N)
1054 and then (In_Extended_Main_Source_Unit (Lhs)
1055 or else In_Extended_Main_Source_Unit (Original_Node (Lhs)))
1056 then
1057 Set_Referenced_Modified (Lhs, Out_Param => False);
1058 end if;
1059
1060 -- RM 7.3.2 (12/3): An assignment to a view conversion (from a type to
1061 -- one of its ancestors) requires an invariant check. Apply check only
1062 -- if expression comes from source, otherwise it will be applied when
1063 -- value is assigned to source entity. This is not done in GNATprove
1064 -- mode, as GNATprove handles invariant checks itself.
1065
1066 if Nkind (Lhs) = N_Type_Conversion
1067 and then Has_Invariants (Etype (Expression (Lhs)))
1068 and then Comes_From_Source (Expression (Lhs))
1069 and then not GNATprove_Mode
1070 then
1071 Insert_After (N, Make_Invariant_Call (Expression (Lhs)));
1072 end if;
1073
1074 -- Final step. If left side is an entity, then we may be able to reset
1075 -- the current tracked values to new safe values. We only have something
1076 -- to do if the left side is an entity name, and expansion has not
1077 -- modified the node into something other than an assignment, and of
1078 -- course we only capture values if it is safe to do so.
1079
1080 if Is_Entity_Name (Lhs)
1081 and then Nkind (N) = N_Assignment_Statement
1082 then
1083 declare
1084 Ent : constant Entity_Id := Entity (Lhs);
1085
1086 begin
1087 if Safe_To_Capture_Value (N, Ent) then
1088
1089 -- If simple variable on left side, warn if this assignment
1090 -- blots out another one (rendering it useless). We only do
1091 -- this for source assignments, otherwise we can generate bogus
1092 -- warnings when an assignment is rewritten as another
1093 -- assignment, and gets tied up with itself.
1094
1095 -- We also omit the warning if the RHS includes target names,
1096 -- that is to say the Ada 2022 "@" that denotes an instance of
1097 -- the LHS, which indicates that the current value is being
1098 -- used. Note that this implicit reference to the entity on
1099 -- the RHS is not treated as a source reference.
1100
1101 -- There may have been a previous reference to a component of
1102 -- the variable, which in general removes the Last_Assignment
1103 -- field of the variable to indicate a relevant use of the
1104 -- previous assignment.
1105
1106 if Warn_On_Modified_Unread
1107 and then Is_Assignable (Ent)
1108 and then Comes_From_Source (N)
1109 and then In_Extended_Main_Source_Unit (Ent)
1110 and then not Has_Target_Names (N)
1111 then
1112 Warn_On_Useless_Assignment (Ent, N);
1113 end if;
1114
1115 -- If we are assigning an access type and the left side is an
1116 -- entity, then make sure that the Is_Known_[Non_]Null flags
1117 -- properly reflect the state of the entity after assignment.
1118
1119 if Is_Access_Type (T1) then
1120 if Known_Non_Null (Rhs) then
1121 Set_Is_Known_Non_Null (Ent, True);
1122
1123 elsif Known_Null (Rhs)
1124 and then not Can_Never_Be_Null (Ent)
1125 then
1126 Set_Is_Known_Null (Ent, True);
1127
1128 else
1129 Set_Is_Known_Null (Ent, False);
1130
1131 if not Can_Never_Be_Null (Ent) then
1132 Set_Is_Known_Non_Null (Ent, False);
1133 end if;
1134 end if;
1135
1136 -- For discrete types, we may be able to set the current value
1137 -- if the value is known at compile time.
1138
1139 elsif Is_Discrete_Type (T1)
1140 and then Compile_Time_Known_Value (Rhs)
1141 then
1142 Set_Current_Value (Ent, Rhs);
1143 else
1144 Set_Current_Value (Ent, Empty);
1145 end if;
1146
1147 -- If not safe to capture values, kill them
1148
1149 else
1150 Kill_Lhs;
1151 end if;
1152 end;
1153 end if;
1154
1155 -- If assigning to an object in whole or in part, note location of
1156 -- assignment in case no one references value. We only do this for
1157 -- source assignments, otherwise we can generate bogus warnings when an
1158 -- assignment is rewritten as another assignment, and gets tied up with
1159 -- itself.
1160
1161 declare
1162 Ent : constant Entity_Id := Get_Enclosing_Object (Lhs);
1163 begin
1164 if Present (Ent)
1165 and then Safe_To_Capture_Value (N, Ent)
1166 and then Nkind (N) = N_Assignment_Statement
1167 and then Warn_On_Modified_Unread
1168 and then Is_Assignable (Ent)
1169 and then Comes_From_Source (N)
1170 and then In_Extended_Main_Source_Unit (Ent)
1171 then
1172 Set_Last_Assignment (Ent, Lhs);
1173 end if;
1174 end;
1175
1176 Analyze_Dimension (N);
1177
1178 <<Leave>>
1179 Restore_Ghost_Region (Saved_GM, Saved_IGR);
1180
1181 -- If the right-hand side contains target names, expansion has been
1182 -- disabled to prevent expansion that might move target names out of
1183 -- the context of the assignment statement. Restore the expander mode
1184 -- now so that assignment statement can be properly expanded.
1185
1186 if Nkind (N) = N_Assignment_Statement then
1187 if Has_Target_Names (N) then
1188 Expander_Mode_Restore;
1189 Full_Analysis := Save_Full_Analysis;
1190 Current_Assignment := Empty;
1191 end if;
1192 end if;
1193 end Analyze_Assignment;
1194
1195 -----------------------------
1196 -- Analyze_Block_Statement --
1197 -----------------------------
1198
1199 procedure Analyze_Block_Statement (N : Node_Id) is
1200 procedure Install_Return_Entities (Scop : Entity_Id);
1201 -- Install all entities of return statement scope Scop in the visibility
1202 -- chain except for the return object since its entity is reused in a
1203 -- renaming.
1204
1205 -----------------------------
1206 -- Install_Return_Entities --
1207 -----------------------------
1208
1209 procedure Install_Return_Entities (Scop : Entity_Id) is
1210 Id : Entity_Id;
1211
1212 begin
1213 Id := First_Entity (Scop);
1214 while Present (Id) loop
1215
1216 -- Do not install the return object
1217
1218 if Ekind (Id) not in E_Constant | E_Variable
1219 or else not Is_Return_Object (Id)
1220 then
1221 Install_Entity (Id);
1222 end if;
1223
1224 Next_Entity (Id);
1225 end loop;
1226 end Install_Return_Entities;
1227
1228 -- Local constants and variables
1229
1230 Decls : constant List_Id := Declarations (N);
1231 Id : constant Node_Id := Identifier (N);
1232 HSS : constant Node_Id := Handled_Statement_Sequence (N);
1233
1234 Is_BIP_Return_Statement : Boolean;
1235
1236 -- Start of processing for Analyze_Block_Statement
1237
1238 begin
1239 -- If no handled statement sequence is present, things are really messed
1240 -- up, and we just return immediately (defence against previous errors).
1241
1242 if No (HSS) then
1243 Check_Error_Detected;
1244 return;
1245 end if;
1246
1247 -- Detect whether the block is actually a rewritten return statement of
1248 -- a build-in-place function.
1249
1250 Is_BIP_Return_Statement :=
1251 Present (Id)
1252 and then Present (Entity (Id))
1253 and then Ekind (Entity (Id)) = E_Return_Statement
1254 and then Is_Build_In_Place_Function
1255 (Return_Applies_To (Entity (Id)));
1256
1257 -- Normal processing with HSS present
1258
1259 declare
1260 EH : constant List_Id := Exception_Handlers (HSS);
1261 Ent : Entity_Id := Empty;
1262 S : Entity_Id;
1263
1264 Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
1265 -- Recursively save value of this global, will be restored on exit
1266
1267 begin
1268 -- Initialize unblocked exit count for statements of begin block
1269 -- plus one for each exception handler that is present, plus one for
1270 -- the finally part if it present.
1271
1272 Unblocked_Exit_Count :=
1273 1 + List_Length (EH)
1274 + (if Present (Finally_Statements (HSS)) then 1 else 0);
1275
1276 -- If a label is present analyze it and mark it as referenced
1277
1278 if Present (Id) then
1279 Analyze (Id);
1280 Ent := Entity (Id);
1281
1282 -- An error defense. If we have an identifier, but no entity, then
1283 -- something is wrong. If previous errors, then just remove the
1284 -- identifier and continue, otherwise raise an exception.
1285
1286 if No (Ent) then
1287 Check_Error_Detected;
1288 Set_Identifier (N, Empty);
1289
1290 else
1291 if Ekind (Ent) = E_Label then
1292 Reinit_Field_To_Zero (Ent, F_Enclosing_Scope);
1293 end if;
1294
1295 Mutate_Ekind (Ent, E_Block);
1296 Generate_Reference (Ent, N, ' ');
1297 Generate_Definition (Ent);
1298
1299 if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
1300 Set_Label_Construct (Parent (Ent), N);
1301 end if;
1302 end if;
1303 end if;
1304
1305 -- If no entity set, create a label entity
1306
1307 if No (Ent) then
1308 Ent := New_Internal_Entity (E_Block, Current_Scope, Sloc (N), 'B');
1309 Set_Identifier (N, New_Occurrence_Of (Ent, Sloc (N)));
1310 Set_Parent (Ent, N);
1311 end if;
1312
1313 Set_Etype (Ent, Standard_Void_Type);
1314 Set_Block_Node (Ent, Identifier (N));
1315 Push_Scope (Ent);
1316
1317 -- The block served as an extended return statement. Ensure that any
1318 -- entities created during the analysis and expansion of the return
1319 -- object declaration are once again visible.
1320
1321 if Is_BIP_Return_Statement then
1322 Install_Return_Entities (Ent);
1323 end if;
1324
1325 if Present (Decls) then
1326 Analyze_Declarations (Decls);
1327 Check_Completion;
1328 Inspect_Deferred_Constant_Completion (Decls);
1329 end if;
1330
1331 Analyze (HSS);
1332 Process_End_Label (HSS, 'e', Ent);
1333
1334 -- If exception handlers are present, then we indicate that enclosing
1335 -- scopes contain a block with handlers. We only need to mark non-
1336 -- generic scopes.
1337
1338 if Present (EH) then
1339 S := Scope (Ent);
1340 loop
1341 Set_Has_Nested_Block_With_Handler (S);
1342 exit when Is_Overloadable (S)
1343 or else Ekind (S) = E_Package
1344 or else Is_Generic_Unit (S);
1345 S := Scope (S);
1346 end loop;
1347 end if;
1348
1349 Check_References (Ent);
1350 Update_Use_Clause_Chain;
1351 End_Scope;
1352
1353 if Unblocked_Exit_Count = 0 then
1354 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1355 Check_Unreachable_Code (N);
1356 else
1357 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1358 end if;
1359 end;
1360 end Analyze_Block_Statement;
1361
1362 --------------------------------
1363 -- Analyze_Compound_Statement --
1364 --------------------------------
1365
1366 procedure Analyze_Compound_Statement (N : Node_Id) is
1367 begin
1368 Analyze_List (Actions (N));
1369 end Analyze_Compound_Statement;
1370
1371 ----------------------------
1372 -- Analyze_Case_Statement --
1373 ----------------------------
1374
1375 procedure Analyze_Case_Statement (N : Node_Id) is
1376 Exp : constant Node_Id := Expression (N);
1377
1378 Statements_Analyzed : Boolean := False;
1379 -- Set True if at least some statement sequences get analyzed. If False
1380 -- on exit, means we had a serious error that prevented full analysis of
1381 -- the case statement, and as a result it is not a good idea to output
1382 -- warning messages about unreachable code.
1383
1384 Is_General_Case_Statement : Boolean := False;
1385 -- Set True (later) if type of case expression is not discrete
1386
1387 procedure Non_Static_Choice_Error (Choice : Node_Id);
1388 -- Error routine invoked by the generic instantiation below when the
1389 -- case statement has a non static choice.
1390
1391 procedure Process_Statements (Alternative : Node_Id);
1392 -- Analyzes the statements associated with a case alternative. Needed
1393 -- by instantiation below.
1394
1395 package Analyze_Case_Choices is new
1396 Generic_Analyze_Choices
1397 (Process_Associated_Node => Process_Statements);
1398 use Analyze_Case_Choices;
1399 -- Instantiation of the generic choice analysis package
1400
1401 package Check_Case_Choices is new
1402 Generic_Check_Choices
1403 (Process_Empty_Choice => No_OP,
1404 Process_Non_Static_Choice => Non_Static_Choice_Error,
1405 Process_Associated_Node => No_OP);
1406 use Check_Case_Choices;
1407 -- Instantiation of the generic choice processing package
1408
1409 -----------------------------
1410 -- Non_Static_Choice_Error --
1411 -----------------------------
1412
1413 procedure Non_Static_Choice_Error (Choice : Node_Id) is
1414 begin
1415 Flag_Non_Static_Expr
1416 ("choice given in case statement is not static!", Choice);
1417 end Non_Static_Choice_Error;
1418
1419 ------------------------
1420 -- Process_Statements --
1421 ------------------------
1422
1423 procedure Process_Statements (Alternative : Node_Id) is
1424 Choices : constant List_Id := Discrete_Choices (Alternative);
1425 Ent : Entity_Id;
1426
1427 begin
1428 if Is_General_Case_Statement then
1429 return;
1430 -- Processing deferred in this case; decls associated with
1431 -- pattern match bindings don't exist yet.
1432 end if;
1433
1434 Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
1435 Statements_Analyzed := True;
1436
1437 -- An interesting optimization. If the case statement expression
1438 -- is a simple entity, then we can set the current value within an
1439 -- alternative if the alternative has one possible value.
1440
1441 -- case N is
1442 -- when 1 => alpha
1443 -- when 2 | 3 => beta
1444 -- when others => gamma
1445
1446 -- Here we know that N is initially 1 within alpha, but for beta and
1447 -- gamma, we do not know anything more about the initial value.
1448
1449 if Is_Entity_Name (Exp) then
1450 Ent := Entity (Exp);
1451
1452 if Is_Object (Ent) then
1453 if List_Length (Choices) = 1
1454 and then Nkind (First (Choices)) in N_Subexpr
1455 and then Compile_Time_Known_Value (First (Choices))
1456 then
1457 Set_Current_Value (Entity (Exp), First (Choices));
1458 end if;
1459
1460 Analyze_Statements (Statements (Alternative));
1461
1462 -- After analyzing the case, set the current value to empty
1463 -- since we won't know what it is for the next alternative
1464 -- (unless reset by this same circuit), or after the case.
1465
1466 Set_Current_Value (Entity (Exp), Empty);
1467 return;
1468 end if;
1469 end if;
1470
1471 -- Case where expression is not an entity name of an object
1472
1473 Analyze_Statements (Statements (Alternative));
1474 end Process_Statements;
1475
1476 -- Local variables
1477
1478 Exp_Type : Entity_Id;
1479 Exp_Btype : Entity_Id;
1480
1481 Others_Present : Boolean;
1482 -- Indicates if Others was present
1483
1484 Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
1485 -- Recursively save value of this global, will be restored on exit
1486
1487 -- Start of processing for Analyze_Case_Statement
1488
1489 begin
1490 Analyze (Exp);
1491
1492 -- The expression must be of any discrete type. In rare cases, the
1493 -- expander constructs a case statement whose expression has a private
1494 -- type whose full view is discrete. This can happen when generating
1495 -- a stream operation for a variant type after the type is frozen,
1496 -- when the partial of view of the type of the discriminant is private.
1497 -- In that case, use the full view to analyze case alternatives.
1498
1499 if not Is_Overloaded (Exp)
1500 and then not Comes_From_Source (N)
1501 and then Is_Private_Type (Etype (Exp))
1502 and then Present (Full_View (Etype (Exp)))
1503 and then Is_Discrete_Type (Full_View (Etype (Exp)))
1504 then
1505 Resolve (Exp);
1506 Exp_Type := Full_View (Etype (Exp));
1507
1508 -- For Ada, overloading might be ok because subsequently filtering
1509 -- out non-discretes may resolve the ambiguity.
1510 -- But GNAT extensions allow casing on non-discretes.
1511
1512 elsif All_Extensions_Allowed and then Is_Overloaded (Exp) then
1513
1514 -- It would be nice if we could generate all the right error
1515 -- messages by calling "Resolve (Exp, Any_Type);" in the
1516 -- same way that they are generated a few lines below by the
1517 -- call "Analyze_And_Resolve (Exp, Any_Discrete);".
1518 -- Unfortunately, Any_Type and Any_Discrete are not treated
1519 -- consistently (specifically, by Sem_Type.Covers), so that
1520 -- doesn't work.
1521
1522 Error_Msg_N
1523 ("selecting expression of general case statement is ambiguous",
1524 Exp);
1525 return;
1526
1527 -- Check for a GNAT-extension "general" case statement (i.e., one where
1528 -- the type of the selecting expression is not discrete).
1529
1530 elsif All_Extensions_Allowed
1531 and then not Is_Discrete_Type (Etype (Exp))
1532 then
1533 Resolve (Exp, Etype (Exp));
1534 Exp_Type := Etype (Exp);
1535 Is_General_Case_Statement := True;
1536 if not (Is_Record_Type (Exp_Type) or Is_Array_Type (Exp_Type)) then
1537 Error_Msg_N
1538 ("selecting expression of general case statement " &
1539 "must be a record or an array",
1540 Exp);
1541
1542 -- Avoid cascading errors
1543 return;
1544 end if;
1545 else
1546 Analyze_And_Resolve (Exp, Any_Discrete);
1547 Exp_Type := Etype (Exp);
1548 end if;
1549
1550 Check_Unset_Reference (Exp);
1551 Exp_Btype := Base_Type (Exp_Type);
1552
1553 -- The expression must be of a discrete type which must be determinable
1554 -- independently of the context in which the expression occurs, but
1555 -- using the fact that the expression must be of a discrete type.
1556 -- Moreover, the type this expression must not be a character literal
1557 -- (which is always ambiguous) or, for Ada-83, a generic formal type.
1558
1559 -- If error already reported by Resolve, nothing more to do
1560
1561 if Exp_Btype = Any_Discrete or else Exp_Btype = Any_Type then
1562 return;
1563
1564 elsif Exp_Btype = Any_Character then
1565 Error_Msg_N
1566 ("character literal as case expression is ambiguous", Exp);
1567 return;
1568
1569 elsif Ada_Version = Ada_83
1570 and then (Is_Generic_Type (Exp_Btype)
1571 or else Is_Generic_Type (Root_Type (Exp_Btype)))
1572 then
1573 Error_Msg_N
1574 ("(Ada 83) case expression cannot be of a generic type", Exp);
1575 return;
1576
1577 elsif not All_Extensions_Allowed
1578 and then not Is_Discrete_Type (Exp_Type)
1579 then
1580 Error_Msg_N
1581 ("expression in case statement must be of a discrete_Type", Exp);
1582 return;
1583 end if;
1584
1585 -- If the case expression is a formal object of mode in out, then treat
1586 -- it as having a nonstatic subtype by forcing use of the base type
1587 -- (which has to get passed to Check_Case_Choices below). Also use base
1588 -- type when the case expression is parenthesized.
1589
1590 if Paren_Count (Exp) > 0
1591 or else (Is_Entity_Name (Exp)
1592 and then Ekind (Entity (Exp)) = E_Generic_In_Out_Parameter)
1593 then
1594 Exp_Type := Exp_Btype;
1595 end if;
1596
1597 -- Call instantiated procedures to analyze and check discrete choices
1598
1599 Unblocked_Exit_Count := 0;
1600
1601 Analyze_Choices (Alternatives (N), Exp_Type);
1602 Check_Choices (N, Alternatives (N), Exp_Type, Others_Present);
1603
1604 if Is_General_Case_Statement then
1605 -- Work normally done in Process_Statements was deferred; do that
1606 -- deferred work now that Check_Choices has had a chance to create
1607 -- any needed pattern-match-binding declarations.
1608 declare
1609 Alt : Node_Id := First (Alternatives (N));
1610 begin
1611 while Present (Alt) loop
1612 Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
1613 Analyze_Statements (Statements (Alt));
1614 Next (Alt);
1615 end loop;
1616 end;
1617 end if;
1618
1619 if Exp_Type = Universal_Integer and then not Others_Present then
1620 Error_Msg_N ("case on universal integer requires OTHERS choice", Exp);
1621 end if;
1622
1623 -- If all our exits were blocked by unconditional transfers of control,
1624 -- then the entire CASE statement acts as an unconditional transfer of
1625 -- control, so treat it like one, and check unreachable code. Skip this
1626 -- test if we had serious errors preventing any statement analysis.
1627
1628 if Unblocked_Exit_Count = 0 and then Statements_Analyzed then
1629 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1630 Check_Unreachable_Code (N);
1631 else
1632 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1633 end if;
1634
1635 -- If the expander is active it will detect the case of a statically
1636 -- determined single alternative and remove warnings for the case, but
1637 -- if we are not doing expansion, that circuit won't be active. Here we
1638 -- duplicate the effect of removing warnings in the same way, so that
1639 -- we will get the same set of warnings in -gnatc mode.
1640
1641 if not Expander_Active
1642 and then Compile_Time_Known_Value (Expression (N))
1643 and then Serious_Errors_Detected = 0
1644 then
1645 declare
1646 Chosen : constant Node_Id := Find_Static_Alternative (N);
1647 Alt : Node_Id;
1648
1649 begin
1650 Alt := First (Alternatives (N));
1651 while Present (Alt) loop
1652 if Alt /= Chosen then
1653 Remove_Warning_Messages (Statements (Alt));
1654 end if;
1655
1656 Next (Alt);
1657 end loop;
1658 end;
1659 end if;
1660 end Analyze_Case_Statement;
1661
1662 ----------------------------
1663 -- Analyze_Exit_Statement --
1664 ----------------------------
1665
1666 -- If the exit includes a name, it must be the name of a currently open
1667 -- loop. Otherwise there must be an innermost open loop on the stack, to
1668 -- which the statement implicitly refers.
1669
1670 -- Additionally, in SPARK mode:
1671
1672 -- The exit can only name the closest enclosing loop;
1673
1674 -- An exit with a when clause must be directly contained in a loop;
1675
1676 -- An exit without a when clause must be directly contained in an
1677 -- if-statement with no elsif or else, which is itself directly contained
1678 -- in a loop. The exit must be the last statement in the if-statement.
1679
1680 procedure Analyze_Exit_Statement (N : Node_Id) is
1681 Target : constant Node_Id := Name (N);
1682 Cond : constant Node_Id := Condition (N);
1683 Scope_Id : Entity_Id := Empty; -- initialize to prevent warning
1684 U_Name : Entity_Id;
1685 Kind : Entity_Kind;
1686
1687 begin
1688 if No (Cond) then
1689 Check_Unreachable_Code (N);
1690 end if;
1691
1692 if Present (Target) then
1693 Analyze (Target);
1694 U_Name := Entity (Target);
1695
1696 if not In_Open_Scopes (U_Name) or else Ekind (U_Name) /= E_Loop then
1697 Error_Msg_N ("invalid loop name in exit statement", N);
1698 return;
1699
1700 else
1701 Set_Has_Exit (U_Name);
1702 end if;
1703
1704 else
1705 U_Name := Empty;
1706 end if;
1707
1708 for J in reverse 0 .. Scope_Stack.Last loop
1709 Scope_Id := Scope_Stack.Table (J).Entity;
1710 Kind := Ekind (Scope_Id);
1711
1712 if Kind = E_Loop and then (No (Target) or else Scope_Id = U_Name) then
1713 Set_Has_Exit (Scope_Id);
1714 exit;
1715
1716 elsif Kind = E_Block
1717 or else Kind = E_Loop
1718 or else Kind = E_Return_Statement
1719 then
1720 null;
1721
1722 else
1723 Error_Msg_N
1724 ("cannot exit from program unit or accept statement", N);
1725 return;
1726 end if;
1727 end loop;
1728
1729 Finally_Legality_Check : declare
1730 -- The following value can actually be a block statement due to
1731 -- expansion, but we call it Target_Loop_Statement because it was
1732 -- originally a loop statement.
1733 Target_Loop_Statement : constant Node_Id :=
1734 (if Present (U_Name) then Label_Construct ((Parent (U_Name)))
1735 else Empty);
1736
1737 X : Node_Id := N;
1738 begin
1739 while Present (X) loop
1740 if Nkind (X) = N_Loop_Statement
1741 and then (No (Target_Loop_Statement)
1742 or else X = Target_Loop_Statement)
1743 then
1744 exit;
1745 elsif Nkind (Parent (X)) = N_Handled_Sequence_Of_Statements
1746 and then Is_List_Member (X)
1747 and then List_Containing (X) = Finally_Statements (Parent (X))
1748 then
1749 Error_Msg_N ("cannot exit out of finally part", N);
1750 exit;
1751 end if;
1752 X := Parent (X);
1753 end loop;
1754 end Finally_Legality_Check;
1755
1756 -- Verify that if present the condition is a Boolean expression
1757
1758 if Present (Cond) then
1759 Analyze_And_Resolve (Cond, Any_Boolean);
1760 Check_Unset_Reference (Cond);
1761 end if;
1762
1763 -- Chain exit statement to associated loop entity
1764
1765 Set_Next_Exit_Statement (N, First_Exit_Statement (Scope_Id));
1766 Set_First_Exit_Statement (Scope_Id, N);
1767
1768 -- Since the exit may take us out of a loop, any previous assignment
1769 -- statement is not useless, so clear last assignment indications. It
1770 -- is OK to keep other current values, since if the exit statement
1771 -- does not exit, then the current values are still valid.
1772
1773 Kill_Current_Values (Last_Assignment_Only => True);
1774 end Analyze_Exit_Statement;
1775
1776 ----------------------------
1777 -- Analyze_Goto_Statement --
1778 ----------------------------
1779
1780 procedure Analyze_Goto_Statement (N : Node_Id) is
1781 Label : constant Node_Id := Name (N);
1782 Scope_Id : Entity_Id;
1783 Label_Scope : Entity_Id;
1784 Label_Ent : Entity_Id;
1785
1786 begin
1787 -- Actual semantic checks
1788
1789 Check_Unreachable_Code (N);
1790 Kill_Current_Values (Last_Assignment_Only => True);
1791
1792 Analyze (Label);
1793 Label_Ent := Entity (Label);
1794
1795 -- Ignore previous error
1796
1797 if Label_Ent = Any_Id then
1798 Check_Error_Detected;
1799 return;
1800
1801 -- We just have a label as the target of a goto
1802
1803 elsif Ekind (Label_Ent) /= E_Label then
1804 Error_Msg_N ("target of goto statement must be a label", Label);
1805 return;
1806
1807 -- Check that the target of the goto is reachable according to Ada
1808 -- scoping rules. Note: the special gotos we generate for optimizing
1809 -- local handling of exceptions would violate these rules, but we mark
1810 -- such gotos as analyzed when built, so this code is never entered.
1811
1812 elsif not Reachable (Label_Ent) then
1813 Error_Msg_N ("target of goto statement is not reachable", Label);
1814 return;
1815 end if;
1816
1817 Finally_Legality_Check : declare
1818 LCA : constant Union_Id :=
1819 Lowest_Common_Ancestor (N, Label_Construct (Parent (Label_Ent)));
1820
1821 N1 : Union_Id := Union_Id (N);
1822 N2 : Union_Id;
1823 begin
1824 while N1 /= LCA loop
1825 N2 := Parent_Or_List_Containing (N1);
1826
1827 if N2 in Node_Range
1828 and then Nkind (Node_Id (N2)) = N_Handled_Sequence_Of_Statements
1829 and then Union_Id (Finally_Statements (Node_Id (N2))) = N1
1830 then
1831 Error_Msg_N ("cannot goto out of finally part", N);
1832 exit;
1833 end if;
1834
1835 N1 := N2;
1836 end loop;
1837 end Finally_Legality_Check;
1838
1839 -- Here if goto passes initial validity checks
1840
1841 Label_Scope := Enclosing_Scope (Label_Ent);
1842
1843 for J in reverse 0 .. Scope_Stack.Last loop
1844 Scope_Id := Scope_Stack.Table (J).Entity;
1845
1846 if Label_Scope = Scope_Id
1847 or else Ekind (Scope_Id) not in
1848 E_Block | E_Loop | E_Return_Statement
1849 then
1850 if Scope_Id /= Label_Scope then
1851 Error_Msg_N
1852 ("cannot exit from program unit or accept statement", N);
1853 end if;
1854
1855 return;
1856 end if;
1857 end loop;
1858
1859 raise Program_Error;
1860 end Analyze_Goto_Statement;
1861
1862 ---------------------------------
1863 -- Analyze_Goto_When_Statement --
1864 ---------------------------------
1865
1866 procedure Analyze_Goto_When_Statement (N : Node_Id) is
1867 begin
1868 -- Verify the condition is a Boolean expression
1869
1870 Analyze_And_Resolve (Condition (N), Any_Boolean);
1871 Check_Unset_Reference (Condition (N));
1872 end Analyze_Goto_When_Statement;
1873
1874 --------------------------
1875 -- Analyze_If_Statement --
1876 --------------------------
1877
1878 -- A special complication arises in the analysis of if statements
1879
1880 -- The expander has circuitry to completely delete code that it can tell
1881 -- will not be executed (as a result of compile time known conditions). In
1882 -- the analyzer, we ensure that code that will be deleted in this manner
1883 -- is analyzed but not expanded. This is obviously more efficient, but
1884 -- more significantly, difficulties arise if code is expanded and then
1885 -- eliminated (e.g. exception table entries disappear). Similarly, itypes
1886 -- generated in deleted code must be frozen from start, because the nodes
1887 -- on which they depend will not be available at the freeze point.
1888
1889 procedure Analyze_If_Statement (N : Node_Id) is
1890 Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
1891 -- Recursively save value of this global, will be restored on exit
1892
1893 Save_In_Deleted_Code : Boolean := In_Deleted_Code;
1894
1895 Del : Boolean := False;
1896 -- This flag gets set True if a True condition has been found, which
1897 -- means that remaining ELSE/ELSIF parts are deleted.
1898
1899 procedure Analyze_Cond_Then (Cnode : Node_Id);
1900 -- This is applied to either the N_If_Statement node itself or to an
1901 -- N_Elsif_Part node. It deals with analyzing the condition and the THEN
1902 -- statements associated with it.
1903
1904 -----------------------
1905 -- Analyze_Cond_Then --
1906 -----------------------
1907
1908 procedure Analyze_Cond_Then (Cnode : Node_Id) is
1909 Cond : constant Node_Id := Condition (Cnode);
1910 Tstm : constant List_Id := Then_Statements (Cnode);
1911
1912 begin
1913 Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
1914 Analyze_And_Resolve (Cond, Any_Boolean);
1915 Check_Unset_Reference (Cond);
1916 Set_Current_Value_Condition (Cnode);
1917
1918 -- If already deleting, then just analyze then statements
1919
1920 if Del then
1921 Analyze_Statements (Tstm);
1922
1923 -- Compile time known value, not deleting yet
1924
1925 elsif Compile_Time_Known_Value (Cond) then
1926 Save_In_Deleted_Code := In_Deleted_Code;
1927
1928 -- If condition is True, then analyze the THEN statements and set
1929 -- no expansion for ELSE and ELSIF parts.
1930
1931 if Is_True (Expr_Value (Cond)) then
1932 Analyze_Statements (Tstm);
1933 Del := True;
1934 Expander_Mode_Save_And_Set (False);
1935 In_Deleted_Code := True;
1936
1937 -- If condition is False, analyze THEN with expansion off
1938
1939 else pragma Assert (Is_False (Expr_Value (Cond)));
1940 Expander_Mode_Save_And_Set (False);
1941 In_Deleted_Code := True;
1942 Analyze_Statements (Tstm);
1943 Expander_Mode_Restore;
1944 In_Deleted_Code := Save_In_Deleted_Code;
1945 end if;
1946
1947 -- Not known at compile time, not deleting, normal analysis
1948
1949 else
1950 Analyze_Statements (Tstm);
1951 end if;
1952 end Analyze_Cond_Then;
1953
1954 -- Local variables
1955
1956 E : Node_Id;
1957 -- For iterating over elsif parts
1958
1959 -- Start of processing for Analyze_If_Statement
1960
1961 begin
1962 -- Initialize exit count for else statements. If there is no else part,
1963 -- this count will stay non-zero reflecting the fact that the uncovered
1964 -- else case is an unblocked exit.
1965
1966 Unblocked_Exit_Count := 1;
1967 Analyze_Cond_Then (N);
1968
1969 -- Now to analyze the elsif parts if any are present
1970
1971 E := First (Elsif_Parts (N));
1972 while Present (E) loop
1973 Analyze_Cond_Then (E);
1974 Next (E);
1975 end loop;
1976
1977 if Present (Else_Statements (N)) then
1978 Analyze_Statements (Else_Statements (N));
1979 end if;
1980
1981 -- If all our exits were blocked by unconditional transfers of control,
1982 -- then the entire IF statement acts as an unconditional transfer of
1983 -- control, so treat it like one, and check unreachable code.
1984
1985 if Unblocked_Exit_Count = 0 then
1986 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1987 Check_Unreachable_Code (N);
1988 else
1989 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1990 end if;
1991
1992 if Del then
1993 Expander_Mode_Restore;
1994 In_Deleted_Code := Save_In_Deleted_Code;
1995 end if;
1996
1997 if not Expander_Active
1998 and then Compile_Time_Known_Value (Condition (N))
1999 and then Serious_Errors_Detected = 0
2000 then
2001 if Is_True (Expr_Value (Condition (N))) then
2002 Remove_Warning_Messages (Else_Statements (N));
2003
2004 E := First (Elsif_Parts (N));
2005 while Present (E) loop
2006 Remove_Warning_Messages (Then_Statements (E));
2007 Next (E);
2008 end loop;
2009
2010 else
2011 Remove_Warning_Messages (Then_Statements (N));
2012 end if;
2013 end if;
2014
2015 -- Warn on redundant if statement that has no effect
2016
2017 -- Note, we could also check empty ELSIF parts ???
2018
2019 if Warn_On_Redundant_Constructs
2020
2021 -- If statement must be from source
2022
2023 and then Comes_From_Source (N)
2024
2025 -- Condition must not have obvious side effect
2026
2027 and then Has_No_Obvious_Side_Effects (Condition (N))
2028
2029 -- No elsif parts of else part
2030
2031 and then No (Elsif_Parts (N))
2032 and then No (Else_Statements (N))
2033
2034 -- Then must be a single null statement
2035
2036 and then List_Length (Then_Statements (N)) = 1
2037 then
2038 -- Go to original node, since we may have rewritten something as
2039 -- a null statement (e.g. a case we could figure the outcome of).
2040
2041 declare
2042 T : constant Node_Id := First (Then_Statements (N));
2043 S : constant Node_Id := Original_Node (T);
2044
2045 begin
2046 if Comes_From_Source (S) and then Nkind (S) = N_Null_Statement then
2047 Error_Msg_N ("if statement has no effect?r?", N);
2048 end if;
2049 end;
2050 end if;
2051 end Analyze_If_Statement;
2052
2053 ----------------------------------------
2054 -- Analyze_Implicit_Label_Declaration --
2055 ----------------------------------------
2056
2057 -- An implicit label declaration is generated in the innermost enclosing
2058 -- declarative part. This is done for labels, and block and loop names.
2059
2060 procedure Analyze_Implicit_Label_Declaration (N : Node_Id) is
2061 Id : constant Node_Id := Defining_Identifier (N);
2062 begin
2063 Enter_Name (Id);
2064 Mutate_Ekind (Id, E_Label);
2065 Set_Etype (Id, Standard_Void_Type);
2066 Set_Enclosing_Scope (Id, Current_Scope);
2067
2068 -- A label declared within a Ghost region becomes Ghost (SPARK RM
2069 -- 6.9(2)).
2070
2071 if Ghost_Mode > None then
2072 Set_Is_Ghost_Entity (Id);
2073 end if;
2074 end Analyze_Implicit_Label_Declaration;
2075
2076 ------------------------------
2077 -- Analyze_Iteration_Scheme --
2078 ------------------------------
2079
2080 procedure Analyze_Iteration_Scheme (N : Node_Id) is
2081 Cond : Node_Id;
2082 Iter_Spec : Node_Id;
2083 Loop_Spec : Node_Id;
2084
2085 begin
2086 -- For an infinite loop, there is no iteration scheme
2087
2088 if No (N) then
2089 return;
2090 end if;
2091
2092 Cond := Condition (N);
2093 Iter_Spec := Iterator_Specification (N);
2094 Loop_Spec := Loop_Parameter_Specification (N);
2095
2096 if Present (Cond) then
2097 Analyze_And_Resolve (Cond, Any_Boolean);
2098 Check_Unset_Reference (Cond);
2099 Set_Current_Value_Condition (N);
2100
2101 elsif Present (Iter_Spec) then
2102 Analyze_Iterator_Specification (Iter_Spec);
2103
2104 else
2105 Analyze_Loop_Parameter_Specification (Loop_Spec);
2106 end if;
2107 end Analyze_Iteration_Scheme;
2108
2109 ------------------------------------
2110 -- Analyze_Iterator_Specification --
2111 ------------------------------------
2112
2113 procedure Analyze_Iterator_Specification (N : Node_Id) is
2114 Def_Id : constant Node_Id := Defining_Identifier (N);
2115 Iter_Name : constant Node_Id := Name (N);
2116 Loc : constant Source_Ptr := Sloc (N);
2117 Subt : constant Node_Id := Subtype_Indication (N);
2118
2119 Bas : Entity_Id := Empty; -- initialize to prevent warning
2120 Typ : Entity_Id;
2121
2122 procedure Check_Reverse_Iteration (Typ : Entity_Id);
2123 -- For an iteration over a container, if the loop carries the Reverse
2124 -- indicator, verify that the container type has an Iterate aspect that
2125 -- implements the reversible iterator interface.
2126
2127 procedure Check_Subtype_Definition (Comp_Type : Entity_Id);
2128 -- If a subtype indication is present, verify that it is consistent
2129 -- with the component type of the array or container name.
2130 -- In Ada 2022, the subtype indication may be an access definition,
2131 -- if the array or container has elements of an anonymous access type.
2132
2133 function Get_Cursor_Type (Typ : Entity_Id) return Entity_Id;
2134 -- For containers with Iterator and related aspects, the cursor is
2135 -- obtained by locating an entity with the proper name in the scope
2136 -- of the type.
2137
2138 -----------------------------
2139 -- Check_Reverse_Iteration --
2140 -----------------------------
2141
2142 procedure Check_Reverse_Iteration (Typ : Entity_Id) is
2143 begin
2144 if Reverse_Present (N) then
2145 if Is_Array_Type (Typ)
2146 or else Is_Reversible_Iterator (Typ)
2147 or else
2148 (Has_Aspect (Typ, Aspect_Iterable)
2149 and then
2150 Present
2151 (Get_Iterable_Type_Primitive (Typ, Name_Previous)))
2152 then
2153 null;
2154 else
2155 Error_Msg_N
2156 ("container type does not support reverse iteration", N);
2157 end if;
2158 end if;
2159 end Check_Reverse_Iteration;
2160
2161 -------------------------------
2162 -- Check_Subtype_Definition --
2163 -------------------------------
2164
2165 procedure Check_Subtype_Definition (Comp_Type : Entity_Id) is
2166 begin
2167 if No (Subt) then
2168 return;
2169 end if;
2170
2171 if Is_Anonymous_Access_Type (Entity (Subt)) then
2172 if not Is_Anonymous_Access_Type (Comp_Type) then
2173 Error_Msg_NE
2174 ("component type& is not an anonymous access",
2175 Subt, Comp_Type);
2176
2177 elsif not Conforming_Types
2178 (Designated_Type (Entity (Subt)),
2179 Designated_Type (Comp_Type),
2180 Fully_Conformant)
2181 then
2182 Error_Msg_NE
2183 ("subtype indication does not match component type&",
2184 Subt, Comp_Type);
2185 end if;
2186
2187 elsif not Covers (Base_Type (Bas), Comp_Type)
2188 or else not Subtypes_Statically_Match (Bas, Comp_Type)
2189 then
2190 if Is_Array_Type (Typ) then
2191 Error_Msg_NE
2192 ("subtype indication does not match component type&",
2193 Subt, Comp_Type);
2194 else
2195 Error_Msg_NE
2196 ("subtype indication does not match element type&",
2197 Subt, Comp_Type);
2198 end if;
2199 end if;
2200 end Check_Subtype_Definition;
2201
2202 ---------------------
2203 -- Get_Cursor_Type --
2204 ---------------------
2205
2206 function Get_Cursor_Type (Typ : Entity_Id) return Entity_Id is
2207 Ent : Entity_Id;
2208
2209 begin
2210 -- If the iterator type is derived and it has an iterator interface
2211 -- type as an ancestor, then the cursor type is declared in the scope
2212 -- of that interface type.
2213
2214 if Is_Derived_Type (Typ) then
2215 declare
2216 Iter_Iface : constant Entity_Id :=
2217 Iterator_Interface_Ancestor (Typ);
2218
2219 begin
2220 if Present (Iter_Iface) then
2221 Ent := First_Entity (Scope (Iter_Iface));
2222
2223 -- If there's not an iterator interface, then retrieve the
2224 -- scope associated with the parent type and start from its
2225 -- first entity.
2226
2227 else
2228 Ent := First_Entity (Scope (Etype (Typ)));
2229 end if;
2230 end;
2231
2232 else
2233 Ent := First_Entity (Scope (Typ));
2234 end if;
2235
2236 while Present (Ent) loop
2237 exit when Chars (Ent) = Name_Cursor;
2238 Next_Entity (Ent);
2239 end loop;
2240
2241 if No (Ent) then
2242 return Any_Type;
2243 end if;
2244
2245 -- The cursor is the target of generated assignments in the
2246 -- loop, and cannot have a limited type.
2247
2248 if Is_Limited_Type (Etype (Ent)) then
2249 Error_Msg_N ("cursor type cannot be limited", N);
2250 end if;
2251
2252 return Etype (Ent);
2253 end Get_Cursor_Type;
2254
2255 -- Start of processing for Analyze_Iterator_Specification
2256
2257 begin
2258 Enter_Name (Def_Id);
2259
2260 -- AI12-0151 specifies that when the subtype indication is present, it
2261 -- must statically match the type of the array or container element.
2262 -- To simplify this check, we introduce a subtype declaration with the
2263 -- given subtype indication when it carries a constraint, and rewrite
2264 -- the original as a reference to the created subtype entity.
2265
2266 if Present (Subt) then
2267 if Nkind (Subt) = N_Subtype_Indication then
2268 declare
2269 S : constant Entity_Id := Make_Temporary (Sloc (Subt), 'S');
2270 Decl : constant Node_Id :=
2271 Make_Subtype_Declaration (Loc,
2272 Defining_Identifier => S,
2273 Subtype_Indication => New_Copy_Tree (Subt));
2274 begin
2275 Insert_Action (N, Decl);
2276 Analyze (Decl);
2277 Rewrite (Subt, New_Occurrence_Of (S, Sloc (Subt)));
2278 end;
2279
2280 -- Ada 2022: the subtype definition may be for an anonymous
2281 -- access type.
2282
2283 elsif Nkind (Subt) = N_Access_Definition then
2284 declare
2285 S : constant Entity_Id := Make_Temporary (Sloc (Subt), 'S');
2286 Decl : Node_Id;
2287 begin
2288 if Present (Subtype_Mark (Subt)) then
2289 Decl :=
2290 Make_Full_Type_Declaration (Loc,
2291 Defining_Identifier => S,
2292 Type_Definition =>
2293 Make_Access_To_Object_Definition (Loc,
2294 All_Present => True,
2295 Subtype_Indication =>
2296 New_Copy_Tree (Subtype_Mark (Subt))));
2297
2298 else
2299 Decl :=
2300 Make_Full_Type_Declaration (Loc,
2301 Defining_Identifier => S,
2302 Type_Definition =>
2303 New_Copy_Tree
2304 (Access_To_Subprogram_Definition (Subt)));
2305 end if;
2306
2307 Insert_Before (Parent (Parent (N)), Decl);
2308 Analyze (Decl);
2309 Freeze_Before (First (Statements (Parent (Parent (N)))), S);
2310 Rewrite (Subt, New_Occurrence_Of (S, Sloc (Subt)));
2311 end;
2312 else
2313 Analyze (Subt);
2314 end if;
2315
2316 -- Save entity of subtype indication for subsequent check
2317
2318 Bas := Entity (Subt);
2319 end if;
2320
2321 Preanalyze_Range (Iter_Name);
2322
2323 -- If the domain of iteration is a function call, make sure the function
2324 -- itself is frozen. This is an issue if this is a local expression
2325 -- function.
2326
2327 if Nkind (Iter_Name) = N_Function_Call
2328 and then Is_Entity_Name (Name (Iter_Name))
2329 and then Full_Analysis
2330 and then (In_Assertion_Expr = 0 or else Assertions_Enabled)
2331 then
2332 Freeze_Before (N, Entity (Name (Iter_Name)));
2333 end if;
2334
2335 -- Set the kind of the loop variable, which is not visible within the
2336 -- iterator name.
2337
2338 Mutate_Ekind (Def_Id, E_Variable);
2339 Set_Is_Not_Self_Hidden (Def_Id);
2340
2341 -- Provide a link between the iterator variable and the container, for
2342 -- subsequent use in cross-reference and modification information.
2343
2344 if Of_Present (N) then
2345 Set_Related_Expression (Def_Id, Iter_Name);
2346
2347 -- For a container, the iterator is specified through the aspect
2348
2349 if not Is_Array_Type (Etype (Iter_Name)) then
2350 declare
2351 Iterator : constant Entity_Id :=
2352 Find_Value_Of_Aspect
2353 (Etype (Iter_Name), Aspect_Default_Iterator);
2354
2355 I : Interp_Index;
2356 It : Interp;
2357
2358 begin
2359 -- The domain of iteration must implement either the RM
2360 -- iterator interface, or the SPARK Iterable aspect.
2361
2362 if No (Iterator) then
2363 if No (Find_Aspect (Etype (Iter_Name), Aspect_Iterable)) then
2364 Error_Msg_NE
2365 ("cannot iterate over&",
2366 N, Base_Type (Etype (Iter_Name)));
2367 return;
2368 end if;
2369
2370 elsif not Is_Overloaded (Iterator) then
2371 Check_Reverse_Iteration (Etype (Iterator));
2372
2373 -- If Iterator is overloaded, use reversible iterator if one is
2374 -- available.
2375
2376 elsif Is_Overloaded (Iterator) then
2377 Get_First_Interp (Iterator, I, It);
2378 while Present (It.Nam) loop
2379 if Ekind (It.Nam) = E_Function
2380 and then Is_Reversible_Iterator (Etype (It.Nam))
2381 then
2382 Set_Etype (Iterator, It.Typ);
2383 Set_Entity (Iterator, It.Nam);
2384 exit;
2385 end if;
2386
2387 Get_Next_Interp (I, It);
2388 end loop;
2389
2390 Check_Reverse_Iteration (Etype (Iterator));
2391 end if;
2392 end;
2393 end if;
2394 end if;
2395
2396 -- If the domain of iteration is an expression, create a declaration for
2397 -- it, so that finalization actions are introduced outside of the loop.
2398 -- The declaration must be a renaming (both in GNAT and GNATprove
2399 -- modes), because the body of the loop may assign to elements.
2400
2401 if not Is_Entity_Name (Iter_Name)
2402
2403 -- Do not perform this expansion in preanalysis
2404
2405 and then Full_Analysis
2406
2407 -- Do not perform this expansion when expansion is disabled, where the
2408 -- temporary may hide the transformation of a selected component into
2409 -- a prefixed function call, and references need to see the original
2410 -- expression.
2411
2412 and then (Expander_Active or GNATprove_Mode)
2413 then
2414 declare
2415 Id : constant Entity_Id := Make_Temporary (Loc, 'R', Iter_Name);
2416 Decl : Node_Id;
2417 Act_S : Node_Id;
2418
2419 begin
2420
2421 -- If the domain of iteration is an array component that depends
2422 -- on a discriminant, create actual subtype for it. Preanalysis
2423 -- does not generate the actual subtype of a selected component.
2424
2425 if Nkind (Iter_Name) = N_Selected_Component
2426 and then Is_Array_Type (Etype (Iter_Name))
2427 then
2428 Act_S :=
2429 Build_Actual_Subtype_Of_Component
2430 (Etype (Selector_Name (Iter_Name)), Iter_Name);
2431 Insert_Action (N, Act_S);
2432
2433 if Present (Act_S) then
2434 Typ := Defining_Identifier (Act_S);
2435 else
2436 Typ := Etype (Iter_Name);
2437 end if;
2438
2439 else
2440 Typ := Etype (Iter_Name);
2441
2442 -- Verify that the expression produces an iterator
2443
2444 if not Of_Present (N) and then not Is_Iterator (Typ)
2445 and then not Is_Array_Type (Typ)
2446 and then No (Find_Aspect (Typ, Aspect_Iterable))
2447 then
2448 Error_Msg_N
2449 ("expect object that implements iterator interface",
2450 Iter_Name);
2451 end if;
2452 end if;
2453
2454 -- Protect against malformed iterator
2455
2456 if Typ = Any_Type then
2457 Error_Msg_N ("invalid expression in loop iterator", Iter_Name);
2458 return;
2459 end if;
2460
2461 if not Of_Present (N) then
2462 Check_Reverse_Iteration (Typ);
2463 end if;
2464
2465 -- For an element iteration over a slice, we must complete
2466 -- the resolution and expansion of the slice bounds. These
2467 -- can be arbitrary expressions, and the preanalysis that
2468 -- was performed in preparation for the iteration may have
2469 -- generated an itype whose bounds must be fully expanded.
2470 -- We set the parent node to provide a proper insertion
2471 -- point for generated actions, if any.
2472
2473 if Nkind (Iter_Name) = N_Slice
2474 and then Nkind (Discrete_Range (Iter_Name)) = N_Range
2475 and then not Analyzed (Discrete_Range (Iter_Name))
2476 then
2477 declare
2478 Indx : constant Node_Id :=
2479 Entity (First_Index (Etype (Iter_Name)));
2480 begin
2481 Set_Parent (Indx, Iter_Name);
2482 Resolve (Scalar_Range (Indx), Etype (Indx));
2483 end;
2484 end if;
2485
2486 -- The name in the renaming declaration may be a function call.
2487 -- Indicate that it does not come from source, to suppress
2488 -- spurious warnings on renamings of parameterless functions,
2489 -- a common enough idiom in user-defined iterators.
2490
2491 Decl :=
2492 Make_Object_Renaming_Declaration (Loc,
2493 Defining_Identifier => Id,
2494 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
2495 Name =>
2496 New_Copy_Tree (Iter_Name, New_Sloc => Loc));
2497 Set_Comes_From_Iterator (Decl);
2498
2499 Insert_Actions (Parent (Parent (N)), New_List (Decl));
2500 Rewrite (Name (N), New_Occurrence_Of (Id, Loc));
2501 Analyze (Name (N));
2502 Set_Etype (Id, Typ);
2503 Set_Etype (Name (N), Typ);
2504 end;
2505
2506 -- Container is an entity or an array with uncontrolled components, or
2507 -- else it is a container iterator given by a function call, typically
2508 -- called Iterate in the case of predefined containers, even though
2509 -- Iterate is not a reserved name. What matters is that the return type
2510 -- of the function is an iterator type.
2511
2512 elsif Is_Entity_Name (Iter_Name) then
2513 Analyze (Iter_Name);
2514
2515 if Nkind (Iter_Name) = N_Function_Call then
2516 declare
2517 C : constant Node_Id := Name (Iter_Name);
2518 I : Interp_Index;
2519 It : Interp;
2520
2521 begin
2522 if not Is_Overloaded (Iter_Name) then
2523 Resolve (Iter_Name, Etype (C));
2524
2525 else
2526 Get_First_Interp (C, I, It);
2527 while It.Typ /= Empty loop
2528 if Reverse_Present (N) then
2529 if Is_Reversible_Iterator (It.Typ) then
2530 Resolve (Iter_Name, It.Typ);
2531 exit;
2532 end if;
2533
2534 elsif Is_Iterator (It.Typ) then
2535 Resolve (Iter_Name, It.Typ);
2536 exit;
2537 end if;
2538
2539 Get_Next_Interp (I, It);
2540 end loop;
2541 end if;
2542 end;
2543
2544 -- Domain of iteration is not overloaded
2545
2546 else
2547 Resolve (Iter_Name);
2548 end if;
2549
2550 if not Of_Present (N) then
2551 Check_Reverse_Iteration (Etype (Iter_Name));
2552 end if;
2553 end if;
2554
2555 -- Get base type of container, for proper retrieval of Cursor type
2556 -- and primitive operations.
2557
2558 Typ := Base_Type (Etype (Iter_Name));
2559
2560 if Is_Array_Type (Typ) then
2561 if Of_Present (N) then
2562 Set_Etype (Def_Id, Component_Type (Typ));
2563
2564 -- The loop variable is aliased if the array components are
2565 -- aliased. Likewise for the independent aspect.
2566
2567 Set_Is_Aliased (Def_Id, Has_Aliased_Components (Typ));
2568 Set_Is_Independent (Def_Id, Has_Independent_Components (Typ));
2569
2570 -- AI12-0047 stipulates that the domain (array or container)
2571 -- cannot be a component that depends on a discriminant if the
2572 -- enclosing object is mutable, to prevent a modification of the
2573 -- domain of iteration in the course of an iteration.
2574
2575 -- If the object is an expression it has been captured in a
2576 -- temporary, so examine original node.
2577
2578 if Nkind (Original_Node (Iter_Name)) = N_Selected_Component
2579 and then Is_Dependent_Component_Of_Mutable_Object
2580 (Original_Node (Iter_Name))
2581 then
2582 Error_Msg_N
2583 ("iterable name cannot be a discriminant-dependent "
2584 & "component of a mutable object", N);
2585
2586 elsif Depends_On_Mutably_Tagged_Ext_Comp
2587 (Original_Node (Iter_Name))
2588 then
2589 Error_Msg_N
2590 ("iterable name cannot depend on a mutably tagged component",
2591 N);
2592 end if;
2593
2594 Check_Subtype_Definition (Component_Type (Typ));
2595
2596 -- Here we have a missing Range attribute
2597
2598 else
2599 Error_Msg_N
2600 ("missing Range attribute in iteration over an array", N);
2601
2602 -- In Ada 2012 mode, this may be an attempt at an iterator
2603
2604 if Ada_Version >= Ada_2012 then
2605 Error_Msg_NE
2606 ("\if& is meant to designate an element of the array, use OF",
2607 N, Def_Id);
2608 end if;
2609
2610 -- Prevent cascaded errors
2611
2612 Mutate_Ekind (Def_Id, E_Loop_Parameter);
2613 Set_Etype (Def_Id, Etype (First_Index (Typ)));
2614 end if;
2615
2616 -- Check for type error in iterator
2617
2618 elsif Typ = Any_Type then
2619 return;
2620
2621 -- Iteration over a container
2622
2623 else
2624 Mutate_Ekind (Def_Id, E_Loop_Parameter);
2625 Set_Is_Not_Self_Hidden (Def_Id);
2626 Error_Msg_Ada_2012_Feature ("container iterator", Sloc (N));
2627
2628 -- OF present
2629
2630 if Of_Present (N) then
2631 if Has_Aspect (Typ, Aspect_Iterable) then
2632 declare
2633 Elt : constant Entity_Id :=
2634 Get_Iterable_Type_Primitive (Typ, Name_Element);
2635 begin
2636 if No (Elt) then
2637 Error_Msg_N
2638 ("missing Element primitive for iteration", N);
2639 else
2640 Set_Etype (Def_Id, Etype (Elt));
2641 Check_Reverse_Iteration (Typ);
2642 end if;
2643 end;
2644
2645 Check_Subtype_Definition (Etype (Def_Id));
2646
2647 -- For a predefined container, the type of the loop variable is
2648 -- the Iterator_Element aspect of the container type.
2649
2650 else
2651 declare
2652 Element : constant Entity_Id :=
2653 Find_Value_Of_Aspect
2654 (Typ, Aspect_Iterator_Element);
2655 Iterator : constant Entity_Id :=
2656 Find_Value_Of_Aspect
2657 (Typ, Aspect_Default_Iterator);
2658 Orig_Iter_Name : constant Node_Id :=
2659 Original_Node (Iter_Name);
2660 Cursor_Type : Entity_Id;
2661
2662 begin
2663 if No (Element) then
2664 Error_Msg_NE ("cannot iterate over&", N, Typ);
2665 return;
2666
2667 else
2668 Set_Etype (Def_Id, Entity (Element));
2669 Cursor_Type := Get_Cursor_Type (Typ);
2670 pragma Assert (Present (Cursor_Type));
2671
2672 Check_Subtype_Definition (Etype (Def_Id));
2673
2674 -- If the container has a variable indexing aspect, the
2675 -- element is a variable and is modifiable in the loop.
2676
2677 if Has_Aspect (Typ, Aspect_Variable_Indexing) then
2678 Mutate_Ekind (Def_Id, E_Variable);
2679 Set_Is_Not_Self_Hidden (Def_Id);
2680 end if;
2681
2682 -- If the container is a constant, iterating over it
2683 -- requires a Constant_Indexing operation.
2684
2685 if not Is_Variable (Iter_Name)
2686 and then not Has_Aspect (Typ, Aspect_Constant_Indexing)
2687 then
2688 Error_Msg_N
2689 ("iteration over constant container require "
2690 & "constant_indexing aspect", N);
2691
2692 -- The Iterate function may have an in_out parameter,
2693 -- and a constant container is thus illegal.
2694
2695 elsif Present (Iterator)
2696 and then Ekind (Entity (Iterator)) = E_Function
2697 and then Ekind (First_Formal (Entity (Iterator))) /=
2698 E_In_Parameter
2699 and then not Is_Variable (Iter_Name)
2700 then
2701 Error_Msg_N ("variable container expected", N);
2702 end if;
2703
2704 -- Detect a case where the iterator denotes a component
2705 -- of a mutable object which depends on a discriminant.
2706 -- Note that the iterator may denote a function call in
2707 -- qualified form, in which case this check should not
2708 -- be performed.
2709
2710 if Nkind (Orig_Iter_Name) = N_Selected_Component
2711 and then
2712 Present (Entity (Selector_Name (Orig_Iter_Name)))
2713 and then
2714 Ekind (Entity (Selector_Name (Orig_Iter_Name))) in
2715 E_Component | E_Discriminant
2716 and then Is_Dependent_Component_Of_Mutable_Object
2717 (Orig_Iter_Name)
2718 then
2719 Error_Msg_N
2720 ("container cannot be a discriminant-dependent "
2721 & "component of a mutable object", N);
2722
2723 elsif Depends_On_Mutably_Tagged_Ext_Comp
2724 (Orig_Iter_Name)
2725 then
2726 Error_Msg_N
2727 ("container cannot depend on a mutably tagged "
2728 & "component", N);
2729 end if;
2730 end if;
2731 end;
2732 end if;
2733
2734 -- IN iterator, domain is a range, a call to Iterate function,
2735 -- or an object/actual parameter of an iterator type.
2736
2737 else
2738 -- If the type of the name is class-wide and its root type is a
2739 -- derived type, the primitive operations (First, Next, etc.) are
2740 -- those inherited by its specific type. Calls to these primitives
2741 -- will be dispatching.
2742
2743 if Is_Class_Wide_Type (Typ)
2744 and then Is_Derived_Type (Etype (Typ))
2745 then
2746 Typ := Etype (Typ);
2747 end if;
2748
2749 -- For an iteration of the form IN, the name must denote an
2750 -- iterator, typically the result of a call to Iterate. Give a
2751 -- useful error message when the name is a container by itself.
2752
2753 -- The type may be a formal container type, which has to have
2754 -- an Iterable aspect detailing the required primitives.
2755
2756 if Is_Entity_Name (Original_Node (Name (N)))
2757 and then not Is_Iterator (Typ)
2758 then
2759 if Has_Aspect (Typ, Aspect_Iterable) then
2760 null;
2761
2762 elsif not Has_Aspect (Typ, Aspect_Iterator_Element) then
2763 Error_Msg_NE
2764 ("cannot iterate over&", Name (N), Typ);
2765 else
2766 Error_Msg_N
2767 ("name must be an iterator, not a container", Name (N));
2768 end if;
2769
2770 if Has_Aspect (Typ, Aspect_Iterable) then
2771 null;
2772 else
2773 Error_Msg_NE
2774 ("\to iterate directly over the elements of a container, "
2775 & "write `of &`", Name (N), Original_Node (Name (N)));
2776
2777 -- No point in continuing analysis of iterator spec
2778
2779 return;
2780 end if;
2781 end if;
2782
2783 -- If the name is a call (typically prefixed) to some Iterate
2784 -- function, it has been rewritten as an object declaration.
2785 -- If that object is a selected component, verify that it is not
2786 -- a component of an unconstrained mutable object.
2787
2788 if Nkind (Iter_Name) = N_Identifier
2789 or else (not Expander_Active and Comes_From_Source (Iter_Name))
2790 then
2791 declare
2792 Orig_Node : constant Node_Id := Original_Node (Iter_Name);
2793 Iter_Kind : constant Node_Kind := Nkind (Orig_Node);
2794 Obj : Node_Id;
2795
2796 begin
2797 if Iter_Kind = N_Selected_Component then
2798 Obj := Prefix (Orig_Node);
2799
2800 elsif Iter_Kind = N_Function_Call then
2801 Obj := First_Actual (Orig_Node);
2802
2803 -- If neither, the name comes from source
2804
2805 else
2806 Obj := Iter_Name;
2807 end if;
2808
2809 if Nkind (Obj) = N_Selected_Component
2810 and then Is_Dependent_Component_Of_Mutable_Object (Obj)
2811 then
2812 Error_Msg_N
2813 ("container cannot be a discriminant-dependent "
2814 & "component of a mutable object", N);
2815
2816 elsif Depends_On_Mutably_Tagged_Ext_Comp (Obj) then
2817 Error_Msg_N
2818 ("container cannot depend on a mutably tagged"
2819 & " component", N);
2820 end if;
2821 end;
2822 end if;
2823
2824 -- The result type of Iterate function is the classwide type of
2825 -- the interface parent. We need the specific Cursor type defined
2826 -- in the container package. We obtain it by name for a predefined
2827 -- container, or through the Iterable aspect for a formal one.
2828
2829 if Has_Aspect (Typ, Aspect_Iterable) then
2830 Set_Etype (Def_Id,
2831 Get_Cursor_Type
2832 (Parent (Find_Value_Of_Aspect (Typ, Aspect_Iterable)),
2833 Typ));
2834
2835 else
2836 Set_Etype (Def_Id, Get_Cursor_Type (Typ));
2837 Check_Reverse_Iteration (Etype (Iter_Name));
2838 end if;
2839
2840 end if;
2841 end if;
2842
2843 -- Preanalyze the filter. Expansion will take place when enclosing
2844 -- loop is expanded.
2845
2846 if Present (Iterator_Filter (N)) then
2847 Preanalyze_And_Resolve (Iterator_Filter (N), Standard_Boolean);
2848 end if;
2849 end Analyze_Iterator_Specification;
2850
2851 -------------------
2852 -- Analyze_Label --
2853 -------------------
2854
2855 -- Note: the semantic work required for analyzing labels (setting them as
2856 -- reachable) was done in a prepass through the statements in the block,
2857 -- so that forward gotos would be properly handled. See Analyze_Statements
2858 -- for further details. The only processing required here is to deal with
2859 -- optimizations that depend on an assumption of sequential control flow,
2860 -- since of course the occurrence of a label breaks this assumption.
2861
2862 procedure Analyze_Label (N : Node_Id) is
2863 pragma Warnings (Off, N);
2864 begin
2865 Kill_Current_Values;
2866 end Analyze_Label;
2867
2868 ------------------------------------------
2869 -- Analyze_Loop_Parameter_Specification --
2870 ------------------------------------------
2871
2872 procedure Analyze_Loop_Parameter_Specification (N : Node_Id) is
2873 Loop_Nod : constant Node_Id := Parent (Parent (N));
2874
2875 procedure Check_Controlled_Array_Attribute (DS : Node_Id);
2876 -- If the bounds are given by a 'Range reference on a function call
2877 -- that returns a controlled array, introduce an explicit declaration
2878 -- to capture the bounds, so that the function result can be finalized
2879 -- in timely fashion.
2880
2881 procedure Check_Predicate_Use (T : Entity_Id);
2882 -- Diagnose Attempt to iterate through non-static predicate. Note that
2883 -- a type with inherited predicates may have both static and dynamic
2884 -- forms. In this case it is not sufficient to check the static
2885 -- predicate function only, look for a dynamic predicate aspect as well.
2886
2887 procedure Process_Bounds (R : Node_Id);
2888 -- If the iteration is given by a range, create temporaries and
2889 -- assignment statements block to capture the bounds and perform
2890 -- required finalization actions in case a bound includes a function
2891 -- call that uses the temporary stack. We first preanalyze a copy of
2892 -- the range in order to determine the expected type, and analyze and
2893 -- resolve the original bounds.
2894
2895 --------------------------------------
2896 -- Check_Controlled_Array_Attribute --
2897 --------------------------------------
2898
2899 procedure Check_Controlled_Array_Attribute (DS : Node_Id) is
2900 begin
2901 if Nkind (DS) = N_Attribute_Reference
2902 and then Is_Entity_Name (Prefix (DS))
2903 and then Ekind (Entity (Prefix (DS))) = E_Function
2904 and then Is_Array_Type (Etype (Entity (Prefix (DS))))
2905 and then
2906 Is_Controlled (Component_Type (Etype (Entity (Prefix (DS)))))
2907 and then Expander_Active
2908 then
2909 declare
2910 Loc : constant Source_Ptr := Sloc (N);
2911 Arr : constant Entity_Id := Etype (Entity (Prefix (DS)));
2912 Indx : constant Entity_Id :=
2913 Base_Type (Etype (First_Index (Arr)));
2914 Subt : constant Entity_Id := Make_Temporary (Loc, 'S');
2915 Decl : Node_Id;
2916
2917 begin
2918 Decl :=
2919 Make_Subtype_Declaration (Loc,
2920 Defining_Identifier => Subt,
2921 Subtype_Indication =>
2922 Make_Subtype_Indication (Loc,
2923 Subtype_Mark => New_Occurrence_Of (Indx, Loc),
2924 Constraint =>
2925 Make_Range_Constraint (Loc, Relocate_Node (DS))));
2926 Insert_Before (Loop_Nod, Decl);
2927 Analyze (Decl);
2928
2929 Rewrite (DS,
2930 Make_Attribute_Reference (Loc,
2931 Prefix => New_Occurrence_Of (Subt, Loc),
2932 Attribute_Name => Attribute_Name (DS)));
2933
2934 Analyze (DS);
2935 end;
2936 end if;
2937 end Check_Controlled_Array_Attribute;
2938
2939 -------------------------
2940 -- Check_Predicate_Use --
2941 -------------------------
2942
2943 procedure Check_Predicate_Use (T : Entity_Id) is
2944 begin
2945 -- A predicated subtype is illegal in loops and related constructs
2946 -- if the predicate is not static, or if it is a non-static subtype
2947 -- of a statically predicated subtype.
2948
2949 if Is_Discrete_Type (T)
2950 and then Has_Predicates (T)
2951 and then (not Has_Static_Predicate (T)
2952 or else not Is_Static_Subtype (T)
2953 or else Has_Dynamic_Predicate_Aspect (T)
2954 or else Has_Ghost_Predicate_Aspect (T))
2955 then
2956 -- Seems a confusing message for the case of a static predicate
2957 -- with a non-static subtype???
2958
2959 Bad_Predicated_Subtype_Use
2960 ("cannot use subtype& with non-static predicate for loop "
2961 & "iteration", Discrete_Subtype_Definition (N),
2962 T, Suggest_Static => True);
2963
2964 elsif Inside_A_Generic
2965 and then Is_Generic_Formal (T)
2966 and then Is_Discrete_Type (T)
2967 then
2968 Set_No_Dynamic_Predicate_On_Actual (T);
2969 end if;
2970 end Check_Predicate_Use;
2971
2972 --------------------
2973 -- Process_Bounds --
2974 --------------------
2975
2976 procedure Process_Bounds (R : Node_Id) is
2977 Loc : constant Source_Ptr := Sloc (N);
2978
2979 function One_Bound
2980 (Original_Bound : Node_Id;
2981 Analyzed_Bound : Node_Id;
2982 Typ : Entity_Id) return Node_Id;
2983 -- Capture value of bound and return captured value
2984
2985 ---------------
2986 -- One_Bound --
2987 ---------------
2988
2989 function One_Bound
2990 (Original_Bound : Node_Id;
2991 Analyzed_Bound : Node_Id;
2992 Typ : Entity_Id) return Node_Id
2993 is
2994 Assign : Node_Id;
2995 Decl : Node_Id;
2996 Id : Entity_Id;
2997
2998 begin
2999 -- If the bound is a constant or an object, no need for a separate
3000 -- declaration. If the bound is the result of previous expansion
3001 -- it is already analyzed and should not be modified. Note that
3002 -- the Bound will be resolved later, if needed, as part of the
3003 -- call to Make_Index (literal bounds may need to be resolved to
3004 -- type Integer).
3005
3006 if Analyzed (Original_Bound) then
3007 return Original_Bound;
3008
3009 elsif Nkind (Analyzed_Bound) in
3010 N_Integer_Literal | N_Character_Literal
3011 or else Is_Entity_Name (Analyzed_Bound)
3012 then
3013 Analyze_And_Resolve (Original_Bound, Typ);
3014 return Original_Bound;
3015
3016 elsif Inside_Class_Condition_Preanalysis then
3017 Analyze_And_Resolve (Original_Bound, Typ);
3018 return Original_Bound;
3019 end if;
3020
3021 -- Normally, the best approach is simply to generate a constant
3022 -- declaration that captures the bound. However, there is a nasty
3023 -- case where this is wrong. If the bound is complex, and has a
3024 -- possible use of the secondary stack, we need to generate a
3025 -- separate assignment statement to ensure the creation of a block
3026 -- which will release the secondary stack.
3027
3028 -- We prefer the constant declaration, since it leaves us with a
3029 -- proper trace of the value, useful in optimizations that get rid
3030 -- of junk range checks.
3031
3032 if not Has_Sec_Stack_Call (Analyzed_Bound) then
3033 Analyze_And_Resolve (Original_Bound, Typ);
3034
3035 -- Ensure that the bound is valid. This check should not be
3036 -- generated when the range belongs to a quantified expression
3037 -- as the construct is still not expanded into its final form.
3038
3039 if Nkind (Parent (R)) /= N_Loop_Parameter_Specification
3040 or else Nkind (Parent (Parent (R))) /= N_Quantified_Expression
3041 then
3042 Ensure_Valid (Original_Bound);
3043 end if;
3044
3045 Force_Evaluation (Original_Bound);
3046 return Original_Bound;
3047 end if;
3048
3049 Id := Make_Temporary (Loc, 'R', Original_Bound);
3050
3051 -- Here we make a declaration with a separate assignment
3052 -- statement, and insert before loop header.
3053
3054 Decl :=
3055 Make_Object_Declaration (Loc,
3056 Defining_Identifier => Id,
3057 Object_Definition => New_Occurrence_Of (Typ, Loc));
3058
3059 Assign :=
3060 Make_Assignment_Statement (Loc,
3061 Name => New_Occurrence_Of (Id, Loc),
3062 Expression => Relocate_Node (Original_Bound));
3063
3064 Insert_Actions (Loop_Nod, New_List (Decl, Assign));
3065
3066 -- Now that this temporary variable is initialized we decorate it
3067 -- as safe-to-reevaluate to inform to the backend that no further
3068 -- asignment will be issued and hence it can be handled as side
3069 -- effect free. Note that this decoration must be done when the
3070 -- assignment has been analyzed because otherwise it will be
3071 -- rejected (see Analyze_Assignment).
3072
3073 Set_Is_Safe_To_Reevaluate (Id);
3074
3075 Rewrite (Original_Bound, New_Occurrence_Of (Id, Loc));
3076
3077 if Nkind (Assign) = N_Assignment_Statement then
3078 return Expression (Assign);
3079 else
3080 return Original_Bound;
3081 end if;
3082 end One_Bound;
3083
3084 Hi : constant Node_Id := High_Bound (R);
3085 Lo : constant Node_Id := Low_Bound (R);
3086 R_Copy : constant Node_Id := New_Copy_Tree (R);
3087 New_Hi : Node_Id;
3088 New_Lo : Node_Id;
3089 Typ : Entity_Id;
3090
3091 -- Start of processing for Process_Bounds
3092
3093 begin
3094 Set_Parent (R_Copy, Parent (R));
3095 Preanalyze_Range (R_Copy);
3096 Typ := Etype (R_Copy);
3097
3098 -- If the type of the discrete range is Universal_Integer, then the
3099 -- bound's type must be resolved to Integer, and any object used to
3100 -- hold the bound must also have type Integer, unless the literal
3101 -- bounds are constant-folded expressions with a user-defined type.
3102
3103 if Typ = Universal_Integer then
3104 if Nkind (Lo) = N_Integer_Literal
3105 and then Present (Etype (Lo))
3106 and then Scope (Etype (Lo)) /= Standard_Standard
3107 then
3108 Typ := Etype (Lo);
3109
3110 elsif Nkind (Hi) = N_Integer_Literal
3111 and then Present (Etype (Hi))
3112 and then Scope (Etype (Hi)) /= Standard_Standard
3113 then
3114 Typ := Etype (Hi);
3115
3116 else
3117 Typ := Standard_Integer;
3118 end if;
3119 end if;
3120
3121 Set_Etype (R, Typ);
3122
3123 New_Lo := One_Bound (Lo, Low_Bound (R_Copy), Typ);
3124 New_Hi := One_Bound (Hi, High_Bound (R_Copy), Typ);
3125
3126 -- Propagate staticness to loop range itself, in case the
3127 -- corresponding subtype is static.
3128
3129 if New_Lo /= Lo and then Is_OK_Static_Expression (New_Lo) then
3130 Rewrite (Low_Bound (R), New_Copy (New_Lo));
3131 end if;
3132
3133 if New_Hi /= Hi and then Is_OK_Static_Expression (New_Hi) then
3134 Rewrite (High_Bound (R), New_Copy (New_Hi));
3135 end if;
3136 end Process_Bounds;
3137
3138 -- Local variables
3139
3140 DS : constant Node_Id := Discrete_Subtype_Definition (N);
3141 Id : constant Entity_Id := Defining_Identifier (N);
3142
3143 DS_Copy : Node_Id;
3144
3145 -- Start of processing for Analyze_Loop_Parameter_Specification
3146
3147 begin
3148 Enter_Name (Id);
3149
3150 -- We always consider the loop variable to be referenced, since the loop
3151 -- may be used just for counting purposes.
3152
3153 Generate_Reference (Id, N, ' ');
3154
3155 -- Check for the case of loop variable hiding a local variable (used
3156 -- later on to give a nice warning if the hidden variable is never
3157 -- assigned).
3158
3159 declare
3160 H : constant Entity_Id := Homonym (Id);
3161 begin
3162 if Present (H)
3163 and then Ekind (H) = E_Variable
3164 and then Is_Discrete_Type (Etype (H))
3165 and then Enclosing_Dynamic_Scope (H) = Enclosing_Dynamic_Scope (Id)
3166 then
3167 Set_Hiding_Loop_Variable (H, Id);
3168 end if;
3169 end;
3170
3171 -- Analyze the subtype definition and create temporaries for the bounds.
3172 -- Do not evaluate the range when preanalyzing a quantified expression
3173 -- because bounds expressed as function calls with side effects will be
3174 -- incorrectly replicated.
3175
3176 if Nkind (DS) = N_Range
3177 and then Expander_Active
3178 and then Nkind (Parent (N)) /= N_Quantified_Expression
3179 then
3180 Process_Bounds (DS);
3181
3182 -- Either the expander not active or the range of iteration is a subtype
3183 -- indication, an entity, or a function call that yields an aggregate or
3184 -- a container.
3185
3186 else
3187 DS_Copy := New_Copy_Tree (DS);
3188 Set_Parent (DS_Copy, Parent (DS));
3189 Preanalyze_Range (DS_Copy);
3190
3191 -- Ada 2012: If the domain of iteration is:
3192
3193 -- a) a function call,
3194 -- b) an identifier that is not a type,
3195 -- c) an attribute reference 'Old (within a postcondition),
3196 -- d) an unchecked conversion or a qualified expression with
3197 -- the proper iterator type.
3198
3199 -- then it is an iteration over a container. It was classified as
3200 -- a loop specification by the parser, and must be rewritten now
3201 -- to activate container iteration. The last case will occur within
3202 -- an expanded inlined call, where the expansion wraps an actual in
3203 -- an unchecked conversion when needed. The expression of the
3204 -- conversion is always an object.
3205
3206 if Nkind (DS_Copy) = N_Function_Call
3207
3208 or else (Is_Entity_Name (DS_Copy)
3209 and then not Is_Type (Entity (DS_Copy)))
3210
3211 or else (Nkind (DS_Copy) = N_Attribute_Reference
3212 and then Attribute_Name (DS_Copy) in
3213 Name_Loop_Entry | Name_Old)
3214
3215 or else Has_Aspect (Etype (DS_Copy), Aspect_Iterable)
3216
3217 or else Nkind (DS_Copy) = N_Unchecked_Type_Conversion
3218 or else (Nkind (DS_Copy) = N_Qualified_Expression
3219 and then Is_Iterator (Etype (DS_Copy)))
3220 then
3221 -- This is an iterator specification. Rewrite it as such and
3222 -- analyze it to capture function calls that may require
3223 -- finalization actions.
3224
3225 declare
3226 I_Spec : constant Node_Id :=
3227 Make_Iterator_Specification (Sloc (N),
3228 Defining_Identifier => Relocate_Node (Id),
3229 Name => DS_Copy,
3230 Subtype_Indication => Empty,
3231 Reverse_Present => Reverse_Present (N));
3232 Scheme : constant Node_Id := Parent (N);
3233
3234 begin
3235 Set_Iterator_Specification (Scheme, I_Spec);
3236 Set_Loop_Parameter_Specification (Scheme, Empty);
3237 Set_Iterator_Filter (I_Spec,
3238 Relocate_Node (Iterator_Filter (N)));
3239
3240 Analyze_Iterator_Specification (I_Spec);
3241
3242 -- In a generic context, analyze the original domain of
3243 -- iteration, for name capture.
3244
3245 if not Expander_Active then
3246 Analyze (DS);
3247 end if;
3248
3249 -- Set kind of loop parameter, which may be used in the
3250 -- subsequent analysis of the condition in a quantified
3251 -- expression.
3252
3253 Mutate_Ekind (Id, E_Loop_Parameter);
3254 return;
3255 end;
3256
3257 -- Domain of iteration is not a function call, and is side-effect
3258 -- free.
3259
3260 else
3261 -- A quantified expression that appears in a pre/post condition
3262 -- is preanalyzed several times. If the range is given by an
3263 -- attribute reference it is rewritten as a range, and this is
3264 -- done even with expansion disabled. If the type is already set
3265 -- do not reanalyze, because a range with static bounds may be
3266 -- typed Integer by default.
3267
3268 if Nkind (Parent (N)) = N_Quantified_Expression
3269 and then Present (Etype (DS))
3270 then
3271 null;
3272 else
3273 Analyze (DS);
3274 end if;
3275 end if;
3276 end if;
3277
3278 if DS = Error then
3279 return;
3280 end if;
3281
3282 -- Some additional checks if we are iterating through a type
3283
3284 if Is_Entity_Name (DS)
3285 and then Present (Entity (DS))
3286 and then Is_Type (Entity (DS))
3287 then
3288 -- The subtype indication may denote the completion of an incomplete
3289 -- type declaration.
3290
3291 if Ekind (Entity (DS)) = E_Incomplete_Type then
3292 Set_Entity (DS, Get_Full_View (Entity (DS)));
3293 Set_Etype (DS, Entity (DS));
3294 end if;
3295
3296 Check_Predicate_Use (Entity (DS));
3297 end if;
3298
3299 -- Error if not discrete type
3300
3301 if not Is_Discrete_Type (Etype (DS)) then
3302 Wrong_Type (DS, Any_Discrete);
3303 Set_Etype (DS, Any_Type);
3304 end if;
3305
3306 Check_Controlled_Array_Attribute (DS);
3307
3308 if Nkind (DS) = N_Subtype_Indication then
3309 Check_Predicate_Use (Entity (Subtype_Mark (DS)));
3310 end if;
3311
3312 if Nkind (DS) not in N_Raise_xxx_Error then
3313 Make_Index (DS, N);
3314 end if;
3315
3316 Mutate_Ekind (Id, E_Loop_Parameter);
3317 Set_Etype (Id, Etype (DS));
3318
3319 Set_Is_Not_Self_Hidden (Id);
3320
3321 -- Treat a range as an implicit reference to the type, to inhibit
3322 -- spurious warnings.
3323
3324 Generate_Reference (Base_Type (Etype (DS)), N, ' ');
3325 Set_Is_Known_Valid (Id, True);
3326
3327 -- The loop is not a declarative part, so the loop variable must be
3328 -- frozen explicitly. Do not freeze while preanalyzing a quantified
3329 -- expression because the freeze node will not be inserted into the
3330 -- tree due to flag Is_Spec_Expression being set.
3331
3332 if Nkind (Parent (N)) /= N_Quantified_Expression then
3333 declare
3334 Flist : constant List_Id := Freeze_Entity (Id, N);
3335 begin
3336 Insert_Actions (N, Flist);
3337 end;
3338 end if;
3339
3340 -- Case where we have a range or a subtype, get type bounds
3341
3342 if Nkind (DS) in N_Range | N_Subtype_Indication
3343 and then not Error_Posted (DS)
3344 and then Etype (DS) /= Any_Type
3345 and then Is_Discrete_Type (Etype (DS))
3346 then
3347 declare
3348 L : Node_Id;
3349 H : Node_Id;
3350 Null_Range : Boolean := False;
3351
3352 begin
3353 if Nkind (DS) = N_Range then
3354 L := Low_Bound (DS);
3355 H := High_Bound (DS);
3356 else
3357 L :=
3358 Type_Low_Bound (Underlying_Type (Etype (Subtype_Mark (DS))));
3359 H :=
3360 Type_High_Bound (Underlying_Type (Etype (Subtype_Mark (DS))));
3361 end if;
3362
3363 -- Check for null or possibly null range and issue warning. We
3364 -- suppress such messages in generic templates and instances,
3365 -- because in practice they tend to be dubious in these cases. The
3366 -- check applies as well to rewritten array element loops where a
3367 -- null range may be detected statically.
3368
3369 if Compile_Time_Compare (L, H, Assume_Valid => True) = GT then
3370 if Compile_Time_Compare (L, H, Assume_Valid => False) = GT then
3371 -- Since we know the range of the loop is always null,
3372 -- set the appropriate flag to remove the loop entirely
3373 -- during expansion.
3374
3375 if Nkind (Loop_Nod) = N_Loop_Statement then
3376 Set_Is_Null_Loop (Loop_Nod);
3377 end if;
3378
3379 Null_Range := True;
3380 end if;
3381
3382 -- Suppress the warning if inside a generic template or
3383 -- instance, since in practice they tend to be dubious in these
3384 -- cases since they can result from intended parameterization.
3385
3386 if Comes_From_Source (N)
3387 and then not Inside_A_Generic
3388 and then not In_Instance
3389 then
3390
3391 -- Specialize msg if invalid values could make the loop
3392 -- non-null after all.
3393
3394 if Null_Range then
3395 Error_Msg_N
3396 ("??loop range is null, loop will not execute", DS);
3397
3398 -- Here is where the loop could execute because of
3399 -- invalid values, so issue appropriate message.
3400
3401 else
3402 Error_Msg_N
3403 ("??loop range may be null, loop may not execute", DS);
3404
3405 Error_Msg_N
3406 ("??can only execute if invalid values are present",
3407 DS);
3408 end if;
3409 end if;
3410
3411 -- In either case, suppress warnings in the body of the loop,
3412 -- since it is likely that these warnings will be inappropriate
3413 -- if the loop never actually executes, which is likely.
3414
3415 if Nkind (Loop_Nod) = N_Loop_Statement then
3416 Set_Suppress_Loop_Warnings (Loop_Nod);
3417 end if;
3418
3419 -- The other case for a warning is a reverse loop where the
3420 -- upper bound is the integer literal zero or one, and the
3421 -- lower bound may exceed this value.
3422
3423 -- For example, we have
3424
3425 -- for J in reverse N .. 1 loop
3426
3427 -- In practice, this is very likely to be a case of reversing
3428 -- the bounds incorrectly in the range.
3429
3430 elsif Reverse_Present (N)
3431 and then Nkind (Original_Node (H)) = N_Integer_Literal
3432 and then
3433 (Intval (Original_Node (H)) = Uint_0
3434 or else
3435 Intval (Original_Node (H)) = Uint_1)
3436 then
3437 -- Lower bound may in fact be known and known not to exceed
3438 -- upper bound (e.g. reverse 0 .. 1) and that's OK.
3439
3440 if Compile_Time_Known_Value (L)
3441 and then Expr_Value (L) <= Expr_Value (H)
3442 then
3443 null;
3444
3445 -- Otherwise warning is warranted
3446
3447 else
3448 Error_Msg_N ("??loop range may be null", DS);
3449 Error_Msg_N ("\??bounds may be wrong way round", DS);
3450 end if;
3451 end if;
3452
3453 -- Check if either bound is known to be outside the range of the
3454 -- loop parameter type, this is e.g. the case of a loop from
3455 -- 20..X where the type is 1..19.
3456
3457 -- Such a loop is dubious since either it raises CE or it executes
3458 -- zero times, and that cannot be useful!
3459
3460 if Etype (DS) /= Any_Type
3461 and then not Error_Posted (DS)
3462 and then Nkind (DS) = N_Subtype_Indication
3463 and then Nkind (Constraint (DS)) = N_Range_Constraint
3464 then
3465 declare
3466 LLo : constant Node_Id :=
3467 Low_Bound (Range_Expression (Constraint (DS)));
3468 LHi : constant Node_Id :=
3469 High_Bound (Range_Expression (Constraint (DS)));
3470
3471 Bad_Bound : Node_Id := Empty;
3472 -- Suspicious loop bound
3473
3474 begin
3475 -- At this stage L, H are the bounds of the type, and LLo
3476 -- Lhi are the low bound and high bound of the loop.
3477
3478 if Compile_Time_Compare (LLo, L, Assume_Valid => True) = LT
3479 or else
3480 Compile_Time_Compare (LLo, H, Assume_Valid => True) = GT
3481 then
3482 Bad_Bound := LLo;
3483 end if;
3484
3485 if Compile_Time_Compare (LHi, L, Assume_Valid => True) = LT
3486 or else
3487 Compile_Time_Compare (LHi, H, Assume_Valid => True) = GT
3488 then
3489 Bad_Bound := LHi;
3490 end if;
3491
3492 if Present (Bad_Bound) then
3493 Error_Msg_N
3494 ("suspicious loop bound out of range of "
3495 & "loop subtype??", Bad_Bound);
3496 Error_Msg_N
3497 ("\loop executes zero times or raises "
3498 & "Constraint_Error??", Bad_Bound);
3499 end if;
3500
3501 if Compile_Time_Compare (LLo, LHi, Assume_Valid => False)
3502 = GT
3503 then
3504 Error_Msg_N ("??constrained range is null",
3505 Constraint (DS));
3506
3507 -- Additional constraints on modular types can be
3508 -- confusing, add more information.
3509
3510 if Ekind (Etype (DS)) = E_Modular_Integer_Subtype then
3511 Error_Msg_Uint_1 := Intval (LLo);
3512 Error_Msg_Uint_2 := Intval (LHi);
3513 Error_Msg_NE ("\iterator has modular type &, " &
3514 "so the loop has bounds ^ ..^",
3515 Constraint (DS),
3516 Subtype_Mark (DS));
3517 end if;
3518
3519 if Nkind (Loop_Nod) = N_Loop_Statement then
3520 Set_Is_Null_Loop (Loop_Nod);
3521
3522 -- Suppress other warnings about the body of the loop,
3523 -- as it will never execute.
3524 Set_Suppress_Loop_Warnings (Loop_Nod);
3525 end if;
3526 end if;
3527 end;
3528 end if;
3529
3530 -- This declare block is about warnings, if we get an exception while
3531 -- testing for warnings, we simply abandon the attempt silently. This
3532 -- most likely occurs as the result of a previous error, but might
3533 -- just be an obscure case we have missed. In either case, not giving
3534 -- the warning is perfectly acceptable.
3535
3536 exception
3537 when others =>
3538 -- With debug flag K we will get an exception unless an error
3539 -- has already occurred (useful for debugging).
3540
3541 if Debug_Flag_K then
3542 Check_Error_Detected;
3543 end if;
3544 end;
3545 end if;
3546
3547 -- Preanalyze the filter. Expansion will take place when enclosing
3548 -- loop is expanded.
3549
3550 if Present (Iterator_Filter (N)) then
3551 Preanalyze_And_Resolve (Iterator_Filter (N), Standard_Boolean);
3552 end if;
3553 end Analyze_Loop_Parameter_Specification;
3554
3555 ----------------------------
3556 -- Analyze_Loop_Statement --
3557 ----------------------------
3558
3559 procedure Analyze_Loop_Statement (N : Node_Id) is
3560
3561 -- The following exception is raised by routine Prepare_Loop_Statement
3562 -- to avoid further analysis of a transformed loop.
3563
3564 procedure Prepare_Loop_Statement
3565 (Iter : Node_Id;
3566 Stop_Processing : out Boolean);
3567 -- Determine whether loop statement N with iteration scheme Iter must be
3568 -- transformed prior to analysis, and if so, perform it.
3569 -- If Stop_Processing is set to True, should stop further processing.
3570
3571 ----------------------------
3572 -- Prepare_Loop_Statement --
3573 ----------------------------
3574
3575 procedure Prepare_Loop_Statement
3576 (Iter : Node_Id;
3577 Stop_Processing : out Boolean)
3578 is
3579 function Has_Sec_Stack_Default_Iterator
3580 (Cont_Typ : Entity_Id) return Boolean;
3581 pragma Inline (Has_Sec_Stack_Default_Iterator);
3582 -- Determine whether container type Cont_Typ has a default iterator
3583 -- that requires secondary stack management.
3584
3585 function Is_Sec_Stack_Iteration_Primitive
3586 (Cont_Typ : Entity_Id;
3587 Iter_Prim_Nam : Name_Id) return Boolean;
3588 pragma Inline (Is_Sec_Stack_Iteration_Primitive);
3589 -- Determine whether container type Cont_Typ has an iteration routine
3590 -- described by its name Iter_Prim_Nam that requires secondary stack
3591 -- management.
3592
3593 function Is_Wrapped_In_Block (Stmt : Node_Id) return Boolean;
3594 pragma Inline (Is_Wrapped_In_Block);
3595 -- Determine whether arbitrary statement Stmt is the sole statement
3596 -- wrapped within some block, excluding pragmas.
3597
3598 procedure Prepare_Iterator_Loop
3599 (Iter_Spec : Node_Id;
3600 Stop_Processing : out Boolean);
3601 pragma Inline (Prepare_Iterator_Loop);
3602 -- Prepare an iterator loop with iteration specification Iter_Spec
3603 -- for transformation if needed.
3604 -- If Stop_Processing is set to True, should stop further processing.
3605
3606 procedure Prepare_Param_Spec_Loop
3607 (Param_Spec : Node_Id;
3608 Stop_Processing : out Boolean);
3609 pragma Inline (Prepare_Param_Spec_Loop);
3610 -- Prepare a discrete loop with parameter specification Param_Spec
3611 -- for transformation if needed.
3612 -- If Stop_Processing is set to True, should stop further processing.
3613
3614 procedure Wrap_Loop_Statement (Manage_Sec_Stack : Boolean);
3615 pragma Inline (Wrap_Loop_Statement);
3616 -- Wrap loop statement N within a block. Flag Manage_Sec_Stack must
3617 -- be set when the block must mark and release the secondary stack.
3618 -- Should stop further processing after calling this procedure.
3619
3620 ------------------------------------
3621 -- Has_Sec_Stack_Default_Iterator --
3622 ------------------------------------
3623
3624 function Has_Sec_Stack_Default_Iterator
3625 (Cont_Typ : Entity_Id) return Boolean
3626 is
3627 Def_Iter : constant Node_Id :=
3628 Find_Value_Of_Aspect
3629 (Cont_Typ, Aspect_Default_Iterator);
3630 begin
3631 return
3632 Present (Def_Iter)
3633 and then Present (Etype (Def_Iter))
3634 and then Requires_Transient_Scope (Etype (Def_Iter));
3635 end Has_Sec_Stack_Default_Iterator;
3636
3637 --------------------------------------
3638 -- Is_Sec_Stack_Iteration_Primitive --
3639 --------------------------------------
3640
3641 function Is_Sec_Stack_Iteration_Primitive
3642 (Cont_Typ : Entity_Id;
3643 Iter_Prim_Nam : Name_Id) return Boolean
3644 is
3645 Iter_Prim : constant Entity_Id :=
3646 Get_Iterable_Type_Primitive
3647 (Cont_Typ, Iter_Prim_Nam);
3648 begin
3649 return
3650 Present (Iter_Prim)
3651 and then Requires_Transient_Scope (Etype (Iter_Prim));
3652 end Is_Sec_Stack_Iteration_Primitive;
3653
3654 -------------------------
3655 -- Is_Wrapped_In_Block --
3656 -------------------------
3657
3658 function Is_Wrapped_In_Block (Stmt : Node_Id) return Boolean is
3659 Blk_HSS : Node_Id;
3660 Blk_Id : Entity_Id;
3661 Blk_Stmt : Node_Id;
3662
3663 begin
3664 Blk_Id := Current_Scope;
3665
3666 -- The current context is a block. Inspect the statements of the
3667 -- block to determine whether it wraps Stmt.
3668
3669 if Ekind (Blk_Id) = E_Block
3670 and then Present (Block_Node (Blk_Id))
3671 then
3672 Blk_HSS :=
3673 Handled_Statement_Sequence (Parent (Block_Node (Blk_Id)));
3674
3675 -- Skip leading pragmas introduced for invariant and predicate
3676 -- checks.
3677
3678 Blk_Stmt := First (Statements (Blk_HSS));
3679 while Present (Blk_Stmt)
3680 and then Nkind (Blk_Stmt) = N_Pragma
3681 loop
3682 Next (Blk_Stmt);
3683 end loop;
3684
3685 return Blk_Stmt = Stmt and then No (Next (Blk_Stmt));
3686 end if;
3687
3688 return False;
3689 end Is_Wrapped_In_Block;
3690
3691 ---------------------------
3692 -- Prepare_Iterator_Loop --
3693 ---------------------------
3694
3695 procedure Prepare_Iterator_Loop
3696 (Iter_Spec : Node_Id;
3697 Stop_Processing : out Boolean)
3698 is
3699 Cont_Typ : Entity_Id;
3700 Nam : Node_Id;
3701 Nam_Copy : Node_Id;
3702
3703 begin
3704 Stop_Processing := False;
3705
3706 -- The iterator specification has syntactic errors. Transform the
3707 -- loop into an infinite loop in order to safely perform at least
3708 -- some minor analysis. This check must come first.
3709
3710 if Error_Posted (Iter_Spec) then
3711 Set_Iteration_Scheme (N, Empty);
3712 Analyze (N);
3713 Stop_Processing := True;
3714
3715 -- Nothing to do when the loop is already wrapped in a block
3716
3717 elsif Is_Wrapped_In_Block (N) then
3718 null;
3719
3720 -- Otherwise the iterator loop traverses an array or a container
3721 -- and appears in the form
3722 --
3723 -- for Def_Id in [reverse] Iterator_Name loop
3724 -- for Def_Id [: Subtyp_Indic] of [reverse] Iterable_Name loop
3725
3726 else
3727 -- Prepare a copy of the iterated name for preanalysis. The
3728 -- copy is semi inserted into the tree by setting its Parent
3729 -- pointer.
3730
3731 Nam := Name (Iter_Spec);
3732 Nam_Copy := New_Copy_Tree (Nam);
3733 Set_Parent (Nam_Copy, Parent (Nam));
3734
3735 -- Determine what the loop is iterating on
3736
3737 Preanalyze_Range (Nam_Copy);
3738 Cont_Typ := Etype (Nam_Copy);
3739
3740 -- The iterator loop is traversing an array. This case does not
3741 -- require any transformation, unless the name contains a call
3742 -- that returns on the secondary stack since we need to release
3743 -- the space allocated there.
3744
3745 if Is_Array_Type (Cont_Typ)
3746 and then not Has_Sec_Stack_Call (Nam_Copy)
3747 then
3748 null;
3749
3750 -- Otherwise unconditionally wrap the loop statement within
3751 -- a block. The expansion of iterator loops may relocate the
3752 -- iterator outside the loop, thus "leaking" its entity into
3753 -- the enclosing scope. Wrapping the loop statement allows
3754 -- for multiple iterator loops using the same iterator name
3755 -- to coexist within the same scope.
3756 --
3757 -- The block must manage the secondary stack when the iterator
3758 -- loop is traversing a container using either
3759 --
3760 -- * A default iterator obtained on the secondary stack
3761 --
3762 -- * Call to Iterate where the iterator is returned on the
3763 -- secondary stack.
3764 --
3765 -- * Combination of First, Next, and Has_Element where the
3766 -- first two return a cursor on the secondary stack.
3767
3768 else
3769 Wrap_Loop_Statement
3770 (Manage_Sec_Stack =>
3771 Has_Sec_Stack_Default_Iterator (Cont_Typ)
3772 or else Has_Sec_Stack_Call (Nam_Copy)
3773 or else Is_Sec_Stack_Iteration_Primitive
3774 (Cont_Typ, Name_First)
3775 or else Is_Sec_Stack_Iteration_Primitive
3776 (Cont_Typ, Name_Next));
3777 Stop_Processing := True;
3778 end if;
3779 end if;
3780 end Prepare_Iterator_Loop;
3781
3782 -----------------------------
3783 -- Prepare_Param_Spec_Loop --
3784 -----------------------------
3785
3786 procedure Prepare_Param_Spec_Loop
3787 (Param_Spec : Node_Id;
3788 Stop_Processing : out Boolean)
3789 is
3790 High : Node_Id;
3791 Low : Node_Id;
3792 Rng : Node_Id;
3793 Rng_Copy : Node_Id;
3794 Rng_Typ : Entity_Id;
3795
3796 begin
3797 Stop_Processing := False;
3798 Rng := Discrete_Subtype_Definition (Param_Spec);
3799
3800 -- Nothing to do when the loop is already wrapped in a block
3801
3802 if Is_Wrapped_In_Block (N) then
3803 null;
3804
3805 -- The parameter specification appears in the form
3806 --
3807 -- for Def_Id in Subtype_Mark Constraint loop
3808
3809 elsif Nkind (Rng) = N_Subtype_Indication
3810 and then Nkind (Range_Expression (Constraint (Rng))) = N_Range
3811 then
3812 Rng := Range_Expression (Constraint (Rng));
3813
3814 -- Preanalyze the bounds of the range constraint, setting
3815 -- parent fields to associate the copied bounds with the range,
3816 -- allowing proper tree climbing during preanalysis.
3817
3818 Low := New_Copy_Tree (Low_Bound (Rng));
3819 High := New_Copy_Tree (High_Bound (Rng));
3820
3821 Set_Parent (Low, Rng);
3822 Set_Parent (High, Rng);
3823
3824 Preanalyze (Low);
3825 Preanalyze (High);
3826
3827 -- The bounds contain at least one function call that returns
3828 -- on the secondary stack. Note that the loop must be wrapped
3829 -- only when such a call exists.
3830
3831 if Has_Sec_Stack_Call (Low) or else Has_Sec_Stack_Call (High)
3832 then
3833 Wrap_Loop_Statement (Manage_Sec_Stack => True);
3834 Stop_Processing := True;
3835 end if;
3836
3837 -- Otherwise the parameter specification appears in the form
3838 --
3839 -- for Def_Id in Range loop
3840
3841 else
3842 -- Prepare a copy of the discrete range for preanalysis. The
3843 -- copy is semi inserted into the tree by setting its Parent
3844 -- pointer.
3845
3846 Rng_Copy := New_Copy_Tree (Rng);
3847 Set_Parent (Rng_Copy, Parent (Rng));
3848
3849 -- Determine what the loop is iterating on
3850
3851 Preanalyze_Range (Rng_Copy);
3852 Rng_Typ := Etype (Rng_Copy);
3853
3854 -- Wrap the loop statement within a block in order to manage
3855 -- the secondary stack when the discrete range:
3856 --
3857 -- * is either a Forward_Iterator or a Reverse_Iterator
3858 -- or
3859 --
3860 -- * contains a function call that returns on the secondary
3861 -- stack.
3862
3863 if Is_Iterator (Rng_Typ)
3864 or else Has_Sec_Stack_Call (Rng_Copy)
3865 then
3866 Wrap_Loop_Statement (Manage_Sec_Stack => True);
3867 Stop_Processing := True;
3868 end if;
3869 end if;
3870 end Prepare_Param_Spec_Loop;
3871
3872 -------------------------
3873 -- Wrap_Loop_Statement --
3874 -------------------------
3875
3876 procedure Wrap_Loop_Statement (Manage_Sec_Stack : Boolean) is
3877 Loc : constant Source_Ptr := Sloc (N);
3878
3879 Blk : Node_Id;
3880 Blk_Id : Entity_Id;
3881 Loop_Id : constant Entity_Id := Entity (Identifier (N));
3882
3883 begin
3884 Blk :=
3885 Make_Block_Statement (Loc,
3886 Declarations => New_List,
3887 Handled_Statement_Sequence =>
3888 Make_Handled_Sequence_Of_Statements (Loc,
3889 Statements => New_List (Relocate_Node (N))));
3890
3891 Add_Block_Identifier (Blk, Blk_Id);
3892 Set_Uses_Sec_Stack (Blk_Id, Manage_Sec_Stack);
3893
3894 Rewrite (N, Blk);
3895 Analyze (N);
3896
3897 -- Transfer the loop entity from its old scope to the new block
3898 -- scope.
3899
3900 Remove_Entity (Loop_Id);
3901 Append_Entity (Loop_Id, Blk_Id);
3902 end Wrap_Loop_Statement;
3903
3904 -- Local variables
3905
3906 Iter_Spec : constant Node_Id := Iterator_Specification (Iter);
3907 Param_Spec : constant Node_Id := Loop_Parameter_Specification (Iter);
3908
3909 -- Start of processing for Prepare_Loop_Statement
3910
3911 begin
3912 Stop_Processing := False;
3913
3914 if Present (Iter_Spec) then
3915 Prepare_Iterator_Loop (Iter_Spec, Stop_Processing);
3916
3917 elsif Present (Param_Spec) then
3918 Prepare_Param_Spec_Loop (Param_Spec, Stop_Processing);
3919 end if;
3920 end Prepare_Loop_Statement;
3921
3922 -- Local declarations
3923
3924 Id : constant Node_Id := Identifier (N);
3925 Iter : constant Node_Id := Iteration_Scheme (N);
3926 Loc : constant Source_Ptr := Sloc (N);
3927 Ent : Entity_Id;
3928 Stmt : Node_Id;
3929
3930 -- Start of processing for Analyze_Loop_Statement
3931
3932 begin
3933 if Present (Id) then
3934
3935 -- Make name visible, e.g. for use in exit statements. Loop labels
3936 -- are always considered to be referenced.
3937
3938 Analyze (Id);
3939 Ent := Entity (Id);
3940
3941 -- Guard against serious error (typically, a scope mismatch when
3942 -- semantic analysis is requested) by creating loop entity to
3943 -- continue analysis.
3944
3945 if No (Ent) then
3946 if Total_Errors_Detected /= 0 then
3947 Ent := New_Internal_Entity (E_Loop, Current_Scope, Loc, 'L');
3948 else
3949 raise Program_Error;
3950 end if;
3951
3952 -- Verify that the loop name is hot hidden by an unrelated
3953 -- declaration in an inner scope.
3954
3955 elsif Ekind (Ent) /= E_Label and then Ekind (Ent) /= E_Loop then
3956 Error_Msg_Sloc := Sloc (Ent);
3957 Error_Msg_N ("implicit label declaration for & is hidden#", Id);
3958
3959 if Present (Homonym (Ent))
3960 and then Ekind (Homonym (Ent)) = E_Label
3961 then
3962 Set_Entity (Id, Ent);
3963 Mutate_Ekind (Ent, E_Loop);
3964 end if;
3965
3966 else
3967 Generate_Reference (Ent, N, ' ');
3968 Generate_Definition (Ent);
3969
3970 -- If we found a label, mark its type. If not, ignore it, since it
3971 -- means we have a conflicting declaration, which would already
3972 -- have been diagnosed at declaration time. Set Label_Construct
3973 -- of the implicit label declaration, which is not created by the
3974 -- parser for generic units.
3975
3976 if Ekind (Ent) = E_Label then
3977 Reinit_Field_To_Zero (Ent, F_Enclosing_Scope);
3978 Reinit_Field_To_Zero (Ent, F_Reachable);
3979 Mutate_Ekind (Ent, E_Loop);
3980
3981 if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
3982 Set_Label_Construct (Parent (Ent), N);
3983 end if;
3984 end if;
3985 end if;
3986
3987 -- Case of no identifier present. Create one and attach it to the
3988 -- loop statement for use as a scope and as a reference for later
3989 -- expansions. Indicate that the label does not come from source,
3990 -- and attach it to the loop statement so it is part of the tree,
3991 -- even without a full declaration.
3992
3993 else
3994 Ent := New_Internal_Entity (E_Loop, Current_Scope, Loc, 'L');
3995 Set_Etype (Ent, Standard_Void_Type);
3996 Set_Identifier (N, New_Occurrence_Of (Ent, Loc));
3997 Set_Parent (Ent, N);
3998 Set_Has_Created_Identifier (N);
3999 end if;
4000
4001 -- Determine whether the loop statement must be transformed prior to
4002 -- analysis, and if so, perform it. This early modification is needed
4003 -- when:
4004 --
4005 -- * The loop has an erroneous iteration scheme. In this case the
4006 -- loop is converted into an infinite loop in order to perform
4007 -- minor analysis.
4008 --
4009 -- * The loop is an Ada 2012 iterator loop. In this case the loop is
4010 -- wrapped within a block to provide a local scope for the iterator.
4011 -- If the iterator specification requires the secondary stack in any
4012 -- way, the block is marked in order to manage it.
4013 --
4014 -- * The loop is using a parameter specification where the discrete
4015 -- range requires the secondary stack. In this case the loop is
4016 -- wrapped within a block in order to manage the secondary stack.
4017
4018 -- ??? This overlooks finalization: the loop may leave the secondary
4019 -- stack untouched, but its iterator or discrete range may need
4020 -- finalization, in which case the block is also required. Therefore
4021 -- the criterion must be based on Sem_Util.Requires_Transient_Scope,
4022 -- which happens to be what is currently implemented.
4023
4024 if Present (Iter) then
4025 declare
4026 Stop_Processing : Boolean;
4027 begin
4028 Prepare_Loop_Statement (Iter, Stop_Processing);
4029
4030 if Stop_Processing then
4031 return;
4032 end if;
4033 end;
4034 end if;
4035
4036 -- Kill current values on entry to loop, since statements in the body of
4037 -- the loop may have been executed before the loop is entered. Similarly
4038 -- we kill values after the loop, since we do not know that the body of
4039 -- the loop was executed.
4040
4041 Kill_Current_Values;
4042 Push_Scope (Ent);
4043 Analyze_Iteration_Scheme (Iter);
4044
4045 -- Check for following case which merits a warning if the type of E is
4046 -- a multi-dimensional array (and no explicit subscript ranges present).
4047
4048 -- for J in E'Range
4049 -- for K in E'Range
4050
4051 if Present (Iter)
4052 and then Present (Loop_Parameter_Specification (Iter))
4053 then
4054 declare
4055 LPS : constant Node_Id := Loop_Parameter_Specification (Iter);
4056 DSD : constant Node_Id :=
4057 Original_Node (Discrete_Subtype_Definition (LPS));
4058 begin
4059 if Nkind (DSD) = N_Attribute_Reference
4060 and then Attribute_Name (DSD) = Name_Range
4061 and then No (Expressions (DSD))
4062 then
4063 declare
4064 Typ : constant Entity_Id := Etype (Prefix (DSD));
4065 begin
4066 if Is_Array_Type (Typ)
4067 and then Number_Dimensions (Typ) > 1
4068 and then Nkind (Parent (N)) = N_Loop_Statement
4069 and then Present (Iteration_Scheme (Parent (N)))
4070 -- The next conjunct tests that the enclosing loop is
4071 -- a for loop and not a while loop.
4072 and then Present (Loop_Parameter_Specification
4073 (Iteration_Scheme (Parent (N))))
4074 then
4075 declare
4076 OIter : constant Node_Id :=
4077 Iteration_Scheme (Parent (N));
4078 OLPS : constant Node_Id :=
4079 Loop_Parameter_Specification (OIter);
4080 ODSD : constant Node_Id :=
4081 Original_Node (Discrete_Subtype_Definition (OLPS));
4082 begin
4083 if Nkind (ODSD) = N_Attribute_Reference
4084 and then Attribute_Name (ODSD) = Name_Range
4085 and then No (Expressions (ODSD))
4086 and then Etype (Prefix (ODSD)) = Typ
4087 then
4088 Error_Msg_Sloc := Sloc (ODSD);
4089 Error_Msg_N
4090 ("inner range same as outer range#??", DSD);
4091 end if;
4092 end;
4093 end if;
4094 end;
4095 end if;
4096 end;
4097 end if;
4098
4099 -- Analyze the statements of the body except in the case of an Ada 2012
4100 -- iterator with the expander active. In this case the expander will do
4101 -- a rewrite of the loop into a while loop. We will then analyze the
4102 -- loop body when we analyze this while loop.
4103
4104 -- We need to do this delay because if the container is for indefinite
4105 -- types the actual subtype of the components will only be determined
4106 -- when the cursor declaration is analyzed.
4107
4108 -- If the expander is not active then we want to analyze the loop body
4109 -- now even in the Ada 2012 iterator case, since the rewriting will not
4110 -- be done. Insert the loop variable in the current scope, if not done
4111 -- when analysing the iteration scheme. Set its kind properly to detect
4112 -- improper uses in the loop body.
4113
4114 -- In GNATprove mode, we do one of the above depending on the kind of
4115 -- loop. If it is an iterator over an array, then we do not analyze the
4116 -- loop now. We will analyze it after it has been rewritten by the
4117 -- special SPARK expansion which is activated in GNATprove mode. We need
4118 -- to do this so that other expansions that should occur in GNATprove
4119 -- mode take into account the specificities of the rewritten loop, in
4120 -- particular the introduction of a renaming (which needs to be
4121 -- expanded).
4122
4123 -- In other cases in GNATprove mode then we want to analyze the loop
4124 -- body now, since no rewriting will occur. Within a generic the
4125 -- GNATprove mode is irrelevant, we must analyze the generic for
4126 -- non-local name capture.
4127
4128 if Present (Iter)
4129 and then Present (Iterator_Specification (Iter))
4130 then
4131 if GNATprove_Mode
4132 and then Is_Iterator_Over_Array (Iterator_Specification (Iter))
4133 and then not Inside_A_Generic
4134 then
4135 null;
4136
4137 elsif not Expander_Active then
4138 declare
4139 I_Spec : constant Node_Id := Iterator_Specification (Iter);
4140 Id : constant Entity_Id := Defining_Identifier (I_Spec);
4141
4142 begin
4143 if Scope (Id) /= Current_Scope then
4144 Enter_Name (Id);
4145 end if;
4146
4147 -- In an element iterator, the loop parameter is a variable if
4148 -- the domain of iteration (container or array) is a variable.
4149
4150 if not Of_Present (I_Spec)
4151 or else not Is_Variable (Name (I_Spec))
4152 then
4153 Mutate_Ekind (Id, E_Loop_Parameter);
4154 end if;
4155 end;
4156
4157 Analyze_Statements (Statements (N));
4158 end if;
4159
4160 else
4161 -- Pre-Ada2012 for-loops and while loops
4162
4163 Analyze_Statements (Statements (N));
4164 end if;
4165
4166 -- If the loop has no side effects, mark it for removal.
4167
4168 if Side_Effect_Free_Loop (N) then
4169 Set_Is_Null_Loop (N);
4170 end if;
4171
4172 -- When the iteration scheme of a loop contains attribute 'Loop_Entry,
4173 -- the loop is transformed into a conditional block. Retrieve the loop.
4174
4175 Stmt := N;
4176
4177 if Subject_To_Loop_Entry_Attributes (Stmt) then
4178 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4179 end if;
4180
4181 -- Finish up processing for the loop. We kill all current values, since
4182 -- in general we don't know if the statements in the loop have been
4183 -- executed. We could do a bit better than this with a loop that we
4184 -- know will execute at least once, but it's not worth the trouble and
4185 -- the front end is not in the business of flow tracing.
4186
4187 Process_End_Label (Stmt, 'e', Ent);
4188 End_Scope;
4189 Kill_Current_Values;
4190
4191 -- Check for infinite loop. Skip check for generated code, since it
4192 -- justs waste time and makes debugging the routine called harder.
4193
4194 -- Note that we have to wait till the body of the loop is fully analyzed
4195 -- before making this call, since Check_Infinite_Loop_Warning relies on
4196 -- being able to use semantic visibility information to find references.
4197
4198 if Comes_From_Source (Stmt) then
4199 Check_Infinite_Loop_Warning (Stmt);
4200 end if;
4201
4202 -- Code after loop is unreachable if the loop has no WHILE or FOR and
4203 -- contains no EXIT statements within the body of the loop.
4204
4205 if No (Iter) and then not Has_Exit (Ent) then
4206 Check_Unreachable_Code (Stmt);
4207 end if;
4208 end Analyze_Loop_Statement;
4209
4210 ----------------------------
4211 -- Analyze_Null_Statement --
4212 ----------------------------
4213
4214 -- Note: the semantics of the null statement is implemented by a single
4215 -- null statement, too bad everything isn't as simple as this.
4216
4217 procedure Analyze_Null_Statement (N : Node_Id) is
4218 pragma Warnings (Off, N);
4219 begin
4220 null;
4221 end Analyze_Null_Statement;
4222
4223 -------------------------
4224 -- Analyze_Target_Name --
4225 -------------------------
4226
4227 procedure Analyze_Target_Name (N : Node_Id) is
4228 procedure Report_Error;
4229 -- Complain about illegal use of target_name and rewrite it into unknown
4230 -- identifier.
4231
4232 ------------------
4233 -- Report_Error --
4234 ------------------
4235
4236 procedure Report_Error is
4237 begin
4238 Error_Msg_N
4239 ("must appear in the right-hand side of an assignment statement",
4240 N);
4241 Rewrite (N, New_Occurrence_Of (Any_Id, Sloc (N)));
4242 end Report_Error;
4243
4244 -- Start of processing for Analyze_Target_Name
4245
4246 begin
4247 -- A target name has the type of the left-hand side of the enclosing
4248 -- assignment.
4249
4250 -- First, verify that the context is the right-hand side of an
4251 -- assignment statement.
4252
4253 if No (Current_Assignment) then
4254 Report_Error;
4255 return;
4256 end if;
4257
4258 declare
4259 Current : Node_Id := N;
4260 Context : Node_Id := Parent (N);
4261 begin
4262 while Present (Context) loop
4263
4264 -- Check if target_name appears in the expression of the enclosing
4265 -- assignment.
4266
4267 if Nkind (Context) = N_Assignment_Statement then
4268 if Current = Expression (Context) then
4269 pragma Assert (Context = Current_Assignment);
4270 Set_Etype (N, Etype (Name (Current_Assignment)));
4271 Analyze_Dimension (N);
4272 else
4273 Report_Error;
4274 end if;
4275 return;
4276
4277 -- Prevent the search from going too far
4278
4279 elsif Is_Body_Or_Package_Declaration (Context) then
4280 Report_Error;
4281 return;
4282 end if;
4283
4284 Current := Context;
4285 Context := Parent (Context);
4286 end loop;
4287
4288 Report_Error;
4289 end;
4290 end Analyze_Target_Name;
4291
4292 ------------------------
4293 -- Analyze_Statements --
4294 ------------------------
4295
4296 procedure Analyze_Statements (L : List_Id) is
4297 Lab : Entity_Id;
4298 S : Node_Id;
4299
4300 begin
4301 -- The labels declared in the statement list are reachable from
4302 -- statements in the list. We do this as a prepass so that any goto
4303 -- statement will be properly flagged if its target is not reachable.
4304 -- This is not required, but is nice behavior.
4305
4306 S := First (L);
4307 while Present (S) loop
4308 if Nkind (S) = N_Label then
4309 Analyze (Identifier (S));
4310 Lab := Entity (Identifier (S));
4311
4312 -- If we found a label mark it as reachable
4313
4314 if Ekind (Lab) = E_Label then
4315 Generate_Definition (Lab);
4316 Set_Reachable (Lab);
4317
4318 if Nkind (Parent (Lab)) = N_Implicit_Label_Declaration then
4319 Set_Label_Construct (Parent (Lab), S);
4320 end if;
4321
4322 -- If we failed to find a label, it means the implicit declaration
4323 -- of the label was hidden. A for-loop parameter can do this to
4324 -- a label with the same name inside the loop, since the implicit
4325 -- label declaration is in the innermost enclosing body or block
4326 -- statement.
4327
4328 else
4329 Error_Msg_Sloc := Sloc (Lab);
4330 Error_Msg_N
4331 ("implicit label declaration for & is hidden#",
4332 Identifier (S));
4333 end if;
4334 else
4335 Inspect_Deferred_Constant_Completion (S);
4336 end if;
4337
4338 Next (S);
4339 end loop;
4340
4341 -- Perform semantic analysis on all statements
4342
4343 Conditional_Statements_Begin;
4344
4345 S := First (L);
4346 while Present (S) loop
4347 Analyze (S);
4348
4349 -- Remove dimension in all statements
4350
4351 Remove_Dimension_In_Statement (S);
4352 Next (S);
4353 end loop;
4354
4355 Conditional_Statements_End;
4356
4357 -- Make labels unreachable. Visibility is not sufficient, because labels
4358 -- in one if-branch for example are not reachable from the other branch,
4359 -- even though their declarations are in the enclosing declarative part.
4360
4361 S := First (L);
4362 while Present (S) loop
4363 if Nkind (S) = N_Label
4364 and then Ekind (Entity (Identifier (S))) = E_Label
4365 then
4366 Set_Reachable (Entity (Identifier (S)), False);
4367 end if;
4368
4369 Next (S);
4370 end loop;
4371 end Analyze_Statements;
4372
4373 ----------------------------
4374 -- Check_Unreachable_Code --
4375 ----------------------------
4376
4377 procedure Check_Unreachable_Code (N : Node_Id) is
4378
4379 function Is_Simple_Case (N : Node_Id) return Boolean;
4380 -- N is the condition of an if statement. True if N is simple enough
4381 -- that we should not set Unblocked_Exit_Count in the special case
4382 -- below.
4383
4384 --------------------
4385 -- Is_Simple_Case --
4386 --------------------
4387
4388 function Is_Simple_Case (N : Node_Id) return Boolean is
4389 begin
4390 return
4391 Is_Trivial_Boolean (N)
4392 or else
4393 (Comes_From_Source (N)
4394 and then Is_Static_Expression (N)
4395 and then Nkind (N) in N_Identifier | N_Expanded_Name
4396 and then Ekind (Entity (N)) = E_Constant)
4397 or else
4398 (not In_Instance
4399 and then Nkind (Original_Node (N)) = N_Op_Not
4400 and then Is_Simple_Case (Right_Opnd (Original_Node (N))));
4401 end Is_Simple_Case;
4402
4403 Error_Node : Node_Id;
4404 Nxt : Node_Id;
4405 P : Node_Id;
4406
4407 begin
4408 if Comes_From_Source (N) then
4409 Nxt := Original_Node (Next (N));
4410
4411 -- Skip past pragmas
4412
4413 while Nkind (Nxt) = N_Pragma loop
4414 Nxt := Original_Node (Next (Nxt));
4415 end loop;
4416
4417 -- If a label follows us, then we never have dead code, since someone
4418 -- could branch to the label, so we just ignore it.
4419
4420 if Nkind (Nxt) = N_Label then
4421 return;
4422
4423 -- Otherwise see if we have a real statement following us
4424
4425 elsif Comes_From_Source (Nxt)
4426 and then Is_Statement (Nxt)
4427 then
4428 -- Special very annoying exception. Ada RM 6.5(5) annoyingly
4429 -- requires functions to have at least one return statement, so
4430 -- don't complain about a simple return that follows a raise or a
4431 -- call to procedure with No_Return.
4432
4433 if not (Present (Current_Subprogram)
4434 and then Ekind (Current_Subprogram) = E_Function
4435 and then (Nkind (N) in N_Raise_Statement
4436 or else
4437 (Nkind (N) = N_Procedure_Call_Statement
4438 and then Is_Entity_Name (Name (N))
4439 and then Present (Entity (Name (N)))
4440 and then No_Return (Entity (Name (N)))))
4441 and then Nkind (Nxt) = N_Simple_Return_Statement)
4442 then
4443 -- The rather strange shenanigans with the warning message
4444 -- here reflects the fact that Kill_Dead_Code is very good at
4445 -- removing warnings in deleted code, and this is one warning
4446 -- we would prefer NOT to have removed.
4447
4448 Error_Node := Nxt;
4449
4450 -- If we have unreachable code, analyze and remove the
4451 -- unreachable code, since it is useless and we don't want
4452 -- to generate junk warnings.
4453
4454 -- We skip this step if we are not in code generation mode.
4455
4456 -- This is the one case where we remove dead code in the
4457 -- semantics as opposed to the expander, and we do not want
4458 -- to remove code if we are not in code generation mode, since
4459 -- this messes up the tree or loses useful information for
4460 -- analysis tools such as CodePeer.
4461
4462 -- Note that one might react by moving the whole circuit to
4463 -- exp_ch5, but then we lose the warning in -gnatc mode.
4464
4465 if Operating_Mode = Generate_Code then
4466 loop
4467 declare
4468 Del : constant Node_Id := Next (N);
4469 -- Node to be possibly deleted
4470 begin
4471 -- Quit deleting when we have nothing more to delete
4472 -- or if we hit a label (since someone could transfer
4473 -- control to a label, so we should not delete it).
4474
4475 exit when No (Del) or else Nkind (Del) = N_Label;
4476
4477 -- Statement/declaration is to be deleted
4478
4479 Analyze (Del);
4480 Kill_Dead_Code (Del);
4481 Remove (Del);
4482 end;
4483 end loop;
4484
4485 -- If this is a function, we add "raise Program_Error;",
4486 -- because otherwise, we will get incorrect warnings about
4487 -- falling off the end of the function.
4488
4489 declare
4490 Subp : constant Entity_Id := Current_Subprogram;
4491 begin
4492 if Present (Subp) and then Ekind (Subp) = E_Function then
4493 Insert_After_And_Analyze (N,
4494 Make_Raise_Program_Error (Sloc (Error_Node),
4495 Reason => PE_Missing_Return));
4496 end if;
4497 end;
4498
4499 end if;
4500
4501 -- Suppress the warning in instances, because a statement can
4502 -- be unreachable in some instances but not others.
4503
4504 if not In_Instance then
4505 Error_Msg_N ("??unreachable code!", Error_Node);
4506 end if;
4507 end if;
4508
4509 -- If the unconditional transfer of control instruction is the
4510 -- last statement of a sequence, then see if our parent is one of
4511 -- the constructs for which we count unblocked exits, and if so,
4512 -- adjust the count.
4513
4514 else
4515 P := Parent (N);
4516
4517 -- Statements in THEN part or ELSE part of IF statement
4518
4519 if Nkind (P) = N_If_Statement then
4520 null;
4521
4522 -- Statements in ELSIF part of an IF statement
4523
4524 elsif Nkind (P) = N_Elsif_Part then
4525 P := Parent (P);
4526 pragma Assert (Nkind (P) = N_If_Statement);
4527
4528 -- Statements in CASE statement alternative
4529
4530 elsif Nkind (P) = N_Case_Statement_Alternative then
4531 P := Parent (P);
4532 pragma Assert (Nkind (P) = N_Case_Statement);
4533
4534 -- Statements in body of block
4535
4536 elsif Nkind (P) = N_Handled_Sequence_Of_Statements
4537 and then Nkind (Parent (P)) = N_Block_Statement
4538 then
4539 -- The original loop is now placed inside a block statement
4540 -- due to the expansion of attribute 'Loop_Entry. Return as
4541 -- this is not a "real" block for the purposes of exit
4542 -- counting.
4543
4544 if Nkind (N) = N_Loop_Statement
4545 and then Subject_To_Loop_Entry_Attributes (N)
4546 then
4547 return;
4548 end if;
4549
4550 -- Statements in exception handler in a block
4551
4552 elsif Nkind (P) = N_Exception_Handler
4553 and then Nkind (Parent (P)) = N_Handled_Sequence_Of_Statements
4554 and then Nkind (Parent (Parent (P))) = N_Block_Statement
4555 then
4556 null;
4557
4558 -- None of these cases, so return
4559
4560 else
4561 return;
4562 end if;
4563
4564 -- This was one of the cases we are looking for (i.e. the parent
4565 -- construct was IF, CASE or block). In most cases, we simply
4566 -- decrement the count. However, if the parent is something like:
4567 --
4568 -- if cond then
4569 -- raise ...; -- or some other jump
4570 -- end if;
4571 --
4572 -- where cond is an expression that is known-true at compile time,
4573 -- we can treat that as just the jump -- i.e. anything following
4574 -- the if statement is unreachable. We don't do this for simple
4575 -- cases like "if True" or "if Debug_Flag", because that causes
4576 -- too many warnings.
4577
4578 if Nkind (P) = N_If_Statement
4579 and then Present (Then_Statements (P))
4580 and then No (Elsif_Parts (P))
4581 and then No (Else_Statements (P))
4582 and then Is_OK_Static_Expression (Condition (P))
4583 and then Is_True (Expr_Value (Condition (P)))
4584 and then not Is_Simple_Case (Condition (P))
4585 then
4586 pragma Assert (Unblocked_Exit_Count = 2);
4587 Unblocked_Exit_Count := 0;
4588 else
4589 Unblocked_Exit_Count := Unblocked_Exit_Count - 1;
4590 end if;
4591 end if;
4592 end if;
4593 end Check_Unreachable_Code;
4594
4595 ------------------------
4596 -- Has_Sec_Stack_Call --
4597 ------------------------
4598
4599 function Has_Sec_Stack_Call (N : Node_Id) return Boolean is
4600 function Check_Call (N : Node_Id) return Traverse_Result;
4601 -- Check if N is a function call which uses the secondary stack
4602
4603 ----------------
4604 -- Check_Call --
4605 ----------------
4606
4607 function Check_Call (N : Node_Id) return Traverse_Result is
4608 Subp : Entity_Id;
4609
4610 begin
4611 if Nkind (N) = N_Function_Call then
4612 Subp := Get_Called_Entity (N);
4613
4614 if Present (Subp) then
4615 if Requires_Transient_Scope (Etype (Subp)) then
4616 return Abandon;
4617
4618 elsif Sec_Stack_Needed_For_Return (Subp) then
4619 return Abandon;
4620 end if;
4621 end if;
4622 end if;
4623
4624 -- Continue traversing the tree
4625
4626 return OK;
4627 end Check_Call;
4628
4629 function Check_Calls is new Traverse_Func (Check_Call);
4630
4631 -- Start of processing for Has_Sec_Stack_Call
4632
4633 begin
4634 return Check_Calls (N) = Abandon;
4635 end Has_Sec_Stack_Call;
4636
4637 ----------------------
4638 -- Preanalyze_Range --
4639 ----------------------
4640
4641 procedure Preanalyze_Range (R_Copy : Node_Id) is
4642 Save_Analysis : constant Boolean := Full_Analysis;
4643 Typ : Entity_Id;
4644
4645 begin
4646 Full_Analysis := False;
4647 Expander_Mode_Save_And_Set (False);
4648
4649 -- In addition to the above we must explicitly suppress the generation
4650 -- of freeze nodes that might otherwise be generated during resolution
4651 -- of the range (e.g. if given by an attribute that will freeze its
4652 -- prefix).
4653
4654 Set_Must_Not_Freeze (R_Copy);
4655
4656 if Nkind (R_Copy) = N_Attribute_Reference then
4657 Set_Must_Not_Freeze (Prefix (R_Copy));
4658 end if;
4659
4660 Analyze (R_Copy);
4661
4662 if Nkind (R_Copy) in N_Subexpr and then Is_Overloaded (R_Copy) then
4663
4664 -- Apply preference rules for range of predefined integer types, or
4665 -- check for array or iterable construct for "of" iterator, or
4666 -- diagnose true ambiguity.
4667
4668 declare
4669 I : Interp_Index;
4670 It : Interp;
4671 Found : Entity_Id := Empty;
4672
4673 begin
4674 Get_First_Interp (R_Copy, I, It);
4675 while Present (It.Typ) loop
4676 if Is_Discrete_Type (It.Typ) then
4677 if No (Found) then
4678 Found := It.Typ;
4679 else
4680 if Scope (Found) = Standard_Standard then
4681 null;
4682
4683 elsif Scope (It.Typ) = Standard_Standard then
4684 Found := It.Typ;
4685
4686 else
4687 -- Both of them are user-defined
4688
4689 Error_Msg_N
4690 ("ambiguous bounds in range of iteration", R_Copy);
4691 Error_Msg_N ("\possible interpretations:", R_Copy);
4692 Error_Msg_NE ("\\}", R_Copy, Found);
4693 Error_Msg_NE ("\\}", R_Copy, It.Typ);
4694 exit;
4695 end if;
4696 end if;
4697
4698 elsif Nkind (Parent (R_Copy)) = N_Iterator_Specification
4699 and then Of_Present (Parent (R_Copy))
4700 then
4701 if Is_Array_Type (It.Typ)
4702 or else Has_Aspect (It.Typ, Aspect_Iterator_Element)
4703 or else Has_Aspect (It.Typ, Aspect_Constant_Indexing)
4704 or else Has_Aspect (It.Typ, Aspect_Variable_Indexing)
4705 then
4706 if No (Found) then
4707 Found := It.Typ;
4708 Set_Etype (R_Copy, It.Typ);
4709
4710 else
4711 Error_Msg_N ("ambiguous domain of iteration", R_Copy);
4712 end if;
4713 end if;
4714 end if;
4715
4716 Get_Next_Interp (I, It);
4717 end loop;
4718 end;
4719 end if;
4720
4721 -- Subtype mark in iteration scheme
4722
4723 if Is_Entity_Name (R_Copy) and then Is_Type (Entity (R_Copy)) then
4724 null;
4725
4726 -- Expression in range, or Ada 2012 iterator
4727
4728 elsif Nkind (R_Copy) in N_Subexpr then
4729 Resolve (R_Copy);
4730 Typ := Etype (R_Copy);
4731
4732 if Is_Discrete_Type (Typ) then
4733 null;
4734
4735 -- Check that the resulting object is an iterable container
4736
4737 elsif Has_Aspect (Typ, Aspect_Iterator_Element)
4738 or else Has_Aspect (Typ, Aspect_Constant_Indexing)
4739 or else Has_Aspect (Typ, Aspect_Variable_Indexing)
4740 then
4741 null;
4742
4743 -- The expression may yield an implicit reference to an iterable
4744 -- container. Insert explicit dereference so that proper type is
4745 -- visible in the loop.
4746
4747 elsif Has_Implicit_Dereference (Etype (R_Copy)) then
4748 Build_Explicit_Dereference
4749 (R_Copy, Get_Reference_Discriminant (Etype (R_Copy)));
4750 end if;
4751 end if;
4752
4753 Expander_Mode_Restore;
4754 Full_Analysis := Save_Analysis;
4755 end Preanalyze_Range;
4756
4757 end Sem_Ch5;