PR rtl-optimization/82913
[official-gcc.git] / gcc / ada / sem_ch5.adb
blob14cf2e5a732fbc04f3f8156e8572b627c7ffc384
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-2017, 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 ------------------------------------------------------------------------------
26 with Aspects; use Aspects;
27 with Atree; use Atree;
28 with Checks; use Checks;
29 with Einfo; use Einfo;
30 with Errout; use Errout;
31 with Expander; use Expander;
32 with Exp_Ch6; use Exp_Ch6;
33 with Exp_Util; use Exp_Util;
34 with Freeze; use Freeze;
35 with Ghost; use Ghost;
36 with Lib; use Lib;
37 with Lib.Xref; use Lib.Xref;
38 with Namet; use Namet;
39 with Nlists; use Nlists;
40 with Nmake; use Nmake;
41 with Opt; use Opt;
42 with Restrict; use Restrict;
43 with Rident; use Rident;
44 with Sem; use Sem;
45 with Sem_Aux; use Sem_Aux;
46 with Sem_Case; use Sem_Case;
47 with Sem_Ch3; use Sem_Ch3;
48 with Sem_Ch6; use Sem_Ch6;
49 with Sem_Ch8; use Sem_Ch8;
50 with Sem_Dim; use Sem_Dim;
51 with Sem_Disp; use Sem_Disp;
52 with Sem_Elab; use Sem_Elab;
53 with Sem_Eval; use Sem_Eval;
54 with Sem_Res; use Sem_Res;
55 with Sem_Type; use Sem_Type;
56 with Sem_Util; use Sem_Util;
57 with Sem_Warn; use Sem_Warn;
58 with Snames; use Snames;
59 with Stand; use Stand;
60 with Sinfo; use Sinfo;
61 with Targparm; use Targparm;
62 with Tbuild; use Tbuild;
63 with Uintp; use Uintp;
65 package body Sem_Ch5 is
67 Current_Assignment : Node_Id := Empty;
68 -- This variable holds the node for an assignment that contains target
69 -- names. The corresponding flag has been set by the parser, and when
70 -- set the analysis of the RHS must be done with all expansion disabled,
71 -- because the assignment is reanalyzed after expansion has replaced all
72 -- occurrences of the target name appropriately.
74 Unblocked_Exit_Count : Nat := 0;
75 -- This variable is used when processing if statements, case statements,
76 -- and block statements. It counts the number of exit points that are not
77 -- blocked by unconditional transfer instructions: for IF and CASE, these
78 -- are the branches of the conditional; for a block, they are the statement
79 -- sequence of the block, and the statement sequences of any exception
80 -- handlers that are part of the block. When processing is complete, if
81 -- this count is zero, it means that control cannot fall through the IF,
82 -- CASE or block statement. This is used for the generation of warning
83 -- messages. This variable is recursively saved on entry to processing the
84 -- construct, and restored on exit.
86 procedure Preanalyze_Range (R_Copy : Node_Id);
87 -- Determine expected type of range or domain of iteration of Ada 2012
88 -- loop by analyzing separate copy. Do the analysis and resolution of the
89 -- copy of the bound(s) with expansion disabled, to prevent the generation
90 -- of finalization actions. This prevents memory leaks when the bounds
91 -- contain calls to functions returning controlled arrays or when the
92 -- domain of iteration is a container.
94 ------------------------
95 -- Analyze_Assignment --
96 ------------------------
98 -- WARNING: This routine manages Ghost regions. Return statements must be
99 -- replaced by gotos which jump to the end of the routine and restore the
100 -- Ghost mode.
102 procedure Analyze_Assignment (N : Node_Id) is
103 Lhs : constant Node_Id := Name (N);
104 Rhs : Node_Id := Expression (N);
106 procedure Diagnose_Non_Variable_Lhs (N : Node_Id);
107 -- N is the node for the left hand side of an assignment, and it is not
108 -- a variable. This routine issues an appropriate diagnostic.
110 procedure Kill_Lhs;
111 -- This is called to kill current value settings of a simple variable
112 -- on the left hand side. We call it if we find any error in analyzing
113 -- the assignment, and at the end of processing before setting any new
114 -- current values in place.
116 procedure Set_Assignment_Type
117 (Opnd : Node_Id;
118 Opnd_Type : in out Entity_Id);
119 -- Opnd is either the Lhs or Rhs of the assignment, and Opnd_Type is the
120 -- nominal subtype. This procedure is used to deal with cases where the
121 -- nominal subtype must be replaced by the actual subtype.
123 procedure Transform_BIP_Assignment (Typ : Entity_Id);
124 function Should_Transform_BIP_Assignment
125 (Typ : Entity_Id) return Boolean;
126 -- If the right-hand side of an assignment statement is a build-in-place
127 -- call we cannot build in place, so we insert a temp initialized with
128 -- the call, and transform the assignment statement to copy the temp.
129 -- Transform_BIP_Assignment does the tranformation, and
130 -- Should_Transform_BIP_Assignment determines whether we should.
131 -- The same goes for qualified expressions and conversions whose
132 -- operand is such a call.
134 -- This is only for nonlimited types; assignment statements are illegal
135 -- for limited types, but are generated internally for aggregates and
136 -- init procs. These limited-type are not really assignment statements
137 -- -- conceptually, they are initializations, so should not be
138 -- transformed.
140 -- Similarly, for nonlimited types, aggregates and init procs generate
141 -- assignment statements that are really initializations. These are
142 -- marked No_Ctrl_Actions.
144 -------------------------------
145 -- Diagnose_Non_Variable_Lhs --
146 -------------------------------
148 procedure Diagnose_Non_Variable_Lhs (N : Node_Id) is
149 begin
150 -- Not worth posting another error if left hand side already flagged
151 -- as being illegal in some respect.
153 if Error_Posted (N) then
154 return;
156 -- Some special bad cases of entity names
158 elsif Is_Entity_Name (N) then
159 declare
160 Ent : constant Entity_Id := Entity (N);
162 begin
163 if Ekind (Ent) = E_In_Parameter then
164 Error_Msg_N
165 ("assignment to IN mode parameter not allowed", N);
166 return;
168 -- Renamings of protected private components are turned into
169 -- constants when compiling a protected function. In the case
170 -- of single protected types, the private component appears
171 -- directly.
173 elsif (Is_Prival (Ent)
174 and then
175 (Ekind (Current_Scope) = E_Function
176 or else Ekind (Enclosing_Dynamic_Scope
177 (Current_Scope)) = E_Function))
178 or else
179 (Ekind (Ent) = E_Component
180 and then Is_Protected_Type (Scope (Ent)))
181 then
182 Error_Msg_N
183 ("protected function cannot modify protected object", N);
184 return;
186 elsif Ekind (Ent) = E_Loop_Parameter then
187 Error_Msg_N ("assignment to loop parameter not allowed", N);
188 return;
189 end if;
190 end;
192 -- For indexed components, test prefix if it is in array. We do not
193 -- want to recurse for cases where the prefix is a pointer, since we
194 -- may get a message confusing the pointer and what it references.
196 elsif Nkind (N) = N_Indexed_Component
197 and then Is_Array_Type (Etype (Prefix (N)))
198 then
199 Diagnose_Non_Variable_Lhs (Prefix (N));
200 return;
202 -- Another special case for assignment to discriminant
204 elsif Nkind (N) = N_Selected_Component then
205 if Present (Entity (Selector_Name (N)))
206 and then Ekind (Entity (Selector_Name (N))) = E_Discriminant
207 then
208 Error_Msg_N ("assignment to discriminant not allowed", N);
209 return;
211 -- For selection from record, diagnose prefix, but note that again
212 -- we only do this for a record, not e.g. for a pointer.
214 elsif Is_Record_Type (Etype (Prefix (N))) then
215 Diagnose_Non_Variable_Lhs (Prefix (N));
216 return;
217 end if;
218 end if;
220 -- If we fall through, we have no special message to issue
222 Error_Msg_N ("left hand side of assignment must be a variable", N);
223 end Diagnose_Non_Variable_Lhs;
225 --------------
226 -- Kill_Lhs --
227 --------------
229 procedure Kill_Lhs is
230 begin
231 if Is_Entity_Name (Lhs) then
232 declare
233 Ent : constant Entity_Id := Entity (Lhs);
234 begin
235 if Present (Ent) then
236 Kill_Current_Values (Ent);
237 end if;
238 end;
239 end if;
240 end Kill_Lhs;
242 -------------------------
243 -- Set_Assignment_Type --
244 -------------------------
246 procedure Set_Assignment_Type
247 (Opnd : Node_Id;
248 Opnd_Type : in out Entity_Id)
250 Decl : Node_Id;
252 begin
253 Require_Entity (Opnd);
255 -- If the assignment operand is an in-out or out parameter, then we
256 -- get the actual subtype (needed for the unconstrained case). If the
257 -- operand is the actual in an entry declaration, then within the
258 -- accept statement it is replaced with a local renaming, which may
259 -- also have an actual subtype.
261 if Is_Entity_Name (Opnd)
262 and then (Ekind (Entity (Opnd)) = E_Out_Parameter
263 or else Ekind_In (Entity (Opnd),
264 E_In_Out_Parameter,
265 E_Generic_In_Out_Parameter)
266 or else
267 (Ekind (Entity (Opnd)) = E_Variable
268 and then Nkind (Parent (Entity (Opnd))) =
269 N_Object_Renaming_Declaration
270 and then Nkind (Parent (Parent (Entity (Opnd)))) =
271 N_Accept_Statement))
272 then
273 Opnd_Type := Get_Actual_Subtype (Opnd);
275 -- If assignment operand is a component reference, then we get the
276 -- actual subtype of the component for the unconstrained case.
278 elsif Nkind_In (Opnd, N_Selected_Component, N_Explicit_Dereference)
279 and then not Is_Unchecked_Union (Opnd_Type)
280 then
281 Decl := Build_Actual_Subtype_Of_Component (Opnd_Type, Opnd);
283 if Present (Decl) then
284 Insert_Action (N, Decl);
285 Mark_Rewrite_Insertion (Decl);
286 Analyze (Decl);
287 Opnd_Type := Defining_Identifier (Decl);
288 Set_Etype (Opnd, Opnd_Type);
289 Freeze_Itype (Opnd_Type, N);
291 elsif Is_Constrained (Etype (Opnd)) then
292 Opnd_Type := Etype (Opnd);
293 end if;
295 -- For slice, use the constrained subtype created for the slice
297 elsif Nkind (Opnd) = N_Slice then
298 Opnd_Type := Etype (Opnd);
299 end if;
300 end Set_Assignment_Type;
302 -------------------------------------
303 -- Should_Transform_BIP_Assignment --
304 -------------------------------------
306 function Should_Transform_BIP_Assignment
307 (Typ : Entity_Id) return Boolean
309 Result : Boolean;
311 begin
312 if Expander_Active
313 and then not Is_Limited_View (Typ)
314 and then Is_Build_In_Place_Result_Type (Typ)
315 and then not No_Ctrl_Actions (N)
316 then
317 -- This function is called early, before name resolution is
318 -- complete, so we have to deal with things that might turn into
319 -- function calls later. N_Function_Call and N_Op nodes are the
320 -- obvious case. An N_Identifier or N_Expanded_Name is a
321 -- parameterless function call if it denotes a function.
322 -- Finally, an attribute reference can be a function call.
324 case Nkind (Unqual_Conv (Rhs)) is
325 when N_Function_Call
326 | N_Op
328 Result := True;
330 when N_Expanded_Name
331 | N_Identifier
333 case Ekind (Entity (Unqual_Conv (Rhs))) is
334 when E_Function
335 | E_Operator
337 Result := True;
339 when others =>
340 Result := False;
341 end case;
343 when N_Attribute_Reference =>
344 Result := Attribute_Name (Unqual_Conv (Rhs)) = Name_Input;
345 -- T'Input will turn into a call whose result type is T
347 when others =>
348 Result := False;
349 end case;
350 else
351 Result := False;
352 end if;
354 return Result;
355 end Should_Transform_BIP_Assignment;
357 ------------------------------
358 -- Transform_BIP_Assignment --
359 ------------------------------
361 procedure Transform_BIP_Assignment (Typ : Entity_Id) is
363 -- Tranform "X : [constant] T := F (...);" into:
365 -- Temp : constant T := F (...);
366 -- X := Temp;
368 Loc : constant Source_Ptr := Sloc (N);
369 Def_Id : constant Entity_Id := Make_Temporary (Loc, 'Y', Rhs);
370 Obj_Decl : constant Node_Id :=
371 Make_Object_Declaration (Loc,
372 Defining_Identifier => Def_Id,
373 Constant_Present => True,
374 Object_Definition => New_Occurrence_Of (Typ, Loc),
375 Expression => Rhs,
376 Has_Init_Expression => True);
378 begin
379 Set_Etype (Def_Id, Typ);
380 Set_Expression (N, New_Occurrence_Of (Def_Id, Loc));
382 -- At this point, Rhs is no longer equal to Expression (N), so:
384 Rhs := Expression (N);
386 Insert_Action (N, Obj_Decl);
387 end Transform_BIP_Assignment;
389 -- Local variables
391 T1 : Entity_Id;
392 T2 : Entity_Id;
394 Save_Full_Analysis : Boolean := False;
395 -- Force initialization to facilitate static analysis
397 Saved_GM : constant Ghost_Mode_Type := Ghost_Mode;
398 -- Save the Ghost mode to restore on exit
400 -- Start of processing for Analyze_Assignment
402 begin
403 Mark_Coextensions (N, Rhs);
405 -- Preserve relevant elaboration-related attributes of the context which
406 -- are no longer available or very expensive to recompute once analysis,
407 -- resolution, and expansion are over.
409 Mark_Elaboration_Attributes
410 (N_Id => N,
411 Checks => True,
412 Modes => True);
414 -- Analyze the target of the assignment first in case the expression
415 -- contains references to Ghost entities. The checks that verify the
416 -- proper use of a Ghost entity need to know the enclosing context.
418 Analyze (Lhs);
420 -- An assignment statement is Ghost when the left hand side denotes a
421 -- Ghost entity. Set the mode now to ensure that any nodes generated
422 -- during analysis and expansion are properly marked as Ghost.
424 if Has_Target_Names (N) then
425 Current_Assignment := N;
426 Expander_Mode_Save_And_Set (False);
427 Save_Full_Analysis := Full_Analysis;
428 Full_Analysis := False;
429 else
430 Current_Assignment := Empty;
431 end if;
433 Mark_And_Set_Ghost_Assignment (N);
434 Analyze (Rhs);
436 -- Ensure that we never do an assignment on a variable marked as
437 -- Is_Safe_To_Reevaluate.
439 pragma Assert
440 (not Is_Entity_Name (Lhs)
441 or else Ekind (Entity (Lhs)) /= E_Variable
442 or else not Is_Safe_To_Reevaluate (Entity (Lhs)));
444 -- Start type analysis for assignment
446 T1 := Etype (Lhs);
448 -- In the most general case, both Lhs and Rhs can be overloaded, and we
449 -- must compute the intersection of the possible types on each side.
451 if Is_Overloaded (Lhs) then
452 declare
453 I : Interp_Index;
454 It : Interp;
456 begin
457 T1 := Any_Type;
458 Get_First_Interp (Lhs, I, It);
460 while Present (It.Typ) loop
462 -- An indexed component with generalized indexing is always
463 -- overloaded with the corresponding dereference. Discard the
464 -- interpretation that yields a reference type, which is not
465 -- assignable.
467 if Nkind (Lhs) = N_Indexed_Component
468 and then Present (Generalized_Indexing (Lhs))
469 and then Has_Implicit_Dereference (It.Typ)
470 then
471 null;
473 -- This may be a call to a parameterless function through an
474 -- implicit dereference, so discard interpretation as well.
476 elsif Is_Entity_Name (Lhs)
477 and then Has_Implicit_Dereference (It.Typ)
478 then
479 null;
481 elsif Has_Compatible_Type (Rhs, It.Typ) then
482 if T1 = Any_Type then
483 T1 := It.Typ;
484 else
485 -- An explicit dereference is overloaded if the prefix
486 -- is. Try to remove the ambiguity on the prefix, the
487 -- error will be posted there if the ambiguity is real.
489 if Nkind (Lhs) = N_Explicit_Dereference then
490 declare
491 PI : Interp_Index;
492 PI1 : Interp_Index := 0;
493 PIt : Interp;
494 Found : Boolean;
496 begin
497 Found := False;
498 Get_First_Interp (Prefix (Lhs), PI, PIt);
500 while Present (PIt.Typ) loop
501 if Is_Access_Type (PIt.Typ)
502 and then Has_Compatible_Type
503 (Rhs, Designated_Type (PIt.Typ))
504 then
505 if Found then
506 PIt :=
507 Disambiguate (Prefix (Lhs),
508 PI1, PI, Any_Type);
510 if PIt = No_Interp then
511 Error_Msg_N
512 ("ambiguous left-hand side in "
513 & "assignment", Lhs);
514 exit;
515 else
516 Resolve (Prefix (Lhs), PIt.Typ);
517 end if;
519 exit;
520 else
521 Found := True;
522 PI1 := PI;
523 end if;
524 end if;
526 Get_Next_Interp (PI, PIt);
527 end loop;
528 end;
530 else
531 Error_Msg_N
532 ("ambiguous left-hand side in assignment", Lhs);
533 exit;
534 end if;
535 end if;
536 end if;
538 Get_Next_Interp (I, It);
539 end loop;
540 end;
542 if T1 = Any_Type then
543 Error_Msg_N
544 ("no valid types for left-hand side for assignment", Lhs);
545 Kill_Lhs;
546 goto Leave;
547 end if;
548 end if;
550 -- Deal with build-in-place calls for nonlimited types. We don't do this
551 -- later, because resolving the rhs tranforms it incorrectly for build-
552 -- in-place.
554 if Should_Transform_BIP_Assignment (Typ => T1) then
555 Transform_BIP_Assignment (Typ => T1);
556 end if;
558 pragma Assert (not Should_Transform_BIP_Assignment (Typ => T1));
560 -- The resulting assignment type is T1, so now we will resolve the left
561 -- hand side of the assignment using this determined type.
563 Resolve (Lhs, T1);
565 -- Cases where Lhs is not a variable. In an instance or an inlined body
566 -- no need for further check because assignment was legal in template.
568 if In_Inlined_Body then
569 null;
571 elsif not Is_Variable (Lhs) then
573 -- Ada 2005 (AI-327): Check assignment to the attribute Priority of a
574 -- protected object.
576 declare
577 Ent : Entity_Id;
578 S : Entity_Id;
580 begin
581 if Ada_Version >= Ada_2005 then
583 -- Handle chains of renamings
585 Ent := Lhs;
586 while Nkind (Ent) in N_Has_Entity
587 and then Present (Entity (Ent))
588 and then Present (Renamed_Object (Entity (Ent)))
589 loop
590 Ent := Renamed_Object (Entity (Ent));
591 end loop;
593 if (Nkind (Ent) = N_Attribute_Reference
594 and then Attribute_Name (Ent) = Name_Priority)
596 -- Renamings of the attribute Priority applied to protected
597 -- objects have been previously expanded into calls to the
598 -- Get_Ceiling run-time subprogram.
600 or else Is_Expanded_Priority_Attribute (Ent)
601 then
602 -- The enclosing subprogram cannot be a protected function
604 S := Current_Scope;
605 while not (Is_Subprogram (S)
606 and then Convention (S) = Convention_Protected)
607 and then S /= Standard_Standard
608 loop
609 S := Scope (S);
610 end loop;
612 if Ekind (S) = E_Function
613 and then Convention (S) = Convention_Protected
614 then
615 Error_Msg_N
616 ("protected function cannot modify protected object",
617 Lhs);
618 end if;
620 -- Changes of the ceiling priority of the protected object
621 -- are only effective if the Ceiling_Locking policy is in
622 -- effect (AARM D.5.2 (5/2)).
624 if Locking_Policy /= 'C' then
625 Error_Msg_N
626 ("assignment to the attribute PRIORITY has no effect??",
627 Lhs);
628 Error_Msg_N
629 ("\since no Locking_Policy has been specified??", Lhs);
630 end if;
632 goto Leave;
633 end if;
634 end if;
635 end;
637 Diagnose_Non_Variable_Lhs (Lhs);
638 goto Leave;
640 -- Error of assigning to limited type. We do however allow this in
641 -- certain cases where the front end generates the assignments.
643 elsif Is_Limited_Type (T1)
644 and then not Assignment_OK (Lhs)
645 and then not Assignment_OK (Original_Node (Lhs))
646 then
647 -- CPP constructors can only be called in declarations
649 if Is_CPP_Constructor_Call (Rhs) then
650 Error_Msg_N ("invalid use of 'C'P'P constructor", Rhs);
651 else
652 Error_Msg_N
653 ("left hand of assignment must not be limited type", Lhs);
654 Explain_Limited_Type (T1, Lhs);
655 end if;
657 goto Leave;
659 -- A class-wide type may be a limited view. This illegal case is not
660 -- caught by previous checks.
662 elsif Ekind (T1) = E_Class_Wide_Type and then From_Limited_With (T1) then
663 Error_Msg_NE ("invalid use of limited view of&", Lhs, T1);
664 goto Leave;
666 -- Enforce RM 3.9.3 (8): the target of an assignment operation cannot be
667 -- abstract. This is only checked when the assignment Comes_From_Source,
668 -- because in some cases the expander generates such assignments (such
669 -- in the _assign operation for an abstract type).
671 elsif Is_Abstract_Type (T1) and then Comes_From_Source (N) then
672 Error_Msg_N
673 ("target of assignment operation must not be abstract", Lhs);
674 end if;
676 -- Resolution may have updated the subtype, in case the left-hand side
677 -- is a private protected component. Use the correct subtype to avoid
678 -- scoping issues in the back-end.
680 T1 := Etype (Lhs);
682 -- Ada 2005 (AI-50217, AI-326): Check wrong dereference of incomplete
683 -- type. For example:
685 -- limited with P;
686 -- package Pkg is
687 -- type Acc is access P.T;
688 -- end Pkg;
690 -- with Pkg; use Acc;
691 -- procedure Example is
692 -- A, B : Acc;
693 -- begin
694 -- A.all := B.all; -- ERROR
695 -- end Example;
697 if Nkind (Lhs) = N_Explicit_Dereference
698 and then Ekind (T1) = E_Incomplete_Type
699 then
700 Error_Msg_N ("invalid use of incomplete type", Lhs);
701 Kill_Lhs;
702 goto Leave;
703 end if;
705 -- Now we can complete the resolution of the right hand side
707 Set_Assignment_Type (Lhs, T1);
709 -- If the target of the assignment is an entity of a mutable type and
710 -- the expression is a conditional expression, its alternatives can be
711 -- of different subtypes of the nominal type of the LHS, so they must be
712 -- resolved with the base type, given that their subtype may differ from
713 -- that of the target mutable object.
715 if Is_Entity_Name (Lhs)
716 and then Ekind_In (Entity (Lhs), E_In_Out_Parameter,
717 E_Out_Parameter,
718 E_Variable)
719 and then Is_Composite_Type (T1)
720 and then not Is_Constrained (Etype (Entity (Lhs)))
721 and then Nkind_In (Rhs, N_If_Expression, N_Case_Expression)
722 then
723 Resolve (Rhs, Base_Type (T1));
725 else
726 Resolve (Rhs, T1);
727 end if;
729 -- This is the point at which we check for an unset reference
731 Check_Unset_Reference (Rhs);
732 Check_Unprotected_Access (Lhs, Rhs);
734 -- Remaining steps are skipped if Rhs was syntactically in error
736 if Rhs = Error then
737 Kill_Lhs;
738 goto Leave;
739 end if;
741 T2 := Etype (Rhs);
743 if not Covers (T1, T2) then
744 Wrong_Type (Rhs, Etype (Lhs));
745 Kill_Lhs;
746 goto Leave;
747 end if;
749 -- Ada 2005 (AI-326): In case of explicit dereference of incomplete
750 -- types, use the non-limited view if available
752 if Nkind (Rhs) = N_Explicit_Dereference
753 and then Is_Tagged_Type (T2)
754 and then Has_Non_Limited_View (T2)
755 then
756 T2 := Non_Limited_View (T2);
757 end if;
759 Set_Assignment_Type (Rhs, T2);
761 if Total_Errors_Detected /= 0 then
762 if No (T1) then
763 T1 := Any_Type;
764 end if;
766 if No (T2) then
767 T2 := Any_Type;
768 end if;
769 end if;
771 if T1 = Any_Type or else T2 = Any_Type then
772 Kill_Lhs;
773 goto Leave;
774 end if;
776 -- If the rhs is class-wide or dynamically tagged, then require the lhs
777 -- to be class-wide. The case where the rhs is a dynamically tagged call
778 -- to a dispatching operation with a controlling access result is
779 -- excluded from this check, since the target has an access type (and
780 -- no tag propagation occurs in that case).
782 if (Is_Class_Wide_Type (T2)
783 or else (Is_Dynamically_Tagged (Rhs)
784 and then not Is_Access_Type (T1)))
785 and then not Is_Class_Wide_Type (T1)
786 then
787 Error_Msg_N ("dynamically tagged expression not allowed!", Rhs);
789 elsif Is_Class_Wide_Type (T1)
790 and then not Is_Class_Wide_Type (T2)
791 and then not Is_Tag_Indeterminate (Rhs)
792 and then not Is_Dynamically_Tagged (Rhs)
793 then
794 Error_Msg_N ("dynamically tagged expression required!", Rhs);
795 end if;
797 -- Propagate the tag from a class-wide target to the rhs when the rhs
798 -- is a tag-indeterminate call.
800 if Is_Tag_Indeterminate (Rhs) then
801 if Is_Class_Wide_Type (T1) then
802 Propagate_Tag (Lhs, Rhs);
804 elsif Nkind (Rhs) = N_Function_Call
805 and then Is_Entity_Name (Name (Rhs))
806 and then Is_Abstract_Subprogram (Entity (Name (Rhs)))
807 then
808 Error_Msg_N
809 ("call to abstract function must be dispatching", Name (Rhs));
811 elsif Nkind (Rhs) = N_Qualified_Expression
812 and then Nkind (Expression (Rhs)) = N_Function_Call
813 and then Is_Entity_Name (Name (Expression (Rhs)))
814 and then
815 Is_Abstract_Subprogram (Entity (Name (Expression (Rhs))))
816 then
817 Error_Msg_N
818 ("call to abstract function must be dispatching",
819 Name (Expression (Rhs)));
820 end if;
821 end if;
823 -- Ada 2005 (AI-385): When the lhs type is an anonymous access type,
824 -- apply an implicit conversion of the rhs to that type to force
825 -- appropriate static and run-time accessibility checks. This applies
826 -- as well to anonymous access-to-subprogram types that are component
827 -- subtypes or formal parameters.
829 if Ada_Version >= Ada_2005 and then Is_Access_Type (T1) then
830 if Is_Local_Anonymous_Access (T1)
831 or else Ekind (T2) = E_Anonymous_Access_Subprogram_Type
833 -- Handle assignment to an Ada 2012 stand-alone object
834 -- of an anonymous access type.
836 or else (Ekind (T1) = E_Anonymous_Access_Type
837 and then Nkind (Associated_Node_For_Itype (T1)) =
838 N_Object_Declaration)
840 then
841 Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
842 Analyze_And_Resolve (Rhs, T1);
843 end if;
844 end if;
846 -- Ada 2005 (AI-231): Assignment to not null variable
848 if Ada_Version >= Ada_2005
849 and then Can_Never_Be_Null (T1)
850 and then not Assignment_OK (Lhs)
851 then
852 -- Case where we know the right hand side is null
854 if Known_Null (Rhs) then
855 Apply_Compile_Time_Constraint_Error
856 (N => Rhs,
857 Msg =>
858 "(Ada 2005) null not allowed in null-excluding objects??",
859 Reason => CE_Null_Not_Allowed);
861 -- We still mark this as a possible modification, that's necessary
862 -- to reset Is_True_Constant, and desirable for xref purposes.
864 Note_Possible_Modification (Lhs, Sure => True);
865 goto Leave;
867 -- If we know the right hand side is non-null, then we convert to the
868 -- target type, since we don't need a run time check in that case.
870 elsif not Can_Never_Be_Null (T2) then
871 Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
872 Analyze_And_Resolve (Rhs, T1);
873 end if;
874 end if;
876 if Is_Scalar_Type (T1) then
877 Apply_Scalar_Range_Check (Rhs, Etype (Lhs));
879 -- For array types, verify that lengths match. If the right hand side
880 -- is a function call that has been inlined, the assignment has been
881 -- rewritten as a block, and the constraint check will be applied to the
882 -- assignment within the block.
884 elsif Is_Array_Type (T1)
885 and then (Nkind (Rhs) /= N_Type_Conversion
886 or else Is_Constrained (Etype (Rhs)))
887 and then (Nkind (Rhs) /= N_Function_Call
888 or else Nkind (N) /= N_Block_Statement)
889 then
890 -- Assignment verifies that the length of the Lsh and Rhs are equal,
891 -- but of course the indexes do not have to match. If the right-hand
892 -- side is a type conversion to an unconstrained type, a length check
893 -- is performed on the expression itself during expansion. In rare
894 -- cases, the redundant length check is computed on an index type
895 -- with a different representation, triggering incorrect code in the
896 -- back end.
898 Apply_Length_Check (Rhs, Etype (Lhs));
900 else
901 -- Discriminant checks are applied in the course of expansion
903 null;
904 end if;
906 -- Note: modifications of the Lhs may only be recorded after
907 -- checks have been applied.
909 Note_Possible_Modification (Lhs, Sure => True);
911 -- ??? a real accessibility check is needed when ???
913 -- Post warning for redundant assignment or variable to itself
915 if Warn_On_Redundant_Constructs
917 -- We only warn for source constructs
919 and then Comes_From_Source (N)
921 -- Where the object is the same on both sides
923 and then Same_Object (Lhs, Original_Node (Rhs))
925 -- But exclude the case where the right side was an operation that
926 -- got rewritten (e.g. JUNK + K, where K was known to be zero). We
927 -- don't want to warn in such a case, since it is reasonable to write
928 -- such expressions especially when K is defined symbolically in some
929 -- other package.
931 and then Nkind (Original_Node (Rhs)) not in N_Op
932 then
933 if Nkind (Lhs) in N_Has_Entity then
934 Error_Msg_NE -- CODEFIX
935 ("?r?useless assignment of & to itself!", N, Entity (Lhs));
936 else
937 Error_Msg_N -- CODEFIX
938 ("?r?useless assignment of object to itself!", N);
939 end if;
940 end if;
942 -- Check for non-allowed composite assignment
944 if not Support_Composite_Assign_On_Target
945 and then (Is_Array_Type (T1) or else Is_Record_Type (T1))
946 and then (not Has_Size_Clause (T1) or else Esize (T1) > 64)
947 then
948 Error_Msg_CRT ("composite assignment", N);
949 end if;
951 -- Save the scenario for later examination by the ABE Processing phase
953 Record_Elaboration_Scenario (N);
955 -- Set Referenced_As_LHS if appropriate. We only set this flag if the
956 -- assignment is a source assignment in the extended main source unit.
957 -- We are not interested in any reference information outside this
958 -- context, or in compiler generated assignment statements.
960 if Comes_From_Source (N)
961 and then In_Extended_Main_Source_Unit (Lhs)
962 then
963 Set_Referenced_Modified (Lhs, Out_Param => False);
964 end if;
966 -- RM 7.3.2 (12/3): An assignment to a view conversion (from a type to
967 -- one of its ancestors) requires an invariant check. Apply check only
968 -- if expression comes from source, otherwise it will be applied when
969 -- value is assigned to source entity. This is not done in GNATprove
970 -- mode, as GNATprove handles invariant checks itself.
972 if Nkind (Lhs) = N_Type_Conversion
973 and then Has_Invariants (Etype (Expression (Lhs)))
974 and then Comes_From_Source (Expression (Lhs))
975 and then not GNATprove_Mode
976 then
977 Insert_After (N, Make_Invariant_Call (Expression (Lhs)));
978 end if;
980 -- Final step. If left side is an entity, then we may be able to reset
981 -- the current tracked values to new safe values. We only have something
982 -- to do if the left side is an entity name, and expansion has not
983 -- modified the node into something other than an assignment, and of
984 -- course we only capture values if it is safe to do so.
986 if Is_Entity_Name (Lhs)
987 and then Nkind (N) = N_Assignment_Statement
988 then
989 declare
990 Ent : constant Entity_Id := Entity (Lhs);
992 begin
993 if Safe_To_Capture_Value (N, Ent) then
995 -- If simple variable on left side, warn if this assignment
996 -- blots out another one (rendering it useless). We only do
997 -- this for source assignments, otherwise we can generate bogus
998 -- warnings when an assignment is rewritten as another
999 -- assignment, and gets tied up with itself.
1001 -- There may have been a previous reference to a component of
1002 -- the variable, which in general removes the Last_Assignment
1003 -- field of the variable to indicate a relevant use of the
1004 -- previous assignment. However, if the assignment is to a
1005 -- subcomponent the reference may not have registered, because
1006 -- it is not possible to determine whether the context is an
1007 -- assignment. In those cases we generate a Deferred_Reference,
1008 -- to be used at the end of compilation to generate the right
1009 -- kind of reference, and we suppress a potential warning for
1010 -- a useless assignment, which might be premature. This may
1011 -- lose a warning in rare cases, but seems preferable to a
1012 -- misleading warning.
1014 if Warn_On_Modified_Unread
1015 and then Is_Assignable (Ent)
1016 and then Comes_From_Source (N)
1017 and then In_Extended_Main_Source_Unit (Ent)
1018 and then not Has_Deferred_Reference (Ent)
1019 then
1020 Warn_On_Useless_Assignment (Ent, N);
1021 end if;
1023 -- If we are assigning an access type and the left side is an
1024 -- entity, then make sure that the Is_Known_[Non_]Null flags
1025 -- properly reflect the state of the entity after assignment.
1027 if Is_Access_Type (T1) then
1028 if Known_Non_Null (Rhs) then
1029 Set_Is_Known_Non_Null (Ent, True);
1031 elsif Known_Null (Rhs)
1032 and then not Can_Never_Be_Null (Ent)
1033 then
1034 Set_Is_Known_Null (Ent, True);
1036 else
1037 Set_Is_Known_Null (Ent, False);
1039 if not Can_Never_Be_Null (Ent) then
1040 Set_Is_Known_Non_Null (Ent, False);
1041 end if;
1042 end if;
1044 -- For discrete types, we may be able to set the current value
1045 -- if the value is known at compile time.
1047 elsif Is_Discrete_Type (T1)
1048 and then Compile_Time_Known_Value (Rhs)
1049 then
1050 Set_Current_Value (Ent, Rhs);
1051 else
1052 Set_Current_Value (Ent, Empty);
1053 end if;
1055 -- If not safe to capture values, kill them
1057 else
1058 Kill_Lhs;
1059 end if;
1060 end;
1061 end if;
1063 -- If assigning to an object in whole or in part, note location of
1064 -- assignment in case no one references value. We only do this for
1065 -- source assignments, otherwise we can generate bogus warnings when an
1066 -- assignment is rewritten as another assignment, and gets tied up with
1067 -- itself.
1069 declare
1070 Ent : constant Entity_Id := Get_Enclosing_Object (Lhs);
1071 begin
1072 if Present (Ent)
1073 and then Safe_To_Capture_Value (N, Ent)
1074 and then Nkind (N) = N_Assignment_Statement
1075 and then Warn_On_Modified_Unread
1076 and then Is_Assignable (Ent)
1077 and then Comes_From_Source (N)
1078 and then In_Extended_Main_Source_Unit (Ent)
1079 then
1080 Set_Last_Assignment (Ent, Lhs);
1081 end if;
1082 end;
1084 Analyze_Dimension (N);
1086 <<Leave>>
1087 Restore_Ghost_Mode (Saved_GM);
1089 -- If the right-hand side contains target names, expansion has been
1090 -- disabled to prevent expansion that might move target names out of
1091 -- the context of the assignment statement. Restore the expander mode
1092 -- now so that assignment statement can be properly expanded.
1094 if Nkind (N) = N_Assignment_Statement then
1095 if Has_Target_Names (N) then
1096 Expander_Mode_Restore;
1097 Full_Analysis := Save_Full_Analysis;
1098 end if;
1100 pragma Assert (not Should_Transform_BIP_Assignment (Typ => T1));
1101 end if;
1102 end Analyze_Assignment;
1104 -----------------------------
1105 -- Analyze_Block_Statement --
1106 -----------------------------
1108 procedure Analyze_Block_Statement (N : Node_Id) is
1109 procedure Install_Return_Entities (Scop : Entity_Id);
1110 -- Install all entities of return statement scope Scop in the visibility
1111 -- chain except for the return object since its entity is reused in a
1112 -- renaming.
1114 -----------------------------
1115 -- Install_Return_Entities --
1116 -----------------------------
1118 procedure Install_Return_Entities (Scop : Entity_Id) is
1119 Id : Entity_Id;
1121 begin
1122 Id := First_Entity (Scop);
1123 while Present (Id) loop
1125 -- Do not install the return object
1127 if not Ekind_In (Id, E_Constant, E_Variable)
1128 or else not Is_Return_Object (Id)
1129 then
1130 Install_Entity (Id);
1131 end if;
1133 Next_Entity (Id);
1134 end loop;
1135 end Install_Return_Entities;
1137 -- Local constants and variables
1139 Decls : constant List_Id := Declarations (N);
1140 Id : constant Node_Id := Identifier (N);
1141 HSS : constant Node_Id := Handled_Statement_Sequence (N);
1143 Is_BIP_Return_Statement : Boolean;
1145 -- Start of processing for Analyze_Block_Statement
1147 begin
1148 -- In SPARK mode, we reject block statements. Note that the case of
1149 -- block statements generated by the expander is fine.
1151 if Nkind (Original_Node (N)) = N_Block_Statement then
1152 Check_SPARK_05_Restriction ("block statement is not allowed", N);
1153 end if;
1155 -- If no handled statement sequence is present, things are really messed
1156 -- up, and we just return immediately (defence against previous errors).
1158 if No (HSS) then
1159 Check_Error_Detected;
1160 return;
1161 end if;
1163 -- Detect whether the block is actually a rewritten return statement of
1164 -- a build-in-place function.
1166 Is_BIP_Return_Statement :=
1167 Present (Id)
1168 and then Present (Entity (Id))
1169 and then Ekind (Entity (Id)) = E_Return_Statement
1170 and then Is_Build_In_Place_Function
1171 (Return_Applies_To (Entity (Id)));
1173 -- Normal processing with HSS present
1175 declare
1176 EH : constant List_Id := Exception_Handlers (HSS);
1177 Ent : Entity_Id := Empty;
1178 S : Entity_Id;
1180 Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
1181 -- Recursively save value of this global, will be restored on exit
1183 begin
1184 -- Initialize unblocked exit count for statements of begin block
1185 -- plus one for each exception handler that is present.
1187 Unblocked_Exit_Count := 1;
1189 if Present (EH) then
1190 Unblocked_Exit_Count := Unblocked_Exit_Count + List_Length (EH);
1191 end if;
1193 -- If a label is present analyze it and mark it as referenced
1195 if Present (Id) then
1196 Analyze (Id);
1197 Ent := Entity (Id);
1199 -- An error defense. If we have an identifier, but no entity, then
1200 -- something is wrong. If previous errors, then just remove the
1201 -- identifier and continue, otherwise raise an exception.
1203 if No (Ent) then
1204 Check_Error_Detected;
1205 Set_Identifier (N, Empty);
1207 else
1208 Set_Ekind (Ent, E_Block);
1209 Generate_Reference (Ent, N, ' ');
1210 Generate_Definition (Ent);
1212 if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
1213 Set_Label_Construct (Parent (Ent), N);
1214 end if;
1215 end if;
1216 end if;
1218 -- If no entity set, create a label entity
1220 if No (Ent) then
1221 Ent := New_Internal_Entity (E_Block, Current_Scope, Sloc (N), 'B');
1222 Set_Identifier (N, New_Occurrence_Of (Ent, Sloc (N)));
1223 Set_Parent (Ent, N);
1224 end if;
1226 Set_Etype (Ent, Standard_Void_Type);
1227 Set_Block_Node (Ent, Identifier (N));
1228 Push_Scope (Ent);
1230 -- The block served as an extended return statement. Ensure that any
1231 -- entities created during the analysis and expansion of the return
1232 -- object declaration are once again visible.
1234 if Is_BIP_Return_Statement then
1235 Install_Return_Entities (Ent);
1236 end if;
1238 if Present (Decls) then
1239 Analyze_Declarations (Decls);
1240 Check_Completion;
1241 Inspect_Deferred_Constant_Completion (Decls);
1242 end if;
1244 Analyze (HSS);
1245 Process_End_Label (HSS, 'e', Ent);
1247 -- If exception handlers are present, then we indicate that enclosing
1248 -- scopes contain a block with handlers. We only need to mark non-
1249 -- generic scopes.
1251 if Present (EH) then
1252 S := Scope (Ent);
1253 loop
1254 Set_Has_Nested_Block_With_Handler (S);
1255 exit when Is_Overloadable (S)
1256 or else Ekind (S) = E_Package
1257 or else Is_Generic_Unit (S);
1258 S := Scope (S);
1259 end loop;
1260 end if;
1262 Check_References (Ent);
1263 Update_Use_Clause_Chain;
1264 End_Scope;
1266 if Unblocked_Exit_Count = 0 then
1267 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1268 Check_Unreachable_Code (N);
1269 else
1270 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1271 end if;
1272 end;
1273 end Analyze_Block_Statement;
1275 --------------------------------
1276 -- Analyze_Compound_Statement --
1277 --------------------------------
1279 procedure Analyze_Compound_Statement (N : Node_Id) is
1280 begin
1281 Analyze_List (Actions (N));
1282 end Analyze_Compound_Statement;
1284 ----------------------------
1285 -- Analyze_Case_Statement --
1286 ----------------------------
1288 procedure Analyze_Case_Statement (N : Node_Id) is
1289 Exp : Node_Id;
1290 Exp_Type : Entity_Id;
1291 Exp_Btype : Entity_Id;
1292 Last_Choice : Nat;
1294 Others_Present : Boolean;
1295 -- Indicates if Others was present
1297 pragma Warnings (Off, Last_Choice);
1298 -- Don't care about assigned value
1300 Statements_Analyzed : Boolean := False;
1301 -- Set True if at least some statement sequences get analyzed. If False
1302 -- on exit, means we had a serious error that prevented full analysis of
1303 -- the case statement, and as a result it is not a good idea to output
1304 -- warning messages about unreachable code.
1306 Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
1307 -- Recursively save value of this global, will be restored on exit
1309 procedure Non_Static_Choice_Error (Choice : Node_Id);
1310 -- Error routine invoked by the generic instantiation below when the
1311 -- case statement has a non static choice.
1313 procedure Process_Statements (Alternative : Node_Id);
1314 -- Analyzes the statements associated with a case alternative. Needed
1315 -- by instantiation below.
1317 package Analyze_Case_Choices is new
1318 Generic_Analyze_Choices
1319 (Process_Associated_Node => Process_Statements);
1320 use Analyze_Case_Choices;
1321 -- Instantiation of the generic choice analysis package
1323 package Check_Case_Choices is new
1324 Generic_Check_Choices
1325 (Process_Empty_Choice => No_OP,
1326 Process_Non_Static_Choice => Non_Static_Choice_Error,
1327 Process_Associated_Node => No_OP);
1328 use Check_Case_Choices;
1329 -- Instantiation of the generic choice processing package
1331 -----------------------------
1332 -- Non_Static_Choice_Error --
1333 -----------------------------
1335 procedure Non_Static_Choice_Error (Choice : Node_Id) is
1336 begin
1337 Flag_Non_Static_Expr
1338 ("choice given in case statement is not static!", Choice);
1339 end Non_Static_Choice_Error;
1341 ------------------------
1342 -- Process_Statements --
1343 ------------------------
1345 procedure Process_Statements (Alternative : Node_Id) is
1346 Choices : constant List_Id := Discrete_Choices (Alternative);
1347 Ent : Entity_Id;
1349 begin
1350 Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
1351 Statements_Analyzed := True;
1353 -- An interesting optimization. If the case statement expression
1354 -- is a simple entity, then we can set the current value within an
1355 -- alternative if the alternative has one possible value.
1357 -- case N is
1358 -- when 1 => alpha
1359 -- when 2 | 3 => beta
1360 -- when others => gamma
1362 -- Here we know that N is initially 1 within alpha, but for beta and
1363 -- gamma, we do not know anything more about the initial value.
1365 if Is_Entity_Name (Exp) then
1366 Ent := Entity (Exp);
1368 if Ekind_In (Ent, E_Variable,
1369 E_In_Out_Parameter,
1370 E_Out_Parameter)
1371 then
1372 if List_Length (Choices) = 1
1373 and then Nkind (First (Choices)) in N_Subexpr
1374 and then Compile_Time_Known_Value (First (Choices))
1375 then
1376 Set_Current_Value (Entity (Exp), First (Choices));
1377 end if;
1379 Analyze_Statements (Statements (Alternative));
1381 -- After analyzing the case, set the current value to empty
1382 -- since we won't know what it is for the next alternative
1383 -- (unless reset by this same circuit), or after the case.
1385 Set_Current_Value (Entity (Exp), Empty);
1386 return;
1387 end if;
1388 end if;
1390 -- Case where expression is not an entity name of a variable
1392 Analyze_Statements (Statements (Alternative));
1393 end Process_Statements;
1395 -- Start of processing for Analyze_Case_Statement
1397 begin
1398 Unblocked_Exit_Count := 0;
1399 Exp := Expression (N);
1400 Analyze (Exp);
1402 -- The expression must be of any discrete type. In rare cases, the
1403 -- expander constructs a case statement whose expression has a private
1404 -- type whose full view is discrete. This can happen when generating
1405 -- a stream operation for a variant type after the type is frozen,
1406 -- when the partial of view of the type of the discriminant is private.
1407 -- In that case, use the full view to analyze case alternatives.
1409 if not Is_Overloaded (Exp)
1410 and then not Comes_From_Source (N)
1411 and then Is_Private_Type (Etype (Exp))
1412 and then Present (Full_View (Etype (Exp)))
1413 and then Is_Discrete_Type (Full_View (Etype (Exp)))
1414 then
1415 Resolve (Exp, Etype (Exp));
1416 Exp_Type := Full_View (Etype (Exp));
1418 else
1419 Analyze_And_Resolve (Exp, Any_Discrete);
1420 Exp_Type := Etype (Exp);
1421 end if;
1423 Check_Unset_Reference (Exp);
1424 Exp_Btype := Base_Type (Exp_Type);
1426 -- The expression must be of a discrete type which must be determinable
1427 -- independently of the context in which the expression occurs, but
1428 -- using the fact that the expression must be of a discrete type.
1429 -- Moreover, the type this expression must not be a character literal
1430 -- (which is always ambiguous) or, for Ada-83, a generic formal type.
1432 -- If error already reported by Resolve, nothing more to do
1434 if Exp_Btype = Any_Discrete or else Exp_Btype = Any_Type then
1435 return;
1437 elsif Exp_Btype = Any_Character then
1438 Error_Msg_N
1439 ("character literal as case expression is ambiguous", Exp);
1440 return;
1442 elsif Ada_Version = Ada_83
1443 and then (Is_Generic_Type (Exp_Btype)
1444 or else Is_Generic_Type (Root_Type (Exp_Btype)))
1445 then
1446 Error_Msg_N
1447 ("(Ada 83) case expression cannot be of a generic type", Exp);
1448 return;
1449 end if;
1451 -- If the case expression is a formal object of mode in out, then treat
1452 -- it as having a nonstatic subtype by forcing use of the base type
1453 -- (which has to get passed to Check_Case_Choices below). Also use base
1454 -- type when the case expression is parenthesized.
1456 if Paren_Count (Exp) > 0
1457 or else (Is_Entity_Name (Exp)
1458 and then Ekind (Entity (Exp)) = E_Generic_In_Out_Parameter)
1459 then
1460 Exp_Type := Exp_Btype;
1461 end if;
1463 -- Call instantiated procedures to analyzwe and check discrete choices
1465 Analyze_Choices (Alternatives (N), Exp_Type);
1466 Check_Choices (N, Alternatives (N), Exp_Type, Others_Present);
1468 -- Case statement with single OTHERS alternative not allowed in SPARK
1470 if Others_Present and then List_Length (Alternatives (N)) = 1 then
1471 Check_SPARK_05_Restriction
1472 ("OTHERS as unique case alternative is not allowed", N);
1473 end if;
1475 if Exp_Type = Universal_Integer and then not Others_Present then
1476 Error_Msg_N ("case on universal integer requires OTHERS choice", Exp);
1477 end if;
1479 -- If all our exits were blocked by unconditional transfers of control,
1480 -- then the entire CASE statement acts as an unconditional transfer of
1481 -- control, so treat it like one, and check unreachable code. Skip this
1482 -- test if we had serious errors preventing any statement analysis.
1484 if Unblocked_Exit_Count = 0 and then Statements_Analyzed then
1485 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1486 Check_Unreachable_Code (N);
1487 else
1488 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1489 end if;
1491 -- If the expander is active it will detect the case of a statically
1492 -- determined single alternative and remove warnings for the case, but
1493 -- if we are not doing expansion, that circuit won't be active. Here we
1494 -- duplicate the effect of removing warnings in the same way, so that
1495 -- we will get the same set of warnings in -gnatc mode.
1497 if not Expander_Active
1498 and then Compile_Time_Known_Value (Expression (N))
1499 and then Serious_Errors_Detected = 0
1500 then
1501 declare
1502 Chosen : constant Node_Id := Find_Static_Alternative (N);
1503 Alt : Node_Id;
1505 begin
1506 Alt := First (Alternatives (N));
1507 while Present (Alt) loop
1508 if Alt /= Chosen then
1509 Remove_Warning_Messages (Statements (Alt));
1510 end if;
1512 Next (Alt);
1513 end loop;
1514 end;
1515 end if;
1516 end Analyze_Case_Statement;
1518 ----------------------------
1519 -- Analyze_Exit_Statement --
1520 ----------------------------
1522 -- If the exit includes a name, it must be the name of a currently open
1523 -- loop. Otherwise there must be an innermost open loop on the stack, to
1524 -- which the statement implicitly refers.
1526 -- Additionally, in SPARK mode:
1528 -- The exit can only name the closest enclosing loop;
1530 -- An exit with a when clause must be directly contained in a loop;
1532 -- An exit without a when clause must be directly contained in an
1533 -- if-statement with no elsif or else, which is itself directly contained
1534 -- in a loop. The exit must be the last statement in the if-statement.
1536 procedure Analyze_Exit_Statement (N : Node_Id) is
1537 Target : constant Node_Id := Name (N);
1538 Cond : constant Node_Id := Condition (N);
1539 Scope_Id : Entity_Id := Empty; -- initialize to prevent warning
1540 U_Name : Entity_Id;
1541 Kind : Entity_Kind;
1543 begin
1544 if No (Cond) then
1545 Check_Unreachable_Code (N);
1546 end if;
1548 if Present (Target) then
1549 Analyze (Target);
1550 U_Name := Entity (Target);
1552 if not In_Open_Scopes (U_Name) or else Ekind (U_Name) /= E_Loop then
1553 Error_Msg_N ("invalid loop name in exit statement", N);
1554 return;
1556 else
1557 if Has_Loop_In_Inner_Open_Scopes (U_Name) then
1558 Check_SPARK_05_Restriction
1559 ("exit label must name the closest enclosing loop", N);
1560 end if;
1562 Set_Has_Exit (U_Name);
1563 end if;
1565 else
1566 U_Name := Empty;
1567 end if;
1569 for J in reverse 0 .. Scope_Stack.Last loop
1570 Scope_Id := Scope_Stack.Table (J).Entity;
1571 Kind := Ekind (Scope_Id);
1573 if Kind = E_Loop and then (No (Target) or else Scope_Id = U_Name) then
1574 Set_Has_Exit (Scope_Id);
1575 exit;
1577 elsif Kind = E_Block
1578 or else Kind = E_Loop
1579 or else Kind = E_Return_Statement
1580 then
1581 null;
1583 else
1584 Error_Msg_N
1585 ("cannot exit from program unit or accept statement", N);
1586 return;
1587 end if;
1588 end loop;
1590 -- Verify that if present the condition is a Boolean expression
1592 if Present (Cond) then
1593 Analyze_And_Resolve (Cond, Any_Boolean);
1594 Check_Unset_Reference (Cond);
1595 end if;
1597 -- In SPARK mode, verify that the exit statement respects the SPARK
1598 -- restrictions.
1600 if Present (Cond) then
1601 if Nkind (Parent (N)) /= N_Loop_Statement then
1602 Check_SPARK_05_Restriction
1603 ("exit with when clause must be directly in loop", N);
1604 end if;
1606 else
1607 if Nkind (Parent (N)) /= N_If_Statement then
1608 if Nkind (Parent (N)) = N_Elsif_Part then
1609 Check_SPARK_05_Restriction
1610 ("exit must be in IF without ELSIF", N);
1611 else
1612 Check_SPARK_05_Restriction ("exit must be directly in IF", N);
1613 end if;
1615 elsif Nkind (Parent (Parent (N))) /= N_Loop_Statement then
1616 Check_SPARK_05_Restriction
1617 ("exit must be in IF directly in loop", N);
1619 -- First test the presence of ELSE, so that an exit in an ELSE leads
1620 -- to an error mentioning the ELSE.
1622 elsif Present (Else_Statements (Parent (N))) then
1623 Check_SPARK_05_Restriction ("exit must be in IF without ELSE", N);
1625 -- An exit in an ELSIF does not reach here, as it would have been
1626 -- detected in the case (Nkind (Parent (N)) /= N_If_Statement).
1628 elsif Present (Elsif_Parts (Parent (N))) then
1629 Check_SPARK_05_Restriction ("exit must be in IF without ELSIF", N);
1630 end if;
1631 end if;
1633 -- Chain exit statement to associated loop entity
1635 Set_Next_Exit_Statement (N, First_Exit_Statement (Scope_Id));
1636 Set_First_Exit_Statement (Scope_Id, N);
1638 -- Since the exit may take us out of a loop, any previous assignment
1639 -- statement is not useless, so clear last assignment indications. It
1640 -- is OK to keep other current values, since if the exit statement
1641 -- does not exit, then the current values are still valid.
1643 Kill_Current_Values (Last_Assignment_Only => True);
1644 end Analyze_Exit_Statement;
1646 ----------------------------
1647 -- Analyze_Goto_Statement --
1648 ----------------------------
1650 procedure Analyze_Goto_Statement (N : Node_Id) is
1651 Label : constant Node_Id := Name (N);
1652 Scope_Id : Entity_Id;
1653 Label_Scope : Entity_Id;
1654 Label_Ent : Entity_Id;
1656 begin
1657 Check_SPARK_05_Restriction ("goto statement is not allowed", N);
1659 -- Actual semantic checks
1661 Check_Unreachable_Code (N);
1662 Kill_Current_Values (Last_Assignment_Only => True);
1664 Analyze (Label);
1665 Label_Ent := Entity (Label);
1667 -- Ignore previous error
1669 if Label_Ent = Any_Id then
1670 Check_Error_Detected;
1671 return;
1673 -- We just have a label as the target of a goto
1675 elsif Ekind (Label_Ent) /= E_Label then
1676 Error_Msg_N ("target of goto statement must be a label", Label);
1677 return;
1679 -- Check that the target of the goto is reachable according to Ada
1680 -- scoping rules. Note: the special gotos we generate for optimizing
1681 -- local handling of exceptions would violate these rules, but we mark
1682 -- such gotos as analyzed when built, so this code is never entered.
1684 elsif not Reachable (Label_Ent) then
1685 Error_Msg_N ("target of goto statement is not reachable", Label);
1686 return;
1687 end if;
1689 -- Here if goto passes initial validity checks
1691 Label_Scope := Enclosing_Scope (Label_Ent);
1693 for J in reverse 0 .. Scope_Stack.Last loop
1694 Scope_Id := Scope_Stack.Table (J).Entity;
1696 if Label_Scope = Scope_Id
1697 or else not Ekind_In (Scope_Id, E_Block, E_Loop, E_Return_Statement)
1698 then
1699 if Scope_Id /= Label_Scope then
1700 Error_Msg_N
1701 ("cannot exit from program unit or accept statement", N);
1702 end if;
1704 return;
1705 end if;
1706 end loop;
1708 raise Program_Error;
1709 end Analyze_Goto_Statement;
1711 --------------------------
1712 -- Analyze_If_Statement --
1713 --------------------------
1715 -- A special complication arises in the analysis of if statements
1717 -- The expander has circuitry to completely delete code that it can tell
1718 -- will not be executed (as a result of compile time known conditions). In
1719 -- the analyzer, we ensure that code that will be deleted in this manner
1720 -- is analyzed but not expanded. This is obviously more efficient, but
1721 -- more significantly, difficulties arise if code is expanded and then
1722 -- eliminated (e.g. exception table entries disappear). Similarly, itypes
1723 -- generated in deleted code must be frozen from start, because the nodes
1724 -- on which they depend will not be available at the freeze point.
1726 procedure Analyze_If_Statement (N : Node_Id) is
1727 E : Node_Id;
1729 Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
1730 -- Recursively save value of this global, will be restored on exit
1732 Save_In_Deleted_Code : Boolean;
1734 Del : Boolean := False;
1735 -- This flag gets set True if a True condition has been found, which
1736 -- means that remaining ELSE/ELSIF parts are deleted.
1738 procedure Analyze_Cond_Then (Cnode : Node_Id);
1739 -- This is applied to either the N_If_Statement node itself or to an
1740 -- N_Elsif_Part node. It deals with analyzing the condition and the THEN
1741 -- statements associated with it.
1743 -----------------------
1744 -- Analyze_Cond_Then --
1745 -----------------------
1747 procedure Analyze_Cond_Then (Cnode : Node_Id) is
1748 Cond : constant Node_Id := Condition (Cnode);
1749 Tstm : constant List_Id := Then_Statements (Cnode);
1751 begin
1752 Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
1753 Analyze_And_Resolve (Cond, Any_Boolean);
1754 Check_Unset_Reference (Cond);
1755 Set_Current_Value_Condition (Cnode);
1757 -- If already deleting, then just analyze then statements
1759 if Del then
1760 Analyze_Statements (Tstm);
1762 -- Compile time known value, not deleting yet
1764 elsif Compile_Time_Known_Value (Cond) then
1765 Save_In_Deleted_Code := In_Deleted_Code;
1767 -- If condition is True, then analyze the THEN statements and set
1768 -- no expansion for ELSE and ELSIF parts.
1770 if Is_True (Expr_Value (Cond)) then
1771 Analyze_Statements (Tstm);
1772 Del := True;
1773 Expander_Mode_Save_And_Set (False);
1774 In_Deleted_Code := True;
1776 -- If condition is False, analyze THEN with expansion off
1778 else -- Is_False (Expr_Value (Cond))
1779 Expander_Mode_Save_And_Set (False);
1780 In_Deleted_Code := True;
1781 Analyze_Statements (Tstm);
1782 Expander_Mode_Restore;
1783 In_Deleted_Code := Save_In_Deleted_Code;
1784 end if;
1786 -- Not known at compile time, not deleting, normal analysis
1788 else
1789 Analyze_Statements (Tstm);
1790 end if;
1791 end Analyze_Cond_Then;
1793 -- Start of processing for Analyze_If_Statement
1795 begin
1796 -- Initialize exit count for else statements. If there is no else part,
1797 -- this count will stay non-zero reflecting the fact that the uncovered
1798 -- else case is an unblocked exit.
1800 Unblocked_Exit_Count := 1;
1801 Analyze_Cond_Then (N);
1803 -- Now to analyze the elsif parts if any are present
1805 if Present (Elsif_Parts (N)) then
1806 E := First (Elsif_Parts (N));
1807 while Present (E) loop
1808 Analyze_Cond_Then (E);
1809 Next (E);
1810 end loop;
1811 end if;
1813 if Present (Else_Statements (N)) then
1814 Analyze_Statements (Else_Statements (N));
1815 end if;
1817 -- If all our exits were blocked by unconditional transfers of control,
1818 -- then the entire IF statement acts as an unconditional transfer of
1819 -- control, so treat it like one, and check unreachable code.
1821 if Unblocked_Exit_Count = 0 then
1822 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1823 Check_Unreachable_Code (N);
1824 else
1825 Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
1826 end if;
1828 if Del then
1829 Expander_Mode_Restore;
1830 In_Deleted_Code := Save_In_Deleted_Code;
1831 end if;
1833 if not Expander_Active
1834 and then Compile_Time_Known_Value (Condition (N))
1835 and then Serious_Errors_Detected = 0
1836 then
1837 if Is_True (Expr_Value (Condition (N))) then
1838 Remove_Warning_Messages (Else_Statements (N));
1840 if Present (Elsif_Parts (N)) then
1841 E := First (Elsif_Parts (N));
1842 while Present (E) loop
1843 Remove_Warning_Messages (Then_Statements (E));
1844 Next (E);
1845 end loop;
1846 end if;
1848 else
1849 Remove_Warning_Messages (Then_Statements (N));
1850 end if;
1851 end if;
1853 -- Warn on redundant if statement that has no effect
1855 -- Note, we could also check empty ELSIF parts ???
1857 if Warn_On_Redundant_Constructs
1859 -- If statement must be from source
1861 and then Comes_From_Source (N)
1863 -- Condition must not have obvious side effect
1865 and then Has_No_Obvious_Side_Effects (Condition (N))
1867 -- No elsif parts of else part
1869 and then No (Elsif_Parts (N))
1870 and then No (Else_Statements (N))
1872 -- Then must be a single null statement
1874 and then List_Length (Then_Statements (N)) = 1
1875 then
1876 -- Go to original node, since we may have rewritten something as
1877 -- a null statement (e.g. a case we could figure the outcome of).
1879 declare
1880 T : constant Node_Id := First (Then_Statements (N));
1881 S : constant Node_Id := Original_Node (T);
1883 begin
1884 if Comes_From_Source (S) and then Nkind (S) = N_Null_Statement then
1885 Error_Msg_N ("if statement has no effect?r?", N);
1886 end if;
1887 end;
1888 end if;
1889 end Analyze_If_Statement;
1891 ----------------------------------------
1892 -- Analyze_Implicit_Label_Declaration --
1893 ----------------------------------------
1895 -- An implicit label declaration is generated in the innermost enclosing
1896 -- declarative part. This is done for labels, and block and loop names.
1898 -- Note: any changes in this routine may need to be reflected in
1899 -- Analyze_Label_Entity.
1901 procedure Analyze_Implicit_Label_Declaration (N : Node_Id) is
1902 Id : constant Node_Id := Defining_Identifier (N);
1903 begin
1904 Enter_Name (Id);
1905 Set_Ekind (Id, E_Label);
1906 Set_Etype (Id, Standard_Void_Type);
1907 Set_Enclosing_Scope (Id, Current_Scope);
1908 end Analyze_Implicit_Label_Declaration;
1910 ------------------------------
1911 -- Analyze_Iteration_Scheme --
1912 ------------------------------
1914 procedure Analyze_Iteration_Scheme (N : Node_Id) is
1915 Cond : Node_Id;
1916 Iter_Spec : Node_Id;
1917 Loop_Spec : Node_Id;
1919 begin
1920 -- For an infinite loop, there is no iteration scheme
1922 if No (N) then
1923 return;
1924 end if;
1926 Cond := Condition (N);
1927 Iter_Spec := Iterator_Specification (N);
1928 Loop_Spec := Loop_Parameter_Specification (N);
1930 if Present (Cond) then
1931 Analyze_And_Resolve (Cond, Any_Boolean);
1932 Check_Unset_Reference (Cond);
1933 Set_Current_Value_Condition (N);
1935 elsif Present (Iter_Spec) then
1936 Analyze_Iterator_Specification (Iter_Spec);
1938 else
1939 Analyze_Loop_Parameter_Specification (Loop_Spec);
1940 end if;
1941 end Analyze_Iteration_Scheme;
1943 ------------------------------------
1944 -- Analyze_Iterator_Specification --
1945 ------------------------------------
1947 procedure Analyze_Iterator_Specification (N : Node_Id) is
1948 procedure Check_Reverse_Iteration (Typ : Entity_Id);
1949 -- For an iteration over a container, if the loop carries the Reverse
1950 -- indicator, verify that the container type has an Iterate aspect that
1951 -- implements the reversible iterator interface.
1953 function Get_Cursor_Type (Typ : Entity_Id) return Entity_Id;
1954 -- For containers with Iterator and related aspects, the cursor is
1955 -- obtained by locating an entity with the proper name in the scope
1956 -- of the type.
1958 -----------------------------
1959 -- Check_Reverse_Iteration --
1960 -----------------------------
1962 procedure Check_Reverse_Iteration (Typ : Entity_Id) is
1963 begin
1964 if Reverse_Present (N) then
1965 if Is_Array_Type (Typ)
1966 or else Is_Reversible_Iterator (Typ)
1967 or else
1968 (Present (Find_Aspect (Typ, Aspect_Iterable))
1969 and then
1970 Present
1971 (Get_Iterable_Type_Primitive (Typ, Name_Previous)))
1972 then
1973 null;
1974 else
1975 Error_Msg_NE
1976 ("container type does not support reverse iteration", N, Typ);
1977 end if;
1978 end if;
1979 end Check_Reverse_Iteration;
1981 ---------------------
1982 -- Get_Cursor_Type --
1983 ---------------------
1985 function Get_Cursor_Type (Typ : Entity_Id) return Entity_Id is
1986 Ent : Entity_Id;
1988 begin
1989 -- If iterator type is derived, the cursor is declared in the scope
1990 -- of the parent type.
1992 if Is_Derived_Type (Typ) then
1993 Ent := First_Entity (Scope (Etype (Typ)));
1994 else
1995 Ent := First_Entity (Scope (Typ));
1996 end if;
1998 while Present (Ent) loop
1999 exit when Chars (Ent) = Name_Cursor;
2000 Next_Entity (Ent);
2001 end loop;
2003 if No (Ent) then
2004 return Any_Type;
2005 end if;
2007 -- The cursor is the target of generated assignments in the
2008 -- loop, and cannot have a limited type.
2010 if Is_Limited_Type (Etype (Ent)) then
2011 Error_Msg_N ("cursor type cannot be limited", N);
2012 end if;
2014 return Etype (Ent);
2015 end Get_Cursor_Type;
2017 -- Local variables
2019 Def_Id : constant Node_Id := Defining_Identifier (N);
2020 Iter_Name : constant Node_Id := Name (N);
2021 Loc : constant Source_Ptr := Sloc (N);
2022 Subt : constant Node_Id := Subtype_Indication (N);
2024 Bas : Entity_Id := Empty; -- initialize to prevent warning
2025 Typ : Entity_Id;
2027 -- Start of processing for Analyze_Iterator_Specification
2029 begin
2030 Enter_Name (Def_Id);
2032 -- AI12-0151 specifies that when the subtype indication is present, it
2033 -- must statically match the type of the array or container element.
2034 -- To simplify this check, we introduce a subtype declaration with the
2035 -- given subtype indication when it carries a constraint, and rewrite
2036 -- the original as a reference to the created subtype entity.
2038 if Present (Subt) then
2039 if Nkind (Subt) = N_Subtype_Indication then
2040 declare
2041 S : constant Entity_Id := Make_Temporary (Sloc (Subt), 'S');
2042 Decl : constant Node_Id :=
2043 Make_Subtype_Declaration (Loc,
2044 Defining_Identifier => S,
2045 Subtype_Indication => New_Copy_Tree (Subt));
2046 begin
2047 Insert_Before (Parent (Parent (N)), Decl);
2048 Analyze (Decl);
2049 Rewrite (Subt, New_Occurrence_Of (S, Sloc (Subt)));
2050 end;
2051 else
2052 Analyze (Subt);
2053 end if;
2055 -- Save entity of subtype indication for subsequent check
2057 Bas := Entity (Subt);
2058 end if;
2060 Preanalyze_Range (Iter_Name);
2062 -- Set the kind of the loop variable, which is not visible within the
2063 -- iterator name.
2065 Set_Ekind (Def_Id, E_Variable);
2067 -- Provide a link between the iterator variable and the container, for
2068 -- subsequent use in cross-reference and modification information.
2070 if Of_Present (N) then
2071 Set_Related_Expression (Def_Id, Iter_Name);
2073 -- For a container, the iterator is specified through the aspect
2075 if not Is_Array_Type (Etype (Iter_Name)) then
2076 declare
2077 Iterator : constant Entity_Id :=
2078 Find_Value_Of_Aspect
2079 (Etype (Iter_Name), Aspect_Default_Iterator);
2081 I : Interp_Index;
2082 It : Interp;
2084 begin
2085 if No (Iterator) then
2086 null; -- error reported below
2088 elsif not Is_Overloaded (Iterator) then
2089 Check_Reverse_Iteration (Etype (Iterator));
2091 -- If Iterator is overloaded, use reversible iterator if one is
2092 -- available.
2094 elsif Is_Overloaded (Iterator) then
2095 Get_First_Interp (Iterator, I, It);
2096 while Present (It.Nam) loop
2097 if Ekind (It.Nam) = E_Function
2098 and then Is_Reversible_Iterator (Etype (It.Nam))
2099 then
2100 Set_Etype (Iterator, It.Typ);
2101 Set_Entity (Iterator, It.Nam);
2102 exit;
2103 end if;
2105 Get_Next_Interp (I, It);
2106 end loop;
2108 Check_Reverse_Iteration (Etype (Iterator));
2109 end if;
2110 end;
2111 end if;
2112 end if;
2114 -- If the domain of iteration is an expression, create a declaration for
2115 -- it, so that finalization actions are introduced outside of the loop.
2116 -- The declaration must be a renaming because the body of the loop may
2117 -- assign to elements.
2119 if not Is_Entity_Name (Iter_Name)
2121 -- When the context is a quantified expression, the renaming
2122 -- declaration is delayed until the expansion phase if we are
2123 -- doing expansion.
2125 and then (Nkind (Parent (N)) /= N_Quantified_Expression
2126 or else Operating_Mode = Check_Semantics)
2128 -- Do not perform this expansion for ASIS and when expansion is
2129 -- disabled, where the temporary may hide the transformation of a
2130 -- selected component into a prefixed function call, and references
2131 -- need to see the original expression.
2133 and then Expander_Active
2134 then
2135 declare
2136 Id : constant Entity_Id := Make_Temporary (Loc, 'R', Iter_Name);
2137 Decl : Node_Id;
2138 Act_S : Node_Id;
2140 begin
2142 -- If the domain of iteration is an array component that depends
2143 -- on a discriminant, create actual subtype for it. Pre-analysis
2144 -- does not generate the actual subtype of a selected component.
2146 if Nkind (Iter_Name) = N_Selected_Component
2147 and then Is_Array_Type (Etype (Iter_Name))
2148 then
2149 Act_S :=
2150 Build_Actual_Subtype_Of_Component
2151 (Etype (Selector_Name (Iter_Name)), Iter_Name);
2152 Insert_Action (N, Act_S);
2154 if Present (Act_S) then
2155 Typ := Defining_Identifier (Act_S);
2156 else
2157 Typ := Etype (Iter_Name);
2158 end if;
2160 else
2161 Typ := Etype (Iter_Name);
2163 -- Verify that the expression produces an iterator
2165 if not Of_Present (N) and then not Is_Iterator (Typ)
2166 and then not Is_Array_Type (Typ)
2167 and then No (Find_Aspect (Typ, Aspect_Iterable))
2168 then
2169 Error_Msg_N
2170 ("expect object that implements iterator interface",
2171 Iter_Name);
2172 end if;
2173 end if;
2175 -- Protect against malformed iterator
2177 if Typ = Any_Type then
2178 Error_Msg_N ("invalid expression in loop iterator", Iter_Name);
2179 return;
2180 end if;
2182 if not Of_Present (N) then
2183 Check_Reverse_Iteration (Typ);
2184 end if;
2186 -- The name in the renaming declaration may be a function call.
2187 -- Indicate that it does not come from source, to suppress
2188 -- spurious warnings on renamings of parameterless functions,
2189 -- a common enough idiom in user-defined iterators.
2191 Decl :=
2192 Make_Object_Renaming_Declaration (Loc,
2193 Defining_Identifier => Id,
2194 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
2195 Name =>
2196 New_Copy_Tree (Iter_Name, New_Sloc => Loc));
2198 Insert_Actions (Parent (Parent (N)), New_List (Decl));
2199 Rewrite (Name (N), New_Occurrence_Of (Id, Loc));
2200 Set_Etype (Id, Typ);
2201 Set_Etype (Name (N), Typ);
2202 end;
2204 -- Container is an entity or an array with uncontrolled components, or
2205 -- else it is a container iterator given by a function call, typically
2206 -- called Iterate in the case of predefined containers, even though
2207 -- Iterate is not a reserved name. What matters is that the return type
2208 -- of the function is an iterator type.
2210 elsif Is_Entity_Name (Iter_Name) then
2211 Analyze (Iter_Name);
2213 if Nkind (Iter_Name) = N_Function_Call then
2214 declare
2215 C : constant Node_Id := Name (Iter_Name);
2216 I : Interp_Index;
2217 It : Interp;
2219 begin
2220 if not Is_Overloaded (Iter_Name) then
2221 Resolve (Iter_Name, Etype (C));
2223 else
2224 Get_First_Interp (C, I, It);
2225 while It.Typ /= Empty loop
2226 if Reverse_Present (N) then
2227 if Is_Reversible_Iterator (It.Typ) then
2228 Resolve (Iter_Name, It.Typ);
2229 exit;
2230 end if;
2232 elsif Is_Iterator (It.Typ) then
2233 Resolve (Iter_Name, It.Typ);
2234 exit;
2235 end if;
2237 Get_Next_Interp (I, It);
2238 end loop;
2239 end if;
2240 end;
2242 -- Domain of iteration is not overloaded
2244 else
2245 Resolve (Iter_Name, Etype (Iter_Name));
2246 end if;
2248 if not Of_Present (N) then
2249 Check_Reverse_Iteration (Etype (Iter_Name));
2250 end if;
2251 end if;
2253 -- Get base type of container, for proper retrieval of Cursor type
2254 -- and primitive operations.
2256 Typ := Base_Type (Etype (Iter_Name));
2258 if Is_Array_Type (Typ) then
2259 if Of_Present (N) then
2260 Set_Etype (Def_Id, Component_Type (Typ));
2262 -- The loop variable is aliased if the array components are
2263 -- aliased.
2265 Set_Is_Aliased (Def_Id, Has_Aliased_Components (Typ));
2267 -- AI12-0047 stipulates that the domain (array or container)
2268 -- cannot be a component that depends on a discriminant if the
2269 -- enclosing object is mutable, to prevent a modification of the
2270 -- dowmain of iteration in the course of an iteration.
2272 -- If the object is an expression it has been captured in a
2273 -- temporary, so examine original node.
2275 if Nkind (Original_Node (Iter_Name)) = N_Selected_Component
2276 and then Is_Dependent_Component_Of_Mutable_Object
2277 (Original_Node (Iter_Name))
2278 then
2279 Error_Msg_N
2280 ("iterable name cannot be a discriminant-dependent "
2281 & "component of a mutable object", N);
2282 end if;
2284 if Present (Subt)
2285 and then
2286 (Base_Type (Bas) /= Base_Type (Component_Type (Typ))
2287 or else
2288 not Subtypes_Statically_Match (Bas, Component_Type (Typ)))
2289 then
2290 Error_Msg_N
2291 ("subtype indication does not match component type", Subt);
2292 end if;
2294 -- Here we have a missing Range attribute
2296 else
2297 Error_Msg_N
2298 ("missing Range attribute in iteration over an array", N);
2300 -- In Ada 2012 mode, this may be an attempt at an iterator
2302 if Ada_Version >= Ada_2012 then
2303 Error_Msg_NE
2304 ("\if& is meant to designate an element of the array, use OF",
2305 N, Def_Id);
2306 end if;
2308 -- Prevent cascaded errors
2310 Set_Ekind (Def_Id, E_Loop_Parameter);
2311 Set_Etype (Def_Id, Etype (First_Index (Typ)));
2312 end if;
2314 -- Check for type error in iterator
2316 elsif Typ = Any_Type then
2317 return;
2319 -- Iteration over a container
2321 else
2322 Set_Ekind (Def_Id, E_Loop_Parameter);
2323 Error_Msg_Ada_2012_Feature ("container iterator", Sloc (N));
2325 -- OF present
2327 if Of_Present (N) then
2328 if Has_Aspect (Typ, Aspect_Iterable) then
2329 declare
2330 Elt : constant Entity_Id :=
2331 Get_Iterable_Type_Primitive (Typ, Name_Element);
2332 begin
2333 if No (Elt) then
2334 Error_Msg_N
2335 ("missing Element primitive for iteration", N);
2336 else
2337 Set_Etype (Def_Id, Etype (Elt));
2338 Check_Reverse_Iteration (Typ);
2339 end if;
2340 end;
2342 -- For a predefined container, The type of the loop variable is
2343 -- the Iterator_Element aspect of the container type.
2345 else
2346 declare
2347 Element : constant Entity_Id :=
2348 Find_Value_Of_Aspect
2349 (Typ, Aspect_Iterator_Element);
2350 Iterator : constant Entity_Id :=
2351 Find_Value_Of_Aspect
2352 (Typ, Aspect_Default_Iterator);
2353 Orig_Iter_Name : constant Node_Id :=
2354 Original_Node (Iter_Name);
2355 Cursor_Type : Entity_Id;
2357 begin
2358 if No (Element) then
2359 Error_Msg_NE ("cannot iterate over&", N, Typ);
2360 return;
2362 else
2363 Set_Etype (Def_Id, Entity (Element));
2364 Cursor_Type := Get_Cursor_Type (Typ);
2365 pragma Assert (Present (Cursor_Type));
2367 -- If subtype indication was given, verify that it covers
2368 -- the element type of the container.
2370 if Present (Subt)
2371 and then (not Covers (Bas, Etype (Def_Id))
2372 or else not Subtypes_Statically_Match
2373 (Bas, Etype (Def_Id)))
2374 then
2375 Error_Msg_N
2376 ("subtype indication does not match element type",
2377 Subt);
2378 end if;
2380 -- If the container has a variable indexing aspect, the
2381 -- element is a variable and is modifiable in the loop.
2383 if Has_Aspect (Typ, Aspect_Variable_Indexing) then
2384 Set_Ekind (Def_Id, E_Variable);
2385 end if;
2387 -- If the container is a constant, iterating over it
2388 -- requires a Constant_Indexing operation.
2390 if not Is_Variable (Iter_Name)
2391 and then not Has_Aspect (Typ, Aspect_Constant_Indexing)
2392 then
2393 Error_Msg_N
2394 ("iteration over constant container require "
2395 & "constant_indexing aspect", N);
2397 -- The Iterate function may have an in_out parameter,
2398 -- and a constant container is thus illegal.
2400 elsif Present (Iterator)
2401 and then Ekind (Entity (Iterator)) = E_Function
2402 and then Ekind (First_Formal (Entity (Iterator))) /=
2403 E_In_Parameter
2404 and then not Is_Variable (Iter_Name)
2405 then
2406 Error_Msg_N ("variable container expected", N);
2407 end if;
2409 -- Detect a case where the iterator denotes a component
2410 -- of a mutable object which depends on a discriminant.
2411 -- Note that the iterator may denote a function call in
2412 -- qualified form, in which case this check should not
2413 -- be performed.
2415 if Nkind (Orig_Iter_Name) = N_Selected_Component
2416 and then
2417 Present (Entity (Selector_Name (Orig_Iter_Name)))
2418 and then Ekind_In
2419 (Entity (Selector_Name (Orig_Iter_Name)),
2420 E_Component,
2421 E_Discriminant)
2422 and then Is_Dependent_Component_Of_Mutable_Object
2423 (Orig_Iter_Name)
2424 then
2425 Error_Msg_N
2426 ("container cannot be a discriminant-dependent "
2427 & "component of a mutable object", N);
2428 end if;
2429 end if;
2430 end;
2431 end if;
2433 -- IN iterator, domain is a range, or a call to Iterate function
2435 else
2436 -- For an iteration of the form IN, the name must denote an
2437 -- iterator, typically the result of a call to Iterate. Give a
2438 -- useful error message when the name is a container by itself.
2440 -- The type may be a formal container type, which has to have
2441 -- an Iterable aspect detailing the required primitives.
2443 if Is_Entity_Name (Original_Node (Name (N)))
2444 and then not Is_Iterator (Typ)
2445 then
2446 if Has_Aspect (Typ, Aspect_Iterable) then
2447 null;
2449 elsif not Has_Aspect (Typ, Aspect_Iterator_Element) then
2450 Error_Msg_NE
2451 ("cannot iterate over&", Name (N), Typ);
2452 else
2453 Error_Msg_N
2454 ("name must be an iterator, not a container", Name (N));
2455 end if;
2457 if Has_Aspect (Typ, Aspect_Iterable) then
2458 null;
2459 else
2460 Error_Msg_NE
2461 ("\to iterate directly over the elements of a container, "
2462 & "write `of &`", Name (N), Original_Node (Name (N)));
2464 -- No point in continuing analysis of iterator spec
2466 return;
2467 end if;
2468 end if;
2470 -- If the name is a call (typically prefixed) to some Iterate
2471 -- function, it has been rewritten as an object declaration.
2472 -- If that object is a selected component, verify that it is not
2473 -- a component of an unconstrained mutable object.
2475 if Nkind (Iter_Name) = N_Identifier
2476 or else (not Expander_Active and Comes_From_Source (Iter_Name))
2477 then
2478 declare
2479 Orig_Node : constant Node_Id := Original_Node (Iter_Name);
2480 Iter_Kind : constant Node_Kind := Nkind (Orig_Node);
2481 Obj : Node_Id;
2483 begin
2484 if Iter_Kind = N_Selected_Component then
2485 Obj := Prefix (Orig_Node);
2487 elsif Iter_Kind = N_Function_Call then
2488 Obj := First_Actual (Orig_Node);
2490 -- If neither, the name comes from source
2492 else
2493 Obj := Iter_Name;
2494 end if;
2496 if Nkind (Obj) = N_Selected_Component
2497 and then Is_Dependent_Component_Of_Mutable_Object (Obj)
2498 then
2499 Error_Msg_N
2500 ("container cannot be a discriminant-dependent "
2501 & "component of a mutable object", N);
2502 end if;
2503 end;
2504 end if;
2506 -- The result type of Iterate function is the classwide type of
2507 -- the interface parent. We need the specific Cursor type defined
2508 -- in the container package. We obtain it by name for a predefined
2509 -- container, or through the Iterable aspect for a formal one.
2511 if Has_Aspect (Typ, Aspect_Iterable) then
2512 Set_Etype (Def_Id,
2513 Get_Cursor_Type
2514 (Parent (Find_Value_Of_Aspect (Typ, Aspect_Iterable)),
2515 Typ));
2517 else
2518 Set_Etype (Def_Id, Get_Cursor_Type (Typ));
2519 Check_Reverse_Iteration (Etype (Iter_Name));
2520 end if;
2522 end if;
2523 end if;
2524 end Analyze_Iterator_Specification;
2526 -------------------
2527 -- Analyze_Label --
2528 -------------------
2530 -- Note: the semantic work required for analyzing labels (setting them as
2531 -- reachable) was done in a prepass through the statements in the block,
2532 -- so that forward gotos would be properly handled. See Analyze_Statements
2533 -- for further details. The only processing required here is to deal with
2534 -- optimizations that depend on an assumption of sequential control flow,
2535 -- since of course the occurrence of a label breaks this assumption.
2537 procedure Analyze_Label (N : Node_Id) is
2538 pragma Warnings (Off, N);
2539 begin
2540 Kill_Current_Values;
2541 end Analyze_Label;
2543 --------------------------
2544 -- Analyze_Label_Entity --
2545 --------------------------
2547 procedure Analyze_Label_Entity (E : Entity_Id) is
2548 begin
2549 Set_Ekind (E, E_Label);
2550 Set_Etype (E, Standard_Void_Type);
2551 Set_Enclosing_Scope (E, Current_Scope);
2552 Set_Reachable (E, True);
2553 end Analyze_Label_Entity;
2555 ------------------------------------------
2556 -- Analyze_Loop_Parameter_Specification --
2557 ------------------------------------------
2559 procedure Analyze_Loop_Parameter_Specification (N : Node_Id) is
2560 Loop_Nod : constant Node_Id := Parent (Parent (N));
2562 procedure Check_Controlled_Array_Attribute (DS : Node_Id);
2563 -- If the bounds are given by a 'Range reference on a function call
2564 -- that returns a controlled array, introduce an explicit declaration
2565 -- to capture the bounds, so that the function result can be finalized
2566 -- in timely fashion.
2568 procedure Check_Predicate_Use (T : Entity_Id);
2569 -- Diagnose Attempt to iterate through non-static predicate. Note that
2570 -- a type with inherited predicates may have both static and dynamic
2571 -- forms. In this case it is not sufficent to check the static predicate
2572 -- function only, look for a dynamic predicate aspect as well.
2574 function Has_Call_Using_Secondary_Stack (N : Node_Id) return Boolean;
2575 -- N is the node for an arbitrary construct. This function searches the
2576 -- construct N to see if any expressions within it contain function
2577 -- calls that use the secondary stack, returning True if any such call
2578 -- is found, and False otherwise.
2580 procedure Process_Bounds (R : Node_Id);
2581 -- If the iteration is given by a range, create temporaries and
2582 -- assignment statements block to capture the bounds and perform
2583 -- required finalization actions in case a bound includes a function
2584 -- call that uses the temporary stack. We first pre-analyze a copy of
2585 -- the range in order to determine the expected type, and analyze and
2586 -- resolve the original bounds.
2588 --------------------------------------
2589 -- Check_Controlled_Array_Attribute --
2590 --------------------------------------
2592 procedure Check_Controlled_Array_Attribute (DS : Node_Id) is
2593 begin
2594 if Nkind (DS) = N_Attribute_Reference
2595 and then Is_Entity_Name (Prefix (DS))
2596 and then Ekind (Entity (Prefix (DS))) = E_Function
2597 and then Is_Array_Type (Etype (Entity (Prefix (DS))))
2598 and then
2599 Is_Controlled (Component_Type (Etype (Entity (Prefix (DS)))))
2600 and then Expander_Active
2601 then
2602 declare
2603 Loc : constant Source_Ptr := Sloc (N);
2604 Arr : constant Entity_Id := Etype (Entity (Prefix (DS)));
2605 Indx : constant Entity_Id :=
2606 Base_Type (Etype (First_Index (Arr)));
2607 Subt : constant Entity_Id := Make_Temporary (Loc, 'S');
2608 Decl : Node_Id;
2610 begin
2611 Decl :=
2612 Make_Subtype_Declaration (Loc,
2613 Defining_Identifier => Subt,
2614 Subtype_Indication =>
2615 Make_Subtype_Indication (Loc,
2616 Subtype_Mark => New_Occurrence_Of (Indx, Loc),
2617 Constraint =>
2618 Make_Range_Constraint (Loc, Relocate_Node (DS))));
2619 Insert_Before (Loop_Nod, Decl);
2620 Analyze (Decl);
2622 Rewrite (DS,
2623 Make_Attribute_Reference (Loc,
2624 Prefix => New_Occurrence_Of (Subt, Loc),
2625 Attribute_Name => Attribute_Name (DS)));
2627 Analyze (DS);
2628 end;
2629 end if;
2630 end Check_Controlled_Array_Attribute;
2632 -------------------------
2633 -- Check_Predicate_Use --
2634 -------------------------
2636 procedure Check_Predicate_Use (T : Entity_Id) is
2637 begin
2638 -- A predicated subtype is illegal in loops and related constructs
2639 -- if the predicate is not static, or if it is a non-static subtype
2640 -- of a statically predicated subtype.
2642 if Is_Discrete_Type (T)
2643 and then Has_Predicates (T)
2644 and then (not Has_Static_Predicate (T)
2645 or else not Is_Static_Subtype (T)
2646 or else Has_Dynamic_Predicate_Aspect (T))
2647 then
2648 -- Seems a confusing message for the case of a static predicate
2649 -- with a non-static subtype???
2651 Bad_Predicated_Subtype_Use
2652 ("cannot use subtype& with non-static predicate for loop "
2653 & "iteration", Discrete_Subtype_Definition (N),
2654 T, Suggest_Static => True);
2656 elsif Inside_A_Generic
2657 and then Is_Generic_Formal (T)
2658 and then Is_Discrete_Type (T)
2659 then
2660 Set_No_Dynamic_Predicate_On_Actual (T);
2661 end if;
2662 end Check_Predicate_Use;
2664 ------------------------------------
2665 -- Has_Call_Using_Secondary_Stack --
2666 ------------------------------------
2668 function Has_Call_Using_Secondary_Stack (N : Node_Id) return Boolean is
2670 function Check_Call (N : Node_Id) return Traverse_Result;
2671 -- Check if N is a function call which uses the secondary stack
2673 ----------------
2674 -- Check_Call --
2675 ----------------
2677 function Check_Call (N : Node_Id) return Traverse_Result is
2678 Nam : Node_Id;
2679 Subp : Entity_Id;
2680 Return_Typ : Entity_Id;
2682 begin
2683 if Nkind (N) = N_Function_Call then
2684 Nam := Name (N);
2686 -- Call using access to subprogram with explicit dereference
2688 if Nkind (Nam) = N_Explicit_Dereference then
2689 Subp := Etype (Nam);
2691 -- Call using a selected component notation or Ada 2005 object
2692 -- operation notation
2694 elsif Nkind (Nam) = N_Selected_Component then
2695 Subp := Entity (Selector_Name (Nam));
2697 -- Common case
2699 else
2700 Subp := Entity (Nam);
2701 end if;
2703 Return_Typ := Etype (Subp);
2705 if Is_Composite_Type (Return_Typ)
2706 and then not Is_Constrained (Return_Typ)
2707 then
2708 return Abandon;
2710 elsif Sec_Stack_Needed_For_Return (Subp) then
2711 return Abandon;
2712 end if;
2713 end if;
2715 -- Continue traversing the tree
2717 return OK;
2718 end Check_Call;
2720 function Check_Calls is new Traverse_Func (Check_Call);
2722 -- Start of processing for Has_Call_Using_Secondary_Stack
2724 begin
2725 return Check_Calls (N) = Abandon;
2726 end Has_Call_Using_Secondary_Stack;
2728 --------------------
2729 -- Process_Bounds --
2730 --------------------
2732 procedure Process_Bounds (R : Node_Id) is
2733 Loc : constant Source_Ptr := Sloc (N);
2735 function One_Bound
2736 (Original_Bound : Node_Id;
2737 Analyzed_Bound : Node_Id;
2738 Typ : Entity_Id) return Node_Id;
2739 -- Capture value of bound and return captured value
2741 ---------------
2742 -- One_Bound --
2743 ---------------
2745 function One_Bound
2746 (Original_Bound : Node_Id;
2747 Analyzed_Bound : Node_Id;
2748 Typ : Entity_Id) return Node_Id
2750 Assign : Node_Id;
2751 Decl : Node_Id;
2752 Id : Entity_Id;
2754 begin
2755 -- If the bound is a constant or an object, no need for a separate
2756 -- declaration. If the bound is the result of previous expansion
2757 -- it is already analyzed and should not be modified. Note that
2758 -- the Bound will be resolved later, if needed, as part of the
2759 -- call to Make_Index (literal bounds may need to be resolved to
2760 -- type Integer).
2762 if Analyzed (Original_Bound) then
2763 return Original_Bound;
2765 elsif Nkind_In (Analyzed_Bound, N_Integer_Literal,
2766 N_Character_Literal)
2767 or else Is_Entity_Name (Analyzed_Bound)
2768 then
2769 Analyze_And_Resolve (Original_Bound, Typ);
2770 return Original_Bound;
2771 end if;
2773 -- Normally, the best approach is simply to generate a constant
2774 -- declaration that captures the bound. However, there is a nasty
2775 -- case where this is wrong. If the bound is complex, and has a
2776 -- possible use of the secondary stack, we need to generate a
2777 -- separate assignment statement to ensure the creation of a block
2778 -- which will release the secondary stack.
2780 -- We prefer the constant declaration, since it leaves us with a
2781 -- proper trace of the value, useful in optimizations that get rid
2782 -- of junk range checks.
2784 if not Has_Call_Using_Secondary_Stack (Analyzed_Bound) then
2785 Analyze_And_Resolve (Original_Bound, Typ);
2787 -- Ensure that the bound is valid. This check should not be
2788 -- generated when the range belongs to a quantified expression
2789 -- as the construct is still not expanded into its final form.
2791 if Nkind (Parent (R)) /= N_Loop_Parameter_Specification
2792 or else Nkind (Parent (Parent (R))) /= N_Quantified_Expression
2793 then
2794 Ensure_Valid (Original_Bound);
2795 end if;
2797 Force_Evaluation (Original_Bound);
2798 return Original_Bound;
2799 end if;
2801 Id := Make_Temporary (Loc, 'R', Original_Bound);
2803 -- Here we make a declaration with a separate assignment
2804 -- statement, and insert before loop header.
2806 Decl :=
2807 Make_Object_Declaration (Loc,
2808 Defining_Identifier => Id,
2809 Object_Definition => New_Occurrence_Of (Typ, Loc));
2811 Assign :=
2812 Make_Assignment_Statement (Loc,
2813 Name => New_Occurrence_Of (Id, Loc),
2814 Expression => Relocate_Node (Original_Bound));
2816 Insert_Actions (Loop_Nod, New_List (Decl, Assign));
2818 -- Now that this temporary variable is initialized we decorate it
2819 -- as safe-to-reevaluate to inform to the backend that no further
2820 -- asignment will be issued and hence it can be handled as side
2821 -- effect free. Note that this decoration must be done when the
2822 -- assignment has been analyzed because otherwise it will be
2823 -- rejected (see Analyze_Assignment).
2825 Set_Is_Safe_To_Reevaluate (Id);
2827 Rewrite (Original_Bound, New_Occurrence_Of (Id, Loc));
2829 if Nkind (Assign) = N_Assignment_Statement then
2830 return Expression (Assign);
2831 else
2832 return Original_Bound;
2833 end if;
2834 end One_Bound;
2836 Hi : constant Node_Id := High_Bound (R);
2837 Lo : constant Node_Id := Low_Bound (R);
2838 R_Copy : constant Node_Id := New_Copy_Tree (R);
2839 New_Hi : Node_Id;
2840 New_Lo : Node_Id;
2841 Typ : Entity_Id;
2843 -- Start of processing for Process_Bounds
2845 begin
2846 Set_Parent (R_Copy, Parent (R));
2847 Preanalyze_Range (R_Copy);
2848 Typ := Etype (R_Copy);
2850 -- If the type of the discrete range is Universal_Integer, then the
2851 -- bound's type must be resolved to Integer, and any object used to
2852 -- hold the bound must also have type Integer, unless the literal
2853 -- bounds are constant-folded expressions with a user-defined type.
2855 if Typ = Universal_Integer then
2856 if Nkind (Lo) = N_Integer_Literal
2857 and then Present (Etype (Lo))
2858 and then Scope (Etype (Lo)) /= Standard_Standard
2859 then
2860 Typ := Etype (Lo);
2862 elsif Nkind (Hi) = N_Integer_Literal
2863 and then Present (Etype (Hi))
2864 and then Scope (Etype (Hi)) /= Standard_Standard
2865 then
2866 Typ := Etype (Hi);
2868 else
2869 Typ := Standard_Integer;
2870 end if;
2871 end if;
2873 Set_Etype (R, Typ);
2875 New_Lo := One_Bound (Lo, Low_Bound (R_Copy), Typ);
2876 New_Hi := One_Bound (Hi, High_Bound (R_Copy), Typ);
2878 -- Propagate staticness to loop range itself, in case the
2879 -- corresponding subtype is static.
2881 if New_Lo /= Lo and then Is_OK_Static_Expression (New_Lo) then
2882 Rewrite (Low_Bound (R), New_Copy (New_Lo));
2883 end if;
2885 if New_Hi /= Hi and then Is_OK_Static_Expression (New_Hi) then
2886 Rewrite (High_Bound (R), New_Copy (New_Hi));
2887 end if;
2888 end Process_Bounds;
2890 -- Local variables
2892 DS : constant Node_Id := Discrete_Subtype_Definition (N);
2893 Id : constant Entity_Id := Defining_Identifier (N);
2895 DS_Copy : Node_Id;
2897 -- Start of processing for Analyze_Loop_Parameter_Specification
2899 begin
2900 Enter_Name (Id);
2902 -- We always consider the loop variable to be referenced, since the loop
2903 -- may be used just for counting purposes.
2905 Generate_Reference (Id, N, ' ');
2907 -- Check for the case of loop variable hiding a local variable (used
2908 -- later on to give a nice warning if the hidden variable is never
2909 -- assigned).
2911 declare
2912 H : constant Entity_Id := Homonym (Id);
2913 begin
2914 if Present (H)
2915 and then Ekind (H) = E_Variable
2916 and then Is_Discrete_Type (Etype (H))
2917 and then Enclosing_Dynamic_Scope (H) = Enclosing_Dynamic_Scope (Id)
2918 then
2919 Set_Hiding_Loop_Variable (H, Id);
2920 end if;
2921 end;
2923 -- Loop parameter specification must include subtype mark in SPARK
2925 if Nkind (DS) = N_Range then
2926 Check_SPARK_05_Restriction
2927 ("loop parameter specification must include subtype mark", N);
2928 end if;
2930 -- Analyze the subtype definition and create temporaries for the bounds.
2931 -- Do not evaluate the range when preanalyzing a quantified expression
2932 -- because bounds expressed as function calls with side effects will be
2933 -- incorrectly replicated.
2935 if Nkind (DS) = N_Range
2936 and then Expander_Active
2937 and then Nkind (Parent (N)) /= N_Quantified_Expression
2938 then
2939 Process_Bounds (DS);
2941 -- Either the expander not active or the range of iteration is a subtype
2942 -- indication, an entity, or a function call that yields an aggregate or
2943 -- a container.
2945 else
2946 DS_Copy := New_Copy_Tree (DS);
2947 Set_Parent (DS_Copy, Parent (DS));
2948 Preanalyze_Range (DS_Copy);
2950 -- Ada 2012: If the domain of iteration is:
2952 -- a) a function call,
2953 -- b) an identifier that is not a type,
2954 -- c) an attribute reference 'Old (within a postcondition),
2955 -- d) an unchecked conversion or a qualified expression with
2956 -- the proper iterator type.
2958 -- then it is an iteration over a container. It was classified as
2959 -- a loop specification by the parser, and must be rewritten now
2960 -- to activate container iteration. The last case will occur within
2961 -- an expanded inlined call, where the expansion wraps an actual in
2962 -- an unchecked conversion when needed. The expression of the
2963 -- conversion is always an object.
2965 if Nkind (DS_Copy) = N_Function_Call
2967 or else (Is_Entity_Name (DS_Copy)
2968 and then not Is_Type (Entity (DS_Copy)))
2970 or else (Nkind (DS_Copy) = N_Attribute_Reference
2971 and then Nam_In (Attribute_Name (DS_Copy),
2972 Name_Loop_Entry, Name_Old))
2974 or else Has_Aspect (Etype (DS_Copy), Aspect_Iterable)
2976 or else Nkind (DS_Copy) = N_Unchecked_Type_Conversion
2977 or else (Nkind (DS_Copy) = N_Qualified_Expression
2978 and then Is_Iterator (Etype (DS_Copy)))
2979 then
2980 -- This is an iterator specification. Rewrite it as such and
2981 -- analyze it to capture function calls that may require
2982 -- finalization actions.
2984 declare
2985 I_Spec : constant Node_Id :=
2986 Make_Iterator_Specification (Sloc (N),
2987 Defining_Identifier => Relocate_Node (Id),
2988 Name => DS_Copy,
2989 Subtype_Indication => Empty,
2990 Reverse_Present => Reverse_Present (N));
2991 Scheme : constant Node_Id := Parent (N);
2993 begin
2994 Set_Iterator_Specification (Scheme, I_Spec);
2995 Set_Loop_Parameter_Specification (Scheme, Empty);
2996 Analyze_Iterator_Specification (I_Spec);
2998 -- In a generic context, analyze the original domain of
2999 -- iteration, for name capture.
3001 if not Expander_Active then
3002 Analyze (DS);
3003 end if;
3005 -- Set kind of loop parameter, which may be used in the
3006 -- subsequent analysis of the condition in a quantified
3007 -- expression.
3009 Set_Ekind (Id, E_Loop_Parameter);
3010 return;
3011 end;
3013 -- Domain of iteration is not a function call, and is side-effect
3014 -- free.
3016 else
3017 -- A quantified expression that appears in a pre/post condition
3018 -- is pre-analyzed several times. If the range is given by an
3019 -- attribute reference it is rewritten as a range, and this is
3020 -- done even with expansion disabled. If the type is already set
3021 -- do not reanalyze, because a range with static bounds may be
3022 -- typed Integer by default.
3024 if Nkind (Parent (N)) = N_Quantified_Expression
3025 and then Present (Etype (DS))
3026 then
3027 null;
3028 else
3029 Analyze (DS);
3030 end if;
3031 end if;
3032 end if;
3034 if DS = Error then
3035 return;
3036 end if;
3038 -- Some additional checks if we are iterating through a type
3040 if Is_Entity_Name (DS)
3041 and then Present (Entity (DS))
3042 and then Is_Type (Entity (DS))
3043 then
3044 -- The subtype indication may denote the completion of an incomplete
3045 -- type declaration.
3047 if Ekind (Entity (DS)) = E_Incomplete_Type then
3048 Set_Entity (DS, Get_Full_View (Entity (DS)));
3049 Set_Etype (DS, Entity (DS));
3050 end if;
3052 Check_Predicate_Use (Entity (DS));
3053 end if;
3055 -- Error if not discrete type
3057 if not Is_Discrete_Type (Etype (DS)) then
3058 Wrong_Type (DS, Any_Discrete);
3059 Set_Etype (DS, Any_Type);
3060 end if;
3062 Check_Controlled_Array_Attribute (DS);
3064 if Nkind (DS) = N_Subtype_Indication then
3065 Check_Predicate_Use (Entity (Subtype_Mark (DS)));
3066 end if;
3068 Make_Index (DS, N, In_Iter_Schm => True);
3069 Set_Ekind (Id, E_Loop_Parameter);
3071 -- A quantified expression which appears in a pre- or post-condition may
3072 -- be analyzed multiple times. The analysis of the range creates several
3073 -- itypes which reside in different scopes depending on whether the pre-
3074 -- or post-condition has been expanded. Update the type of the loop
3075 -- variable to reflect the proper itype at each stage of analysis.
3077 if No (Etype (Id))
3078 or else Etype (Id) = Any_Type
3079 or else
3080 (Present (Etype (Id))
3081 and then Is_Itype (Etype (Id))
3082 and then Nkind (Parent (Loop_Nod)) = N_Expression_With_Actions
3083 and then Nkind (Original_Node (Parent (Loop_Nod))) =
3084 N_Quantified_Expression)
3085 then
3086 Set_Etype (Id, Etype (DS));
3087 end if;
3089 -- Treat a range as an implicit reference to the type, to inhibit
3090 -- spurious warnings.
3092 Generate_Reference (Base_Type (Etype (DS)), N, ' ');
3093 Set_Is_Known_Valid (Id, True);
3095 -- The loop is not a declarative part, so the loop variable must be
3096 -- frozen explicitly. Do not freeze while preanalyzing a quantified
3097 -- expression because the freeze node will not be inserted into the
3098 -- tree due to flag Is_Spec_Expression being set.
3100 if Nkind (Parent (N)) /= N_Quantified_Expression then
3101 declare
3102 Flist : constant List_Id := Freeze_Entity (Id, N);
3103 begin
3104 if Is_Non_Empty_List (Flist) then
3105 Insert_Actions (N, Flist);
3106 end if;
3107 end;
3108 end if;
3110 -- Case where we have a range or a subtype, get type bounds
3112 if Nkind_In (DS, N_Range, N_Subtype_Indication)
3113 and then not Error_Posted (DS)
3114 and then Etype (DS) /= Any_Type
3115 and then Is_Discrete_Type (Etype (DS))
3116 then
3117 declare
3118 L : Node_Id;
3119 H : Node_Id;
3121 begin
3122 if Nkind (DS) = N_Range then
3123 L := Low_Bound (DS);
3124 H := High_Bound (DS);
3125 else
3126 L :=
3127 Type_Low_Bound (Underlying_Type (Etype (Subtype_Mark (DS))));
3128 H :=
3129 Type_High_Bound (Underlying_Type (Etype (Subtype_Mark (DS))));
3130 end if;
3132 -- Check for null or possibly null range and issue warning. We
3133 -- suppress such messages in generic templates and instances,
3134 -- because in practice they tend to be dubious in these cases. The
3135 -- check applies as well to rewritten array element loops where a
3136 -- null range may be detected statically.
3138 if Compile_Time_Compare (L, H, Assume_Valid => True) = GT then
3140 -- Suppress the warning if inside a generic template or
3141 -- instance, since in practice they tend to be dubious in these
3142 -- cases since they can result from intended parameterization.
3144 if not Inside_A_Generic and then not In_Instance then
3146 -- Specialize msg if invalid values could make the loop
3147 -- non-null after all.
3149 if Compile_Time_Compare
3150 (L, H, Assume_Valid => False) = GT
3151 then
3152 -- Since we know the range of the loop is null, set the
3153 -- appropriate flag to remove the loop entirely during
3154 -- expansion.
3156 Set_Is_Null_Loop (Loop_Nod);
3158 if Comes_From_Source (N) then
3159 Error_Msg_N
3160 ("??loop range is null, loop will not execute", DS);
3161 end if;
3163 -- Here is where the loop could execute because of
3164 -- invalid values, so issue appropriate message and in
3165 -- this case we do not set the Is_Null_Loop flag since
3166 -- the loop may execute.
3168 elsif Comes_From_Source (N) then
3169 Error_Msg_N
3170 ("??loop range may be null, loop may not execute",
3171 DS);
3172 Error_Msg_N
3173 ("??can only execute if invalid values are present",
3174 DS);
3175 end if;
3176 end if;
3178 -- In either case, suppress warnings in the body of the loop,
3179 -- since it is likely that these warnings will be inappropriate
3180 -- if the loop never actually executes, which is likely.
3182 Set_Suppress_Loop_Warnings (Loop_Nod);
3184 -- The other case for a warning is a reverse loop where the
3185 -- upper bound is the integer literal zero or one, and the
3186 -- lower bound may exceed this value.
3188 -- For example, we have
3190 -- for J in reverse N .. 1 loop
3192 -- In practice, this is very likely to be a case of reversing
3193 -- the bounds incorrectly in the range.
3195 elsif Reverse_Present (N)
3196 and then Nkind (Original_Node (H)) = N_Integer_Literal
3197 and then
3198 (Intval (Original_Node (H)) = Uint_0
3199 or else
3200 Intval (Original_Node (H)) = Uint_1)
3201 then
3202 -- Lower bound may in fact be known and known not to exceed
3203 -- upper bound (e.g. reverse 0 .. 1) and that's OK.
3205 if Compile_Time_Known_Value (L)
3206 and then Expr_Value (L) <= Expr_Value (H)
3207 then
3208 null;
3210 -- Otherwise warning is warranted
3212 else
3213 Error_Msg_N ("??loop range may be null", DS);
3214 Error_Msg_N ("\??bounds may be wrong way round", DS);
3215 end if;
3216 end if;
3218 -- Check if either bound is known to be outside the range of the
3219 -- loop parameter type, this is e.g. the case of a loop from
3220 -- 20..X where the type is 1..19.
3222 -- Such a loop is dubious since either it raises CE or it executes
3223 -- zero times, and that cannot be useful!
3225 if Etype (DS) /= Any_Type
3226 and then not Error_Posted (DS)
3227 and then Nkind (DS) = N_Subtype_Indication
3228 and then Nkind (Constraint (DS)) = N_Range_Constraint
3229 then
3230 declare
3231 LLo : constant Node_Id :=
3232 Low_Bound (Range_Expression (Constraint (DS)));
3233 LHi : constant Node_Id :=
3234 High_Bound (Range_Expression (Constraint (DS)));
3236 Bad_Bound : Node_Id := Empty;
3237 -- Suspicious loop bound
3239 begin
3240 -- At this stage L, H are the bounds of the type, and LLo
3241 -- Lhi are the low bound and high bound of the loop.
3243 if Compile_Time_Compare (LLo, L, Assume_Valid => True) = LT
3244 or else
3245 Compile_Time_Compare (LLo, H, Assume_Valid => True) = GT
3246 then
3247 Bad_Bound := LLo;
3248 end if;
3250 if Compile_Time_Compare (LHi, L, Assume_Valid => True) = LT
3251 or else
3252 Compile_Time_Compare (LHi, H, Assume_Valid => True) = GT
3253 then
3254 Bad_Bound := LHi;
3255 end if;
3257 if Present (Bad_Bound) then
3258 Error_Msg_N
3259 ("suspicious loop bound out of range of "
3260 & "loop subtype??", Bad_Bound);
3261 Error_Msg_N
3262 ("\loop executes zero times or raises "
3263 & "Constraint_Error??", Bad_Bound);
3264 end if;
3265 end;
3266 end if;
3268 -- This declare block is about warnings, if we get an exception while
3269 -- testing for warnings, we simply abandon the attempt silently. This
3270 -- most likely occurs as the result of a previous error, but might
3271 -- just be an obscure case we have missed. In either case, not giving
3272 -- the warning is perfectly acceptable.
3274 exception
3275 when others => null;
3276 end;
3277 end if;
3279 -- A loop parameter cannot be effectively volatile (SPARK RM 7.1.3(4)).
3280 -- This check is relevant only when SPARK_Mode is on as it is not a
3281 -- standard Ada legality check.
3283 if SPARK_Mode = On and then Is_Effectively_Volatile (Id) then
3284 Error_Msg_N ("loop parameter cannot be volatile", Id);
3285 end if;
3286 end Analyze_Loop_Parameter_Specification;
3288 ----------------------------
3289 -- Analyze_Loop_Statement --
3290 ----------------------------
3292 procedure Analyze_Loop_Statement (N : Node_Id) is
3294 function Is_Container_Iterator (Iter : Node_Id) return Boolean;
3295 -- Given a loop iteration scheme, determine whether it is an Ada 2012
3296 -- container iteration.
3298 function Is_Wrapped_In_Block (N : Node_Id) return Boolean;
3299 -- Determine whether loop statement N has been wrapped in a block to
3300 -- capture finalization actions that may be generated for container
3301 -- iterators. Prevents infinite recursion when block is analyzed.
3302 -- Routine is a noop if loop is single statement within source block.
3304 ---------------------------
3305 -- Is_Container_Iterator --
3306 ---------------------------
3308 function Is_Container_Iterator (Iter : Node_Id) return Boolean is
3309 begin
3310 -- Infinite loop
3312 if No (Iter) then
3313 return False;
3315 -- While loop
3317 elsif Present (Condition (Iter)) then
3318 return False;
3320 -- for Def_Id in [reverse] Name loop
3321 -- for Def_Id [: Subtype_Indication] of [reverse] Name loop
3323 elsif Present (Iterator_Specification (Iter)) then
3324 declare
3325 Nam : constant Node_Id := Name (Iterator_Specification (Iter));
3326 Nam_Copy : Node_Id;
3328 begin
3329 Nam_Copy := New_Copy_Tree (Nam);
3330 Set_Parent (Nam_Copy, Parent (Nam));
3331 Preanalyze_Range (Nam_Copy);
3333 -- The only two options here are iteration over a container or
3334 -- an array.
3336 return not Is_Array_Type (Etype (Nam_Copy));
3337 end;
3339 -- for Def_Id in [reverse] Discrete_Subtype_Definition loop
3341 else
3342 declare
3343 LP : constant Node_Id := Loop_Parameter_Specification (Iter);
3344 DS : constant Node_Id := Discrete_Subtype_Definition (LP);
3345 DS_Copy : Node_Id;
3347 begin
3348 DS_Copy := New_Copy_Tree (DS);
3349 Set_Parent (DS_Copy, Parent (DS));
3350 Preanalyze_Range (DS_Copy);
3352 -- Check for a call to Iterate () or an expression with
3353 -- an iterator type.
3355 return
3356 (Nkind (DS_Copy) = N_Function_Call
3357 and then Needs_Finalization (Etype (DS_Copy)))
3358 or else Is_Iterator (Etype (DS_Copy));
3359 end;
3360 end if;
3361 end Is_Container_Iterator;
3363 -------------------------
3364 -- Is_Wrapped_In_Block --
3365 -------------------------
3367 function Is_Wrapped_In_Block (N : Node_Id) return Boolean is
3368 HSS : Node_Id;
3369 Stat : Node_Id;
3371 begin
3373 -- Check if current scope is a block that is not a transient block.
3375 if Ekind (Current_Scope) /= E_Block
3376 or else No (Block_Node (Current_Scope))
3377 then
3378 return False;
3380 else
3381 HSS :=
3382 Handled_Statement_Sequence (Parent (Block_Node (Current_Scope)));
3384 -- Skip leading pragmas that may be introduced for invariant and
3385 -- predicate checks.
3387 Stat := First (Statements (HSS));
3388 while Present (Stat) and then Nkind (Stat) = N_Pragma loop
3389 Stat := Next (Stat);
3390 end loop;
3392 return Stat = N and then No (Next (Stat));
3393 end if;
3394 end Is_Wrapped_In_Block;
3396 -- Local declarations
3398 Id : constant Node_Id := Identifier (N);
3399 Iter : constant Node_Id := Iteration_Scheme (N);
3400 Loc : constant Source_Ptr := Sloc (N);
3401 Ent : Entity_Id;
3402 Stmt : Node_Id;
3404 -- Start of processing for Analyze_Loop_Statement
3406 begin
3407 if Present (Id) then
3409 -- Make name visible, e.g. for use in exit statements. Loop labels
3410 -- are always considered to be referenced.
3412 Analyze (Id);
3413 Ent := Entity (Id);
3415 -- Guard against serious error (typically, a scope mismatch when
3416 -- semantic analysis is requested) by creating loop entity to
3417 -- continue analysis.
3419 if No (Ent) then
3420 if Total_Errors_Detected /= 0 then
3421 Ent := New_Internal_Entity (E_Loop, Current_Scope, Loc, 'L');
3422 else
3423 raise Program_Error;
3424 end if;
3426 -- Verify that the loop name is hot hidden by an unrelated
3427 -- declaration in an inner scope.
3429 elsif Ekind (Ent) /= E_Label and then Ekind (Ent) /= E_Loop then
3430 Error_Msg_Sloc := Sloc (Ent);
3431 Error_Msg_N ("implicit label declaration for & is hidden#", Id);
3433 if Present (Homonym (Ent))
3434 and then Ekind (Homonym (Ent)) = E_Label
3435 then
3436 Set_Entity (Id, Ent);
3437 Set_Ekind (Ent, E_Loop);
3438 end if;
3440 else
3441 Generate_Reference (Ent, N, ' ');
3442 Generate_Definition (Ent);
3444 -- If we found a label, mark its type. If not, ignore it, since it
3445 -- means we have a conflicting declaration, which would already
3446 -- have been diagnosed at declaration time. Set Label_Construct
3447 -- of the implicit label declaration, which is not created by the
3448 -- parser for generic units.
3450 if Ekind (Ent) = E_Label then
3451 Set_Ekind (Ent, E_Loop);
3453 if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
3454 Set_Label_Construct (Parent (Ent), N);
3455 end if;
3456 end if;
3457 end if;
3459 -- Case of no identifier present. Create one and attach it to the
3460 -- loop statement for use as a scope and as a reference for later
3461 -- expansions. Indicate that the label does not come from source,
3462 -- and attach it to the loop statement so it is part of the tree,
3463 -- even without a full declaration.
3465 else
3466 Ent := New_Internal_Entity (E_Loop, Current_Scope, Loc, 'L');
3467 Set_Etype (Ent, Standard_Void_Type);
3468 Set_Identifier (N, New_Occurrence_Of (Ent, Loc));
3469 Set_Parent (Ent, N);
3470 Set_Has_Created_Identifier (N);
3471 end if;
3473 -- If the iterator specification has a syntactic error, transform
3474 -- construct into an infinite loop to prevent a crash and perform
3475 -- some analysis.
3477 if Present (Iter)
3478 and then Present (Iterator_Specification (Iter))
3479 and then Error_Posted (Iterator_Specification (Iter))
3480 then
3481 Set_Iteration_Scheme (N, Empty);
3482 Analyze (N);
3483 return;
3484 end if;
3486 -- Iteration over a container in Ada 2012 involves the creation of a
3487 -- controlled iterator object. Wrap the loop in a block to ensure the
3488 -- timely finalization of the iterator and release of container locks.
3489 -- The same applies to the use of secondary stack when obtaining an
3490 -- iterator.
3492 if Ada_Version >= Ada_2012
3493 and then Is_Container_Iterator (Iter)
3494 and then not Is_Wrapped_In_Block (N)
3495 then
3496 declare
3497 Block_Nod : Node_Id;
3498 Block_Id : Entity_Id;
3500 begin
3501 Block_Nod :=
3502 Make_Block_Statement (Loc,
3503 Declarations => New_List,
3504 Handled_Statement_Sequence =>
3505 Make_Handled_Sequence_Of_Statements (Loc,
3506 Statements => New_List (Relocate_Node (N))));
3508 Add_Block_Identifier (Block_Nod, Block_Id);
3510 -- The expansion of iterator loops generates an iterator in order
3511 -- to traverse the elements of a container:
3513 -- Iter : <iterator type> := Iterate (Container)'reference;
3515 -- The iterator is controlled and returned on the secondary stack.
3516 -- The analysis of the call to Iterate establishes a transient
3517 -- scope to deal with the secondary stack management, but never
3518 -- really creates a physical block as this would kill the iterator
3519 -- too early (see Wrap_Transient_Declaration). To address this
3520 -- case, mark the generated block as needing secondary stack
3521 -- management.
3523 Set_Uses_Sec_Stack (Block_Id);
3525 Rewrite (N, Block_Nod);
3526 Analyze (N);
3527 return;
3528 end;
3529 end if;
3531 -- Kill current values on entry to loop, since statements in the body of
3532 -- the loop may have been executed before the loop is entered. Similarly
3533 -- we kill values after the loop, since we do not know that the body of
3534 -- the loop was executed.
3536 Kill_Current_Values;
3537 Push_Scope (Ent);
3538 Analyze_Iteration_Scheme (Iter);
3540 -- Check for following case which merits a warning if the type E of is
3541 -- a multi-dimensional array (and no explicit subscript ranges present).
3543 -- for J in E'Range
3544 -- for K in E'Range
3546 if Present (Iter)
3547 and then Present (Loop_Parameter_Specification (Iter))
3548 then
3549 declare
3550 LPS : constant Node_Id := Loop_Parameter_Specification (Iter);
3551 DSD : constant Node_Id :=
3552 Original_Node (Discrete_Subtype_Definition (LPS));
3553 begin
3554 if Nkind (DSD) = N_Attribute_Reference
3555 and then Attribute_Name (DSD) = Name_Range
3556 and then No (Expressions (DSD))
3557 then
3558 declare
3559 Typ : constant Entity_Id := Etype (Prefix (DSD));
3560 begin
3561 if Is_Array_Type (Typ)
3562 and then Number_Dimensions (Typ) > 1
3563 and then Nkind (Parent (N)) = N_Loop_Statement
3564 and then Present (Iteration_Scheme (Parent (N)))
3565 then
3566 declare
3567 OIter : constant Node_Id :=
3568 Iteration_Scheme (Parent (N));
3569 OLPS : constant Node_Id :=
3570 Loop_Parameter_Specification (OIter);
3571 ODSD : constant Node_Id :=
3572 Original_Node (Discrete_Subtype_Definition (OLPS));
3573 begin
3574 if Nkind (ODSD) = N_Attribute_Reference
3575 and then Attribute_Name (ODSD) = Name_Range
3576 and then No (Expressions (ODSD))
3577 and then Etype (Prefix (ODSD)) = Typ
3578 then
3579 Error_Msg_Sloc := Sloc (ODSD);
3580 Error_Msg_N
3581 ("inner range same as outer range#??", DSD);
3582 end if;
3583 end;
3584 end if;
3585 end;
3586 end if;
3587 end;
3588 end if;
3590 -- Analyze the statements of the body except in the case of an Ada 2012
3591 -- iterator with the expander active. In this case the expander will do
3592 -- a rewrite of the loop into a while loop. We will then analyze the
3593 -- loop body when we analyze this while loop.
3595 -- We need to do this delay because if the container is for indefinite
3596 -- types the actual subtype of the components will only be determined
3597 -- when the cursor declaration is analyzed.
3599 -- If the expander is not active then we want to analyze the loop body
3600 -- now even in the Ada 2012 iterator case, since the rewriting will not
3601 -- be done. Insert the loop variable in the current scope, if not done
3602 -- when analysing the iteration scheme. Set its kind properly to detect
3603 -- improper uses in the loop body.
3605 -- In GNATprove mode, we do one of the above depending on the kind of
3606 -- loop. If it is an iterator over an array, then we do not analyze the
3607 -- loop now. We will analyze it after it has been rewritten by the
3608 -- special SPARK expansion which is activated in GNATprove mode. We need
3609 -- to do this so that other expansions that should occur in GNATprove
3610 -- mode take into account the specificities of the rewritten loop, in
3611 -- particular the introduction of a renaming (which needs to be
3612 -- expanded).
3614 -- In other cases in GNATprove mode then we want to analyze the loop
3615 -- body now, since no rewriting will occur. Within a generic the
3616 -- GNATprove mode is irrelevant, we must analyze the generic for
3617 -- non-local name capture.
3619 if Present (Iter)
3620 and then Present (Iterator_Specification (Iter))
3621 then
3622 if GNATprove_Mode
3623 and then Is_Iterator_Over_Array (Iterator_Specification (Iter))
3624 and then not Inside_A_Generic
3625 then
3626 null;
3628 elsif not Expander_Active then
3629 declare
3630 I_Spec : constant Node_Id := Iterator_Specification (Iter);
3631 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3633 begin
3634 if Scope (Id) /= Current_Scope then
3635 Enter_Name (Id);
3636 end if;
3638 -- In an element iterator, The loop parameter is a variable if
3639 -- the domain of iteration (container or array) is a variable.
3641 if not Of_Present (I_Spec)
3642 or else not Is_Variable (Name (I_Spec))
3643 then
3644 Set_Ekind (Id, E_Loop_Parameter);
3645 end if;
3646 end;
3648 Analyze_Statements (Statements (N));
3649 end if;
3651 else
3652 -- Pre-Ada2012 for-loops and while loops
3654 Analyze_Statements (Statements (N));
3655 end if;
3657 -- When the iteration scheme of a loop contains attribute 'Loop_Entry,
3658 -- the loop is transformed into a conditional block. Retrieve the loop.
3660 Stmt := N;
3662 if Subject_To_Loop_Entry_Attributes (Stmt) then
3663 Stmt := Find_Loop_In_Conditional_Block (Stmt);
3664 end if;
3666 -- Finish up processing for the loop. We kill all current values, since
3667 -- in general we don't know if the statements in the loop have been
3668 -- executed. We could do a bit better than this with a loop that we
3669 -- know will execute at least once, but it's not worth the trouble and
3670 -- the front end is not in the business of flow tracing.
3672 Process_End_Label (Stmt, 'e', Ent);
3673 End_Scope;
3674 Kill_Current_Values;
3676 -- Check for infinite loop. Skip check for generated code, since it
3677 -- justs waste time and makes debugging the routine called harder.
3679 -- Note that we have to wait till the body of the loop is fully analyzed
3680 -- before making this call, since Check_Infinite_Loop_Warning relies on
3681 -- being able to use semantic visibility information to find references.
3683 if Comes_From_Source (Stmt) then
3684 Check_Infinite_Loop_Warning (Stmt);
3685 end if;
3687 -- Code after loop is unreachable if the loop has no WHILE or FOR and
3688 -- contains no EXIT statements within the body of the loop.
3690 if No (Iter) and then not Has_Exit (Ent) then
3691 Check_Unreachable_Code (Stmt);
3692 end if;
3693 end Analyze_Loop_Statement;
3695 ----------------------------
3696 -- Analyze_Null_Statement --
3697 ----------------------------
3699 -- Note: the semantics of the null statement is implemented by a single
3700 -- null statement, too bad everything isn't as simple as this.
3702 procedure Analyze_Null_Statement (N : Node_Id) is
3703 pragma Warnings (Off, N);
3704 begin
3705 null;
3706 end Analyze_Null_Statement;
3708 -------------------------
3709 -- Analyze_Target_Name --
3710 -------------------------
3712 procedure Analyze_Target_Name (N : Node_Id) is
3713 begin
3714 -- A target name has the type of the left-hand side of the enclosing
3715 -- assignment.
3717 Set_Etype (N, Etype (Name (Current_Assignment)));
3718 end Analyze_Target_Name;
3720 ------------------------
3721 -- Analyze_Statements --
3722 ------------------------
3724 procedure Analyze_Statements (L : List_Id) is
3725 Lab : Entity_Id;
3726 S : Node_Id;
3728 begin
3729 -- The labels declared in the statement list are reachable from
3730 -- statements in the list. We do this as a prepass so that any goto
3731 -- statement will be properly flagged if its target is not reachable.
3732 -- This is not required, but is nice behavior.
3734 S := First (L);
3735 while Present (S) loop
3736 if Nkind (S) = N_Label then
3737 Analyze (Identifier (S));
3738 Lab := Entity (Identifier (S));
3740 -- If we found a label mark it as reachable
3742 if Ekind (Lab) = E_Label then
3743 Generate_Definition (Lab);
3744 Set_Reachable (Lab);
3746 if Nkind (Parent (Lab)) = N_Implicit_Label_Declaration then
3747 Set_Label_Construct (Parent (Lab), S);
3748 end if;
3750 -- If we failed to find a label, it means the implicit declaration
3751 -- of the label was hidden. A for-loop parameter can do this to
3752 -- a label with the same name inside the loop, since the implicit
3753 -- label declaration is in the innermost enclosing body or block
3754 -- statement.
3756 else
3757 Error_Msg_Sloc := Sloc (Lab);
3758 Error_Msg_N
3759 ("implicit label declaration for & is hidden#",
3760 Identifier (S));
3761 end if;
3762 end if;
3764 Next (S);
3765 end loop;
3767 -- Perform semantic analysis on all statements
3769 Conditional_Statements_Begin;
3771 S := First (L);
3772 while Present (S) loop
3773 Analyze (S);
3775 -- Remove dimension in all statements
3777 Remove_Dimension_In_Statement (S);
3778 Next (S);
3779 end loop;
3781 Conditional_Statements_End;
3783 -- Make labels unreachable. Visibility is not sufficient, because labels
3784 -- in one if-branch for example are not reachable from the other branch,
3785 -- even though their declarations are in the enclosing declarative part.
3787 S := First (L);
3788 while Present (S) loop
3789 if Nkind (S) = N_Label then
3790 Set_Reachable (Entity (Identifier (S)), False);
3791 end if;
3793 Next (S);
3794 end loop;
3795 end Analyze_Statements;
3797 ----------------------------
3798 -- Check_Unreachable_Code --
3799 ----------------------------
3801 procedure Check_Unreachable_Code (N : Node_Id) is
3802 Error_Node : Node_Id;
3803 P : Node_Id;
3805 begin
3806 if Is_List_Member (N) and then Comes_From_Source (N) then
3807 declare
3808 Nxt : Node_Id;
3810 begin
3811 Nxt := Original_Node (Next (N));
3813 -- Skip past pragmas
3815 while Nkind (Nxt) = N_Pragma loop
3816 Nxt := Original_Node (Next (Nxt));
3817 end loop;
3819 -- If a label follows us, then we never have dead code, since
3820 -- someone could branch to the label, so we just ignore it, unless
3821 -- we are in formal mode where goto statements are not allowed.
3823 if Nkind (Nxt) = N_Label
3824 and then not Restriction_Check_Required (SPARK_05)
3825 then
3826 return;
3828 -- Otherwise see if we have a real statement following us
3830 elsif Present (Nxt)
3831 and then Comes_From_Source (Nxt)
3832 and then Is_Statement (Nxt)
3833 then
3834 -- Special very annoying exception. If we have a return that
3835 -- follows a raise, then we allow it without a warning, since
3836 -- the Ada RM annoyingly requires a useless return here.
3838 if Nkind (Original_Node (N)) /= N_Raise_Statement
3839 or else Nkind (Nxt) /= N_Simple_Return_Statement
3840 then
3841 -- The rather strange shenanigans with the warning message
3842 -- here reflects the fact that Kill_Dead_Code is very good
3843 -- at removing warnings in deleted code, and this is one
3844 -- warning we would prefer NOT to have removed.
3846 Error_Node := Nxt;
3848 -- If we have unreachable code, analyze and remove the
3849 -- unreachable code, since it is useless and we don't
3850 -- want to generate junk warnings.
3852 -- We skip this step if we are not in code generation mode
3853 -- or CodePeer mode.
3855 -- This is the one case where we remove dead code in the
3856 -- semantics as opposed to the expander, and we do not want
3857 -- to remove code if we are not in code generation mode,
3858 -- since this messes up the ASIS trees or loses useful
3859 -- information in the CodePeer tree.
3861 -- Note that one might react by moving the whole circuit to
3862 -- exp_ch5, but then we lose the warning in -gnatc mode.
3864 if Operating_Mode = Generate_Code
3865 and then not CodePeer_Mode
3866 then
3867 loop
3868 Nxt := Next (N);
3870 -- Quit deleting when we have nothing more to delete
3871 -- or if we hit a label (since someone could transfer
3872 -- control to a label, so we should not delete it).
3874 exit when No (Nxt) or else Nkind (Nxt) = N_Label;
3876 -- Statement/declaration is to be deleted
3878 Analyze (Nxt);
3879 Remove (Nxt);
3880 Kill_Dead_Code (Nxt);
3881 end loop;
3882 end if;
3884 -- Now issue the warning (or error in formal mode)
3886 if Restriction_Check_Required (SPARK_05) then
3887 Check_SPARK_05_Restriction
3888 ("unreachable code is not allowed", Error_Node);
3889 else
3890 Error_Msg
3891 ("??unreachable code!", Sloc (Error_Node), Error_Node);
3892 end if;
3893 end if;
3895 -- If the unconditional transfer of control instruction is the
3896 -- last statement of a sequence, then see if our parent is one of
3897 -- the constructs for which we count unblocked exits, and if so,
3898 -- adjust the count.
3900 else
3901 P := Parent (N);
3903 -- Statements in THEN part or ELSE part of IF statement
3905 if Nkind (P) = N_If_Statement then
3906 null;
3908 -- Statements in ELSIF part of an IF statement
3910 elsif Nkind (P) = N_Elsif_Part then
3911 P := Parent (P);
3912 pragma Assert (Nkind (P) = N_If_Statement);
3914 -- Statements in CASE statement alternative
3916 elsif Nkind (P) = N_Case_Statement_Alternative then
3917 P := Parent (P);
3918 pragma Assert (Nkind (P) = N_Case_Statement);
3920 -- Statements in body of block
3922 elsif Nkind (P) = N_Handled_Sequence_Of_Statements
3923 and then Nkind (Parent (P)) = N_Block_Statement
3924 then
3925 -- The original loop is now placed inside a block statement
3926 -- due to the expansion of attribute 'Loop_Entry. Return as
3927 -- this is not a "real" block for the purposes of exit
3928 -- counting.
3930 if Nkind (N) = N_Loop_Statement
3931 and then Subject_To_Loop_Entry_Attributes (N)
3932 then
3933 return;
3934 end if;
3936 -- Statements in exception handler in a block
3938 elsif Nkind (P) = N_Exception_Handler
3939 and then Nkind (Parent (P)) = N_Handled_Sequence_Of_Statements
3940 and then Nkind (Parent (Parent (P))) = N_Block_Statement
3941 then
3942 null;
3944 -- None of these cases, so return
3946 else
3947 return;
3948 end if;
3950 -- This was one of the cases we are looking for (i.e. the
3951 -- parent construct was IF, CASE or block) so decrement count.
3953 Unblocked_Exit_Count := Unblocked_Exit_Count - 1;
3954 end if;
3955 end;
3956 end if;
3957 end Check_Unreachable_Code;
3959 ----------------------
3960 -- Preanalyze_Range --
3961 ----------------------
3963 procedure Preanalyze_Range (R_Copy : Node_Id) is
3964 Save_Analysis : constant Boolean := Full_Analysis;
3965 Typ : Entity_Id;
3967 begin
3968 Full_Analysis := False;
3969 Expander_Mode_Save_And_Set (False);
3971 Analyze (R_Copy);
3973 if Nkind (R_Copy) in N_Subexpr and then Is_Overloaded (R_Copy) then
3975 -- Apply preference rules for range of predefined integer types, or
3976 -- check for array or iterable construct for "of" iterator, or
3977 -- diagnose true ambiguity.
3979 declare
3980 I : Interp_Index;
3981 It : Interp;
3982 Found : Entity_Id := Empty;
3984 begin
3985 Get_First_Interp (R_Copy, I, It);
3986 while Present (It.Typ) loop
3987 if Is_Discrete_Type (It.Typ) then
3988 if No (Found) then
3989 Found := It.Typ;
3990 else
3991 if Scope (Found) = Standard_Standard then
3992 null;
3994 elsif Scope (It.Typ) = Standard_Standard then
3995 Found := It.Typ;
3997 else
3998 -- Both of them are user-defined
4000 Error_Msg_N
4001 ("ambiguous bounds in range of iteration", R_Copy);
4002 Error_Msg_N ("\possible interpretations:", R_Copy);
4003 Error_Msg_NE ("\\} ", R_Copy, Found);
4004 Error_Msg_NE ("\\} ", R_Copy, It.Typ);
4005 exit;
4006 end if;
4007 end if;
4009 elsif Nkind (Parent (R_Copy)) = N_Iterator_Specification
4010 and then Of_Present (Parent (R_Copy))
4011 then
4012 if Is_Array_Type (It.Typ)
4013 or else Has_Aspect (It.Typ, Aspect_Iterator_Element)
4014 or else Has_Aspect (It.Typ, Aspect_Constant_Indexing)
4015 or else Has_Aspect (It.Typ, Aspect_Variable_Indexing)
4016 then
4017 if No (Found) then
4018 Found := It.Typ;
4019 Set_Etype (R_Copy, It.Typ);
4021 else
4022 Error_Msg_N ("ambiguous domain of iteration", R_Copy);
4023 end if;
4024 end if;
4025 end if;
4027 Get_Next_Interp (I, It);
4028 end loop;
4029 end;
4030 end if;
4032 -- Subtype mark in iteration scheme
4034 if Is_Entity_Name (R_Copy) and then Is_Type (Entity (R_Copy)) then
4035 null;
4037 -- Expression in range, or Ada 2012 iterator
4039 elsif Nkind (R_Copy) in N_Subexpr then
4040 Resolve (R_Copy);
4041 Typ := Etype (R_Copy);
4043 if Is_Discrete_Type (Typ) then
4044 null;
4046 -- Check that the resulting object is an iterable container
4048 elsif Has_Aspect (Typ, Aspect_Iterator_Element)
4049 or else Has_Aspect (Typ, Aspect_Constant_Indexing)
4050 or else Has_Aspect (Typ, Aspect_Variable_Indexing)
4051 then
4052 null;
4054 -- The expression may yield an implicit reference to an iterable
4055 -- container. Insert explicit dereference so that proper type is
4056 -- visible in the loop.
4058 elsif Has_Implicit_Dereference (Etype (R_Copy)) then
4059 declare
4060 Disc : Entity_Id;
4062 begin
4063 Disc := First_Discriminant (Typ);
4064 while Present (Disc) loop
4065 if Has_Implicit_Dereference (Disc) then
4066 Build_Explicit_Dereference (R_Copy, Disc);
4067 exit;
4068 end if;
4070 Next_Discriminant (Disc);
4071 end loop;
4072 end;
4074 end if;
4075 end if;
4077 Expander_Mode_Restore;
4078 Full_Analysis := Save_Analysis;
4079 end Preanalyze_Range;
4081 end Sem_Ch5;