content
stringlengths
23
1.05M
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . F I L E _ I O -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Finalization; use Ada.Finalization; with Ada.IO_Exceptions; use Ada.IO_Exceptions; with Interfaces.C_Streams; use Interfaces.C_Streams; with System.Soft_Links; with Unchecked_Deallocation; package body System.File_IO is use System.File_Control_Block; package SSL renames System.Soft_Links; ---------------------- -- Global Variables -- ---------------------- Open_Files : AFCB_Ptr; -- This points to a list of AFCB's for all open files. This is a doubly -- linked list, with the Prev pointer of the first entry, and the Next -- pointer of the last entry containing null. Note that this global -- variable must be properly protected to provide thread safety. type Temp_File_Record; type Temp_File_Record_Ptr is access all Temp_File_Record; type Temp_File_Record is record Name : String (1 .. L_tmpnam + 1); Next : Temp_File_Record_Ptr; end record; -- One of these is allocated for each temporary file created Temp_Files : Temp_File_Record_Ptr; -- Points to list of names of temporary files. Note that this global -- variable must be properly protected to provide thread safety. type File_IO_Clean_Up_Type is new Controlled with null record; -- The closing of all open files and deletion of temporary files is an -- action which takes place at the end of execution of the main program. -- This action can be implemented using a library level object which -- gets finalized at the end of the main program execution. The above is -- a controlled type introduced for this purpose. procedure Finalize (V : in out File_IO_Clean_Up_Type); -- This is the finalize operation that is used to do the cleanup. File_IO_Clean_Up_Object : File_IO_Clean_Up_Type; -- This is the single object of the type that triggers the finalization -- call. Since it is at the library level, this happens just before the -- environment task is finalized. text_translation_required : Boolean; pragma Import (C, text_translation_required, "__gnat_text_translation_required"); -- If true, add appropriate suffix to control string for Open. ----------------------- -- Local Subprograms -- ----------------------- procedure Free_String is new Unchecked_Deallocation (String, Pstring); subtype Fopen_String is String (1 .. 4); -- Holds open string (longest is "w+b" & nul) procedure Fopen_Mode (Mode : File_Mode; Text : Boolean; Creat : Boolean; Amethod : Character; Fopstr : out Fopen_String); -- Determines proper open mode for a file to be opened in the given -- Ada mode. Text is true for a text file and false otherwise, and -- Creat is true for a create call, and False for an open call. The -- value stored in Fopstr is a nul-terminated string suitable for a -- call to fopen or freopen. Amethod is the character designating -- the access method from the Access_Method field of the FCB. ---------------- -- Append_Set -- ---------------- procedure Append_Set (File : AFCB_Ptr) is begin if File.Mode = Append_File then if fseek (File.Stream, 0, SEEK_END) /= 0 then raise Device_Error; end if; end if; end Append_Set; ---------------- -- Chain_File -- ---------------- procedure Chain_File (File : AFCB_Ptr) is begin -- Take a task lock, to protect the global data value Open_Files -- No exception handler needed, since we cannot get an exception. SSL.Lock_Task.all; File.Next := Open_Files; File.Prev := null; Open_Files := File; if File.Next /= null then File.Next.Prev := File; end if; SSL.Unlock_Task.all; end Chain_File; --------------------- -- Check_File_Open -- --------------------- procedure Check_File_Open (File : AFCB_Ptr) is begin if File = null then raise Status_Error; end if; end Check_File_Open; ----------------------- -- Check_Read_Status -- ----------------------- procedure Check_Read_Status (File : AFCB_Ptr) is begin if File = null then raise Status_Error; elsif File.Mode > Inout_File then raise Mode_Error; end if; end Check_Read_Status; ------------------------ -- Check_Write_Status -- ------------------------ procedure Check_Write_Status (File : AFCB_Ptr) is begin if File = null then raise Status_Error; elsif File.Mode = In_File then raise Mode_Error; end if; end Check_Write_Status; ----------- -- Close -- ----------- procedure Close (File : in out AFCB_Ptr) is Close_Status : int := 0; Dup_Strm : Boolean := False; begin Check_File_Open (File); AFCB_Close (File); -- Sever the association between the given file and its associated -- external file. The given file is left closed. Do not perform system -- closes on the standard input, output and error files and also do -- not attempt to close a stream that does not exist (signalled by a -- null stream value -- happens in some error situations). if not File.Is_System_File and then File.Stream /= NULL_Stream then -- Do not do an fclose if this is a shared file and there is -- at least one other instance of the stream that is open. if File.Shared_Status = Yes then declare P : AFCB_Ptr; begin P := Open_Files; while P /= null loop if P /= File and then File.Stream = P.Stream then Dup_Strm := True; exit; end if; P := P.Next; end loop; end; end if; -- Do the fclose unless this was a duplicate in the shared case if not Dup_Strm then Close_Status := fclose (File.Stream); end if; end if; -- Dechain file from list of open files and then free the storage -- Since this is a global data structure, we have to protect against -- multiple tasks attempting to access this list. -- Note that we do not use an exception handler to unlock here since -- no exception can occur inside the lock/unlock pair. begin SSL.Lock_Task.all; if File.Prev = null then Open_Files := File.Next; else File.Prev.Next := File.Next; end if; if File.Next /= null then File.Next.Prev := File.Prev; end if; SSL.Unlock_Task.all; end; -- Deallocate some parts of the file structure that were kept in heap -- storage with the exception of system files (standard input, output -- and error) since they had some information allocated in the stack. if not File.Is_System_File then Free_String (File.Name); Free_String (File.Form); AFCB_Free (File); end if; File := null; if Close_Status /= 0 then raise Device_Error; end if; end Close; ------------ -- Delete -- ------------ procedure Delete (File : in out AFCB_Ptr) is begin Check_File_Open (File); if not File.Is_Regular_File then raise Use_Error; end if; declare Filename : aliased constant String := File.Name.all; begin Close (File); -- Now unlink the external file. Note that we use the full name -- in this unlink, because the working directory may have changed -- since we did the open, and we want to unlink the right file! if unlink (Filename'Address) = -1 then raise Use_Error; end if; end; end Delete; ----------------- -- End_Of_File -- ----------------- function End_Of_File (File : AFCB_Ptr) return Boolean is begin Check_File_Open (File); if feof (File.Stream) /= 0 then return True; else Check_Read_Status (File); if ungetc (fgetc (File.Stream), File.Stream) = EOF then clearerr (File.Stream); return True; else return False; end if; end if; end End_Of_File; -------------- -- Finalize -- -------------- -- Note: we do not need to worry about locking against multiple task -- access in this routine, since it is called only from the environment -- task just before terminating execution. procedure Finalize (V : in out File_IO_Clean_Up_Type) is Discard : int; Fptr1 : AFCB_Ptr; Fptr2 : AFCB_Ptr; begin -- First close all open files (the slightly complex form of this loop -- is required because Close as a side effect nulls out its argument) Fptr1 := Open_Files; while Fptr1 /= null loop Fptr2 := Fptr1.Next; Close (Fptr1); Fptr1 := Fptr2; end loop; -- Now unlink all temporary files. We do not bother to free the -- blocks because we are just about to terminate the program. We -- also ignore any errors while attempting these unlink operations. while Temp_Files /= null loop Discard := unlink (Temp_Files.Name'Address); Temp_Files := Temp_Files.Next; end loop; end Finalize; ----------- -- Flush -- ----------- procedure Flush (File : AFCB_Ptr) is begin Check_Write_Status (File); if fflush (File.Stream) = 0 then return; else raise Device_Error; end if; end Flush; ---------------- -- Fopen_Mode -- ---------------- -- The fopen mode to be used is shown by the following table: -- OPEN CREATE -- Append_File "r+" "w+" -- In_File "r" "w+" -- Out_File (Direct_IO) "r+" "w" -- Out_File (all others) "w" "w" -- Inout_File "r+" "w+" -- Note: we do not use "a" or "a+" for Append_File, since this would not -- work in the case of stream files, where even if in append file mode, -- you can reset to earlier points in the file. The caller must use the -- Append_Set routine to deal with the necessary positioning. -- Note: in several cases, the fopen mode used allows reading and -- writing, but the setting of the Ada mode is more restrictive. For -- instance, Create in In_File mode uses "w+" which allows writing, -- but the Ada mode In_File will cause any write operations to be -- rejected with Mode_Error in any case. -- Note: for the Out_File/Open cases for other than the Direct_IO case, -- an initial call will be made by the caller to first open the file in -- "r" mode to be sure that it exists. The real open, in "w" mode, will -- then destroy this file. This is peculiar, but that's what Ada semantics -- require and the ACVT tests insist on! -- If text file translation is required, then either b or t is -- added to the mode, depending on the setting of Text. procedure Fopen_Mode (Mode : File_Mode; Text : Boolean; Creat : Boolean; Amethod : Character; Fopstr : out Fopen_String) is Fptr : Positive; begin case Mode is when In_File => if Creat then Fopstr (1) := 'w'; Fopstr (2) := '+'; Fptr := 3; else Fopstr (1) := 'r'; Fptr := 2; end if; when Out_File => if Amethod = 'D' and not Creat then Fopstr (1) := 'r'; Fopstr (2) := '+'; Fptr := 3; else Fopstr (1) := 'w'; Fptr := 2; end if; when Inout_File | Append_File => if Creat then Fopstr (1) := 'w'; else Fopstr (1) := 'r'; end if; Fopstr (2) := '+'; Fptr := 3; end case; -- If text_translation_required is true then we need to append -- either a t or b to the string to get the right mode if text_translation_required then if Text then Fopstr (Fptr) := 't'; else Fopstr (Fptr) := 'b'; end if; Fptr := Fptr + 1; end if; Fopstr (Fptr) := ASCII.NUL; end Fopen_Mode; ---------- -- Form -- ---------- function Form (File : in AFCB_Ptr) return String is begin if File = null then raise Status_Error; else return File.Form.all (1 .. File.Form'Length - 1); end if; end Form; ------------------ -- Form_Boolean -- ------------------ function Form_Boolean (Form : String; Keyword : String; Default : Boolean) return Boolean is V1, V2 : Natural; begin Form_Parameter (Form, Keyword, V1, V2); if V1 = 0 then return Default; elsif Form (V1) = 'y' then return True; elsif Form (V1) = 'n' then return False; else raise Use_Error; end if; end Form_Boolean; ------------------ -- Form_Integer -- ------------------ function Form_Integer (Form : String; Keyword : String; Default : Integer) return Integer is V1, V2 : Natural; V : Integer; begin Form_Parameter (Form, Keyword, V1, V2); if V1 = 0 then return Default; else V := 0; for J in V1 .. V2 loop if Form (J) not in '0' .. '9' then raise Use_Error; else V := V * 10 + Character'Pos (Form (J)) - Character'Pos ('0'); end if; if V > 999_999 then raise Use_Error; end if; end loop; return V; end if; end Form_Integer; -------------------- -- Form_Parameter -- -------------------- procedure Form_Parameter (Form : String; Keyword : String; Start : out Natural; Stop : out Natural) is Klen : constant Integer := Keyword'Length; -- Start of processing for Form_Parameter begin for J in Form'First + Klen .. Form'Last - 1 loop if Form (J) = '=' and then Form (J - Klen .. J - 1) = Keyword then Start := J + 1; Stop := Start - 1; while Form (Stop + 1) /= ASCII.NUL and then Form (Stop + 1) /= ',' loop Stop := Stop + 1; end loop; return; end if; end loop; Start := 0; Stop := 0; end Form_Parameter; ------------- -- Is_Open -- ------------- function Is_Open (File : in AFCB_Ptr) return Boolean is begin return (File /= null); end Is_Open; ------------------- -- Make_Buffered -- ------------------- procedure Make_Buffered (File : AFCB_Ptr; Buf_Siz : Interfaces.C_Streams.size_t) is status : Integer; begin status := setvbuf (File.Stream, Null_Address, IOFBF, Buf_Siz); end Make_Buffered; ------------------------ -- Make_Line_Buffered -- ------------------------ procedure Make_Line_Buffered (File : AFCB_Ptr; Line_Siz : Interfaces.C_Streams.size_t) is status : Integer; begin status := setvbuf (File.Stream, Null_Address, IOLBF, Line_Siz); end Make_Line_Buffered; --------------------- -- Make_Unbuffered -- --------------------- procedure Make_Unbuffered (File : AFCB_Ptr) is status : Integer; begin status := setvbuf (File.Stream, Null_Address, IONBF, 0); end Make_Unbuffered; ---------- -- Mode -- ---------- function Mode (File : in AFCB_Ptr) return File_Mode is begin if File = null then raise Status_Error; else return File.Mode; end if; end Mode; ---------- -- Name -- ---------- function Name (File : in AFCB_Ptr) return String is begin if File = null then raise Status_Error; else return File.Name.all (1 .. File.Name'Length - 1); end if; end Name; ---------- -- Open -- ---------- procedure Open (File_Ptr : in out AFCB_Ptr; Dummy_FCB : in out AFCB'Class; Mode : File_Mode; Name : String; Form : String; Amethod : Character; Creat : Boolean; Text : Boolean; C_Stream : FILEs := NULL_Stream) is procedure Tmp_Name (Buffer : Address); pragma Import (C, Tmp_Name, "__gnat_tmp_name"); -- set buffer (a String address) with a temporary filename. Stream : FILEs := C_Stream; -- Stream which we open in response to this request Shared : Shared_Status_Type; -- Setting of Shared_Status field for file Fopstr : aliased Fopen_String; -- Mode string used in fopen call Formstr : aliased String (1 .. Form'Length + 1); -- Form string with ASCII.NUL appended, folded to lower case Tempfile : constant Boolean := (Name'Length = 0); -- Indicates temporary file case Namelen : constant Integer := max_path_len; -- Length required for file name, not including final ASCII.NUL -- Note that we used to reference L_tmpnam here, which is not -- reliable since __gnat_tmp_name does not always use tmpnam. Namestr : aliased String (1 .. Namelen + 1); -- Name as given or temporary file name with ASCII.NUL appended Fullname : aliased String (1 .. max_path_len + 1); -- Full name (as required for Name function, and as stored in the -- control block in the Name field) with ASCII.NUL appended. Full_Name_Len : Integer; -- Length of name actually stored in Fullname begin if File_Ptr /= null then raise Status_Error; end if; -- Acquire form string, setting required NUL terminator Formstr (1 .. Form'Length) := Form; Formstr (Formstr'Last) := ASCII.NUL; -- Convert form string to lower case for J in Formstr'Range loop if Formstr (J) in 'A' .. 'Z' then Formstr (J) := Character'Val (Character'Pos (Formstr (J)) + 32); end if; end loop; -- Acquire setting of shared parameter declare V1, V2 : Natural; begin Form_Parameter (Formstr, "shared", V1, V2); if V1 = 0 then Shared := None; elsif Formstr (V1 .. V2) = "yes" then Shared := Yes; elsif Formstr (V1 .. V2) = "no" then Shared := No; else raise Use_Error; end if; end; -- If we were given a stream (call from xxx.C_Streams.Open), then set -- full name to null and that is all we have to do in this case so -- skip to end of processing. if Stream /= NULL_Stream then Fullname (1) := ASCII.Nul; Full_Name_Len := 1; -- Normal case of Open or Create else -- If temporary file case, get temporary file name and add -- to the list of temporary files to be deleted on exit. if Tempfile then if not Creat then raise Name_Error; end if; Tmp_Name (Namestr'Address); if Namestr (1) = ASCII.NUL then raise Use_Error; end if; -- Chain to temp file list, ensuring thread safety with a lock begin SSL.Lock_Task.all; Temp_Files := new Temp_File_Record'(Name => Namestr, Next => Temp_Files); SSL.Unlock_Task.all; exception when others => SSL.Unlock_Task.all; raise; end; -- Normal case of non-null name given else Namestr (1 .. Name'Length) := Name; Namestr (Name'Length + 1) := ASCII.NUL; end if; -- Get full name in accordance with the advice of RM A.8.2(22). full_name (Namestr'Address, Fullname'Address); if Fullname (1) = ASCII.NUL then raise Use_Error; end if; for J in Fullname'Range loop if Fullname (J) = ASCII.NUL then Full_Name_Len := J; exit; end if; end loop; -- If Shared=None or Shared=Yes, then check for the existence -- of another file with exactly the same full name. if Shared /= No then declare P : AFCB_Ptr; begin P := Open_Files; while P /= null loop if Fullname (1 .. Full_Name_Len) = P.Name.all then -- If we get a match, and either file has Shared=None, -- then raise Use_Error, since we don't allow two -- files of the same name to be opened unless they -- specify the required sharing mode. if Shared = None or else P.Shared_Status = None then raise Use_Error; -- If both files have Shared=Yes, then we acquire the -- stream from the located file to use as our stream. elsif Shared = Yes and then P.Shared_Status = Yes then Stream := P.Stream; exit; -- Otherwise one of the files has Shared=Yes and one -- has Shared=No. If the current file has Shared=No -- then all is well but we don't want to share any -- other file's stream. If the current file has -- Shared=Yes, we would like to share a stream, but -- not from a file that has Shared=No, so in either -- case we just keep going on the search. else null; end if; end if; P := P.Next; end loop; end; end if; -- Open specified file if we did not find an existing stream if Stream = NULL_Stream then Fopen_Mode (Mode, Text, Creat, Amethod, Fopstr); -- A special case, if we are opening (OPEN case) a file and -- the mode returned by Fopen_Mode is not "r" or "r+", then -- we first make sure that the file exists as required by -- Ada semantics. if Creat = False and then Fopstr (1) /= 'r' then if file_exists (Namestr'Address) = 0 then raise Name_Error; end if; end if; -- Now open the file. Note that we use the name as given -- in the original Open call for this purpose, since that -- seems the clearest implementation of the intent. It -- would presumably work to use the full name here, but -- if there is any difference, then we should use the -- name used in the call. -- Note: for a corresponding delete, we will use the -- full name, since by the time of the delete, the -- current working directory may have changed and -- we do not want to delete a different file! Stream := fopen (Namestr'Address, Fopstr'Address); if Stream = NULL_Stream then if file_exists (Namestr'Address) = 0 then raise Name_Error; else raise Use_Error; end if; end if; end if; end if; -- Stream has been successfully located or opened, so now we are -- committed to completing the opening of the file. Allocate block -- on heap and fill in its fields. File_Ptr := AFCB_Allocate (Dummy_FCB); File_Ptr.Is_Regular_File := (is_regular_file (fileno (Stream)) /= 0); File_Ptr.Is_System_File := False; File_Ptr.Is_Text_File := Text; File_Ptr.Shared_Status := Shared; File_Ptr.Access_Method := Amethod; File_Ptr.Stream := Stream; File_Ptr.Form := new String'(Formstr); File_Ptr.Name := new String'(Fullname (1 .. Full_Name_Len)); File_Ptr.Mode := Mode; File_Ptr.Is_Temporary_File := Tempfile; Chain_File (File_Ptr); Append_Set (File_Ptr); end Open; -------------- -- Read_Buf -- -------------- procedure Read_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is Nread : size_t; begin Nread := fread (Buf, 1, Siz, File.Stream); if Nread = Siz then return; elsif ferror (File.Stream) /= 0 then raise Device_Error; elsif Nread = 0 then raise End_Error; else -- 0 < Nread < Siz raise Data_Error; end if; end Read_Buf; procedure Read_Buf (File : AFCB_Ptr; Buf : Address; Siz : in Interfaces.C_Streams.size_t; Count : out Interfaces.C_Streams.size_t) is begin Count := fread (Buf, 1, Siz, File.Stream); if Count = 0 and then ferror (File.Stream) /= 0 then raise Device_Error; end if; end Read_Buf; ----------- -- Reset -- ----------- -- The reset which does not change the mode simply does a rewind. procedure Reset (File : in out AFCB_Ptr) is begin Check_File_Open (File); Reset (File, File.Mode); end Reset; -- The reset with a change in mode is done using freopen, and is -- not permitted except for regular files (since otherwise there -- is no name for the freopen, and in any case it seems meaningless) procedure Reset (File : in out AFCB_Ptr; Mode : in File_Mode) is Fopstr : aliased Fopen_String; begin Check_File_Open (File); -- Change of mode not allowed for shared file or file with no name -- or file that is not a regular file, or for a system file. if File.Shared_Status = Yes or else File.Name'Length <= 1 or else File.Is_System_File or else (not File.Is_Regular_File) then raise Use_Error; -- For In_File or Inout_File for a regular file, we can just do a -- rewind if the mode is unchanged, which is more efficient than -- doing a full reopen. elsif Mode = File.Mode and then Mode <= Inout_File then rewind (File.Stream); -- Here the change of mode is permitted, we do it by reopening the -- file in the new mode and replacing the stream with a new stream. else Fopen_Mode (Mode, File.Is_Text_File, False, File.Access_Method, Fopstr); File.Stream := freopen (File.Name.all'Address, Fopstr'Address, File.Stream); if File.Stream = NULL_Stream then Close (File); raise Use_Error; else File.Mode := Mode; Append_Set (File); end if; end if; end Reset; --------------- -- Write_Buf -- --------------- procedure Write_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is begin -- Note: for most purposes, the Siz and 1 parameters in the fwrite -- call could be reversed, but on VMS, this is a better choice, since -- for some file formats, reversing the parameters results in records -- of one byte each. SSL.Abort_Defer.all; if fwrite (Buf, Siz, 1, File.Stream) /= 1 then if Siz /= 0 then SSL.Abort_Undefer.all; raise Device_Error; end if; end if; SSL.Abort_Undefer.all; end Write_Buf; end System.File_IO;
with Ada.Characters.Handling; with Ada.Wide_Text_IO; package body Indented_Text is package Ach renames Ada.Characters.Handling; package Awti renames Ada.Wide_Text_IO; ----------- -- PRIVATE: ----------- procedure Trace_Put (Message : in Wide_String) is begin if Trace_On then Awti.Put (Message); end if; end Trace_Put; ----------- -- PRIVATE: ----------- procedure Trace_Put_Line (Message : in Wide_String) is begin if Trace_On then Awti.Put_Line ("$$$ " & Message); end if; end Trace_Put_Line; -- Used below to control which routines are used for output: procedure Put (Message : in Wide_String) renames Trace_Put; procedure Put_Line (Message : in Wide_String) renames Trace_Put_Line; ------------ -- EXPORTED: ------------ procedure Indent (This : in out Class) is begin This.Indent_Level := This.Indent_Level + 1; end Indent; ------------ -- EXPORTED: ------------ procedure Dedent (This : in out Class) is begin if This.Indent_Level = 0 then Put_Line ("(Attempted negative indent)"); else This.Indent_Level := This.Indent_Level - 1; end if; end Dedent; ------------ -- EXPORTED: ------------ procedure New_Line (This : in out Class) is begin Put_Line (""); This.Line_In_Progress := False; end New_Line; ------------ -- EXPORTED: ------------ procedure End_Line (This : in out Class) is begin if This.Line_In_Progress then This.New_Line; end if; end End_Line; ------------ -- EXPORTED: ------------ procedure Put (This : in out Class; Message : in String) is begin This.Put (ACH.To_Wide_String (Message)); end Put; ------------ -- EXPORTED: ------------ procedure Put (This : in out Class; Message : in Wide_String) is begin This.Put_Indent_If_Needed; Put (Message); end Put; ------------ -- EXPORTED: ------------ procedure Put_Indented_Line (This : in out Class; Message : in String) is begin This.Put_Indented_Line (ACH.To_Wide_String (Message)); end Put_Indented_Line; ------------ -- EXPORTED: ------------ procedure Put_Indented_Line (This : in out Class; Message : in Wide_String) is begin This.Put_Indent_If_Needed; Put_Line (Message); This.Line_In_Progress := False; end Put_Indented_Line; ------------ -- PRIVATE: ------------ procedure Put_Indent_If_Needed (This : in out Class) is begin if not This.Line_In_Progress then Put (This.White_Space); This.Line_In_Progress := True; end if; end Put_Indent_If_Needed; ------------ -- PRIVATE: ------------ function White_Space (This : in Class) return Wide_String is ((1 .. This.Indent_Level * 2 => ' ')); end Indented_Text;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ package body AMF.Internals.Tables.DG_Metamodel is -------------- -- MM_DG_DG -- -------------- function MM_DG_DG return AMF.Internals.CMOF_Element is begin return Base + 98; end MM_DG_DG; ---------------------- -- MC_DG_Close_Path -- ---------------------- function MC_DG_Close_Path return AMF.Internals.CMOF_Element is begin return Base + 314; end MC_DG_Close_Path; -------------------------- -- MC_DG_Cubic_Curve_To -- -------------------------- function MC_DG_Cubic_Curve_To return AMF.Internals.CMOF_Element is begin return Base + 288; end MC_DG_Cubic_Curve_To; ----------------------------- -- MC_DG_Elliptical_Arc_To -- ----------------------------- function MC_DG_Elliptical_Arc_To return AMF.Internals.CMOF_Element is begin return Base + 302; end MC_DG_Elliptical_Arc_To; ------------------------- -- MC_DG_Gradient_Stop -- ------------------------- function MC_DG_Gradient_Stop return AMF.Internals.CMOF_Element is begin return Base + 127; end MC_DG_Gradient_Stop; ------------------- -- MC_DG_Line_To -- ------------------- function MC_DG_Line_To return AMF.Internals.CMOF_Element is begin return Base + 284; end MC_DG_Line_To; ------------------ -- MC_DG_Matrix -- ------------------ function MC_DG_Matrix return AMF.Internals.CMOF_Element is begin return Base + 262; end MC_DG_Matrix; ------------------- -- MC_DG_Move_To -- ------------------- function MC_DG_Move_To return AMF.Internals.CMOF_Element is begin return Base + 280; end MC_DG_Move_To; ------------------------ -- MC_DG_Path_Command -- ------------------------ function MC_DG_Path_Command return AMF.Internals.CMOF_Element is begin return Base + 276; end MC_DG_Path_Command; ------------------------------ -- MC_DG_Quadratic_Curve_To -- ------------------------------ function MC_DG_Quadratic_Curve_To return AMF.Internals.CMOF_Element is begin return Base + 296; end MC_DG_Quadratic_Curve_To; ------------------ -- MC_DG_Rotate -- ------------------ function MC_DG_Rotate return AMF.Internals.CMOF_Element is begin return Base + 204; end MC_DG_Rotate; ----------------- -- MC_DG_Scale -- ----------------- function MC_DG_Scale return AMF.Internals.CMOF_Element is begin return Base + 195; end MC_DG_Scale; ---------------- -- MC_DG_Skew -- ---------------- function MC_DG_Skew return AMF.Internals.CMOF_Element is begin return Base + 212; end MC_DG_Skew; --------------------- -- MC_DG_Transform -- --------------------- function MC_DG_Transform return AMF.Internals.CMOF_Element is begin return Base + 187; end MC_DG_Transform; --------------------- -- MC_DG_Translate -- --------------------- function MC_DG_Translate return AMF.Internals.CMOF_Element is begin return Base + 189; end MC_DG_Translate; ------------------ -- MC_DG_Canvas -- ------------------ function MC_DG_Canvas return AMF.Internals.CMOF_Element is begin return Base + 1; end MC_DG_Canvas; ------------------ -- MC_DG_Circle -- ------------------ function MC_DG_Circle return AMF.Internals.CMOF_Element is begin return Base + 2; end MC_DG_Circle; --------------------- -- MC_DG_Clip_Path -- --------------------- function MC_DG_Clip_Path return AMF.Internals.CMOF_Element is begin return Base + 3; end MC_DG_Clip_Path; ------------------- -- MC_DG_Ellipse -- ------------------- function MC_DG_Ellipse return AMF.Internals.CMOF_Element is begin return Base + 4; end MC_DG_Ellipse; ---------------- -- MC_DG_Fill -- ---------------- function MC_DG_Fill return AMF.Internals.CMOF_Element is begin return Base + 5; end MC_DG_Fill; -------------------- -- MC_DG_Gradient -- -------------------- function MC_DG_Gradient return AMF.Internals.CMOF_Element is begin return Base + 6; end MC_DG_Gradient; ----------------------------- -- MC_DG_Graphical_Element -- ----------------------------- function MC_DG_Graphical_Element return AMF.Internals.CMOF_Element is begin return Base + 7; end MC_DG_Graphical_Element; ----------------- -- MC_DG_Group -- ----------------- function MC_DG_Group return AMF.Internals.CMOF_Element is begin return Base + 8; end MC_DG_Group; ----------------- -- MC_DG_Image -- ----------------- function MC_DG_Image return AMF.Internals.CMOF_Element is begin return Base + 9; end MC_DG_Image; ---------------- -- MC_DG_Line -- ---------------- function MC_DG_Line return AMF.Internals.CMOF_Element is begin return Base + 10; end MC_DG_Line; --------------------------- -- MC_DG_Linear_Gradient -- --------------------------- function MC_DG_Linear_Gradient return AMF.Internals.CMOF_Element is begin return Base + 11; end MC_DG_Linear_Gradient; -------------------------- -- MC_DG_Marked_Element -- -------------------------- function MC_DG_Marked_Element return AMF.Internals.CMOF_Element is begin return Base + 12; end MC_DG_Marked_Element; ------------------ -- MC_DG_Marker -- ------------------ function MC_DG_Marker return AMF.Internals.CMOF_Element is begin return Base + 13; end MC_DG_Marker; ---------------- -- MC_DG_Path -- ---------------- function MC_DG_Path return AMF.Internals.CMOF_Element is begin return Base + 14; end MC_DG_Path; ------------------- -- MC_DG_Pattern -- ------------------- function MC_DG_Pattern return AMF.Internals.CMOF_Element is begin return Base + 15; end MC_DG_Pattern; ------------------- -- MC_DG_Polygon -- ------------------- function MC_DG_Polygon return AMF.Internals.CMOF_Element is begin return Base + 16; end MC_DG_Polygon; -------------------- -- MC_DG_Polyline -- -------------------- function MC_DG_Polyline return AMF.Internals.CMOF_Element is begin return Base + 17; end MC_DG_Polyline; --------------------------- -- MC_DG_Radial_Gradient -- --------------------------- function MC_DG_Radial_Gradient return AMF.Internals.CMOF_Element is begin return Base + 18; end MC_DG_Radial_Gradient; --------------------- -- MC_DG_Rectangle -- --------------------- function MC_DG_Rectangle return AMF.Internals.CMOF_Element is begin return Base + 19; end MC_DG_Rectangle; ----------------- -- MC_DG_Style -- ----------------- function MC_DG_Style return AMF.Internals.CMOF_Element is begin return Base + 20; end MC_DG_Style; ---------------- -- MC_DG_Text -- ---------------- function MC_DG_Text return AMF.Internals.CMOF_Element is begin return Base + 21; end MC_DG_Text; ----------------------------------- -- MP_DG_Canvas_Background_Color -- ----------------------------------- function MP_DG_Canvas_Background_Color return AMF.Internals.CMOF_Element is begin return Base + 28; end MP_DG_Canvas_Background_Color; ------------------------------------------- -- MP_DG_Canvas_Background_Fill_A_Canvas -- ------------------------------------------- function MP_DG_Canvas_Background_Fill_A_Canvas return AMF.Internals.CMOF_Element is begin return Base + 29; end MP_DG_Canvas_Background_Fill_A_Canvas; -------------------------------------------- -- MP_DG_Canvas_Packaged_Fill_Fill_Canvas -- -------------------------------------------- function MP_DG_Canvas_Packaged_Fill_Fill_Canvas return AMF.Internals.CMOF_Element is begin return Base + 22; end MP_DG_Canvas_Packaged_Fill_Fill_Canvas; ------------------------------------------------ -- MP_DG_Canvas_Packaged_Marker_Marker_Canvas -- ------------------------------------------------ function MP_DG_Canvas_Packaged_Marker_Marker_Canvas return AMF.Internals.CMOF_Element is begin return Base + 23; end MP_DG_Canvas_Packaged_Marker_Marker_Canvas; ------------------------------------------ -- MP_DG_Canvas_Packaged_Style_A_Canvas -- ------------------------------------------ function MP_DG_Canvas_Packaged_Style_A_Canvas return AMF.Internals.CMOF_Element is begin return Base + 24; end MP_DG_Canvas_Packaged_Style_A_Canvas; ------------------------- -- MP_DG_Circle_Center -- ------------------------- function MP_DG_Circle_Center return AMF.Internals.CMOF_Element is begin return Base + 30; end MP_DG_Circle_Center; ------------------------- -- MP_DG_Circle_Radius -- ------------------------- function MP_DG_Circle_Radius return AMF.Internals.CMOF_Element is begin return Base + 31; end MP_DG_Circle_Radius; ----------------------------------------------------------------- -- MP_DG_Clip_Path_Clipped_Element_Graphical_Element_Clip_Path -- ----------------------------------------------------------------- function MP_DG_Clip_Path_Clipped_Element_Graphical_Element_Clip_Path return AMF.Internals.CMOF_Element is begin return Base + 32; end MP_DG_Clip_Path_Clipped_Element_Graphical_Element_Clip_Path; -------------------------- -- MP_DG_Ellipse_Center -- -------------------------- function MP_DG_Ellipse_Center return AMF.Internals.CMOF_Element is begin return Base + 33; end MP_DG_Ellipse_Center; ------------------------- -- MP_DG_Ellipse_Radii -- ------------------------- function MP_DG_Ellipse_Radii return AMF.Internals.CMOF_Element is begin return Base + 34; end MP_DG_Ellipse_Radii; -------------------------------------------- -- MP_DG_Fill_Canvas_Canvas_Packaged_Fill -- -------------------------------------------- function MP_DG_Fill_Canvas_Canvas_Packaged_Fill return AMF.Internals.CMOF_Element is begin return Base + 35; end MP_DG_Fill_Canvas_Canvas_Packaged_Fill; -------------------------- -- MP_DG_Fill_Transform -- -------------------------- function MP_DG_Fill_Transform return AMF.Internals.CMOF_Element is begin return Base + 36; end MP_DG_Fill_Transform; ------------------------- -- MP_DG_Gradient_Stop -- ------------------------- function MP_DG_Gradient_Stop return AMF.Internals.CMOF_Element is begin return Base + 37; end MP_DG_Gradient_Stop; ----------------------------------------------------------------- -- MP_DG_Graphical_Element_Clip_Path_Clip_Path_Clipped_Element -- ----------------------------------------------------------------- function MP_DG_Graphical_Element_Clip_Path_Clip_Path_Clipped_Element return AMF.Internals.CMOF_Element is begin return Base + 38; end MP_DG_Graphical_Element_Clip_Path_Clip_Path_Clipped_Element; ------------------------------------------------ -- MP_DG_Graphical_Element_Group_Group_Member -- ------------------------------------------------ function MP_DG_Graphical_Element_Group_Group_Member return AMF.Internals.CMOF_Element is begin return Base + 39; end MP_DG_Graphical_Element_Group_Group_Member; ---------------------------------------------------------- -- MP_DG_Graphical_Element_Local_Style_A_Styled_Element -- ---------------------------------------------------------- function MP_DG_Graphical_Element_Local_Style_A_Styled_Element return AMF.Internals.CMOF_Element is begin return Base + 25; end MP_DG_Graphical_Element_Local_Style_A_Styled_Element; ----------------------------------------------------------- -- MP_DG_Graphical_Element_Shared_Style_A_Styled_Element -- ----------------------------------------------------------- function MP_DG_Graphical_Element_Shared_Style_A_Styled_Element return AMF.Internals.CMOF_Element is begin return Base + 26; end MP_DG_Graphical_Element_Shared_Style_A_Styled_Element; --------------------------------------- -- MP_DG_Graphical_Element_Transform -- --------------------------------------- function MP_DG_Graphical_Element_Transform return AMF.Internals.CMOF_Element is begin return Base + 40; end MP_DG_Graphical_Element_Transform; ------------------------------------------------ -- MP_DG_Group_Member_Graphical_Element_Group -- ------------------------------------------------ function MP_DG_Group_Member_Graphical_Element_Group return AMF.Internals.CMOF_Element is begin return Base + 27; end MP_DG_Group_Member_Graphical_Element_Group; ------------------------ -- MP_DG_Image_Bounds -- ------------------------ function MP_DG_Image_Bounds return AMF.Internals.CMOF_Element is begin return Base + 41; end MP_DG_Image_Bounds; ------------------------------------------- -- MP_DG_Image_Is_Aspect_Ratio_Preserved -- ------------------------------------------- function MP_DG_Image_Is_Aspect_Ratio_Preserved return AMF.Internals.CMOF_Element is begin return Base + 42; end MP_DG_Image_Is_Aspect_Ratio_Preserved; ------------------------ -- MP_DG_Image_Source -- ------------------------ function MP_DG_Image_Source return AMF.Internals.CMOF_Element is begin return Base + 43; end MP_DG_Image_Source; -------------------- -- MP_DG_Line_End -- -------------------- function MP_DG_Line_End return AMF.Internals.CMOF_Element is begin return Base + 44; end MP_DG_Line_End; ---------------------- -- MP_DG_Line_Start -- ---------------------- function MP_DG_Line_Start return AMF.Internals.CMOF_Element is begin return Base + 45; end MP_DG_Line_Start; ------------------------------ -- MP_DG_Linear_Gradient_X1 -- ------------------------------ function MP_DG_Linear_Gradient_X1 return AMF.Internals.CMOF_Element is begin return Base + 46; end MP_DG_Linear_Gradient_X1; ------------------------------ -- MP_DG_Linear_Gradient_X2 -- ------------------------------ function MP_DG_Linear_Gradient_X2 return AMF.Internals.CMOF_Element is begin return Base + 47; end MP_DG_Linear_Gradient_X2; ------------------------------ -- MP_DG_Linear_Gradient_Y1 -- ------------------------------ function MP_DG_Linear_Gradient_Y1 return AMF.Internals.CMOF_Element is begin return Base + 48; end MP_DG_Linear_Gradient_Y1; ------------------------------ -- MP_DG_Linear_Gradient_Y2 -- ------------------------------ function MP_DG_Linear_Gradient_Y2 return AMF.Internals.CMOF_Element is begin return Base + 49; end MP_DG_Linear_Gradient_Y2; ------------------------------------------------------ -- MP_DG_Marked_Element_End_Marker_A_Marked_Element -- ------------------------------------------------------ function MP_DG_Marked_Element_End_Marker_A_Marked_Element return AMF.Internals.CMOF_Element is begin return Base + 50; end MP_DG_Marked_Element_End_Marker_A_Marked_Element; ------------------------------------------------------ -- MP_DG_Marked_Element_Mid_Marker_A_Marked_Element -- ------------------------------------------------------ function MP_DG_Marked_Element_Mid_Marker_A_Marked_Element return AMF.Internals.CMOF_Element is begin return Base + 51; end MP_DG_Marked_Element_Mid_Marker_A_Marked_Element; -------------------------------------------------------- -- MP_DG_Marked_Element_Start_Marker_A_Marked_Element -- -------------------------------------------------------- function MP_DG_Marked_Element_Start_Marker_A_Marked_Element return AMF.Internals.CMOF_Element is begin return Base + 52; end MP_DG_Marked_Element_Start_Marker_A_Marked_Element; ------------------------------------------------ -- MP_DG_Marker_Canvas_Canvas_Packaged_Marker -- ------------------------------------------------ function MP_DG_Marker_Canvas_Canvas_Packaged_Marker return AMF.Internals.CMOF_Element is begin return Base + 53; end MP_DG_Marker_Canvas_Canvas_Packaged_Marker; ---------------------------- -- MP_DG_Marker_Reference -- ---------------------------- function MP_DG_Marker_Reference return AMF.Internals.CMOF_Element is begin return Base + 54; end MP_DG_Marker_Reference; ----------------------- -- MP_DG_Marker_Size -- ----------------------- function MP_DG_Marker_Size return AMF.Internals.CMOF_Element is begin return Base + 55; end MP_DG_Marker_Size; ------------------------ -- MP_DG_Path_Command -- ------------------------ function MP_DG_Path_Command return AMF.Internals.CMOF_Element is begin return Base + 56; end MP_DG_Path_Command; -------------------------- -- MP_DG_Pattern_Bounds -- -------------------------- function MP_DG_Pattern_Bounds return AMF.Internals.CMOF_Element is begin return Base + 57; end MP_DG_Pattern_Bounds; ---------------------------------- -- MP_DG_Pattern_Tile_A_Pattern -- ---------------------------------- function MP_DG_Pattern_Tile_A_Pattern return AMF.Internals.CMOF_Element is begin return Base + 58; end MP_DG_Pattern_Tile_A_Pattern; ------------------------- -- MP_DG_Polygon_Point -- ------------------------- function MP_DG_Polygon_Point return AMF.Internals.CMOF_Element is begin return Base + 59; end MP_DG_Polygon_Point; -------------------------- -- MP_DG_Polyline_Point -- -------------------------- function MP_DG_Polyline_Point return AMF.Internals.CMOF_Element is begin return Base + 60; end MP_DG_Polyline_Point; ------------------------------------ -- MP_DG_Radial_Gradient_Center_X -- ------------------------------------ function MP_DG_Radial_Gradient_Center_X return AMF.Internals.CMOF_Element is begin return Base + 61; end MP_DG_Radial_Gradient_Center_X; ------------------------------------ -- MP_DG_Radial_Gradient_Center_Y -- ------------------------------------ function MP_DG_Radial_Gradient_Center_Y return AMF.Internals.CMOF_Element is begin return Base + 62; end MP_DG_Radial_Gradient_Center_Y; ----------------------------------- -- MP_DG_Radial_Gradient_Focus_X -- ----------------------------------- function MP_DG_Radial_Gradient_Focus_X return AMF.Internals.CMOF_Element is begin return Base + 63; end MP_DG_Radial_Gradient_Focus_X; ----------------------------------- -- MP_DG_Radial_Gradient_Focus_Y -- ----------------------------------- function MP_DG_Radial_Gradient_Focus_Y return AMF.Internals.CMOF_Element is begin return Base + 64; end MP_DG_Radial_Gradient_Focus_Y; ---------------------------------- -- MP_DG_Radial_Gradient_Radius -- ---------------------------------- function MP_DG_Radial_Gradient_Radius return AMF.Internals.CMOF_Element is begin return Base + 65; end MP_DG_Radial_Gradient_Radius; ---------------------------- -- MP_DG_Rectangle_Bounds -- ---------------------------- function MP_DG_Rectangle_Bounds return AMF.Internals.CMOF_Element is begin return Base + 66; end MP_DG_Rectangle_Bounds; ----------------------------------- -- MP_DG_Rectangle_Corner_Radius -- ----------------------------------- function MP_DG_Rectangle_Corner_Radius return AMF.Internals.CMOF_Element is begin return Base + 67; end MP_DG_Rectangle_Corner_Radius; ------------------------------ -- MP_DG_Style_Fill_A_Style -- ------------------------------ function MP_DG_Style_Fill_A_Style return AMF.Internals.CMOF_Element is begin return Base + 68; end MP_DG_Style_Fill_A_Style; ---------------------------- -- MP_DG_Style_Fill_Color -- ---------------------------- function MP_DG_Style_Fill_Color return AMF.Internals.CMOF_Element is begin return Base + 69; end MP_DG_Style_Fill_Color; ------------------------------ -- MP_DG_Style_Fill_Opacity -- ------------------------------ function MP_DG_Style_Fill_Opacity return AMF.Internals.CMOF_Element is begin return Base + 70; end MP_DG_Style_Fill_Opacity; --------------------------- -- MP_DG_Style_Font_Bold -- --------------------------- function MP_DG_Style_Font_Bold return AMF.Internals.CMOF_Element is begin return Base + 71; end MP_DG_Style_Font_Bold; ---------------------------- -- MP_DG_Style_Font_Color -- ---------------------------- function MP_DG_Style_Font_Color return AMF.Internals.CMOF_Element is begin return Base + 72; end MP_DG_Style_Font_Color; ----------------------------- -- MP_DG_Style_Font_Italic -- ----------------------------- function MP_DG_Style_Font_Italic return AMF.Internals.CMOF_Element is begin return Base + 73; end MP_DG_Style_Font_Italic; --------------------------- -- MP_DG_Style_Font_Name -- --------------------------- function MP_DG_Style_Font_Name return AMF.Internals.CMOF_Element is begin return Base + 74; end MP_DG_Style_Font_Name; --------------------------- -- MP_DG_Style_Font_Size -- --------------------------- function MP_DG_Style_Font_Size return AMF.Internals.CMOF_Element is begin return Base + 75; end MP_DG_Style_Font_Size; ------------------------------------- -- MP_DG_Style_Font_Strike_Through -- ------------------------------------- function MP_DG_Style_Font_Strike_Through return AMF.Internals.CMOF_Element is begin return Base + 76; end MP_DG_Style_Font_Strike_Through; -------------------------------- -- MP_DG_Style_Font_Underline -- -------------------------------- function MP_DG_Style_Font_Underline return AMF.Internals.CMOF_Element is begin return Base + 77; end MP_DG_Style_Font_Underline; ------------------------------ -- MP_DG_Style_Stroke_Color -- ------------------------------ function MP_DG_Style_Stroke_Color return AMF.Internals.CMOF_Element is begin return Base + 78; end MP_DG_Style_Stroke_Color; ------------------------------------ -- MP_DG_Style_Stroke_Dash_Length -- ------------------------------------ function MP_DG_Style_Stroke_Dash_Length return AMF.Internals.CMOF_Element is begin return Base + 79; end MP_DG_Style_Stroke_Dash_Length; -------------------------------- -- MP_DG_Style_Stroke_Opacity -- -------------------------------- function MP_DG_Style_Stroke_Opacity return AMF.Internals.CMOF_Element is begin return Base + 80; end MP_DG_Style_Stroke_Opacity; ------------------------------ -- MP_DG_Style_Stroke_Width -- ------------------------------ function MP_DG_Style_Stroke_Width return AMF.Internals.CMOF_Element is begin return Base + 81; end MP_DG_Style_Stroke_Width; -------------------------- -- MP_DG_Text_Alignment -- -------------------------- function MP_DG_Text_Alignment return AMF.Internals.CMOF_Element is begin return Base + 82; end MP_DG_Text_Alignment; ----------------------- -- MP_DG_Text_Bounds -- ----------------------- function MP_DG_Text_Bounds return AMF.Internals.CMOF_Element is begin return Base + 83; end MP_DG_Text_Bounds; --------------------- -- MP_DG_Text_Data -- --------------------- function MP_DG_Text_Data return AMF.Internals.CMOF_Element is begin return Base + 84; end MP_DG_Text_Data; -------------------------------------- -- MP_DG_Cubic_Curve_To_End_Control -- -------------------------------------- function MP_DG_Cubic_Curve_To_End_Control return AMF.Internals.CMOF_Element is begin return Base + 294; end MP_DG_Cubic_Curve_To_End_Control; -------------------------------- -- MP_DG_Cubic_Curve_To_Point -- -------------------------------- function MP_DG_Cubic_Curve_To_Point return AMF.Internals.CMOF_Element is begin return Base + 290; end MP_DG_Cubic_Curve_To_Point; ---------------------------------------- -- MP_DG_Cubic_Curve_To_Start_Control -- ---------------------------------------- function MP_DG_Cubic_Curve_To_Start_Control return AMF.Internals.CMOF_Element is begin return Base + 292; end MP_DG_Cubic_Curve_To_Start_Control; ------------------------------------------ -- MP_DG_Elliptical_Arc_To_Is_Large_Arc -- ------------------------------------------ function MP_DG_Elliptical_Arc_To_Is_Large_Arc return AMF.Internals.CMOF_Element is begin return Base + 310; end MP_DG_Elliptical_Arc_To_Is_Large_Arc; -------------------------------------- -- MP_DG_Elliptical_Arc_To_Is_Sweep -- -------------------------------------- function MP_DG_Elliptical_Arc_To_Is_Sweep return AMF.Internals.CMOF_Element is begin return Base + 312; end MP_DG_Elliptical_Arc_To_Is_Sweep; ----------------------------------- -- MP_DG_Elliptical_Arc_To_Point -- ----------------------------------- function MP_DG_Elliptical_Arc_To_Point return AMF.Internals.CMOF_Element is begin return Base + 304; end MP_DG_Elliptical_Arc_To_Point; ----------------------------------- -- MP_DG_Elliptical_Arc_To_Radii -- ----------------------------------- function MP_DG_Elliptical_Arc_To_Radii return AMF.Internals.CMOF_Element is begin return Base + 306; end MP_DG_Elliptical_Arc_To_Radii; -------------------------------------- -- MP_DG_Elliptical_Arc_To_Rotation -- -------------------------------------- function MP_DG_Elliptical_Arc_To_Rotation return AMF.Internals.CMOF_Element is begin return Base + 308; end MP_DG_Elliptical_Arc_To_Rotation; ------------------------------- -- MP_DG_Gradient_Stop_Color -- ------------------------------- function MP_DG_Gradient_Stop_Color return AMF.Internals.CMOF_Element is begin return Base + 135; end MP_DG_Gradient_Stop_Color; -------------------------------- -- MP_DG_Gradient_Stop_Offset -- -------------------------------- function MP_DG_Gradient_Stop_Offset return AMF.Internals.CMOF_Element is begin return Base + 137; end MP_DG_Gradient_Stop_Offset; --------------------------------- -- MP_DG_Gradient_Stop_Opacity -- --------------------------------- function MP_DG_Gradient_Stop_Opacity return AMF.Internals.CMOF_Element is begin return Base + 139; end MP_DG_Gradient_Stop_Opacity; ------------------------- -- MP_DG_Line_To_Point -- ------------------------- function MP_DG_Line_To_Point return AMF.Internals.CMOF_Element is begin return Base + 286; end MP_DG_Line_To_Point; -------------------- -- MP_DG_Matrix_A -- -------------------- function MP_DG_Matrix_A return AMF.Internals.CMOF_Element is begin return Base + 264; end MP_DG_Matrix_A; -------------------- -- MP_DG_Matrix_B -- -------------------- function MP_DG_Matrix_B return AMF.Internals.CMOF_Element is begin return Base + 266; end MP_DG_Matrix_B; -------------------- -- MP_DG_Matrix_C -- -------------------- function MP_DG_Matrix_C return AMF.Internals.CMOF_Element is begin return Base + 268; end MP_DG_Matrix_C; -------------------- -- MP_DG_Matrix_D -- -------------------- function MP_DG_Matrix_D return AMF.Internals.CMOF_Element is begin return Base + 270; end MP_DG_Matrix_D; -------------------- -- MP_DG_Matrix_E -- -------------------- function MP_DG_Matrix_E return AMF.Internals.CMOF_Element is begin return Base + 272; end MP_DG_Matrix_E; -------------------- -- MP_DG_Matrix_F -- -------------------- function MP_DG_Matrix_F return AMF.Internals.CMOF_Element is begin return Base + 274; end MP_DG_Matrix_F; ------------------------- -- MP_DG_Move_To_Point -- ------------------------- function MP_DG_Move_To_Point return AMF.Internals.CMOF_Element is begin return Base + 282; end MP_DG_Move_To_Point; ------------------------------------ -- MP_DG_Path_Command_Is_Relative -- ------------------------------------ function MP_DG_Path_Command_Is_Relative return AMF.Internals.CMOF_Element is begin return Base + 278; end MP_DG_Path_Command_Is_Relative; -------------------------------------- -- MP_DG_Quadratic_Curve_To_Control -- -------------------------------------- function MP_DG_Quadratic_Curve_To_Control return AMF.Internals.CMOF_Element is begin return Base + 300; end MP_DG_Quadratic_Curve_To_Control; ------------------------------------ -- MP_DG_Quadratic_Curve_To_Point -- ------------------------------------ function MP_DG_Quadratic_Curve_To_Point return AMF.Internals.CMOF_Element is begin return Base + 298; end MP_DG_Quadratic_Curve_To_Point; ------------------------ -- MP_DG_Rotate_Angle -- ------------------------ function MP_DG_Rotate_Angle return AMF.Internals.CMOF_Element is begin return Base + 206; end MP_DG_Rotate_Angle; ------------------------- -- MP_DG_Rotate_Center -- ------------------------- function MP_DG_Rotate_Center return AMF.Internals.CMOF_Element is begin return Base + 208; end MP_DG_Rotate_Center; -------------------------- -- MP_DG_Scale_Factor_X -- -------------------------- function MP_DG_Scale_Factor_X return AMF.Internals.CMOF_Element is begin return Base + 200; end MP_DG_Scale_Factor_X; -------------------------- -- MP_DG_Scale_Factor_Y -- -------------------------- function MP_DG_Scale_Factor_Y return AMF.Internals.CMOF_Element is begin return Base + 202; end MP_DG_Scale_Factor_Y; ------------------------ -- MP_DG_Skew_Angle_X -- ------------------------ function MP_DG_Skew_Angle_X return AMF.Internals.CMOF_Element is begin return Base + 214; end MP_DG_Skew_Angle_X; ------------------------ -- MP_DG_Skew_Angle_Y -- ------------------------ function MP_DG_Skew_Angle_Y return AMF.Internals.CMOF_Element is begin return Base + 216; end MP_DG_Skew_Angle_Y; ----------------------------- -- MP_DG_Translate_Delta_X -- ----------------------------- function MP_DG_Translate_Delta_X return AMF.Internals.CMOF_Element is begin return Base + 191; end MP_DG_Translate_Delta_X; ----------------------------- -- MP_DG_Translate_Delta_Y -- ----------------------------- function MP_DG_Translate_Delta_Y return AMF.Internals.CMOF_Element is begin return Base + 193; end MP_DG_Translate_Delta_Y; ---------------------------------- -- MP_DG_A_Pattern_Pattern_Tile -- ---------------------------------- function MP_DG_A_Pattern_Pattern_Tile return AMF.Internals.CMOF_Element is begin return Base + 319; end MP_DG_A_Pattern_Pattern_Tile; ------------------------------------------ -- MP_DG_A_Canvas_Canvas_Packaged_Style -- ------------------------------------------ function MP_DG_A_Canvas_Canvas_Packaged_Style return AMF.Internals.CMOF_Element is begin return Base + 320; end MP_DG_A_Canvas_Canvas_Packaged_Style; -------------------------------------------------------- -- MP_DG_A_Marked_Element_Marked_Element_Start_Marker -- -------------------------------------------------------- function MP_DG_A_Marked_Element_Marked_Element_Start_Marker return AMF.Internals.CMOF_Element is begin return Base + 210; end MP_DG_A_Marked_Element_Marked_Element_Start_Marker; ------------------------------------------------------ -- MP_DG_A_Marked_Element_Marked_Element_End_Marker -- ------------------------------------------------------ function MP_DG_A_Marked_Element_Marked_Element_End_Marker return AMF.Internals.CMOF_Element is begin return Base + 211; end MP_DG_A_Marked_Element_Marked_Element_End_Marker; ------------------------------------------------------ -- MP_DG_A_Marked_Element_Marked_Element_Mid_Marker -- ------------------------------------------------------ function MP_DG_A_Marked_Element_Marked_Element_Mid_Marker return AMF.Internals.CMOF_Element is begin return Base + 218; end MP_DG_A_Marked_Element_Marked_Element_Mid_Marker; ---------------------------------------------------------- -- MP_DG_A_Styled_Element_Graphical_Element_Local_Style -- ---------------------------------------------------------- function MP_DG_A_Styled_Element_Graphical_Element_Local_Style return AMF.Internals.CMOF_Element is begin return Base + 261; end MP_DG_A_Styled_Element_Graphical_Element_Local_Style; ------------------------------ -- MP_DG_A_Style_Style_Fill -- ------------------------------ function MP_DG_A_Style_Style_Fill return AMF.Internals.CMOF_Element is begin return Base + 316; end MP_DG_A_Style_Style_Fill; ----------------------------------------------------------- -- MP_DG_A_Styled_Element_Graphical_Element_Shared_Style -- ----------------------------------------------------------- function MP_DG_A_Styled_Element_Graphical_Element_Shared_Style return AMF.Internals.CMOF_Element is begin return Base + 317; end MP_DG_A_Styled_Element_Graphical_Element_Shared_Style; ------------------------------------------- -- MP_DG_A_Canvas_Canvas_Background_Fill -- ------------------------------------------- function MP_DG_A_Canvas_Canvas_Background_Fill return AMF.Internals.CMOF_Element is begin return Base + 318; end MP_DG_A_Canvas_Canvas_Background_Fill; -------------------------------- -- MA_DG_Pattern_Tile_Pattern -- -------------------------------- function MA_DG_Pattern_Tile_Pattern return AMF.Internals.CMOF_Element is begin return Base + 85; end MA_DG_Pattern_Tile_Pattern; ---------------------------------------- -- MA_DG_Canvas_Packaged_Style_Canvas -- ---------------------------------------- function MA_DG_Canvas_Packaged_Style_Canvas return AMF.Internals.CMOF_Element is begin return Base + 86; end MA_DG_Canvas_Packaged_Style_Canvas; ------------------------------------------------------ -- MA_DG_Marked_Element_Start_Marker_Marked_Element -- ------------------------------------------------------ function MA_DG_Marked_Element_Start_Marker_Marked_Element return AMF.Internals.CMOF_Element is begin return Base + 87; end MA_DG_Marked_Element_Start_Marker_Marked_Element; ---------------------------------------------------- -- MA_DG_Marked_Element_End_Marker_Marked_Element -- ---------------------------------------------------- function MA_DG_Marked_Element_End_Marker_Marked_Element return AMF.Internals.CMOF_Element is begin return Base + 88; end MA_DG_Marked_Element_End_Marker_Marked_Element; ------------------------------ -- MA_DG_Group_Member_Group -- ------------------------------ function MA_DG_Group_Member_Group return AMF.Internals.CMOF_Element is begin return Base + 89; end MA_DG_Group_Member_Group; ---------------------------------------------------- -- MA_DG_Marked_Element_Mid_Marker_Marked_Element -- ---------------------------------------------------- function MA_DG_Marked_Element_Mid_Marker_Marked_Element return AMF.Internals.CMOF_Element is begin return Base + 90; end MA_DG_Marked_Element_Mid_Marker_Marked_Element; ----------------------------------------- -- MA_DG_Canvas_Packaged_Marker_Canvas -- ----------------------------------------- function MA_DG_Canvas_Packaged_Marker_Canvas return AMF.Internals.CMOF_Element is begin return Base + 91; end MA_DG_Canvas_Packaged_Marker_Canvas; ------------------------------------------------------- -- MA_DG_Graphical_Element_Clip_Path_Clipped_Element -- ------------------------------------------------------- function MA_DG_Graphical_Element_Clip_Path_Clipped_Element return AMF.Internals.CMOF_Element is begin return Base + 92; end MA_DG_Graphical_Element_Clip_Path_Clipped_Element; -------------------------------------------------------- -- MA_DG_Graphical_Element_Local_Style_Styled_Element -- -------------------------------------------------------- function MA_DG_Graphical_Element_Local_Style_Styled_Element return AMF.Internals.CMOF_Element is begin return Base + 93; end MA_DG_Graphical_Element_Local_Style_Styled_Element; --------------------------------------- -- MA_DG_Canvas_Packaged_Fill_Canvas -- --------------------------------------- function MA_DG_Canvas_Packaged_Fill_Canvas return AMF.Internals.CMOF_Element is begin return Base + 94; end MA_DG_Canvas_Packaged_Fill_Canvas; ---------------------------- -- MA_DG_Style_Fill_Style -- ---------------------------- function MA_DG_Style_Fill_Style return AMF.Internals.CMOF_Element is begin return Base + 95; end MA_DG_Style_Fill_Style; --------------------------------------------------------- -- MA_DG_Graphical_Element_Shared_Style_Styled_Element -- --------------------------------------------------------- function MA_DG_Graphical_Element_Shared_Style_Styled_Element return AMF.Internals.CMOF_Element is begin return Base + 96; end MA_DG_Graphical_Element_Shared_Style_Styled_Element; ----------------------------------------- -- MA_DG_Canvas_Background_Fill_Canvas -- ----------------------------------------- function MA_DG_Canvas_Background_Fill_Canvas return AMF.Internals.CMOF_Element is begin return Base + 97; end MA_DG_Canvas_Background_Fill_Canvas; ----------- -- MB_DG -- ----------- function MB_DG return AMF.Internals.AMF_Element is begin return Base; end MB_DG; ----------- -- MB_DG -- ----------- function ML_DG return AMF.Internals.AMF_Element is begin return Base + 322; end ML_DG; end AMF.Internals.Tables.DG_Metamodel;
pragma Ada_2012; package body BitOperations.Search with SPARK_Mode, Pure is -------------------------- -- Most_Significant_Bit -- -------------------------- function Most_Significant_Bit (Value : Modular) return Bit_Position is begin for Idx in reverse Bit_Position'First .. Bit_Position'Last loop if (Value and Logic_Left(1, Idx)) /= 0 then return Idx; end if; end loop; return Bit_Position'First; end Most_Significant_Bit; end BitOperations.Search;
type Int_Access is access Integer; Int_Acc : Int_Access := new Integer'(5);
with Interfaces; use Interfaces; with Interfaces.C; use Interfaces.C; generic type Element is mod <>; -- ELement type, must be mod 2**8, i.e. represent a byte type Index is range <>; -- Index type type Element_Array is array (Index range <>) of aliased Element; -- An array of aliased Elements package System_Random with Preelaborate is -- @summary -- Ada interface to system sources of randomness -- -- @description -- This package provides generic interface to OS' sources of randomeness. -- On Windows, BCryptGenRandom() is used, on other platforms such as Linux, -- BSD, Mac OS portable getentropy() is used. -- -- This is a generic package as it is intended to be used with user-defined -- byte array type, that would later be converted to a seed value used to -- seed an appropriate strong PRNG algorithm. pragma Compile_Time_Error (Element'Modulus /= 2**8, "'Element' type must be mod 2**8, i.e. represent a byte"); System_Random_Error : exception; -- Raised whenever an underlying system function has failed procedure Random (Output : aliased out Element_Array) with Pre => Output'Length <= Interfaces.Unsigned_32'Last and Output'Length <= Interfaces.C.size_t'Last; -- Fill Output with random data. This function call blocks, thus it's -- better to call it as few times as possible. -- -- Maximum length of Output array is determined by the underlying system -- implementation, and for unix is equal to 256 bytes. end System_Random;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure Create_Vector_Data(Xa,Ya,Za,Xb,Yb,Zb: in Integer; L,Vy,Vz: out Integer) is begin Put(Xa); end Create_Vector_Data;
-- { dg-do compile } procedure Atomic3 is type Unsigned_32_T is mod 2 ** 32; for Unsigned_32_T'Size use 32; type Id_T is (One, Two, Three); type Array_T is array (Id_T) of Unsigned_32_T; pragma Atomic_Components (Array_T); A : Array_T := (others => 0); function Get_Array return Array_T is begin return A; end; X : Array_T; begin X := Get_Array; end;
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Elements.Expressions; with Program.Lexical_Elements; with Program.Elements.Defining_Operator_Symbols; package Program.Elements.Operator_Symbols is pragma Pure (Program.Elements.Operator_Symbols); type Operator_Symbol is limited interface and Program.Elements.Expressions.Expression; type Operator_Symbol_Access is access all Operator_Symbol'Class with Storage_Size => 0; not overriding function Image (Self : Operator_Symbol) return Text is abstract; not overriding function Corresponding_Defining_Operator_Symbol (Self : Operator_Symbol) return Program.Elements.Defining_Operator_Symbols .Defining_Operator_Symbol_Access is abstract; type Operator_Symbol_Text is limited interface; type Operator_Symbol_Text_Access is access all Operator_Symbol_Text'Class with Storage_Size => 0; not overriding function To_Operator_Symbol_Text (Self : in out Operator_Symbol) return Operator_Symbol_Text_Access is abstract; not overriding function Operator_Symbol_Token (Self : Operator_Symbol_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; end Program.Elements.Operator_Symbols;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ C H 7 -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains virtually all expansion mechanisms related to -- - controlled types -- - transient scopes with Atree; use Atree; with Debug; use Debug; with Einfo; use Einfo; with Elists; use Elists; with Errout; use Errout; with Exp_Ch6; use Exp_Ch6; with Exp_Ch9; use Exp_Ch9; with Exp_Ch11; use Exp_Ch11; with Exp_Dbug; use Exp_Dbug; with Exp_Dist; use Exp_Dist; with Exp_Disp; use Exp_Disp; with Exp_Prag; use Exp_Prag; with Exp_Tss; use Exp_Tss; with Exp_Util; use Exp_Util; with Freeze; use Freeze; with Lib; use Lib; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Output; use Output; with Restrict; use Restrict; with Rident; use Rident; with Rtsfind; use Rtsfind; with Sinfo; use Sinfo; with Sem; use Sem; with Sem_Aux; use Sem_Aux; with Sem_Ch3; use Sem_Ch3; with Sem_Ch7; use Sem_Ch7; with Sem_Ch8; use Sem_Ch8; with Sem_Res; use Sem_Res; with Sem_Util; use Sem_Util; with Snames; use Snames; with Stand; use Stand; with Tbuild; use Tbuild; with Ttypes; use Ttypes; with Uintp; use Uintp; package body Exp_Ch7 is -------------------------------- -- Transient Scope Management -- -------------------------------- -- A transient scope is created when temporary objects are created by the -- compiler. These temporary objects are allocated on the secondary stack -- and the transient scope is responsible for finalizing the object when -- appropriate and reclaiming the memory at the right time. The temporary -- objects are generally the objects allocated to store the result of a -- function returning an unconstrained or a tagged value. Expressions -- needing to be wrapped in a transient scope (functions calls returning -- unconstrained or tagged values) may appear in 3 different contexts which -- lead to 3 different kinds of transient scope expansion: -- 1. In a simple statement (procedure call, assignment, ...). In this -- case the instruction is wrapped into a transient block. See -- Wrap_Transient_Statement for details. -- 2. In an expression of a control structure (test in a IF statement, -- expression in a CASE statement, ...). See Wrap_Transient_Expression -- for details. -- 3. In a expression of an object_declaration. No wrapping is possible -- here, so the finalization actions, if any, are done right after the -- declaration and the secondary stack deallocation is done in the -- proper enclosing scope. See Wrap_Transient_Declaration for details. -- Note about functions returning tagged types: it has been decided to -- always allocate their result in the secondary stack, even though is not -- absolutely mandatory when the tagged type is constrained because the -- caller knows the size of the returned object and thus could allocate the -- result in the primary stack. An exception to this is when the function -- builds its result in place, as is done for functions with inherently -- limited result types for Ada 2005. In that case, certain callers may -- pass the address of a constrained object as the target object for the -- function result. -- By allocating tagged results in the secondary stack a number of -- implementation difficulties are avoided: -- - If it is a dispatching function call, the computation of the size of -- the result is possible but complex from the outside. -- - If the returned type is controlled, the assignment of the returned -- value to the anonymous object involves an Adjust, and we have no -- easy way to access the anonymous object created by the back end. -- - If the returned type is class-wide, this is an unconstrained type -- anyway. -- Furthermore, the small loss in efficiency which is the result of this -- decision is not such a big deal because functions returning tagged types -- are not as common in practice compared to functions returning access to -- a tagged type. -------------------------------------------------- -- Transient Blocks and Finalization Management -- -------------------------------------------------- function Find_Transient_Context (N : Node_Id) return Node_Id; -- Locate a suitable context for arbitrary node N which may need to be -- serviced by a transient scope. Return Empty if no suitable context is -- available. procedure Insert_Actions_In_Scope_Around (N : Node_Id; Clean : Boolean; Manage_SS : Boolean); -- Insert the before-actions kept in the scope stack before N, and the -- after-actions after N, which must be a member of a list. If flag Clean -- is set, insert any cleanup actions. If flag Manage_SS is set, insert -- calls to mark and release the secondary stack. function Make_Transient_Block (Loc : Source_Ptr; Action : Node_Id; Par : Node_Id) return Node_Id; -- Action is a single statement or object declaration. Par is the proper -- parent of the generated block. Create a transient block whose name is -- the current scope and the only handled statement is Action. If Action -- involves controlled objects or secondary stack usage, the corresponding -- cleanup actions are performed at the end of the block. procedure Set_Node_To_Be_Wrapped (N : Node_Id); -- Set the field Node_To_Be_Wrapped of the current scope -- ??? The entire comment needs to be rewritten -- ??? which entire comment? procedure Store_Actions_In_Scope (AK : Scope_Action_Kind; L : List_Id); -- Shared processing for Store_xxx_Actions_In_Scope ----------------------------- -- Finalization Management -- ----------------------------- -- This part describe how Initialization/Adjustment/Finalization procedures -- are generated and called. Two cases must be considered, types that are -- Controlled (Is_Controlled flag set) and composite types that contain -- controlled components (Has_Controlled_Component flag set). In the first -- case the procedures to call are the user-defined primitive operations -- Initialize/Adjust/Finalize. In the second case, GNAT generates -- Deep_Initialize, Deep_Adjust and Deep_Finalize that are in charge -- of calling the former procedures on the controlled components. -- For records with Has_Controlled_Component set, a hidden "controller" -- component is inserted. This controller component contains its own -- finalization list on which all controlled components are attached -- creating an indirection on the upper-level Finalization list. This -- technique facilitates the management of objects whose number of -- controlled components changes during execution. This controller -- component is itself controlled and is attached to the upper-level -- finalization chain. Its adjust primitive is in charge of calling adjust -- on the components and adjusting the finalization pointer to match their -- new location (see a-finali.adb). -- It is not possible to use a similar technique for arrays that have -- Has_Controlled_Component set. In this case, deep procedures are -- generated that call initialize/adjust/finalize + attachment or -- detachment on the finalization list for all component. -- Initialize calls: they are generated for declarations or dynamic -- allocations of Controlled objects with no initial value. They are always -- followed by an attachment to the current Finalization Chain. For the -- dynamic allocation case this the chain attached to the scope of the -- access type definition otherwise, this is the chain of the current -- scope. -- Adjust Calls: They are generated on 2 occasions: (1) for declarations -- or dynamic allocations of Controlled objects with an initial value. -- (2) after an assignment. In the first case they are followed by an -- attachment to the final chain, in the second case they are not. -- Finalization Calls: They are generated on (1) scope exit, (2) -- assignments, (3) unchecked deallocations. In case (3) they have to -- be detached from the final chain, in case (2) they must not and in -- case (1) this is not important since we are exiting the scope anyway. -- Other details: -- Type extensions will have a new record controller at each derivation -- level containing controlled components. The record controller for -- the parent/ancestor is attached to the finalization list of the -- extension's record controller (i.e. the parent is like a component -- of the extension). -- For types that are both Is_Controlled and Has_Controlled_Components, -- the record controller and the object itself are handled separately. -- It could seem simpler to attach the object at the end of its record -- controller but this would not tackle view conversions properly. -- A classwide type can always potentially have controlled components -- but the record controller of the corresponding actual type may not -- be known at compile time so the dispatch table contains a special -- field that allows computation of the offset of the record controller -- dynamically. See s-finimp.Deep_Tag_Attach and a-tags.RC_Offset. -- Here is a simple example of the expansion of a controlled block : -- declare -- X : Controlled; -- Y : Controlled := Init; -- -- type R is record -- C : Controlled; -- end record; -- W : R; -- Z : R := (C => X); -- begin -- X := Y; -- W := Z; -- end; -- -- is expanded into -- -- declare -- _L : System.FI.Finalizable_Ptr; -- procedure _Clean is -- begin -- Abort_Defer; -- System.FI.Finalize_List (_L); -- Abort_Undefer; -- end _Clean; -- X : Controlled; -- begin -- Abort_Defer; -- Initialize (X); -- Attach_To_Final_List (_L, Finalizable (X), 1); -- at end: Abort_Undefer; -- Y : Controlled := Init; -- Adjust (Y); -- Attach_To_Final_List (_L, Finalizable (Y), 1); -- -- type R is record -- C : Controlled; -- end record; -- W : R; -- begin -- Abort_Defer; -- Deep_Initialize (W, _L, 1); -- at end: Abort_Under; -- Z : R := (C => X); -- Deep_Adjust (Z, _L, 1); -- begin -- _Assign (X, Y); -- Deep_Finalize (W, False); -- <save W's final pointers> -- W := Z; -- <restore W's final pointers> -- Deep_Adjust (W, _L, 0); -- at end -- _Clean; -- end; type Final_Primitives is (Initialize_Case, Adjust_Case, Finalize_Case, Address_Case); -- This enumeration type is defined in order to ease sharing code for -- building finalization procedures for composite types. Name_Of : constant array (Final_Primitives) of Name_Id := (Initialize_Case => Name_Initialize, Adjust_Case => Name_Adjust, Finalize_Case => Name_Finalize, Address_Case => Name_Finalize_Address); Deep_Name_Of : constant array (Final_Primitives) of TSS_Name_Type := (Initialize_Case => TSS_Deep_Initialize, Adjust_Case => TSS_Deep_Adjust, Finalize_Case => TSS_Deep_Finalize, Address_Case => TSS_Finalize_Address); function Allows_Finalization_Master (Typ : Entity_Id) return Boolean; -- Determine whether access type Typ may have a finalization master procedure Build_Array_Deep_Procs (Typ : Entity_Id); -- Build the deep Initialize/Adjust/Finalize for a record Typ with -- Has_Controlled_Component set and store them using the TSS mechanism. function Build_Cleanup_Statements (N : Node_Id; Additional_Cleanup : List_Id) return List_Id; -- Create the cleanup calls for an asynchronous call block, task master, -- protected subprogram body, task allocation block or task body, or -- additional cleanup actions parked on a transient block. If the context -- does not contain the above constructs, the routine returns an empty -- list. procedure Build_Finalizer (N : Node_Id; Clean_Stmts : List_Id; Mark_Id : Entity_Id; Top_Decls : List_Id; Defer_Abort : Boolean; Fin_Id : out Entity_Id); -- N may denote an accept statement, block, entry body, package body, -- package spec, protected body, subprogram body, or a task body. Create -- a procedure which contains finalization calls for all controlled objects -- declared in the declarative or statement region of N. The calls are -- built in reverse order relative to the original declarations. In the -- case of a task body, the routine delays the creation of the finalizer -- until all statements have been moved to the task body procedure. -- Clean_Stmts may contain additional context-dependent code used to abort -- asynchronous calls or complete tasks (see Build_Cleanup_Statements). -- Mark_Id is the secondary stack used in the current context or Empty if -- missing. Top_Decls is the list on which the declaration of the finalizer -- is attached in the non-package case. Defer_Abort indicates that the -- statements passed in perform actions that require abort to be deferred, -- such as for task termination. Fin_Id is the finalizer declaration -- entity. procedure Build_Finalizer_Call (N : Node_Id; Fin_Id : Entity_Id); -- N is a construct which contains a handled sequence of statements, Fin_Id -- is the entity of a finalizer. Create an At_End handler which covers the -- statements of N and calls Fin_Id. If the handled statement sequence has -- an exception handler, the statements will be wrapped in a block to avoid -- unwanted interaction with the new At_End handler. procedure Build_Record_Deep_Procs (Typ : Entity_Id); -- Build the deep Initialize/Adjust/Finalize for a record Typ with -- Has_Component_Component set and store them using the TSS mechanism. ------------------------------------------- -- Unnesting procedures for CCG and LLVM -- ------------------------------------------- -- Expansion generates subprograms for controlled types management that -- may appear in declarative lists in package declarations and bodies. -- These subprograms appear within generated blocks that contain local -- declarations and a call to finalization procedures. To ensure that -- such subprograms get activation records when needed, we transform the -- block into a procedure body, followed by a call to it in the same -- declarative list. procedure Check_Unnesting_Elaboration_Code (N : Node_Id); -- The statement part of a package body that is a compilation unit may -- contain blocks that declare local subprograms. In Subprogram_Unnesting_ -- Mode such subprograms must be handled as nested inside the (implicit) -- elaboration procedure that executes that statement part. To handle -- properly uplevel references we construct that subprogram explicitly, -- to contain blocks and inner subprograms, the statement part becomes -- a call to this subprogram. This is only done if blocks are present -- in the statement list of the body. (It would be nice to unify this -- procedure with Check_Unnesting_In_Decls_Or_Stmts, if possible, since -- they're doing very similar work, but are structured differently. ???) procedure Check_Unnesting_In_Decls_Or_Stmts (Decls_Or_Stmts : List_Id); -- Similarly, the declarations or statements in library-level packages may -- have created blocks with nested subprograms. Such a block must be -- transformed into a procedure followed by a call to it, so that unnesting -- can handle uplevel references within these nested subprograms (typically -- subprograms that handle finalization actions). This also applies to -- nested packages, including instantiations, in which case it must -- recursively process inner bodies. procedure Check_Unnesting_In_Handlers (N : Node_Id); -- Similarly, check for blocks with nested subprograms occurring within -- a set of exception handlers associated with a package body N. procedure Unnest_Block (Decl : Node_Id); -- Blocks that contain nested subprograms with up-level references need to -- create activation records for them. We do this by rewriting the block as -- a procedure, followed by a call to it in the same declarative list, to -- replicate the semantics of the original block. -- -- A common source for such block is a transient block created for a -- construct (declaration, assignment, etc.) that involves controlled -- actions or secondary-stack management, in which case the nested -- subprogram is a finalizer. procedure Unnest_If_Statement (If_Stmt : Node_Id); -- The separate statement lists associated with an if-statement (then part, -- elsif parts, else part) may require unnesting if they directly contain -- a subprogram body that references up-level objects. Each statement list -- is traversed to locate such subprogram bodies, and if a part's statement -- list contains a body, then the list is replaced with a new procedure -- containing the part's statements followed by a call to the procedure. -- Furthermore, any nested blocks, loops, or if statements will also be -- traversed to determine the need for further unnesting transformations. procedure Unnest_Statement_List (Stmts : in out List_Id); -- A list of statements that directly contains a subprogram at its outer -- level, that may reference objects declared in that same statement list, -- is rewritten as a procedure containing the statement list Stmts (which -- includes any such objects as well as the nested subprogram), followed by -- a call to the new procedure, and Stmts becomes the list containing the -- procedure and the call. This ensures that Unnest_Subprogram will later -- properly handle up-level references from the nested subprogram to -- objects declared earlier in statement list, by creating an activation -- record and passing it to the nested subprogram. This procedure also -- resets the Scope of objects declared in the statement list, as well as -- the Scope of the nested subprogram, to refer to the new procedure. -- Also, the new procedure is marked Has_Nested_Subprogram, so this should -- only be called when known that the statement list contains a subprogram. procedure Unnest_Loop (Loop_Stmt : Node_Id); -- Top-level Loops that contain nested subprograms with up-level references -- need to have activation records. We do this by rewriting the loop as a -- procedure containing the loop, followed by a call to the procedure in -- the same library-level declarative list, to replicate the semantics of -- the original loop. Such loops can occur due to aggregate expansions and -- other constructs. procedure Check_Visibly_Controlled (Prim : Final_Primitives; Typ : Entity_Id; E : in out Entity_Id; Cref : in out Node_Id); -- The controlled operation declared for a derived type may not be -- overriding, if the controlled operations of the parent type are hidden, -- for example when the parent is a private type whose full view is -- controlled. For other primitive operations we modify the name of the -- operation to indicate that it is not overriding, but this is not -- possible for Initialize, etc. because they have to be retrievable by -- name. Before generating the proper call to one of these operations we -- check whether Typ is known to be controlled at the point of definition. -- If it is not then we must retrieve the hidden operation of the parent -- and use it instead. This is one case that might be solved more cleanly -- once Overriding pragmas or declarations are in place. function Contains_Subprogram (Blk : Entity_Id) return Boolean; -- Check recursively whether a loop or block contains a subprogram that -- may need an activation record. function Convert_View (Proc : Entity_Id; Arg : Node_Id; Ind : Pos := 1) return Node_Id; -- Proc is one of the Initialize/Adjust/Finalize operations, and Arg is the -- argument being passed to it. Ind indicates which formal of procedure -- Proc we are trying to match. This function will, if necessary, generate -- a conversion between the partial and full view of Arg to match the type -- of the formal of Proc, or force a conversion to the class-wide type in -- the case where the operation is abstract. function Enclosing_Function (E : Entity_Id) return Entity_Id; -- Given an arbitrary entity, traverse the scope chain looking for the -- first enclosing function. Return Empty if no function was found. function Make_Call (Loc : Source_Ptr; Proc_Id : Entity_Id; Param : Node_Id; Skip_Self : Boolean := False) return Node_Id; -- Subsidiary to Make_Adjust_Call and Make_Final_Call. Given the entity of -- routine [Deep_]Adjust or [Deep_]Finalize and an object parameter, create -- an adjust or finalization call. Wnen flag Skip_Self is set, the related -- action has an effect on the components only (if any). function Make_Deep_Proc (Prim : Final_Primitives; Typ : Entity_Id; Stmts : List_Id) return Node_Id; -- This function generates the tree for Deep_Initialize, Deep_Adjust or -- Deep_Finalize procedures according to the first parameter, these -- procedures operate on the type Typ. The Stmts parameter gives the body -- of the procedure. function Make_Deep_Array_Body (Prim : Final_Primitives; Typ : Entity_Id) return List_Id; -- This function generates the list of statements for implementing -- Deep_Initialize, Deep_Adjust or Deep_Finalize procedures according to -- the first parameter, these procedures operate on the array type Typ. function Make_Deep_Record_Body (Prim : Final_Primitives; Typ : Entity_Id; Is_Local : Boolean := False) return List_Id; -- This function generates the list of statements for implementing -- Deep_Initialize, Deep_Adjust or Deep_Finalize procedures according to -- the first parameter, these procedures operate on the record type Typ. -- Flag Is_Local is used in conjunction with Deep_Finalize to designate -- whether the inner logic should be dictated by state counters. function Make_Finalize_Address_Stmts (Typ : Entity_Id) return List_Id; -- Subsidiary to Make_Finalize_Address_Body, Make_Deep_Array_Body and -- Make_Deep_Record_Body. Generate the following statements: -- -- declare -- type Acc_Typ is access all Typ; -- for Acc_Typ'Storage_Size use 0; -- begin -- [Deep_]Finalize (Acc_Typ (V).all); -- end; -------------------------------- -- Allows_Finalization_Master -- -------------------------------- function Allows_Finalization_Master (Typ : Entity_Id) return Boolean is function In_Deallocation_Instance (E : Entity_Id) return Boolean; -- Determine whether entity E is inside a wrapper package created for -- an instance of Ada.Unchecked_Deallocation. ------------------------------ -- In_Deallocation_Instance -- ------------------------------ function In_Deallocation_Instance (E : Entity_Id) return Boolean is Pkg : constant Entity_Id := Scope (E); Par : Node_Id := Empty; begin if Ekind (Pkg) = E_Package and then Present (Related_Instance (Pkg)) and then Ekind (Related_Instance (Pkg)) = E_Procedure then Par := Generic_Parent (Parent (Related_Instance (Pkg))); return Present (Par) and then Chars (Par) = Name_Unchecked_Deallocation and then Chars (Scope (Par)) = Name_Ada and then Scope (Scope (Par)) = Standard_Standard; end if; return False; end In_Deallocation_Instance; -- Local variables Desig_Typ : constant Entity_Id := Designated_Type (Typ); Ptr_Typ : constant Entity_Id := Root_Type_Of_Full_View (Base_Type (Typ)); -- Start of processing for Allows_Finalization_Master begin -- Certain run-time configurations and targets do not provide support -- for controlled types and therefore do not need masters. if Restriction_Active (No_Finalization) then return False; -- Do not consider C and C++ types since it is assumed that the non-Ada -- side will handle their cleanup. elsif Convention (Desig_Typ) = Convention_C or else Convention (Desig_Typ) = Convention_CPP then return False; -- Do not consider an access type that returns on the secondary stack elsif Present (Associated_Storage_Pool (Ptr_Typ)) and then Is_RTE (Associated_Storage_Pool (Ptr_Typ), RE_SS_Pool) then return False; -- Do not consider an access type that can never allocate an object elsif No_Pool_Assigned (Ptr_Typ) then return False; -- Do not consider an access type coming from an Unchecked_Deallocation -- instance. Even though the designated type may be controlled, the -- access type will never participate in any allocations. elsif In_Deallocation_Instance (Ptr_Typ) then return False; -- Do not consider a non-library access type when No_Nested_Finalization -- is in effect since finalization masters are controlled objects and if -- created will violate the restriction. elsif Restriction_Active (No_Nested_Finalization) and then not Is_Library_Level_Entity (Ptr_Typ) then return False; -- Do not consider an access type subject to pragma No_Heap_Finalization -- because objects allocated through such a type are not to be finalized -- when the access type goes out of scope. elsif No_Heap_Finalization (Ptr_Typ) then return False; -- Do not create finalization masters in GNATprove mode because this -- causes unwanted extra expansion. A compilation in this mode must -- keep the tree as close as possible to the original sources. elsif GNATprove_Mode then return False; -- Otherwise the access type may use a finalization master else return True; end if; end Allows_Finalization_Master; ---------------------------- -- Build_Anonymous_Master -- ---------------------------- procedure Build_Anonymous_Master (Ptr_Typ : Entity_Id) is function Create_Anonymous_Master (Desig_Typ : Entity_Id; Unit_Id : Entity_Id; Unit_Decl : Node_Id) return Entity_Id; -- Create a new anonymous master for access type Ptr_Typ with designated -- type Desig_Typ. The declaration of the master and its initialization -- are inserted in the declarative part of unit Unit_Decl. Unit_Id is -- the entity of Unit_Decl. function Current_Anonymous_Master (Desig_Typ : Entity_Id; Unit_Id : Entity_Id) return Entity_Id; -- Find an anonymous master declared within unit Unit_Id which services -- designated type Desig_Typ. If there is no such master, return Empty. ----------------------------- -- Create_Anonymous_Master -- ----------------------------- function Create_Anonymous_Master (Desig_Typ : Entity_Id; Unit_Id : Entity_Id; Unit_Decl : Node_Id) return Entity_Id is Loc : constant Source_Ptr := Sloc (Unit_Id); All_FMs : Elist_Id; Decls : List_Id; FM_Decl : Node_Id; FM_Id : Entity_Id; FM_Init : Node_Id; Unit_Spec : Node_Id; begin -- Generate: -- <FM_Id> : Finalization_Master; FM_Id := Make_Temporary (Loc, 'A'); FM_Decl := Make_Object_Declaration (Loc, Defining_Identifier => FM_Id, Object_Definition => New_Occurrence_Of (RTE (RE_Finalization_Master), Loc)); -- Generate: -- Set_Base_Pool -- (<FM_Id>, Global_Pool_Object'Unrestricted_Access); FM_Init := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Set_Base_Pool), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (FM_Id, Loc), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (RTE (RE_Global_Pool_Object), Loc), Attribute_Name => Name_Unrestricted_Access))); -- Find the declarative list of the unit if Nkind (Unit_Decl) = N_Package_Declaration then Unit_Spec := Specification (Unit_Decl); Decls := Visible_Declarations (Unit_Spec); if No (Decls) then Decls := New_List; Set_Visible_Declarations (Unit_Spec, Decls); end if; -- Package body or subprogram case -- ??? A subprogram spec or body that acts as a compilation unit may -- contain a formal parameter of an anonymous access-to-controlled -- type initialized by an allocator. -- procedure Comp_Unit_Proc (Param : access Ctrl := new Ctrl); -- There is no suitable place to create the master as the subprogram -- is not in a declarative list. else Decls := Declarations (Unit_Decl); if No (Decls) then Decls := New_List; Set_Declarations (Unit_Decl, Decls); end if; end if; Prepend_To (Decls, FM_Init); Prepend_To (Decls, FM_Decl); -- Use the scope of the unit when analyzing the declaration of the -- master and its initialization actions. Push_Scope (Unit_Id); Analyze (FM_Decl); Analyze (FM_Init); Pop_Scope; -- Mark the master as servicing this specific designated type Set_Anonymous_Designated_Type (FM_Id, Desig_Typ); -- Include the anonymous master in the list of existing masters which -- appear in this unit. This effectively creates a mapping between a -- master and a designated type which in turn allows for the reuse of -- masters on a per-unit basis. All_FMs := Anonymous_Masters (Unit_Id); if No (All_FMs) then All_FMs := New_Elmt_List; Set_Anonymous_Masters (Unit_Id, All_FMs); end if; Prepend_Elmt (FM_Id, All_FMs); return FM_Id; end Create_Anonymous_Master; ------------------------------ -- Current_Anonymous_Master -- ------------------------------ function Current_Anonymous_Master (Desig_Typ : Entity_Id; Unit_Id : Entity_Id) return Entity_Id is All_FMs : constant Elist_Id := Anonymous_Masters (Unit_Id); FM_Elmt : Elmt_Id; FM_Id : Entity_Id; begin -- Inspect the list of anonymous masters declared within the unit -- looking for an existing master which services the same designated -- type. if Present (All_FMs) then FM_Elmt := First_Elmt (All_FMs); while Present (FM_Elmt) loop FM_Id := Node (FM_Elmt); -- The currect master services the same designated type. As a -- result the master can be reused and associated with another -- anonymous access-to-controlled type. if Anonymous_Designated_Type (FM_Id) = Desig_Typ then return FM_Id; end if; Next_Elmt (FM_Elmt); end loop; end if; return Empty; end Current_Anonymous_Master; -- Local variables Desig_Typ : Entity_Id; FM_Id : Entity_Id; Priv_View : Entity_Id; Unit_Decl : Node_Id; Unit_Id : Entity_Id; -- Start of processing for Build_Anonymous_Master begin -- Nothing to do if the circumstances do not allow for a finalization -- master. if not Allows_Finalization_Master (Ptr_Typ) then return; end if; Unit_Decl := Unit (Cunit (Current_Sem_Unit)); Unit_Id := Unique_Defining_Entity (Unit_Decl); -- The compilation unit is a package instantiation. In this case the -- anonymous master is associated with the package spec as both the -- spec and body appear at the same level. if Nkind (Unit_Decl) = N_Package_Body and then Nkind (Original_Node (Unit_Decl)) = N_Package_Instantiation then Unit_Id := Corresponding_Spec (Unit_Decl); Unit_Decl := Unit_Declaration_Node (Unit_Id); end if; -- Use the initial declaration of the designated type when it denotes -- the full view of an incomplete or private type. This ensures that -- types with one and two views are treated the same. Desig_Typ := Directly_Designated_Type (Ptr_Typ); Priv_View := Incomplete_Or_Partial_View (Desig_Typ); if Present (Priv_View) then Desig_Typ := Priv_View; end if; -- Determine whether the current semantic unit already has an anonymous -- master which services the designated type. FM_Id := Current_Anonymous_Master (Desig_Typ, Unit_Id); -- If this is not the case, create a new master if No (FM_Id) then FM_Id := Create_Anonymous_Master (Desig_Typ, Unit_Id, Unit_Decl); end if; Set_Finalization_Master (Ptr_Typ, FM_Id); end Build_Anonymous_Master; ---------------------------- -- Build_Array_Deep_Procs -- ---------------------------- procedure Build_Array_Deep_Procs (Typ : Entity_Id) is begin Set_TSS (Typ, Make_Deep_Proc (Prim => Initialize_Case, Typ => Typ, Stmts => Make_Deep_Array_Body (Initialize_Case, Typ))); if not Is_Limited_View (Typ) then Set_TSS (Typ, Make_Deep_Proc (Prim => Adjust_Case, Typ => Typ, Stmts => Make_Deep_Array_Body (Adjust_Case, Typ))); end if; -- Do not generate Deep_Finalize and Finalize_Address if finalization is -- suppressed since these routine will not be used. if not Restriction_Active (No_Finalization) then Set_TSS (Typ, Make_Deep_Proc (Prim => Finalize_Case, Typ => Typ, Stmts => Make_Deep_Array_Body (Finalize_Case, Typ))); -- Create TSS primitive Finalize_Address (unless CodePeer_Mode) if not CodePeer_Mode then Set_TSS (Typ, Make_Deep_Proc (Prim => Address_Case, Typ => Typ, Stmts => Make_Deep_Array_Body (Address_Case, Typ))); end if; end if; end Build_Array_Deep_Procs; ------------------------------ -- Build_Cleanup_Statements -- ------------------------------ function Build_Cleanup_Statements (N : Node_Id; Additional_Cleanup : List_Id) return List_Id is Is_Asynchronous_Call : constant Boolean := Nkind (N) = N_Block_Statement and then Is_Asynchronous_Call_Block (N); Is_Master : constant Boolean := Nkind (N) /= N_Entry_Body and then Is_Task_Master (N); Is_Protected_Body : constant Boolean := Nkind (N) = N_Subprogram_Body and then Is_Protected_Subprogram_Body (N); Is_Task_Allocation : constant Boolean := Nkind (N) = N_Block_Statement and then Is_Task_Allocation_Block (N); Is_Task_Body : constant Boolean := Nkind (Original_Node (N)) = N_Task_Body; Loc : constant Source_Ptr := Sloc (N); Stmts : constant List_Id := New_List; begin if Is_Task_Body then if Restricted_Profile then Append_To (Stmts, Build_Runtime_Call (Loc, RE_Complete_Restricted_Task)); else Append_To (Stmts, Build_Runtime_Call (Loc, RE_Complete_Task)); end if; elsif Is_Master then if Restriction_Active (No_Task_Hierarchy) = False then Append_To (Stmts, Build_Runtime_Call (Loc, RE_Complete_Master)); end if; -- Add statements to unlock the protected object parameter and to -- undefer abort. If the context is a protected procedure and the object -- has entries, call the entry service routine. -- NOTE: The generated code references _object, a parameter to the -- procedure. elsif Is_Protected_Body then declare Spec : constant Node_Id := Parent (Corresponding_Spec (N)); Conc_Typ : Entity_Id := Empty; Param : Node_Id; Param_Typ : Entity_Id; begin -- Find the _object parameter representing the protected object Param := First (Parameter_Specifications (Spec)); loop Param_Typ := Etype (Parameter_Type (Param)); if Ekind (Param_Typ) = E_Record_Type then Conc_Typ := Corresponding_Concurrent_Type (Param_Typ); end if; exit when No (Param) or else Present (Conc_Typ); Next (Param); end loop; pragma Assert (Present (Param)); pragma Assert (Present (Conc_Typ)); -- Historical note: In earlier versions of GNAT, there was code -- at this point to generate stuff to service entry queues. It is -- now abstracted in Build_Protected_Subprogram_Call_Cleanup. Build_Protected_Subprogram_Call_Cleanup (Specification (N), Conc_Typ, Loc, Stmts); end; -- Add a call to Expunge_Unactivated_Tasks for dynamically allocated -- tasks. Other unactivated tasks are completed by Complete_Task or -- Complete_Master. -- NOTE: The generated code references _chain, a local object elsif Is_Task_Allocation then -- Generate: -- Expunge_Unactivated_Tasks (_chain); -- where _chain is the list of tasks created by the allocator but not -- yet activated. This list will be empty unless the block completes -- abnormally. Append_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Expunge_Unactivated_Tasks), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Activation_Chain_Entity (N), Loc)))); -- Attempt to cancel an asynchronous entry call whenever the block which -- contains the abortable part is exited. -- NOTE: The generated code references Cnn, a local object elsif Is_Asynchronous_Call then declare Cancel_Param : constant Entity_Id := Entry_Cancel_Parameter (Entity (Identifier (N))); begin -- If it is of type Communication_Block, this must be a protected -- entry call. Generate: -- if Enqueued (Cancel_Param) then -- Cancel_Protected_Entry_Call (Cancel_Param); -- end if; if Is_RTE (Etype (Cancel_Param), RE_Communication_Block) then Append_To (Stmts, Make_If_Statement (Loc, Condition => Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Enqueued), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Cancel_Param, Loc))), Then_Statements => New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Cancel_Protected_Entry_Call), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Cancel_Param, Loc)))))); -- Asynchronous delay, generate: -- Cancel_Async_Delay (Cancel_Param); elsif Is_RTE (Etype (Cancel_Param), RE_Delay_Block) then Append_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Cancel_Async_Delay), Loc), Parameter_Associations => New_List ( Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Cancel_Param, Loc), Attribute_Name => Name_Unchecked_Access)))); -- Task entry call, generate: -- Cancel_Task_Entry_Call (Cancel_Param); else Append_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Cancel_Task_Entry_Call), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Cancel_Param, Loc)))); end if; end; end if; Append_List_To (Stmts, Additional_Cleanup); return Stmts; end Build_Cleanup_Statements; ----------------------------- -- Build_Controlling_Procs -- ----------------------------- procedure Build_Controlling_Procs (Typ : Entity_Id) is begin if Is_Array_Type (Typ) then Build_Array_Deep_Procs (Typ); else pragma Assert (Is_Record_Type (Typ)); Build_Record_Deep_Procs (Typ); end if; end Build_Controlling_Procs; ----------------------------- -- Build_Exception_Handler -- ----------------------------- function Build_Exception_Handler (Data : Finalization_Exception_Data; For_Library : Boolean := False) return Node_Id is Actuals : List_Id; Proc_To_Call : Entity_Id; Except : Node_Id; Stmts : List_Id; begin pragma Assert (Present (Data.Raised_Id)); if Exception_Extra_Info or else (For_Library and not Restricted_Profile) then if Exception_Extra_Info then -- Generate: -- Get_Current_Excep.all Except := Make_Function_Call (Data.Loc, Name => Make_Explicit_Dereference (Data.Loc, Prefix => New_Occurrence_Of (RTE (RE_Get_Current_Excep), Data.Loc))); else -- Generate: -- null Except := Make_Null (Data.Loc); end if; if For_Library and then not Restricted_Profile then Proc_To_Call := RTE (RE_Save_Library_Occurrence); Actuals := New_List (Except); else Proc_To_Call := RTE (RE_Save_Occurrence); -- The dereference occurs only when Exception_Extra_Info is true, -- and therefore Except is not null. Actuals := New_List ( New_Occurrence_Of (Data.E_Id, Data.Loc), Make_Explicit_Dereference (Data.Loc, Except)); end if; -- Generate: -- when others => -- if not Raised_Id then -- Raised_Id := True; -- Save_Occurrence (E_Id, Get_Current_Excep.all.all); -- or -- Save_Library_Occurrence (Get_Current_Excep.all); -- end if; Stmts := New_List ( Make_If_Statement (Data.Loc, Condition => Make_Op_Not (Data.Loc, Right_Opnd => New_Occurrence_Of (Data.Raised_Id, Data.Loc)), Then_Statements => New_List ( Make_Assignment_Statement (Data.Loc, Name => New_Occurrence_Of (Data.Raised_Id, Data.Loc), Expression => New_Occurrence_Of (Standard_True, Data.Loc)), Make_Procedure_Call_Statement (Data.Loc, Name => New_Occurrence_Of (Proc_To_Call, Data.Loc), Parameter_Associations => Actuals)))); else -- Generate: -- Raised_Id := True; Stmts := New_List ( Make_Assignment_Statement (Data.Loc, Name => New_Occurrence_Of (Data.Raised_Id, Data.Loc), Expression => New_Occurrence_Of (Standard_True, Data.Loc))); end if; -- Generate: -- when others => return Make_Exception_Handler (Data.Loc, Exception_Choices => New_List (Make_Others_Choice (Data.Loc)), Statements => Stmts); end Build_Exception_Handler; ------------------------------- -- Build_Finalization_Master -- ------------------------------- procedure Build_Finalization_Master (Typ : Entity_Id; For_Lib_Level : Boolean := False; For_Private : Boolean := False; Context_Scope : Entity_Id := Empty; Insertion_Node : Node_Id := Empty) is procedure Add_Pending_Access_Type (Typ : Entity_Id; Ptr_Typ : Entity_Id); -- Add access type Ptr_Typ to the pending access type list for type Typ ----------------------------- -- Add_Pending_Access_Type -- ----------------------------- procedure Add_Pending_Access_Type (Typ : Entity_Id; Ptr_Typ : Entity_Id) is List : Elist_Id; begin if Present (Pending_Access_Types (Typ)) then List := Pending_Access_Types (Typ); else List := New_Elmt_List; Set_Pending_Access_Types (Typ, List); end if; Prepend_Elmt (Ptr_Typ, List); end Add_Pending_Access_Type; -- Local variables Desig_Typ : constant Entity_Id := Designated_Type (Typ); Ptr_Typ : constant Entity_Id := Root_Type_Of_Full_View (Base_Type (Typ)); -- A finalization master created for a named access type is associated -- with the full view (if applicable) as a consequence of freezing. The -- full view criteria does not apply to anonymous access types because -- those cannot have a private and a full view. -- Start of processing for Build_Finalization_Master begin -- Nothing to do if the circumstances do not allow for a finalization -- master. if not Allows_Finalization_Master (Typ) then return; -- Various machinery such as freezing may have already created a -- finalization master. elsif Present (Finalization_Master (Ptr_Typ)) then return; end if; declare Actions : constant List_Id := New_List; Loc : constant Source_Ptr := Sloc (Ptr_Typ); Fin_Mas_Id : Entity_Id; Pool_Id : Entity_Id; begin -- Source access types use fixed master names since the master is -- inserted in the same source unit only once. The only exception to -- this are instances using the same access type as generic actual. if Comes_From_Source (Ptr_Typ) and then not Inside_A_Generic then Fin_Mas_Id := Make_Defining_Identifier (Loc, Chars => New_External_Name (Chars (Ptr_Typ), "FM")); -- Internally generated access types use temporaries as their names -- due to possible collision with identical names coming from other -- packages. else Fin_Mas_Id := Make_Temporary (Loc, 'F'); end if; Set_Finalization_Master (Ptr_Typ, Fin_Mas_Id); -- Generate: -- <Ptr_Typ>FM : aliased Finalization_Master; Append_To (Actions, Make_Object_Declaration (Loc, Defining_Identifier => Fin_Mas_Id, Aliased_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Finalization_Master), Loc))); -- Set the associated pool and primitive Finalize_Address of the new -- finalization master. -- The access type has a user-defined storage pool, use it if Present (Associated_Storage_Pool (Ptr_Typ)) then Pool_Id := Associated_Storage_Pool (Ptr_Typ); -- Otherwise the default choice is the global storage pool else Pool_Id := RTE (RE_Global_Pool_Object); Set_Associated_Storage_Pool (Ptr_Typ, Pool_Id); end if; -- Generate: -- Set_Base_Pool (<Ptr_Typ>FM, Pool_Id'Unchecked_Access); Append_To (Actions, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Set_Base_Pool), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Fin_Mas_Id, Loc), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Pool_Id, Loc), Attribute_Name => Name_Unrestricted_Access)))); -- Finalize_Address is not generated in CodePeer mode because the -- body contains address arithmetic. Skip this step. if CodePeer_Mode then null; -- Associate the Finalize_Address primitive of the designated type -- with the finalization master of the access type. The designated -- type must be forzen as Finalize_Address is generated when the -- freeze node is expanded. elsif Is_Frozen (Desig_Typ) and then Present (Finalize_Address (Desig_Typ)) -- The finalization master of an anonymous access type may need -- to be inserted in a specific place in the tree. For instance: -- type Comp_Typ; -- <finalization master of "access Comp_Typ"> -- type Rec_Typ is record -- Comp : access Comp_Typ; -- end record; -- <freeze node for Comp_Typ> -- <freeze node for Rec_Typ> -- Due to this oddity, the anonymous access type is stored for -- later processing (see below). and then Ekind (Ptr_Typ) /= E_Anonymous_Access_Type then -- Generate: -- Set_Finalize_Address -- (<Ptr_Typ>FM, <Desig_Typ>FD'Unrestricted_Access); Append_To (Actions, Make_Set_Finalize_Address_Call (Loc => Loc, Ptr_Typ => Ptr_Typ)); -- Otherwise the designated type is either anonymous access or a -- Taft-amendment type and has not been frozen. Store the access -- type for later processing (see Freeze_Type). else Add_Pending_Access_Type (Desig_Typ, Ptr_Typ); end if; -- A finalization master created for an access designating a type -- with private components is inserted before a context-dependent -- node. if For_Private then -- At this point both the scope of the context and the insertion -- mode must be known. pragma Assert (Present (Context_Scope)); pragma Assert (Present (Insertion_Node)); Push_Scope (Context_Scope); -- Treat use clauses as declarations and insert directly in front -- of them. if Nkind (Insertion_Node) in N_Use_Package_Clause | N_Use_Type_Clause then Insert_List_Before_And_Analyze (Insertion_Node, Actions); else Insert_Actions (Insertion_Node, Actions); end if; Pop_Scope; -- The finalization master belongs to an access result type related -- to a build-in-place function call used to initialize a library -- level object. The master must be inserted in front of the access -- result type declaration denoted by Insertion_Node. elsif For_Lib_Level then pragma Assert (Present (Insertion_Node)); Insert_Actions (Insertion_Node, Actions); -- Otherwise the finalization master and its initialization become a -- part of the freeze node. else Append_Freeze_Actions (Ptr_Typ, Actions); end if; end; end Build_Finalization_Master; --------------------- -- Build_Finalizer -- --------------------- procedure Build_Finalizer (N : Node_Id; Clean_Stmts : List_Id; Mark_Id : Entity_Id; Top_Decls : List_Id; Defer_Abort : Boolean; Fin_Id : out Entity_Id) is Acts_As_Clean : constant Boolean := Present (Mark_Id) or else (Present (Clean_Stmts) and then Is_Non_Empty_List (Clean_Stmts)); For_Package_Body : constant Boolean := Nkind (N) = N_Package_Body; For_Package_Spec : constant Boolean := Nkind (N) = N_Package_Declaration; For_Package : constant Boolean := For_Package_Body or else For_Package_Spec; Loc : constant Source_Ptr := Sloc (N); -- NOTE: Local variable declarations are conservative and do not create -- structures right from the start. Entities and lists are created once -- it has been established that N has at least one controlled object. Components_Built : Boolean := False; -- A flag used to avoid double initialization of entities and lists. If -- the flag is set then the following variables have been initialized: -- Counter_Id -- Finalizer_Decls -- Finalizer_Stmts -- Jump_Alts Counter_Id : Entity_Id := Empty; Counter_Val : Nat := 0; -- Name and value of the state counter Decls : List_Id := No_List; -- Declarative region of N (if available). If N is a package declaration -- Decls denotes the visible declarations. Finalizer_Data : Finalization_Exception_Data; -- Data for the exception Finalizer_Decls : List_Id := No_List; -- Local variable declarations. This list holds the label declarations -- of all jump block alternatives as well as the declaration of the -- local exception occurrence and the raised flag: -- E : Exception_Occurrence; -- Raised : Boolean := False; -- L<counter value> : label; Finalizer_Insert_Nod : Node_Id := Empty; -- Insertion point for the finalizer body. Depending on the context -- (Nkind of N) and the individual grouping of controlled objects, this -- node may denote a package declaration or body, package instantiation, -- block statement or a counter update statement. Finalizer_Stmts : List_Id := No_List; -- The statement list of the finalizer body. It contains the following: -- -- Abort_Defer; -- Added if abort is allowed -- <call to Prev_At_End> -- Added if exists -- <cleanup statements> -- Added if Acts_As_Clean -- <jump block> -- Added if Has_Ctrl_Objs -- <finalization statements> -- Added if Has_Ctrl_Objs -- <stack release> -- Added if Mark_Id exists -- Abort_Undefer; -- Added if abort is allowed Has_Ctrl_Objs : Boolean := False; -- A general flag which denotes whether N has at least one controlled -- object. Has_Tagged_Types : Boolean := False; -- A general flag which indicates whether N has at least one library- -- level tagged type declaration. HSS : Node_Id := Empty; -- The sequence of statements of N (if available) Jump_Alts : List_Id := No_List; -- Jump block alternatives. Depending on the value of the state counter, -- the control flow jumps to a sequence of finalization statements. This -- list contains the following: -- -- when <counter value> => -- goto L<counter value>; Jump_Block_Insert_Nod : Node_Id := Empty; -- Specific point in the finalizer statements where the jump block is -- inserted. Last_Top_Level_Ctrl_Construct : Node_Id := Empty; -- The last controlled construct encountered when processing the top -- level lists of N. This can be a nested package, an instantiation or -- an object declaration. Prev_At_End : Entity_Id := Empty; -- The previous at end procedure of the handled statements block of N Priv_Decls : List_Id := No_List; -- The private declarations of N if N is a package declaration Spec_Id : Entity_Id := Empty; Spec_Decls : List_Id := Top_Decls; Stmts : List_Id := No_List; Tagged_Type_Stmts : List_Id := No_List; -- Contains calls to Ada.Tags.Unregister_Tag for all library-level -- tagged types found in N. ----------------------- -- Local subprograms -- ----------------------- procedure Build_Components; -- Create all entites and initialize all lists used in the creation of -- the finalizer. procedure Create_Finalizer; -- Create the spec and body of the finalizer and insert them in the -- proper place in the tree depending on the context. procedure Process_Declarations (Decls : List_Id; Preprocess : Boolean := False; Top_Level : Boolean := False); -- Inspect a list of declarations or statements which may contain -- objects that need finalization. When flag Preprocess is set, the -- routine will simply count the total number of controlled objects in -- Decls. Flag Top_Level denotes whether the processing is done for -- objects in nested package declarations or instances. procedure Process_Object_Declaration (Decl : Node_Id; Has_No_Init : Boolean := False; Is_Protected : Boolean := False); -- Generate all the machinery associated with the finalization of a -- single object. Flag Has_No_Init is used to denote certain contexts -- where Decl does not have initialization call(s). Flag Is_Protected -- is set when Decl denotes a simple protected object. procedure Process_Tagged_Type_Declaration (Decl : Node_Id); -- Generate all the code necessary to unregister the external tag of a -- tagged type. ---------------------- -- Build_Components -- ---------------------- procedure Build_Components is Counter_Decl : Node_Id; Counter_Typ : Entity_Id; Counter_Typ_Decl : Node_Id; begin pragma Assert (Present (Decls)); -- This routine might be invoked several times when dealing with -- constructs that have two lists (either two declarative regions -- or declarations and statements). Avoid double initialization. if Components_Built then return; end if; Components_Built := True; if Has_Ctrl_Objs then -- Create entities for the counter, its type, the local exception -- and the raised flag. Counter_Id := Make_Temporary (Loc, 'C'); Counter_Typ := Make_Temporary (Loc, 'T'); Finalizer_Decls := New_List; Build_Object_Declarations (Finalizer_Data, Finalizer_Decls, Loc, For_Package); -- Since the total number of controlled objects is always known, -- build a subtype of Natural with precise bounds. This allows -- the backend to optimize the case statement. Generate: -- -- subtype Tnn is Natural range 0 .. Counter_Val; Counter_Typ_Decl := Make_Subtype_Declaration (Loc, Defining_Identifier => Counter_Typ, Subtype_Indication => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (Standard_Natural, Loc), Constraint => Make_Range_Constraint (Loc, Range_Expression => Make_Range (Loc, Low_Bound => Make_Integer_Literal (Loc, Uint_0), High_Bound => Make_Integer_Literal (Loc, Counter_Val))))); -- Generate the declaration of the counter itself: -- -- Counter : Integer := 0; Counter_Decl := Make_Object_Declaration (Loc, Defining_Identifier => Counter_Id, Object_Definition => New_Occurrence_Of (Counter_Typ, Loc), Expression => Make_Integer_Literal (Loc, 0)); -- Set the type of the counter explicitly to prevent errors when -- examining object declarations later on. Set_Etype (Counter_Id, Counter_Typ); -- The counter and its type are inserted before the source -- declarations of N. Prepend_To (Decls, Counter_Decl); Prepend_To (Decls, Counter_Typ_Decl); -- The counter and its associated type must be manually analyzed -- since N has already been analyzed. Use the scope of the spec -- when inserting in a package. if For_Package then Push_Scope (Spec_Id); Analyze (Counter_Typ_Decl); Analyze (Counter_Decl); Pop_Scope; else Analyze (Counter_Typ_Decl); Analyze (Counter_Decl); end if; Jump_Alts := New_List; end if; -- If the context requires additional cleanup, the finalization -- machinery is added after the cleanup code. if Acts_As_Clean then Finalizer_Stmts := Clean_Stmts; Jump_Block_Insert_Nod := Last (Finalizer_Stmts); else Finalizer_Stmts := New_List; end if; if Has_Tagged_Types then Tagged_Type_Stmts := New_List; end if; end Build_Components; ---------------------- -- Create_Finalizer -- ---------------------- procedure Create_Finalizer is function New_Finalizer_Name return Name_Id; -- Create a fully qualified name of a package spec or body finalizer. -- The generated name is of the form: xx__yy__finalize_[spec|body]. ------------------------ -- New_Finalizer_Name -- ------------------------ function New_Finalizer_Name return Name_Id is procedure New_Finalizer_Name (Id : Entity_Id); -- Place "__<name-of-Id>" in the name buffer. If the identifier -- has a non-standard scope, process the scope first. ------------------------ -- New_Finalizer_Name -- ------------------------ procedure New_Finalizer_Name (Id : Entity_Id) is begin if Scope (Id) = Standard_Standard then Get_Name_String (Chars (Id)); else New_Finalizer_Name (Scope (Id)); Add_Str_To_Name_Buffer ("__"); Add_Str_To_Name_Buffer (Get_Name_String (Chars (Id))); end if; end New_Finalizer_Name; -- Start of processing for New_Finalizer_Name begin -- Create the fully qualified name of the enclosing scope New_Finalizer_Name (Spec_Id); -- Generate: -- __finalize_[spec|body] Add_Str_To_Name_Buffer ("__finalize_"); if For_Package_Spec then Add_Str_To_Name_Buffer ("spec"); else Add_Str_To_Name_Buffer ("body"); end if; return Name_Find; end New_Finalizer_Name; -- Local variables Body_Id : Entity_Id; Fin_Body : Node_Id; Fin_Spec : Node_Id; Jump_Block : Node_Id; Label : Node_Id; Label_Id : Entity_Id; -- Start of processing for Create_Finalizer begin -- Step 1: Creation of the finalizer name -- Packages must use a distinct name for their finalizers since the -- binder will have to generate calls to them by name. The name is -- of the following form: -- xx__yy__finalize_[spec|body] if For_Package then Fin_Id := Make_Defining_Identifier (Loc, New_Finalizer_Name); Set_Has_Qualified_Name (Fin_Id); Set_Has_Fully_Qualified_Name (Fin_Id); -- The default name is _finalizer else Fin_Id := Make_Defining_Identifier (Loc, Chars => New_External_Name (Name_uFinalizer)); -- The visibility semantics of AT_END handlers force a strange -- separation of spec and body for stack-related finalizers: -- declare : Enclosing_Scope -- procedure _finalizer; -- begin -- <controlled objects> -- procedure _finalizer is -- ... -- at end -- _finalizer; -- end; -- Both spec and body are within the same construct and scope, but -- the body is part of the handled sequence of statements. This -- placement confuses the elaboration mechanism on targets where -- AT_END handlers are expanded into "when all others" handlers: -- exception -- when all others => -- _finalizer; -- appears to require elab checks -- at end -- _finalizer; -- end; -- Since the compiler guarantees that the body of a _finalizer is -- always inserted in the same construct where the AT_END handler -- resides, there is no need for elaboration checks. Set_Kill_Elaboration_Checks (Fin_Id); -- Inlining the finalizer produces a substantial speedup at -O2. -- It is inlined by default at -O3. Either way, it is called -- exactly twice (once on the normal path, and once for -- exceptions/abort), so this won't bloat the code too much. Set_Is_Inlined (Fin_Id); end if; -- Step 2: Creation of the finalizer specification -- Generate: -- procedure Fin_Id; Fin_Spec := Make_Subprogram_Declaration (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Fin_Id)); -- Step 3: Creation of the finalizer body if Has_Ctrl_Objs then -- Add L0, the default destination to the jump block Label_Id := Make_Identifier (Loc, New_External_Name ('L', 0)); Set_Entity (Label_Id, Make_Defining_Identifier (Loc, Chars (Label_Id))); Label := Make_Label (Loc, Label_Id); -- Generate: -- L0 : label; Prepend_To (Finalizer_Decls, Make_Implicit_Label_Declaration (Loc, Defining_Identifier => Entity (Label_Id), Label_Construct => Label)); -- Generate: -- when others => -- goto L0; Append_To (Jump_Alts, Make_Case_Statement_Alternative (Loc, Discrete_Choices => New_List (Make_Others_Choice (Loc)), Statements => New_List ( Make_Goto_Statement (Loc, Name => New_Occurrence_Of (Entity (Label_Id), Loc))))); -- Generate: -- <<L0>> Append_To (Finalizer_Stmts, Label); -- Create the jump block which controls the finalization flow -- depending on the value of the state counter. Jump_Block := Make_Case_Statement (Loc, Expression => Make_Identifier (Loc, Chars (Counter_Id)), Alternatives => Jump_Alts); if Acts_As_Clean and then Present (Jump_Block_Insert_Nod) then Insert_After (Jump_Block_Insert_Nod, Jump_Block); else Prepend_To (Finalizer_Stmts, Jump_Block); end if; end if; -- Add the library-level tagged type unregistration machinery before -- the jump block circuitry. This ensures that external tags will be -- removed even if a finalization exception occurs at some point. if Has_Tagged_Types then Prepend_List_To (Finalizer_Stmts, Tagged_Type_Stmts); end if; -- Add a call to the previous At_End handler if it exists. The call -- must always precede the jump block. if Present (Prev_At_End) then Prepend_To (Finalizer_Stmts, Make_Procedure_Call_Statement (Loc, Prev_At_End)); -- Clear the At_End handler since we have already generated the -- proper replacement call for it. Set_At_End_Proc (HSS, Empty); end if; -- Release the secondary stack if Present (Mark_Id) then declare Release : Node_Id := Build_SS_Release_Call (Loc, Mark_Id); begin -- If the context is a build-in-place function, the secondary -- stack must be released, unless the build-in-place function -- itself is returning on the secondary stack. Generate: -- -- if BIP_Alloc_Form /= Secondary_Stack then -- SS_Release (Mark_Id); -- end if; -- -- Note that if the function returns on the secondary stack, -- then the responsibility of reclaiming the space is always -- left to the caller (recursively if needed). if Nkind (N) = N_Subprogram_Body then declare Spec_Id : constant Entity_Id := Unique_Defining_Entity (N); BIP_SS : constant Boolean := Is_Build_In_Place_Function (Spec_Id) and then Needs_BIP_Alloc_Form (Spec_Id); begin if BIP_SS then Release := Make_If_Statement (Loc, Condition => Make_Op_Ne (Loc, Left_Opnd => New_Occurrence_Of (Build_In_Place_Formal (Spec_Id, BIP_Alloc_Form), Loc), Right_Opnd => Make_Integer_Literal (Loc, UI_From_Int (BIP_Allocation_Form'Pos (Secondary_Stack)))), Then_Statements => New_List (Release)); end if; end; end if; Append_To (Finalizer_Stmts, Release); end; end if; -- Protect the statements with abort defer/undefer. This is only when -- aborts are allowed and the cleanup statements require deferral or -- there are controlled objects to be finalized. Note that the abort -- defer/undefer pair does not require an extra block because each -- finalization exception is caught in its corresponding finalization -- block. As a result, the call to Abort_Defer always takes place. if Abort_Allowed and then (Defer_Abort or Has_Ctrl_Objs) then Prepend_To (Finalizer_Stmts, Build_Runtime_Call (Loc, RE_Abort_Defer)); Append_To (Finalizer_Stmts, Build_Runtime_Call (Loc, RE_Abort_Undefer)); end if; -- The local exception does not need to be reraised for library-level -- finalizers. Note that this action must be carried out after object -- cleanup, secondary stack release, and abort undeferral. Generate: -- if Raised and then not Abort then -- Raise_From_Controlled_Operation (E); -- end if; if Has_Ctrl_Objs and Exceptions_OK and not For_Package then Append_To (Finalizer_Stmts, Build_Raise_Statement (Finalizer_Data)); end if; -- Generate: -- procedure Fin_Id is -- Abort : constant Boolean := Triggered_By_Abort; -- <or> -- Abort : constant Boolean := False; -- no abort -- E : Exception_Occurrence; -- All added if flag -- Raised : Boolean := False; -- Has_Ctrl_Objs is set -- L0 : label; -- ... -- Lnn : label; -- begin -- Abort_Defer; -- Added if abort is allowed -- <call to Prev_At_End> -- Added if exists -- <cleanup statements> -- Added if Acts_As_Clean -- <jump block> -- Added if Has_Ctrl_Objs -- <finalization statements> -- Added if Has_Ctrl_Objs -- <stack release> -- Added if Mark_Id exists -- Abort_Undefer; -- Added if abort is allowed -- <exception propagation> -- Added if Has_Ctrl_Objs -- end Fin_Id; -- Create the body of the finalizer Body_Id := Make_Defining_Identifier (Loc, Chars (Fin_Id)); if For_Package then Set_Has_Qualified_Name (Body_Id); Set_Has_Fully_Qualified_Name (Body_Id); end if; Fin_Body := Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Body_Id), Declarations => Finalizer_Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Finalizer_Stmts)); -- Step 4: Spec and body insertion, analysis if For_Package then -- If the package spec has private declarations, the finalizer -- body must be added to the end of the list in order to have -- visibility of all private controlled objects. if For_Package_Spec then if Present (Priv_Decls) then Append_To (Priv_Decls, Fin_Spec); Append_To (Priv_Decls, Fin_Body); else Append_To (Decls, Fin_Spec); Append_To (Decls, Fin_Body); end if; -- For package bodies, both the finalizer spec and body are -- inserted at the end of the package declarations. else Append_To (Decls, Fin_Spec); Append_To (Decls, Fin_Body); end if; -- Push the name of the package Push_Scope (Spec_Id); Analyze (Fin_Spec); Analyze (Fin_Body); Pop_Scope; -- Non-package case else -- Create the spec for the finalizer. The At_End handler must be -- able to call the body which resides in a nested structure. -- Generate: -- declare -- procedure Fin_Id; -- Spec -- begin -- <objects and possibly statements> -- procedure Fin_Id is ... -- Body -- <statements> -- at end -- Fin_Id; -- At_End handler -- end; pragma Assert (Present (Spec_Decls)); Append_To (Spec_Decls, Fin_Spec); Analyze (Fin_Spec); -- When the finalizer acts solely as a cleanup routine, the body -- is inserted right after the spec. if Acts_As_Clean and not Has_Ctrl_Objs then Insert_After (Fin_Spec, Fin_Body); -- In all other cases the body is inserted after either: -- -- 1) The counter update statement of the last controlled object -- 2) The last top level nested controlled package -- 3) The last top level controlled instantiation else -- Manually freeze the spec. This is somewhat of a hack because -- a subprogram is frozen when its body is seen and the freeze -- node appears right before the body. However, in this case, -- the spec must be frozen earlier since the At_End handler -- must be able to call it. -- -- declare -- procedure Fin_Id; -- Spec -- [Fin_Id] -- Freeze node -- begin -- ... -- at end -- Fin_Id; -- At_End handler -- end; Ensure_Freeze_Node (Fin_Id); Insert_After (Fin_Spec, Freeze_Node (Fin_Id)); Set_Is_Frozen (Fin_Id); -- In the case where the last construct to contain a controlled -- object is either a nested package, an instantiation or a -- freeze node, the body must be inserted directly after the -- construct. if Nkind (Last_Top_Level_Ctrl_Construct) in N_Freeze_Entity | N_Package_Declaration | N_Package_Body then Finalizer_Insert_Nod := Last_Top_Level_Ctrl_Construct; end if; Insert_After (Finalizer_Insert_Nod, Fin_Body); end if; Analyze (Fin_Body, Suppress => All_Checks); end if; -- Never consider that the finalizer procedure is enabled Ghost, even -- when the corresponding unit is Ghost, as this would lead to an -- an external name with a ___ghost_ prefix that the binder cannot -- generate, as it has no knowledge of the Ghost status of units. Set_Is_Checked_Ghost_Entity (Fin_Id, False); end Create_Finalizer; -------------------------- -- Process_Declarations -- -------------------------- procedure Process_Declarations (Decls : List_Id; Preprocess : Boolean := False; Top_Level : Boolean := False) is Decl : Node_Id; Expr : Node_Id; Obj_Id : Entity_Id; Obj_Typ : Entity_Id; Pack_Id : Entity_Id; Spec : Node_Id; Typ : Entity_Id; Old_Counter_Val : Nat; -- This variable is used to determine whether a nested package or -- instance contains at least one controlled object. procedure Processing_Actions (Has_No_Init : Boolean := False; Is_Protected : Boolean := False); -- Depending on the mode of operation of Process_Declarations, either -- increment the controlled object counter, set the controlled object -- flag and store the last top level construct or process the current -- declaration. Flag Has_No_Init is used to propagate scenarios where -- the current declaration may not have initialization proc(s). Flag -- Is_Protected should be set when the current declaration denotes a -- simple protected object. ------------------------ -- Processing_Actions -- ------------------------ procedure Processing_Actions (Has_No_Init : Boolean := False; Is_Protected : Boolean := False) is begin -- Library-level tagged type if Nkind (Decl) = N_Full_Type_Declaration then if Preprocess then Has_Tagged_Types := True; if Top_Level and then No (Last_Top_Level_Ctrl_Construct) then Last_Top_Level_Ctrl_Construct := Decl; end if; else Process_Tagged_Type_Declaration (Decl); end if; -- Controlled object declaration else if Preprocess then Counter_Val := Counter_Val + 1; Has_Ctrl_Objs := True; if Top_Level and then No (Last_Top_Level_Ctrl_Construct) then Last_Top_Level_Ctrl_Construct := Decl; end if; else Process_Object_Declaration (Decl, Has_No_Init, Is_Protected); end if; end if; end Processing_Actions; -- Start of processing for Process_Declarations begin if No (Decls) or else Is_Empty_List (Decls) then return; end if; -- Process all declarations in reverse order Decl := Last_Non_Pragma (Decls); while Present (Decl) loop -- Library-level tagged types if Nkind (Decl) = N_Full_Type_Declaration then Typ := Defining_Identifier (Decl); -- Ignored Ghost types do not need any cleanup actions because -- they will not appear in the final tree. if Is_Ignored_Ghost_Entity (Typ) then null; elsif Is_Tagged_Type (Typ) and then Is_Library_Level_Entity (Typ) and then Convention (Typ) = Convention_Ada and then Present (Access_Disp_Table (Typ)) and then RTE_Available (RE_Register_Tag) and then not Is_Abstract_Type (Typ) and then not No_Run_Time_Mode then Processing_Actions; end if; -- Regular object declarations elsif Nkind (Decl) = N_Object_Declaration then Obj_Id := Defining_Identifier (Decl); Obj_Typ := Base_Type (Etype (Obj_Id)); Expr := Expression (Decl); -- Bypass any form of processing for objects which have their -- finalization disabled. This applies only to objects at the -- library level. if For_Package and then Finalize_Storage_Only (Obj_Typ) then null; -- Finalization of transient objects are treated separately in -- order to handle sensitive cases. These include: -- * Aggregate expansion -- * If, case, and expression with actions expansion -- * Transient scopes -- If one of those contexts has marked the transient object as -- ignored, do not generate finalization actions for it. elsif Is_Finalized_Transient (Obj_Id) or else Is_Ignored_Transient (Obj_Id) then null; -- Ignored Ghost objects do not need any cleanup actions -- because they will not appear in the final tree. elsif Is_Ignored_Ghost_Entity (Obj_Id) then null; -- The object is of the form: -- Obj : [constant] Typ [:= Expr]; -- Do not process tag-to-class-wide conversions because they do -- not yield an object. Do not process the incomplete view of a -- deferred constant. Note that an object initialized by means -- of a build-in-place function call may appear as a deferred -- constant after expansion activities. These kinds of objects -- must be finalized. elsif not Is_Imported (Obj_Id) and then Needs_Finalization (Obj_Typ) and then not Is_Tag_To_Class_Wide_Conversion (Obj_Id) and then not (Ekind (Obj_Id) = E_Constant and then not Has_Completion (Obj_Id) and then No (BIP_Initialization_Call (Obj_Id))) then Processing_Actions; -- The object is of the form: -- Obj : Access_Typ := Non_BIP_Function_Call'reference; -- Obj : Access_Typ := -- BIP_Function_Call (BIPalloc => 2, ...)'reference; elsif Is_Access_Type (Obj_Typ) and then Needs_Finalization (Available_View (Designated_Type (Obj_Typ))) and then Present (Expr) and then (Is_Secondary_Stack_BIP_Func_Call (Expr) or else (Is_Non_BIP_Func_Call (Expr) and then not Is_Related_To_Func_Return (Obj_Id))) then Processing_Actions (Has_No_Init => True); -- Processing for "hook" objects generated for transient -- objects declared inside an Expression_With_Actions. elsif Is_Access_Type (Obj_Typ) and then Present (Status_Flag_Or_Transient_Decl (Obj_Id)) and then Nkind (Status_Flag_Or_Transient_Decl (Obj_Id)) = N_Object_Declaration then Processing_Actions (Has_No_Init => True); -- Process intermediate results of an if expression with one -- of the alternatives using a controlled function call. elsif Is_Access_Type (Obj_Typ) and then Present (Status_Flag_Or_Transient_Decl (Obj_Id)) and then Nkind (Status_Flag_Or_Transient_Decl (Obj_Id)) = N_Defining_Identifier and then Present (Expr) and then Nkind (Expr) = N_Null then Processing_Actions (Has_No_Init => True); -- Simple protected objects which use type System.Tasking. -- Protected_Objects.Protection to manage their locks should -- be treated as controlled since they require manual cleanup. -- The only exception is illustrated in the following example: -- package Pkg is -- type Ctrl is new Controlled ... -- procedure Finalize (Obj : in out Ctrl); -- Lib_Obj : Ctrl; -- end Pkg; -- package body Pkg is -- protected Prot is -- procedure Do_Something (Obj : in out Ctrl); -- end Prot; -- protected body Prot is -- procedure Do_Something (Obj : in out Ctrl) is ... -- end Prot; -- procedure Finalize (Obj : in out Ctrl) is -- begin -- Prot.Do_Something (Obj); -- end Finalize; -- end Pkg; -- Since for the most part entities in package bodies depend on -- those in package specs, Prot's lock should be cleaned up -- first. The subsequent cleanup of the spec finalizes Lib_Obj. -- This act however attempts to invoke Do_Something and fails -- because the lock has disappeared. elsif Ekind (Obj_Id) = E_Variable and then not In_Library_Level_Package_Body (Obj_Id) and then (Is_Simple_Protected_Type (Obj_Typ) or else Has_Simple_Protected_Object (Obj_Typ)) then Processing_Actions (Is_Protected => True); end if; -- Specific cases of object renamings elsif Nkind (Decl) = N_Object_Renaming_Declaration then Obj_Id := Defining_Identifier (Decl); Obj_Typ := Base_Type (Etype (Obj_Id)); -- Bypass any form of processing for objects which have their -- finalization disabled. This applies only to objects at the -- library level. if For_Package and then Finalize_Storage_Only (Obj_Typ) then null; -- Ignored Ghost object renamings do not need any cleanup -- actions because they will not appear in the final tree. elsif Is_Ignored_Ghost_Entity (Obj_Id) then null; -- Return object of a build-in-place function. This case is -- recognized and marked by the expansion of an extended return -- statement (see Expand_N_Extended_Return_Statement). elsif Needs_Finalization (Obj_Typ) and then Is_Return_Object (Obj_Id) and then Present (Status_Flag_Or_Transient_Decl (Obj_Id)) then Processing_Actions (Has_No_Init => True); -- Detect a case where a source object has been initialized by -- a controlled function call or another object which was later -- rewritten as a class-wide conversion of Ada.Tags.Displace. -- Obj1 : CW_Type := Src_Obj; -- Obj2 : CW_Type := Function_Call (...); -- Obj1 : CW_Type renames (... Ada.Tags.Displace (Src_Obj)); -- Tmp : ... := Function_Call (...)'reference; -- Obj2 : CW_Type renames (... Ada.Tags.Displace (Tmp)); elsif Is_Displacement_Of_Object_Or_Function_Result (Obj_Id) then Processing_Actions (Has_No_Init => True); end if; -- Inspect the freeze node of an access-to-controlled type and -- look for a delayed finalization master. This case arises when -- the freeze actions are inserted at a later time than the -- expansion of the context. Since Build_Finalizer is never called -- on a single construct twice, the master will be ultimately -- left out and never finalized. This is also needed for freeze -- actions of designated types themselves, since in some cases the -- finalization master is associated with a designated type's -- freeze node rather than that of the access type (see handling -- for freeze actions in Build_Finalization_Master). elsif Nkind (Decl) = N_Freeze_Entity and then Present (Actions (Decl)) then Typ := Entity (Decl); -- Freeze nodes for ignored Ghost types do not need cleanup -- actions because they will never appear in the final tree. if Is_Ignored_Ghost_Entity (Typ) then null; elsif (Is_Access_Type (Typ) and then not Is_Access_Subprogram_Type (Typ) and then Needs_Finalization (Available_View (Designated_Type (Typ)))) or else (Is_Type (Typ) and then Needs_Finalization (Typ)) then Old_Counter_Val := Counter_Val; -- Freeze nodes are considered to be identical to packages -- and blocks in terms of nesting. The difference is that -- a finalization master created inside the freeze node is -- at the same nesting level as the node itself. Process_Declarations (Actions (Decl), Preprocess); -- The freeze node contains a finalization master if Preprocess and then Top_Level and then No (Last_Top_Level_Ctrl_Construct) and then Counter_Val > Old_Counter_Val then Last_Top_Level_Ctrl_Construct := Decl; end if; end if; -- Nested package declarations, avoid generics elsif Nkind (Decl) = N_Package_Declaration then Pack_Id := Defining_Entity (Decl); Spec := Specification (Decl); -- Do not inspect an ignored Ghost package because all code -- found within will not appear in the final tree. if Is_Ignored_Ghost_Entity (Pack_Id) then null; elsif Ekind (Pack_Id) /= E_Generic_Package then Old_Counter_Val := Counter_Val; Process_Declarations (Private_Declarations (Spec), Preprocess); Process_Declarations (Visible_Declarations (Spec), Preprocess); -- Either the visible or the private declarations contain a -- controlled object. The nested package declaration is the -- last such construct. if Preprocess and then Top_Level and then No (Last_Top_Level_Ctrl_Construct) and then Counter_Val > Old_Counter_Val then Last_Top_Level_Ctrl_Construct := Decl; end if; end if; -- Nested package bodies, avoid generics elsif Nkind (Decl) = N_Package_Body then -- Do not inspect an ignored Ghost package body because all -- code found within will not appear in the final tree. if Is_Ignored_Ghost_Entity (Defining_Entity (Decl)) then null; elsif Ekind (Corresponding_Spec (Decl)) /= E_Generic_Package then Old_Counter_Val := Counter_Val; Process_Declarations (Declarations (Decl), Preprocess); -- The nested package body is the last construct to contain -- a controlled object. if Preprocess and then Top_Level and then No (Last_Top_Level_Ctrl_Construct) and then Counter_Val > Old_Counter_Val then Last_Top_Level_Ctrl_Construct := Decl; end if; end if; -- Handle a rare case caused by a controlled transient object -- created as part of a record init proc. The variable is wrapped -- in a block, but the block is not associated with a transient -- scope. elsif Nkind (Decl) = N_Block_Statement and then Inside_Init_Proc then Old_Counter_Val := Counter_Val; if Present (Handled_Statement_Sequence (Decl)) then Process_Declarations (Statements (Handled_Statement_Sequence (Decl)), Preprocess); end if; Process_Declarations (Declarations (Decl), Preprocess); -- Either the declaration or statement list of the block has a -- controlled object. if Preprocess and then Top_Level and then No (Last_Top_Level_Ctrl_Construct) and then Counter_Val > Old_Counter_Val then Last_Top_Level_Ctrl_Construct := Decl; end if; -- Handle the case where the original context has been wrapped in -- a block to avoid interference between exception handlers and -- At_End handlers. Treat the block as transparent and process its -- contents. elsif Nkind (Decl) = N_Block_Statement and then Is_Finalization_Wrapper (Decl) then if Present (Handled_Statement_Sequence (Decl)) then Process_Declarations (Statements (Handled_Statement_Sequence (Decl)), Preprocess); end if; Process_Declarations (Declarations (Decl), Preprocess); end if; Prev_Non_Pragma (Decl); end loop; end Process_Declarations; -------------------------------- -- Process_Object_Declaration -- -------------------------------- procedure Process_Object_Declaration (Decl : Node_Id; Has_No_Init : Boolean := False; Is_Protected : Boolean := False) is Loc : constant Source_Ptr := Sloc (Decl); Obj_Id : constant Entity_Id := Defining_Identifier (Decl); Init_Typ : Entity_Id; -- The initialization type of the related object declaration. Note -- that this is not necessarily the same type as Obj_Typ because of -- possible type derivations. Obj_Typ : Entity_Id; -- The type of the related object declaration function Build_BIP_Cleanup_Stmts (Func_Id : Entity_Id) return Node_Id; -- Func_Id denotes a build-in-place function. Generate the following -- cleanup code: -- -- if BIPallocfrom > Secondary_Stack'Pos -- and then BIPfinalizationmaster /= null -- then -- declare -- type Ptr_Typ is access Obj_Typ; -- for Ptr_Typ'Storage_Pool -- use Base_Pool (BIPfinalizationmaster); -- begin -- Free (Ptr_Typ (Temp)); -- end; -- end if; -- -- Obj_Typ is the type of the current object, Temp is the original -- allocation which Obj_Id renames. procedure Find_Last_Init (Last_Init : out Node_Id; Body_Insert : out Node_Id); -- Find the last initialization call related to object declaration -- Decl. Last_Init denotes the last initialization call which follows -- Decl. Body_Insert denotes a node where the finalizer body could be -- potentially inserted after (if blocks are involved). ----------------------------- -- Build_BIP_Cleanup_Stmts -- ----------------------------- function Build_BIP_Cleanup_Stmts (Func_Id : Entity_Id) return Node_Id is Decls : constant List_Id := New_List; Fin_Mas_Id : constant Entity_Id := Build_In_Place_Formal (Func_Id, BIP_Finalization_Master); Func_Typ : constant Entity_Id := Etype (Func_Id); Temp_Id : constant Entity_Id := Entity (Prefix (Name (Parent (Obj_Id)))); Cond : Node_Id; Free_Blk : Node_Id; Free_Stmt : Node_Id; Pool_Id : Entity_Id; Ptr_Typ : Entity_Id; begin -- Generate: -- Pool_Id renames Base_Pool (BIPfinalizationmaster.all).all; Pool_Id := Make_Temporary (Loc, 'P'); Append_To (Decls, Make_Object_Renaming_Declaration (Loc, Defining_Identifier => Pool_Id, Subtype_Mark => New_Occurrence_Of (RTE (RE_Root_Storage_Pool), Loc), Name => Make_Explicit_Dereference (Loc, Prefix => Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Base_Pool), Loc), Parameter_Associations => New_List ( Make_Explicit_Dereference (Loc, Prefix => New_Occurrence_Of (Fin_Mas_Id, Loc))))))); -- Create an access type which uses the storage pool of the -- caller's finalization master. -- Generate: -- type Ptr_Typ is access Func_Typ; Ptr_Typ := Make_Temporary (Loc, 'P'); Append_To (Decls, Make_Full_Type_Declaration (Loc, Defining_Identifier => Ptr_Typ, Type_Definition => Make_Access_To_Object_Definition (Loc, Subtype_Indication => New_Occurrence_Of (Func_Typ, Loc)))); -- Perform minor decoration in order to set the master and the -- storage pool attributes. Set_Ekind (Ptr_Typ, E_Access_Type); Set_Finalization_Master (Ptr_Typ, Fin_Mas_Id); Set_Associated_Storage_Pool (Ptr_Typ, Pool_Id); -- Create an explicit free statement. Note that the free uses the -- caller's pool expressed as a renaming. Free_Stmt := Make_Free_Statement (Loc, Expression => Unchecked_Convert_To (Ptr_Typ, New_Occurrence_Of (Temp_Id, Loc))); Set_Storage_Pool (Free_Stmt, Pool_Id); -- Create a block to house the dummy type and the instantiation as -- well as to perform the cleanup the temporary. -- Generate: -- declare -- <Decls> -- begin -- Free (Ptr_Typ (Temp_Id)); -- end; Free_Blk := Make_Block_Statement (Loc, Declarations => Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Free_Stmt))); -- Generate: -- if BIPfinalizationmaster /= null then Cond := Make_Op_Ne (Loc, Left_Opnd => New_Occurrence_Of (Fin_Mas_Id, Loc), Right_Opnd => Make_Null (Loc)); -- For constrained or tagged results escalate the condition to -- include the allocation format. Generate: -- if BIPallocform > Secondary_Stack'Pos -- and then BIPfinalizationmaster /= null -- then if not Is_Constrained (Func_Typ) or else Is_Tagged_Type (Func_Typ) then declare Alloc : constant Entity_Id := Build_In_Place_Formal (Func_Id, BIP_Alloc_Form); begin Cond := Make_And_Then (Loc, Left_Opnd => Make_Op_Gt (Loc, Left_Opnd => New_Occurrence_Of (Alloc, Loc), Right_Opnd => Make_Integer_Literal (Loc, UI_From_Int (BIP_Allocation_Form'Pos (Secondary_Stack)))), Right_Opnd => Cond); end; end if; -- Generate: -- if <Cond> then -- <Free_Blk> -- end if; return Make_If_Statement (Loc, Condition => Cond, Then_Statements => New_List (Free_Blk)); end Build_BIP_Cleanup_Stmts; -------------------- -- Find_Last_Init -- -------------------- procedure Find_Last_Init (Last_Init : out Node_Id; Body_Insert : out Node_Id) is function Find_Last_Init_In_Block (Blk : Node_Id) return Node_Id; -- Find the last initialization call within the statements of -- block Blk. function Is_Init_Call (N : Node_Id) return Boolean; -- Determine whether node N denotes one of the initialization -- procedures of types Init_Typ or Obj_Typ. function Next_Suitable_Statement (Stmt : Node_Id) return Node_Id; -- Obtain the next statement which follows list member Stmt while -- ignoring artifacts related to access-before-elaboration checks. ----------------------------- -- Find_Last_Init_In_Block -- ----------------------------- function Find_Last_Init_In_Block (Blk : Node_Id) return Node_Id is HSS : constant Node_Id := Handled_Statement_Sequence (Blk); Stmt : Node_Id; begin -- Examine the individual statements of the block in reverse to -- locate the last initialization call. if Present (HSS) and then Present (Statements (HSS)) then Stmt := Last (Statements (HSS)); while Present (Stmt) loop -- Peek inside nested blocks in case aborts are allowed if Nkind (Stmt) = N_Block_Statement then return Find_Last_Init_In_Block (Stmt); elsif Is_Init_Call (Stmt) then return Stmt; end if; Prev (Stmt); end loop; end if; return Empty; end Find_Last_Init_In_Block; ------------------ -- Is_Init_Call -- ------------------ function Is_Init_Call (N : Node_Id) return Boolean is function Is_Init_Proc_Of (Subp_Id : Entity_Id; Typ : Entity_Id) return Boolean; -- Determine whether subprogram Subp_Id is a valid init proc of -- type Typ. --------------------- -- Is_Init_Proc_Of -- --------------------- function Is_Init_Proc_Of (Subp_Id : Entity_Id; Typ : Entity_Id) return Boolean is Deep_Init : Entity_Id := Empty; Prim_Init : Entity_Id := Empty; Type_Init : Entity_Id := Empty; begin -- Obtain all possible initialization routines of the -- related type and try to match the subprogram entity -- against one of them. -- Deep_Initialize Deep_Init := TSS (Typ, TSS_Deep_Initialize); -- Primitive Initialize if Is_Controlled (Typ) then Prim_Init := Find_Optional_Prim_Op (Typ, Name_Initialize); if Present (Prim_Init) then Prim_Init := Ultimate_Alias (Prim_Init); end if; end if; -- Type initialization routine if Has_Non_Null_Base_Init_Proc (Typ) then Type_Init := Base_Init_Proc (Typ); end if; return (Present (Deep_Init) and then Subp_Id = Deep_Init) or else (Present (Prim_Init) and then Subp_Id = Prim_Init) or else (Present (Type_Init) and then Subp_Id = Type_Init); end Is_Init_Proc_Of; -- Local variables Call_Id : Entity_Id; -- Start of processing for Is_Init_Call begin if Nkind (N) = N_Procedure_Call_Statement and then Nkind (Name (N)) = N_Identifier then Call_Id := Entity (Name (N)); -- Consider both the type of the object declaration and its -- related initialization type. return Is_Init_Proc_Of (Call_Id, Init_Typ) or else Is_Init_Proc_Of (Call_Id, Obj_Typ); end if; return False; end Is_Init_Call; ----------------------------- -- Next_Suitable_Statement -- ----------------------------- function Next_Suitable_Statement (Stmt : Node_Id) return Node_Id is Result : Node_Id; begin -- Skip call markers and Program_Error raises installed by the -- ABE mechanism. Result := Next (Stmt); while Present (Result) loop exit when Nkind (Result) not in N_Call_Marker | N_Raise_Program_Error; Next (Result); end loop; return Result; end Next_Suitable_Statement; -- Local variables Call : Node_Id; Stmt : Node_Id; Stmt_2 : Node_Id; Deep_Init_Found : Boolean := False; -- A flag set when a call to [Deep_]Initialize has been found -- Start of processing for Find_Last_Init begin Last_Init := Decl; Body_Insert := Empty; -- Object renamings and objects associated with controlled -- function results do not require initialization. if Has_No_Init then return; end if; Stmt := Next_Suitable_Statement (Decl); -- For an object with suppressed initialization, we check whether -- there is in fact no initialization expression. If there is not, -- then this is an object declaration that has been turned into a -- different object declaration that calls the build-in-place -- function in a 'Reference attribute, as in "F(...)'Reference". -- We search for that later object declaration, so that the -- Inc_Decl will be inserted after the call. Otherwise, if the -- call raises an exception, we will finalize the (uninitialized) -- object, which is wrong. if No_Initialization (Decl) then if No (Expression (Last_Init)) then loop Next (Last_Init); exit when No (Last_Init); exit when Nkind (Last_Init) = N_Object_Declaration and then Nkind (Expression (Last_Init)) = N_Reference and then Nkind (Prefix (Expression (Last_Init))) = N_Function_Call and then Is_Expanded_Build_In_Place_Call (Prefix (Expression (Last_Init))); end loop; end if; return; -- In all other cases the initialization calls follow the related -- object. The general structure of object initialization built by -- routine Default_Initialize_Object is as follows: -- [begin -- aborts allowed -- Abort_Defer;] -- Type_Init_Proc (Obj); -- [begin] -- exceptions allowed -- Deep_Initialize (Obj); -- [exception -- exceptions allowed -- when others => -- Deep_Finalize (Obj, Self => False); -- raise; -- end;] -- [at end -- aborts allowed -- Abort_Undefer; -- end;] -- When aborts are allowed, the initialization calls are housed -- within a block. elsif Nkind (Stmt) = N_Block_Statement then Last_Init := Find_Last_Init_In_Block (Stmt); Body_Insert := Stmt; -- Otherwise the initialization calls follow the related object else Stmt_2 := Next_Suitable_Statement (Stmt); -- Check for an optional call to Deep_Initialize which may -- appear within a block depending on whether the object has -- controlled components. if Present (Stmt_2) then if Nkind (Stmt_2) = N_Block_Statement then Call := Find_Last_Init_In_Block (Stmt_2); if Present (Call) then Deep_Init_Found := True; Last_Init := Call; Body_Insert := Stmt_2; end if; elsif Is_Init_Call (Stmt_2) then Deep_Init_Found := True; Last_Init := Stmt_2; Body_Insert := Last_Init; end if; end if; -- If the object lacks a call to Deep_Initialize, then it must -- have a call to its related type init proc. if not Deep_Init_Found and then Is_Init_Call (Stmt) then Last_Init := Stmt; Body_Insert := Last_Init; end if; end if; end Find_Last_Init; -- Local variables Body_Ins : Node_Id; Count_Ins : Node_Id; Fin_Call : Node_Id; Fin_Stmts : List_Id := No_List; Inc_Decl : Node_Id; Label : Node_Id; Label_Id : Entity_Id; Obj_Ref : Node_Id; -- Start of processing for Process_Object_Declaration begin -- Handle the object type and the reference to the object Obj_Ref := New_Occurrence_Of (Obj_Id, Loc); Obj_Typ := Base_Type (Etype (Obj_Id)); loop if Is_Access_Type (Obj_Typ) then Obj_Typ := Directly_Designated_Type (Obj_Typ); Obj_Ref := Make_Explicit_Dereference (Loc, Obj_Ref); elsif Is_Concurrent_Type (Obj_Typ) and then Present (Corresponding_Record_Type (Obj_Typ)) then Obj_Typ := Corresponding_Record_Type (Obj_Typ); Obj_Ref := Unchecked_Convert_To (Obj_Typ, Obj_Ref); elsif Is_Private_Type (Obj_Typ) and then Present (Full_View (Obj_Typ)) then Obj_Typ := Full_View (Obj_Typ); Obj_Ref := Unchecked_Convert_To (Obj_Typ, Obj_Ref); elsif Obj_Typ /= Base_Type (Obj_Typ) then Obj_Typ := Base_Type (Obj_Typ); Obj_Ref := Unchecked_Convert_To (Obj_Typ, Obj_Ref); else exit; end if; end loop; Set_Etype (Obj_Ref, Obj_Typ); -- Handle the initialization type of the object declaration Init_Typ := Obj_Typ; loop if Is_Private_Type (Init_Typ) and then Present (Full_View (Init_Typ)) then Init_Typ := Full_View (Init_Typ); elsif Is_Untagged_Derivation (Init_Typ) then Init_Typ := Root_Type (Init_Typ); else exit; end if; end loop; -- Set a new value for the state counter and insert the statement -- after the object declaration. Generate: -- Counter := <value>; Inc_Decl := Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Counter_Id, Loc), Expression => Make_Integer_Literal (Loc, Counter_Val)); -- Insert the counter after all initialization has been done. The -- place of insertion depends on the context. if Ekind (Obj_Id) in E_Constant | E_Variable then -- The object is initialized by a build-in-place function call. -- The counter insertion point is after the function call. if Present (BIP_Initialization_Call (Obj_Id)) then Count_Ins := BIP_Initialization_Call (Obj_Id); Body_Ins := Empty; -- The object is initialized by an aggregate. Insert the counter -- after the last aggregate assignment. elsif Present (Last_Aggregate_Assignment (Obj_Id)) then Count_Ins := Last_Aggregate_Assignment (Obj_Id); Body_Ins := Empty; -- In all other cases the counter is inserted after the last call -- to either [Deep_]Initialize or the type-specific init proc. else Find_Last_Init (Count_Ins, Body_Ins); end if; -- In all other cases the counter is inserted after the last call to -- either [Deep_]Initialize or the type-specific init proc. else Find_Last_Init (Count_Ins, Body_Ins); end if; -- If the Initialize function is null or trivial, the call will have -- been replaced with a null statement, in which case place counter -- declaration after object declaration itself. if No (Count_Ins) then Count_Ins := Decl; end if; Insert_After (Count_Ins, Inc_Decl); Analyze (Inc_Decl); -- If the current declaration is the last in the list, the finalizer -- body needs to be inserted after the set counter statement for the -- current object declaration. This is complicated by the fact that -- the set counter statement may appear in abort deferred block. In -- that case, the proper insertion place is after the block. if No (Finalizer_Insert_Nod) then -- Insertion after an abort deferred block if Present (Body_Ins) then Finalizer_Insert_Nod := Body_Ins; else Finalizer_Insert_Nod := Inc_Decl; end if; end if; -- Create the associated label with this object, generate: -- L<counter> : label; Label_Id := Make_Identifier (Loc, New_External_Name ('L', Counter_Val)); Set_Entity (Label_Id, Make_Defining_Identifier (Loc, Chars (Label_Id))); Label := Make_Label (Loc, Label_Id); Prepend_To (Finalizer_Decls, Make_Implicit_Label_Declaration (Loc, Defining_Identifier => Entity (Label_Id), Label_Construct => Label)); -- Create the associated jump with this object, generate: -- when <counter> => -- goto L<counter>; Prepend_To (Jump_Alts, Make_Case_Statement_Alternative (Loc, Discrete_Choices => New_List ( Make_Integer_Literal (Loc, Counter_Val)), Statements => New_List ( Make_Goto_Statement (Loc, Name => New_Occurrence_Of (Entity (Label_Id), Loc))))); -- Insert the jump destination, generate: -- <<L<counter>>> Append_To (Finalizer_Stmts, Label); -- Processing for simple protected objects. Such objects require -- manual finalization of their lock managers. if Is_Protected then if Is_Simple_Protected_Type (Obj_Typ) then Fin_Call := Cleanup_Protected_Object (Decl, Obj_Ref); if Present (Fin_Call) then Fin_Stmts := New_List (Fin_Call); end if; elsif Has_Simple_Protected_Object (Obj_Typ) then if Is_Record_Type (Obj_Typ) then Fin_Stmts := Cleanup_Record (Decl, Obj_Ref, Obj_Typ); elsif Is_Array_Type (Obj_Typ) then Fin_Stmts := Cleanup_Array (Decl, Obj_Ref, Obj_Typ); end if; end if; -- Generate: -- begin -- System.Tasking.Protected_Objects.Finalize_Protection -- (Obj._object); -- exception -- when others => -- null; -- end; if Present (Fin_Stmts) and then Exceptions_OK then Fin_Stmts := New_List ( Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Fin_Stmts, Exception_Handlers => New_List ( Make_Exception_Handler (Loc, Exception_Choices => New_List ( Make_Others_Choice (Loc)), Statements => New_List ( Make_Null_Statement (Loc))))))); end if; -- Processing for regular controlled objects else -- Generate: -- begin -- [Deep_]Finalize (Obj); -- exception -- when Id : others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Id); -- end if; -- end; Fin_Call := Make_Final_Call ( Obj_Ref => Obj_Ref, Typ => Obj_Typ); -- Guard against a missing [Deep_]Finalize when the object type -- was not properly frozen. if No (Fin_Call) then Fin_Call := Make_Null_Statement (Loc); end if; -- For CodePeer, the exception handlers normally generated here -- generate complex flowgraphs which result in capacity problems. -- Omitting these handlers for CodePeer is justified as follows: -- If a handler is dead, then omitting it is surely ok -- If a handler is live, then CodePeer should flag the -- potentially-exception-raising construct that causes it -- to be live. That is what we are interested in, not what -- happens after the exception is raised. if Exceptions_OK and not CodePeer_Mode then Fin_Stmts := New_List ( Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Fin_Call), Exception_Handlers => New_List ( Build_Exception_Handler (Finalizer_Data, For_Package))))); -- When exception handlers are prohibited, the finalization call -- appears unprotected. Any exception raised during finalization -- will bypass the circuitry which ensures the cleanup of all -- remaining objects. else Fin_Stmts := New_List (Fin_Call); end if; -- If we are dealing with a return object of a build-in-place -- function, generate the following cleanup statements: -- if BIPallocfrom > Secondary_Stack'Pos -- and then BIPfinalizationmaster /= null -- then -- declare -- type Ptr_Typ is access Obj_Typ; -- for Ptr_Typ'Storage_Pool use -- Base_Pool (BIPfinalizationmaster.all).all; -- begin -- Free (Ptr_Typ (Temp)); -- end; -- end if; -- The generated code effectively detaches the temporary from the -- caller finalization master and deallocates the object. if Is_Return_Object (Obj_Id) then declare Func_Id : constant Entity_Id := Enclosing_Function (Obj_Id); begin if Is_Build_In_Place_Function (Func_Id) and then Needs_BIP_Finalization_Master (Func_Id) then Append_To (Fin_Stmts, Build_BIP_Cleanup_Stmts (Func_Id)); end if; end; end if; if Ekind (Obj_Id) in E_Constant | E_Variable and then Present (Status_Flag_Or_Transient_Decl (Obj_Id)) then -- Temporaries created for the purpose of "exporting" a -- transient object out of an Expression_With_Actions (EWA) -- need guards. The following illustrates the usage of such -- temporaries. -- Access_Typ : access [all] Obj_Typ; -- Temp : Access_Typ := null; -- <Counter> := ...; -- do -- Ctrl_Trans : [access [all]] Obj_Typ := ...; -- Temp := Access_Typ (Ctrl_Trans); -- when a pointer -- <or> -- Temp := Ctrl_Trans'Unchecked_Access; -- in ... end; -- The finalization machinery does not process EWA nodes as -- this may lead to premature finalization of expressions. Note -- that Temp is marked as being properly initialized regardless -- of whether the initialization of Ctrl_Trans succeeded. Since -- a failed initialization may leave Temp with a value of null, -- add a guard to handle this case: -- if Obj /= null then -- <object finalization statements> -- end if; if Nkind (Status_Flag_Or_Transient_Decl (Obj_Id)) = N_Object_Declaration then Fin_Stmts := New_List ( Make_If_Statement (Loc, Condition => Make_Op_Ne (Loc, Left_Opnd => New_Occurrence_Of (Obj_Id, Loc), Right_Opnd => Make_Null (Loc)), Then_Statements => Fin_Stmts)); -- Return objects use a flag to aid in processing their -- potential finalization when the enclosing function fails -- to return properly. Generate: -- if not Flag then -- <object finalization statements> -- end if; else Fin_Stmts := New_List ( Make_If_Statement (Loc, Condition => Make_Op_Not (Loc, Right_Opnd => New_Occurrence_Of (Status_Flag_Or_Transient_Decl (Obj_Id), Loc)), Then_Statements => Fin_Stmts)); end if; end if; end if; Append_List_To (Finalizer_Stmts, Fin_Stmts); -- Since the declarations are examined in reverse, the state counter -- must be decremented in order to keep with the true position of -- objects. Counter_Val := Counter_Val - 1; end Process_Object_Declaration; ------------------------------------- -- Process_Tagged_Type_Declaration -- ------------------------------------- procedure Process_Tagged_Type_Declaration (Decl : Node_Id) is Typ : constant Entity_Id := Defining_Identifier (Decl); DT_Ptr : constant Entity_Id := Node (First_Elmt (Access_Disp_Table (Typ))); begin -- Generate: -- Ada.Tags.Unregister_Tag (<Typ>P); Append_To (Tagged_Type_Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Unregister_Tag), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (DT_Ptr, Loc)))); end Process_Tagged_Type_Declaration; -- Start of processing for Build_Finalizer begin Fin_Id := Empty; -- Do not perform this expansion in SPARK mode because it is not -- necessary. if GNATprove_Mode then return; end if; -- Step 1: Extract all lists which may contain controlled objects or -- library-level tagged types. if For_Package_Spec then Decls := Visible_Declarations (Specification (N)); Priv_Decls := Private_Declarations (Specification (N)); -- Retrieve the package spec id Spec_Id := Defining_Unit_Name (Specification (N)); if Nkind (Spec_Id) = N_Defining_Program_Unit_Name then Spec_Id := Defining_Identifier (Spec_Id); end if; -- Accept statement, block, entry body, package body, protected body, -- subprogram body or task body. else Decls := Declarations (N); HSS := Handled_Statement_Sequence (N); if Present (HSS) then if Present (Statements (HSS)) then Stmts := Statements (HSS); end if; if Present (At_End_Proc (HSS)) then Prev_At_End := At_End_Proc (HSS); end if; end if; -- Retrieve the package spec id for package bodies if For_Package_Body then Spec_Id := Corresponding_Spec (N); end if; end if; -- Do not process nested packages since those are handled by the -- enclosing scope's finalizer. Do not process non-expanded package -- instantiations since those will be re-analyzed and re-expanded. if For_Package and then (not Is_Library_Level_Entity (Spec_Id) -- Nested packages are considered to be library level entities, -- but do not need to be processed separately. True library level -- packages have a scope value of 1. or else Scope_Depth_Value (Spec_Id) /= Uint_1 or else (Is_Generic_Instance (Spec_Id) and then Package_Instantiation (Spec_Id) /= N)) then return; end if; -- Step 2: Object [pre]processing if For_Package then -- Preprocess the visible declarations now in order to obtain the -- correct number of controlled object by the time the private -- declarations are processed. Process_Declarations (Decls, Preprocess => True, Top_Level => True); -- From all the possible contexts, only package specifications may -- have private declarations. if For_Package_Spec then Process_Declarations (Priv_Decls, Preprocess => True, Top_Level => True); end if; -- The current context may lack controlled objects, but require some -- other form of completion (task termination for instance). In such -- cases, the finalizer must be created and carry the additional -- statements. if Acts_As_Clean or Has_Ctrl_Objs or Has_Tagged_Types then Build_Components; end if; -- The preprocessing has determined that the context has controlled -- objects or library-level tagged types. if Has_Ctrl_Objs or Has_Tagged_Types then -- Private declarations are processed first in order to preserve -- possible dependencies between public and private objects. if For_Package_Spec then Process_Declarations (Priv_Decls); end if; Process_Declarations (Decls); end if; -- Non-package case else -- Preprocess both declarations and statements Process_Declarations (Decls, Preprocess => True, Top_Level => True); Process_Declarations (Stmts, Preprocess => True, Top_Level => True); -- At this point it is known that N has controlled objects. Ensure -- that N has a declarative list since the finalizer spec will be -- attached to it. if Has_Ctrl_Objs and then No (Decls) then Set_Declarations (N, New_List); Decls := Declarations (N); Spec_Decls := Decls; end if; -- The current context may lack controlled objects, but require some -- other form of completion (task termination for instance). In such -- cases, the finalizer must be created and carry the additional -- statements. if Acts_As_Clean or Has_Ctrl_Objs or Has_Tagged_Types then Build_Components; end if; if Has_Ctrl_Objs or Has_Tagged_Types then Process_Declarations (Stmts); Process_Declarations (Decls); end if; end if; -- Step 3: Finalizer creation if Acts_As_Clean or else Has_Ctrl_Objs or else Has_Tagged_Types then Create_Finalizer; end if; end Build_Finalizer; -------------------------- -- Build_Finalizer_Call -- -------------------------- procedure Build_Finalizer_Call (N : Node_Id; Fin_Id : Entity_Id) is Is_Prot_Body : constant Boolean := Nkind (N) = N_Subprogram_Body and then Is_Protected_Subprogram_Body (N); -- Determine whether N denotes the protected version of a subprogram -- which belongs to a protected type. Loc : constant Source_Ptr := Sloc (N); HSS : Node_Id; begin -- Do not perform this expansion in SPARK mode because we do not create -- finalizers in the first place. if GNATprove_Mode then return; end if; -- The At_End handler should have been assimilated by the finalizer HSS := Handled_Statement_Sequence (N); pragma Assert (No (At_End_Proc (HSS))); -- If the construct to be cleaned up is a protected subprogram body, the -- finalizer call needs to be associated with the block which wraps the -- unprotected version of the subprogram. The following illustrates this -- scenario: -- procedure Prot_SubpP is -- procedure finalizer is -- begin -- Service_Entries (Prot_Obj); -- Abort_Undefer; -- end finalizer; -- begin -- . . . -- begin -- Prot_SubpN (Prot_Obj); -- at end -- finalizer; -- end; -- end Prot_SubpP; if Is_Prot_Body then HSS := Handled_Statement_Sequence (Last (Statements (HSS))); -- An At_End handler and regular exception handlers cannot coexist in -- the same statement sequence. Wrap the original statements in a block. elsif Present (Exception_Handlers (HSS)) then declare End_Lab : constant Node_Id := End_Label (HSS); Block : Node_Id; begin Block := Make_Block_Statement (Loc, Handled_Statement_Sequence => HSS); Set_Handled_Statement_Sequence (N, Make_Handled_Sequence_Of_Statements (Loc, New_List (Block))); HSS := Handled_Statement_Sequence (N); Set_End_Label (HSS, End_Lab); end; end if; Set_At_End_Proc (HSS, New_Occurrence_Of (Fin_Id, Loc)); -- Attach reference to finalizer to tree, for LLVM use Set_Parent (At_End_Proc (HSS), HSS); Analyze (At_End_Proc (HSS)); Expand_At_End_Handler (HSS, Empty); end Build_Finalizer_Call; --------------------- -- Build_Late_Proc -- --------------------- procedure Build_Late_Proc (Typ : Entity_Id; Nam : Name_Id) is begin for Final_Prim in Name_Of'Range loop if Name_Of (Final_Prim) = Nam then Set_TSS (Typ, Make_Deep_Proc (Prim => Final_Prim, Typ => Typ, Stmts => Make_Deep_Record_Body (Final_Prim, Typ))); end if; end loop; end Build_Late_Proc; ------------------------------- -- Build_Object_Declarations -- ------------------------------- procedure Build_Object_Declarations (Data : out Finalization_Exception_Data; Decls : List_Id; Loc : Source_Ptr; For_Package : Boolean := False) is Decl : Node_Id; Dummy : Entity_Id; -- This variable captures an unused dummy internal entity, see the -- comment associated with its use. begin pragma Assert (Decls /= No_List); -- Always set the proper location as it may be needed even when -- exception propagation is forbidden. Data.Loc := Loc; if Restriction_Active (No_Exception_Propagation) then Data.Abort_Id := Empty; Data.E_Id := Empty; Data.Raised_Id := Empty; return; end if; Data.Raised_Id := Make_Temporary (Loc, 'R'); -- In certain scenarios, finalization can be triggered by an abort. If -- the finalization itself fails and raises an exception, the resulting -- Program_Error must be supressed and replaced by an abort signal. In -- order to detect this scenario, save the state of entry into the -- finalization code. -- This is not needed for library-level finalizers as they are called by -- the environment task and cannot be aborted. if not For_Package then if Abort_Allowed then Data.Abort_Id := Make_Temporary (Loc, 'A'); -- Generate: -- Abort_Id : constant Boolean := <A_Expr>; Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Data.Abort_Id, Constant_Present => True, Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc), Expression => New_Occurrence_Of (RTE (RE_Triggered_By_Abort), Loc))); -- Abort is not required else -- Generate a dummy entity to ensure that the internal symbols are -- in sync when a unit is compiled with and without aborts. Dummy := Make_Temporary (Loc, 'A'); Data.Abort_Id := Empty; end if; -- Library-level finalizers else Data.Abort_Id := Empty; end if; if Exception_Extra_Info then Data.E_Id := Make_Temporary (Loc, 'E'); -- Generate: -- E_Id : Exception_Occurrence; Decl := Make_Object_Declaration (Loc, Defining_Identifier => Data.E_Id, Object_Definition => New_Occurrence_Of (RTE (RE_Exception_Occurrence), Loc)); Set_No_Initialization (Decl); Append_To (Decls, Decl); else Data.E_Id := Empty; end if; -- Generate: -- Raised_Id : Boolean := False; Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Data.Raised_Id, Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc), Expression => New_Occurrence_Of (Standard_False, Loc))); end Build_Object_Declarations; --------------------------- -- Build_Raise_Statement -- --------------------------- function Build_Raise_Statement (Data : Finalization_Exception_Data) return Node_Id is Stmt : Node_Id; Expr : Node_Id; begin -- Standard run-time use the specialized routine -- Raise_From_Controlled_Operation. if Exception_Extra_Info and then RTE_Available (RE_Raise_From_Controlled_Operation) then Stmt := Make_Procedure_Call_Statement (Data.Loc, Name => New_Occurrence_Of (RTE (RE_Raise_From_Controlled_Operation), Data.Loc), Parameter_Associations => New_List (New_Occurrence_Of (Data.E_Id, Data.Loc))); -- Restricted run-time: exception messages are not supported and hence -- Raise_From_Controlled_Operation is not supported. Raise Program_Error -- instead. else Stmt := Make_Raise_Program_Error (Data.Loc, Reason => PE_Finalize_Raised_Exception); end if; -- Generate: -- Raised_Id and then not Abort_Id -- <or> -- Raised_Id Expr := New_Occurrence_Of (Data.Raised_Id, Data.Loc); if Present (Data.Abort_Id) then Expr := Make_And_Then (Data.Loc, Left_Opnd => Expr, Right_Opnd => Make_Op_Not (Data.Loc, Right_Opnd => New_Occurrence_Of (Data.Abort_Id, Data.Loc))); end if; -- Generate: -- if Raised_Id and then not Abort_Id then -- Raise_From_Controlled_Operation (E_Id); -- <or> -- raise Program_Error; -- restricted runtime -- end if; return Make_If_Statement (Data.Loc, Condition => Expr, Then_Statements => New_List (Stmt)); end Build_Raise_Statement; ----------------------------- -- Build_Record_Deep_Procs -- ----------------------------- procedure Build_Record_Deep_Procs (Typ : Entity_Id) is begin Set_TSS (Typ, Make_Deep_Proc (Prim => Initialize_Case, Typ => Typ, Stmts => Make_Deep_Record_Body (Initialize_Case, Typ))); if not Is_Limited_View (Typ) then Set_TSS (Typ, Make_Deep_Proc (Prim => Adjust_Case, Typ => Typ, Stmts => Make_Deep_Record_Body (Adjust_Case, Typ))); end if; -- Do not generate Deep_Finalize and Finalize_Address if finalization is -- suppressed since these routine will not be used. if not Restriction_Active (No_Finalization) then Set_TSS (Typ, Make_Deep_Proc (Prim => Finalize_Case, Typ => Typ, Stmts => Make_Deep_Record_Body (Finalize_Case, Typ))); -- Create TSS primitive Finalize_Address (unless CodePeer_Mode) if not CodePeer_Mode then Set_TSS (Typ, Make_Deep_Proc (Prim => Address_Case, Typ => Typ, Stmts => Make_Deep_Record_Body (Address_Case, Typ))); end if; end if; end Build_Record_Deep_Procs; ------------------- -- Cleanup_Array -- ------------------- function Cleanup_Array (N : Node_Id; Obj : Node_Id; Typ : Entity_Id) return List_Id is Loc : constant Source_Ptr := Sloc (N); Index_List : constant List_Id := New_List; function Free_Component return List_Id; -- Generate the code to finalize the task or protected subcomponents -- of a single component of the array. function Free_One_Dimension (Dim : Int) return List_Id; -- Generate a loop over one dimension of the array -------------------- -- Free_Component -- -------------------- function Free_Component return List_Id is Stmts : List_Id := New_List; Tsk : Node_Id; C_Typ : constant Entity_Id := Component_Type (Typ); begin -- Component type is known to contain tasks or protected objects Tsk := Make_Indexed_Component (Loc, Prefix => Duplicate_Subexpr_No_Checks (Obj), Expressions => Index_List); Set_Etype (Tsk, C_Typ); if Is_Task_Type (C_Typ) then Append_To (Stmts, Cleanup_Task (N, Tsk)); elsif Is_Simple_Protected_Type (C_Typ) then Append_To (Stmts, Cleanup_Protected_Object (N, Tsk)); elsif Is_Record_Type (C_Typ) then Stmts := Cleanup_Record (N, Tsk, C_Typ); elsif Is_Array_Type (C_Typ) then Stmts := Cleanup_Array (N, Tsk, C_Typ); end if; return Stmts; end Free_Component; ------------------------ -- Free_One_Dimension -- ------------------------ function Free_One_Dimension (Dim : Int) return List_Id is Index : Entity_Id; begin if Dim > Number_Dimensions (Typ) then return Free_Component; -- Here we generate the required loop else Index := Make_Temporary (Loc, 'J'); Append (New_Occurrence_Of (Index, Loc), Index_List); return New_List ( Make_Implicit_Loop_Statement (N, Identifier => Empty, Iteration_Scheme => Make_Iteration_Scheme (Loc, Loop_Parameter_Specification => Make_Loop_Parameter_Specification (Loc, Defining_Identifier => Index, Discrete_Subtype_Definition => Make_Attribute_Reference (Loc, Prefix => Duplicate_Subexpr (Obj), Attribute_Name => Name_Range, Expressions => New_List ( Make_Integer_Literal (Loc, Dim))))), Statements => Free_One_Dimension (Dim + 1))); end if; end Free_One_Dimension; -- Start of processing for Cleanup_Array begin return Free_One_Dimension (1); end Cleanup_Array; -------------------- -- Cleanup_Record -- -------------------- function Cleanup_Record (N : Node_Id; Obj : Node_Id; Typ : Entity_Id) return List_Id is Loc : constant Source_Ptr := Sloc (N); Stmts : constant List_Id := New_List; U_Typ : constant Entity_Id := Underlying_Type (Typ); Comp : Entity_Id; Tsk : Node_Id; begin if Has_Discriminants (U_Typ) and then Nkind (Parent (U_Typ)) = N_Full_Type_Declaration and then Nkind (Type_Definition (Parent (U_Typ))) = N_Record_Definition and then Present (Variant_Part (Component_List (Type_Definition (Parent (U_Typ))))) then -- For now, do not attempt to free a component that may appear in a -- variant, and instead issue a warning. Doing this "properly" would -- require building a case statement and would be quite a mess. Note -- that the RM only requires that free "work" for the case of a task -- access value, so already we go way beyond this in that we deal -- with the array case and non-discriminated record cases. Error_Msg_N ("task/protected object in variant record will not be freed??", N); return New_List (Make_Null_Statement (Loc)); end if; Comp := First_Component (U_Typ); while Present (Comp) loop if Has_Task (Etype (Comp)) or else Has_Simple_Protected_Object (Etype (Comp)) then Tsk := Make_Selected_Component (Loc, Prefix => Duplicate_Subexpr_No_Checks (Obj), Selector_Name => New_Occurrence_Of (Comp, Loc)); Set_Etype (Tsk, Etype (Comp)); if Is_Task_Type (Etype (Comp)) then Append_To (Stmts, Cleanup_Task (N, Tsk)); elsif Is_Simple_Protected_Type (Etype (Comp)) then Append_To (Stmts, Cleanup_Protected_Object (N, Tsk)); elsif Is_Record_Type (Etype (Comp)) then -- Recurse, by generating the prefix of the argument to the -- eventual cleanup call. Append_List_To (Stmts, Cleanup_Record (N, Tsk, Etype (Comp))); elsif Is_Array_Type (Etype (Comp)) then Append_List_To (Stmts, Cleanup_Array (N, Tsk, Etype (Comp))); end if; end if; Next_Component (Comp); end loop; return Stmts; end Cleanup_Record; ------------------------------ -- Cleanup_Protected_Object -- ------------------------------ function Cleanup_Protected_Object (N : Node_Id; Ref : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (N); begin -- For restricted run-time libraries (Ravenscar), tasks are -- non-terminating, and protected objects can only appear at library -- level, so we do not want finalization of protected objects. if Restricted_Profile then return Empty; else return Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Finalize_Protection), Loc), Parameter_Associations => New_List (Concurrent_Ref (Ref))); end if; end Cleanup_Protected_Object; ------------------ -- Cleanup_Task -- ------------------ function Cleanup_Task (N : Node_Id; Ref : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (N); begin -- For restricted run-time libraries (Ravenscar), tasks are -- non-terminating and they can only appear at library level, -- so we do not want finalization of task objects. if Restricted_Profile then return Empty; else return Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Free_Task), Loc), Parameter_Associations => New_List (Concurrent_Ref (Ref))); end if; end Cleanup_Task; -------------------------------------- -- Check_Unnesting_Elaboration_Code -- -------------------------------------- procedure Check_Unnesting_Elaboration_Code (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Block_Elab_Proc : Entity_Id := Empty; procedure Set_Block_Elab_Proc; -- Create a defining identifier for a procedure that will replace -- a block with nested subprograms (unless it has already been created, -- in which case this is a no-op). procedure Set_Block_Elab_Proc is begin if No (Block_Elab_Proc) then Block_Elab_Proc := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('I')); end if; end Set_Block_Elab_Proc; procedure Reset_Scopes_To_Block_Elab_Proc (L : List_Id); -- Find entities in the elaboration code of a library package body that -- contain or represent a subprogram body. A body can appear within a -- block or a loop or can appear by itself if generated for an object -- declaration that involves controlled actions. The first such entity -- forces creation of a new procedure entity (via Set_Block_Elab_Proc) -- that will be used to reset the scopes of all entities that become -- local to the new elaboration procedure. This is needed for subsequent -- unnesting actions, which depend on proper setting of the Scope links -- to determine the nesting level of each subprogram. ----------------------- -- Find_Local_Scope -- ----------------------- procedure Reset_Scopes_To_Block_Elab_Proc (L : List_Id) is Id : Entity_Id; Stat : Node_Id; begin Stat := First (L); while Present (Stat) loop case Nkind (Stat) is when N_Block_Statement => Id := Entity (Identifier (Stat)); -- The Scope of this block needs to be reset to the new -- procedure if the block contains nested subprograms. if Present (Id) and then Contains_Subprogram (Id) then Set_Block_Elab_Proc; Set_Scope (Id, Block_Elab_Proc); end if; when N_Loop_Statement => Id := Entity (Identifier (Stat)); if Present (Id) and then Contains_Subprogram (Id) then if Scope (Id) = Current_Scope then Set_Block_Elab_Proc; Set_Scope (Id, Block_Elab_Proc); end if; end if; -- We traverse the loop's statements as well, which may -- include other block (etc.) statements that need to have -- their Scope set to Block_Elab_Proc. (Is this really the -- case, or do such nested blocks refer to the loop scope -- rather than the loop's enclosing scope???.) Reset_Scopes_To_Block_Elab_Proc (Statements (Stat)); when N_If_Statement => Reset_Scopes_To_Block_Elab_Proc (Then_Statements (Stat)); Reset_Scopes_To_Block_Elab_Proc (Else_Statements (Stat)); declare Elif : Node_Id; begin Elif := First (Elsif_Parts (Stat)); while Present (Elif) loop Reset_Scopes_To_Block_Elab_Proc (Then_Statements (Elif)); Next (Elif); end loop; end; when N_Case_Statement => declare Alt : Node_Id; begin Alt := First (Alternatives (Stat)); while Present (Alt) loop Reset_Scopes_To_Block_Elab_Proc (Statements (Alt)); Next (Alt); end loop; end; -- Reset the Scope of a subprogram occurring at the top level when N_Subprogram_Body => Id := Defining_Entity (Stat); Set_Block_Elab_Proc; Set_Scope (Id, Block_Elab_Proc); when others => null; end case; Next (Stat); end loop; end Reset_Scopes_To_Block_Elab_Proc; -- Local variables H_Seq : constant Node_Id := Handled_Statement_Sequence (N); Elab_Body : Node_Id; Elab_Call : Node_Id; -- Start of processing for Check_Unnesting_Elaboration_Code begin if Present (H_Seq) then Reset_Scopes_To_Block_Elab_Proc (Statements (H_Seq)); -- There may be subprograms declared in the exception handlers -- of the current body. if Present (Exception_Handlers (H_Seq)) then declare Handler : Node_Id := First (Exception_Handlers (H_Seq)); begin while Present (Handler) loop Reset_Scopes_To_Block_Elab_Proc (Statements (Handler)); Next (Handler); end loop; end; end if; if Present (Block_Elab_Proc) then Elab_Body := Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Block_Elab_Proc), Declarations => New_List, Handled_Statement_Sequence => Relocate_Node (Handled_Statement_Sequence (N))); Elab_Call := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Block_Elab_Proc, Loc)); Append_To (Declarations (N), Elab_Body); Analyze (Elab_Body); Set_Has_Nested_Subprogram (Block_Elab_Proc); Set_Handled_Statement_Sequence (N, Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Elab_Call))); Analyze (Elab_Call); -- Could we reset the scopes of entities associated with the new -- procedure here via a loop over entities rather than doing it in -- the recursive Reset_Scopes_To_Elab_Proc procedure??? end if; end if; end Check_Unnesting_Elaboration_Code; --------------------------------------- -- Check_Unnesting_In_Decls_Or_Stmts -- --------------------------------------- procedure Check_Unnesting_In_Decls_Or_Stmts (Decls_Or_Stmts : List_Id) is Decl_Or_Stmt : Node_Id; begin if Unnest_Subprogram_Mode and then Present (Decls_Or_Stmts) then Decl_Or_Stmt := First (Decls_Or_Stmts); while Present (Decl_Or_Stmt) loop if Nkind (Decl_Or_Stmt) = N_Block_Statement and then Contains_Subprogram (Entity (Identifier (Decl_Or_Stmt))) then Unnest_Block (Decl_Or_Stmt); -- If-statements may contain subprogram bodies at the outer level -- of their statement lists, and the subprograms may make up-level -- references (such as to objects declared in the same statement -- list). Unlike block and loop cases, however, we don't have an -- entity on which to test the Contains_Subprogram flag, so -- Unnest_If_Statement must traverse the statement lists to -- determine whether there are nested subprograms present. elsif Nkind (Decl_Or_Stmt) = N_If_Statement then Unnest_If_Statement (Decl_Or_Stmt); elsif Nkind (Decl_Or_Stmt) = N_Loop_Statement then declare Id : constant Entity_Id := Entity (Identifier (Decl_Or_Stmt)); begin -- When a top-level loop within declarations of a library -- package spec or body contains nested subprograms, we wrap -- it in a procedure to handle possible up-level references -- to entities associated with the loop (such as loop -- parameters). if Present (Id) and then Contains_Subprogram (Id) then Unnest_Loop (Decl_Or_Stmt); end if; end; elsif Nkind (Decl_Or_Stmt) = N_Package_Declaration and then not Modify_Tree_For_C then Check_Unnesting_In_Decls_Or_Stmts (Visible_Declarations (Specification (Decl_Or_Stmt))); Check_Unnesting_In_Decls_Or_Stmts (Private_Declarations (Specification (Decl_Or_Stmt))); elsif Nkind (Decl_Or_Stmt) = N_Package_Body and then not Modify_Tree_For_C then Check_Unnesting_In_Decls_Or_Stmts (Declarations (Decl_Or_Stmt)); if Present (Statements (Handled_Statement_Sequence (Decl_Or_Stmt))) then Check_Unnesting_In_Decls_Or_Stmts (Statements (Handled_Statement_Sequence (Decl_Or_Stmt))); Check_Unnesting_In_Handlers (Decl_Or_Stmt); end if; end if; Next (Decl_Or_Stmt); end loop; end if; end Check_Unnesting_In_Decls_Or_Stmts; --------------------------------- -- Check_Unnesting_In_Handlers -- --------------------------------- procedure Check_Unnesting_In_Handlers (N : Node_Id) is Stmt_Seq : constant Node_Id := Handled_Statement_Sequence (N); begin if Present (Stmt_Seq) and then Present (Exception_Handlers (Stmt_Seq)) then declare Handler : Node_Id := First (Exception_Handlers (Stmt_Seq)); begin while Present (Handler) loop if Present (Statements (Handler)) then Check_Unnesting_In_Decls_Or_Stmts (Statements (Handler)); end if; Next (Handler); end loop; end; end if; end Check_Unnesting_In_Handlers; ------------------------------ -- Check_Visibly_Controlled -- ------------------------------ procedure Check_Visibly_Controlled (Prim : Final_Primitives; Typ : Entity_Id; E : in out Entity_Id; Cref : in out Node_Id) is Parent_Type : Entity_Id; Op : Entity_Id; begin if Is_Derived_Type (Typ) and then Comes_From_Source (E) and then not Present (Overridden_Operation (E)) then -- We know that the explicit operation on the type does not override -- the inherited operation of the parent, and that the derivation -- is from a private type that is not visibly controlled. Parent_Type := Etype (Typ); Op := Find_Optional_Prim_Op (Parent_Type, Name_Of (Prim)); if Present (Op) then E := Op; -- Wrap the object to be initialized into the proper -- unchecked conversion, to be compatible with the operation -- to be called. if Nkind (Cref) = N_Unchecked_Type_Conversion then Cref := Unchecked_Convert_To (Parent_Type, Expression (Cref)); else Cref := Unchecked_Convert_To (Parent_Type, Cref); end if; end if; end if; end Check_Visibly_Controlled; -------------------------- -- Contains_Subprogram -- -------------------------- function Contains_Subprogram (Blk : Entity_Id) return Boolean is E : Entity_Id; begin E := First_Entity (Blk); while Present (E) loop if Is_Subprogram (E) then return True; elsif Ekind (E) in E_Block | E_Loop and then Contains_Subprogram (E) then return True; end if; Next_Entity (E); end loop; return False; end Contains_Subprogram; ------------------ -- Convert_View -- ------------------ function Convert_View (Proc : Entity_Id; Arg : Node_Id; Ind : Pos := 1) return Node_Id is Fent : Entity_Id := First_Entity (Proc); Ftyp : Entity_Id; Atyp : Entity_Id; begin for J in 2 .. Ind loop Next_Entity (Fent); end loop; Ftyp := Etype (Fent); if Nkind (Arg) in N_Type_Conversion | N_Unchecked_Type_Conversion then Atyp := Entity (Subtype_Mark (Arg)); else Atyp := Etype (Arg); end if; if Is_Abstract_Subprogram (Proc) and then Is_Tagged_Type (Ftyp) then return Unchecked_Convert_To (Class_Wide_Type (Ftyp), Arg); elsif Ftyp /= Atyp and then Present (Atyp) and then (Is_Private_Type (Ftyp) or else Is_Private_Type (Atyp)) and then Base_Type (Underlying_Type (Atyp)) = Base_Type (Underlying_Type (Ftyp)) then return Unchecked_Convert_To (Ftyp, Arg); -- If the argument is already a conversion, as generated by -- Make_Init_Call, set the target type to the type of the formal -- directly, to avoid spurious typing problems. elsif Nkind (Arg) in N_Unchecked_Type_Conversion | N_Type_Conversion and then not Is_Class_Wide_Type (Atyp) then Set_Subtype_Mark (Arg, New_Occurrence_Of (Ftyp, Sloc (Arg))); Set_Etype (Arg, Ftyp); return Arg; -- Otherwise, introduce a conversion when the designated object -- has a type derived from the formal of the controlled routine. elsif Is_Private_Type (Ftyp) and then Present (Atyp) and then Is_Derived_Type (Underlying_Type (Base_Type (Atyp))) then return Unchecked_Convert_To (Ftyp, Arg); else return Arg; end if; end Convert_View; ------------------------------- -- CW_Or_Has_Controlled_Part -- ------------------------------- function CW_Or_Has_Controlled_Part (T : Entity_Id) return Boolean is begin return Is_Class_Wide_Type (T) or else Needs_Finalization (T); end CW_Or_Has_Controlled_Part; ------------------------ -- Enclosing_Function -- ------------------------ function Enclosing_Function (E : Entity_Id) return Entity_Id is Func_Id : Entity_Id; begin Func_Id := E; while Present (Func_Id) and then Func_Id /= Standard_Standard loop if Ekind (Func_Id) = E_Function then return Func_Id; end if; Func_Id := Scope (Func_Id); end loop; return Empty; end Enclosing_Function; ------------------------------- -- Establish_Transient_Scope -- ------------------------------- -- This procedure is called each time a transient block has to be inserted -- that is to say for each call to a function with unconstrained or tagged -- result. It creates a new scope on the scope stack in order to enclose -- all transient variables generated. procedure Establish_Transient_Scope (N : Node_Id; Manage_Sec_Stack : Boolean) is procedure Create_Transient_Scope (Constr : Node_Id); -- Place a new scope on the scope stack in order to service construct -- Constr. The new scope may also manage the secondary stack. procedure Delegate_Sec_Stack_Management; -- Move the management of the secondary stack to the nearest enclosing -- suitable scope. function Find_Enclosing_Transient_Scope return Entity_Id; -- Examine the scope stack looking for the nearest enclosing transient -- scope. Return Empty if no such scope exists. function Is_Package_Or_Subprogram (Id : Entity_Id) return Boolean; -- Determine whether arbitrary Id denotes a package or subprogram [body] ---------------------------- -- Create_Transient_Scope -- ---------------------------- procedure Create_Transient_Scope (Constr : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Iter_Loop : Entity_Id; Trans_Scop : Entity_Id; begin Trans_Scop := New_Internal_Entity (E_Block, Current_Scope, Loc, 'B'); Set_Etype (Trans_Scop, Standard_Void_Type); Push_Scope (Trans_Scop); Set_Node_To_Be_Wrapped (Constr); Set_Scope_Is_Transient; -- The transient scope must also manage the secondary stack if Manage_Sec_Stack then Set_Uses_Sec_Stack (Trans_Scop); Check_Restriction (No_Secondary_Stack, N); -- The expansion of iterator loops generates references to objects -- in order to extract elements from a container: -- Ref : Reference_Type_Ptr := Reference (Container, Cursor); -- Obj : <object type> renames Ref.all.Element.all; -- These references are controlled and returned on the secondary -- stack. A new reference is created at each iteration of the loop -- and as a result it must be finalized and the space occupied by -- it on the secondary stack reclaimed at the end of the current -- iteration. -- When the context that requires a transient scope is a call to -- routine Reference, the node to be wrapped is the source object: -- for Obj of Container loop -- Routine Wrap_Transient_Declaration however does not generate -- a physical block as wrapping a declaration will kill it too -- early. To handle this peculiar case, mark the related iterator -- loop as requiring the secondary stack. This signals the -- finalization machinery to manage the secondary stack (see -- routine Process_Statements_For_Controlled_Objects). Iter_Loop := Find_Enclosing_Iterator_Loop (Trans_Scop); if Present (Iter_Loop) then Set_Uses_Sec_Stack (Iter_Loop); end if; end if; if Debug_Flag_W then Write_Str (" <Transient>"); Write_Eol; end if; end Create_Transient_Scope; ----------------------------------- -- Delegate_Sec_Stack_Management -- ----------------------------------- procedure Delegate_Sec_Stack_Management is Scop_Id : Entity_Id; Scop_Rec : Scope_Stack_Entry; begin for Index in reverse Scope_Stack.First .. Scope_Stack.Last loop Scop_Rec := Scope_Stack.Table (Index); Scop_Id := Scop_Rec.Entity; -- Prevent the search from going too far or within the scope space -- of another unit. if Scop_Id = Standard_Standard then return; -- No transient scope should be encountered during the traversal -- because Establish_Transient_Scope should have already handled -- this case. elsif Scop_Rec.Is_Transient then pragma Assert (False); return; -- The construct which requires secondary stack management is -- always enclosed by a package or subprogram scope. elsif Is_Package_Or_Subprogram (Scop_Id) then Set_Uses_Sec_Stack (Scop_Id); Check_Restriction (No_Secondary_Stack, N); return; end if; end loop; -- At this point no suitable scope was found. This should never occur -- because a construct is always enclosed by a compilation unit which -- has a scope. pragma Assert (False); end Delegate_Sec_Stack_Management; ------------------------------------ -- Find_Enclosing_Transient_Scope -- ------------------------------------ function Find_Enclosing_Transient_Scope return Entity_Id is Scop_Id : Entity_Id; Scop_Rec : Scope_Stack_Entry; begin for Index in reverse Scope_Stack.First .. Scope_Stack.Last loop Scop_Rec := Scope_Stack.Table (Index); Scop_Id := Scop_Rec.Entity; -- Prevent the search from going too far or within the scope space -- of another unit. if Scop_Id = Standard_Standard or else Is_Package_Or_Subprogram (Scop_Id) then exit; elsif Scop_Rec.Is_Transient then return Scop_Id; end if; end loop; return Empty; end Find_Enclosing_Transient_Scope; ------------------------------ -- Is_Package_Or_Subprogram -- ------------------------------ function Is_Package_Or_Subprogram (Id : Entity_Id) return Boolean is begin return Ekind (Id) in E_Entry | E_Entry_Family | E_Function | E_Package | E_Procedure | E_Subprogram_Body; end Is_Package_Or_Subprogram; -- Local variables Trans_Id : constant Entity_Id := Find_Enclosing_Transient_Scope; Context : Node_Id; -- Start of processing for Establish_Transient_Scope begin -- Do not create a new transient scope if there is an existing transient -- scope on the stack. if Present (Trans_Id) then -- If the transient scope was requested for purposes of managing the -- secondary stack, then the existing scope must perform this task. if Manage_Sec_Stack then Set_Uses_Sec_Stack (Trans_Id); end if; return; end if; -- At this point it is known that the scope stack is free of transient -- scopes. Locate the proper construct which must be serviced by a new -- transient scope. Context := Find_Transient_Context (N); if Present (Context) then if Nkind (Context) = N_Assignment_Statement then -- An assignment statement with suppressed controlled semantics -- does not need a transient scope because finalization is not -- desirable at this point. Note that No_Ctrl_Actions is also -- set for non-controlled assignments to suppress dispatching -- _assign. if No_Ctrl_Actions (Context) and then Needs_Finalization (Etype (Name (Context))) then -- When a controlled component is initialized by a function -- call, the result on the secondary stack is always assigned -- to the component. Signal the nearest suitable scope that it -- is safe to manage the secondary stack. if Manage_Sec_Stack and then Within_Init_Proc then Delegate_Sec_Stack_Management; end if; -- Otherwise the assignment is a normal transient context and thus -- requires a transient scope. else Create_Transient_Scope (Context); end if; -- General case else Create_Transient_Scope (Context); end if; end if; end Establish_Transient_Scope; ---------------------------- -- Expand_Cleanup_Actions -- ---------------------------- procedure Expand_Cleanup_Actions (N : Node_Id) is pragma Assert (Nkind (N) in N_Block_Statement | N_Entry_Body | N_Extended_Return_Statement | N_Subprogram_Body | N_Task_Body); Scop : constant Entity_Id := Current_Scope; Is_Asynchronous_Call : constant Boolean := Nkind (N) = N_Block_Statement and then Is_Asynchronous_Call_Block (N); Is_Master : constant Boolean := Nkind (N) /= N_Extended_Return_Statement and then Nkind (N) /= N_Entry_Body and then Is_Task_Master (N); Is_Protected_Subp_Body : constant Boolean := Nkind (N) = N_Subprogram_Body and then Is_Protected_Subprogram_Body (N); Is_Task_Allocation : constant Boolean := Nkind (N) = N_Block_Statement and then Is_Task_Allocation_Block (N); Is_Task_Body : constant Boolean := Nkind (Original_Node (N)) = N_Task_Body; -- We mark the secondary stack if it is used in this construct, and -- we're not returning a function result on the secondary stack, except -- that a build-in-place function that might or might not return on the -- secondary stack always needs a mark. A run-time test is required in -- the case where the build-in-place function has a BIP_Alloc extra -- parameter (see Create_Finalizer). Needs_Sec_Stack_Mark : constant Boolean := (Uses_Sec_Stack (Scop) and then not Sec_Stack_Needed_For_Return (Scop)) or else (Is_Build_In_Place_Function (Scop) and then Needs_BIP_Alloc_Form (Scop)); Needs_Custom_Cleanup : constant Boolean := Nkind (N) = N_Block_Statement and then Present (Cleanup_Actions (N)); Actions_Required : constant Boolean := Requires_Cleanup_Actions (N, True) or else Is_Asynchronous_Call or else Is_Master or else Is_Protected_Subp_Body or else Is_Task_Allocation or else Is_Task_Body or else Needs_Sec_Stack_Mark or else Needs_Custom_Cleanup; HSS : Node_Id := Handled_Statement_Sequence (N); Loc : Source_Ptr; Cln : List_Id; procedure Wrap_HSS_In_Block; -- Move HSS inside a new block along with the original exception -- handlers. Make the newly generated block the sole statement of HSS. ----------------------- -- Wrap_HSS_In_Block -- ----------------------- procedure Wrap_HSS_In_Block is Block : Node_Id; Block_Id : Entity_Id; End_Lab : Node_Id; begin -- Preserve end label to provide proper cross-reference information End_Lab := End_Label (HSS); Block := Make_Block_Statement (Loc, Handled_Statement_Sequence => HSS); Block_Id := New_Internal_Entity (E_Block, Current_Scope, Loc, 'B'); Set_Identifier (Block, New_Occurrence_Of (Block_Id, Loc)); Set_Etype (Block_Id, Standard_Void_Type); Set_Block_Node (Block_Id, Identifier (Block)); -- Signal the finalization machinery that this particular block -- contains the original context. Set_Is_Finalization_Wrapper (Block); Set_Handled_Statement_Sequence (N, Make_Handled_Sequence_Of_Statements (Loc, New_List (Block))); HSS := Handled_Statement_Sequence (N); Set_First_Real_Statement (HSS, Block); Set_End_Label (HSS, End_Lab); -- Comment needed here, see RH for 1.306 ??? if Nkind (N) = N_Subprogram_Body then Set_Has_Nested_Block_With_Handler (Scop); end if; end Wrap_HSS_In_Block; -- Start of processing for Expand_Cleanup_Actions begin -- The current construct does not need any form of servicing if not Actions_Required then return; -- If the current node is a rewritten task body and the descriptors have -- not been delayed (due to some nested instantiations), do not generate -- redundant cleanup actions. elsif Is_Task_Body and then Nkind (N) = N_Subprogram_Body and then not Delay_Subprogram_Descriptors (Corresponding_Spec (N)) then return; end if; -- If an extended return statement contains something like -- -- X := F (...); -- -- where F is a build-in-place function call returning a controlled -- type, then a temporary object will be implicitly declared as part -- of the statement list, and this will need cleanup. In such cases, -- we transform: -- -- return Result : T := ... do -- <statements> -- possibly with handlers -- end return; -- -- into: -- -- return Result : T := ... do -- declare -- no declarations -- begin -- <statements> -- possibly with handlers -- end; -- no handlers -- end return; -- -- So Expand_Cleanup_Actions will end up being called recursively on the -- block statement. if Nkind (N) = N_Extended_Return_Statement then declare Block : constant Node_Id := Make_Block_Statement (Sloc (N), Declarations => Empty_List, Handled_Statement_Sequence => Handled_Statement_Sequence (N)); begin Set_Handled_Statement_Sequence (N, Make_Handled_Sequence_Of_Statements (Sloc (N), Statements => New_List (Block))); Analyze (Block); end; -- Analysis of the block did all the work return; end if; if Needs_Custom_Cleanup then Cln := Cleanup_Actions (N); else Cln := No_List; end if; declare Decls : List_Id := Declarations (N); Fin_Id : Entity_Id; Mark : Entity_Id := Empty; New_Decls : List_Id; begin -- If we are generating expanded code for debugging purposes, use the -- Sloc of the point of insertion for the cleanup code. The Sloc will -- be updated subsequently to reference the proper line in .dg files. -- If we are not debugging generated code, use No_Location instead, -- so that no debug information is generated for the cleanup code. -- This makes the behavior of the NEXT command in GDB monotonic, and -- makes the placement of breakpoints more accurate. if Debug_Generated_Code then Loc := Sloc (Scop); else Loc := No_Location; end if; -- A task activation call has already been built for a task -- allocation block. if not Is_Task_Allocation then Build_Task_Activation_Call (N); end if; if Is_Master then Establish_Task_Master (N); end if; New_Decls := New_List; -- If secondary stack is in use, generate: -- -- Mnn : constant Mark_Id := SS_Mark; if Needs_Sec_Stack_Mark then Mark := Make_Temporary (Loc, 'M'); Append_To (New_Decls, Build_SS_Mark_Call (Loc, Mark)); Set_Uses_Sec_Stack (Scop, False); end if; -- If exception handlers are present, wrap the sequence of statements -- in a block since it is not possible to have exception handlers and -- an At_End handler in the same construct. if Present (Exception_Handlers (HSS)) then Wrap_HSS_In_Block; -- Ensure that the First_Real_Statement field is set elsif No (First_Real_Statement (HSS)) then Set_First_Real_Statement (HSS, First (Statements (HSS))); end if; -- Do not move the Activation_Chain declaration in the context of -- task allocation blocks. Task allocation blocks use _chain in their -- cleanup handlers and gigi complains if it is declared in the -- sequence of statements of the scope that declares the handler. if Is_Task_Allocation then declare Chain : constant Entity_Id := Activation_Chain_Entity (N); Decl : Node_Id; begin Decl := First (Decls); while Nkind (Decl) /= N_Object_Declaration or else Defining_Identifier (Decl) /= Chain loop Next (Decl); -- A task allocation block should always include a _chain -- declaration. pragma Assert (Present (Decl)); end loop; Remove (Decl); Prepend_To (New_Decls, Decl); end; end if; -- Ensure the presence of a declaration list in order to successfully -- append all original statements to it. if No (Decls) then Set_Declarations (N, New_List); Decls := Declarations (N); end if; -- Move the declarations into the sequence of statements in order to -- have them protected by the At_End handler. It may seem weird to -- put declarations in the sequence of statement but in fact nothing -- forbids that at the tree level. Append_List_To (Decls, Statements (HSS)); Set_Statements (HSS, Decls); -- Reset the Sloc of the handled statement sequence to properly -- reflect the new initial "statement" in the sequence. Set_Sloc (HSS, Sloc (First (Decls))); -- The declarations of finalizer spec and auxiliary variables replace -- the old declarations that have been moved inward. Set_Declarations (N, New_Decls); Analyze_Declarations (New_Decls); -- Generate finalization calls for all controlled objects appearing -- in the statements of N. Add context specific cleanup for various -- constructs. Build_Finalizer (N => N, Clean_Stmts => Build_Cleanup_Statements (N, Cln), Mark_Id => Mark, Top_Decls => New_Decls, Defer_Abort => Nkind (Original_Node (N)) = N_Task_Body or else Is_Master, Fin_Id => Fin_Id); if Present (Fin_Id) then Build_Finalizer_Call (N, Fin_Id); end if; end; end Expand_Cleanup_Actions; --------------------------- -- Expand_N_Package_Body -- --------------------------- -- Add call to Activate_Tasks if body is an activator (actual processing -- is in chapter 9). -- Generate subprogram descriptor for elaboration routine -- Encode entity names in package body procedure Expand_N_Package_Body (N : Node_Id) is Spec_Id : constant Entity_Id := Corresponding_Spec (N); Fin_Id : Entity_Id; begin -- This is done only for non-generic packages if Ekind (Spec_Id) = E_Package then Push_Scope (Spec_Id); -- Build dispatch tables of library level tagged types if Tagged_Type_Expansion and then Is_Library_Level_Entity (Spec_Id) then Build_Static_Dispatch_Tables (N); end if; Build_Task_Activation_Call (N); -- Verify the run-time semantics of pragma Initial_Condition at the -- end of the body statements. Expand_Pragma_Initial_Condition (Spec_Id, N); -- If this is a library-level package and unnesting is enabled, -- check for the presence of blocks with nested subprograms occurring -- in elaboration code, and generate procedures to encapsulate the -- blocks in case the nested subprograms make up-level references. if Unnest_Subprogram_Mode and then Is_Library_Level_Entity (Current_Scope) then Check_Unnesting_Elaboration_Code (N); Check_Unnesting_In_Decls_Or_Stmts (Declarations (N)); Check_Unnesting_In_Handlers (N); end if; Pop_Scope; end if; Set_Elaboration_Flag (N, Spec_Id); Set_In_Package_Body (Spec_Id, False); -- Set to encode entity names in package body before gigi is called Qualify_Entity_Names (N); if Ekind (Spec_Id) /= E_Generic_Package then Build_Finalizer (N => N, Clean_Stmts => No_List, Mark_Id => Empty, Top_Decls => No_List, Defer_Abort => False, Fin_Id => Fin_Id); if Present (Fin_Id) then declare Body_Ent : Node_Id := Defining_Unit_Name (N); begin if Nkind (Body_Ent) = N_Defining_Program_Unit_Name then Body_Ent := Defining_Identifier (Body_Ent); end if; Set_Finalizer (Body_Ent, Fin_Id); end; end if; end if; end Expand_N_Package_Body; ---------------------------------- -- Expand_N_Package_Declaration -- ---------------------------------- -- Add call to Activate_Tasks if there are tasks declared and the package -- has no body. Note that in Ada 83 this may result in premature activation -- of some tasks, given that we cannot tell whether a body will eventually -- appear. procedure Expand_N_Package_Declaration (N : Node_Id) is Id : constant Entity_Id := Defining_Entity (N); Spec : constant Node_Id := Specification (N); Decls : List_Id; Fin_Id : Entity_Id; No_Body : Boolean := False; -- True in the case of a package declaration that is a compilation -- unit and for which no associated body will be compiled in this -- compilation. begin -- Case of a package declaration other than a compilation unit if Nkind (Parent (N)) /= N_Compilation_Unit then null; -- Case of a compilation unit that does not require a body elsif not Body_Required (Parent (N)) and then not Unit_Requires_Body (Id) then No_Body := True; -- Special case of generating calling stubs for a remote call interface -- package: even though the package declaration requires one, the body -- won't be processed in this compilation (so any stubs for RACWs -- declared in the package must be generated here, along with the spec). elsif Parent (N) = Cunit (Main_Unit) and then Is_Remote_Call_Interface (Id) and then Distribution_Stub_Mode = Generate_Caller_Stub_Body then No_Body := True; end if; -- For a nested instance, delay processing until freeze point if Has_Delayed_Freeze (Id) and then Nkind (Parent (N)) /= N_Compilation_Unit then return; end if; -- For a package declaration that implies no associated body, generate -- task activation call and RACW supporting bodies now (since we won't -- have a specific separate compilation unit for that). if No_Body then Push_Scope (Id); -- Generate RACW subprogram bodies if Has_RACW (Id) then Decls := Private_Declarations (Spec); if No (Decls) then Decls := Visible_Declarations (Spec); end if; if No (Decls) then Decls := New_List; Set_Visible_Declarations (Spec, Decls); end if; Append_RACW_Bodies (Decls, Id); Analyze_List (Decls); end if; -- Generate task activation call as last step of elaboration if Present (Activation_Chain_Entity (N)) then Build_Task_Activation_Call (N); end if; -- Verify the run-time semantics of pragma Initial_Condition at the -- end of the private declarations when the package lacks a body. Expand_Pragma_Initial_Condition (Id, N); Pop_Scope; end if; -- Build dispatch tables of library level tagged types if Tagged_Type_Expansion and then (Is_Compilation_Unit (Id) or else (Is_Generic_Instance (Id) and then Is_Library_Level_Entity (Id))) then Build_Static_Dispatch_Tables (N); end if; -- Note: it is not necessary to worry about generating a subprogram -- descriptor, since the only way to get exception handlers into a -- package spec is to include instantiations, and that would cause -- generation of subprogram descriptors to be delayed in any case. -- Set to encode entity names in package spec before gigi is called Qualify_Entity_Names (N); if Ekind (Id) /= E_Generic_Package then Build_Finalizer (N => N, Clean_Stmts => No_List, Mark_Id => Empty, Top_Decls => No_List, Defer_Abort => False, Fin_Id => Fin_Id); Set_Finalizer (Id, Fin_Id); end if; -- If this is a library-level package and unnesting is enabled, -- check for the presence of blocks with nested subprograms occurring -- in elaboration code, and generate procedures to encapsulate the -- blocks in case the nested subprograms make up-level references. if Unnest_Subprogram_Mode and then Is_Library_Level_Entity (Current_Scope) then Check_Unnesting_In_Decls_Or_Stmts (Visible_Declarations (Spec)); Check_Unnesting_In_Decls_Or_Stmts (Private_Declarations (Spec)); end if; end Expand_N_Package_Declaration; ---------------------------- -- Find_Transient_Context -- ---------------------------- function Find_Transient_Context (N : Node_Id) return Node_Id is Curr : Node_Id; Prev : Node_Id; begin Curr := N; Prev := Empty; while Present (Curr) loop case Nkind (Curr) is -- Declarations -- Declarations act as a boundary for a transient scope even if -- they are not wrapped, see Wrap_Transient_Declaration. when N_Object_Declaration | N_Object_Renaming_Declaration | N_Subtype_Declaration => return Curr; -- Statements -- Statements and statement-like constructs act as a boundary for -- a transient scope. when N_Accept_Alternative | N_Attribute_Definition_Clause | N_Case_Statement | N_Case_Statement_Alternative | N_Code_Statement | N_Delay_Alternative | N_Delay_Until_Statement | N_Delay_Relative_Statement | N_Discriminant_Association | N_Elsif_Part | N_Entry_Body_Formal_Part | N_Exit_Statement | N_If_Statement | N_Iteration_Scheme | N_Terminate_Alternative => pragma Assert (Present (Prev)); return Prev; when N_Assignment_Statement => return Curr; when N_Entry_Call_Statement | N_Procedure_Call_Statement => -- When an entry or procedure call acts as the alternative of a -- conditional or timed entry call, the proper context is that -- of the alternative. if Nkind (Parent (Curr)) = N_Entry_Call_Alternative and then Nkind (Parent (Parent (Curr))) in N_Conditional_Entry_Call | N_Timed_Entry_Call then return Parent (Parent (Curr)); -- General case for entry or procedure calls else return Curr; end if; when N_Pragma => -- Pragma Check is not a valid transient context in GNATprove -- mode because the pragma must remain unchanged. if GNATprove_Mode and then Get_Pragma_Id (Curr) = Pragma_Check then return Empty; -- General case for pragmas else return Curr; end if; when N_Raise_Statement => return Curr; when N_Simple_Return_Statement => -- A return statement is not a valid transient context when the -- function itself requires transient scope management because -- the result will be reclaimed too early. if Requires_Transient_Scope (Etype (Return_Applies_To (Return_Statement_Entity (Curr)))) then return Empty; -- General case for return statements else return Curr; end if; -- Special when N_Attribute_Reference => if Is_Procedure_Attribute_Name (Attribute_Name (Curr)) then return Curr; end if; -- An Ada 2012 iterator specification is not a valid context -- because Analyze_Iterator_Specification already employs special -- processing for it. when N_Iterator_Specification => return Empty; when N_Loop_Parameter_Specification => -- An iteration scheme is not a valid context because routine -- Analyze_Iteration_Scheme already employs special processing. if Nkind (Parent (Curr)) = N_Iteration_Scheme then return Empty; else return Parent (Curr); end if; -- Termination -- The following nodes represent "dummy contexts" which do not -- need to be wrapped. when N_Component_Declaration | N_Discriminant_Specification | N_Parameter_Specification => return Empty; -- If the traversal leaves a scope without having been able to -- find a construct to wrap, something is going wrong, but this -- can happen in error situations that are not detected yet (such -- as a dynamic string in a pragma Export). when N_Block_Statement | N_Entry_Body | N_Package_Body | N_Package_Declaration | N_Protected_Body | N_Subprogram_Body | N_Task_Body => return Empty; -- Default when others => null; end case; Prev := Curr; Curr := Parent (Curr); end loop; return Empty; end Find_Transient_Context; ---------------------------------- -- Has_New_Controlled_Component -- ---------------------------------- function Has_New_Controlled_Component (E : Entity_Id) return Boolean is Comp : Entity_Id; begin if not Is_Tagged_Type (E) then return Has_Controlled_Component (E); elsif not Is_Derived_Type (E) then return Has_Controlled_Component (E); end if; Comp := First_Component (E); while Present (Comp) loop if Chars (Comp) = Name_uParent then null; elsif Scope (Original_Record_Component (Comp)) = E and then Needs_Finalization (Etype (Comp)) then return True; end if; Next_Component (Comp); end loop; return False; end Has_New_Controlled_Component; --------------------------------- -- Has_Simple_Protected_Object -- --------------------------------- function Has_Simple_Protected_Object (T : Entity_Id) return Boolean is begin if Has_Task (T) then return False; elsif Is_Simple_Protected_Type (T) then return True; elsif Is_Array_Type (T) then return Has_Simple_Protected_Object (Component_Type (T)); elsif Is_Record_Type (T) then declare Comp : Entity_Id; begin Comp := First_Component (T); while Present (Comp) loop if Has_Simple_Protected_Object (Etype (Comp)) then return True; end if; Next_Component (Comp); end loop; return False; end; else return False; end if; end Has_Simple_Protected_Object; ------------------------------------ -- Insert_Actions_In_Scope_Around -- ------------------------------------ procedure Insert_Actions_In_Scope_Around (N : Node_Id; Clean : Boolean; Manage_SS : Boolean) is Act_Before : constant List_Id := Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (Before); Act_After : constant List_Id := Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (After); Act_Cleanup : constant List_Id := Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (Cleanup); -- Note: We used to use renamings of Scope_Stack.Table (Scope_Stack. -- Last), but this was incorrect as Process_Transients_In_Scope may -- introduce new scopes and cause a reallocation of Scope_Stack.Table. procedure Process_Transients_In_Scope (First_Object : Node_Id; Last_Object : Node_Id; Related_Node : Node_Id); -- Find all transient objects in the list First_Object .. Last_Object -- and generate finalization actions for them. Related_Node denotes the -- node which created all transient objects. --------------------------------- -- Process_Transients_In_Scope -- --------------------------------- procedure Process_Transients_In_Scope (First_Object : Node_Id; Last_Object : Node_Id; Related_Node : Node_Id) is Must_Hook : Boolean := False; -- Flag denoting whether the context requires transient object -- export to the outer finalizer. function Is_Subprogram_Call (N : Node_Id) return Traverse_Result; -- Determine whether an arbitrary node denotes a subprogram call procedure Detect_Subprogram_Call is new Traverse_Proc (Is_Subprogram_Call); procedure Process_Transient_In_Scope (Obj_Decl : Node_Id; Blk_Data : Finalization_Exception_Data; Blk_Stmts : List_Id); -- Generate finalization actions for a single transient object -- denoted by object declaration Obj_Decl. Blk_Data is the -- exception data of the enclosing block. Blk_Stmts denotes the -- statements of the enclosing block. ------------------------ -- Is_Subprogram_Call -- ------------------------ function Is_Subprogram_Call (N : Node_Id) return Traverse_Result is begin -- A regular procedure or function call if Nkind (N) in N_Subprogram_Call then Must_Hook := True; return Abandon; -- Special cases -- Heavy expansion may relocate function calls outside the related -- node. Inspect the original node to detect the initial placement -- of the call. elsif Is_Rewrite_Substitution (N) then Detect_Subprogram_Call (Original_Node (N)); if Must_Hook then return Abandon; else return OK; end if; -- Generalized indexing always involves a function call elsif Nkind (N) = N_Indexed_Component and then Present (Generalized_Indexing (N)) then Must_Hook := True; return Abandon; -- Keep searching else return OK; end if; end Is_Subprogram_Call; -------------------------------- -- Process_Transient_In_Scope -- -------------------------------- procedure Process_Transient_In_Scope (Obj_Decl : Node_Id; Blk_Data : Finalization_Exception_Data; Blk_Stmts : List_Id) is Loc : constant Source_Ptr := Sloc (Obj_Decl); Obj_Id : constant Entity_Id := Defining_Entity (Obj_Decl); Fin_Call : Node_Id; Fin_Stmts : List_Id; Hook_Assign : Node_Id; Hook_Clear : Node_Id; Hook_Decl : Node_Id; Hook_Insert : Node_Id; Ptr_Decl : Node_Id; begin -- Mark the transient object as successfully processed to avoid -- double finalization. Set_Is_Finalized_Transient (Obj_Id); -- Construct all the pieces necessary to hook and finalize the -- transient object. Build_Transient_Object_Statements (Obj_Decl => Obj_Decl, Fin_Call => Fin_Call, Hook_Assign => Hook_Assign, Hook_Clear => Hook_Clear, Hook_Decl => Hook_Decl, Ptr_Decl => Ptr_Decl); -- The context contains at least one subprogram call which may -- raise an exception. This scenario employs "hooking" to pass -- transient objects to the enclosing finalizer in case of an -- exception. if Must_Hook then -- Add the access type which provides a reference to the -- transient object. Generate: -- type Ptr_Typ is access all Desig_Typ; Insert_Action (Obj_Decl, Ptr_Decl); -- Add the temporary which acts as a hook to the transient -- object. Generate: -- Hook : Ptr_Typ := null; Insert_Action (Obj_Decl, Hook_Decl); -- When the transient object is initialized by an aggregate, -- the hook must capture the object after the last aggregate -- assignment takes place. Only then is the object considered -- fully initialized. Generate: -- Hook := Ptr_Typ (Obj_Id); -- <or> -- Hook := Obj_Id'Unrestricted_Access; -- Similarly if we have a build in place call: we must -- initialize Hook only after the call has happened, otherwise -- Obj_Id will not be initialized yet. if Ekind (Obj_Id) in E_Constant | E_Variable then if Present (Last_Aggregate_Assignment (Obj_Id)) then Hook_Insert := Last_Aggregate_Assignment (Obj_Id); elsif Present (BIP_Initialization_Call (Obj_Id)) then Hook_Insert := BIP_Initialization_Call (Obj_Id); else Hook_Insert := Obj_Decl; end if; -- Otherwise the hook seizes the related object immediately else Hook_Insert := Obj_Decl; end if; Insert_After_And_Analyze (Hook_Insert, Hook_Assign); end if; -- When exception propagation is enabled wrap the hook clear -- statement and the finalization call into a block to catch -- potential exceptions raised during finalization. Generate: -- begin -- [Hook := null;] -- [Deep_]Finalize (Obj_Ref); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence -- (Enn, Get_Current_Excep.all.all); -- end if; -- end; if Exceptions_OK then Fin_Stmts := New_List; if Must_Hook then Append_To (Fin_Stmts, Hook_Clear); end if; Append_To (Fin_Stmts, Fin_Call); Prepend_To (Blk_Stmts, Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Fin_Stmts, Exception_Handlers => New_List ( Build_Exception_Handler (Blk_Data))))); -- Otherwise generate: -- [Hook := null;] -- [Deep_]Finalize (Obj_Ref); -- Note that the statements are inserted in reverse order to -- achieve the desired final order outlined above. else Prepend_To (Blk_Stmts, Fin_Call); if Must_Hook then Prepend_To (Blk_Stmts, Hook_Clear); end if; end if; end Process_Transient_In_Scope; -- Local variables Built : Boolean := False; Blk_Data : Finalization_Exception_Data; Blk_Decl : Node_Id := Empty; Blk_Decls : List_Id := No_List; Blk_Ins : Node_Id; Blk_Stmts : List_Id := No_List; Loc : Source_Ptr := No_Location; Obj_Decl : Node_Id; -- Start of processing for Process_Transients_In_Scope begin -- The expansion performed by this routine is as follows: -- type Ptr_Typ_1 is access all Ctrl_Trans_Obj_1_Typ; -- Hook_1 : Ptr_Typ_1 := null; -- Ctrl_Trans_Obj_1 : ...; -- Hook_1 := Ctrl_Trans_Obj_1'Unrestricted_Access; -- . . . -- type Ptr_Typ_N is access all Ctrl_Trans_Obj_N_Typ; -- Hook_N : Ptr_Typ_N := null; -- Ctrl_Trans_Obj_N : ...; -- Hook_N := Ctrl_Trans_Obj_N'Unrestricted_Access; -- declare -- Abrt : constant Boolean := ...; -- Ex : Exception_Occurrence; -- Raised : Boolean := False; -- begin -- Abort_Defer; -- begin -- Hook_N := null; -- [Deep_]Finalize (Ctrl_Trans_Obj_N); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (Ex, Get_Current_Excep.all.all); -- end; -- . . . -- begin -- Hook_1 := null; -- [Deep_]Finalize (Ctrl_Trans_Obj_1); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (Ex, Get_Current_Excep.all.all); -- end; -- Abort_Undefer; -- if Raised and not Abrt then -- Raise_From_Controlled_Operation (Ex); -- end if; -- end; -- Recognize a scenario where the transient context is an object -- declaration initialized by a build-in-place function call: -- Obj : ... := BIP_Function_Call (Ctrl_Func_Call); -- The rough expansion of the above is: -- Temp : ... := Ctrl_Func_Call; -- Obj : ...; -- Res : ... := BIP_Func_Call (..., Obj, ...); -- The finalization of any transient object must happen after the -- build-in-place function call is executed. if Nkind (N) = N_Object_Declaration and then Present (BIP_Initialization_Call (Defining_Identifier (N))) then Must_Hook := True; Blk_Ins := BIP_Initialization_Call (Defining_Identifier (N)); -- Search the context for at least one subprogram call. If found, the -- machinery exports all transient objects to the enclosing finalizer -- due to the possibility of abnormal call termination. else Detect_Subprogram_Call (N); Blk_Ins := Last_Object; end if; if Clean then Insert_List_After_And_Analyze (Blk_Ins, Act_Cleanup); end if; -- Examine all objects in the list First_Object .. Last_Object Obj_Decl := First_Object; while Present (Obj_Decl) loop if Nkind (Obj_Decl) = N_Object_Declaration and then Analyzed (Obj_Decl) and then Is_Finalizable_Transient (Obj_Decl, N) -- Do not process the node to be wrapped since it will be -- handled by the enclosing finalizer. and then Obj_Decl /= Related_Node then Loc := Sloc (Obj_Decl); -- Before generating the cleanup code for the first transient -- object, create a wrapper block which houses all hook clear -- statements and finalization calls. This wrapper is needed by -- the back end. if not Built then Built := True; Blk_Stmts := New_List; -- Generate: -- Abrt : constant Boolean := ...; -- Ex : Exception_Occurrence; -- Raised : Boolean := False; if Exceptions_OK then Blk_Decls := New_List; Build_Object_Declarations (Blk_Data, Blk_Decls, Loc); end if; Blk_Decl := Make_Block_Statement (Loc, Declarations => Blk_Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Blk_Stmts)); end if; -- Construct all necessary circuitry to hook and finalize a -- single transient object. pragma Assert (Present (Blk_Stmts)); Process_Transient_In_Scope (Obj_Decl => Obj_Decl, Blk_Data => Blk_Data, Blk_Stmts => Blk_Stmts); end if; -- Terminate the scan after the last object has been processed to -- avoid touching unrelated code. if Obj_Decl = Last_Object then exit; end if; Next (Obj_Decl); end loop; -- Complete the decoration of the enclosing finalization block and -- insert it into the tree. if Present (Blk_Decl) then pragma Assert (Present (Blk_Stmts)); pragma Assert (Loc /= No_Location); -- Note that this Abort_Undefer does not require a extra block or -- an AT_END handler because each finalization exception is caught -- in its own corresponding finalization block. As a result, the -- call to Abort_Defer always takes place. if Abort_Allowed then Prepend_To (Blk_Stmts, Build_Runtime_Call (Loc, RE_Abort_Defer)); Append_To (Blk_Stmts, Build_Runtime_Call (Loc, RE_Abort_Undefer)); end if; -- Generate: -- if Raised and then not Abrt then -- Raise_From_Controlled_Operation (Ex); -- end if; if Exceptions_OK then Append_To (Blk_Stmts, Build_Raise_Statement (Blk_Data)); end if; Insert_After_And_Analyze (Blk_Ins, Blk_Decl); end if; end Process_Transients_In_Scope; -- Local variables Loc : constant Source_Ptr := Sloc (N); Node_To_Wrap : constant Node_Id := Node_To_Be_Wrapped; First_Obj : Node_Id; Last_Obj : Node_Id; Mark_Id : Entity_Id; Target : Node_Id; -- Start of processing for Insert_Actions_In_Scope_Around begin -- Nothing to do if the scope does not manage the secondary stack or -- does not contain meaninful actions for insertion. if not Manage_SS and then No (Act_Before) and then No (Act_After) and then No (Act_Cleanup) then return; end if; -- If the node to be wrapped is the trigger of an asynchronous select, -- it is not part of a statement list. The actions must be inserted -- before the select itself, which is part of some list of statements. -- Note that the triggering alternative includes the triggering -- statement and an optional statement list. If the node to be -- wrapped is part of that list, the normal insertion applies. if Nkind (Parent (Node_To_Wrap)) = N_Triggering_Alternative and then not Is_List_Member (Node_To_Wrap) then Target := Parent (Parent (Node_To_Wrap)); else Target := N; end if; First_Obj := Target; Last_Obj := Target; -- Add all actions associated with a transient scope into the main tree. -- There are several scenarios here: -- +--- Before ----+ +----- After ---+ -- 1) First_Obj ....... Target ........ Last_Obj -- 2) First_Obj ....... Target -- 3) Target ........ Last_Obj -- Flag declarations are inserted before the first object if Present (Act_Before) then First_Obj := First (Act_Before); Insert_List_Before (Target, Act_Before); end if; -- Finalization calls are inserted after the last object if Present (Act_After) then Last_Obj := Last (Act_After); Insert_List_After (Target, Act_After); end if; -- Mark and release the secondary stack when the context warrants it if Manage_SS then Mark_Id := Make_Temporary (Loc, 'M'); -- Generate: -- Mnn : constant Mark_Id := SS_Mark; Insert_Before_And_Analyze (First_Obj, Build_SS_Mark_Call (Loc, Mark_Id)); -- Generate: -- SS_Release (Mnn); Insert_After_And_Analyze (Last_Obj, Build_SS_Release_Call (Loc, Mark_Id)); end if; -- Check for transient objects associated with Target and generate the -- appropriate finalization actions for them. Process_Transients_In_Scope (First_Object => First_Obj, Last_Object => Last_Obj, Related_Node => Target); -- Reset the action lists Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (Before) := No_List; Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (After) := No_List; if Clean then Scope_Stack.Table (Scope_Stack.Last).Actions_To_Be_Wrapped (Cleanup) := No_List; end if; end Insert_Actions_In_Scope_Around; ------------------------------ -- Is_Simple_Protected_Type -- ------------------------------ function Is_Simple_Protected_Type (T : Entity_Id) return Boolean is begin return Is_Protected_Type (T) and then not Uses_Lock_Free (T) and then not Has_Entries (T) and then Is_RTE (Find_Protection_Type (T), RE_Protection); end Is_Simple_Protected_Type; ----------------------- -- Make_Adjust_Call -- ----------------------- function Make_Adjust_Call (Obj_Ref : Node_Id; Typ : Entity_Id; Skip_Self : Boolean := False) return Node_Id is Loc : constant Source_Ptr := Sloc (Obj_Ref); Adj_Id : Entity_Id := Empty; Ref : Node_Id; Utyp : Entity_Id; begin Ref := Obj_Ref; -- Recover the proper type which contains Deep_Adjust if Is_Class_Wide_Type (Typ) then Utyp := Root_Type (Typ); else Utyp := Typ; end if; Utyp := Underlying_Type (Base_Type (Utyp)); Set_Assignment_OK (Ref); -- Deal with untagged derivation of private views if Present (Utyp) and then Is_Untagged_Derivation (Typ) then Utyp := Underlying_Type (Root_Type (Base_Type (Typ))); Ref := Unchecked_Convert_To (Utyp, Ref); Set_Assignment_OK (Ref); end if; -- When dealing with the completion of a private type, use the base -- type instead. if Present (Utyp) and then Utyp /= Base_Type (Utyp) then pragma Assert (Is_Private_Type (Typ)); Utyp := Base_Type (Utyp); Ref := Unchecked_Convert_To (Utyp, Ref); end if; -- The underlying type may not be present due to a missing full view. In -- this case freezing did not take place and there is no [Deep_]Adjust -- primitive to call. if No (Utyp) then return Empty; elsif Skip_Self then if Has_Controlled_Component (Utyp) then if Is_Tagged_Type (Utyp) then Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust); else Adj_Id := TSS (Utyp, TSS_Deep_Adjust); end if; end if; -- Class-wide types, interfaces and types with controlled components elsif Is_Class_Wide_Type (Typ) or else Is_Interface (Typ) or else Has_Controlled_Component (Utyp) then if Is_Tagged_Type (Utyp) then Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust); else Adj_Id := TSS (Utyp, TSS_Deep_Adjust); end if; -- Derivations from [Limited_]Controlled elsif Is_Controlled (Utyp) then if Has_Controlled_Component (Utyp) then Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust); else Adj_Id := Find_Optional_Prim_Op (Utyp, Name_Of (Adjust_Case)); end if; -- Tagged types elsif Is_Tagged_Type (Utyp) then Adj_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Adjust); else raise Program_Error; end if; if Present (Adj_Id) then -- If the object is unanalyzed, set its expected type for use in -- Convert_View in case an additional conversion is needed. if No (Etype (Ref)) and then Nkind (Ref) /= N_Unchecked_Type_Conversion then Set_Etype (Ref, Typ); end if; -- The object reference may need another conversion depending on the -- type of the formal and that of the actual. if not Is_Class_Wide_Type (Typ) then Ref := Convert_View (Adj_Id, Ref); end if; return Make_Call (Loc, Proc_Id => Adj_Id, Param => Ref, Skip_Self => Skip_Self); else return Empty; end if; end Make_Adjust_Call; ---------------------- -- Make_Detach_Call -- ---------------------- function Make_Detach_Call (Obj_Ref : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Obj_Ref); begin return Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Detach), Loc), Parameter_Associations => New_List ( Unchecked_Convert_To (RTE (RE_Root_Controlled_Ptr), Obj_Ref))); end Make_Detach_Call; --------------- -- Make_Call -- --------------- function Make_Call (Loc : Source_Ptr; Proc_Id : Entity_Id; Param : Node_Id; Skip_Self : Boolean := False) return Node_Id is Params : constant List_Id := New_List (Param); begin -- Do not apply the controlled action to the object itself by signaling -- the related routine to avoid self. if Skip_Self then Append_To (Params, New_Occurrence_Of (Standard_False, Loc)); end if; return Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Proc_Id, Loc), Parameter_Associations => Params); end Make_Call; -------------------------- -- Make_Deep_Array_Body -- -------------------------- function Make_Deep_Array_Body (Prim : Final_Primitives; Typ : Entity_Id) return List_Id is function Build_Adjust_Or_Finalize_Statements (Typ : Entity_Id) return List_Id; -- Create the statements necessary to adjust or finalize an array of -- controlled elements. Generate: -- -- declare -- Abort : constant Boolean := Triggered_By_Abort; -- <or> -- Abort : constant Boolean := False; -- no abort -- -- E : Exception_Occurrence; -- Raised : Boolean := False; -- -- begin -- for J1 in [reverse] Typ'First (1) .. Typ'Last (1) loop -- ^-- in the finalization case -- ... -- for Jn in [reverse] Typ'First (n) .. Typ'Last (n) loop -- begin -- [Deep_]Adjust / Finalize (V (J1, ..., Jn)); -- -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; -- end loop; -- ... -- end loop; -- -- if Raised and then not Abort then -- Raise_From_Controlled_Operation (E); -- end if; -- end; function Build_Initialize_Statements (Typ : Entity_Id) return List_Id; -- Create the statements necessary to initialize an array of controlled -- elements. Include a mechanism to carry out partial finalization if an -- exception occurs. Generate: -- -- declare -- Counter : Integer := 0; -- -- begin -- for J1 in V'Range (1) loop -- ... -- for JN in V'Range (N) loop -- begin -- [Deep_]Initialize (V (J1, ..., JN)); -- -- Counter := Counter + 1; -- -- exception -- when others => -- declare -- Abort : constant Boolean := Triggered_By_Abort; -- <or> -- Abort : constant Boolean := False; -- no abort -- E : Exception_Occurrence; -- Raised : Boolean := False; -- begin -- Counter := -- V'Length (1) * -- V'Length (2) * -- ... -- V'Length (N) - Counter; -- for F1 in reverse V'Range (1) loop -- ... -- for FN in reverse V'Range (N) loop -- if Counter > 0 then -- Counter := Counter - 1; -- else -- begin -- [Deep_]Finalize (V (F1, ..., FN)); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, -- Get_Current_Excep.all.all); -- end if; -- end; -- end if; -- end loop; -- ... -- end loop; -- end; -- -- if Raised and then not Abort then -- Raise_From_Controlled_Operation (E); -- end if; -- -- raise; -- end; -- end loop; -- end loop; -- end; function New_References_To (L : List_Id; Loc : Source_Ptr) return List_Id; -- Given a list of defining identifiers, return a list of references to -- the original identifiers, in the same order as they appear. ----------------------------------------- -- Build_Adjust_Or_Finalize_Statements -- ----------------------------------------- function Build_Adjust_Or_Finalize_Statements (Typ : Entity_Id) return List_Id is Comp_Typ : constant Entity_Id := Component_Type (Typ); Index_List : constant List_Id := New_List; Loc : constant Source_Ptr := Sloc (Typ); Num_Dims : constant Int := Number_Dimensions (Typ); procedure Build_Indexes; -- Generate the indexes used in the dimension loops ------------------- -- Build_Indexes -- ------------------- procedure Build_Indexes is begin -- Generate the following identifiers: -- Jnn - for initialization for Dim in 1 .. Num_Dims loop Append_To (Index_List, Make_Defining_Identifier (Loc, New_External_Name ('J', Dim))); end loop; end Build_Indexes; -- Local variables Final_Decls : List_Id := No_List; Final_Data : Finalization_Exception_Data; Block : Node_Id; Call : Node_Id; Comp_Ref : Node_Id; Core_Loop : Node_Id; Dim : Int; J : Entity_Id; Loop_Id : Entity_Id; Stmts : List_Id; -- Start of processing for Build_Adjust_Or_Finalize_Statements begin Final_Decls := New_List; Build_Indexes; Build_Object_Declarations (Final_Data, Final_Decls, Loc); Comp_Ref := Make_Indexed_Component (Loc, Prefix => Make_Identifier (Loc, Name_V), Expressions => New_References_To (Index_List, Loc)); Set_Etype (Comp_Ref, Comp_Typ); -- Generate: -- [Deep_]Adjust (V (J1, ..., JN)) if Prim = Adjust_Case then Call := Make_Adjust_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ); -- Generate: -- [Deep_]Finalize (V (J1, ..., JN)) else pragma Assert (Prim = Finalize_Case); Call := Make_Final_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ); end if; if Present (Call) then -- Generate the block which houses the adjust or finalize call: -- begin -- <adjust or finalize call> -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; if Exceptions_OK then Core_Loop := Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Call), Exception_Handlers => New_List ( Build_Exception_Handler (Final_Data)))); else Core_Loop := Call; end if; -- Generate the dimension loops starting from the innermost one -- for Jnn in [reverse] V'Range (Dim) loop -- <core loop> -- end loop; J := Last (Index_List); Dim := Num_Dims; while Present (J) and then Dim > 0 loop Loop_Id := J; Prev (J); Remove (Loop_Id); Core_Loop := Make_Loop_Statement (Loc, Iteration_Scheme => Make_Iteration_Scheme (Loc, Loop_Parameter_Specification => Make_Loop_Parameter_Specification (Loc, Defining_Identifier => Loop_Id, Discrete_Subtype_Definition => Make_Attribute_Reference (Loc, Prefix => Make_Identifier (Loc, Name_V), Attribute_Name => Name_Range, Expressions => New_List ( Make_Integer_Literal (Loc, Dim))), Reverse_Present => Prim = Finalize_Case)), Statements => New_List (Core_Loop), End_Label => Empty); Dim := Dim - 1; end loop; -- Generate the block which contains the core loop, declarations -- of the abort flag, the exception occurrence, the raised flag -- and the conditional raise: -- declare -- Abort : constant Boolean := Triggered_By_Abort; -- <or> -- Abort : constant Boolean := False; -- no abort -- E : Exception_Occurrence; -- Raised : Boolean := False; -- begin -- <core loop> -- if Raised and then not Abort then -- Raise_From_Controlled_Operation (E); -- end if; -- end; Stmts := New_List (Core_Loop); if Exceptions_OK then Append_To (Stmts, Build_Raise_Statement (Final_Data)); end if; Block := Make_Block_Statement (Loc, Declarations => Final_Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts)); -- Otherwise previous errors or a missing full view may prevent the -- proper freezing of the component type. If this is the case, there -- is no [Deep_]Adjust or [Deep_]Finalize primitive to call. else Block := Make_Null_Statement (Loc); end if; return New_List (Block); end Build_Adjust_Or_Finalize_Statements; --------------------------------- -- Build_Initialize_Statements -- --------------------------------- function Build_Initialize_Statements (Typ : Entity_Id) return List_Id is Comp_Typ : constant Entity_Id := Component_Type (Typ); Final_List : constant List_Id := New_List; Index_List : constant List_Id := New_List; Loc : constant Source_Ptr := Sloc (Typ); Num_Dims : constant Int := Number_Dimensions (Typ); function Build_Assignment (Counter_Id : Entity_Id) return Node_Id; -- Generate the following assignment: -- Counter := V'Length (1) * -- ... -- V'Length (N) - Counter; -- -- Counter_Id denotes the entity of the counter. function Build_Finalization_Call return Node_Id; -- Generate a deep finalization call for an array element procedure Build_Indexes; -- Generate the initialization and finalization indexes used in the -- dimension loops. function Build_Initialization_Call return Node_Id; -- Generate a deep initialization call for an array element ---------------------- -- Build_Assignment -- ---------------------- function Build_Assignment (Counter_Id : Entity_Id) return Node_Id is Dim : Int; Expr : Node_Id; begin -- Start from the first dimension and generate: -- V'Length (1) Dim := 1; Expr := Make_Attribute_Reference (Loc, Prefix => Make_Identifier (Loc, Name_V), Attribute_Name => Name_Length, Expressions => New_List (Make_Integer_Literal (Loc, Dim))); -- Process the rest of the dimensions, generate: -- Expr * V'Length (N) Dim := Dim + 1; while Dim <= Num_Dims loop Expr := Make_Op_Multiply (Loc, Left_Opnd => Expr, Right_Opnd => Make_Attribute_Reference (Loc, Prefix => Make_Identifier (Loc, Name_V), Attribute_Name => Name_Length, Expressions => New_List ( Make_Integer_Literal (Loc, Dim)))); Dim := Dim + 1; end loop; -- Generate: -- Counter := Expr - Counter; return Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Counter_Id, Loc), Expression => Make_Op_Subtract (Loc, Left_Opnd => Expr, Right_Opnd => New_Occurrence_Of (Counter_Id, Loc))); end Build_Assignment; ----------------------------- -- Build_Finalization_Call -- ----------------------------- function Build_Finalization_Call return Node_Id is Comp_Ref : constant Node_Id := Make_Indexed_Component (Loc, Prefix => Make_Identifier (Loc, Name_V), Expressions => New_References_To (Final_List, Loc)); begin Set_Etype (Comp_Ref, Comp_Typ); -- Generate: -- [Deep_]Finalize (V); return Make_Final_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ); end Build_Finalization_Call; ------------------- -- Build_Indexes -- ------------------- procedure Build_Indexes is begin -- Generate the following identifiers: -- Jnn - for initialization -- Fnn - for finalization for Dim in 1 .. Num_Dims loop Append_To (Index_List, Make_Defining_Identifier (Loc, New_External_Name ('J', Dim))); Append_To (Final_List, Make_Defining_Identifier (Loc, New_External_Name ('F', Dim))); end loop; end Build_Indexes; ------------------------------- -- Build_Initialization_Call -- ------------------------------- function Build_Initialization_Call return Node_Id is Comp_Ref : constant Node_Id := Make_Indexed_Component (Loc, Prefix => Make_Identifier (Loc, Name_V), Expressions => New_References_To (Index_List, Loc)); begin Set_Etype (Comp_Ref, Comp_Typ); -- Generate: -- [Deep_]Initialize (V (J1, ..., JN)); return Make_Init_Call (Obj_Ref => Comp_Ref, Typ => Comp_Typ); end Build_Initialization_Call; -- Local variables Counter_Id : Entity_Id; Dim : Int; F : Node_Id; Fin_Stmt : Node_Id; Final_Block : Node_Id; Final_Data : Finalization_Exception_Data; Final_Decls : List_Id := No_List; Final_Loop : Node_Id; Init_Block : Node_Id; Init_Call : Node_Id; Init_Loop : Node_Id; J : Node_Id; Loop_Id : Node_Id; Stmts : List_Id; -- Start of processing for Build_Initialize_Statements begin Counter_Id := Make_Temporary (Loc, 'C'); Final_Decls := New_List; Build_Indexes; Build_Object_Declarations (Final_Data, Final_Decls, Loc); -- Generate the block which houses the finalization call, the index -- guard and the handler which triggers Program_Error later on. -- if Counter > 0 then -- Counter := Counter - 1; -- else -- begin -- [Deep_]Finalize (V (F1, ..., FN)); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; -- end if; Fin_Stmt := Build_Finalization_Call; if Present (Fin_Stmt) then if Exceptions_OK then Fin_Stmt := Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Fin_Stmt), Exception_Handlers => New_List ( Build_Exception_Handler (Final_Data)))); end if; -- This is the core of the loop, the dimension iterators are added -- one by one in reverse. Final_Loop := Make_If_Statement (Loc, Condition => Make_Op_Gt (Loc, Left_Opnd => New_Occurrence_Of (Counter_Id, Loc), Right_Opnd => Make_Integer_Literal (Loc, 0)), Then_Statements => New_List ( Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Counter_Id, Loc), Expression => Make_Op_Subtract (Loc, Left_Opnd => New_Occurrence_Of (Counter_Id, Loc), Right_Opnd => Make_Integer_Literal (Loc, 1)))), Else_Statements => New_List (Fin_Stmt)); -- Generate all finalization loops starting from the innermost -- dimension. -- for Fnn in reverse V'Range (Dim) loop -- <final loop> -- end loop; F := Last (Final_List); Dim := Num_Dims; while Present (F) and then Dim > 0 loop Loop_Id := F; Prev (F); Remove (Loop_Id); Final_Loop := Make_Loop_Statement (Loc, Iteration_Scheme => Make_Iteration_Scheme (Loc, Loop_Parameter_Specification => Make_Loop_Parameter_Specification (Loc, Defining_Identifier => Loop_Id, Discrete_Subtype_Definition => Make_Attribute_Reference (Loc, Prefix => Make_Identifier (Loc, Name_V), Attribute_Name => Name_Range, Expressions => New_List ( Make_Integer_Literal (Loc, Dim))), Reverse_Present => True)), Statements => New_List (Final_Loop), End_Label => Empty); Dim := Dim - 1; end loop; -- Generate the block which contains the finalization loops, the -- declarations of the abort flag, the exception occurrence, the -- raised flag and the conditional raise. -- declare -- Abort : constant Boolean := Triggered_By_Abort; -- <or> -- Abort : constant Boolean := False; -- no abort -- E : Exception_Occurrence; -- Raised : Boolean := False; -- begin -- Counter := -- V'Length (1) * -- ... -- V'Length (N) - Counter; -- <final loop> -- if Raised and then not Abort then -- Raise_From_Controlled_Operation (E); -- end if; -- raise; -- end; Stmts := New_List (Build_Assignment (Counter_Id), Final_Loop); if Exceptions_OK then Append_To (Stmts, Build_Raise_Statement (Final_Data)); Append_To (Stmts, Make_Raise_Statement (Loc)); end if; Final_Block := Make_Block_Statement (Loc, Declarations => Final_Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts)); -- Otherwise previous errors or a missing full view may prevent the -- proper freezing of the component type. If this is the case, there -- is no [Deep_]Finalize primitive to call. else Final_Block := Make_Null_Statement (Loc); end if; -- Generate the block which contains the initialization call and -- the partial finalization code. -- begin -- [Deep_]Initialize (V (J1, ..., JN)); -- Counter := Counter + 1; -- exception -- when others => -- <finalization code> -- end; Init_Call := Build_Initialization_Call; -- Only create finalization block if there is a non-trivial -- call to initialization. if Present (Init_Call) and then Nkind (Init_Call) /= N_Null_Statement then Init_Loop := Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Init_Call), Exception_Handlers => New_List ( Make_Exception_Handler (Loc, Exception_Choices => New_List ( Make_Others_Choice (Loc)), Statements => New_List (Final_Block))))); Append_To (Statements (Handled_Statement_Sequence (Init_Loop)), Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Counter_Id, Loc), Expression => Make_Op_Add (Loc, Left_Opnd => New_Occurrence_Of (Counter_Id, Loc), Right_Opnd => Make_Integer_Literal (Loc, 1)))); -- Generate all initialization loops starting from the innermost -- dimension. -- for Jnn in V'Range (Dim) loop -- <init loop> -- end loop; J := Last (Index_List); Dim := Num_Dims; while Present (J) and then Dim > 0 loop Loop_Id := J; Prev (J); Remove (Loop_Id); Init_Loop := Make_Loop_Statement (Loc, Iteration_Scheme => Make_Iteration_Scheme (Loc, Loop_Parameter_Specification => Make_Loop_Parameter_Specification (Loc, Defining_Identifier => Loop_Id, Discrete_Subtype_Definition => Make_Attribute_Reference (Loc, Prefix => Make_Identifier (Loc, Name_V), Attribute_Name => Name_Range, Expressions => New_List ( Make_Integer_Literal (Loc, Dim))))), Statements => New_List (Init_Loop), End_Label => Empty); Dim := Dim - 1; end loop; -- Generate the block which contains the counter variable and the -- initialization loops. -- declare -- Counter : Integer := 0; -- begin -- <init loop> -- end; Init_Block := Make_Block_Statement (Loc, Declarations => New_List ( Make_Object_Declaration (Loc, Defining_Identifier => Counter_Id, Object_Definition => New_Occurrence_Of (Standard_Integer, Loc), Expression => Make_Integer_Literal (Loc, 0))), Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Init_Loop))); -- Otherwise previous errors or a missing full view may prevent the -- proper freezing of the component type. If this is the case, there -- is no [Deep_]Initialize primitive to call. else Init_Block := Make_Null_Statement (Loc); end if; return New_List (Init_Block); end Build_Initialize_Statements; ----------------------- -- New_References_To -- ----------------------- function New_References_To (L : List_Id; Loc : Source_Ptr) return List_Id is Refs : constant List_Id := New_List; Id : Node_Id; begin Id := First (L); while Present (Id) loop Append_To (Refs, New_Occurrence_Of (Id, Loc)); Next (Id); end loop; return Refs; end New_References_To; -- Start of processing for Make_Deep_Array_Body begin case Prim is when Address_Case => return Make_Finalize_Address_Stmts (Typ); when Adjust_Case | Finalize_Case => return Build_Adjust_Or_Finalize_Statements (Typ); when Initialize_Case => return Build_Initialize_Statements (Typ); end case; end Make_Deep_Array_Body; -------------------- -- Make_Deep_Proc -- -------------------- function Make_Deep_Proc (Prim : Final_Primitives; Typ : Entity_Id; Stmts : List_Id) return Entity_Id is Loc : constant Source_Ptr := Sloc (Typ); Formals : List_Id; Proc_Id : Entity_Id; begin -- Create the object formal, generate: -- V : System.Address if Prim = Address_Case then Formals := New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_V), Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc))); -- Default case else -- V : in out Typ Formals := New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_V), In_Present => True, Out_Present => True, Parameter_Type => New_Occurrence_Of (Typ, Loc))); -- F : Boolean := True if Prim = Adjust_Case or else Prim = Finalize_Case then Append_To (Formals, Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_F), Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc), Expression => New_Occurrence_Of (Standard_True, Loc))); end if; end if; Proc_Id := Make_Defining_Identifier (Loc, Chars => Make_TSS_Name (Typ, Deep_Name_Of (Prim))); -- Generate: -- procedure Deep_Initialize / Adjust / Finalize (V : in out <typ>) is -- begin -- <stmts> -- exception -- Finalize and Adjust cases only -- raise Program_Error; -- end Deep_Initialize / Adjust / Finalize; -- or -- procedure Finalize_Address (V : System.Address) is -- begin -- <stmts> -- end Finalize_Address; Discard_Node ( Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Proc_Id, Parameter_Specifications => Formals), Declarations => Empty_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts))); -- If there are no calls to component initialization, indicate that -- the procedure is trivial, so prevent calls to it. if Is_Empty_List (Stmts) or else Nkind (First (Stmts)) = N_Null_Statement then Set_Is_Trivial_Subprogram (Proc_Id); end if; return Proc_Id; end Make_Deep_Proc; --------------------------- -- Make_Deep_Record_Body -- --------------------------- function Make_Deep_Record_Body (Prim : Final_Primitives; Typ : Entity_Id; Is_Local : Boolean := False) return List_Id is function Build_Adjust_Statements (Typ : Entity_Id) return List_Id; -- Build the statements necessary to adjust a record type. The type may -- have discriminants and contain variant parts. Generate: -- -- begin -- begin -- [Deep_]Adjust (V.Comp_1); -- exception -- when Id : others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; -- . . . -- begin -- [Deep_]Adjust (V.Comp_N); -- exception -- when Id : others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; -- -- begin -- Deep_Adjust (V._parent, False); -- If applicable -- exception -- when Id : others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; -- -- if F then -- begin -- Adjust (V); -- If applicable -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; -- end if; -- -- if Raised and then not Abort then -- Raise_From_Controlled_Operation (E); -- end if; -- end; function Build_Finalize_Statements (Typ : Entity_Id) return List_Id; -- Build the statements necessary to finalize a record type. The type -- may have discriminants and contain variant parts. Generate: -- -- declare -- Abort : constant Boolean := Triggered_By_Abort; -- <or> -- Abort : constant Boolean := False; -- no abort -- E : Exception_Occurrence; -- Raised : Boolean := False; -- -- begin -- if F then -- begin -- Finalize (V); -- If applicable -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; -- end if; -- -- case Variant_1 is -- when Value_1 => -- case State_Counter_N => -- If Is_Local is enabled -- when N => . -- goto LN; . -- ... . -- when 1 => . -- goto L1; . -- when others => . -- goto L0; . -- end case; . -- -- <<LN>> -- If Is_Local is enabled -- begin -- [Deep_]Finalize (V.Comp_N); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; -- . . . -- <<L1>> -- begin -- [Deep_]Finalize (V.Comp_1); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; -- <<L0>> -- end case; -- -- case State_Counter_1 => -- If Is_Local is enabled -- when M => . -- goto LM; . -- ... -- -- begin -- Deep_Finalize (V._parent, False); -- If applicable -- exception -- when Id : others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; -- -- if Raised and then not Abort then -- Raise_From_Controlled_Operation (E); -- end if; -- end; function Parent_Field_Type (Typ : Entity_Id) return Entity_Id; -- Given a derived tagged type Typ, traverse all components, find field -- _parent and return its type. procedure Preprocess_Components (Comps : Node_Id; Num_Comps : out Nat; Has_POC : out Boolean); -- Examine all components in component list Comps, count all controlled -- components and determine whether at least one of them is per-object -- constrained. Component _parent is always skipped. ----------------------------- -- Build_Adjust_Statements -- ----------------------------- function Build_Adjust_Statements (Typ : Entity_Id) return List_Id is Loc : constant Source_Ptr := Sloc (Typ); Typ_Def : constant Node_Id := Type_Definition (Parent (Typ)); Finalizer_Data : Finalization_Exception_Data; function Process_Component_List_For_Adjust (Comps : Node_Id) return List_Id; -- Build all necessary adjust statements for a single component list --------------------------------------- -- Process_Component_List_For_Adjust -- --------------------------------------- function Process_Component_List_For_Adjust (Comps : Node_Id) return List_Id is Stmts : constant List_Id := New_List; procedure Process_Component_For_Adjust (Decl : Node_Id); -- Process the declaration of a single controlled component ---------------------------------- -- Process_Component_For_Adjust -- ---------------------------------- procedure Process_Component_For_Adjust (Decl : Node_Id) is Id : constant Entity_Id := Defining_Identifier (Decl); Typ : constant Entity_Id := Etype (Id); Adj_Call : Node_Id; begin -- begin -- [Deep_]Adjust (V.Id); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, Get_Current_Excep.all.all); -- end if; -- end; Adj_Call := Make_Adjust_Call ( Obj_Ref => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_V), Selector_Name => Make_Identifier (Loc, Chars (Id))), Typ => Typ); -- Guard against a missing [Deep_]Adjust when the component -- type was not properly frozen. if Present (Adj_Call) then if Exceptions_OK then Adj_Call := Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Adj_Call), Exception_Handlers => New_List ( Build_Exception_Handler (Finalizer_Data)))); end if; Append_To (Stmts, Adj_Call); end if; end Process_Component_For_Adjust; -- Local variables Decl : Node_Id; Decl_Id : Entity_Id; Decl_Typ : Entity_Id; Has_POC : Boolean; Num_Comps : Nat; Var_Case : Node_Id; -- Start of processing for Process_Component_List_For_Adjust begin -- Perform an initial check, determine the number of controlled -- components in the current list and whether at least one of them -- is per-object constrained. Preprocess_Components (Comps, Num_Comps, Has_POC); -- The processing in this routine is done in the following order: -- 1) Regular components -- 2) Per-object constrained components -- 3) Variant parts if Num_Comps > 0 then -- Process all regular components in order of declarations Decl := First_Non_Pragma (Component_Items (Comps)); while Present (Decl) loop Decl_Id := Defining_Identifier (Decl); Decl_Typ := Etype (Decl_Id); -- Skip _parent as well as per-object constrained components if Chars (Decl_Id) /= Name_uParent and then Needs_Finalization (Decl_Typ) then if Has_Access_Constraint (Decl_Id) and then No (Expression (Decl)) then null; else Process_Component_For_Adjust (Decl); end if; end if; Next_Non_Pragma (Decl); end loop; -- Process all per-object constrained components in order of -- declarations. if Has_POC then Decl := First_Non_Pragma (Component_Items (Comps)); while Present (Decl) loop Decl_Id := Defining_Identifier (Decl); Decl_Typ := Etype (Decl_Id); -- Skip _parent if Chars (Decl_Id) /= Name_uParent and then Needs_Finalization (Decl_Typ) and then Has_Access_Constraint (Decl_Id) and then No (Expression (Decl)) then Process_Component_For_Adjust (Decl); end if; Next_Non_Pragma (Decl); end loop; end if; end if; -- Process all variants, if any Var_Case := Empty; if Present (Variant_Part (Comps)) then declare Var_Alts : constant List_Id := New_List; Var : Node_Id; begin Var := First_Non_Pragma (Variants (Variant_Part (Comps))); while Present (Var) loop -- Generate: -- when <discrete choices> => -- <adjust statements> Append_To (Var_Alts, Make_Case_Statement_Alternative (Loc, Discrete_Choices => New_Copy_List (Discrete_Choices (Var)), Statements => Process_Component_List_For_Adjust ( Component_List (Var)))); Next_Non_Pragma (Var); end loop; -- Generate: -- case V.<discriminant> is -- when <discrete choices 1> => -- <adjust statements 1> -- ... -- when <discrete choices N> => -- <adjust statements N> -- end case; Var_Case := Make_Case_Statement (Loc, Expression => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_V), Selector_Name => Make_Identifier (Loc, Chars => Chars (Name (Variant_Part (Comps))))), Alternatives => Var_Alts); end; end if; -- Add the variant case statement to the list of statements if Present (Var_Case) then Append_To (Stmts, Var_Case); end if; -- If the component list did not have any controlled components -- nor variants, return null. if Is_Empty_List (Stmts) then Append_To (Stmts, Make_Null_Statement (Loc)); end if; return Stmts; end Process_Component_List_For_Adjust; -- Local variables Bod_Stmts : List_Id := No_List; Finalizer_Decls : List_Id := No_List; Rec_Def : Node_Id; -- Start of processing for Build_Adjust_Statements begin Finalizer_Decls := New_List; Build_Object_Declarations (Finalizer_Data, Finalizer_Decls, Loc); if Nkind (Typ_Def) = N_Derived_Type_Definition then Rec_Def := Record_Extension_Part (Typ_Def); else Rec_Def := Typ_Def; end if; -- Create an adjust sequence for all record components if Present (Component_List (Rec_Def)) then Bod_Stmts := Process_Component_List_For_Adjust (Component_List (Rec_Def)); end if; -- A derived record type must adjust all inherited components. This -- action poses the following problem: -- procedure Deep_Adjust (Obj : in out Parent_Typ) is -- begin -- Adjust (Obj); -- ... -- procedure Deep_Adjust (Obj : in out Derived_Typ) is -- begin -- Deep_Adjust (Obj._parent); -- ... -- Adjust (Obj); -- ... -- Adjusting the derived type will invoke Adjust of the parent and -- then that of the derived type. This is undesirable because both -- routines may modify shared components. Only the Adjust of the -- derived type should be invoked. -- To prevent this double adjustment of shared components, -- Deep_Adjust uses a flag to control the invocation of Adjust: -- procedure Deep_Adjust -- (Obj : in out Some_Type; -- Flag : Boolean := True) -- is -- begin -- if Flag then -- Adjust (Obj); -- end if; -- ... -- When Deep_Adjust is invokes for field _parent, a value of False is -- provided for the flag: -- Deep_Adjust (Obj._parent, False); if Is_Tagged_Type (Typ) and then Is_Derived_Type (Typ) then declare Par_Typ : constant Entity_Id := Parent_Field_Type (Typ); Adj_Stmt : Node_Id; Call : Node_Id; begin if Needs_Finalization (Par_Typ) then Call := Make_Adjust_Call (Obj_Ref => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_V), Selector_Name => Make_Identifier (Loc, Name_uParent)), Typ => Par_Typ, Skip_Self => True); -- Generate: -- begin -- Deep_Adjust (V._parent, False); -- exception -- when Id : others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, -- Get_Current_Excep.all.all); -- end if; -- end; if Present (Call) then Adj_Stmt := Call; if Exceptions_OK then Adj_Stmt := Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Adj_Stmt), Exception_Handlers => New_List ( Build_Exception_Handler (Finalizer_Data)))); end if; Prepend_To (Bod_Stmts, Adj_Stmt); end if; end if; end; end if; -- Adjust the object. This action must be performed last after all -- components have been adjusted. if Is_Controlled (Typ) then declare Adj_Stmt : Node_Id; Proc : Entity_Id; begin Proc := Find_Optional_Prim_Op (Typ, Name_Adjust); -- Generate: -- if F then -- begin -- Adjust (V); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, -- Get_Current_Excep.all.all); -- end if; -- end; -- end if; if Present (Proc) then Adj_Stmt := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Proc, Loc), Parameter_Associations => New_List ( Make_Identifier (Loc, Name_V))); if Exceptions_OK then Adj_Stmt := Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Adj_Stmt), Exception_Handlers => New_List ( Build_Exception_Handler (Finalizer_Data)))); end if; Append_To (Bod_Stmts, Make_If_Statement (Loc, Condition => Make_Identifier (Loc, Name_F), Then_Statements => New_List (Adj_Stmt))); end if; end; end if; -- At this point either all adjustment statements have been generated -- or the type is not controlled. if Is_Empty_List (Bod_Stmts) then Append_To (Bod_Stmts, Make_Null_Statement (Loc)); return Bod_Stmts; -- Generate: -- declare -- Abort : constant Boolean := Triggered_By_Abort; -- <or> -- Abort : constant Boolean := False; -- no abort -- E : Exception_Occurrence; -- Raised : Boolean := False; -- begin -- <adjust statements> -- if Raised and then not Abort then -- Raise_From_Controlled_Operation (E); -- end if; -- end; else if Exceptions_OK then Append_To (Bod_Stmts, Build_Raise_Statement (Finalizer_Data)); end if; return New_List ( Make_Block_Statement (Loc, Declarations => Finalizer_Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Bod_Stmts))); end if; end Build_Adjust_Statements; ------------------------------- -- Build_Finalize_Statements -- ------------------------------- function Build_Finalize_Statements (Typ : Entity_Id) return List_Id is Loc : constant Source_Ptr := Sloc (Typ); Typ_Def : constant Node_Id := Type_Definition (Parent (Typ)); Counter : Int := 0; Finalizer_Data : Finalization_Exception_Data; function Process_Component_List_For_Finalize (Comps : Node_Id) return List_Id; -- Build all necessary finalization statements for a single component -- list. The statements may include a jump circuitry if flag Is_Local -- is enabled. ----------------------------------------- -- Process_Component_List_For_Finalize -- ----------------------------------------- function Process_Component_List_For_Finalize (Comps : Node_Id) return List_Id is procedure Process_Component_For_Finalize (Decl : Node_Id; Alts : List_Id; Decls : List_Id; Stmts : List_Id; Num_Comps : in out Nat); -- Process the declaration of a single controlled component. If -- flag Is_Local is enabled, create the corresponding label and -- jump circuitry. Alts is the list of case alternatives, Decls -- is the top level declaration list where labels are declared -- and Stmts is the list of finalization actions. Num_Comps -- denotes the current number of components needing finalization. ------------------------------------ -- Process_Component_For_Finalize -- ------------------------------------ procedure Process_Component_For_Finalize (Decl : Node_Id; Alts : List_Id; Decls : List_Id; Stmts : List_Id; Num_Comps : in out Nat) is Id : constant Entity_Id := Defining_Identifier (Decl); Typ : constant Entity_Id := Etype (Id); Fin_Call : Node_Id; begin if Is_Local then declare Label : Node_Id; Label_Id : Entity_Id; begin -- Generate: -- LN : label; Label_Id := Make_Identifier (Loc, Chars => New_External_Name ('L', Num_Comps)); Set_Entity (Label_Id, Make_Defining_Identifier (Loc, Chars (Label_Id))); Label := Make_Label (Loc, Label_Id); Append_To (Decls, Make_Implicit_Label_Declaration (Loc, Defining_Identifier => Entity (Label_Id), Label_Construct => Label)); -- Generate: -- when N => -- goto LN; Append_To (Alts, Make_Case_Statement_Alternative (Loc, Discrete_Choices => New_List ( Make_Integer_Literal (Loc, Num_Comps)), Statements => New_List ( Make_Goto_Statement (Loc, Name => New_Occurrence_Of (Entity (Label_Id), Loc))))); -- Generate: -- <<LN>> Append_To (Stmts, Label); -- Decrease the number of components to be processed. -- This action yields a new Label_Id in future calls. Num_Comps := Num_Comps - 1; end; end if; -- Generate: -- [Deep_]Finalize (V.Id); -- No_Exception_Propagation -- begin -- Exception handlers allowed -- [Deep_]Finalize (V.Id); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, -- Get_Current_Excep.all.all); -- end if; -- end; Fin_Call := Make_Final_Call (Obj_Ref => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_V), Selector_Name => Make_Identifier (Loc, Chars (Id))), Typ => Typ); -- Guard against a missing [Deep_]Finalize when the component -- type was not properly frozen. if Present (Fin_Call) then if Exceptions_OK then Fin_Call := Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Fin_Call), Exception_Handlers => New_List ( Build_Exception_Handler (Finalizer_Data)))); end if; Append_To (Stmts, Fin_Call); end if; end Process_Component_For_Finalize; -- Local variables Alts : List_Id; Counter_Id : Entity_Id := Empty; Decl : Node_Id; Decl_Id : Entity_Id; Decl_Typ : Entity_Id; Decls : List_Id; Has_POC : Boolean; Jump_Block : Node_Id; Label : Node_Id; Label_Id : Entity_Id; Num_Comps : Nat; Stmts : List_Id; Var_Case : Node_Id; -- Start of processing for Process_Component_List_For_Finalize begin -- Perform an initial check, look for controlled and per-object -- constrained components. Preprocess_Components (Comps, Num_Comps, Has_POC); -- Create a state counter to service the current component list. -- This step is performed before the variants are inspected in -- order to generate the same state counter names as those from -- Build_Initialize_Statements. if Num_Comps > 0 and then Is_Local then Counter := Counter + 1; Counter_Id := Make_Defining_Identifier (Loc, Chars => New_External_Name ('C', Counter)); end if; -- Process the component in the following order: -- 1) Variants -- 2) Per-object constrained components -- 3) Regular components -- Start with the variant parts Var_Case := Empty; if Present (Variant_Part (Comps)) then declare Var_Alts : constant List_Id := New_List; Var : Node_Id; begin Var := First_Non_Pragma (Variants (Variant_Part (Comps))); while Present (Var) loop -- Generate: -- when <discrete choices> => -- <finalize statements> Append_To (Var_Alts, Make_Case_Statement_Alternative (Loc, Discrete_Choices => New_Copy_List (Discrete_Choices (Var)), Statements => Process_Component_List_For_Finalize ( Component_List (Var)))); Next_Non_Pragma (Var); end loop; -- Generate: -- case V.<discriminant> is -- when <discrete choices 1> => -- <finalize statements 1> -- ... -- when <discrete choices N> => -- <finalize statements N> -- end case; Var_Case := Make_Case_Statement (Loc, Expression => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_V), Selector_Name => Make_Identifier (Loc, Chars => Chars (Name (Variant_Part (Comps))))), Alternatives => Var_Alts); end; end if; -- The current component list does not have a single controlled -- component, however it may contain variants. Return the case -- statement for the variants or nothing. if Num_Comps = 0 then if Present (Var_Case) then return New_List (Var_Case); else return New_List (Make_Null_Statement (Loc)); end if; end if; -- Prepare all lists Alts := New_List; Decls := New_List; Stmts := New_List; -- Process all per-object constrained components in reverse order if Has_POC then Decl := Last_Non_Pragma (Component_Items (Comps)); while Present (Decl) loop Decl_Id := Defining_Identifier (Decl); Decl_Typ := Etype (Decl_Id); -- Skip _parent if Chars (Decl_Id) /= Name_uParent and then Needs_Finalization (Decl_Typ) and then Has_Access_Constraint (Decl_Id) and then No (Expression (Decl)) then Process_Component_For_Finalize (Decl, Alts, Decls, Stmts, Num_Comps); end if; Prev_Non_Pragma (Decl); end loop; end if; -- Process the rest of the components in reverse order Decl := Last_Non_Pragma (Component_Items (Comps)); while Present (Decl) loop Decl_Id := Defining_Identifier (Decl); Decl_Typ := Etype (Decl_Id); -- Skip _parent if Chars (Decl_Id) /= Name_uParent and then Needs_Finalization (Decl_Typ) then -- Skip per-object constrained components since they were -- handled in the above step. if Has_Access_Constraint (Decl_Id) and then No (Expression (Decl)) then null; else Process_Component_For_Finalize (Decl, Alts, Decls, Stmts, Num_Comps); end if; end if; Prev_Non_Pragma (Decl); end loop; -- Generate: -- declare -- LN : label; -- If Is_Local is enabled -- ... . -- L0 : label; . -- begin . -- case CounterX is . -- when N => . -- goto LN; . -- ... . -- when 1 => . -- goto L1; . -- when others => . -- goto L0; . -- end case; . -- <<LN>> -- If Is_Local is enabled -- begin -- [Deep_]Finalize (V.CompY); -- exception -- when Id : others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, -- Get_Current_Excep.all.all); -- end if; -- end; -- ... -- <<L0>> -- If Is_Local is enabled -- end; if Is_Local then -- Add the declaration of default jump location L0, its -- corresponding alternative and its place in the statements. Label_Id := Make_Identifier (Loc, New_External_Name ('L', 0)); Set_Entity (Label_Id, Make_Defining_Identifier (Loc, Chars (Label_Id))); Label := Make_Label (Loc, Label_Id); Append_To (Decls, -- declaration Make_Implicit_Label_Declaration (Loc, Defining_Identifier => Entity (Label_Id), Label_Construct => Label)); Append_To (Alts, -- alternative Make_Case_Statement_Alternative (Loc, Discrete_Choices => New_List ( Make_Others_Choice (Loc)), Statements => New_List ( Make_Goto_Statement (Loc, Name => New_Occurrence_Of (Entity (Label_Id), Loc))))); Append_To (Stmts, Label); -- statement -- Create the jump block Prepend_To (Stmts, Make_Case_Statement (Loc, Expression => Make_Identifier (Loc, Chars (Counter_Id)), Alternatives => Alts)); end if; Jump_Block := Make_Block_Statement (Loc, Declarations => Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Stmts)); if Present (Var_Case) then return New_List (Var_Case, Jump_Block); else return New_List (Jump_Block); end if; end Process_Component_List_For_Finalize; -- Local variables Bod_Stmts : List_Id := No_List; Finalizer_Decls : List_Id := No_List; Rec_Def : Node_Id; -- Start of processing for Build_Finalize_Statements begin Finalizer_Decls := New_List; Build_Object_Declarations (Finalizer_Data, Finalizer_Decls, Loc); if Nkind (Typ_Def) = N_Derived_Type_Definition then Rec_Def := Record_Extension_Part (Typ_Def); else Rec_Def := Typ_Def; end if; -- Create a finalization sequence for all record components if Present (Component_List (Rec_Def)) then Bod_Stmts := Process_Component_List_For_Finalize (Component_List (Rec_Def)); end if; -- A derived record type must finalize all inherited components. This -- action poses the following problem: -- procedure Deep_Finalize (Obj : in out Parent_Typ) is -- begin -- Finalize (Obj); -- ... -- procedure Deep_Finalize (Obj : in out Derived_Typ) is -- begin -- Deep_Finalize (Obj._parent); -- ... -- Finalize (Obj); -- ... -- Finalizing the derived type will invoke Finalize of the parent and -- then that of the derived type. This is undesirable because both -- routines may modify shared components. Only the Finalize of the -- derived type should be invoked. -- To prevent this double adjustment of shared components, -- Deep_Finalize uses a flag to control the invocation of Finalize: -- procedure Deep_Finalize -- (Obj : in out Some_Type; -- Flag : Boolean := True) -- is -- begin -- if Flag then -- Finalize (Obj); -- end if; -- ... -- When Deep_Finalize is invoked for field _parent, a value of False -- is provided for the flag: -- Deep_Finalize (Obj._parent, False); if Is_Tagged_Type (Typ) and then Is_Derived_Type (Typ) then declare Par_Typ : constant Entity_Id := Parent_Field_Type (Typ); Call : Node_Id; Fin_Stmt : Node_Id; begin if Needs_Finalization (Par_Typ) then Call := Make_Final_Call (Obj_Ref => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_V), Selector_Name => Make_Identifier (Loc, Name_uParent)), Typ => Par_Typ, Skip_Self => True); -- Generate: -- begin -- Deep_Finalize (V._parent, False); -- exception -- when Id : others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, -- Get_Current_Excep.all.all); -- end if; -- end; if Present (Call) then Fin_Stmt := Call; if Exceptions_OK then Fin_Stmt := Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Fin_Stmt), Exception_Handlers => New_List ( Build_Exception_Handler (Finalizer_Data)))); end if; Append_To (Bod_Stmts, Fin_Stmt); end if; end if; end; end if; -- Finalize the object. This action must be performed first before -- all components have been finalized. if Is_Controlled (Typ) and then not Is_Local then declare Fin_Stmt : Node_Id; Proc : Entity_Id; begin Proc := Find_Optional_Prim_Op (Typ, Name_Finalize); -- Generate: -- if F then -- begin -- Finalize (V); -- exception -- when others => -- if not Raised then -- Raised := True; -- Save_Occurrence (E, -- Get_Current_Excep.all.all); -- end if; -- end; -- end if; if Present (Proc) then Fin_Stmt := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Proc, Loc), Parameter_Associations => New_List ( Make_Identifier (Loc, Name_V))); if Exceptions_OK then Fin_Stmt := Make_Block_Statement (Loc, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Fin_Stmt), Exception_Handlers => New_List ( Build_Exception_Handler (Finalizer_Data)))); end if; Prepend_To (Bod_Stmts, Make_If_Statement (Loc, Condition => Make_Identifier (Loc, Name_F), Then_Statements => New_List (Fin_Stmt))); end if; end; end if; -- At this point either all finalization statements have been -- generated or the type is not controlled. if No (Bod_Stmts) then return New_List (Make_Null_Statement (Loc)); -- Generate: -- declare -- Abort : constant Boolean := Triggered_By_Abort; -- <or> -- Abort : constant Boolean := False; -- no abort -- E : Exception_Occurrence; -- Raised : Boolean := False; -- begin -- <finalize statements> -- if Raised and then not Abort then -- Raise_From_Controlled_Operation (E); -- end if; -- end; else if Exceptions_OK then Append_To (Bod_Stmts, Build_Raise_Statement (Finalizer_Data)); end if; return New_List ( Make_Block_Statement (Loc, Declarations => Finalizer_Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Bod_Stmts))); end if; end Build_Finalize_Statements; ----------------------- -- Parent_Field_Type -- ----------------------- function Parent_Field_Type (Typ : Entity_Id) return Entity_Id is Field : Entity_Id; begin Field := First_Entity (Typ); while Present (Field) loop if Chars (Field) = Name_uParent then return Etype (Field); end if; Next_Entity (Field); end loop; -- A derived tagged type should always have a parent field raise Program_Error; end Parent_Field_Type; --------------------------- -- Preprocess_Components -- --------------------------- procedure Preprocess_Components (Comps : Node_Id; Num_Comps : out Nat; Has_POC : out Boolean) is Decl : Node_Id; Id : Entity_Id; Typ : Entity_Id; begin Num_Comps := 0; Has_POC := False; Decl := First_Non_Pragma (Component_Items (Comps)); while Present (Decl) loop Id := Defining_Identifier (Decl); Typ := Etype (Id); -- Skip field _parent if Chars (Id) /= Name_uParent and then Needs_Finalization (Typ) then Num_Comps := Num_Comps + 1; if Has_Access_Constraint (Id) and then No (Expression (Decl)) then Has_POC := True; end if; end if; Next_Non_Pragma (Decl); end loop; end Preprocess_Components; -- Start of processing for Make_Deep_Record_Body begin case Prim is when Address_Case => return Make_Finalize_Address_Stmts (Typ); when Adjust_Case => return Build_Adjust_Statements (Typ); when Finalize_Case => return Build_Finalize_Statements (Typ); when Initialize_Case => declare Loc : constant Source_Ptr := Sloc (Typ); begin if Is_Controlled (Typ) then return New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Find_Prim_Op (Typ, Name_Of (Prim)), Loc), Parameter_Associations => New_List ( Make_Identifier (Loc, Name_V)))); else return Empty_List; end if; end; end case; end Make_Deep_Record_Body; ---------------------- -- Make_Final_Call -- ---------------------- function Make_Final_Call (Obj_Ref : Node_Id; Typ : Entity_Id; Skip_Self : Boolean := False) return Node_Id is Loc : constant Source_Ptr := Sloc (Obj_Ref); Atyp : Entity_Id; Fin_Id : Entity_Id := Empty; Ref : Node_Id; Utyp : Entity_Id; begin Ref := Obj_Ref; -- Recover the proper type which contains [Deep_]Finalize if Is_Class_Wide_Type (Typ) then Utyp := Root_Type (Typ); Atyp := Utyp; elsif Is_Concurrent_Type (Typ) then Utyp := Corresponding_Record_Type (Typ); Atyp := Empty; Ref := Convert_Concurrent (Ref, Typ); elsif Is_Private_Type (Typ) and then Present (Underlying_Type (Typ)) and then Is_Concurrent_Type (Underlying_Type (Typ)) then Utyp := Corresponding_Record_Type (Underlying_Type (Typ)); Atyp := Typ; Ref := Convert_Concurrent (Ref, Underlying_Type (Typ)); else Utyp := Typ; Atyp := Typ; end if; Utyp := Underlying_Type (Base_Type (Utyp)); Set_Assignment_OK (Ref); -- Deal with untagged derivation of private views. If the parent type -- is a protected type, Deep_Finalize is found on the corresponding -- record of the ancestor. if Is_Untagged_Derivation (Typ) then if Is_Protected_Type (Typ) then Utyp := Corresponding_Record_Type (Root_Type (Base_Type (Typ))); else Utyp := Underlying_Type (Root_Type (Base_Type (Typ))); if Is_Protected_Type (Utyp) then Utyp := Corresponding_Record_Type (Utyp); end if; end if; Ref := Unchecked_Convert_To (Utyp, Ref); Set_Assignment_OK (Ref); end if; -- Deal with derived private types which do not inherit primitives from -- their parents. In this case, [Deep_]Finalize can be found in the full -- view of the parent type. if Present (Utyp) and then Is_Tagged_Type (Utyp) and then Is_Derived_Type (Utyp) and then Is_Empty_Elmt_List (Primitive_Operations (Utyp)) and then Is_Private_Type (Etype (Utyp)) and then Present (Full_View (Etype (Utyp))) then Utyp := Full_View (Etype (Utyp)); Ref := Unchecked_Convert_To (Utyp, Ref); Set_Assignment_OK (Ref); end if; -- When dealing with the completion of a private type, use the base type -- instead. if Present (Utyp) and then Utyp /= Base_Type (Utyp) then pragma Assert (Present (Atyp) and then Is_Private_Type (Atyp)); Utyp := Base_Type (Utyp); Ref := Unchecked_Convert_To (Utyp, Ref); Set_Assignment_OK (Ref); end if; -- The underlying type may not be present due to a missing full view. In -- this case freezing did not take place and there is no [Deep_]Finalize -- primitive to call. if No (Utyp) then return Empty; elsif Skip_Self then if Has_Controlled_Component (Utyp) then if Is_Tagged_Type (Utyp) then Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize); else Fin_Id := TSS (Utyp, TSS_Deep_Finalize); end if; end if; -- Class-wide types, interfaces and types with controlled components elsif Is_Class_Wide_Type (Typ) or else Is_Interface (Typ) or else Has_Controlled_Component (Utyp) then if Is_Tagged_Type (Utyp) then Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize); else Fin_Id := TSS (Utyp, TSS_Deep_Finalize); end if; -- Derivations from [Limited_]Controlled elsif Is_Controlled (Utyp) then if Has_Controlled_Component (Utyp) then Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize); else Fin_Id := Find_Optional_Prim_Op (Utyp, Name_Of (Finalize_Case)); end if; -- Tagged types elsif Is_Tagged_Type (Utyp) then Fin_Id := Find_Optional_Prim_Op (Utyp, TSS_Deep_Finalize); else raise Program_Error; end if; if Present (Fin_Id) then -- When finalizing a class-wide object, do not convert to the root -- type in order to produce a dispatching call. if Is_Class_Wide_Type (Typ) then null; -- Ensure that a finalization routine is at least decorated in order -- to inspect the object parameter. elsif Analyzed (Fin_Id) or else Ekind (Fin_Id) = E_Procedure then -- In certain cases, such as the creation of Stream_Read, the -- visible entity of the type is its full view. Since Stream_Read -- will have to create an object of type Typ, the local object -- will be finalzed by the scope finalizer generated later on. The -- object parameter of Deep_Finalize will always use the private -- view of the type. To avoid such a clash between a private and a -- full view, perform an unchecked conversion of the object -- reference to the private view. declare Formal_Typ : constant Entity_Id := Etype (First_Formal (Fin_Id)); begin if Is_Private_Type (Formal_Typ) and then Present (Full_View (Formal_Typ)) and then Full_View (Formal_Typ) = Utyp then Ref := Unchecked_Convert_To (Formal_Typ, Ref); end if; end; -- If the object is unanalyzed, set its expected type for use in -- Convert_View in case an additional conversion is needed. if No (Etype (Ref)) and then Nkind (Ref) /= N_Unchecked_Type_Conversion then Set_Etype (Ref, Typ); end if; Ref := Convert_View (Fin_Id, Ref); end if; return Make_Call (Loc, Proc_Id => Fin_Id, Param => Ref, Skip_Self => Skip_Self); else return Empty; end if; end Make_Final_Call; -------------------------------- -- Make_Finalize_Address_Body -- -------------------------------- procedure Make_Finalize_Address_Body (Typ : Entity_Id) is Is_Task : constant Boolean := Ekind (Typ) = E_Record_Type and then Is_Concurrent_Record_Type (Typ) and then Ekind (Corresponding_Concurrent_Type (Typ)) = E_Task_Type; Loc : constant Source_Ptr := Sloc (Typ); Proc_Id : Entity_Id; Stmts : List_Id; begin -- The corresponding records of task types are not controlled by design. -- For the sake of completeness, create an empty Finalize_Address to be -- used in task class-wide allocations. if Is_Task then null; -- Nothing to do if the type is not controlled or it already has a -- TSS entry for Finalize_Address. Skip class-wide subtypes which do not -- come from source. These are usually generated for completeness and -- do not need the Finalize_Address primitive. elsif not Needs_Finalization (Typ) or else Present (TSS (Typ, TSS_Finalize_Address)) or else (Is_Class_Wide_Type (Typ) and then Ekind (Root_Type (Typ)) = E_Record_Subtype and then not Comes_From_Source (Root_Type (Typ))) then return; end if; -- Do not generate Finalize_Address routine for CodePeer if CodePeer_Mode then return; end if; Proc_Id := Make_Defining_Identifier (Loc, Make_TSS_Name (Typ, TSS_Finalize_Address)); -- Generate: -- procedure <Typ>FD (V : System.Address) is -- begin -- null; -- for tasks -- declare -- for all other types -- type Pnn is access all Typ; -- for Pnn'Storage_Size use 0; -- begin -- [Deep_]Finalize (Pnn (V).all); -- end; -- end TypFD; if Is_Task then Stmts := New_List (Make_Null_Statement (Loc)); else Stmts := Make_Finalize_Address_Stmts (Typ); end if; Discard_Node ( Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Proc_Id, Parameter_Specifications => New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_V), Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc)))), Declarations => No_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts))); Set_TSS (Typ, Proc_Id); end Make_Finalize_Address_Body; --------------------------------- -- Make_Finalize_Address_Stmts -- --------------------------------- function Make_Finalize_Address_Stmts (Typ : Entity_Id) return List_Id is Loc : constant Source_Ptr := Sloc (Typ); Decls : List_Id; Desig_Typ : Entity_Id; Fin_Block : Node_Id; Fin_Call : Node_Id; Obj_Expr : Node_Id; Ptr_Typ : Entity_Id; begin if Is_Array_Type (Typ) then if Is_Constrained (First_Subtype (Typ)) then Desig_Typ := First_Subtype (Typ); else Desig_Typ := Base_Type (Typ); end if; -- Class-wide types of constrained root types elsif Is_Class_Wide_Type (Typ) and then Has_Discriminants (Root_Type (Typ)) and then not Is_Empty_Elmt_List (Discriminant_Constraint (Root_Type (Typ))) then declare Parent_Typ : Entity_Id; begin -- Climb the parent type chain looking for a non-constrained type Parent_Typ := Root_Type (Typ); while Parent_Typ /= Etype (Parent_Typ) and then Has_Discriminants (Parent_Typ) and then not Is_Empty_Elmt_List (Discriminant_Constraint (Parent_Typ)) loop Parent_Typ := Etype (Parent_Typ); end loop; -- Handle views created for tagged types with unknown -- discriminants. if Is_Underlying_Record_View (Parent_Typ) then Parent_Typ := Underlying_Record_View (Parent_Typ); end if; Desig_Typ := Class_Wide_Type (Underlying_Type (Parent_Typ)); end; -- General case else Desig_Typ := Typ; end if; -- Generate: -- type Ptr_Typ is access all Typ; -- for Ptr_Typ'Storage_Size use 0; Ptr_Typ := Make_Temporary (Loc, 'P'); Decls := New_List ( Make_Full_Type_Declaration (Loc, Defining_Identifier => Ptr_Typ, Type_Definition => Make_Access_To_Object_Definition (Loc, All_Present => True, Subtype_Indication => New_Occurrence_Of (Desig_Typ, Loc))), Make_Attribute_Definition_Clause (Loc, Name => New_Occurrence_Of (Ptr_Typ, Loc), Chars => Name_Storage_Size, Expression => Make_Integer_Literal (Loc, 0))); Obj_Expr := Make_Identifier (Loc, Name_V); -- Unconstrained arrays require special processing in order to retrieve -- the elements. To achieve this, we have to skip the dope vector which -- lays in front of the elements and then use a thin pointer to perform -- the address-to-access conversion. if Is_Array_Type (Typ) and then not Is_Constrained (First_Subtype (Typ)) then declare Dope_Id : Entity_Id; begin -- Ensure that Ptr_Typ a thin pointer, generate: -- for Ptr_Typ'Size use System.Address'Size; Append_To (Decls, Make_Attribute_Definition_Clause (Loc, Name => New_Occurrence_Of (Ptr_Typ, Loc), Chars => Name_Size, Expression => Make_Integer_Literal (Loc, System_Address_Size))); -- Generate: -- Dnn : constant Storage_Offset := -- Desig_Typ'Descriptor_Size / Storage_Unit; Dope_Id := Make_Temporary (Loc, 'D'); Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Dope_Id, Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Storage_Offset), Loc), Expression => Make_Op_Divide (Loc, Left_Opnd => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Desig_Typ, Loc), Attribute_Name => Name_Descriptor_Size), Right_Opnd => Make_Integer_Literal (Loc, System_Storage_Unit)))); -- Shift the address from the start of the dope vector to the -- start of the elements: -- -- V + Dnn -- -- Note that this is done through a wrapper routine since RTSfind -- cannot retrieve operations with string names of the form "+". Obj_Expr := Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Add_Offset_To_Address), Loc), Parameter_Associations => New_List ( Obj_Expr, New_Occurrence_Of (Dope_Id, Loc))); end; end if; Fin_Call := Make_Final_Call ( Obj_Ref => Make_Explicit_Dereference (Loc, Prefix => Unchecked_Convert_To (Ptr_Typ, Obj_Expr)), Typ => Desig_Typ); if Present (Fin_Call) then Fin_Block := Make_Block_Statement (Loc, Declarations => Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Fin_Call))); -- Otherwise previous errors or a missing full view may prevent the -- proper freezing of the designated type. If this is the case, there -- is no [Deep_]Finalize primitive to call. else Fin_Block := Make_Null_Statement (Loc); end if; return New_List (Fin_Block); end Make_Finalize_Address_Stmts; ------------------------------------- -- Make_Handler_For_Ctrl_Operation -- ------------------------------------- -- Generate: -- when E : others => -- Raise_From_Controlled_Operation (E); -- or: -- when others => -- raise Program_Error [finalize raised exception]; -- depending on whether Raise_From_Controlled_Operation is available function Make_Handler_For_Ctrl_Operation (Loc : Source_Ptr) return Node_Id is E_Occ : Entity_Id; -- Choice parameter (for the first case above) Raise_Node : Node_Id; -- Procedure call or raise statement begin -- Standard run-time: add choice parameter E and pass it to -- Raise_From_Controlled_Operation so that the original exception -- name and message can be recorded in the exception message for -- Program_Error. if RTE_Available (RE_Raise_From_Controlled_Operation) then E_Occ := Make_Defining_Identifier (Loc, Name_E); Raise_Node := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Raise_From_Controlled_Operation), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (E_Occ, Loc))); -- Restricted run-time: exception messages are not supported else E_Occ := Empty; Raise_Node := Make_Raise_Program_Error (Loc, Reason => PE_Finalize_Raised_Exception); end if; return Make_Implicit_Exception_Handler (Loc, Exception_Choices => New_List (Make_Others_Choice (Loc)), Choice_Parameter => E_Occ, Statements => New_List (Raise_Node)); end Make_Handler_For_Ctrl_Operation; -------------------- -- Make_Init_Call -- -------------------- function Make_Init_Call (Obj_Ref : Node_Id; Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Obj_Ref); Is_Conc : Boolean; Proc : Entity_Id; Ref : Node_Id; Utyp : Entity_Id; begin Ref := Obj_Ref; -- Deal with the type and object reference. Depending on the context, an -- object reference may need several conversions. if Is_Concurrent_Type (Typ) then Is_Conc := True; Utyp := Corresponding_Record_Type (Typ); Ref := Convert_Concurrent (Ref, Typ); elsif Is_Private_Type (Typ) and then Present (Full_View (Typ)) and then Is_Concurrent_Type (Underlying_Type (Typ)) then Is_Conc := True; Utyp := Corresponding_Record_Type (Underlying_Type (Typ)); Ref := Convert_Concurrent (Ref, Underlying_Type (Typ)); else Is_Conc := False; Utyp := Typ; end if; Utyp := Underlying_Type (Base_Type (Utyp)); Set_Assignment_OK (Ref); -- Deal with untagged derivation of private views if Is_Untagged_Derivation (Typ) and then not Is_Conc then Utyp := Underlying_Type (Root_Type (Base_Type (Typ))); Ref := Unchecked_Convert_To (Utyp, Ref); -- The following is to prevent problems with UC see 1.156 RH ??? Set_Assignment_OK (Ref); end if; -- If the underlying_type is a subtype, then we are dealing with the -- completion of a private type. We need to access the base type and -- generate a conversion to it. if Present (Utyp) and then Utyp /= Base_Type (Utyp) then pragma Assert (Is_Private_Type (Typ)); Utyp := Base_Type (Utyp); Ref := Unchecked_Convert_To (Utyp, Ref); end if; -- The underlying type may not be present due to a missing full view. -- In this case freezing did not take place and there is no suitable -- [Deep_]Initialize primitive to call. if No (Utyp) then return Empty; end if; -- Select the appropriate version of initialize if Has_Controlled_Component (Utyp) then Proc := TSS (Utyp, Deep_Name_Of (Initialize_Case)); else Proc := Find_Prim_Op (Utyp, Name_Of (Initialize_Case)); Check_Visibly_Controlled (Initialize_Case, Typ, Proc, Ref); end if; -- If initialization procedure for an array of controlled objects is -- trivial, do not generate a useless call to it. if (Is_Array_Type (Utyp) and then Is_Trivial_Subprogram (Proc)) or else (not Comes_From_Source (Proc) and then Present (Alias (Proc)) and then Is_Trivial_Subprogram (Alias (Proc))) then return Make_Null_Statement (Loc); end if; -- The object reference may need another conversion depending on the -- type of the formal and that of the actual. Ref := Convert_View (Proc, Ref); -- Generate: -- [Deep_]Initialize (Ref); return Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Proc, Loc), Parameter_Associations => New_List (Ref)); end Make_Init_Call; ------------------------------ -- Make_Local_Deep_Finalize -- ------------------------------ function Make_Local_Deep_Finalize (Typ : Entity_Id; Nam : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); Formals : List_Id; begin Formals := New_List ( -- V : in out Typ Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_V), In_Present => True, Out_Present => True, Parameter_Type => New_Occurrence_Of (Typ, Loc)), -- F : Boolean := True Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_F), Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc), Expression => New_Occurrence_Of (Standard_True, Loc))); -- Add the necessary number of counters to represent the initialization -- state of an object. return Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Nam, Parameter_Specifications => Formals), Declarations => No_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Make_Deep_Record_Body (Finalize_Case, Typ, True))); end Make_Local_Deep_Finalize; ------------------------------------ -- Make_Set_Finalize_Address_Call -- ------------------------------------ function Make_Set_Finalize_Address_Call (Loc : Source_Ptr; Ptr_Typ : Entity_Id) return Node_Id is -- It is possible for Ptr_Typ to be a partial view, if the access type -- is a full view declared in the private part of a nested package, and -- the finalization actions take place when completing analysis of the -- enclosing unit. For this reason use Underlying_Type twice below. Desig_Typ : constant Entity_Id := Available_View (Designated_Type (Underlying_Type (Ptr_Typ))); Fin_Addr : constant Entity_Id := Finalize_Address (Desig_Typ); Fin_Mas : constant Entity_Id := Finalization_Master (Underlying_Type (Ptr_Typ)); begin -- Both the finalization master and primitive Finalize_Address must be -- available. pragma Assert (Present (Fin_Addr) and Present (Fin_Mas)); -- Generate: -- Set_Finalize_Address -- (<Ptr_Typ>FM, <Desig_Typ>FD'Unrestricted_Access); return Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Set_Finalize_Address), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Fin_Mas, Loc), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Fin_Addr, Loc), Attribute_Name => Name_Unrestricted_Access))); end Make_Set_Finalize_Address_Call; -------------------------- -- Make_Transient_Block -- -------------------------- function Make_Transient_Block (Loc : Source_Ptr; Action : Node_Id; Par : Node_Id) return Node_Id is function Manages_Sec_Stack (Id : Entity_Id) return Boolean; -- Determine whether scoping entity Id manages the secondary stack function Within_Loop_Statement (N : Node_Id) return Boolean; -- Return True when N appears within a loop and no block is containing N ----------------------- -- Manages_Sec_Stack -- ----------------------- function Manages_Sec_Stack (Id : Entity_Id) return Boolean is begin case Ekind (Id) is -- An exception handler with a choice parameter utilizes a dummy -- block to provide a declarative region. Such a block should not -- be considered because it never manifests in the tree and can -- never release the secondary stack. when E_Block => return Uses_Sec_Stack (Id) and then not Is_Exception_Handler (Id); when E_Entry | E_Entry_Family | E_Function | E_Procedure => return Uses_Sec_Stack (Id); when others => return False; end case; end Manages_Sec_Stack; --------------------------- -- Within_Loop_Statement -- --------------------------- function Within_Loop_Statement (N : Node_Id) return Boolean is Par : Node_Id := Parent (N); begin while Nkind (Par) not in N_Handled_Sequence_Of_Statements | N_Loop_Statement | N_Package_Specification | N_Proper_Body loop pragma Assert (Present (Par)); Par := Parent (Par); end loop; return Nkind (Par) = N_Loop_Statement; end Within_Loop_Statement; -- Local variables Decls : constant List_Id := New_List; Instrs : constant List_Id := New_List (Action); Trans_Id : constant Entity_Id := Current_Scope; Block : Node_Id; Insert : Node_Id; Scop : Entity_Id; -- Start of processing for Make_Transient_Block begin -- Even though the transient block is tasked with managing the secondary -- stack, the block may forgo this functionality depending on how the -- secondary stack is managed by enclosing scopes. if Manages_Sec_Stack (Trans_Id) then -- Determine whether an enclosing scope already manages the secondary -- stack. Scop := Scope (Trans_Id); while Present (Scop) loop -- It should not be possible to reach Standard without hitting one -- of the other cases first unless Standard was manually pushed. if Scop = Standard_Standard then exit; -- The transient block is within a function which returns on the -- secondary stack. Take a conservative approach and assume that -- the value on the secondary stack is part of the result. Note -- that it is not possible to detect this dependency without flow -- analysis which the compiler does not have. Letting the object -- live longer than the transient block will not leak any memory -- because the caller will reclaim the total storage used by the -- function. elsif Ekind (Scop) = E_Function and then Sec_Stack_Needed_For_Return (Scop) then Set_Uses_Sec_Stack (Trans_Id, False); exit; -- The transient block must manage the secondary stack when the -- block appears within a loop in order to reclaim the memory at -- each iteration. elsif Ekind (Scop) = E_Loop then exit; -- Ditto when the block appears without a block that does not -- manage the secondary stack and is located within a loop. elsif Ekind (Scop) = E_Block and then not Manages_Sec_Stack (Scop) and then Present (Block_Node (Scop)) and then Within_Loop_Statement (Block_Node (Scop)) then exit; -- The transient block does not need to manage the secondary stack -- when there is an enclosing construct which already does that. -- This optimization saves on SS_Mark and SS_Release calls but may -- allow objects to live a little longer than required. -- The transient block must manage the secondary stack when switch -- -gnatd.s (strict management) is in effect. elsif Manages_Sec_Stack (Scop) and then not Debug_Flag_Dot_S then Set_Uses_Sec_Stack (Trans_Id, False); exit; -- Prevent the search from going too far because transient blocks -- are bounded by packages and subprogram scopes. elsif Ekind (Scop) in E_Entry | E_Entry_Family | E_Function | E_Package | E_Procedure | E_Subprogram_Body then exit; end if; Scop := Scope (Scop); end loop; end if; -- Create the transient block. Set the parent now since the block itself -- is not part of the tree. The current scope is the E_Block entity that -- has been pushed by Establish_Transient_Scope. pragma Assert (Ekind (Trans_Id) = E_Block); Block := Make_Block_Statement (Loc, Identifier => New_Occurrence_Of (Trans_Id, Loc), Declarations => Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Instrs), Has_Created_Identifier => True); Set_Parent (Block, Par); -- Insert actions stuck in the transient scopes as well as all freezing -- nodes needed by those actions. Do not insert cleanup actions here, -- they will be transferred to the newly created block. Insert_Actions_In_Scope_Around (Action, Clean => False, Manage_SS => False); Insert := Prev (Action); if Present (Insert) then Freeze_All (First_Entity (Trans_Id), Insert); end if; -- Transfer cleanup actions to the newly created block declare Cleanup_Actions : List_Id renames Scope_Stack.Table (Scope_Stack.Last). Actions_To_Be_Wrapped (Cleanup); begin Set_Cleanup_Actions (Block, Cleanup_Actions); Cleanup_Actions := No_List; end; -- When the transient scope was established, we pushed the entry for the -- transient scope onto the scope stack, so that the scope was active -- for the installation of finalizable entities etc. Now we must remove -- this entry, since we have constructed a proper block. Pop_Scope; return Block; end Make_Transient_Block; ------------------------ -- Node_To_Be_Wrapped -- ------------------------ function Node_To_Be_Wrapped return Node_Id is begin return Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped; end Node_To_Be_Wrapped; ---------------------------- -- Set_Node_To_Be_Wrapped -- ---------------------------- procedure Set_Node_To_Be_Wrapped (N : Node_Id) is begin Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped := N; end Set_Node_To_Be_Wrapped; ---------------------------- -- Store_Actions_In_Scope -- ---------------------------- procedure Store_Actions_In_Scope (AK : Scope_Action_Kind; L : List_Id) is SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last); Actions : List_Id renames SE.Actions_To_Be_Wrapped (AK); begin if No (Actions) then Actions := L; if Is_List_Member (SE.Node_To_Be_Wrapped) then Set_Parent (L, Parent (SE.Node_To_Be_Wrapped)); else Set_Parent (L, SE.Node_To_Be_Wrapped); end if; Analyze_List (L); elsif AK = Before then Insert_List_After_And_Analyze (Last (Actions), L); else Insert_List_Before_And_Analyze (First (Actions), L); end if; end Store_Actions_In_Scope; ---------------------------------- -- Store_After_Actions_In_Scope -- ---------------------------------- procedure Store_After_Actions_In_Scope (L : List_Id) is begin Store_Actions_In_Scope (After, L); end Store_After_Actions_In_Scope; ----------------------------------- -- Store_Before_Actions_In_Scope -- ----------------------------------- procedure Store_Before_Actions_In_Scope (L : List_Id) is begin Store_Actions_In_Scope (Before, L); end Store_Before_Actions_In_Scope; ----------------------------------- -- Store_Cleanup_Actions_In_Scope -- ----------------------------------- procedure Store_Cleanup_Actions_In_Scope (L : List_Id) is begin Store_Actions_In_Scope (Cleanup, L); end Store_Cleanup_Actions_In_Scope; ------------------ -- Unnest_Block -- ------------------ procedure Unnest_Block (Decl : Node_Id) is Loc : constant Source_Ptr := Sloc (Decl); Ent : Entity_Id; Local_Body : Node_Id; Local_Call : Node_Id; Local_Proc : Entity_Id; Local_Scop : Entity_Id; begin Local_Scop := Entity (Identifier (Decl)); Ent := First_Entity (Local_Scop); Local_Proc := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('P')); Local_Body := Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Local_Proc), Declarations => Declarations (Decl), Handled_Statement_Sequence => Handled_Statement_Sequence (Decl)); -- Handlers in the block may contain nested subprograms that require -- unnesting. Check_Unnesting_In_Handlers (Local_Body); Rewrite (Decl, Local_Body); Analyze (Decl); Set_Has_Nested_Subprogram (Local_Proc); Local_Call := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Local_Proc, Loc)); Insert_After (Decl, Local_Call); Analyze (Local_Call); -- The new subprogram has the same scope as the original block Set_Scope (Local_Proc, Scope (Local_Scop)); -- And the entity list of the new procedure is that of the block Set_First_Entity (Local_Proc, Ent); -- Reset the scopes of all the entities to the new procedure while Present (Ent) loop Set_Scope (Ent, Local_Proc); Next_Entity (Ent); end loop; end Unnest_Block; ------------------------- -- Unnest_If_Statement -- ------------------------- procedure Unnest_If_Statement (If_Stmt : Node_Id) is procedure Check_Stmts_For_Subp_Unnesting (Stmts : in out List_Id); -- A list of statements (that may be a list associated with a then, -- elsif, or else part of an if-statement) is traversed at the top -- level to determine whether it contains a subprogram body, and if so, -- the statements will be replaced with a new procedure body containing -- the statements followed by a call to the procedure. The individual -- statements may also be blocks, loops, or other if statements that -- themselves may require contain nested subprograms needing unnesting. procedure Check_Stmts_For_Subp_Unnesting (Stmts : in out List_Id) is Subp_Found : Boolean := False; begin if Is_Empty_List (Stmts) then return; end if; declare Stmt : Node_Id := First (Stmts); begin while Present (Stmt) loop if Nkind (Stmt) = N_Subprogram_Body then Subp_Found := True; exit; end if; Next (Stmt); end loop; end; -- The statements themselves may be blocks, loops, etc. that in turn -- contain nested subprograms requiring an unnesting transformation. -- We perform this traversal after looking for subprogram bodies, to -- avoid considering procedures created for one of those statements -- (such as a block rewritten as a procedure) as a nested subprogram -- of the statement list (which could result in an unneeded wrapper -- procedure). Check_Unnesting_In_Decls_Or_Stmts (Stmts); -- If there was a top-level subprogram body in the statement list, -- then perform an unnesting transformation on the list by replacing -- the statements with a wrapper procedure body containing the -- original statements followed by a call to that procedure. if Subp_Found then Unnest_Statement_List (Stmts); end if; end Check_Stmts_For_Subp_Unnesting; -- Local variables Then_Stmts : List_Id := Then_Statements (If_Stmt); Else_Stmts : List_Id := Else_Statements (If_Stmt); -- Start of processing for Unnest_If_Statement begin Check_Stmts_For_Subp_Unnesting (Then_Stmts); Set_Then_Statements (If_Stmt, Then_Stmts); if not Is_Empty_List (Elsif_Parts (If_Stmt)) then declare Elsif_Part : Node_Id := First (Elsif_Parts (If_Stmt)); Elsif_Stmts : List_Id; begin while Present (Elsif_Part) loop Elsif_Stmts := Then_Statements (Elsif_Part); Check_Stmts_For_Subp_Unnesting (Elsif_Stmts); Set_Then_Statements (Elsif_Part, Elsif_Stmts); Next (Elsif_Part); end loop; end; end if; Check_Stmts_For_Subp_Unnesting (Else_Stmts); Set_Else_Statements (If_Stmt, Else_Stmts); end Unnest_If_Statement; ----------------- -- Unnest_Loop -- ----------------- procedure Unnest_Loop (Loop_Stmt : Node_Id) is Loc : constant Source_Ptr := Sloc (Loop_Stmt); Ent : Entity_Id; Local_Body : Node_Id; Local_Call : Node_Id; Local_Proc : Entity_Id; Local_Scop : Entity_Id; Loop_Copy : constant Node_Id := Relocate_Node (Loop_Stmt); begin Local_Scop := Entity (Identifier (Loop_Stmt)); Ent := First_Entity (Local_Scop); Local_Proc := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('P')); Local_Body := Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Local_Proc), Declarations => Empty_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List (Loop_Copy))); Set_First_Real_Statement (Handled_Statement_Sequence (Local_Body), Loop_Copy); Rewrite (Loop_Stmt, Local_Body); Analyze (Loop_Stmt); Set_Has_Nested_Subprogram (Local_Proc); Local_Call := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Local_Proc, Loc)); Insert_After (Loop_Stmt, Local_Call); Analyze (Local_Call); -- New procedure has the same scope as the original loop, and the scope -- of the loop is the new procedure. Set_Scope (Local_Proc, Scope (Local_Scop)); Set_Scope (Local_Scop, Local_Proc); -- The entity list of the new procedure is that of the loop Set_First_Entity (Local_Proc, Ent); -- Note that the entities associated with the loop don't need to have -- their Scope fields reset, since they're still associated with the -- same loop entity that now belongs to the copied loop statement. end Unnest_Loop; --------------------------- -- Unnest_Statement_List -- --------------------------- procedure Unnest_Statement_List (Stmts : in out List_Id) is Loc : constant Source_Ptr := Sloc (First (Stmts)); Local_Body : Node_Id; Local_Call : Node_Id; Local_Proc : Entity_Id; New_Stmts : constant List_Id := Empty_List; begin Local_Proc := Make_Defining_Identifier (Loc, Chars => New_Internal_Name ('P')); Local_Body := Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Local_Proc), Declarations => Empty_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts)); Append_To (New_Stmts, Local_Body); Analyze (Local_Body); Set_Has_Nested_Subprogram (Local_Proc); Local_Call := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Local_Proc, Loc)); Append_To (New_Stmts, Local_Call); Analyze (Local_Call); -- Traverse the statements, and for any that are declarations or -- subprogram bodies that have entities, set the Scope of those -- entities to the new procedure's Entity_Id. declare Stmt : Node_Id := First (Stmts); begin while Present (Stmt) loop case Nkind (Stmt) is when N_Declaration | N_Renaming_Declaration => Set_Scope (Defining_Identifier (Stmt), Local_Proc); when N_Subprogram_Body => Set_Scope (Defining_Unit_Name (Specification (Stmt)), Local_Proc); when others => null; end case; Next (Stmt); end loop; end; Stmts := New_Stmts; end Unnest_Statement_List; -------------------------------- -- Wrap_Transient_Declaration -- -------------------------------- -- If a transient scope has been established during the processing of the -- Expression of an Object_Declaration, it is not possible to wrap the -- declaration into a transient block as usual case, otherwise the object -- would be itself declared in the wrong scope. Therefore, all entities (if -- any) defined in the transient block are moved to the proper enclosing -- scope. Furthermore, if they are controlled variables they are finalized -- right after the declaration. The finalization list of the transient -- scope is defined as a renaming of the enclosing one so during their -- initialization they will be attached to the proper finalization list. -- For instance, the following declaration : -- X : Typ := F (G (A), G (B)); -- (where G(A) and G(B) return controlled values, expanded as _v1 and _v2) -- is expanded into : -- X : Typ := [ complex Expression-Action ]; -- [Deep_]Finalize (_v1); -- [Deep_]Finalize (_v2); procedure Wrap_Transient_Declaration (N : Node_Id) is Curr_S : Entity_Id; Encl_S : Entity_Id; begin Curr_S := Current_Scope; Encl_S := Scope (Curr_S); -- Insert all actions including cleanup generated while analyzing or -- expanding the transient context back into the tree. Manage the -- secondary stack when the object declaration appears in a library -- level package [body]. Insert_Actions_In_Scope_Around (N => N, Clean => True, Manage_SS => Uses_Sec_Stack (Curr_S) and then Nkind (N) = N_Object_Declaration and then Ekind (Encl_S) in E_Package | E_Package_Body and then Is_Library_Level_Entity (Encl_S)); Pop_Scope; -- Relocate local entities declared within the transient scope to the -- enclosing scope. This action sets their Is_Public flag accordingly. Transfer_Entities (Curr_S, Encl_S); -- Mark the enclosing dynamic scope to ensure that the secondary stack -- is properly released upon exiting the said scope. if Uses_Sec_Stack (Curr_S) then Curr_S := Enclosing_Dynamic_Scope (Curr_S); -- Do not mark a function that returns on the secondary stack as the -- reclamation is done by the caller. if Ekind (Curr_S) = E_Function and then Requires_Transient_Scope (Etype (Curr_S)) then null; -- Otherwise mark the enclosing dynamic scope else Set_Uses_Sec_Stack (Curr_S); Check_Restriction (No_Secondary_Stack, N); end if; end if; end Wrap_Transient_Declaration; ------------------------------- -- Wrap_Transient_Expression -- ------------------------------- procedure Wrap_Transient_Expression (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Expr : Node_Id := Relocate_Node (N); Temp : constant Entity_Id := Make_Temporary (Loc, 'E', N); Typ : constant Entity_Id := Etype (N); begin -- Generate: -- Temp : Typ; -- declare -- M : constant Mark_Id := SS_Mark; -- procedure Finalizer is ... (See Build_Finalizer) -- begin -- Temp := <Expr>; -- general case -- Temp := (if <Expr> then True else False); -- boolean case -- at end -- Finalizer; -- end; -- A special case is made for Boolean expressions so that the back end -- knows to generate a conditional branch instruction, if running with -- -fpreserve-control-flow. This ensures that a control-flow change -- signaling the decision outcome occurs before the cleanup actions. if Opt.Suppress_Control_Flow_Optimizations and then Is_Boolean_Type (Typ) then Expr := Make_If_Expression (Loc, Expressions => New_List ( Expr, New_Occurrence_Of (Standard_True, Loc), New_Occurrence_Of (Standard_False, Loc))); end if; Insert_Actions (N, New_List ( Make_Object_Declaration (Loc, Defining_Identifier => Temp, Object_Definition => New_Occurrence_Of (Typ, Loc)), Make_Transient_Block (Loc, Action => Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Temp, Loc), Expression => Expr), Par => Parent (N)))); Rewrite (N, New_Occurrence_Of (Temp, Loc)); Analyze_And_Resolve (N, Typ); end Wrap_Transient_Expression; ------------------------------ -- Wrap_Transient_Statement -- ------------------------------ procedure Wrap_Transient_Statement (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); New_Stmt : constant Node_Id := Relocate_Node (N); begin -- Generate: -- declare -- M : constant Mark_Id := SS_Mark; -- procedure Finalizer is ... (See Build_Finalizer) -- -- begin -- <New_Stmt>; -- -- at end -- Finalizer; -- end; Rewrite (N, Make_Transient_Block (Loc, Action => New_Stmt, Par => Parent (N))); -- With the scope stack back to normal, we can call analyze on the -- resulting block. At this point, the transient scope is being -- treated like a perfectly normal scope, so there is nothing -- special about it. -- Note: Wrap_Transient_Statement is called with the node already -- analyzed (i.e. Analyzed (N) is True). This is important, since -- otherwise we would get a recursive processing of the node when -- we do this Analyze call. Analyze (N); end Wrap_Transient_Statement; end Exp_Ch7;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>AWA.Jobs</b> plugin defines a batch job framework for modules to perform and execute -- long running and deferred actions. The `Jobs` plugin is intended to help web application -- designers in implementing end to end asynchronous operation. A client schedules a job -- and does not block nor wait for the immediate completion. Instead, the client asks -- periodically or uses other mechanisms to check for the job completion. -- -- === Writing a job === -- A new job type is created by implementing the `Execute` operation of the abstract -- `Job_Type` tagged record. -- -- type Resize_Job is new AWA.Jobs.Job_Type with ...; -- -- The `Execute` procedure must be implemented. It should use the `Get_Parameter` functions -- to retrieve the job parameters and perform the work. While the job is being executed, -- it can save result by using the `Set_Result` operations, save messages by using the -- `Set_Message` operations and report the progress by using `Set_Progress`. -- It may report the job status by using `Set_Status`. -- -- procedure Execute (Job : in out Resize_Job) is -- begin -- Job.Set_Result ("done", "ok"); -- end Execute; -- -- === Registering a job === -- The <b>AWA.Jobs</b> plugin must be able to create the job instance when it is going to -- be executed. For this, a registration package must be instantiated: -- -- package Resize_Def is new AWA.Jobs.Definition (Resize_Job); -- -- and the job definition must be added: -- -- AWA.Jobs.Modules.Register (Resize_Def.Create'Access); -- -- === Scheduling a job === -- To schedule a job, declare an instance of the job to execute and set the job specific -- parameters. The job parameters will be saved in the database. As soon as parameters -- are defined, call the `Schedule` procedure to schedule the job in the job queue and -- obtain a job identifier. -- -- Resize : Resize_Job; -- ... -- Resize.Set_Parameter ("file", "image.png"); -- Resize.Set_Parameter ("width", "32"); -- Resize.Set_Parameter ("height, "32"); -- Resize.Schedule; -- -- === Checking for job completion === -- -- -- @include awa-jobs-modules.ads -- @include awa-jobs-services.ads -- -- @include jobs.xml -- -- == Data Model == -- [images/awa_jobs_model.png] -- package AWA.Jobs is end AWA.Jobs;
package body Data_Type is function "<" (L, R : Record_T) return Boolean is begin return False; end "<"; function Image (Element : Record_T) return String is begin return ""; end Image; end Data_Type;
separate(Practica2) procedure Producto(X:in integer;Y:out Integer) is begin--El factorial en los bucles lo calcula bien pero si entran numeros mayores que el 12 --puede haber un fallo de overflow y:=1; if X > 0 then for i in 1..x loop y:=y*I;--Aqui realizo elproducto de los positivos end loop; else if x < 0 then for i in reverse x..-1 loop y:=Y*I;--Aqui realizo el producto del los negativos end loop; else y:=0;-- si no entra en niguno de estos casos entoces es que es cero end if; end if; end;
-- { dg-do compile } -- { dg-options "-O2 -gnatws" } procedure Opt16 is generic type T (<>) is private; V, V1 : T; with function F1 (X : T) return T; package GP is R : Boolean := F1 (V) = V1; end GP; type AB is array (Boolean range <>) of Boolean; begin for I1 in Boolean loop for I2 in Boolean loop declare B1 : Boolean := I1; B2 : Boolean := I2; AB1 : AB (Boolean) := (I1, I2); T : AB (B1 .. B2) := (B1 .. B2 => True); F : AB (B1 .. B2) := (B1 .. B2 => False); package P is new GP (AB, AB1, NOT AB1, "NOT"); begin null; end; end loop; end loop; end;
----------------------------------------------------------------------- -- EL.Contexts.TLS -- EL context and Thread Local Support -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body EL.Contexts.TLS is Context : EL.Contexts.ELContext_Access := null; pragma Thread_Local_Storage (Context); -- ------------------------------ -- Get the current EL context associated with the current thread. -- ------------------------------ function Current return EL.Contexts.ELContext_Access is begin return Context; end Current; -- ------------------------------ -- Initialize and setup a new per-thread EL context. -- ------------------------------ overriding procedure Initialize (Obj : in out TLS_Context) is begin Obj.Previous := Context; Context := Obj'Unchecked_Access; EL.Contexts.Default.Default_Context (Obj).Initialize; end Initialize; -- ------------------------------ -- Restore the previouse per-thread EL context. -- ------------------------------ overriding procedure Finalize (Obj : in out TLS_Context) is begin Context := Obj.Previous; EL.Contexts.Default.Default_Context (Obj).Finalize; end Finalize; end EL.Contexts.TLS;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- A S P E C T S -- -- -- -- B o d y -- -- -- -- Copyright (C) 2010, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Nlists; use Nlists; with Sinfo; use Sinfo; with Snames; use Snames; with Tree_IO; use Tree_IO; with GNAT.HTable; use GNAT.HTable; package body Aspects is ------------------------------------------ -- Hash Table for Aspect Specifications -- ------------------------------------------ type AS_Hash_Range is range 0 .. 510; -- Size of hash table headers function AS_Hash (F : Node_Id) return AS_Hash_Range; -- Hash function for hash table function AS_Hash (F : Node_Id) return AS_Hash_Range is begin return AS_Hash_Range (F mod 511); end AS_Hash; package Aspect_Specifications_Hash_Table is new GNAT.HTable.Simple_HTable (Header_Num => AS_Hash_Range, Element => List_Id, No_Element => No_List, Key => Node_Id, Hash => AS_Hash, Equal => "="); ----------------------------------------- -- Table Linking Names and Aspect_Id's -- ----------------------------------------- type Aspect_Entry is record Nam : Name_Id; Asp : Aspect_Id; end record; Aspect_Names : constant array (Integer range <>) of Aspect_Entry := ( (Name_Ada_2005, Aspect_Ada_2005), (Name_Ada_2012, Aspect_Ada_2012), (Name_Address, Aspect_Address), (Name_Alignment, Aspect_Alignment), (Name_Atomic, Aspect_Atomic), (Name_Atomic_Components, Aspect_Atomic_Components), (Name_Bit_Order, Aspect_Bit_Order), (Name_Component_Size, Aspect_Component_Size), (Name_Discard_Names, Aspect_Discard_Names), (Name_External_Tag, Aspect_External_Tag), (Name_Favor_Top_Level, Aspect_Favor_Top_Level), (Name_Inline, Aspect_Inline), (Name_Inline_Always, Aspect_Inline_Always), (Name_Input, Aspect_Input), (Name_Invariant, Aspect_Invariant), (Name_Machine_Radix, Aspect_Machine_Radix), (Name_Object_Size, Aspect_Object_Size), (Name_Output, Aspect_Output), (Name_Pack, Aspect_Pack), (Name_Persistent_BSS, Aspect_Persistent_BSS), (Name_Post, Aspect_Post), (Name_Pre, Aspect_Pre), (Name_Predicate, Aspect_Predicate), (Name_Preelaborable_Initialization, Aspect_Preelaborable_Initialization), (Name_Pure_Function, Aspect_Pure_Function), (Name_Read, Aspect_Read), (Name_Shared, Aspect_Shared), (Name_Size, Aspect_Size), (Name_Storage_Pool, Aspect_Storage_Pool), (Name_Storage_Size, Aspect_Storage_Size), (Name_Stream_Size, Aspect_Stream_Size), (Name_Suppress, Aspect_Suppress), (Name_Suppress_Debug_Info, Aspect_Suppress_Debug_Info), (Name_Unchecked_Union, Aspect_Unchecked_Union), (Name_Universal_Aliasing, Aspect_Universal_Aliasing), (Name_Unmodified, Aspect_Unmodified), (Name_Unreferenced, Aspect_Unreferenced), (Name_Unreferenced_Objects, Aspect_Unreferenced_Objects), (Name_Unsuppress, Aspect_Unsuppress), (Name_Value_Size, Aspect_Value_Size), (Name_Volatile, Aspect_Volatile), (Name_Volatile_Components, Aspect_Volatile_Components), (Name_Warnings, Aspect_Warnings), (Name_Write, Aspect_Write)); ------------------------------------- -- Hash Table for Aspect Id Values -- ------------------------------------- type AI_Hash_Range is range 0 .. 112; -- Size of hash table headers function AI_Hash (F : Name_Id) return AI_Hash_Range; -- Hash function for hash table function AI_Hash (F : Name_Id) return AI_Hash_Range is begin return AI_Hash_Range (F mod 113); end AI_Hash; package Aspect_Id_Hash_Table is new GNAT.HTable.Simple_HTable (Header_Num => AI_Hash_Range, Element => Aspect_Id, No_Element => No_Aspect, Key => Name_Id, Hash => AI_Hash, Equal => "="); ------------------- -- Get_Aspect_Id -- ------------------- function Get_Aspect_Id (Name : Name_Id) return Aspect_Id is begin return Aspect_Id_Hash_Table.Get (Name); end Get_Aspect_Id; --------------------------- -- Aspect_Specifications -- --------------------------- function Aspect_Specifications (N : Node_Id) return List_Id is begin if Has_Aspects (N) then return Aspect_Specifications_Hash_Table.Get (N); else return No_List; end if; end Aspect_Specifications; ------------------ -- Move_Aspects -- ------------------ procedure Move_Aspects (From : Node_Id; To : Node_Id) is pragma Assert (not Has_Aspects (To)); begin if Has_Aspects (From) then Set_Aspect_Specifications (To, Aspect_Specifications (From)); Aspect_Specifications_Hash_Table.Remove (From); Set_Has_Aspects (From, False); end if; end Move_Aspects; ----------------------------------- -- Permits_Aspect_Specifications -- ----------------------------------- Has_Aspect_Specifications_Flag : constant array (Node_Kind) of Boolean := (N_Abstract_Subprogram_Declaration => True, N_Component_Declaration => True, N_Entry_Declaration => True, N_Exception_Declaration => True, N_Formal_Abstract_Subprogram_Declaration => True, N_Formal_Concrete_Subprogram_Declaration => True, N_Formal_Object_Declaration => True, N_Formal_Package_Declaration => True, N_Formal_Type_Declaration => True, N_Full_Type_Declaration => True, N_Function_Instantiation => True, N_Generic_Package_Declaration => True, N_Generic_Subprogram_Declaration => True, N_Object_Declaration => True, N_Package_Declaration => True, N_Package_Instantiation => True, N_Private_Extension_Declaration => True, N_Private_Type_Declaration => True, N_Procedure_Instantiation => True, N_Protected_Type_Declaration => True, N_Single_Protected_Declaration => True, N_Single_Task_Declaration => True, N_Subprogram_Declaration => True, N_Subtype_Declaration => True, N_Task_Type_Declaration => True, others => False); function Permits_Aspect_Specifications (N : Node_Id) return Boolean is begin return Has_Aspect_Specifications_Flag (Nkind (N)); end Permits_Aspect_Specifications; ------------------------------- -- Set_Aspect_Specifications -- ------------------------------- procedure Set_Aspect_Specifications (N : Node_Id; L : List_Id) is begin pragma Assert (Permits_Aspect_Specifications (N)); pragma Assert (not Has_Aspects (N)); pragma Assert (L /= No_List); Set_Has_Aspects (N); Set_Parent (L, N); Aspect_Specifications_Hash_Table.Set (N, L); end Set_Aspect_Specifications; --------------- -- Tree_Read -- --------------- procedure Tree_Read is Node : Node_Id; List : List_Id; begin loop Tree_Read_Int (Int (Node)); Tree_Read_Int (Int (List)); exit when List = No_List; Set_Aspect_Specifications (Node, List); end loop; end Tree_Read; ---------------- -- Tree_Write -- ---------------- procedure Tree_Write is -- Node : Node_Id := Empty; -- List : List_Id; begin -- Aspect_Specifications_Hash_Table.Get_First (Node, List); -- loop -- Tree_Write_Int (Int (Node)); -- Tree_Write_Int (Int (List)); -- exit when List = No_List; -- Aspect_Specifications_Hash_Table.Get_Next (Node, List); -- end loop; raise Program_Error with "Tree_Write was commended due to compilation errors."; end Tree_Write; -- Package initialization sets up Aspect Id hash table begin for J in Aspect_Names'Range loop Aspect_Id_Hash_Table.Set (Aspect_Names (J).Nam, Aspect_Names (J).Asp); end loop; end Aspects;
package body impact.d3.collision.Algorithm.activating is procedure define (Self : in out Item; ci : in AlgorithmConstructionInfo; colObj0, colObj1 : access impact.d3.Object.item'Class) is pragma Unreferenced (colObj0, colObj1); use impact.d3.collision.Algorithm; begin define (Self, ci); end define; overriding procedure destruct (Self : in out Item) is begin null; -- m_colObj0->activate(); -- m_colObj1->activate(); end destruct; overriding function calculateTimeOfImpact (Self : in Item; body0, body1 : access impact.d3.Object.item'Class; dispatchInfo : in impact.d3.Dispatcher.DispatcherInfo; resultOut : access impact.d3.collision.manifold_Result.item) return math.Real is begin raise Program_Error; -- tbd: return 0.0; end calculateTimeOfImpact; end impact.d3.collision.Algorithm.activating;
---------------------------------------------------------------------- -- -- Screen Input Output Package -- -- written by -- -- Edmond Schonberg -- David Shields -- -- Ada Project -- Courant Institute -- New York University -- 251 Mercer Street -- New York, New York 10012 -- ----------------------------------------------------------------------- with text_io; use text_io; with semaphore; use semaphore; package screen_io is -- These screen input output primitives assume that the terminal can -- function as a VT100 or, for the IBM PC, has ANSI.SYS installed -- as a screen driver. subtype row is integer range 1..25; subtype column is integer range 1..80; procedure clear ; procedure PUTS(s: string; r: row; c: column); procedure PUTSN(s: string; n: integer; r: row; c: column); procedure PUTC(ch: character; r: row; c: column); procedure PUTCB(ch: character; r: row; c: column); procedure fill_screen(c: character) ; end screen_io; with integer_text_io; use integer_text_io; package body screen_io is protect: ACCESS_BINARY_SEMAPHORE := new BINARY_SEMAPHORE; procedure clear is begin put(ASCII.ESC ); put("[2J") ; end ; procedure PUT_INT(R: integer) is digs: constant string := "0123456789"; d : integer := R; begin if d>=100 then put(digs(d/100 + 1)); d := d mod 100; end if; -- always write at least two digits (if setting screen position). put(digs(d/10 + 1)); put(digs(d mod 10 + 1)); end; procedure SET_CURSOR(R: row := 1; C:column := 1) is -- uses escape sequence ESC [ row ; column H begin put(ASCII.ESC); put('['); put_int(R); put( ';'); put_int(C); put('H'); end SET_CURSOR; procedure PUTS(S: string; R: row; C: column) is index: integer; begin PROTECT.P; SET_CURSOR(R, C); put_line(S); PROTECT.V; end; procedure PUTSN(S: string; N: integer; R: row; C: column) is index: integer; -- put string and integer values begin PROTECT.P; SET_CURSOR(R, C); put(S); put_int(N); put_line(" "); PROTECT.V; end; procedure PUTCB(CH: character ; R: row; C: column) is -- put "emphasized" character index: integer; begin PROTECT.P; SET_CURSOR(R, C); put(ASCII.ESC); put("[5m"); -- turn on blinking put(CH); put(ASCII.ESC); put_line("[0m"); -- turn off blinking PROTECT.V; end; procedure PUTC(Ch: character; R: row; C: column) is begin PROTECT.P; SET_CURSOR(R, C); put(Ch); new_line; PROTECT.V; end PUTC; procedure fill_screen(c: character) is line : string(1..80) := (1..80 => c) ; begin for i in 2..23 loop SET_CURSOR(i, 1); put_line(line) ; end loop; end fill_screen; end screen_io;
package body Encodings.Line_Endings.Generic_Add_CR is procedure Convert( This: in out Coder; Source: in String_Type; Source_Last: out Natural; Target: out String_Type; Target_Last: out Natural ) is C: Character_Type; begin Source_Last := Source'First - 1; Target_Last := Target'First - 1; if This.State = Need_LF then if Target_Last >= Target'Last then -- Wonder of anyone would supply zero-size string but precaution is must return; end if; Target_Last := Target_Last + 1; Target(Target_Last) := Line_Feed; This.State := Initial; end if; while Source_Last < Source'Last and Target_Last < Target'Last loop Source_Last := Source_Last + 1; C := Source(Source_Last); if C = Carriage_Return then This.State := Have_CR; elsif C = Line_Feed then if This.State /= Have_CR then Target_Last := Target_Last + 1; Target(Target_Last) := Carriage_Return; if(Target_Last >= Target'Last) then -- Buffer ends while outputtting CR-LF This.State := Need_LF; return; end if; This.State := Initial; end if; end if; Target_Last := Target_Last + 1; Target(Target_Last) := C; end loop; end Convert; end Encodings.Line_Endings.Generic_Add_CR;
-- { dg-do run } procedure self_aggregate_with_zeros is type Sensor is record Value : Natural; A, B, C, D, E, F, G, H, I, J, K, L, M : Natural; end record; Pressure : Sensor; begin Pressure.Value := 256; Pressure := (Pressure.Value, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); if Pressure.Value /= 256 then raise Program_Error; end if; end;
with parse_tokens, parse_goto, parse_shift_reduce, text_io, scanner; with nfa, ccl, misc, misc_defs, sym, ecs, aflex_scanner; with tstring, int_io, main_body, text_io, external_file_manager; use aflex_scanner, external_file_manager; package body parser is -- build_eof_action - build the "<<EOF>>" action for the active start -- conditions use text_io, misc_defs; procedure build_eof_action is begin text_io.put( temp_action_file, "when " ); for i in 1..actvp loop if ( sceof(actvsc(i)) ) then text_io.put( Standard_Error, "multiple <<EOF>> rules for start condition "); tstring.put( Standard_Error, scname(actvsc(i))); main_body.aflexend(1); else sceof(actvsc(i)) := true; text_io.put( temp_action_file, "YY_END_OF_BUFFER +" ); tstring.put( temp_action_file, scname(actvsc(i)) ); text_io.put_line( temp_action_file, " + 1 " ); if (i /= actvp) then text_io.put_line( temp_action_file, " |" ); else text_io.put_line( temp_action_file, " =>" ); end if; end if; end loop; misc.line_directive_out( temp_action_file ); end build_eof_action; -- yyerror - eat up an error message from the parser -- -- synopsis -- char msg[]; -- yyerror( msg ); procedure yyerror( msg : string ) is begin null; end yyerror; use Parse_Goto, Parse_Shift_Reduce, Text_IO, misc_defs, tstring; procedure YYParse is -- Rename User Defined Packages to Internal Names. package yy_goto_tables renames Parse_Goto; package yy_shift_reduce_tables renames Parse_Shift_Reduce; package yy_tokens renames Parse_Tokens; use yy_tokens, yy_goto_tables, yy_shift_reduce_tables; procedure yyerrok; procedure yyclearin; package yy is -- the size of the value and state stacks stack_size : constant Natural := 300; -- subtype rule is natural; subtype parse_state is natural; -- subtype nonterminal is integer; -- encryption constants default : constant := -1; first_shift_entry : constant := 0; accept_code : constant := -1001; error_code : constant := -1000; -- stack data used by the parser tos : natural := 0; value_stack : array(0..stack_size) of yy_tokens.yystype; state_stack : array(0..stack_size) of parse_state; -- current input symbol and action the parser is on action : integer; rule_id : rule; input_symbol : yy_tokens.token; -- error recovery flag error_flag : natural := 0; -- indicates 3 - (number of valid shifts after an error occurs) look_ahead : boolean := true; index : integer; -- Is Debugging option on or off DEBUG : constant boolean := FALSE; end yy; function goto_state (state : yy.parse_state; sym : nonterminal) return yy.parse_state; function parse_action (state : yy.parse_state; t : yy_tokens.token) return integer; pragma inline(goto_state, parse_action); function goto_state(state : yy.parse_state; sym : nonterminal) return yy.parse_state is index : integer; begin index := goto_offset(state); while integer(goto_matrix(index).nonterm) /= sym loop index := index + 1; end loop; return integer(goto_matrix(index).newstate); end goto_state; function parse_action(state : yy.parse_state; t : yy_tokens.token) return integer is index : integer; tok_pos : integer; default : constant integer := -1; begin tok_pos := yy_tokens.token'pos(t); index := shift_reduce_offset(state); while integer(shift_reduce_matrix(index).t) /= tok_pos and then integer(shift_reduce_matrix(index).t) /= default loop index := index + 1; end loop; return integer(shift_reduce_matrix(index).act); end parse_action; -- error recovery stuff procedure handle_error is temp_action : integer; begin if yy.error_flag = 3 then -- no shift yet, clobber input. if yy.debug then text_io.put_line("Ayacc.YYParse: Error Recovery Clobbers " & yy_tokens.token'image(yy.input_symbol)); end if; if yy.input_symbol = yy_tokens.end_of_input then -- don't discard, if yy.debug then text_io.put_line("Ayacc.YYParse: Can't discard END_OF_INPUT, quiting..."); end if; raise yy_tokens.syntax_error; end if; yy.look_ahead := true; -- get next token return; -- and try again... end if; if yy.error_flag = 0 then -- brand new error yyerror("Syntax Error"); end if; yy.error_flag := 3; -- find state on stack where error is a valid shift -- if yy.debug then text_io.put_line("Ayacc.YYParse: Looking for state with error as valid shift"); end if; loop if yy.debug then text_io.put_line("Ayacc.YYParse: Examining State " & yy.parse_state'image(yy.state_stack(yy.tos))); end if; temp_action := parse_action(yy.state_stack(yy.tos), error); if temp_action >= yy.first_shift_entry then if yy.tos = yy.stack_size then text_io.put_line(" Stack size exceeded on state_stack"); raise yy_Tokens.syntax_error; end if; yy.tos := yy.tos + 1; yy.state_stack(yy.tos) := temp_action; exit; end if; Decrement_Stack_Pointer : begin yy.tos := yy.tos - 1; exception when Constraint_Error => yy.tos := 0; end Decrement_Stack_Pointer; if yy.tos = 0 then if yy.debug then text_io.put_line("Ayacc.YYParse: Error recovery popped entire stack, aborting..."); end if; raise yy_tokens.syntax_error; end if; end loop; if yy.debug then text_io.put_line("Ayacc.YYParse: Shifted error token in state " & yy.parse_state'image(yy.state_stack(yy.tos))); end if; end handle_error; -- print debugging information for a shift operation procedure shift_debug(state_id: yy.parse_state; lexeme: yy_tokens.token) is begin text_io.put_line("Ayacc.YYParse: Shift "& yy.parse_state'image(state_id)&" on input symbol "& yy_tokens.token'image(lexeme) ); end; -- print debugging information for a reduce operation procedure reduce_debug(rule_id: rule; state_id: yy.parse_state) is begin text_io.put_line("Ayacc.YYParse: Reduce by rule "&rule'image(rule_id)&" goto state "& yy.parse_state'image(state_id)); end; -- make the parser believe that 3 valid shifts have occured. -- used for error recovery. procedure yyerrok is begin yy.error_flag := 0; end yyerrok; -- called to clear input symbol that caused an error. procedure yyclearin is begin -- yy.input_symbol := yylex; yy.look_ahead := true; end yyclearin; begin -- initialize by pushing state 0 and getting the first input symbol yy.state_stack(yy.tos) := 0; loop yy.index := shift_reduce_offset(yy.state_stack(yy.tos)); if integer(shift_reduce_matrix(yy.index).t) = yy.default then yy.action := integer(shift_reduce_matrix(yy.index).act); else if yy.look_ahead then yy.look_ahead := false; yy.input_symbol := yylex; end if; yy.action := parse_action(yy.state_stack(yy.tos), yy.input_symbol); end if; if yy.action >= yy.first_shift_entry then -- SHIFT if yy.debug then shift_debug(yy.action, yy.input_symbol); end if; -- Enter new state if yy.tos = yy.stack_size then text_io.put_line(" Stack size exceeded on state_stack"); raise yy_Tokens.syntax_error; end if; yy.tos := yy.tos + 1; yy.state_stack(yy.tos) := yy.action; yy.value_stack(yy.tos) := yylval; if yy.error_flag > 0 then -- indicate a valid shift yy.error_flag := yy.error_flag - 1; end if; -- Advance lookahead yy.look_ahead := true; elsif yy.action = yy.error_code then -- ERROR handle_error; elsif yy.action = yy.accept_code then if yy.debug then text_io.put_line("Ayacc.YYParse: Accepting Grammar..."); end if; exit; else -- Reduce Action -- Convert action into a rule yy.rule_id := -1 * yy.action; -- Execute User Action -- user_action(yy.rule_id); case yy.rule_id is when 1 => --#line 44 -- add default rule pat := ccl.cclinit; ccl.cclnegate( pat ); def_rule := nfa.mkstate( -pat ); nfa.finish_rule( def_rule, false, 0, 0 ); for i in 1 .. lastsc loop scset(i) := nfa.mkbranch( scset(i), def_rule ); end loop; if ( spprdflt ) then text_io.put(temp_action_file, "raise AFLEX_SCANNER_JAMMED;"); else text_io.put( temp_action_file, "ECHO" ); text_io.put_line( temp_action_file, ";" ); end if; when 2 => --#line 69 -- initialize for processing rules -- create default DFA start condition sym.scinstal( tstring.vstr("INITIAL"), false ); when 5 => --#line 80 misc.synerr( "unknown error processing section 1" ); when 7 => --#line 87 -- these productions are separate from the s1object -- rule because the semantics must be done before -- we parse the remainder of an s1object xcluflg := false; when 8 => --#line 97 xcluflg := true; when 9 => --#line 101 sym.scinstal( nmstr, xcluflg ); when 10 => --#line 104 sym.scinstal( nmstr, xcluflg ); when 11 => --#line 107 misc.synerr( "bad start condition list" ); when 14 => --#line 115 -- initialize for a parse of one rule trlcontxt := false; variable_trail_rule := false; varlength := false; trailcnt := 0; headcnt := 0; rulelen := 0; current_state_enum := STATE_NORMAL; previous_continued_action := continued_action; nfa.new_rule; when 15 => --#line 130 pat := nfa.link_machines( yy.value_stack(yy.tos-1), yy.value_stack(yy.tos) ); nfa.finish_rule( pat, variable_trail_rule, headcnt, trailcnt ); for i in 1 .. actvp loop scbol(actvsc(i)) := nfa.mkbranch( scbol(actvsc(i)), pat ); end loop; if ( not bol_needed ) then bol_needed := true; if ( performance_report ) then text_io.put( Standard_Error, "'^' operator results in sub-optimal performance"); text_io.new_line(Standard_Error); end if; end if; when 16 => --#line 152 pat := nfa.link_machines( yy.value_stack(yy.tos-1), yy.value_stack(yy.tos) ); nfa.finish_rule( pat, variable_trail_rule, headcnt, trailcnt ); for i in 1 .. actvp loop scset(actvsc(i)) := nfa.mkbranch( scset(actvsc(i)), pat ); end loop; when 17 => --#line 163 pat := nfa.link_machines( yy.value_stack(yy.tos-1), yy.value_stack(yy.tos) ); nfa.finish_rule( pat, variable_trail_rule, headcnt, trailcnt ); -- add to all non-exclusive start conditions, -- including the default (0) start condition for i in 1 .. lastsc loop if ( not scxclu(i) ) then scbol(i) := nfa.mkbranch( scbol(i), pat ); end if; end loop; if ( not bol_needed ) then bol_needed := true; if ( performance_report ) then text_io.put( Standard_Error, "'^' operator results in sub-optimal performance"); text_io.new_line(Standard_Error); end if; end if; when 18 => --#line 188 pat := nfa.link_machines( yy.value_stack(yy.tos-1), yy.value_stack(yy.tos) ); nfa.finish_rule( pat, variable_trail_rule, headcnt, trailcnt ); for i in 1 .. lastsc loop if ( not scxclu(i) ) then scset(i) := nfa.mkbranch( scset(i), pat ); end if; end loop; when 19 => --#line 201 build_eof_action; when 20 => --#line 204 -- this EOF applies only to the INITIAL start cond. actvp := 1; actvsc(actvp) := 1; build_eof_action; when 21 => --#line 212 misc.synerr( "unrecognized rule" ); when 23 => --#line 219 scnum := sym.sclookup( nmstr ); if (scnum = 0 ) then text_io.put( Standard_Error, "undeclared start condition "); tstring.put( Standard_Error, nmstr ); main_body.aflexend( 1 ); else actvp := actvp + 1; actvsc(actvp) := scnum; end if; when 24 => --#line 233 scnum := sym.sclookup( nmstr ); if (scnum = 0 ) then text_io.put( Standard_Error, "undeclared start condition "); tstring.put( Standard_Error, nmstr ); main_body.aflexend ( 1 ); else actvp := 1; actvsc(actvp) := scnum; end if; when 25 => --#line 247 misc.synerr( "bad start condition list" ); when 26 => --#line 251 if trlcontxt then misc.synerr( "trailing context used twice" ); yyval := nfa.mkstate( SYM_EPSILON ); else trlcontxt := true; if ( not varlength ) then headcnt := rulelen; end if; rulelen := rulelen + 1; trailcnt := 1; eps := nfa.mkstate( SYM_EPSILON ); yyval := nfa.link_machines( eps, nfa.mkstate( CHARACTER'POS(ASCII.LF) ) ); end if; when 27 => --#line 272 yyval := nfa.mkstate( SYM_EPSILON ); if ( trlcontxt ) then if ( varlength and (headcnt = 0) ) then -- both head and trail are variable-length variable_trail_rule := true; else trailcnt := rulelen; end if; end if; when 28 => --#line 287 varlength := true; yyval := nfa.mkor( yy.value_stack(yy.tos-2), yy.value_stack(yy.tos) ); when 29 => --#line 294 if ( transchar(lastst( yy.value_stack(yy.tos))) /= SYM_EPSILON ) then -- provide final transition \now/ so it -- will be marked as a trailing context -- state yy.value_stack(yy.tos) := nfa.link_machines( yy.value_stack(yy.tos), nfa.mkstate( SYM_EPSILON ) ); end if; nfa.mark_beginning_as_normal( yy.value_stack(yy.tos) ); current_state_enum := STATE_NORMAL; if ( previous_continued_action ) then -- we need to treat this as variable trailing -- context so that the backup does not happen -- in the action but before the action switch -- statement. If the backup happens in the -- action, then the rules "falling into" this -- one's action will *also* do the backup, -- erroneously. if ( (not varlength) or headcnt /= 0 ) then text_io.put( Standard_Error, "alex: warning - trailing context rule at line"); int_io.put(Standard_Error, linenum); text_io.put( Standard_Error, "made variable because of preceding '|' action" ); int_io.put(Standard_Error, linenum); end if; -- mark as variable varlength := true; headcnt := 0; end if; if ( varlength and (headcnt = 0) ) then -- variable trailing context rule -- mark the first part of the rule as the accepting -- "head" part of a trailing context rule -- by the way, we didn't do this at the beginning -- of this production because back then -- current_state_enum was set up for a trail -- rule, and add_accept() can create a new -- state ... nfa.add_accept( yy.value_stack(yy.tos-1), misc.set_yy_trailing_head_mask(num_rules) ); end if; yyval := nfa.link_machines( yy.value_stack(yy.tos-1), yy.value_stack(yy.tos) ); when 30 => --#line 348 yyval := yy.value_stack(yy.tos); when 31 => --#line 353 -- this rule is separate from the others for "re" so -- that the reduction will occur before the trailing -- series is parsed if ( trlcontxt ) then misc.synerr( "trailing context used twice" ); else trlcontxt := true; end if; if ( varlength ) then -- we hope the trailing context is fixed-length varlength := false; else headcnt := rulelen; end if; rulelen := 0; current_state_enum := STATE_TRAILING_CONTEXT; yyval := yy.value_stack(yy.tos-1); when 32 => --#line 379 -- this is where concatenation of adjacent patterns -- gets done yyval := nfa.link_machines( yy.value_stack(yy.tos-1), yy.value_stack(yy.tos) ); when 33 => --#line 387 yyval := yy.value_stack(yy.tos); when 34 => --#line 391 varlength := true; yyval := nfa.mkclos( yy.value_stack(yy.tos-1) ); when 35 => --#line 398 varlength := true; yyval := nfa.mkposcl( yy.value_stack(yy.tos-1) ); when 36 => --#line 405 varlength := true; yyval := nfa.mkopt( yy.value_stack(yy.tos-1) ); when 37 => --#line 412 varlength := true; if ( ( yy.value_stack(yy.tos-3) > yy.value_stack(yy.tos-1)) or ( yy.value_stack(yy.tos-3) < 0) ) then misc.synerr( "bad iteration values" ); yyval := yy.value_stack(yy.tos-5); else if ( yy.value_stack(yy.tos-3) = 0 ) then yyval := nfa.mkopt( nfa.mkrep( yy.value_stack(yy.tos-5), yy.value_stack(yy.tos-3), yy.value_stack(yy.tos-1) ) ); else yyval := nfa.mkrep( yy.value_stack(yy.tos-5), yy.value_stack(yy.tos-3), yy.value_stack(yy.tos-1) ); end if; end if; when 38 => --#line 428 varlength := true; if ( yy.value_stack(yy.tos-2) <= 0 ) then misc.synerr( "iteration value must be positive" ); yyval := yy.value_stack(yy.tos-4); else yyval := nfa.mkrep( yy.value_stack(yy.tos-4), yy.value_stack(yy.tos-2), INFINITY ); end if; when 39 => --#line 440 -- the singleton could be something like "(foo)", -- in which case we have no idea what its length -- is, so we punt here. varlength := true; if ( yy.value_stack(yy.tos-1) <= 0 ) then misc.synerr( "iteration value must be positive" ); yyval := yy.value_stack(yy.tos-3); else yyval := nfa.link_machines( yy.value_stack(yy.tos-3), nfa.copysingl( yy.value_stack(yy.tos-3), yy.value_stack(yy.tos-1) - 1 ) ); end if; when 40 => --#line 456 if ( not madeany ) then -- create the '.' character class anyccl := ccl.cclinit; ccl.ccladd( anyccl, ASCII.LF ); ccl.cclnegate( anyccl ); if ( useecs ) then ecs.mkeccl( ccltbl(cclmap(anyccl)..cclmap(anyccl) + ccllen(anyccl)), ccllen(anyccl), nextecm, ecgroup, CSIZE ); end if; madeany := true; end if; rulelen := rulelen + 1; yyval := nfa.mkstate( -anyccl ); when 41 => --#line 478 if ( not cclsorted ) then -- sort characters for fast searching. We use a -- shell sort since this list could be large. -- misc.cshell( ccltbl + cclmap($1), ccllen($1) ); misc.cshell( ccltbl(cclmap( yy.value_stack(yy.tos))..cclmap( yy.value_stack(yy.tos)) + ccllen( yy.value_stack(yy.tos))), ccllen( yy.value_stack(yy.tos)) ); end if; if ( useecs ) then ecs.mkeccl( ccltbl(cclmap( yy.value_stack(yy.tos))..cclmap( yy.value_stack(yy.tos)) + ccllen( yy.value_stack(yy.tos))), ccllen( yy.value_stack(yy.tos)),nextecm, ecgroup, CSIZE ); end if; rulelen := rulelen + 1; yyval := nfa.mkstate( - yy.value_stack(yy.tos) ); when 42 => --#line 499 rulelen := rulelen + 1; yyval := nfa.mkstate( - yy.value_stack(yy.tos) ); when 43 => --#line 506 yyval := yy.value_stack(yy.tos-1); when 44 => --#line 509 yyval := yy.value_stack(yy.tos-1); when 45 => --#line 512 rulelen := rulelen + 1; if ( yy.value_stack(yy.tos) = CHARACTER'POS(ASCII.NUL) ) then misc.synerr( "null in rule" ); end if; if ( caseins and ( yy.value_stack(yy.tos) >= CHARACTER'POS('A')) and ( yy.value_stack(yy.tos) <= CHARACTER'POS('Z')) ) then yy.value_stack(yy.tos) := misc.clower( yy.value_stack(yy.tos) ); end if; yyval := nfa.mkstate( yy.value_stack(yy.tos) ); when 46 => --#line 528 yyval := yy.value_stack(yy.tos-1); when 47 => --#line 531 -- *Sigh* - to be compatible Unix lex, negated ccls -- match newlines ccl.cclnegate( yy.value_stack(yy.tos-1) ); yyval := yy.value_stack(yy.tos-1); when 48 => --#line 540 if ( yy.value_stack(yy.tos-2) > yy.value_stack(yy.tos) ) then misc.synerr( "negative range in character class" ); else if ( caseins ) then if ( ( yy.value_stack(yy.tos-2) >= CHARACTER'POS('A')) and ( yy.value_stack(yy.tos-2) <= CHARACTER'POS('Z')) ) then yy.value_stack(yy.tos-2) := misc.clower( yy.value_stack(yy.tos-2) ); end if; if ( ( yy.value_stack(yy.tos) >= CHARACTER'POS('A')) and ( yy.value_stack(yy.tos) <= CHARACTER'POS('Z')) ) then yy.value_stack(yy.tos) := misc.clower( yy.value_stack(yy.tos) ); end if; end if; for i in yy.value_stack(yy.tos-2) .. yy.value_stack(yy.tos) loop ccl.ccladd( yy.value_stack(yy.tos-3), CHARACTER'VAL(i) ); end loop; -- keep track if this ccl is staying in -- alphabetical order cclsorted := cclsorted and ( yy.value_stack(yy.tos-2) > lastchar); lastchar := yy.value_stack(yy.tos); end if; yyval := yy.value_stack(yy.tos-3); when 49 => --#line 568 if ( caseins ) then if ( ( yy.value_stack(yy.tos) >= CHARACTER'POS('A')) and ( yy.value_stack(yy.tos) <= CHARACTER'POS('Z')) ) then yy.value_stack(yy.tos) := misc.clower( yy.value_stack(yy.tos) ); end if; end if; ccl.ccladd( yy.value_stack(yy.tos-1), CHARACTER'VAL( yy.value_stack(yy.tos)) ); cclsorted := cclsorted and ( yy.value_stack(yy.tos) > lastchar); lastchar := yy.value_stack(yy.tos); yyval := yy.value_stack(yy.tos-1); when 50 => --#line 581 cclsorted := true; lastchar := 0; yyval := ccl.cclinit; when 51 => --#line 589 if ( caseins ) then if ( ( yy.value_stack(yy.tos) >= CHARACTER'POS('A')) and ( yy.value_stack(yy.tos) <= CHARACTER'POS('Z')) ) then yy.value_stack(yy.tos) := misc.clower( yy.value_stack(yy.tos) ); end if; end if; rulelen := rulelen + 1; yyval := nfa.link_machines( yy.value_stack(yy.tos-1), nfa.mkstate( yy.value_stack(yy.tos) ) ); when 52 => --#line 602 yyval := nfa.mkstate( SYM_EPSILON ); when others => null; end case; -- Pop RHS states and goto next state yy.tos := yy.tos - rule_length(yy.rule_id) + 1; if yy.tos > yy.stack_size then text_io.put_line(" Stack size exceeded on state_stack"); raise yy_Tokens.syntax_error; end if; yy.state_stack(yy.tos) := goto_state(yy.state_stack(yy.tos-1) , get_lhs_rule(yy.rule_id)); yy.value_stack(yy.tos) := yyval; if yy.debug then reduce_debug(yy.rule_id, goto_state(yy.state_stack(yy.tos - 1), get_lhs_rule(yy.rule_id))); end if; end if; end loop; end yyparse; end parser;
with CLIC.Subcommand; with Commands; with Ada.Text_IO; with CLIC.TTY; with Version; with Ada.Exceptions; use Ada.Exceptions; procedure Glad is begin Ada.Text_IO.New_Line; Commands.Execute; exception when E : others => Ada.Text_IO.Put_Line(Exception_Message (E)); end Glad;
----------------------------------------------------------------------- -- events-tests -- Unit tests for AWA events -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; package AWA.Events.Services.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with null record; -- Test searching an event name in the definition list. procedure Test_Find_Event (T : in out Test); -- Test the Get_Event_Type_Name internal operation. procedure Test_Get_Event_Name (T : in out Test); -- Test creation and initialization of event manager. procedure Test_Initialize (T : in out Test); -- Test adding an action. procedure Test_Add_Action (T : in out Test); -- Test dispatching synchronous event to a global bean. procedure Test_Dispatch_Synchronous (T : in out Test); -- Test dispatching event through a fifo queue. procedure Test_Dispatch_Fifo (T : in out Test); -- Test dispatching event through a database queue. procedure Test_Dispatch_Persist (T : in out Test); -- Test dispatching synchronous event to a dynamic bean (created on demand). procedure Test_Dispatch_Synchronous_Dyn (T : in out Test); -- Test dispatching synchronous event to a dynamic bean and raise an exception in the action. procedure Test_Dispatch_Synchronous_Raise (T : in out Test); procedure Dispatch_Event (T : in out Test; Kind : in Event_Index; Expect_Count : in Natural; Expect_Prio : in Natural); end AWA.Events.Services.Tests;
pragma Style_Checks (Off); ------------------------------------------------------------------------- -- GL.Geometry - GL geometry primitives -- -- Copyright (c) Rod Kay 2007 -- AUSTRALIA -- Permission granted to use this software, without any warranty, -- for any purpose, provided this copyright note remains attached -- and unmodified if sources are distributed further. ------------------------------------------------------------------------- with GL.geometry.Primitives; package GL.Geometry.primal is type primal_Geometry is new Geometry_t with record Primitive : primitives.p_Primitive; end record; type p_primal_Geometry is access all primal_Geometry; function primitive_Id (Self : in primal_Geometry) return GL.ObjectTypeEnm; function vertex_Count (Self : in primal_Geometry) return GL.geometry.vertex_Id; function Vertices (Self : in primal_Geometry) return GL.geometry.GL_Vertex_array; procedure set_Vertices (Self : in out primal_Geometry; To : access GL.geometry.GL_Vertex_array); function indices_Count (Self : in primal_Geometry) return GL.positive_uInt; function Indices (Self : in primal_Geometry) return GL.geometry.vertex_Id_array; procedure set_Indices (Self : in out primal_Geometry; To : access GL.geometry.vertex_Id_array); function Bounds (Self : in primal_Geometry) return GL.geometry.Bounds_record; procedure Draw (Self : in primal_Geometry); procedure destroy (Self : in out primal_Geometry); end GL.Geometry.primal;
----------------------------------------------------------------------- -- akt-filesystem -- Fuse filesystem operations -- Copyright (C) 2019, 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.Calendar.Conversions; with Util.Strings; with Util.Log.Loggers; package body AKT.Filesystem is use type System.St_Mode_Type; use type Interfaces.Unsigned_64; use type Keystore.Entry_Type; use Ada.Streams; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AKT.Filesystem"); procedure Initialize (St_Buf : access System.Stat_Type; Mode : in System.St_Mode_Type); function To_Unix (Date : in Ada.Calendar.Time) return Interfaces.Integer_64 is (Interfaces.Integer_64 (Ada.Calendar.Conversions.To_Unix_Time (Date))); procedure Initialize (St_Buf : access System.Stat_Type; Mode : in System.St_Mode_Type) is begin St_Buf.St_Dev := 0; St_Buf.St_Ino := 0; St_Buf.St_Nlink := 1; St_Buf.St_Uid := 0; St_Buf.St_Gid := 0; St_Buf.St_Rdev := 0; St_Buf.St_Size := 0; St_Buf.St_Atime := 0; St_Buf.St_Mtime := 0; St_Buf.St_Ctime := 0; St_Buf.St_Blksize := 8192; St_Buf.St_Blocks := 0; St_Buf.St_Mode := System.Mode_T_to_St_Mode (8#700#) or Mode; end Initialize; -------------------------- -- Get Attributes -- -------------------------- function GetAttr (Path : in String; St_Buf : access System.Stat_Type) return System.Error_Type is Data : constant User_Data_Type := General.Get_User_Data; Info : Keystore.Entry_Info; begin Log.Debug ("Get attributes of {0}", Path); if Path'Length = 0 then return System.ENOENT; elsif Path = "/" then Initialize (St_Buf, System.S_IFDIR); else Initialize (St_Buf, System.S_IFREG); Info := Data.Wallet.Find (Path (Path'First + 1 .. Path'Last)); if Info.Kind = Keystore.T_DIRECTORY then St_Buf.St_Mode := System.Mode_T_to_St_Mode (8#700#); St_Buf.St_Mode := St_Buf.St_Mode or System.S_IFDIR; else St_Buf.St_Mode := System.Mode_T_to_St_Mode (8#600#); St_Buf.St_Mode := St_Buf.St_Mode or System.S_IFREG; end if; St_Buf.St_Size := Interfaces.Integer_64 (Info.Size); St_Buf.St_Ctime := To_Unix (Info.Create_Date); St_Buf.St_Mtime := To_Unix (Info.Update_Date); St_Buf.St_Atime := St_Buf.St_Mtime; end if; return System.EXIT_SUCCESS; exception when Keystore.Not_Found => return System.ENOENT; end GetAttr; -------------------------- -- MkDir -- -------------------------- function MkDir (Path : in String; Mode : in System.St_Mode_Type) return System.Error_Type is pragma Unreferenced (Mode); Data : constant User_Data_Type := General.Get_User_Data; Empty : constant Ada.Streams.Stream_Element_Array (1 .. 0) := (others => <>); begin Log.Info ("Mkdir {0}", Path); Data.Wallet.Add (Name => Path (Path'First + 1 .. Path'Last), Kind => Keystore.T_DIRECTORY, Content => Empty); return System.EXIT_SUCCESS; exception when Keystore.Name_Exist => return System.EEXIST; end MkDir; -------------------------- -- Unlink -- -------------------------- function Unlink (Path : in String) return System.Error_Type is Data : constant User_Data_Type := General.Get_User_Data; begin Log.Info ("Unlink {0}", Path); Data.Wallet.Delete (Name => Path (Path'First + 1 .. Path'Last)); return System.EXIT_SUCCESS; exception when Keystore.Not_Found => return System.ENOENT; end Unlink; -------------------------- -- RmDir -- -------------------------- function RmDir (Path : in String) return System.Error_Type is Data : constant User_Data_Type := General.Get_User_Data; begin Log.Info ("Rmdir {0}", Path); declare Item : constant Keystore.Entry_Info := Data.Wallet.Find (Path (Path'First + 1 .. Path'Last)); begin if Item.Kind /= Keystore.T_DIRECTORY then return System.ENOTDIR; end if; Data.Wallet.Delete (Path (Path'First + 1 .. Path'Last)); return System.EXIT_SUCCESS; end; exception when Keystore.Not_Found => return System.ENOENT; end RmDir; -------------------------- -- Create -- -------------------------- function Create (Path : in String; Mode : in System.St_Mode_Type; Fi : access System.File_Info_Type) return System.Error_Type is pragma Unreferenced (Mode); Data : constant User_Data_Type := General.Get_User_Data; begin Log.Info ("Create {0}", Path); Fi.Direct_IO := Data.Direct_IO; Fi.Keep_Cache := not Data.Direct_IO; Data.Wallet.Add (Path (Path'First + 1 .. Path'Last), ""); return System.EXIT_SUCCESS; exception when Keystore.Name_Exist => return System.EEXIST; end Create; -------------------------- -- Open -- -------------------------- function Open (Path : in String; Fi : access System.File_Info_Type) return System.Error_Type is Data : constant User_Data_Type := General.Get_User_Data; begin Log.Info ("Open {0}", Path); Fi.Direct_IO := Data.Direct_IO; Fi.Keep_Cache := not Data.Direct_IO; if not Data.Wallet.Contains (Path (Path'First + 1 .. Path'Last)) then return System.ENOENT; else return System.EXIT_SUCCESS; end if; end Open; -------------------------- -- Release -- -------------------------- function Release (Path : in String; Fi : access System.File_Info_Type) return System.Error_Type is pragma Unreferenced (Fi); begin Log.Info ("Release {0}", Path); return System.EXIT_SUCCESS; end Release; -------------------------- -- Read -- -------------------------- function Read (Path : in String; Buffer : access Buffer_Type; Size : in out Natural; Offset : in Natural; Fi : access System.File_Info_Type) return System.Error_Type is Data : constant User_Data_Type := General.Get_User_Data; Last : Stream_Element_Offset; Buf : Ada.Streams.Stream_Element_Array (1 .. Ada.Streams.Stream_Element_Offset (Size)); for Buf'Address use Buffer.all'Address; begin Log.Info ("Read {0}", Path); Fi.Direct_IO := Data.Direct_IO; Fi.Keep_Cache := not Data.Direct_IO; Data.Wallet.Read (Name => Path (Path'First + 1 .. Path'Last), Offset => Stream_Element_Offset (Offset), Content => Buf, Last => Last); Size := Natural (Last - Buf'First + 1); return System.EXIT_SUCCESS; exception when Keystore.Not_Found => return System.EINVAL; end Read; -------------------------- -- Write -- -------------------------- function Write (Path : in String; Buffer : access Buffer_Type; Size : in out Natural; Offset : in Natural; Fi : access System.File_Info_Type) return System.Error_Type is pragma Unmodified (Size); Data : constant User_Data_Type := General.Get_User_Data; Buf : Ada.Streams.Stream_Element_Array (1 .. Ada.Streams.Stream_Element_Offset (Size)); for Buf'Address use Buffer.all'Address; begin Log.Info ("Write {0} at {1}", Path, Natural'Image (Offset) & " size" & Natural'Image (Size)); Fi.Direct_IO := Data.Direct_IO; Fi.Keep_Cache := not Data.Direct_IO; Data.Wallet.Write (Name => Path (Path'First + 1 .. Path'Last), Offset => Stream_Element_Offset (Offset), Content => Buf); return System.EXIT_SUCCESS; exception when Keystore.Not_Found => return System.EINVAL; end Write; -------------------------- -- Read Dir -- -------------------------- function ReadDir (Path : in String; Filler : access procedure (Name : String; St_Buf : System.Stat_Access; Offset : Natural); Offset : in Natural; Fi : access System.File_Info_Type) return System.Error_Type is pragma Unreferenced (Offset, Fi); Data : constant User_Data_Type := General.Get_User_Data; List : Keystore.Entry_Map; Iter : Keystore.Entry_Cursor; St_Buf : aliased System.Stat_Type; begin Log.Info ("Read directory {0}", Path); Initialize (St_Buf'Unchecked_Access, System.S_IFDIR); St_Buf.St_Mode := (S_IFDIR => True, S_IRUSR => True, S_IWUSR => True, others => False); Data.Wallet.List (Content => List); Iter := List.First; St_Buf.St_Mode := (S_IFREG => True, S_IRUSR => True, S_IWUSR => True, others => False); while Keystore.Entry_Maps.Has_Element (Iter) loop declare Name : constant String := Keystore.Entry_Maps.Key (Iter); Pos : Natural := Util.Strings.Rindex (Name, '/'); begin if Pos = 0 then Pos := Name'First - 1; end if; if Name (Name'First .. Pos - 1) = Path (Path'First + 1 .. Path'Last) then declare Item : constant Keystore.Entry_Info := Keystore.Entry_Maps.Element (Iter); begin if Item.Kind = Keystore.T_DIRECTORY then Log.Info ("Directory {0}", Name); Initialize (St_Buf'Unchecked_Access, System.S_IFDIR); else Initialize (St_Buf'Unchecked_Access, System.S_IFREG); Log.Info ("Item {0}", Name); end if; St_Buf.St_Size := Interfaces.Integer_64 (Item.Size); St_Buf.St_Ctime := To_Unix (Item.Create_Date); St_Buf.St_Mtime := To_Unix (Item.Update_Date); St_Buf.St_Blocks := Interfaces.Integer_64 (Item.Block_Count); Filler.all (Name (Pos + 1 .. Name'Last), St_Buf'Unchecked_Access, 0); end; end if; end; Keystore.Entry_Maps.Next (Iter); end loop; return System.EXIT_SUCCESS; exception when Keystore.Not_Found => return System.ENOENT; end ReadDir; function Truncate (Path : in String; Size : in Natural) return System.Error_Type is Data : constant User_Data_Type := General.Get_User_Data; begin Log.Info ("Truncate {0} to {1}", Path, Natural'Image (Size)); if Size /= 0 then return System.EPERM; end if; Data.Wallet.Set (Path (Path'First + 1 .. Path'Last), ""); return System.EXIT_SUCCESS; end Truncate; end AKT.Filesystem;
procedure deref_test is type PString is access String; a,b : String (1 .. 3); res : String := "a"; PtrArr: array(1 .. 2) of PString; function "<"(x,y: in String) return PString is begin return PtrArr(1); end "<"; begin PtrArr(1) := new String'("<"); PtrArr(2) := new String'(">="); res := "<"(a, b).all; PtrArr(2) := a < b; end deref_test;
with Ada.Text_IO; procedure Hello_World is begin Ada.Text_IO.Put_Line ("Hello, world!"); end Hello_World;
with Ada.Text_IO; with Primes; procedure Main is N : Positive := 16; begin Ada.Text_IO.Put_Line (Primes.IsPrime (N)'Image); end Main;
with Ada.Strings.Unbounded; with Planet; with Rule; use Rule; package Player is type Object is tagged private; function Build (Race : String; Good_Ability : Good_Type; Bad_Ability : Bad_Type; Victory_Condition : Victory; Homeworld : Planet.Object) return Object; private package SU renames Ada.Strings.Unbounded; type Object is tagged record Race : SU.Unbounded_String; Good_Ability : Good_Type; Bad_Ability : Bad_Type; Victory_Condition : Victory; Owner_Planets : Planet.Vector; Homeworld : Planet.Object; end record; end Player;
-- Abstract : -- -- See spec. -- -- Copyright (C) 2018 - 2019 Free Software Foundation, Inc. -- -- This library is free software; you can redistribute it and/or modify it -- under terms of the GNU General Public License as published by the Free -- Software Foundation; either version 3, or (at your option) any later -- version. This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- As a special exception under Section 7 of GPL version 3, you are granted -- additional permissions described in the GCC Runtime Library Exception, -- version 3.1, as published by the Free Software Foundation. pragma License (Modified_GPL); with Ada.Containers; with Ada.Text_IO; with SAL.Generic_Decimal_Image; package body WisiToken.Syntax_Trees is -- Body specs, alphabetical, as needed function Image (Tree : in Syntax_Trees.Tree; N : in Syntax_Trees.Node; Descriptor : in WisiToken.Descriptor; Include_Children : in Boolean; Include_RHS_Index : in Boolean := False) return String; function Min (Item : in Valid_Node_Index_Array) return Valid_Node_Index; procedure Move_Branch_Point (Tree : in out Syntax_Trees.Tree; Required_Node : in Valid_Node_Index); type Visit_Parent_Mode is (Before, After); function Process_Tree (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; Visit_Parent : in Visit_Parent_Mode; Process_Node : access function (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean) return Boolean; -- Call Process_Node on nodes in tree rooted at Node. Return when -- Process_Node returns False (Process_Tree returns False), or when -- all nodes have been processed (Process_Tree returns True). procedure Set_Children (Nodes : in out Node_Arrays.Vector; Parent : in Valid_Node_Index; Children : in Valid_Node_Index_Array); ---------- -- Public and body operations, alphabetical function Action (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Semantic_Action is begin return (if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node).Action else Tree.Branched_Nodes (Node).Action); end Action; procedure Add_Child (Tree : in out Syntax_Trees.Tree; Parent : in Valid_Node_Index; Child : in Valid_Node_Index) is Node : Syntax_Trees.Node renames Tree.Shared_Tree.Nodes (Parent); begin Node.Children.Append (Child); -- We don't update Min/Max_terminal_index; they are no longer needed. end Add_Child; function Add_Identifier (Tree : in out Syntax_Trees.Tree; ID : in Token_ID; Identifier : in Identifier_Index; Byte_Region : in WisiToken.Buffer_Region) return Valid_Node_Index is begin Tree.Shared_Tree.Nodes.Append ((Label => Virtual_Identifier, Byte_Region => Byte_Region, ID => ID, Identifier => Identifier, others => <>)); Tree.Last_Shared_Node := Tree.Shared_Tree.Nodes.Last_Index; return Tree.Last_Shared_Node; end Add_Identifier; function Add_Nonterm (Tree : in out Syntax_Trees.Tree; Production : in WisiToken.Production_ID; Children : in Valid_Node_Index_Array; Action : in Semantic_Action := null; Default_Virtual : in Boolean := False) return Valid_Node_Index is Nonterm_Node : Valid_Node_Index; begin if Tree.Flush then Tree.Shared_Tree.Nodes.Append ((Label => Syntax_Trees.Nonterm, ID => Production.LHS, Action => Action, RHS_Index => Production.RHS, Virtual => (if Children'Length = 0 then Default_Virtual else False), others => <>)); Tree.Last_Shared_Node := Tree.Shared_Tree.Nodes.Last_Index; Nonterm_Node := Tree.Last_Shared_Node; else Tree.Branched_Nodes.Append ((Label => Syntax_Trees.Nonterm, ID => Production.LHS, Action => Action, RHS_Index => Production.RHS, Virtual => (if Children'Length = 0 then Default_Virtual else False), others => <>)); Nonterm_Node := Tree.Branched_Nodes.Last_Index; end if; if Children'Length = 0 then return Nonterm_Node; end if; if Tree.Flush then Set_Children (Tree.Shared_Tree.Nodes, Nonterm_Node, Children); else declare Min_Child_Node : constant Valid_Node_Index := Min (Children); begin if Min_Child_Node <= Tree.Last_Shared_Node then Move_Branch_Point (Tree, Min_Child_Node); end if; end; Set_Children (Tree.Branched_Nodes, Nonterm_Node, Children); end if; return Nonterm_Node; end Add_Nonterm; function Add_Terminal (Tree : in out Syntax_Trees.Tree; Terminal : in Token_Index; Terminals : in Base_Token_Arrays.Vector) return Valid_Node_Index is begin if Tree.Flush then Tree.Shared_Tree.Nodes.Append ((Label => Shared_Terminal, ID => Terminals (Terminal).ID, Byte_Region => Terminals (Terminal).Byte_Region, Terminal => Terminal, others => <>)); Tree.Last_Shared_Node := Tree.Shared_Tree.Nodes.Last_Index; return Tree.Last_Shared_Node; else Tree.Branched_Nodes.Append ((Label => Shared_Terminal, ID => Terminals (Terminal).ID, Byte_Region => Terminals (Terminal).Byte_Region, Terminal => Terminal, others => <>)); return Tree.Branched_Nodes.Last_Index; end if; end Add_Terminal; function Add_Terminal (Tree : in out Syntax_Trees.Tree; Terminal : in Token_ID) return Valid_Node_Index is begin if Tree.Flush then Tree.Shared_Tree.Nodes.Append ((Label => Virtual_Terminal, ID => Terminal, others => <>)); Tree.Last_Shared_Node := Tree.Shared_Tree.Nodes.Last_Index; return Tree.Last_Shared_Node; else Tree.Branched_Nodes.Append ((Label => Virtual_Terminal, ID => Terminal, others => <>)); return Tree.Branched_Nodes.Last_Index; end if; end Add_Terminal; function Augmented (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Base_Token_Class_Access is begin if Node <= Tree.Last_Shared_Node then return Tree.Shared_Tree.Nodes (Node).Augmented; else return Tree.Branched_Nodes (Node).Augmented; end if; end Augmented; function Byte_Region (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return WisiToken.Buffer_Region is begin return (if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node).Byte_Region else Tree.Branched_Nodes (Node).Byte_Region); end Byte_Region; function Child (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; Child_Index : in Positive_Index_Type) return Node_Index is function Compute (N : in Syntax_Trees.Node) return Node_Index is begin if Child_Index in N.Children.First_Index .. N.Children.Last_Index then return N.Children (Child_Index); else return Invalid_Node_Index; end if; end Compute; begin if Node <= Tree.Last_Shared_Node then return Compute (Tree.Shared_Tree.Nodes (Node)); else return Compute (Tree.Branched_Nodes (Node)); end if; end Child; function Children (N : in Syntax_Trees.Node) return Valid_Node_Index_Array is use all type Ada.Containers.Count_Type; begin if N.Children.Length = 0 then return (1 .. 0 => <>); else return Result : Valid_Node_Index_Array (N.Children.First_Index .. N.Children.Last_Index) do for I in Result'Range loop Result (I) := N.Children (I); end loop; end return; end if; end Children; function Children (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Valid_Node_Index_Array is begin if Node <= Tree.Last_Shared_Node then return Children (Tree.Shared_Tree.Nodes (Node)); else return Children (Tree.Branched_Nodes (Node)); end if; end Children; procedure Clear (Tree : in out Syntax_Trees.Base_Tree) is begin Tree.Finalize; end Clear; procedure Clear (Tree : in out Syntax_Trees.Tree) is begin if Tree.Shared_Tree.Augmented_Present then for Node of Tree.Branched_Nodes loop if Node.Label = Nonterm then Free (Node.Augmented); end if; end loop; end if; Tree.Shared_Tree.Finalize; Tree.Last_Shared_Node := Invalid_Node_Index; Tree.Branched_Nodes.Clear; end Clear; function Copy_Subtree (Tree : in out Syntax_Trees.Tree; Root : in Valid_Node_Index; Last : in Valid_Node_Index) return Valid_Node_Index is function Copy_Node (Tree : in out Syntax_Trees.Tree; Index : in Valid_Node_Index; Parent : in Node_Index) return Valid_Node_Index is begin case Tree.Shared_Tree.Nodes (Index).Label is when Shared_Terminal => declare Node : Syntax_Trees.Node renames Tree.Shared_Tree.Nodes (Index); begin Tree.Shared_Tree.Nodes.Append ((Label => Shared_Terminal, ID => Node.ID, Byte_Region => Node.Byte_Region, Parent => Parent, State => Unknown_State, Terminal => Node.Terminal)); end; when Virtual_Terminal => declare Node : Syntax_Trees.Node renames Tree.Shared_Tree.Nodes (Index); begin Tree.Shared_Tree.Nodes.Append ((Label => Virtual_Terminal, ID => Node.ID, Byte_Region => Node.Byte_Region, Parent => Parent, State => Unknown_State)); end; when Virtual_Identifier => declare Node : Syntax_Trees.Node renames Tree.Shared_Tree.Nodes (Index); begin Tree.Shared_Tree.Nodes.Append ((Label => Virtual_Identifier, ID => Node.ID, Byte_Region => Node.Byte_Region, Parent => Parent, State => Unknown_State, Identifier => Node.Identifier)); end; when Nonterm => declare Children : constant Valid_Node_Index_Array := Tree.Children (Index); Parent : Node_Index := Invalid_Node_Index; New_Children : Valid_Node_Index_Arrays.Vector; begin if Children'Length > 0 then declare use all type SAL.Base_Peek_Type; Last_Index : SAL.Base_Peek_Type := SAL.Base_Peek_Type'Last; begin for I in Children'Range loop if Children (I) = Last then Last_Index := I; end if; end loop; if Last_Index = SAL.Base_Peek_Type'Last then New_Children.Set_Length (Children'Length); for I in Children'Range loop New_Children (I) := Copy_Node (Tree, Children (I), Parent); end loop; else for I in Last_Index .. Children'Last loop New_Children.Append (Copy_Node (Tree, Children (I), Parent)); end loop; end if; end; end if; declare Node : Syntax_Trees.Node renames Tree.Shared_Tree.Nodes (Index); begin Tree.Shared_Tree.Nodes.Append ((Label => Nonterm, ID => Node.ID, Byte_Region => Node.Byte_Region, Parent => Parent, State => Unknown_State, Virtual => Node.Virtual, RHS_Index => Node.RHS_Index, Action => Node.Action, Name => Node.Name, Children => New_Children, Min_Terminal_Index => Node.Min_Terminal_Index, Max_Terminal_Index => Node.Max_Terminal_Index, Augmented => Node.Augmented)); end; Tree.Last_Shared_Node := Tree.Shared_Tree.Nodes.Last_Index; Parent := Tree.Last_Shared_Node; for I in New_Children.First_Index .. New_Children.Last_Index loop Tree.Shared_Tree.Nodes (New_Children (I)).Parent := Parent; end loop; return Parent; end; end case; Tree.Last_Shared_Node := Tree.Shared_Tree.Nodes.Last_Index; return Tree.Last_Shared_Node; end Copy_Node; begin return Copy_Node (Tree, Root, Invalid_Node_Index); end Copy_Subtree; function Count_IDs (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; ID : in Token_ID) return SAL.Base_Peek_Type is function Compute (N : in Syntax_Trees.Node) return SAL.Base_Peek_Type is use all type SAL.Base_Peek_Type; begin return Result : SAL.Base_Peek_Type := 0 do if N.ID = ID then Result := 1; end if; case N.Label is when Shared_Terminal | Virtual_Terminal | Virtual_Identifier => null; when Nonterm => for I of N.Children loop Result := Result + Count_IDs (Tree, I, ID); end loop; end case; end return; end Compute; begin return Compute ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node))); end Count_IDs; function Count_Terminals (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Integer -- Count_Terminals must return Integer for Get_Terminals, -- Positive_Index_Type for Get_Terminal_IDs. is function Compute (N : in Syntax_Trees.Node) return Integer is begin case N.Label is when Shared_Terminal | Virtual_Terminal | Virtual_Identifier => return 1; when Nonterm => return Result : Integer := 0 do for I of N.Children loop Result := Result + Count_Terminals (Tree, I); end loop; end return; end case; end Compute; begin return Compute ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node))); end Count_Terminals; overriding procedure Finalize (Tree : in out Base_Tree) is begin Tree.Traversing := False; if Tree.Augmented_Present then for Node of Tree.Nodes loop if Node.Label = Nonterm then Free (Node.Augmented); end if; end loop; Tree.Augmented_Present := False; end if; Tree.Nodes.Finalize; end Finalize; overriding procedure Finalize (Tree : in out Syntax_Trees.Tree) is begin if Tree.Last_Shared_Node /= Invalid_Node_Index then if Tree.Shared_Tree.Augmented_Present then for Node of Tree.Branched_Nodes loop Free (Node.Augmented); end loop; -- We don't clear Tree.Shared_Tree.Augmented_Present here; other -- branched trees may need to be finalized. end if; Tree.Branched_Nodes.Finalize; Tree.Last_Shared_Node := Invalid_Node_Index; end if; end Finalize; function Find_Ancestor (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; ID : in Token_ID) return Node_Index is N : Node_Index := Node; begin loop N := (if N <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (N).Parent else Tree.Branched_Nodes (N).Parent); exit when N = Invalid_Node_Index; exit when ID = (if N <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (N).ID else Tree.Branched_Nodes (N).ID); end loop; return N; end Find_Ancestor; function Find_Ancestor (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; IDs : in Token_ID_Array) return Node_Index is N : Node_Index := Node; begin loop N := (if N <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (N).Parent else Tree.Branched_Nodes (N).Parent); exit when N = Invalid_Node_Index; exit when (for some ID of IDs => ID = (if N <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (N).ID else Tree.Branched_Nodes (N).ID)); end loop; return N; end Find_Ancestor; function Find_Child (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; ID : in Token_ID) return Node_Index is function Compute (N : in Syntax_Trees.Node) return Node_Index is begin case N.Label is when Shared_Terminal | Virtual_Terminal | Virtual_Identifier => return Invalid_Node_Index; when Nonterm => for C of N.Children loop if ID = (if C <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (C).ID else Tree.Branched_Nodes (C).ID) then return C; end if; end loop; return Invalid_Node_Index; end case; end Compute; begin return Compute ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node))); end Find_Child; function Find_Descendant (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; ID : in Token_ID) return Node_Index is Found : Node_Index := Invalid_Node_Index; function Process (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean is Node_ID : constant Token_ID := (if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node).ID else Tree.Branched_Nodes (Node).ID); begin if Node_ID = ID then Found := Node; return False; else return True; end if; end Process; Junk : constant Boolean := Process_Tree (Tree, Node, After, Process'Access); pragma Unreferenced (Junk); begin return Found; end Find_Descendant; function Find_Min_Terminal_Index (Tree : in Syntax_Trees.Tree; Index : in Token_Index) return Node_Index is Found : Node_Index := Invalid_Node_Index; function Process (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean is function Compute (N : in Syntax_Trees.Node) return Boolean is begin if N.Label /= Nonterm then return True; elsif Index = N.Min_Terminal_Index then Found := Node; return False; else return True; end if; end Compute; begin return Compute ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node))); end Process; Junk : constant Boolean := Process_Tree (Tree, Tree.Root, Before, Process'Access); pragma Unreferenced (Junk); begin return Found; end Find_Min_Terminal_Index; function Find_Max_Terminal_Index (Tree : in Syntax_Trees.Tree; Index : in Token_Index) return Node_Index is Found : Node_Index := Invalid_Node_Index; function Process (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean is function Compute (N : in Syntax_Trees.Node) return Boolean is begin if N.Label /= Nonterm then return True; elsif Index = N.Max_Terminal_Index then Found := Node; return False; else return True; end if; end Compute; begin return Compute ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node))); end Process; Junk : constant Boolean := Process_Tree (Tree, Tree.Root, Before, Process'Access); pragma Unreferenced (Junk); begin return Found; end Find_Max_Terminal_Index; function Find_Sibling (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; ID : in Token_ID) return Node_Index is function Compute_2 (N : in Syntax_Trees.Node) return Node_Index is begin case N.Label is when Shared_Terminal | Virtual_Terminal | Virtual_Identifier => return Invalid_Node_Index; when Nonterm => for C of N.Children loop if ID = (if C <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (C).ID else Tree.Branched_Nodes (C).ID) then return C; end if; end loop; return Invalid_Node_Index; end case; end Compute_2; function Compute_1 (Parent : in Node_Index) return Node_Index is begin if Parent = Invalid_Node_Index then return Invalid_Node_Index; else return Compute_2 ((if Parent <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Parent) else Tree.Branched_Nodes (Parent))); end if; end Compute_1; begin return Compute_1 ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node).Parent else Tree.Branched_Nodes (Node).Parent)); end Find_Sibling; function First_Index (Tree : in Syntax_Trees.Tree) return Node_Index is begin return Tree.Shared_Tree.Nodes.First_Index; end First_Index; procedure Flush (Tree : in out Syntax_Trees.Tree) is begin -- This is the opposite of Move_Branch_Point Tree.Shared_Tree.Nodes.Merge (Tree.Branched_Nodes); Tree.Last_Shared_Node := Tree.Shared_Tree.Nodes.Last_Index; Tree.Flush := True; end Flush; function Flushed (Tree : in Syntax_Trees.Tree) return Boolean is begin return Tree.Flush; end Flushed; procedure Get_IDs (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; ID : in Token_ID; Result : in out Valid_Node_Index_Array; Last : in out SAL.Base_Peek_Type) is use all type SAL.Base_Peek_Type; procedure Compute (N : in Syntax_Trees.Node) is begin if N.ID = ID then Last := Last + 1; Result (Last) := Node; end if; case N.Label is when Shared_Terminal | Virtual_Terminal | Virtual_Identifier => null; when Nonterm => for I of N.Children loop Get_IDs (Tree, I, ID, Result, Last); end loop; end case; end Compute; begin Compute ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node))); end Get_IDs; function Get_IDs (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; ID : in Token_ID) return Valid_Node_Index_Array is Last : SAL.Base_Peek_Type := 0; begin Tree.Shared_Tree.Traversing := True; return Result : Valid_Node_Index_Array (1 .. Count_IDs (Tree, Node, ID)) do Get_IDs (Tree, Node, ID, Result, Last); Tree.Shared_Tree.Traversing := False; end return; end Get_IDs; procedure Get_Terminals (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; Result : in out Valid_Node_Index_Array; Last : in out SAL.Base_Peek_Type) is use all type SAL.Base_Peek_Type; procedure Compute (N : in Syntax_Trees.Node) is begin case N.Label is when Shared_Terminal | Virtual_Terminal | Virtual_Identifier => Last := Last + 1; Result (Last) := Node; when Nonterm => for I of N.Children loop Get_Terminals (Tree, I, Result, Last); end loop; end case; end Compute; begin Compute ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node))); end Get_Terminals; function Get_Terminals (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Valid_Node_Index_Array is Last : SAL.Base_Peek_Type := 0; begin Tree.Shared_Tree.Traversing := True; return Result : Valid_Node_Index_Array (1 .. SAL.Base_Peek_Type (Count_Terminals (Tree, Node))) do Get_Terminals (Tree, Node, Result, Last); Tree.Shared_Tree.Traversing := False; end return; end Get_Terminals; procedure Get_Terminal_IDs (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; Result : in out Token_ID_Array; Last : in out SAL.Base_Peek_Type) is procedure Compute (N : in Syntax_Trees.Node) is use all type SAL.Base_Peek_Type; begin case N.Label is when Shared_Terminal | Virtual_Terminal | Virtual_Identifier => Last := Last + 1; Result (Integer (Last)) := N.ID; when Nonterm => for I of N.Children loop Get_Terminal_IDs (Tree, I, Result, Last); end loop; end case; end Compute; begin Compute ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node))); end Get_Terminal_IDs; function Get_Terminal_IDs (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Token_ID_Array is Last : SAL.Base_Peek_Type := 0; begin Tree.Shared_Tree.Traversing := True; return Result : Token_ID_Array (1 .. Count_Terminals (Tree, Node)) do Get_Terminal_IDs (Tree, Node, Result, Last); Tree.Shared_Tree.Traversing := False; end return; end Get_Terminal_IDs; function First_Terminal_ID (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Token_ID is function Compute (N : in Syntax_Trees.Node) return Token_ID is begin case N.Label is when Shared_Terminal | Virtual_Terminal | Virtual_Identifier => return N.ID; when Nonterm => return First_Terminal_ID (Tree, N.Children (1)); end case; end Compute; begin return Compute ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node))); end First_Terminal_ID; function Has_Branched_Nodes (Tree : in Syntax_Trees.Tree) return Boolean is use all type Ada.Containers.Count_Type; begin return Tree.Branched_Nodes.Length > 0; end Has_Branched_Nodes; function Has_Children (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean is use all type Ada.Containers.Count_Type; begin if Node <= Tree.Last_Shared_Node then return Tree.Shared_Tree.Nodes (Node).Children.Length > 0; else return Tree.Branched_Nodes (Node).Children.Length > 0; end if; end Has_Children; function Has_Parent (Tree : in Syntax_Trees.Tree; Child : in Valid_Node_Index) return Boolean is begin return (if Child <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Child).Parent /= Invalid_Node_Index else Tree.Branched_Nodes (Child).Parent /= Invalid_Node_Index); end Has_Parent; function Has_Parent (Tree : in Syntax_Trees.Tree; Children : in Valid_Node_Index_Array) return Boolean is begin return (for some Child of Children => (if Child <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Child).Parent /= Invalid_Node_Index else Tree.Branched_Nodes (Child).Parent /= Invalid_Node_Index)); end Has_Parent; function ID (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Token_ID is begin return (if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node).ID else Tree.Branched_Nodes (Node).ID); end ID; function Identifier (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Base_Identifier_Index is begin return (if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node).Identifier else Tree.Branched_Nodes (Node).Identifier); end Identifier; function Image (Tree : in Syntax_Trees.Tree; Children : in Valid_Node_Index_Arrays.Vector; Descriptor : in WisiToken.Descriptor) return String is use Ada.Strings.Unbounded; Result : Unbounded_String := +"("; Need_Comma : Boolean := False; begin for I of Children loop Result := Result & (if Need_Comma then ", " else "") & Tree.Image (I, Descriptor, Include_Children => False); Need_Comma := True; end loop; Result := Result & ")"; return -Result; end Image; function Image (Tree : in Syntax_Trees.Tree; N : in Syntax_Trees.Node; Descriptor : in WisiToken.Descriptor; Include_Children : in Boolean; Include_RHS_Index : in Boolean := False) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin if Include_Children and N.Label = Nonterm then Result := +Image (N.ID, Descriptor) & '_' & Trimmed_Image (N.RHS_Index) & ": "; end if; case N.Label is when Shared_Terminal => Result := Result & (+Token_Index'Image (N.Terminal)) & ":"; when Virtual_Identifier => Result := Result & (+Identifier_Index'Image (N.Identifier)) & ";"; when others => null; end case; Result := Result & "(" & Image (N.ID, Descriptor) & (if Include_RHS_Index and N.Label = Nonterm then "_" & Trimmed_Image (N.RHS_Index) else "") & (if N.Byte_Region = Null_Buffer_Region then "" else ", " & Image (N.Byte_Region)) & ")"; if Include_Children and N.Label = Nonterm then Result := Result & " <= " & Image (Tree, N.Children, Descriptor); end if; return -Result; end Image; function Image (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; Descriptor : in WisiToken.Descriptor; Include_Children : in Boolean := False) return String is begin return Tree.Image ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node)), Descriptor, Include_Children); end Image; function Image (Tree : in Syntax_Trees.Tree; Nodes : in Valid_Node_Index_Array; Descriptor : in WisiToken.Descriptor) return String is use Ada.Strings.Unbounded; Result : Unbounded_String := +"("; Need_Comma : Boolean := False; begin for I in Nodes'Range loop Result := Result & (if Need_Comma then ", " else "") & Tree.Image (Nodes (I), Descriptor, Include_Children => False); Need_Comma := True; end loop; Result := Result & ")"; return -Result; end Image; function Image (Item : in Node_Sets.Vector; Inverted : in Boolean := False) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin for I in Item.First_Index .. Item.Last_Index loop if (if Inverted then not Item (I) else Item (I)) then Result := Result & Node_Index'Image (I); end if; end loop; return -Result; end Image; procedure Initialize (Branched_Tree : in out Syntax_Trees.Tree; Shared_Tree : in Base_Tree_Access; Flush : in Boolean) is begin Branched_Tree := (Ada.Finalization.Controlled with Shared_Tree => Shared_Tree, Last_Shared_Node => Shared_Tree.Nodes.Last_Index, Branched_Nodes => <>, Flush => Flush, Root => <>); end Initialize; function Is_Empty (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean is begin if Node <= Tree.Last_Shared_Node then return Tree.Shared_Tree.Nodes (Node).Byte_Region = Null_Buffer_Region; else return Tree.Branched_Nodes (Node).Byte_Region = Null_Buffer_Region; end if; end Is_Empty; function Is_Nonterm (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean is begin if Node <= Tree.Last_Shared_Node then return Tree.Shared_Tree.Nodes (Node).Label = Nonterm; else return Tree.Branched_Nodes (Node).Label = Nonterm; end if; end Is_Nonterm; function Is_Terminal (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean is begin if Node <= Tree.Last_Shared_Node then return Tree.Shared_Tree.Nodes (Node).Label = Shared_Terminal; else return Tree.Branched_Nodes (Node).Label = Shared_Terminal; end if; end Is_Terminal; function Is_Virtual (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean is function Compute (N : in Syntax_Trees.Node) return Boolean is begin return N.Label = Virtual_Terminal or (N.Label = Nonterm and then N.Virtual); end Compute; begin if Node <= Tree.Last_Shared_Node then return Compute (Tree.Shared_Tree.Nodes (Node)); else return Compute (Tree.Branched_Nodes (Node)); end if; end Is_Virtual; function Is_Virtual_Identifier (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean is begin return (if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node).Label = Virtual_Identifier else Tree.Branched_Nodes (Node).Label = Virtual_Identifier); end Is_Virtual_Identifier; function Label (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Node_Label is begin if Node <= Tree.Last_Shared_Node then return Tree.Shared_Tree.Nodes (Node).Label; else return Tree.Branched_Nodes (Node).Label; end if; end Label; function Last_Index (Tree : in Syntax_Trees.Tree) return Node_Index is begin return (if Tree.Flush then Tree.Shared_Tree.Nodes.Last_Index else Tree.Branched_Nodes.Last_Index); end Last_Index; function Min (Item : in Valid_Node_Index_Array) return Valid_Node_Index is Result : Node_Index := Item (Item'First); begin for I in Item'Range loop if Item (I) < Result then Result := Item (I); end if; end loop; return Result; end Min; function Min_Descendant (Nodes : in Node_Arrays.Vector; Node : in Valid_Node_Index) return Valid_Node_Index is N : Syntax_Trees.Node renames Nodes (Node); begin case N.Label is when Shared_Terminal | Virtual_Terminal | Virtual_Identifier => return Node; when Nonterm => declare Min : Node_Index := Node; begin for C of N.Children loop Min := Node_Index'Min (Min, Min_Descendant (Nodes, C)); end loop; return Min; end; end case; end Min_Descendant; function Min_Terminal_Index (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Base_Token_Index is function Compute (N : in Syntax_Trees.Node) return Base_Token_Index is begin return (case N.Label is when Shared_Terminal => N.Terminal, when Virtual_Terminal | Virtual_Identifier => Invalid_Token_Index, when Nonterm => N.Min_Terminal_Index); end Compute; begin if Node <= Tree.Last_Shared_Node then return Compute (Tree.Shared_Tree.Nodes (Node)); else return Compute (Tree.Branched_Nodes (Node)); end if; end Min_Terminal_Index; function Max_Terminal_Index (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Base_Token_Index is function Compute (N : in Syntax_Trees.Node) return Base_Token_Index is begin return (case N.Label is when Shared_Terminal => N.Terminal, when Virtual_Terminal | Virtual_Identifier => Invalid_Token_Index, when Nonterm => N.Max_Terminal_Index); end Compute; begin if Node <= Tree.Last_Shared_Node then return Compute (Tree.Shared_Tree.Nodes (Node)); else return Compute (Tree.Branched_Nodes (Node)); end if; end Max_Terminal_Index; procedure Move_Branch_Point (Tree : in out Syntax_Trees.Tree; Required_Node : in Valid_Node_Index) is begin -- Note that this preserves all stored indices in Branched_Nodes. Tree.Branched_Nodes.Prepend (Tree.Shared_Tree.Nodes, Required_Node, Tree.Last_Shared_Node); Tree.Last_Shared_Node := Required_Node - 1; end Move_Branch_Point; function Parent (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; Count : in Positive := 1) return Node_Index is Result : Node_Index := Node; N : Natural := 0; begin loop if Result <= Tree.Last_Shared_Node then Result := Tree.Shared_Tree.Nodes (Result).Parent; else Result := Tree.Branched_Nodes (Result).Parent; end if; N := N + 1; exit when N = Count or Result = Invalid_Node_Index; end loop; return Result; end Parent; procedure Print_Tree (Tree : in Syntax_Trees.Tree; Descriptor : in WisiToken.Descriptor; Root : in Node_Index := Invalid_Node_Index) is use Ada.Text_IO; Node_Printed : Node_Sets.Vector; procedure Print_Node (Node : in Valid_Node_Index; Level : in Integer) is function Image is new SAL.Generic_Decimal_Image (Node_Index); N : Syntax_Trees.Node renames Tree.Shared_Tree.Nodes (Node); begin if Node_Printed (Node) then -- This does not catch all possible tree edit errors, but it does -- catch circles. raise SAL.Programmer_Error with "Print_Tree: invalid tree" & Node_Index'Image (Node); else Node_Printed (Node) := True; end if; Put (Image (Node, Width => 4) & ": "); for I in 1 .. Level loop Put ("| "); end loop; Put_Line (Image (Tree, N, Descriptor, Include_Children => False, Include_RHS_Index => True)); if N.Label = Nonterm then for Child of N.Children loop Print_Node (Child, Level + 1); end loop; end if; end Print_Node; begin Node_Printed.Set_First_Last (Tree.First_Index, Tree.Last_Index); Print_Node ((if Root = Invalid_Node_Index then Tree.Root else Root), 0); end Print_Tree; function Process_Tree (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; Visit_Parent : in Visit_Parent_Mode; Process_Node : access function (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Boolean) return Boolean is function Compute (N : in Syntax_Trees.Node) return Boolean is begin if Visit_Parent = Before then if not Process_Node (Tree, Node) then return False; end if; end if; if N.Label = Nonterm then for Child of N.Children loop if not Process_Tree (Tree, Child, Visit_Parent, Process_Node) then return False; end if; end loop; end if; if Visit_Parent = After then return Process_Node (Tree, Node); else return True; end if; end Compute; begin if Node <= Tree.Last_Shared_Node then return Compute (Tree.Shared_Tree.Nodes (Node)); else return Compute (Tree.Branched_Nodes (Node)); end if; end Process_Tree; procedure Process_Tree (Tree : in out Syntax_Trees.Tree; Node : in Valid_Node_Index; Process_Node : access procedure (Tree : in out Syntax_Trees.Tree; Node : in Valid_Node_Index)) is procedure Compute (N : in Syntax_Trees.Node) is begin if N.Label = Nonterm then for Child of N.Children loop Process_Tree (Tree, Child, Process_Node); end loop; end if; Process_Node (Tree, Node); end Compute; begin if Node <= Tree.Last_Shared_Node then Compute (Tree.Shared_Tree.Nodes (Node)); else Compute (Tree.Branched_Nodes (Node)); end if; end Process_Tree; procedure Process_Tree (Tree : in out Syntax_Trees.Tree; Process_Node : access procedure (Tree : in out Syntax_Trees.Tree; Node : in Valid_Node_Index); Root : in Node_Index := Invalid_Node_Index) is begin if Root = Invalid_Node_Index and Tree.Root = Invalid_Node_Index then raise SAL.Programmer_Error with "Tree.Root not set"; end if; Tree.Shared_Tree.Traversing := True; Process_Tree (Tree, (if Root = Invalid_Node_Index then Tree.Root else Root), Process_Node); Tree.Shared_Tree.Traversing := False; exception when others => Tree.Shared_Tree.Traversing := False; raise; end Process_Tree; function Production_ID (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return WisiToken.Production_ID is begin return (if Node <= Tree.Last_Shared_Node then (Tree.Shared_Tree.Nodes (Node).ID, Tree.Shared_Tree.Nodes (Node).RHS_Index) else (Tree.Branched_Nodes (Node).ID, Tree.Branched_Nodes (Node).RHS_Index)); end Production_ID; function RHS_Index (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Natural is begin return (if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node).RHS_Index else Tree.Branched_Nodes (Node).RHS_Index); end RHS_Index; procedure Set_Node_Identifier (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index; ID : in Token_ID; Identifier : in Identifier_Index) is Current : constant Syntax_Trees.Node := Tree.Shared_Tree.Nodes (Node); begin Tree.Shared_Tree.Nodes.Replace_Element (Node, (Label => Virtual_Identifier, ID => ID, Identifier => Identifier, Byte_Region => Current.Byte_Region, Parent => Current.Parent, State => Unknown_State)); end Set_Node_Identifier; procedure Set_Root (Tree : in out Syntax_Trees.Tree; Root : in Valid_Node_Index) is begin Tree.Root := Root; end Set_Root; function Root (Tree : in Syntax_Trees.Tree) return Node_Index is begin if Tree.Root /= Invalid_Node_Index then return Tree.Root; else if Tree.Flush then return Tree.Shared_Tree.Nodes.Last_Index; else return Tree.Branched_Nodes.Last_Index; end if; end if; end Root; function Same_Token (Tree_1 : in Syntax_Trees.Tree'Class; Index_1 : in Valid_Node_Index; Tree_2 : in Syntax_Trees.Tree'Class; Index_2 : in Valid_Node_Index) return Boolean is function Compute (N_1, N_2 : in Syntax_Trees.Node) return Boolean is begin return N_1.Label = N_2.Label and N_1.ID = N_2.ID and N_1.Byte_Region = N_2.Byte_Region; end Compute; begin return Compute ((if Index_1 <= Tree_1.Last_Shared_Node then Tree_1.Shared_Tree.Nodes (Index_1) else Tree_1.Branched_Nodes (Index_1)), (if Index_2 <= Tree_2.Last_Shared_Node then Tree_2.Shared_Tree.Nodes (Index_2) else Tree_2.Branched_Nodes (Index_2))); end Same_Token; procedure Set_Augmented (Tree : in out Syntax_Trees.Tree; Node : in Valid_Node_Index; Value : in Base_Token_Class_Access) is begin if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node).Augmented := Value; else Tree.Branched_Nodes (Node).Augmented := Value; end if; Tree.Shared_Tree.Augmented_Present := True; end Set_Augmented; procedure Set_Children (Nodes : in out Node_Arrays.Vector; Parent : in Valid_Node_Index; Children : in Valid_Node_Index_Array) is use all type SAL.Base_Peek_Type; N : Nonterm_Node renames Nodes (Parent); J : Positive_Index_Type := Positive_Index_Type'First; Min_Terminal_Index_Set : Boolean := False; begin N.Children.Set_Length (Children'Length); for I in Children'Range loop N.Children (J) := Children (I); declare K : Node renames Nodes (Children (I)); begin K.Parent := Parent; N.Virtual := N.Virtual or (case K.Label is when Shared_Terminal => False, when Virtual_Terminal | Virtual_Identifier => True, when Nonterm => K.Virtual); if N.Byte_Region.First > K.Byte_Region.First then N.Byte_Region.First := K.Byte_Region.First; end if; if N.Byte_Region.Last < K.Byte_Region.Last then N.Byte_Region.Last := K.Byte_Region.Last; end if; if not Min_Terminal_Index_Set then case K.Label is when Shared_Terminal => Min_Terminal_Index_Set := True; N.Min_Terminal_Index := K.Terminal; when Virtual_Terminal | Virtual_Identifier => null; when Nonterm => if K.Min_Terminal_Index /= Invalid_Token_Index then -- not an empty nonterm Min_Terminal_Index_Set := True; N.Min_Terminal_Index := K.Min_Terminal_Index; end if; end case; end if; case K.Label is when Shared_Terminal => if N.Max_Terminal_Index < K.Terminal then N.Max_Terminal_Index := K.Terminal; end if; when Virtual_Terminal | Virtual_Identifier => null; when Nonterm => if K.Max_Terminal_Index /= Invalid_Token_Index and then -- not an empty nonterm N.Max_Terminal_Index < K.Max_Terminal_Index then N.Max_Terminal_Index := K.Max_Terminal_Index; end if; end case; end; J := J + 1; end loop; end Set_Children; procedure Set_Children (Tree : in out Syntax_Trees.Tree; Node : in Valid_Node_Index; New_ID : in WisiToken.Production_ID; Children : in Valid_Node_Index_Array) is use all type SAL.Base_Peek_Type; Parent_Node : Syntax_Trees.Node renames Tree.Shared_Tree.Nodes (Node); J : Positive_Index_Type := Positive_Index_Type'First; begin Parent_Node.ID := New_ID.LHS; Parent_Node.RHS_Index := New_ID.RHS; Parent_Node.Action := null; Parent_Node.Children.Set_Length (Children'Length); for I in Children'Range loop -- We don't update Min/Max_terminal_index; we assume Set_Children is -- only called after parsing is done, so they are no longer needed. Parent_Node.Children (J) := Children (I); Tree.Shared_Tree.Nodes (Children (I)).Parent := Node; J := J + 1; end loop; end Set_Children; procedure Set_State (Tree : in out Syntax_Trees.Tree; Node : in Valid_Node_Index; State : in State_Index) is begin if Tree.Flush then Tree.Shared_Tree.Nodes (Node).State := State; else if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node).State := State; else Tree.Branched_Nodes (Node).State := State; end if; end if; end Set_State; procedure Set_Flush_False (Tree : in out Syntax_Trees.Tree) is begin Tree.Flush := False; Tree.Branched_Nodes.Set_First (Tree.Last_Shared_Node + 1); end Set_Flush_False; procedure Set_Name_Region (Tree : in out Syntax_Trees.Tree; Node : in Valid_Node_Index; Region : in Buffer_Region) is begin if Tree.Flush then Tree.Shared_Tree.Nodes (Node).Name := Region; else if Node <= Tree.Last_Shared_Node then Move_Branch_Point (Tree, Node); end if; Tree.Branched_Nodes (Node).Name := Region; end if; end Set_Name_Region; function Terminal (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Base_Token_Index is begin if Node <= Tree.Last_Shared_Node then return Tree.Shared_Tree.Nodes (Node).Terminal; else return Tree.Branched_Nodes (Node).Terminal; end if; end Terminal; function Traversing (Tree : in Syntax_Trees.Tree) return Boolean is begin return Tree.Shared_Tree.Traversing; end Traversing; function Recover_Token (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return WisiToken.Recover_Token is function Compute (N : Syntax_Trees.Node) return WisiToken.Recover_Token is begin case N.Label is when Shared_Terminal => return (ID => N.ID, Byte_Region => N.Byte_Region, Min_Terminal_Index => N.Terminal, Name => Null_Buffer_Region, Virtual => False); when Virtual_Terminal | Virtual_Identifier => return (ID => N.ID, Byte_Region => Null_Buffer_Region, Min_Terminal_Index => Invalid_Token_Index, Name => Null_Buffer_Region, Virtual => True); when Nonterm => return (ID => N.ID, Byte_Region => N.Byte_Region, Min_Terminal_Index => N.Min_Terminal_Index, Name => N.Name, Virtual => N.Virtual); end case; end Compute; begin return Compute ((if Node <= Tree.Last_Shared_Node then Tree.Shared_Tree.Nodes (Node) else Tree.Branched_Nodes (Node))); end Recover_Token; function Recover_Token_Array (Tree : in Syntax_Trees.Tree; Nodes : in Valid_Node_Index_Array) return WisiToken.Recover_Token_Array is begin return Result : WisiToken.Recover_Token_Array (Nodes'First .. Nodes'Last) do for I in Result'Range loop Result (I) := Tree.Recover_Token (Nodes (I)); end loop; end return; end Recover_Token_Array; function State (Tree : in Syntax_Trees.Tree; Node : in Valid_Node_Index) return Unknown_State_Index is begin if Node <= Tree.Last_Shared_Node then return Tree.Shared_Tree.Nodes (Node).State; else return Tree.Branched_Nodes (Node).State; end if; end State; end WisiToken.Syntax_Trees;
with Blinker;use Blinker; with Text_IO; with Ada.Real_Time;use Ada.Real_Time; with Control; package body Bcontrol is protected body Command_Access is procedure Send( Cmd: Command_Type) is begin New_Command := False; if Command /= Cmd then New_Command := True; Command := Cmd; end if; end Send; entry Receive(Cmd : out Command_Type) when New_Command is begin Cmd := Command; end; end Command_Access; Left_Blinker : Blinker.Blinker_Type; --Right_Blinker: Blinker.Blinker_Type(Blinker.R); --Warn_Blinker: Blinker.Blinker_Type(Blinker.E); Blinker_Control : Blinker_Control_Type; Stim_Control : Stim_Control_Type; task body Blinker_Control_Type is Blinker_Left_Started : Boolean := False; Blinker_Right_Started : Boolean := False; Blinker_Warn_Started : Boolean := False; Next_Time : Time := Clock + Milliseconds(100); Cmd : Bcontrol.Command_Type := BLE; Cmd_To : Blinker.Command_To_Type; begin loop Command.Receive(Cmd => Cmd); case Cmd is when BLS => Cmd_To.Cmd := START; if not Blinker_Left_Started then Cmd_To.Receiver := Blinker.L; Protected_Command.Send(Cmd_To); --Text_Io.Put_Line("execute Command " & String(Cmd.All)); Blinker_Left_Started := True; end if; when BLE => Cmd_To.Cmd := Stop; if Blinker_Left_Started then Cmd_To.Receiver := Blinker.L; Protected_Command.Send(Cmd_To); --Text_Io.Put_Line("execute Command " & String(Cmd.All)); Blinker_Left_Started := False; end if; if Blinker_Right_Started then Cmd_To.Receiver := Blinker.R; Protected_Command.Send(Cmd_To); Blinker_Right_Started := False; end if; if Blinker_Warn_Started then Cmd_To.Receiver := Blinker.E; Protected_Command.Send(Cmd_To); --Text_Io.Put_Line("execute Command " & String(Cmd.All)); Blinker_Warn_Started := False; end if; when BRS => Cmd_To.Cmd := START; if not Blinker_Right_Started then Cmd_To.Receiver := Blinker.R; Protected_Command.Send(Cmd_To); --Text_Io.Put_Line("execute Command " & String(Cmd.All)); Blinker_Right_Started := True; end if; when EMS => Cmd_To.Cmd := START; if not Blinker_Warn_Started then Cmd_To.Receiver := Blinker.E; Protected_Command.Send(Cmd_To); --Text_Io.Put_Line("execute Command " & String(Cmd.All)); Blinker_Warn_Started := True; end if; when others => null; end case; delay until Next_Time; Next_Time := Next_Time + Milliseconds(100); end loop; end Blinker_Control_Type; task body Stim_Control_Type is Next_Time : Time := Clock; c :Command_Type := stp; function Process_Command(cmd_par : BControl.Command_Type) return Boolean is begin Command.Receive(c); if c = STP then Command.Send(BLE); return TRUE; end if; -- Blinker_Control.Blink_Left; Next_Time := Next_Time + Seconds(3); Command.Send( cmd_par ); delay until Next_Time; return FALSE; end Process_Command; begin loop Command.Receive(c); if c = STR then loop exit when Process_Command(BLS); exit when Process_Command(BLE); exit when Process_Command(BRS); exit when Process_Command(BLE); exit when Process_Command(EMS); exit when Process_Command(BLE); end loop; end if; Next_Time := Clock + Seconds(1); delay until Next_Time; end loop; end Stim_Control_Type; end Bcontrol;
package body serial is procedure Initialize_UART_GPIO is begin Enable_Clock (USART_1); Enable_Clock (RX_Pin & TX_Pin); Configure_IO (RX_Pin & TX_Pin, (Mode => Mode_AF, AF => GPIO_AF_USART1_7, Resistors => Pull_Up, AF_Speed => Speed_50MHz, AF_Output_Type => Push_Pull)); end Initialize_UART_GPIO; procedure Initialize (baud : UInt32) is begin Initialize_UART_GPIO; Disable (USART_1); Set_Baud_Rate (USART_1, baud); Set_Mode (USART_1, Tx_Rx_Mode); Set_Stop_Bits (USART_1, Stopbits_1); Set_Word_Length (USART_1, Word_Length_8); Set_Parity (USART_1, No_Parity); Set_Flow_Control (USART_1, No_Flow_Control); Enable (USART_1); end Initialize; procedure Await_Send_Ready (This : USART) is begin loop exit when Tx_Ready (This); end loop; end Await_Send_Ready; procedure Await_Read_Ready (This : USART) is begin loop exit when Rx_Ready (This); end loop; end Await_Read_Ready; procedure Serial_Print (Data : String) is begin for i in data'Range loop Await_Send_Ready (USART_1); Transmit (USART_1, UInt9 (Character'Pos(Data(i)))); end loop; end Serial_Print; function Serial_Read return UInt9 is data : UInt9; begin Await_Read_Ready (USART_1); Receive(USART_1,data); return data; end Serial_Read; end serial;
procedure Discriminated_Record is TYPE REC2 (I : INTEGER) IS RECORD CASE I IS WHEN 1 => null; WHEN OTHERS => A2 : integer; A3 : long_integer; END CASE; END RECORD; R2 : REC2(2); begin null; end Discriminated_Record;
-------------------------------------------------------------------------------- -- * Spec name dft.ads -- * Project name dfttest -- * -- * Version 1.0 -- * Last update 11/9/08 -- * -- * Created by Adrian Hoe on 11/9/08. -- * Copyright (c) 2008 AdaStar Informatics http://adastarinformatics.com -- * All rights reserved. -- * -------------------------------------------------------------------------------- with Ada.Text_IO; with Ada.Numerics; with Ada.Numerics.Generic_Elementary_Functions; with Ada.Numerics.Generic_Complex_Types; use Ada.Numerics; package Dft is type Value_Type is new Float; type Value_Vector is array ( Positive range <> ) of Value_Type; package T_IO renames Ada.Text_IO; package F_IO is new Ada.Text_IO.Float_IO ( Value_Type ); package Complex_Functions is new Ada.Numerics.Generic_Elementary_Functions ( Value_Type ); package Complex_Types is new Ada.Numerics.Generic_Complex_Types ( Value_Type ); use Complex_Functions; use Complex_Types; type Complex_Vector is array ( Positive range <> ) of Complex; procedure Compute ( Input : in Value_Vector; Output : out Complex_Vector); end Dft;
with Ada.Text_IO; use Ada.Text_IO; procedure Specifier_Et_Tester is -- Calculer le plus grand commun diviseur de deux entiers strictement -- positifs. -- Paramètres : -- A : in Entier -- B : in Entier -- Retour : Entier -- le pgcd de A et B -- Nécessite : -- A > 0 -- B > 0 -- Assure : -- Pgcd'Result >= 1 -- A mod Pgcd'Résultat = 0 -- le pgcd divise A -- B mod Pgcd'Résultat = 0 -- le pgcd divise B -- -- c'est le plus grand des entiers qui divisent A et B -- // mais on ne sait pas l'exprimer simplement -- Exemples : voir Tester_Pgcd -- Efficacité : faible car on utilise une version naïve de l'algorithme -- d'Euclide. function Pgcd (A, B : in Integer) return Integer with Pre => A > 0 and B > 0, Post => Pgcd'Result >= 1 and A mod Pgcd'Result = 0 -- Le Pgcd divise A and B mod Pgcd'Result = 0 -- Le Pgcd divise B is L_A, L_B: Integer; -- variables correspondant à A et B -- A et B étant en in, on ne peut pas les modifier dans la -- fonction. Or pour appliquer l'algortihme d'Euclide, il faut -- retrancher le plus petit au plus grand jusqu'à avoir deux -- nombres égaux. Nous passons donc par des variables locales et -- utilisons le nom des paramètres formels préfixés par 'L_'. begin L_A := A; L_B := B; while L_A /= L_B loop -- soustraire au plus grand le plus petit if L_A > L_B then L_A := L_A - L_B; else L_B := L_B - L_A; end if; end loop; pragma Assert (L_A = L_B); -- la condition de sortie de boucle. return L_A; end Pgcd; -- Exemple d'utilisation du Pgcd. -- Est-ce que le corps de cette procédure est correct ? Pourquoi ? -- Que donne son exécution ? -- Non le corps de cette procédure n'est pas correct car A ET B doivent -- etre strictement positifs. -- Ça va boucler à l'infini lors de l'éxecution procedure Utiliser_Pgcd is Resultat: Integer; begin Resultat := Pgcd (0, 10); Put ("Pgcd (0, 10) = " & Integer'Image(Resultat)); end Utiliser_Pgcd; -- Permuter deux entiers. -- Paramètres : -- A, B : in out Entier -- les deux entiers à permuter -- Nécessite : Néant -- Assure : -- A = B'Avant et B = A'Avant -- les valeurs de A et B sont bien permutées procedure Permuter (A, B: in out Integer) with Post => A = B'Old and B = A'Old is Copie_A : Integer; begin Copie_A := A; A := B; B := Copie_A; end Permuter; -- Procédure de test de Pgcd. -- -- Parce que c'est une procédure de test, elle n'a pas de paramètre, -- -- pas de type de retour, pas de précondition, pas de postcondition. procedure Tester_Pgcd is begin pragma Assert (4 = Pgcd (4, 4)); -- A = B pragma Assert (2 = Pgcd (10, 16)); -- A < B pragma Assert (1 = Pgcd (21, 10)); -- A > B pragma Assert (3 = Pgcd (105, 147)); -- un autre end Tester_Pgcd; -- Procédure de test pour mettre en évidence la faible efficacité de Pgcd. procedure Tester_Performance_Pgcd is begin pragma Assert (1 = Pgcd (1, 10 ** 9)); -- lent ! end Tester_Performance_Pgcd; -- Procédure de test de Permuter. procedure Tester_Permuter is N1, N2: Integer; begin -- initialiser les données du test N1 := 5; N2 := 18; -- lancer la procédure à tester Permuter (N1, N2); -- contrôler que la procédure a eu l'effet escompté pragma Assert (18 = N1); pragma Assert (5 = N2); end Tester_Permuter; begin --Utiliser_Pgcd; -- lancer les programmes de test. Tester_Pgcd; Tester_Performance_Pgcd; Tester_Permuter; Put_Line ("Fini."); end Specifier_Et_Tester;
------------------------------------------------------------------------------- -- -- FIXED TYPES -- -- Fixed_Long & Fixed_Sat_Long definitions -- -- The MIT License (MIT) -- -- Copyright (c) 2015 Gustavo A. Hoffmann -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to -- deal in the Software without restriction, including without limitation the -- rights to use, copy, modify, merge, publish, distribute, sublicense, and / -- or sell copies of the Software, and to permit persons to whom the Software -- is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -- IN THE SOFTWARE. ------------------------------------------------------------------------------- with Ada.Unchecked_Conversion; package Fixed_Types.Long is -- Fixed_Depth : constant Positive := 32; type Fixed_Long is delta 1.0 / 2.0 ** (Fixed_Depth - 1) range -1.0 .. 1.0 with Size => Fixed_Depth; type Fixed_Sat_Long is new Fixed_Long; pragma Suppress (Overflow_Check, on => Fixed_Long); pragma Suppress (Range_Check, on => Fixed_Long); -- pragma Suppress (All_checks, on => Fixed_Long); type Fixed_Integer_Long is range -2**(Fixed_Depth - 1) .. 2**(Fixed_Depth - 1) - 1 with Size => Fixed_Depth; type Modular_Long is mod 2 ** Fixed_Depth with Size => Fixed_Depth; function To_Fixed_Integer_Long is new Ada.Unchecked_Conversion (Fixed_Long, Fixed_Integer_Long); function To_Fixed_Integer_Long is new Ada.Unchecked_Conversion (Fixed_Sat_Long, Fixed_Integer_Long); function To_Fixed_Long is new Ada.Unchecked_Conversion (Fixed_Integer_Long, Fixed_Long); function To_Fixed_Sat_Long is new Ada.Unchecked_Conversion (Fixed_Integer_Long, Fixed_Sat_Long); function Fixed_Long_To_Mod_Long is new Ada.Unchecked_Conversion (Fixed_Long, Modular_Long); function Fixed_Sat_Long_To_Mod_Long is new Ada.Unchecked_Conversion (Fixed_Sat_Long, Modular_Long); overriding function "abs" (A : Fixed_Sat_Long) return Fixed_Sat_Long; overriding function "+" (A, B : Fixed_Sat_Long) return Fixed_Sat_Long; overriding function "-" (A, B : Fixed_Sat_Long) return Fixed_Sat_Long; overriding function "-" (A : Fixed_Sat_Long) return Fixed_Sat_Long; not overriding function "*" (A, B : Fixed_Sat_Long) return Fixed_Sat_Long; overriding function "*" (A : Fixed_Sat_Long; B : Integer) return Fixed_Sat_Long; end Fixed_Types.Long;
-- -- Copyright 2018 The wookey project team <wookey@ssi.gouv.fr> -- - Ryad Benadjila -- - Arnauld Michelizza -- - Mathieu Renard -- - Philippe Thierry -- - Philippe Trebuchet -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- with ada.unchecked_conversion; with ewok.tasks; use ewok.tasks; with ewok.tasks.debug; with ewok.tasks_shared; use ewok.tasks_shared; with ewok.devices_shared; use ewok.devices_shared; with ewok.sched; with ewok.debug; with ewok.interrupts; with soc.interrupts; with m4.scb; package body ewok.mpu.handler with spark_mode => off is function memory_fault_handler (frame_a : t_stack_frame_access) return t_stack_frame_access is #if not CONFIG_KERNEL_PANIC_FREEZE new_frame_a : t_stack_frame_access #end if; begin if m4.scb.SCB.CFSR.MMFSR.MMARVALID then pragma DEBUG (debug.log (debug.ERROR, "MPU: MMFAR.ADDRESS = " & system_address'image (m4.scb.SCB.MMFAR.ADDRESS))); end if; if m4.scb.SCB.CFSR.MMFSR.MLSPERR then pragma DEBUG (debug.log (debug.ERROR, "MPU: MemManage fault during floating-point lazy state preservation")); end if; if m4.scb.SCB.CFSR.MMFSR.MSTKERR then pragma DEBUG (debug.log (debug.ERROR, "MPU: stacking for an exception entry has caused access violation")); end if; if m4.scb.SCB.CFSR.MMFSR.MUNSTKERR then pragma DEBUG (debug.log (debug.ERROR, "MPU: unstack for an exception return has caused access violation")); end if; if m4.scb.SCB.CFSR.MMFSR.DACCVIOL then pragma DEBUG (debug.log (debug.ERROR, "MPU: the processor attempted a load or store at a location that does not permit the operation")); end if; if m4.scb.SCB.CFSR.MMFSR.IACCVIOL then pragma DEBUG (debug.log (debug.ERROR, "MPU: the processor attempted an instruction fetch from a location that does not permit execution")); end if; pragma DEBUG (ewok.tasks.debug.crashdump (frame_a)); -- On memory fault, the task is not scheduled anymore ewok.tasks.set_state (ewok.sched.get_current, TASK_MODE_MAINTHREAD, ewok.tasks.TASK_STATE_FAULT); #if CONFIG_KERNEL_PANIC_FREEZE debug.panic ("Memory fault!"); return frame_a; #else new_frame_a := ewok.sched.do_schedule (frame_a); return new_frame_a; #end if; end memory_fault_handler; procedure init is ok : boolean; begin ewok.interrupts.set_task_switching_handler (soc.interrupts.INT_MEMMANAGE, memory_fault_handler'access, ID_KERNEL, ID_DEV_UNUSED, ok); if not ok then raise program_error; end if; end init; end ewok.mpu.handler;
with Ada.Text_IO; with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; procedure Euler19 is Count : Natural := 0; begin for Year in 1901 .. 2000 loop for Month in 1 .. 12 loop if Day_Of_Week(Time_Of(Year, Month, 1)) = Sunday then Count := Count + 1; end if; end loop; end loop; Ada.Text_IO.Put_Line(Integer'Image(Count)); end;
with Ada.Numerics; with Ada.Numerics.Generic_Complex_Elementary_Functions; function Generic_FFT (X : Complex_Vector) return Complex_Vector is package Complex_Elementary_Functions is new Ada.Numerics.Generic_Complex_Elementary_Functions (Complex_Arrays.Complex_Types); use Ada.Numerics; use Complex_Elementary_Functions; use Complex_Arrays.Complex_Types; function FFT (X : Complex_Vector; N, S : Positive) return Complex_Vector is begin if N = 1 then return (1..1 => X (X'First)); else declare F : constant Complex := exp (Pi * j / Real_Arrays.Real (N/2)); Even : Complex_Vector := FFT (X, N/2, 2*S); Odd : Complex_Vector := FFT (X (X'First + S..X'Last), N/2, 2*S); begin for K in 0..N/2 - 1 loop declare T : constant Complex := Odd (Odd'First + K) / F ** K; begin Odd (Odd'First + K) := Even (Even'First + K) - T; Even (Even'First + K) := Even (Even'First + K) + T; end; end loop; return Even & Odd; end; end if; end FFT; begin return FFT (X, X'Length, 1); end Generic_FFT;
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- Copyright (C) 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Security.Controllers.Roles is -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- one of the role defined in the <b>Handler</b>. -- ------------------------------ overriding function Has_Permission (Handler : in Role_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Permission); P : constant Security.Principal_Access := Context.Get_User_Principal; Roles : Security.Policies.Roles.Role_Map; begin if P /= null then -- If the principal has some roles, get them. if P.all in Policies.Roles.Role_Principal_Context'Class then Roles := Policies.Roles.Role_Principal_Context'Class (P.all).Get_Roles; else return False; end if; for I in Handler.Roles'Range loop if Roles (Handler.Roles (I)) then return True; end if; end loop; end if; return False; end Has_Permission; end Security.Controllers.Roles;
with EU_Projects.Projects; with Ada.Strings.Bounded; with Latex_Writer; use Latex_Writer; package Project_Processor.Processors.LaTeX is type Processor_Type is new Abstract_Processor with private; overriding function Create (Params : not null access Processor_Parameter) return Processor_Type; overriding procedure Process (Processor : Processor_Type; Input : EU_Projects.Projects.Project_Descriptor); private package Bounded_Filenames is new Ada.Strings.Bounded.Generic_Bounded_Length (2048); subtype Bounded_Filename is Bounded_Filenames.Bounded_String; function Bless (X : String) return Bounded_Filename is (Bounded_Filenames.To_Bounded_String (X)); function To_S (X : Bounded_Filename) return String is (Bounded_Filenames.To_String (X)); type Target_Class is (File, Standard_Output, None); type Target_Spec (Class : Target_Class := File) is record case Class is when None | Standard_Output => null; when File => Filename : Bounded_Filename; end case; end record; type GANTT_Parameters is record Font_Size : Latex_Length; Textwidth : Latex_Length; Pre_Label_Skip : Em_Length; Post_Label_Skip : Em_Length; Header_Skip : Em_Length; Tick_Length : Em_Length; Task_Indent : Natural; Show_Deliverables : Boolean; end record; type Processor_Type is new Abstract_Processor with record Wp_Target : Target_Spec; Wp_Summary_Target : Target_Spec; Partner_Target : Target_Spec; Deliverable_Target : Target_Spec; Deliv_Summary_Target : Target_Spec; Deliv_Compact_Summary_Target : Target_Spec; Milestone_Target : Target_Spec; Effort_Summary_Target : Target_Spec; Gantt_Target : Target_Spec; Gantt_Style : GANTT_Parameters; end record; end Project_Processor.Processors.LaTeX;
with ZMQ.Sockets; with ZMQ.Contexts; with Ada.Text_IO; with GNAT.Sockets; procedure ZMQ.examples.prompt is ctx : aliased Contexts.Context; s : Sockets.Socket; begin ctx.Initialize (1); s.Initialize (ctx, Sockets.PUB); s.Connect ("tcp://localhost:5555"); Read_Loop : loop Ada.Text_IO.Put (">"); declare textbuf : constant String := Ada.Text_IO.Get_Line; begin exit Read_Loop when textbuf'Length = 0; s.Send ("hej" & ASCII.NUL & GNAT.Sockets.Host_Name & ":" & textbuf); delay 0.02; end; end loop Read_Loop; s.Send (END_MESSAGE); end ZMQ.Examples.prompt;
with Ada.Text_IO; use Ada.Text_IO; procedure discotheque is MAX_CHANSONS : constant Natural := 30; MAX_ALBUMS : constant Natural := 200; type T_Chanson is record titre : String (1..40); duree : Natural; end record; type T_Coll_Chansons is array (1..MAX_CHANSONS) of T_Chanson; type T_Album is record contenu : T_Coll_Chansons; nb_chanson : Natural; annee : Natural; titre, artiste : String (1..40); end record; type T_Genre is (G_Classique, G_Variete, G_Rap, G_Disco, G_Rock); type T_Tab_Albums is array (1..MAX_ALBUMS) of T_Album; type T_Coll_Albums is record les_albums : T_Tab_Albums; nb_album : Natural range 0..MAX_ALBUMS; end record; type T_Disco is array(T_Genre) of T_Coll_Albums; function duree_totale(a : in T_Album) return Natural is res : Natural := 0; begin for i in 1..a.nb_chanson loop res := res + a.contenu(i).duree; end loop; return res; end duree_totale; procedure afficher_album(a : in T_Album) is begin Put_Line("Titre : " & a.titre); for i in 1..a.nb_chanson loop Put_Line(" * " & a.contenu(i).titre); end loop; New_Line; end afficher_album; procedure ajouter_album(a : in T_Album; g : in T_Genre; d : in out T_Disco) is begin d(g).nb_album := d(g).nb_album + 1; d(g).les_albums(d(g).nb_album) := a; end ajouter_album; disco : T_Disco; begin Put_Line("bijour"); for g in T_Genre loop Put_Line(1); end loop; end discotheque;
with System.Storage_Pools; use System.Storage_Pools; with Ada.Finalization; use Ada.Finalization; package Opt57_Pkg is type GC_Pool is abstract new Root_Storage_Pool with null record; type Pinned (Pool : access GC_Pool'Class) is new Controlled with null record; procedure Finalize (X : in out Pinned); end Opt57_Pkg;
with Ada.Text_IO; with Ada.Directories; with Ada.Containers.Vectors; with Init_Project; with Blueprint; use Blueprint; with Ada.Command_Line; with Templates_Parser.Utils; package body Commands.Create is package IO renames Ada.Text_IO; package TT renames CLIC.TTY; package Dir renames Ada.Directories; use Ada.Directories; use Ada.Containers; ------------- -- Execute -- ------------- overriding procedure Execute (Cmd : in out Instance; Args : AAA.Strings.Vector) is begin if Args.Length > 0 then declare Path : constant String := Args.First_Element; ToDo : Action := Write; begin if Cmd.Dry_Run then IO.Put_Line (TT.Emph ("You specified the dry-run flag," & " no changes will be written.")); ToDo := DryRun; end if; if not Dir.Exists (Path) then if ToDo = Write then Dir.Create_Directory (Path); end if; end if; if Dir.Kind (Path) = Ada.Directories.Directory then Init_Project.Init (Path, Cmd.Blueprint.all, ToDo); else IO.Put_Line (TT.Error (Path & " exists and is not a directory.")); end if; end; else IO.Put_Line (TT.Error ( "Command requires a project name to be specified.")); end if; end Execute; -------------------- -- Setup_Switches -- -------------------- overriding procedure Setup_Switches (Cmd : in out Instance; Config : in out CLIC.Subcommand.Switches_Configuration) is use CLIC.Subcommand; begin Define_Switch (Config => Config, Output => Cmd.Blueprint'Access, Argument => "NAME", Long_Switch => "--source=", Help => "Selects a blueprint other than the default"); Define_Switch (Config, Cmd.Dry_Run'Access, "", "-dry-run", "Dry-run"); end Setup_Switches; end Commands.Create;
with Gtk.Button; use Gtk.Button; with Gtk.Combo_Box; use Gtk.Combo_Box; with Gtk.Handlers; with Gtk.Scale; use Gtk.Scale; with Gtk.Spin_Button; use Gtk.Spin_Button; with Gtk.Widget; use Gtk.Widget; package GA_Sine_Callbacks is package SpinHand is new Gtk.Handlers.Callback (Widget_Type => Gtk_Spin_Button_Record); procedure Frames_Per_Buffer_Callback (widget : access Gtk_Spin_Button_Record'Class); package CombHand is new Gtk.Handlers.Callback (Widget_Type => Gtk_Combo_Box_Record); procedure Sample_Rate_Callback (widget : access Gtk_Combo_Box_Record'Class); package ScaleHand is new Gtk.Handlers.Callback (Widget_Type => Gtk_Hscale_Record); procedure Amplitude_Callback (widget : access Gtk_Hscale_Record'Class); procedure Frequency_Callback (widget : access Gtk_Hscale_Record'Class); package SpinBtn is new Gtk.Handlers.Callback (Widget_Type => Gtk_Button_Record); procedure Start_Callback (widget : access Gtk_Widget_Record'Class); procedure Stop_Callback (widget : access Gtk_Widget_Record'Class); end GA_Sine_Callbacks;
-- Copyright (c) 2020 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- package body Program.Safe_Element_Visitors is procedure Visit (Self : in out Safe_Element_Visitor'Class; Element : not null access Program.Elements.Element'Class) is begin Element.Visit (Self); pragma Assert (not Self.Failed); end Visit; overriding procedure Pragma_Element (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Pragmas.Pragma_Access) is begin Self.Failed := True; end Pragma_Element; overriding procedure Defining_Identifier (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Defining_Identifiers .Defining_Identifier_Access) is begin Self.Failed := True; end Defining_Identifier; overriding procedure Defining_Character_Literal (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Defining_Character_Literals .Defining_Character_Literal_Access) is begin Self.Failed := True; end Defining_Character_Literal; overriding procedure Defining_Operator_Symbol (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Defining_Operator_Symbols .Defining_Operator_Symbol_Access) is begin Self.Failed := True; end Defining_Operator_Symbol; overriding procedure Defining_Expanded_Name (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Defining_Expanded_Names .Defining_Expanded_Name_Access) is begin Self.Failed := True; end Defining_Expanded_Name; overriding procedure Type_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Type_Declarations .Type_Declaration_Access) is begin Self.Failed := True; end Type_Declaration; overriding procedure Task_Type_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Task_Type_Declarations .Task_Type_Declaration_Access) is begin Self.Failed := True; end Task_Type_Declaration; overriding procedure Protected_Type_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Protected_Type_Declarations .Protected_Type_Declaration_Access) is begin Self.Failed := True; end Protected_Type_Declaration; overriding procedure Subtype_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Subtype_Declarations .Subtype_Declaration_Access) is begin Self.Failed := True; end Subtype_Declaration; overriding procedure Object_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Object_Declarations .Object_Declaration_Access) is begin Self.Failed := True; end Object_Declaration; overriding procedure Single_Task_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Single_Task_Declarations .Single_Task_Declaration_Access) is begin Self.Failed := True; end Single_Task_Declaration; overriding procedure Single_Protected_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Single_Protected_Declarations .Single_Protected_Declaration_Access) is begin Self.Failed := True; end Single_Protected_Declaration; overriding procedure Number_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Number_Declarations .Number_Declaration_Access) is begin Self.Failed := True; end Number_Declaration; overriding procedure Enumeration_Literal_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Enumeration_Literal_Specifications .Enumeration_Literal_Specification_Access) is begin Self.Failed := True; end Enumeration_Literal_Specification; overriding procedure Discriminant_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Discriminant_Specifications .Discriminant_Specification_Access) is begin Self.Failed := True; end Discriminant_Specification; overriding procedure Component_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Component_Declarations .Component_Declaration_Access) is begin Self.Failed := True; end Component_Declaration; overriding procedure Loop_Parameter_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Loop_Parameter_Specifications .Loop_Parameter_Specification_Access) is begin Self.Failed := True; end Loop_Parameter_Specification; overriding procedure Generalized_Iterator_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Generalized_Iterator_Specifications .Generalized_Iterator_Specification_Access) is begin Self.Failed := True; end Generalized_Iterator_Specification; overriding procedure Element_Iterator_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Element_Iterator_Specifications .Element_Iterator_Specification_Access) is begin Self.Failed := True; end Element_Iterator_Specification; overriding procedure Procedure_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Procedure_Declarations .Procedure_Declaration_Access) is begin Self.Failed := True; end Procedure_Declaration; overriding procedure Function_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Function_Declarations .Function_Declaration_Access) is begin Self.Failed := True; end Function_Declaration; overriding procedure Parameter_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Parameter_Specifications .Parameter_Specification_Access) is begin Self.Failed := True; end Parameter_Specification; overriding procedure Procedure_Body_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Procedure_Body_Declarations .Procedure_Body_Declaration_Access) is begin Self.Failed := True; end Procedure_Body_Declaration; overriding procedure Function_Body_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Function_Body_Declarations .Function_Body_Declaration_Access) is begin Self.Failed := True; end Function_Body_Declaration; overriding procedure Return_Object_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Return_Object_Specifications .Return_Object_Specification_Access) is begin Self.Failed := True; end Return_Object_Specification; overriding procedure Package_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Package_Declarations .Package_Declaration_Access) is begin Self.Failed := True; end Package_Declaration; overriding procedure Package_Body_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Package_Body_Declarations .Package_Body_Declaration_Access) is begin Self.Failed := True; end Package_Body_Declaration; overriding procedure Object_Renaming_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Object_Renaming_Declarations .Object_Renaming_Declaration_Access) is begin Self.Failed := True; end Object_Renaming_Declaration; overriding procedure Exception_Renaming_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Exception_Renaming_Declarations .Exception_Renaming_Declaration_Access) is begin Self.Failed := True; end Exception_Renaming_Declaration; overriding procedure Procedure_Renaming_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Procedure_Renaming_Declarations .Procedure_Renaming_Declaration_Access) is begin Self.Failed := True; end Procedure_Renaming_Declaration; overriding procedure Function_Renaming_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Function_Renaming_Declarations .Function_Renaming_Declaration_Access) is begin Self.Failed := True; end Function_Renaming_Declaration; overriding procedure Package_Renaming_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Package_Renaming_Declarations .Package_Renaming_Declaration_Access) is begin Self.Failed := True; end Package_Renaming_Declaration; overriding procedure Generic_Package_Renaming_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Generic_Package_Renaming_Declarations .Generic_Package_Renaming_Declaration_Access) is begin Self.Failed := True; end Generic_Package_Renaming_Declaration; overriding procedure Generic_Procedure_Renaming_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements .Generic_Procedure_Renaming_Declarations .Generic_Procedure_Renaming_Declaration_Access) is begin Self.Failed := True; end Generic_Procedure_Renaming_Declaration; overriding procedure Generic_Function_Renaming_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Generic_Function_Renaming_Declarations .Generic_Function_Renaming_Declaration_Access) is begin Self.Failed := True; end Generic_Function_Renaming_Declaration; overriding procedure Task_Body_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Task_Body_Declarations .Task_Body_Declaration_Access) is begin Self.Failed := True; end Task_Body_Declaration; overriding procedure Protected_Body_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Protected_Body_Declarations .Protected_Body_Declaration_Access) is begin Self.Failed := True; end Protected_Body_Declaration; overriding procedure Entry_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Entry_Declarations .Entry_Declaration_Access) is begin Self.Failed := True; end Entry_Declaration; overriding procedure Entry_Body_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Entry_Body_Declarations .Entry_Body_Declaration_Access) is begin Self.Failed := True; end Entry_Body_Declaration; overriding procedure Entry_Index_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Entry_Index_Specifications .Entry_Index_Specification_Access) is begin Self.Failed := True; end Entry_Index_Specification; overriding procedure Procedure_Body_Stub (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Procedure_Body_Stubs .Procedure_Body_Stub_Access) is begin Self.Failed := True; end Procedure_Body_Stub; overriding procedure Function_Body_Stub (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Function_Body_Stubs .Function_Body_Stub_Access) is begin Self.Failed := True; end Function_Body_Stub; overriding procedure Package_Body_Stub (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Package_Body_Stubs .Package_Body_Stub_Access) is begin Self.Failed := True; end Package_Body_Stub; overriding procedure Task_Body_Stub (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Task_Body_Stubs .Task_Body_Stub_Access) is begin Self.Failed := True; end Task_Body_Stub; overriding procedure Protected_Body_Stub (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Protected_Body_Stubs .Protected_Body_Stub_Access) is begin Self.Failed := True; end Protected_Body_Stub; overriding procedure Exception_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Exception_Declarations .Exception_Declaration_Access) is begin Self.Failed := True; end Exception_Declaration; overriding procedure Choice_Parameter_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Choice_Parameter_Specifications .Choice_Parameter_Specification_Access) is begin Self.Failed := True; end Choice_Parameter_Specification; overriding procedure Generic_Package_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Generic_Package_Declarations .Generic_Package_Declaration_Access) is begin Self.Failed := True; end Generic_Package_Declaration; overriding procedure Generic_Procedure_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Generic_Procedure_Declarations .Generic_Procedure_Declaration_Access) is begin Self.Failed := True; end Generic_Procedure_Declaration; overriding procedure Generic_Function_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Generic_Function_Declarations .Generic_Function_Declaration_Access) is begin Self.Failed := True; end Generic_Function_Declaration; overriding procedure Package_Instantiation (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Package_Instantiations .Package_Instantiation_Access) is begin Self.Failed := True; end Package_Instantiation; overriding procedure Procedure_Instantiation (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Procedure_Instantiations .Procedure_Instantiation_Access) is begin Self.Failed := True; end Procedure_Instantiation; overriding procedure Function_Instantiation (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Function_Instantiations .Function_Instantiation_Access) is begin Self.Failed := True; end Function_Instantiation; overriding procedure Formal_Object_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Object_Declarations .Formal_Object_Declaration_Access) is begin Self.Failed := True; end Formal_Object_Declaration; overriding procedure Formal_Type_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Type_Declarations .Formal_Type_Declaration_Access) is begin Self.Failed := True; end Formal_Type_Declaration; overriding procedure Formal_Procedure_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Procedure_Declarations .Formal_Procedure_Declaration_Access) is begin Self.Failed := True; end Formal_Procedure_Declaration; overriding procedure Formal_Function_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Function_Declarations .Formal_Function_Declaration_Access) is begin Self.Failed := True; end Formal_Function_Declaration; overriding procedure Formal_Package_Declaration (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Package_Declarations .Formal_Package_Declaration_Access) is begin Self.Failed := True; end Formal_Package_Declaration; overriding procedure Subtype_Indication (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Subtype_Indications .Subtype_Indication_Access) is begin Self.Failed := True; end Subtype_Indication; overriding procedure Component_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Component_Definitions .Component_Definition_Access) is begin Self.Failed := True; end Component_Definition; overriding procedure Discrete_Subtype_Indication (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Discrete_Subtype_Indications .Discrete_Subtype_Indication_Access) is begin Self.Failed := True; end Discrete_Subtype_Indication; overriding procedure Discrete_Range_Attribute_Reference (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Discrete_Range_Attribute_References .Discrete_Range_Attribute_Reference_Access) is begin Self.Failed := True; end Discrete_Range_Attribute_Reference; overriding procedure Discrete_Simple_Expression_Range (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Discrete_Simple_Expression_Ranges .Discrete_Simple_Expression_Range_Access) is begin Self.Failed := True; end Discrete_Simple_Expression_Range; overriding procedure Unknown_Discriminant_Part (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Unknown_Discriminant_Parts .Unknown_Discriminant_Part_Access) is begin Self.Failed := True; end Unknown_Discriminant_Part; overriding procedure Known_Discriminant_Part (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Known_Discriminant_Parts .Known_Discriminant_Part_Access) is begin Self.Failed := True; end Known_Discriminant_Part; overriding procedure Record_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Record_Definitions .Record_Definition_Access) is begin Self.Failed := True; end Record_Definition; overriding procedure Null_Component (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Null_Components .Null_Component_Access) is begin Self.Failed := True; end Null_Component; overriding procedure Variant_Part (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Variant_Parts.Variant_Part_Access) is begin Self.Failed := True; end Variant_Part; overriding procedure Variant (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Variants.Variant_Access) is begin Self.Failed := True; end Variant; overriding procedure Others_Choice (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Others_Choices.Others_Choice_Access) is begin Self.Failed := True; end Others_Choice; overriding procedure Anonymous_Access_To_Object (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Anonymous_Access_To_Objects .Anonymous_Access_To_Object_Access) is begin Self.Failed := True; end Anonymous_Access_To_Object; overriding procedure Anonymous_Access_To_Procedure (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Anonymous_Access_To_Procedures .Anonymous_Access_To_Procedure_Access) is begin Self.Failed := True; end Anonymous_Access_To_Procedure; overriding procedure Anonymous_Access_To_Function (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Anonymous_Access_To_Functions .Anonymous_Access_To_Function_Access) is begin Self.Failed := True; end Anonymous_Access_To_Function; overriding procedure Private_Type_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Private_Type_Definitions .Private_Type_Definition_Access) is begin Self.Failed := True; end Private_Type_Definition; overriding procedure Private_Extension_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Private_Extension_Definitions .Private_Extension_Definition_Access) is begin Self.Failed := True; end Private_Extension_Definition; overriding procedure Incomplete_Type_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Incomplete_Type_Definitions .Incomplete_Type_Definition_Access) is begin Self.Failed := True; end Incomplete_Type_Definition; overriding procedure Task_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Task_Definitions .Task_Definition_Access) is begin Self.Failed := True; end Task_Definition; overriding procedure Protected_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Protected_Definitions .Protected_Definition_Access) is begin Self.Failed := True; end Protected_Definition; overriding procedure Aspect_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Aspect_Specifications .Aspect_Specification_Access) is begin Self.Failed := True; end Aspect_Specification; overriding procedure Real_Range_Specification (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Real_Range_Specifications .Real_Range_Specification_Access) is begin Self.Failed := True; end Real_Range_Specification; overriding procedure Numeric_Literal (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Numeric_Literals .Numeric_Literal_Access) is begin Self.Failed := True; end Numeric_Literal; overriding procedure String_Literal (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.String_Literals .String_Literal_Access) is begin Self.Failed := True; end String_Literal; overriding procedure Identifier (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Identifiers.Identifier_Access) is begin Self.Failed := True; end Identifier; overriding procedure Operator_Symbol (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Operator_Symbols .Operator_Symbol_Access) is begin Self.Failed := True; end Operator_Symbol; overriding procedure Character_Literal (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Character_Literals .Character_Literal_Access) is begin Self.Failed := True; end Character_Literal; overriding procedure Explicit_Dereference (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Explicit_Dereferences .Explicit_Dereference_Access) is begin Self.Failed := True; end Explicit_Dereference; overriding procedure Infix_Operator (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Infix_Operators .Infix_Operator_Access) is begin Self.Failed := True; end Infix_Operator; overriding procedure Function_Call (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Function_Calls.Function_Call_Access) is begin Self.Failed := True; end Function_Call; overriding procedure Indexed_Component (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Indexed_Components .Indexed_Component_Access) is begin Self.Failed := True; end Indexed_Component; overriding procedure Slice (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Slices.Slice_Access) is begin Self.Failed := True; end Slice; overriding procedure Selected_Component (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Selected_Components .Selected_Component_Access) is begin Self.Failed := True; end Selected_Component; overriding procedure Attribute_Reference (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Attribute_References .Attribute_Reference_Access) is begin Self.Failed := True; end Attribute_Reference; overriding procedure Record_Aggregate (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Record_Aggregates .Record_Aggregate_Access) is begin Self.Failed := True; end Record_Aggregate; overriding procedure Extension_Aggregate (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Extension_Aggregates .Extension_Aggregate_Access) is begin Self.Failed := True; end Extension_Aggregate; overriding procedure Array_Aggregate (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Array_Aggregates .Array_Aggregate_Access) is begin Self.Failed := True; end Array_Aggregate; overriding procedure Short_Circuit_Operation (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Short_Circuit_Operations .Short_Circuit_Operation_Access) is begin Self.Failed := True; end Short_Circuit_Operation; overriding procedure Membership_Test (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Membership_Tests .Membership_Test_Access) is begin Self.Failed := True; end Membership_Test; overriding procedure Null_Literal (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Null_Literals.Null_Literal_Access) is begin Self.Failed := True; end Null_Literal; overriding procedure Parenthesized_Expression (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Parenthesized_Expressions .Parenthesized_Expression_Access) is begin Self.Failed := True; end Parenthesized_Expression; overriding procedure Raise_Expression (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Raise_Expressions .Raise_Expression_Access) is begin Self.Failed := True; end Raise_Expression; overriding procedure Type_Conversion (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Type_Conversions .Type_Conversion_Access) is begin Self.Failed := True; end Type_Conversion; overriding procedure Qualified_Expression (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Qualified_Expressions .Qualified_Expression_Access) is begin Self.Failed := True; end Qualified_Expression; overriding procedure Allocator (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Allocators.Allocator_Access) is begin Self.Failed := True; end Allocator; overriding procedure Case_Expression (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Case_Expressions .Case_Expression_Access) is begin Self.Failed := True; end Case_Expression; overriding procedure If_Expression (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.If_Expressions.If_Expression_Access) is begin Self.Failed := True; end If_Expression; overriding procedure Quantified_Expression (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Quantified_Expressions .Quantified_Expression_Access) is begin Self.Failed := True; end Quantified_Expression; overriding procedure Discriminant_Association (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Discriminant_Associations .Discriminant_Association_Access) is begin Self.Failed := True; end Discriminant_Association; overriding procedure Record_Component_Association (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Record_Component_Associations .Record_Component_Association_Access) is begin Self.Failed := True; end Record_Component_Association; overriding procedure Array_Component_Association (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Array_Component_Associations .Array_Component_Association_Access) is begin Self.Failed := True; end Array_Component_Association; overriding procedure Parameter_Association (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Parameter_Associations .Parameter_Association_Access) is begin Self.Failed := True; end Parameter_Association; overriding procedure Formal_Package_Association (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Package_Associations .Formal_Package_Association_Access) is begin Self.Failed := True; end Formal_Package_Association; overriding procedure Null_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Null_Statements .Null_Statement_Access) is begin Self.Failed := True; end Null_Statement; overriding procedure Assignment_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Assignment_Statements .Assignment_Statement_Access) is begin Self.Failed := True; end Assignment_Statement; overriding procedure If_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.If_Statements.If_Statement_Access) is begin Self.Failed := True; end If_Statement; overriding procedure Case_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Case_Statements .Case_Statement_Access) is begin Self.Failed := True; end Case_Statement; overriding procedure Loop_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Loop_Statements .Loop_Statement_Access) is begin Self.Failed := True; end Loop_Statement; overriding procedure While_Loop_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.While_Loop_Statements .While_Loop_Statement_Access) is begin Self.Failed := True; end While_Loop_Statement; overriding procedure For_Loop_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.For_Loop_Statements .For_Loop_Statement_Access) is begin Self.Failed := True; end For_Loop_Statement; overriding procedure Block_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Block_Statements .Block_Statement_Access) is begin Self.Failed := True; end Block_Statement; overriding procedure Exit_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Exit_Statements .Exit_Statement_Access) is begin Self.Failed := True; end Exit_Statement; overriding procedure Goto_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Goto_Statements .Goto_Statement_Access) is begin Self.Failed := True; end Goto_Statement; overriding procedure Call_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Call_Statements .Call_Statement_Access) is begin Self.Failed := True; end Call_Statement; overriding procedure Simple_Return_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Simple_Return_Statements .Simple_Return_Statement_Access) is begin Self.Failed := True; end Simple_Return_Statement; overriding procedure Extended_Return_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Extended_Return_Statements .Extended_Return_Statement_Access) is begin Self.Failed := True; end Extended_Return_Statement; overriding procedure Accept_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Accept_Statements .Accept_Statement_Access) is begin Self.Failed := True; end Accept_Statement; overriding procedure Requeue_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Requeue_Statements .Requeue_Statement_Access) is begin Self.Failed := True; end Requeue_Statement; overriding procedure Delay_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Delay_Statements .Delay_Statement_Access) is begin Self.Failed := True; end Delay_Statement; overriding procedure Terminate_Alternative_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Terminate_Alternative_Statements .Terminate_Alternative_Statement_Access) is begin Self.Failed := True; end Terminate_Alternative_Statement; overriding procedure Select_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Select_Statements .Select_Statement_Access) is begin Self.Failed := True; end Select_Statement; overriding procedure Abort_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Abort_Statements .Abort_Statement_Access) is begin Self.Failed := True; end Abort_Statement; overriding procedure Raise_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Raise_Statements .Raise_Statement_Access) is begin Self.Failed := True; end Raise_Statement; overriding procedure Code_Statement (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Code_Statements .Code_Statement_Access) is begin Self.Failed := True; end Code_Statement; overriding procedure Elsif_Path (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Elsif_Paths.Elsif_Path_Access) is begin Self.Failed := True; end Elsif_Path; overriding procedure Case_Path (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Case_Paths.Case_Path_Access) is begin Self.Failed := True; end Case_Path; overriding procedure Select_Path (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Select_Paths.Select_Path_Access) is begin Self.Failed := True; end Select_Path; overriding procedure Case_Expression_Path (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Case_Expression_Paths .Case_Expression_Path_Access) is begin Self.Failed := True; end Case_Expression_Path; overriding procedure Elsif_Expression_Path (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Elsif_Expression_Paths .Elsif_Expression_Path_Access) is begin Self.Failed := True; end Elsif_Expression_Path; overriding procedure Use_Clause (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Use_Clauses.Use_Clause_Access) is begin Self.Failed := True; end Use_Clause; overriding procedure With_Clause (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.With_Clauses.With_Clause_Access) is begin Self.Failed := True; end With_Clause; overriding procedure Component_Clause (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Component_Clauses .Component_Clause_Access) is begin Self.Failed := True; end Component_Clause; overriding procedure Derived_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Derived_Types.Derived_Type_Access) is begin Self.Failed := True; end Derived_Type; overriding procedure Derived_Record_Extension (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Derived_Record_Extensions .Derived_Record_Extension_Access) is begin Self.Failed := True; end Derived_Record_Extension; overriding procedure Enumeration_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Enumeration_Types .Enumeration_Type_Access) is begin Self.Failed := True; end Enumeration_Type; overriding procedure Signed_Integer_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Signed_Integer_Types .Signed_Integer_Type_Access) is begin Self.Failed := True; end Signed_Integer_Type; overriding procedure Modular_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Modular_Types.Modular_Type_Access) is begin Self.Failed := True; end Modular_Type; overriding procedure Root_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Root_Types.Root_Type_Access) is begin Self.Failed := True; end Root_Type; overriding procedure Floating_Point_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Floating_Point_Types .Floating_Point_Type_Access) is begin Self.Failed := True; end Floating_Point_Type; overriding procedure Ordinary_Fixed_Point_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Ordinary_Fixed_Point_Types .Ordinary_Fixed_Point_Type_Access) is begin Self.Failed := True; end Ordinary_Fixed_Point_Type; overriding procedure Decimal_Fixed_Point_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Decimal_Fixed_Point_Types .Decimal_Fixed_Point_Type_Access) is begin Self.Failed := True; end Decimal_Fixed_Point_Type; overriding procedure Unconstrained_Array_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Unconstrained_Array_Types .Unconstrained_Array_Type_Access) is begin Self.Failed := True; end Unconstrained_Array_Type; overriding procedure Constrained_Array_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Constrained_Array_Types .Constrained_Array_Type_Access) is begin Self.Failed := True; end Constrained_Array_Type; overriding procedure Record_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Record_Types.Record_Type_Access) is begin Self.Failed := True; end Record_Type; overriding procedure Interface_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Interface_Types .Interface_Type_Access) is begin Self.Failed := True; end Interface_Type; overriding procedure Object_Access_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Object_Access_Types .Object_Access_Type_Access) is begin Self.Failed := True; end Object_Access_Type; overriding procedure Procedure_Access_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Procedure_Access_Types .Procedure_Access_Type_Access) is begin Self.Failed := True; end Procedure_Access_Type; overriding procedure Function_Access_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Function_Access_Types .Function_Access_Type_Access) is begin Self.Failed := True; end Function_Access_Type; overriding procedure Formal_Private_Type_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Private_Type_Definitions .Formal_Private_Type_Definition_Access) is begin Self.Failed := True; end Formal_Private_Type_Definition; overriding procedure Formal_Derived_Type_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Derived_Type_Definitions .Formal_Derived_Type_Definition_Access) is begin Self.Failed := True; end Formal_Derived_Type_Definition; overriding procedure Formal_Discrete_Type_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Discrete_Type_Definitions .Formal_Discrete_Type_Definition_Access) is begin Self.Failed := True; end Formal_Discrete_Type_Definition; overriding procedure Formal_Signed_Integer_Type_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Signed_Integer_Type_Definitions .Formal_Signed_Integer_Type_Definition_Access) is begin Self.Failed := True; end Formal_Signed_Integer_Type_Definition; overriding procedure Formal_Modular_Type_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Modular_Type_Definitions .Formal_Modular_Type_Definition_Access) is begin Self.Failed := True; end Formal_Modular_Type_Definition; overriding procedure Formal_Floating_Point_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Floating_Point_Definitions .Formal_Floating_Point_Definition_Access) is begin Self.Failed := True; end Formal_Floating_Point_Definition; overriding procedure Formal_Ordinary_Fixed_Point_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements .Formal_Ordinary_Fixed_Point_Definitions .Formal_Ordinary_Fixed_Point_Definition_Access) is begin Self.Failed := True; end Formal_Ordinary_Fixed_Point_Definition; overriding procedure Formal_Decimal_Fixed_Point_Definition (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Decimal_Fixed_Point_Definitions .Formal_Decimal_Fixed_Point_Definition_Access) is begin Self.Failed := True; end Formal_Decimal_Fixed_Point_Definition; overriding procedure Formal_Unconstrained_Array_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Unconstrained_Array_Types .Formal_Unconstrained_Array_Type_Access) is begin Self.Failed := True; end Formal_Unconstrained_Array_Type; overriding procedure Formal_Constrained_Array_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Constrained_Array_Types .Formal_Constrained_Array_Type_Access) is begin Self.Failed := True; end Formal_Constrained_Array_Type; overriding procedure Formal_Object_Access_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Object_Access_Types .Formal_Object_Access_Type_Access) is begin Self.Failed := True; end Formal_Object_Access_Type; overriding procedure Formal_Procedure_Access_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Procedure_Access_Types .Formal_Procedure_Access_Type_Access) is begin Self.Failed := True; end Formal_Procedure_Access_Type; overriding procedure Formal_Function_Access_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Function_Access_Types .Formal_Function_Access_Type_Access) is begin Self.Failed := True; end Formal_Function_Access_Type; overriding procedure Formal_Interface_Type (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Formal_Interface_Types .Formal_Interface_Type_Access) is begin Self.Failed := True; end Formal_Interface_Type; overriding procedure Range_Attribute_Reference (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Range_Attribute_References .Range_Attribute_Reference_Access) is begin Self.Failed := True; end Range_Attribute_Reference; overriding procedure Simple_Expression_Range (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Simple_Expression_Ranges .Simple_Expression_Range_Access) is begin Self.Failed := True; end Simple_Expression_Range; overriding procedure Digits_Constraint (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Digits_Constraints .Digits_Constraint_Access) is begin Self.Failed := True; end Digits_Constraint; overriding procedure Delta_Constraint (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Delta_Constraints .Delta_Constraint_Access) is begin Self.Failed := True; end Delta_Constraint; overriding procedure Index_Constraint (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Index_Constraints .Index_Constraint_Access) is begin Self.Failed := True; end Index_Constraint; overriding procedure Discriminant_Constraint (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Discriminant_Constraints .Discriminant_Constraint_Access) is begin Self.Failed := True; end Discriminant_Constraint; overriding procedure Attribute_Definition_Clause (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Attribute_Definition_Clauses .Attribute_Definition_Clause_Access) is begin Self.Failed := True; end Attribute_Definition_Clause; overriding procedure Enumeration_Representation_Clause (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Enumeration_Representation_Clauses .Enumeration_Representation_Clause_Access) is begin Self.Failed := True; end Enumeration_Representation_Clause; overriding procedure Record_Representation_Clause (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Record_Representation_Clauses .Record_Representation_Clause_Access) is begin Self.Failed := True; end Record_Representation_Clause; overriding procedure At_Clause (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.At_Clauses.At_Clause_Access) is begin Self.Failed := True; end At_Clause; overriding procedure Exception_Handler (Self : in out Safe_Element_Visitor; Ignore : not null Program.Elements.Exception_Handlers .Exception_Handler_Access) is begin Self.Failed := True; end Exception_Handler; end Program.Safe_Element_Visitors;
package body GEL is function to_Asset (Self : in String) return asset_Name is the_Name : String (asset_Name'Range); begin the_Name (1 .. Self'Length) := Self; the_Name (Self'Length + 1 .. the_Name'Last) := (others => ' '); return asset_Name (the_Name); end to_Asset; function to_String (Self : in asset_Name) return String is begin for i in reverse Self'Range loop if Self (i) /= ' ' then return String (Self (1 .. i)); end if; end loop; return ""; end to_String; end GEL;
package Spec is pragma Pure(Spec); function Get_Number return Integer is separate; end Spec;
----------------------------------------------------------------------- -- awa-sysadmin-modules -- Module sysadmin -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Applications; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Sysadmin.Models; with Util.Log.Loggers; with ADO.Sessions; with ADO.Statements; with ADO.Queries; with ADO.Utils.Serialize; with Servlet.Rest; with Swagger.Servers.Operation; with AWA.Sysadmin.Beans; package body AWA.Sysadmin.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Sysadmin.Module"); package Register is new AWA.Modules.Beans (Module => Sysadmin_Module, Module_Access => Sysadmin_Module_Access); procedure List_Users (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); package API_List_Users is new Swagger.Servers.Operation (Handler => List_Users, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/users"); procedure List_Users (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List users"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_User_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Users; -- ------------------------------ -- Initialize the sysadmin module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Sysadmin_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the sysadmin module"); App.Add_Servlet ("sysadmin", Plugin.API_Servlet'Unchecked_Access); App.Add_Filter ("sysadmin-filter", Plugin.API_Filter'Unchecked_Access); Register.Register (Plugin => Plugin, Name => "AWA.Sysadmin.Beans.Authenticate_Bean", Handler => AWA.Sysadmin.Beans.Create_Authenticate_Bean'Access); App.Add_Mapping (Name => "sysadmin", Pattern => "/sysadmin/api/*"); AWA.Modules.Module (Plugin).Initialize (App, Props); Servlet.Rest.Register (App.all, API_List_Users.Definition); end Initialize; -- ------------------------------ -- Get the sysadmin module. -- ------------------------------ function Get_Sysadmin_Module return Sysadmin_Module_Access is function Get is new AWA.Modules.Get (Sysadmin_Module, Sysadmin_Module_Access, NAME); begin return Get; end Get_Sysadmin_Module; end AWA.Sysadmin.Modules;
with Primes_IDL_File.PrimeNumberRequest_DataReader; with Primes_IDL_File.PrimeNumberReply_DataWriter; with DDS.Request_Reply.Typed_Replier_Generic; package Primes.PrimeNumberReplier is new DDS.Request_Reply.Typed_Replier_Generic (Request_DataReaders => Primes_IDL_File.PrimeNumberRequest_DataReader, Reply_DataWriters => Primes_IDL_File.PrimeNumberReply_DataWriter);
pragma License (Unrestricted); package Interfaces.C is pragma Pure; -- Declarations based on C's <limits.h> CHAR_BIT : constant := 8; -- typically 8 SCHAR_MIN : constant := -128; -- typically -128 SCHAR_MAX : constant := 127; -- typically 127 UCHAR_MAX : constant := 255; -- typically 255 -- Signed and Unsigned Integers type int is new Integer; -- implementation-defined type short is new Short_Integer; -- implementation-defined type long is new Long_Integer; -- implementation-defined type long_long is new Long_Long_Integer; -- AI12-0184-1, 64-bit type signed_char is range SCHAR_MIN .. SCHAR_MAX; for signed_char'Size use CHAR_BIT; type unsigned is mod 2 ** int'Size; -- implementation-defined type unsigned_short is mod 2 ** short'Size; -- implementation-defined type unsigned_long is mod 2 ** long'Size; -- implementation-defined type unsigned_long_long is mod 2 ** long_long'Size; -- AI12-0184-1, 64-bit type unsigned_char is mod UCHAR_MAX + 1; for unsigned_char'Size use CHAR_BIT; subtype plain_char is unsigned_char; -- implementation-defined type ptrdiff_t is range -(2 ** (Standard'Address_Size - 1)) .. 2 ** (Standard'Address_Size - 1) - 1; -- implementation-defined type size_t is mod 2 ** Standard'Address_Size; -- implementation-defined -- Floating Point type C_float is new Standard.Float; -- implementation-defined type double is new Standard.Long_Float; -- implementation-defined type long_double is new Standard.Long_Long_Float; -- implementation-defined -- Characters and Strings type char is new Character; -- implementation-defined character type nul : constant char := char'Val (0); -- implementation-defined -- extended function To_char ( Item : Character; Substitute : char) -- Windows only return char; function To_char ( Item : Character) return char; pragma Inline (To_char); function To_C (Item : Character) return char renames To_char; -- extended function To_Character ( Item : char; Substitute : Character) -- Windows only return Character; function To_Character ( Item : char) return Character; pragma Inline (To_Character); function To_Ada (Item : char) return Character renames To_Character; type char_array is array (size_t range <>) of aliased char; for char_array'Component_Size use CHAR_BIT; function Is_Nul_Terminated (Item : char_array) return Boolean; -- extended function Length (Item : char_array) return size_t; -- extended function To_char_array ( Item : String; Append_Nul : Boolean := True; Substitute : char_array := (0 => '?')) -- Windows only return char_array; pragma Inline (To_char_array); -- modified function To_C ( Item : String; Append_Nul : Boolean := True; Substitute : char_array := (0 => '?')) -- additional return char_array renames To_char_array; -- extended function To_String ( Item : char_array; Trim_Nul : Boolean := True; Substitute : String := "?") -- unreferenced return String; pragma Inline (To_String); -- modified function To_Ada ( Item : char_array; Trim_Nul : Boolean := True; Substitute : String := "?") -- additional return String renames To_String; -- extended procedure To_char_array ( Item : String; Target : out char_array; Count : out size_t; Append_Nul : Boolean := True; Substitute : char_array := (0 => '?')); -- Windows only pragma Inline (To_char_array); -- modified procedure To_C ( Item : String; Target : out char_array; Count : out size_t; Append_Nul : Boolean := True; Substitute : char_array := (0 => '?')) -- additional renames To_char_array; -- extended procedure To_String ( Item : char_array; Target : out String; Count : out Natural; Trim_Nul : Boolean := True; Substitute : String := "?"); -- unreferenced pragma Inline (To_String); -- modified procedure To_Ada ( Item : char_array; Target : out String; Count : out Natural; Trim_Nul : Boolean := True; Substitute : String := "?") -- additional renames To_String; -- Wide Character and Wide String type wchar_t is mod 2 ** Standard'Wchar_T_Size; -- implementation-defined character type for wchar_t'Size use Standard'Wchar_T_Size; wide_nul : constant wchar_t := wchar_t'Val (0); -- implementation-defined -- extended function To_wchar_t ( Item : Wide_Character; Substitute : wchar_t) -- POSIX only return wchar_t; function To_wchar_t ( Item : Wide_Character) return wchar_t; pragma Inline (To_wchar_t); function To_C (Item : Wide_Character) return wchar_t renames To_wchar_t; -- extended function To_Wide_Character ( Item : wchar_t; Substitute : Wide_Character) -- POSIX only return Wide_Character; function To_Wide_Character ( Item : wchar_t) return Wide_Character; pragma Inline (To_Wide_Character); function To_Ada (Item : wchar_t) return Wide_Character renames To_Wide_Character; type wchar_array is array (size_t range <>) of aliased wchar_t; pragma Pack (wchar_array); function Is_Nul_Terminated (Item : wchar_array) return Boolean; -- extended function Length (Item : wchar_array) return size_t; -- extended function To_wchar_array ( Item : Wide_String; Append_Nul : Boolean := True; Substitute : wchar_array := (0 => Character'Pos ('?'))) -- POSIX only return wchar_array; pragma Inline (To_wchar_array); -- modified function To_C ( Item : Wide_String; Append_Nul : Boolean := True; Substitute : wchar_array := (0 => Character'Pos ('?'))) -- additional return wchar_array renames To_wchar_array; -- extended function To_Wide_String ( Item : wchar_array; Trim_Nul : Boolean := True; Substitute : Wide_String := "?") -- POSIX only return Wide_String; pragma Inline (To_Wide_String); -- modified function To_Ada ( Item : wchar_array; Trim_Nul : Boolean := True; Substitute : Wide_String := "?") -- additional return Wide_String renames To_Wide_String; -- extended procedure To_wchar_array ( Item : Wide_String; Target : out wchar_array; Count : out size_t; Append_Nul : Boolean := True; Substitute : wchar_array := (0 => Character'Pos ('?'))); -- POSIX only pragma Inline (To_wchar_array); -- modified procedure To_C ( Item : Wide_String; Target : out wchar_array; Count : out size_t; Append_Nul : Boolean := True; Substitute : wchar_array := (0 => Character'Pos ('?'))) -- additional renames To_wchar_array; -- extended procedure To_Wide_String ( Item : wchar_array; Target : out Wide_String; Count : out Natural; Trim_Nul : Boolean := True; Substitute : Wide_String := "?"); -- POSIX only pragma Inline (To_Wide_String); -- modified procedure To_Ada ( Item : wchar_array; Target : out Wide_String; Count : out Natural; Trim_Nul : Boolean := True; Substitute : Wide_String := "?") -- additional renames To_Wide_String; -- extended -- Wide Wide Character and Wide Wide String: function To_wchar_t ( Item : Wide_Wide_Character; Substitute : wchar_t := Character'Pos ('?')) -- Windows only return wchar_t; pragma Inline (To_wchar_t); -- extended function To_Wide_Wide_Character ( Item : wchar_t; Substitute : Wide_Wide_Character := '?') -- Windows only return Wide_Wide_Character; pragma Inline (To_Wide_Wide_Character); -- extended function To_wchar_array ( Item : Wide_Wide_String; Append_Nul : Boolean := True; Substitute : wchar_array := (0 => Character'Pos ('?'))) -- Windows only return wchar_array; pragma Inline (To_wchar_array); -- extended function To_Wide_Wide_String ( Item : wchar_array; Trim_Nul : Boolean := True; Substitute : Wide_Wide_String := "?") -- Windows only return Wide_Wide_String; pragma Inline (To_Wide_Wide_String); -- extended procedure To_wchar_array ( Item : Wide_Wide_String; Target : out wchar_array; Count : out size_t; Append_Nul : Boolean := True; Substitute : wchar_array := (0 => Character'Pos ('?'))); -- Windows only pragma Inline (To_wchar_array); -- extended procedure To_Wide_Wide_String ( Item : wchar_array; Target : out Wide_Wide_String; Count : out Natural; Trim_Nul : Boolean := True; Substitute : Wide_Wide_String := "?"); -- Windows only pragma Inline (To_Wide_Wide_String); -- ISO/IEC 10646:2003 compatible types defined by ISO/IEC TR 19769:2004. type char16_t is new Wide_Character; -- implementation-defined character type char16_nul : constant char16_t := char16_t'Val (0); -- implementation-defined function To_C (Item : Wide_Character) return char16_t; pragma Inline (To_C); function To_Ada (Item : char16_t) return Wide_Character; pragma Inline (To_Ada); type char16_array is array (size_t range <>) of aliased char16_t; pragma Pack (char16_array); function Is_Nul_Terminated (Item : char16_array) return Boolean; -- extended function Length (Item : char16_array) return size_t; -- modified function To_C ( Item : Wide_String; Append_Nul : Boolean := True; Substitute : char16_array := "?") -- additional, and unreferenced return char16_array; pragma Inline (To_C); -- modified function To_Ada ( Item : char16_array; Trim_Nul : Boolean := True; Substitute : Wide_String := "?") -- additional, and unreferenced return Wide_String; pragma Inline (To_Ada); -- modified procedure To_C ( Item : Wide_String; Target : out char16_array; Count : out size_t; Append_Nul : Boolean := True; Substitute : char16_array := "?"); -- additional, and unreferenced pragma Inline (To_C); -- modified procedure To_Ada ( Item : char16_array; Target : out Wide_String; Count : out Natural; Trim_Nul : Boolean := True; Substitute : Wide_String := "?"); -- additional, and unreferenced pragma Inline (To_Ada); type char32_t is new Wide_Wide_Character; -- implementation-defined character type char32_nul : constant char32_t := char32_t'Val (0); -- implementation-defined function To_C (Item : Wide_Wide_Character) return char32_t; pragma Inline (To_C); function To_Ada (Item : char32_t) return Wide_Wide_Character; pragma Inline (To_Ada); type char32_array is array (size_t range <>) of aliased char32_t; pragma Pack (char32_array); function Is_Nul_Terminated (Item : char32_array) return Boolean; -- extended function Length (Item : char32_array) return size_t; -- modified function To_C ( Item : Wide_Wide_String; Append_Nul : Boolean := True; Substitute : char32_array := "?") -- additional, and unreferenced return char32_array; pragma Inline (To_C); -- modified function To_Ada ( Item : char32_array; Trim_Nul : Boolean := True; Substitute : Wide_Wide_String := "?") -- additional, and unreferenced return Wide_Wide_String; pragma Inline (To_Ada); -- modified procedure To_C ( Item : Wide_Wide_String; Target : out char32_array; Count : out size_t; Append_Nul : Boolean := True; Substitute : char32_array := "?"); -- additional, and unreferenced pragma Inline (To_C); -- modified procedure To_Ada ( Item : char32_array; Target : out Wide_Wide_String; Count : out Natural; Trim_Nul : Boolean := True; Substitute : Wide_Wide_String := "?"); -- additional, and unreferenced pragma Inline (To_Ada); Terminator_Error : exception; -- extended -- Common to instances of Interfaces.C.Pointers. Pointer_Error : exception; -- extended -- Common to instances of Interfaces.C.Generic_Strings. Dereference_Error : exception; Update_Error : exception; end Interfaces.C;
-- { dg-do compile } with Ada.Finalization; with Controlled1_Pkg; use Controlled1_Pkg; package Controlled1 is type Collection is new Ada.Finalization.Controlled with null record; type Object_Kind_Type is (One, Two); type Byte_Array is array (Natural range <>) of Integer; type Bounded_Byte_Array_Type is record A : Byte_Array (1 .. Value); end record; type Object_Type is tagged record A : Bounded_Byte_Array_Type; end record; type R_Object_Type is new Object_Type with record L : Collection; end record; type Obj_Type (Kind : Object_Kind_Type := One) is record case Kind is when One => R : R_Object_Type; when others => null; end case; end record; type Obj_Array_Type is array (Positive range <>) of Obj_Type; end Controlled1;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . T A G S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2015, Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. The copyright notice above, and the license provisions that follow -- -- apply solely to the contents of the part following the private keyword. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- For performance analysis, take into account that the operations in this -- package provide the guarantee that all dispatching calls on primitive -- operations of tagged types and interfaces take constant time (in terms -- of source lines executed), that is to say, the cost of these calls is -- independent of the number of primitives of the type or interface, and -- independent of the number of ancestors or interface progenitors that a -- tagged type may have. -- The following subprograms of the public part of this package take constant -- time (in terms of source lines executed): -- Expanded_Name, Wide_Expanded_Name, Wide_Wide_Expanded_Name, External_Tag, -- Is_Descendant_At_Same_Level, Parent_Tag, Type_Is_Abstract -- Descendant_Tag (when used with a library-level tagged type), -- Internal_Tag (when used with a library-level tagged type). -- The following subprograms of the public part of this package execute in -- time that is not constant (in terms of sources line executed): -- Internal_Tag (when used with a locally defined tagged type), because in -- such cases this routine processes the external tag, extracts from it an -- address available there, and converts it into the tag value returned by -- this function. The number of instructions executed is not constant since -- it depends on the length of the external tag string. -- Descendant_Tag (when used with a locally defined tagged type), because -- it relies on the subprogram Internal_Tag() to provide its functionality. -- Interface_Ancestor_Tags, because this function returns a table whose -- length depends on the number of interfaces covered by a tagged type. with System.Storage_Elements; package Ada.Tags is pragma Preelaborate; -- In accordance with Ada 2005 AI-362 type Tag is private; pragma Preelaborable_Initialization (Tag); No_Tag : constant Tag; function Expanded_Name (T : Tag) return String; function Wide_Expanded_Name (T : Tag) return Wide_String; pragma Ada_05 (Wide_Expanded_Name); function Wide_Wide_Expanded_Name (T : Tag) return Wide_Wide_String; pragma Ada_05 (Wide_Wide_Expanded_Name); function External_Tag (T : Tag) return String; function Internal_Tag (External : String) return Tag; function Descendant_Tag (External : String; Ancestor : Tag) return Tag; pragma Ada_05 (Descendant_Tag); function Is_Descendant_At_Same_Level (Descendant : Tag; Ancestor : Tag) return Boolean; pragma Ada_05 (Is_Descendant_At_Same_Level); function Parent_Tag (T : Tag) return Tag; pragma Ada_05 (Parent_Tag); type Tag_Array is array (Positive range <>) of Tag; function Interface_Ancestor_Tags (T : Tag) return Tag_Array; pragma Ada_05 (Interface_Ancestor_Tags); function Type_Is_Abstract (T : Tag) return Boolean; pragma Ada_2012 (Type_Is_Abstract); Tag_Error : exception; private -- Structure of the GNAT Primary Dispatch Table -- +--------------------+ -- | Signature | -- +--------------------+ -- | Tagged_Kind | -- +--------------------+ Predef Prims -- | Predef_Prims -----------------------------> +------------+ -- +--------------------+ | table of | -- | Offset_To_Top | | predefined | -- +--------------------+ | primitives | -- |Typeinfo_Ptr/TSD_Ptr---> Type Specific Data +------------+ -- Tag ---> +--------------------+ +-------------------+ -- | table of | | inheritance depth | -- : primitive ops : +-------------------+ -- | pointers | | access level | -- +--------------------+ +-------------------+ -- | alignment | -- +-------------------+ -- | expanded name | -- +-------------------+ -- | external tag | -- +-------------------+ -- | hash table link | -- +-------------------+ -- | transportable | -- +-------------------+ -- | type_is_abstract | -- +-------------------+ -- | needs finalization| -- +-------------------+ -- | Ifaces_Table ---> Interface Data -- +-------------------+ +------------+ -- Select Specific Data <---- SSD | | Nb_Ifaces | -- +------------------+ +-------------------+ +------------+ -- |table of primitive| | table of | | table | -- : operation : : ancestor : : of : -- | kinds | | tags | | interfaces | -- +------------------+ +-------------------+ +------------+ -- |table of | -- : entry : -- | indexes | -- +------------------+ -- Structure of the GNAT Secondary Dispatch Table -- +--------------------+ -- | Signature | -- +--------------------+ -- | Tagged_Kind | -- +--------------------+ Predef Prims -- | Predef_Prims -----------------------------> +------------+ -- +--------------------+ | table of | -- | Offset_To_Top | | predefined | -- +--------------------+ | primitives | -- | OSD_Ptr |---> Object Specific Data | thunks | -- Tag ---> +--------------------+ +---------------+ +------------+ -- | table of | | num prim ops | -- : primitive op : +---------------+ -- | thunk pointers | | table of | -- +--------------------+ + primitive | -- | op offsets | -- +---------------+ -- The runtime information kept for each tagged type is separated into two -- objects: the Dispatch Table and the Type Specific Data record. package SSE renames System.Storage_Elements; subtype Cstring is String (Positive); type Cstring_Ptr is access all Cstring; pragma No_Strict_Aliasing (Cstring_Ptr); -- Declarations for the table of interfaces type Offset_To_Top_Function_Ptr is access function (This : System.Address) return SSE.Storage_Offset; -- Type definition used to call the function that is generated by the -- expander in case of tagged types with discriminants that have secondary -- dispatch tables. This function provides the Offset_To_Top value in this -- specific case. type Interface_Data_Element is record Iface_Tag : Tag; Static_Offset_To_Top : Boolean; Offset_To_Top_Value : SSE.Storage_Offset; Offset_To_Top_Func : Offset_To_Top_Function_Ptr; Secondary_DT : Tag; end record; -- If some ancestor of the tagged type has discriminants the field -- Static_Offset_To_Top is False and the field Offset_To_Top_Func -- is used to store the access to the function generated by the -- expander which provides this value; otherwise Static_Offset_To_Top -- is True and such value is stored in the Offset_To_Top_Value field. -- Secondary_DT references a secondary dispatch table whose contents -- are pointers to the primitives of the tagged type that cover the -- interface primitives. Secondary_DT gives support to dispatching -- calls through interface types associated with Generic Dispatching -- Constructors. type Interfaces_Array is array (Natural range <>) of Interface_Data_Element; type Interface_Data (Nb_Ifaces : Positive) is record Ifaces_Table : Interfaces_Array (1 .. Nb_Ifaces); end record; type Interface_Data_Ptr is access all Interface_Data; -- Table of abstract interfaces used to give support to backward interface -- conversions and also to IW_Membership. -- Primitive operation kinds. These values differentiate the kinds of -- callable entities stored in the dispatch table. Certain kinds may -- not be used, but are added for completeness. type Prim_Op_Kind is (POK_Function, POK_Procedure, POK_Protected_Entry, POK_Protected_Function, POK_Protected_Procedure, POK_Task_Entry, POK_Task_Function, POK_Task_Procedure); -- Select specific data types type Select_Specific_Data_Element is record Index : Positive; Kind : Prim_Op_Kind; end record; type Select_Specific_Data_Array is array (Positive range <>) of Select_Specific_Data_Element; type Select_Specific_Data (Nb_Prim : Positive) is record SSD_Table : Select_Specific_Data_Array (1 .. Nb_Prim); -- NOTE: Nb_Prim is the number of non-predefined primitive operations end record; type Select_Specific_Data_Ptr is access all Select_Specific_Data; -- A table used to store the primitive operation kind and entry index of -- primitive subprograms of a type that implements a limited interface. -- The Select Specific Data table resides in the Type Specific Data of a -- type. This construct is used in the handling of dispatching triggers -- in select statements. type Prim_Ptr is access procedure; type Address_Array is array (Positive range <>) of Prim_Ptr; subtype Dispatch_Table is Address_Array (1 .. 1); -- Used by GDB to identify the _tags and traverse the run-time structure -- associated with tagged types. For compatibility with older versions of -- gdb, its name must not be changed. type Tag is access all Dispatch_Table; pragma No_Strict_Aliasing (Tag); type Interface_Tag is access all Dispatch_Table; No_Tag : constant Tag := null; -- The expander ensures that Tag objects reference the Prims_Ptr component -- of the wrapper. type Tag_Ptr is access all Tag; pragma No_Strict_Aliasing (Tag_Ptr); type Offset_To_Top_Ptr is access all SSE.Storage_Offset; pragma No_Strict_Aliasing (Offset_To_Top_Ptr); type Tag_Table is array (Natural range <>) of Tag; type Size_Ptr is access function (A : System.Address) return Long_Long_Integer; type Type_Specific_Data (Idepth : Natural) is record -- The discriminant Idepth is the Inheritance Depth Level: Used to -- implement the membership test associated with single inheritance of -- tagged types in constant-time. It also indicates the size of the -- Tags_Table component. Access_Level : Natural; -- Accessibility level required to give support to Ada 2005 nested type -- extensions. This feature allows safe nested type extensions by -- shifting the accessibility checks to certain operations, rather than -- being enforced at the type declaration. In particular, by performing -- run-time accessibility checks on class-wide allocators, class-wide -- function return, and class-wide stream I/O, the danger of objects -- outliving their type declaration can be eliminated (Ada 2005: AI-344) Alignment : Natural; Expanded_Name : Cstring_Ptr; External_Tag : Cstring_Ptr; HT_Link : Tag_Ptr; -- Components used to support to the Ada.Tags subprograms in RM 3.9 -- Note: Expanded_Name is referenced by GDB to determine the actual name -- of the tagged type. Its requirements are: 1) it must have this exact -- name, and 2) its contents must point to a C-style Nul terminated -- string containing its expanded name. GDB has no requirement on a -- given position inside the record. Transportable : Boolean; -- Used to check RM E.4(18), set for types that satisfy the requirements -- for being used in remote calls as actuals for classwide formals or as -- return values for classwide functions. Type_Is_Abstract : Boolean; -- True if the type is abstract (Ada 2012: AI05-0173) Needs_Finalization : Boolean; -- Used to dynamically check whether an object is controlled or not Size_Func : Size_Ptr; -- Pointer to the subprogram computing the _size of the object. Used by -- the run-time whenever a call to the 'size primitive is required. We -- cannot assume that the contents of dispatch tables are addresses -- because in some architectures the ABI allows descriptors. Interfaces_Table : Interface_Data_Ptr; -- Pointer to the table of interface tags. It is used to implement the -- membership test associated with interfaces and also for backward -- abstract interface type conversions (Ada 2005:AI-251) SSD : Select_Specific_Data_Ptr; -- Pointer to a table of records used in dispatching selects. This field -- has a meaningful value for all tagged types that implement a limited, -- protected, synchronized or task interfaces and have non-predefined -- primitive operations. Tags_Table : Tag_Table (0 .. Idepth); -- Table of ancestor tags. Its size actually depends on the inheritance -- depth level of the tagged type. end record; type Type_Specific_Data_Ptr is access all Type_Specific_Data; pragma No_Strict_Aliasing (Type_Specific_Data_Ptr); -- Declarations for the dispatch table record type Signature_Kind is (Unknown, Primary_DT, Secondary_DT); -- Tagged type kinds with respect to concurrency and limitedness type Tagged_Kind is (TK_Abstract_Limited_Tagged, TK_Abstract_Tagged, TK_Limited_Tagged, TK_Protected, TK_Tagged, TK_Task); type Dispatch_Table_Wrapper (Num_Prims : Natural) is record Signature : Signature_Kind; Tag_Kind : Tagged_Kind; Predef_Prims : System.Address; -- Pointer to the dispatch table of predefined Ada primitives -- According to the C++ ABI the components Offset_To_Top and TSD are -- stored just "before" the dispatch table, and they are referenced with -- negative offsets referring to the base of the dispatch table. The -- _Tag (or the VTable_Ptr in C++ terminology) must point to the base -- of the virtual table, just after these components, to point to the -- Prims_Ptr table. Offset_To_Top : SSE.Storage_Offset; TSD : System.Address; Prims_Ptr : aliased Address_Array (1 .. Num_Prims); -- The size of the Prims_Ptr array actually depends on the tagged type -- to which it applies. For each tagged type, the expander computes the -- actual array size, allocates the Dispatch_Table record accordingly. end record; type Dispatch_Table_Ptr is access all Dispatch_Table_Wrapper; pragma No_Strict_Aliasing (Dispatch_Table_Ptr); -- The following type declaration is used by the compiler when the program -- is compiled with restriction No_Dispatching_Calls. It is also used with -- interface types to generate the tag and run-time information associated -- with them. type No_Dispatch_Table_Wrapper is record NDT_TSD : System.Address; NDT_Prims_Ptr : Natural; end record; DT_Predef_Prims_Size : constant SSE.Storage_Count := SSE.Storage_Count (1 * (Standard'Address_Size / System.Storage_Unit)); -- Size of the Predef_Prims field of the Dispatch_Table DT_Offset_To_Top_Size : constant SSE.Storage_Count := SSE.Storage_Count (1 * (Standard'Address_Size / System.Storage_Unit)); -- Size of the Offset_To_Top field of the Dispatch Table DT_Typeinfo_Ptr_Size : constant SSE.Storage_Count := SSE.Storage_Count (1 * (Standard'Address_Size / System.Storage_Unit)); -- Size of the Typeinfo_Ptr field of the Dispatch Table use type System.Storage_Elements.Storage_Offset; DT_Offset_To_Top_Offset : constant SSE.Storage_Count := DT_Typeinfo_Ptr_Size + DT_Offset_To_Top_Size; DT_Predef_Prims_Offset : constant SSE.Storage_Count := DT_Typeinfo_Ptr_Size + DT_Offset_To_Top_Size + DT_Predef_Prims_Size; -- Offset from Prims_Ptr to Predef_Prims component -- Object Specific Data record of secondary dispatch tables type Object_Specific_Data_Array is array (Positive range <>) of Positive; type Object_Specific_Data (OSD_Num_Prims : Positive) is record OSD_Table : Object_Specific_Data_Array (1 .. OSD_Num_Prims); -- Table used in secondary DT to reference their counterpart in the -- select specific data (in the TSD of the primary DT). This construct -- is used in the handling of dispatching triggers in select statements. -- Nb_Prim is the number of non-predefined primitive operations. end record; type Object_Specific_Data_Ptr is access all Object_Specific_Data; pragma No_Strict_Aliasing (Object_Specific_Data_Ptr); -- The following subprogram specifications are placed here instead of the -- package body to see them from the frontend through rtsfind. function Base_Address (This : System.Address) return System.Address; -- Ada 2005 (AI-251): Displace "This" to point to the base address of the -- object (that is, the address of the primary tag of the object). procedure Check_TSD (TSD : Type_Specific_Data_Ptr); -- Ada 2012 (AI-113): Raise Program_Error if the external tag of this TSD -- is the same as the external tag for some other tagged type declaration. function Displace (This : System.Address; T : Tag) return System.Address; -- Ada 2005 (AI-251): Displace "This" to point to the secondary dispatch -- table of T. function Secondary_Tag (T, Iface : Tag) return Tag; -- Ada 2005 (AI-251): Given a primary tag T associated with a tagged type -- Typ, search for the secondary tag of the interface type Iface covered -- by Typ. function DT (T : Tag) return Dispatch_Table_Ptr; -- Return the pointer to the TSD record associated with T function Get_Entry_Index (T : Tag; Position : Positive) return Positive; -- Ada 2005 (AI-251): Return a primitive operation's entry index (if entry) -- given a dispatch table T and a position of a primitive operation in T. function Get_Offset_Index (T : Tag; Position : Positive) return Positive; -- Ada 2005 (AI-251): Given a pointer to a secondary dispatch table (T) -- and a position of an operation in the DT, retrieve the corresponding -- operation's position in the primary dispatch table from the Offset -- Specific Data table of T. function Get_Prim_Op_Kind (T : Tag; Position : Positive) return Prim_Op_Kind; -- Ada 2005 (AI-251): Return a primitive operation's kind given a dispatch -- table T and a position of a primitive operation in T. function Get_Tagged_Kind (T : Tag) return Tagged_Kind; -- Ada 2005 (AI-345): Given a pointer to either a primary or a secondary -- dispatch table, return the tagged kind of a type in the context of -- concurrency and limitedness. function IW_Membership (This : System.Address; T : Tag) return Boolean; -- Ada 2005 (AI-251): General routine that checks if a given object -- implements a tagged type. Its common usage is to check if Obj is in -- Iface'Class, but it is also used to check if a class-wide interface -- implements a given type (Iface_CW_Typ in T'Class). For example: -- -- type I is interface; -- type T is tagged ... -- -- function Test (O : I'Class) is -- begin -- return O in T'Class. -- end Test; function Offset_To_Top (This : System.Address) return SSE.Storage_Offset; -- Ada 2005 (AI-251): Returns the current value of the Offset_To_Top -- component available in the prologue of the dispatch table. If the parent -- of the tagged type has discriminants this value is stored in a record -- component just immediately after the tag component. function Needs_Finalization (T : Tag) return Boolean; -- A helper routine used in conjunction with finalization collections which -- service class-wide types. The function dynamically determines whether an -- object is controlled or has controlled components. function Parent_Size (Obj : System.Address; T : Tag) return SSE.Storage_Count; -- Computes the size the ancestor part of a tagged extension object whose -- address is 'obj' by calling indirectly the ancestor _size function. The -- ancestor is the parent of the type represented by tag T. This function -- assumes that _size is always in slot one of the dispatch table. procedure Register_Interface_Offset (This : System.Address; Interface_T : Tag; Is_Static : Boolean; Offset_Value : SSE.Storage_Offset; Offset_Func : Offset_To_Top_Function_Ptr); -- Register in the table of interfaces of the tagged type associated with -- "This" object the offset of the record component associated with the -- progenitor Interface_T (that is, the distance from "This" to the object -- component containing the tag of the secondary dispatch table). In case -- of constant offset, Is_Static is true and Offset_Value has such value. -- In case of variable offset, Is_Static is false and Offset_Func is an -- access to function that must be called to evaluate the offset. procedure Register_Tag (T : Tag); -- Insert the Tag and its associated external_tag in a table for the sake -- of Internal_Tag. procedure Set_Dynamic_Offset_To_Top (This : System.Address; Interface_T : Tag; Offset_Value : SSE.Storage_Offset; Offset_Func : Offset_To_Top_Function_Ptr); -- Ada 2005 (AI-251): The compiler generates calls to this routine only -- when initializing the Offset_To_Top field of dispatch tables associated -- with tagged type whose parent has variable size components. "This" is -- the object whose dispatch table is being initialized. Interface_T is the -- interface for which the secondary dispatch table is being initialized, -- and Offset_Value is the distance from "This" to the object component -- containing the tag of the secondary dispatch table (a zero value means -- that this interface shares the primary dispatch table). Offset_Func -- references a function that must be called to evaluate the offset at -- runtime. This routine also takes care of registering these values in -- the table of interfaces of the type. procedure Set_Entry_Index (T : Tag; Position : Positive; Value : Positive); -- Ada 2005 (AI-345): Set the entry index of a primitive operation in T's -- TSD table indexed by Position. procedure Set_Prim_Op_Kind (T : Tag; Position : Positive; Value : Prim_Op_Kind); -- Ada 2005 (AI-251): Set the kind of a primitive operation in T's TSD -- table indexed by Position. procedure Unregister_Tag (T : Tag); -- Remove a particular tag from the external tag hash table Max_Predef_Prims : constant Positive := 15; -- Number of reserved slots for the following predefined ada primitives: -- -- 1. Size -- 2. Read -- 3. Write -- 4. Input -- 5. Output -- 6. "=" -- 7. assignment -- 8. deep adjust -- 9. deep finalize -- 10. async select -- 11. conditional select -- 12. prim_op kind -- 13. task_id -- 14. dispatching requeue -- 15. timed select -- -- The compiler checks that the value here is correct subtype Predef_Prims_Table is Address_Array (1 .. Max_Predef_Prims); type Predef_Prims_Table_Ptr is access Predef_Prims_Table; pragma No_Strict_Aliasing (Predef_Prims_Table_Ptr); type Addr_Ptr is access System.Address; pragma No_Strict_Aliasing (Addr_Ptr); -- This type is used by the frontend to generate the code that handles -- dispatch table slots of types declared at the local level. end Ada.Tags;
with Ada.Directories; use Ada.Directories; package Blueprint is type Action is (Write, Delete, DryRun); function Get_Blueprint_Folder return String; procedure Process_File (Target : String; Search_Item : in Directory_Entry_Type; Todo: Action); procedure Iterate(Blueprint_Folder: String; Path: String; Todo: Action); private end Blueprint;
----------------------------------------------------------------------- -- Util -- Utilities -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Properties.Bundles; with Util.Properties.Basic; with Util.Measures; package body Util.Properties.Bundles.Tests is use Util.Tests; use Util.Properties.Basic; -- Test the bundle procedure Test_Bundle (T : in out Test) is Props : aliased Properties.Manager; -- _Access := new Properties.Manager; Bundle : Properties.Bundles.Manager; V : Integer := 23; begin -- Create a first property (while the bundle is empty) -- Integer_Property.Set (Props.all, "test-integer", 123); -- Assert (Bundle.Exists ("test-integer"), "Invalid properties"); -- -- V := Integer_Property.Get (Bundle, "test-integer"); -- Assert (V = 123, "Property was not inserted"); -- Add a property set to the bundle Bundle.Add_Bundle (Props'Unchecked_Access); Integer_Property.Set (Props, "test-integer-second", 24); V := Integer_Property.Get (Props, "test-integer-second"); T.Assert (V = 24, "Property was not inserted"); V := Integer_Property.Get (Bundle, "test-integer-second"); T.Assert (V = 24, "Property was not inserted"); -- Bundle.Remove ("test-integer-second"); -- Assert (Props.all.Exists ("test-integer-second") = False, -- "The 'test-integer-second' property was not removed"); -- Assert (Bundle.Exists ("test-integer-second") = False, -- "Property not removed from bundle"); end Test_Bundle; procedure Test_Bundle_Loader (T : in out Test) is Factory : Loader; Bundle : Util.Properties.Bundles.Manager; begin Initialize (Factory, Util.Tests.Get_Test_Path ("regtests/bundles")); Load_Bundle (Factory, "bundle", "fr", Bundle); Assert_Equals (T, "Message France", String '(Bundle.Get ("message")), "Load fr bundle failed"); Assert_Equals (T, "Default", String '(Bundle.Get ("message_default")), "Load fr bundle failed"); Load_Bundle (Factory, "bundle", "en_GB", Bundle); Assert_Equals (T, "GB message", String '(Bundle.Get ("message")), "Load en_GB bundle failed"); Assert_Equals (T, "Default", String '(Bundle.Get ("message_default")), "Load en_GB bundle failed"); end Test_Bundle_Loader; -- Test overloading some bundle definition by having incomplete files. procedure Test_Bundle_Overload (T : in out Test) is Factory : Loader; Bundle : Util.Properties.Bundles.Manager; P1 : constant String := Util.Tests.Get_Test_Path ("regtests/bundles"); P2 : constant String := Util.Tests.Get_Test_Path ("bundles"); begin Initialize (Factory, P1 & ";" & P2); Load_Bundle (Factory, "dates", "fr", Bundle); -- Overloaded by regtests/bundles/dates.properties Assert_Equals (T, "New", String '(Bundle.Get ("util.test_variable")), "Load fr bundle failed (not defined)"); Assert_Equals (T, "Jan", String '(Bundle.Get ("util.month1.short")), "Load fr bundle failed (should not be overloaded)"); -- Not overloaded, value comes from bundles/dates_fr.properties Assert_Equals (T, "Mar", String '(Bundle.Get ("util.month3.short")), "Load fr bundle failed"); Load_Bundle (Factory, "dates", "en_GB", Bundle); Assert_Equals (T, "Jan_Overloaded", String '(Bundle.Get ("util.month1.short")), "Load en_GB bundle failed (should be overloaded)"); -- Not overloaded, value comes from bundles/dates_fr.properties Assert_Equals (T, "Mar", String '(Bundle.Get ("util.month3.short")), "Load en_GB bundle failed"); end Test_Bundle_Overload; -- ------------------------------ -- Test bundle resolution perf. -- ------------------------------ procedure Test_Bundle_Perf (T : in out Test) is Factory : Loader; Bundle : Util.Properties.Bundles.Manager; P1 : constant String := Util.Tests.Get_Test_Path ("regtests/bundles"); P2 : constant String := Util.Tests.Get_Test_Path ("bundles"); begin Initialize (Factory, P1 & ";" & P2); declare S1 : Util.Measures.Stamp; begin Load_Bundle (Factory, "dates", "fr", Bundle); Util.Measures.Report (S1, "Load_Bundle (first time)"); end; declare S1 : Util.Measures.Stamp; begin Load_Bundle (Factory, "dates", "fr", Bundle); Util.Measures.Report (S1, "Load_Bundle (second time)"); end; declare S1 : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Load_Bundle (Factory, "dates", "fr", Bundle); end loop; Util.Measures.Report (S1, "Load_Bundle", 1000); end; -- Not overloaded, value comes from bundles/dates_fr.properties Assert_Equals (T, "Mar", String '(Bundle.Get ("util.month3.short")), "Load fr bundle failed"); end Test_Bundle_Perf; package Caller is new Util.Test_Caller (Test, "Properties.Bundles"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Properties.Bundles", Test_Bundle'Access); Caller.Add_Test (Suite, "Test Util.Properties.Bundles.Load_Bundle", Test_Bundle_Loader'Access); Caller.Add_Test (Suite, "Test Util.Properties.Bundles.Load_Bundle (overloading)", Test_Bundle_Overload'Access); Caller.Add_Test (Suite, "Test Util.Properties.Bundles.Load_Bundle (perf)", Test_Bundle_Perf'Access); end Add_Tests; end Util.Properties.Bundles.Tests;
-- SPDX-FileCopyrightText: 2021 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with League.String_Vectors; with League.Strings; with Network.Addresses; with Network.Connections; with Network.Connection_Promises; with Network.Polls; package Network.Managers is pragma Preelaborate; type Manager is tagged limited private; -- Network connection manager procedure Initialize (Self : in out Manager'Class); -- Call Initialize before use procedure Connect (Self : in out Manager'Class; Address : Network.Addresses.Address; Error : out League.Strings.Universal_String; Promise : out Connection_Promises.Promise; Options : League.String_Vectors.Universal_String_Vector := League.String_Vectors.Empty_Universal_String_Vector); -- Try to connect to given address asynchronously. Return a connection -- promise or an Error if the address isn't supported. The promise will -- be resolved with a connection or rejected with an error. On successful -- connect the application should set a listener to the connection. After -- that it could write and read data until get a close event. Options are -- protocol dependent. type Connection_Listener is limited interface; type Connection_Listener_Access is access all Connection_Listener'Class with Storage_Size => 0; not overriding procedure Connected (Self : in out Connection_Listener; Connection : not null Network.Connections.Connection_Access; Remote : Network.Addresses.Address) is null; -- Once the manager accepts a new connection. It should assign a listener -- to the connection. procedure Listen (Self : in out Manager'Class; List : Network.Addresses.Address_Array; Listener : Connection_Listener_Access; Error : out League.Strings.Universal_String; Options : League.String_Vectors.Universal_String_Vector := League.String_Vectors.Empty_Universal_String_Vector); -- Make manager to listen given network addresses and call listener on -- new incoming connection. Return Error if some address isn't supported. -- Options are protocol dependent. procedure Wait (Self : in out Manager'Class; Timeout : Duration); -- Run manager for specified time or till some event occurs. private type Protocol is limited interface; type Protocol_Access is access all Protocol'Class with Storage_Size => 0; not overriding function Can_Listen (Self : Protocol; Address : Network.Addresses.Address) return Boolean is abstract; not overriding function Can_Connect (Self : Protocol; Address : Network.Addresses.Address) return Boolean is abstract; not overriding procedure Listen (Self : in out Protocol; List : Network.Addresses.Address_Array; Listener : Connection_Listener_Access; Poll : in out Network.Polls.Poll; Error : out League.Strings.Universal_String; Options : League.String_Vectors.Universal_String_Vector := League.String_Vectors.Empty_Universal_String_Vector) is abstract; not overriding procedure Connect (Self : in out Protocol; Address : Network.Addresses.Address; Poll : in out Network.Polls.Poll; Error : out League.Strings.Universal_String; Promise : out Connection_Promises.Promise; Options : League.String_Vectors.Universal_String_Vector := League.String_Vectors.Empty_Universal_String_Vector) is abstract; procedure Register (Self : in out Manager; Protocol : not null Protocol_Access); type Protocol_Access_Array is array (Positive range <>) of Protocol_Access; type Manager is tagged limited record Poll : Network.Polls.Poll; Proto : Protocol_Access_Array (1 .. 10); Last : Natural := 0; end record; end Network.Managers;
with Ada.Float_Text_IO; use Ada.Float_Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; with System; with PortAudioAda; use PortAudioAda; with PaEx_Sine_Types; use PaEx_Sine_Types; with PaEx_Sine_Callbacks; use PaEx_Sine_Callbacks; procedure PaEx_Sine is stream : aliased Pa_Stream_Ptr; err : PA_Error; begin Put ("PortAudio Test: output sine wave. SR = "); Put (Sample_Rate, 0, 0, 0); Put (", BufSize = "); Put (Frames_Per_Buffer, 0); New_Line; Put_Line (PA_Get_Version); ----------------------------------------------------------------------------- -- initialize sinusoidal wavetable for i in 1 .. Table_Size loop data.sine (i) := Sin (Float (i) / Float (Table_Size) * Ada.Numerics.Pi * 2.0); end loop; data.left_phase := 1; data.right_phase := 1; err := PA_Initialize; if err /= paNoError then raise PortAudio_Exception; end if; outputParameters.device := PA_Get_Default_Output_Device; if outputParameters.device = paNoDevice then raise PortAudio_Exception; end if; outputParameters.channelCount := 2; outputParameters.sampleFormat := paFloat32; outputParameters.suggestedLatency := PA_Get_Device_Info (outputParameters.device).defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo := System.Null_Address; err := PA_Open_Stream (stream'Access, null, outputParameters'Access, Sample_Rate, Frames_Per_Buffer, paClipOff, paTestCallback'Access, data'Address); if err /= paNoError then raise PortAudio_Exception; end if; data.message := "No Message "; err := PA_Set_Stream_Finished_Callback (stream, StreamFinished'Access); if err /= paNoError then raise PortAudio_Exception; end if; err := PA_Start_Stream (stream); if err /= paNoError then raise PortAudio_Exception; end if; delay Num_Seconds; err := PA_Stop_Stream (stream); if err /= paNoError then raise PortAudio_Exception; end if; err := PA_Close_Stream (stream); if err /= paNoError then raise PortAudio_Exception; end if; err := PA_Terminate; Put_Line ("Test finished."); ----------------------------------------------------------------------------- return; exception when PortAudio_Exception => err := PA_Terminate; Put_Line ("Error occured while using the PortAudio stream"); Put_Line ("Error code: " & PA_Error'Image (err)); Put_Line ("Error message: " & PA_Get_Error_Text (err)); end PaEx_Sine;
pragma Ada_2005; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; with CUPS.cups_language_h; private package CUPS.cups_transcode_h is CUPS_MAX_USTRING : constant := 8192; -- cups/transcode.h:36 -- * "$Id: transcode.h 10996 2013-05-29 11:51:34Z msweet $" -- * -- * Transcoding definitions for CUPS. -- * -- * Copyright 2007-2011 by Apple Inc. -- * Copyright 1997-2006 by Easy Software Products. -- * -- * These coded instructions, statements, and computer programs are the -- * property of Apple Inc. and are protected by Federal copyright -- * law. Distribution and use rights are outlined in the file "LICENSE.txt" -- * which should have been included with this file. If this file is -- * file is missing or damaged, see the license at "http://www.cups.org/". -- * -- * This file is subject to the Apple OS-Developed Software exception. -- -- * Include necessary headers... -- -- * Constants... -- -- * Types... -- -- UTF-8 Unicode/ISO-10646 unit subtype cups_utf8_t is unsigned_char; -- cups/transcode.h:43 -- UTF-32 Unicode/ISO-10646 unit subtype cups_utf32_t is unsigned_long; -- cups/transcode.h:44 -- UCS-2 Unicode/ISO-10646 unit subtype cups_ucs2_t is unsigned_short; -- cups/transcode.h:45 -- UCS-4 Unicode/ISO-10646 unit subtype cups_ucs4_t is unsigned_long; -- cups/transcode.h:46 -- SBCS Legacy 8-bit unit subtype cups_sbcs_t is unsigned_char; -- cups/transcode.h:47 -- DBCS Legacy 16-bit unit subtype cups_dbcs_t is unsigned_short; -- cups/transcode.h:48 -- VBCS Legacy 32-bit unit subtype cups_vbcs_t is unsigned_long; -- cups/transcode.h:49 -- EUC uses 8, 16, 24, 32-bit -- * Prototypes... -- function cupsCharsetToUTF8 (dest : access cups_utf8_t; src : Interfaces.C.Strings.chars_ptr; maxout : int; encoding : CUPS.cups_language_h.cups_encoding_t) return int; -- cups/transcode.h:57 pragma Import (C, cupsCharsetToUTF8, "cupsCharsetToUTF8"); function cupsUTF8ToCharset (dest : Interfaces.C.Strings.chars_ptr; src : access cups_utf8_t; maxout : int; encoding : CUPS.cups_language_h.cups_encoding_t) return int; -- cups/transcode.h:61 pragma Import (C, cupsUTF8ToCharset, "cupsUTF8ToCharset"); function cupsUTF8ToUTF32 (dest : access cups_utf32_t; src : access cups_utf8_t; maxout : int) return int; -- cups/transcode.h:65 pragma Import (C, cupsUTF8ToUTF32, "cupsUTF8ToUTF32"); function cupsUTF32ToUTF8 (dest : access cups_utf8_t; src : access cups_utf32_t; maxout : int) return int; -- cups/transcode.h:68 pragma Import (C, cupsUTF32ToUTF8, "cupsUTF32ToUTF8"); -- * End of "$Id: transcode.h 10996 2013-05-29 11:51:34Z msweet $" -- end CUPS.cups_transcode_h;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- I N T E R F A C E S . V X W O R K S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1999-2005, AdaCore -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNARL is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNARL; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by Ada Core Technologies, Inc. -- -- -- ------------------------------------------------------------------------------ -- This package provides a limited binding to the VxWorks API -- In particular, it interfaces with the VxWorks hardware interrupt -- facilities, allowing the use of low-latency direct-vectored -- interrupt handlers. Note that such handlers have a variety of -- restrictions regarding system calls and language constructs. In particular, -- the use of exception handlers and functions returning variable-length -- objects cannot be used. Less restrictive, but higher-latency handlers can -- be written using Ada protected procedures, Ada 83 style interrupt entries, -- or by signalling an Ada task from within an interrupt handler using a -- binary semaphore as described in the VxWorks Programmer's Manual. -- -- For complete documentation of the operations in this package, please -- consult the VxWorks Programmer's Manual and VxWorks Reference Manual. with System.VxWorks; package Interfaces.VxWorks is pragma Preelaborate; ------------------------------------------------------------------------ -- Here is a complete example that shows how to handle the Interrupt 0x14 -- with a direct-vectored interrupt handler in Ada using this package: -- with Interfaces.VxWorks; use Interfaces.VxWorks; -- with System; -- -- package P is -- -- Count : Integer; -- pragma Atomic (Count); -- -- Level : constant := 1; -- -- Interrupt level used by this example -- -- procedure Handler (parameter : System.Address); -- -- end P; -- -- package body P is -- -- procedure Handler (parameter : System.Address) is -- S : STATUS; -- begin -- Count := Count + 1; -- logMsg ("received an interrupt" & ASCII.LF & ASCII.Nul); -- -- -- Acknowledge VME interrupt -- S := sysBusIntAck (intLevel => Level); -- end Handler; -- end P; -- -- with Interfaces.VxWorks; use Interfaces.VxWorks; -- with Ada.Text_IO; use Ada.Text_IO; -- -- with P; use P; -- procedure Useint is -- -- Be sure to use a reasonable interrupt number for the target -- -- board! -- -- This one is the unused VME graphics interrupt on the PPC MV2604 -- Interrupt : constant := 16#14#; -- -- task T; -- -- S : STATUS; -- -- task body T is -- begin -- loop -- Put_Line ("Generating an interrupt..."); -- delay 1.0; -- -- -- Generate VME interrupt, using interrupt number -- S := sysBusIntGen (1, Interrupt); -- end loop; -- end T; -- -- begin -- S := sysIntEnable (intLevel => Level); -- S := intConnect (INUM_TO_IVEC (Interrupt), handler'Access); -- -- loop -- delay 2.0; -- Put_Line ("value of count:" & P.Count'Img); -- end loop; -- end Useint; ------------------------------------- subtype int is Integer; type STATUS is new int; -- Equivalent of the C type STATUS OK : constant STATUS := 0; ERROR : constant STATUS := -1; type VOIDFUNCPTR is access procedure (parameter : System.Address); type Interrupt_Vector is new System.Address; type Exception_Vector is new System.Address; function intConnect (vector : Interrupt_Vector; handler : VOIDFUNCPTR; parameter : System.Address := System.Null_Address) return STATUS; -- Binding to the C routine intConnect. Use this to set up an -- user handler. The routine generates a wrapper around the user -- handler to save and restore context function intContext return int; -- Binding to the C routine intContext. This function returns 1 only -- if the current execution state is in interrupt context. function intVecGet (Vector : Interrupt_Vector) return VOIDFUNCPTR; -- Binding to the C routine intVecGet. Use this to get the -- existing handler for later restoral procedure intVecSet (Vector : Interrupt_Vector; Handler : VOIDFUNCPTR); -- Binding to the C routine intVecSet. Use this to restore a -- handler obtained using intVecGet function INUM_TO_IVEC (intNum : int) return Interrupt_Vector; -- Equivalent to the C macro INUM_TO_IVEC used to convert an interrupt -- number to an interrupt vector function sysIntEnable (intLevel : int) return STATUS; -- Binding to the C routine sysIntEnable function sysIntDisable (intLevel : int) return STATUS; -- Binding to the C routine sysIntDisable function sysBusIntAck (intLevel : int) return STATUS; -- Binding to the C routine sysBusIntAck function sysBusIntGen (intLevel : int; Intnum : int) return STATUS; -- Binding to the C routine sysBusIntGen. Note that the T2 -- documentation implies that a vector address is the proper -- argument - it's not. The interrupt number in the range -- 0 .. 255 (for 68K and PPC) is the correct agument. procedure logMsg (fmt : String; arg1, arg2, arg3, arg4, arg5, arg6 : int := 0); -- Binding to the C routine logMsg. Note that it is the caller's -- responsibility to ensure that fmt is a null-terminated string -- (e.g logMsg ("Interrupt" & ASCII.NUL)) type FP_CONTEXT is private; -- Floating point context save and restore. Handlers using floating -- point must be bracketed with these calls. The pFpContext parameter -- should be an object of type FP_CONTEXT that is -- declared local to the handler. procedure fppRestore (pFpContext : in out FP_CONTEXT); -- Restore floating point context procedure fppSave (pFpContext : in out FP_CONTEXT); -- Save floating point context private type FP_CONTEXT is new System.VxWorks.FP_CONTEXT; -- Target-dependent floating point context type pragma Import (C, intConnect, "intConnect"); pragma Import (C, intContext, "intContext"); pragma Import (C, intVecGet, "intVecGet"); pragma Import (C, intVecSet, "intVecSet"); pragma Import (C, INUM_TO_IVEC, "__gnat_inum_to_ivec"); pragma Import (C, sysIntEnable, "sysIntEnable"); pragma Import (C, sysIntDisable, "sysIntDisable"); pragma Import (C, sysBusIntAck, "sysBusIntAck"); pragma Import (C, sysBusIntGen, "sysBusIntGen"); pragma Import (C, logMsg, "logMsg"); pragma Import (C, fppRestore, "fppRestore"); pragma Import (C, fppSave, "fppSave"); end Interfaces.VxWorks;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ W A R N -- -- -- -- B o d y -- -- -- -- Copyright (C) 1999-2006, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Alloc; with Atree; use Atree; with Einfo; use Einfo; with Errout; use Errout; with Fname; use Fname; with Lib; use Lib; with Nlists; use Nlists; with Opt; use Opt; with Sem; use Sem; with Sem_Ch8; use Sem_Ch8; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Sinput; use Sinput; with Snames; use Snames; with Stand; use Stand; with Table; package body Sem_Warn is -- The following table collects Id's of entities that are potentially -- unreferenced. See Check_Unset_Reference for further details. package Unreferenced_Entities is new Table.Table ( Table_Component_Type => Entity_Id, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => Alloc.Unreferenced_Entities_Initial, Table_Increment => Alloc.Unreferenced_Entities_Increment, Table_Name => "Unreferenced_Entities"); ------------------------------ -- Handling of Conditionals -- ------------------------------ -- Note: this is work in progress, the data structures and general approach -- are defined, but are not in use yet. ??? -- An entry is made in the following table for each branch of conditional, -- e.g. an if-then-elsif-else-endif structure creates three entries in this -- table. type Branch_Entry is record Sloc : Source_Ptr; -- Location for warnings associated with this branch Defs : Elist_Id; -- List of entities defined for the first time in this branch. On exit -- from a conditional structure, any entity that is in the list of all -- branches is removed (and the entity flagged as defined by the -- conditional as a whole). Thus after processing a conditional, Defs -- contains a list of entities defined in this branch for the first -- time, but not defined at all in some other branch of the same -- conditional. A value of No_Elist is used to represent the initial -- empty list. Next : Nat; -- Index of next branch for this conditional, zero = last branch end record; package Branch_Table is new Table.Table ( Table_Component_Type => Branch_Entry, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => Alloc.Branches_Initial, Table_Increment => Alloc.Branches_Increment, Table_Name => "Branches"); -- The following table is used to represent conditionals, there is one -- entry in this table for each conditional structure. type Conditional_Entry is record If_Stmt : Boolean; -- True for IF statement, False for CASE statement First_Branch : Nat; -- Index in Branch table of first branch, zero = none yet Current_Branch : Nat; -- Index in Branch table of current branch, zero = none yet end record; package Conditional_Table is new Table.Table ( Table_Component_Type => Conditional_Entry, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => Alloc.Conditionals_Initial, Table_Increment => Alloc.Conditionals_Increment, Table_Name => "Conditionals"); -- The following table is a stack that keeps track of the current -- conditional. The Last entry is the top of the stack. An Empty entry -- represents the start of a compilation unit. Non-zero entries in the -- stack are indexes into the conditional table. package Conditional_Stack is new Table.Table ( Table_Component_Type => Nat, Table_Index_Type => Nat, Table_Low_Bound => 1, Table_Initial => Alloc.Conditional_Stack_Initial, Table_Increment => Alloc.Conditional_Stack_Increment, Table_Name => "Conditional_Stack"); pragma Warnings (Off, Branch_Table); pragma Warnings (Off, Conditional_Table); pragma Warnings (Off, Conditional_Stack); -- Not yet referenced, see note above ??? ----------------------- -- Local Subprograms -- ----------------------- function Generic_Package_Spec_Entity (E : Entity_Id) return Boolean; -- This returns true if the entity E is declared within a generic package. -- The point of this is to detect variables which are not assigned within -- the generic, but might be assigned outside the package for any given -- instance. These are cases where we leave the warnings to be posted -- for the instance, when we will know more. function Operand_Has_Warnings_Suppressed (N : Node_Id) return Boolean; -- This function traverses the expression tree represented by the node N -- and determines if any sub-operand is a reference to an entity for which -- the Warnings_Off flag is set. True is returned if such an entity is -- encountered, and False otherwise. ---------------------- -- Check_References -- ---------------------- procedure Check_References (E : Entity_Id; Anod : Node_Id := Empty) is E1 : Entity_Id; UR : Node_Id; function Missing_Subunits return Boolean; -- We suppress warnings when there are missing subunits, because this -- may generate too many false positives: entities in a parent may only -- be referenced in one of the subunits. We make an exception for -- subunits that contain no other stubs. procedure Output_Reference_Error (M : String); -- Used to output an error message. Deals with posting the error on the -- body formal in the accept case. function Publicly_Referenceable (Ent : Entity_Id) return Boolean; -- This is true if the entity in question is potentially referenceable -- from another unit. This is true for entities in packages that are at -- the library level. ---------------------- -- Missing_Subunits -- ---------------------- function Missing_Subunits return Boolean is D : Node_Id; begin if not Unloaded_Subunits then -- Normal compilation, all subunits are present return False; elsif E /= Main_Unit_Entity then -- No warnings on a stub that is not the main unit return True; elsif Nkind (Unit_Declaration_Node (E)) in N_Proper_Body then D := First (Declarations (Unit_Declaration_Node (E))); while Present (D) loop -- No warnings if the proper body contains nested stubs if Nkind (D) in N_Body_Stub then return True; end if; Next (D); end loop; return False; else -- Missing stubs elsewhere return True; end if; end Missing_Subunits; ---------------------------- -- Output_Reference_Error -- ---------------------------- procedure Output_Reference_Error (M : String) is begin -- Other than accept case, post error on defining identifier if No (Anod) then Error_Msg_N (M, E1); -- Accept case, find body formal to post the message else declare Parm : Node_Id; Enod : Node_Id; Defid : Entity_Id; begin Enod := Anod; if Present (Parameter_Specifications (Anod)) then Parm := First (Parameter_Specifications (Anod)); while Present (Parm) loop Defid := Defining_Identifier (Parm); if Chars (E1) = Chars (Defid) then Enod := Defid; exit; end if; Next (Parm); end loop; end if; Error_Msg_NE (M, Enod, E1); end; end if; end Output_Reference_Error; ---------------------------- -- Publicly_Referenceable -- ---------------------------- function Publicly_Referenceable (Ent : Entity_Id) return Boolean is P : Node_Id; Prev : Node_Id; begin -- Examine parents to look for a library level package spec. But if -- we find a body or block or other similar construct along the way, -- we cannot be referenced. Prev := Ent; P := Parent (Ent); loop case Nkind (P) is -- If we get to top of tree, then publicly referenceable when N_Empty => return True; -- If we reach a generic package declaration, then always -- consider this referenceable, since any instantiation will -- have access to the entities in the generic package. Note -- that the package itself may not be instantiated, but then -- we will get a warning for the package entity. -- Note that generic formal parameters are themselves not -- publicly referenceable in an instance, and warnings on -- them are useful. when N_Generic_Package_Declaration => return not Is_List_Member (Prev) or else List_Containing (Prev) /= Generic_Formal_Declarations (P); -- Similarly, the generic formals of a generic subprogram -- are not accessible. when N_Generic_Subprogram_Declaration => if Is_List_Member (Prev) and then List_Containing (Prev) = Generic_Formal_Declarations (P) then return False; else P := Parent (P); end if; -- If we reach a subprogram body, entity is not referenceable -- unless it is the defining entity of the body. This will -- happen, e.g. when a function is an attribute renaming that -- is rewritten as a body. when N_Subprogram_Body => if Ent /= Defining_Entity (P) then return False; else P := Parent (P); end if; -- If we reach any other body, definitely not referenceable when N_Package_Body | N_Task_Body | N_Entry_Body | N_Protected_Body | N_Block_Statement | N_Subunit => return False; -- For all other cases, keep looking up tree when others => Prev := P; P := Parent (P); end case; end loop; end Publicly_Referenceable; -- Start of processing for Check_References begin -- No messages if warnings are suppressed, or if we have detected any -- real errors so far (this last check avoids junk messages resulting -- from errors, e.g. a subunit that is not loaded). if Warning_Mode = Suppress or else Serious_Errors_Detected /= 0 then return; end if; -- We also skip the messages if any subunits were not loaded (see -- comment in Sem_Ch10 to understand how this is set, and why it is -- necessary to suppress the warnings in this case). if Missing_Subunits then return; end if; -- Otherwise loop through entities, looking for suspicious stuff E1 := First_Entity (E); while Present (E1) loop -- We only look at source entities with warning flag on if Comes_From_Source (E1) and then not Warnings_Off (E1) then -- We are interested in variables and out parameters, but we -- exclude protected types, too complicated to worry about. if Ekind (E1) = E_Variable or else (Ekind (E1) = E_Out_Parameter and then not Is_Protected_Type (Current_Scope)) then -- Post warning if this object not assigned. Note that we do -- not consider the implicit initialization of an access type -- to be the assignment of a value for this purpose. if Ekind (E1) = E_Out_Parameter and then Present (Spec_Entity (E1)) then UR := Unset_Reference (Spec_Entity (E1)); else UR := Unset_Reference (E1); end if; -- If the entity is an out parameter of the current subprogram -- body, check the warning status of the parameter in the spec. if Ekind (E1) = E_Out_Parameter and then Present (Spec_Entity (E1)) and then Warnings_Off (Spec_Entity (E1)) then null; elsif Present (UR) and then Is_Access_Type (Etype (E1)) then -- For access types, the only time we made a UR entry was -- for a dereference, and so we post the appropriate warning -- here (note that the dereference may not be explicit in -- the source, for example in the case of a dispatching call -- with an anonymous access controlling formal, or of an -- assignment of a pointer involving discriminant check on -- the designated object). Error_Msg_NE ("& may be null?", UR, E1); goto Continue; elsif Never_Set_In_Source (E1) and then not Generic_Package_Spec_Entity (E1) then if Warn_On_No_Value_Assigned then -- Do not output complaint about never being assigned a -- value if a pragma Unreferenced applies to the variable -- or if it is a parameter, to the corresponding spec. if Has_Pragma_Unreferenced (E1) or else (Is_Formal (E1) and then Present (Spec_Entity (E1)) and then Has_Pragma_Unreferenced (Spec_Entity (E1))) then null; -- Pragma Unreferenced not set, so output message else Output_Reference_Error ("& is never assigned a value?"); -- Deal with special case where this variable is -- hidden by a loop variable if Ekind (E1) = E_Variable and then Present (Hiding_Loop_Variable (E1)) then Error_Msg_Sloc := Sloc (E1); Error_Msg_N ("declaration hides &#?", Hiding_Loop_Variable (E1)); Error_Msg_N ("for loop implicitly declares loop variable?", Hiding_Loop_Variable (E1)); end if; end if; end if; goto Continue; -- Case of variable that could be a constant. Note that we -- never signal such messages for generic package entities, -- since a given instance could have modifications outside -- the package. elsif Warn_On_Constant and then Ekind (E1) = E_Variable and then Is_True_Constant (E1) and then not Generic_Package_Spec_Entity (E1) then -- A special case, if this variable is volatile and not -- imported, it is not helpful to tell the programmer -- to mark the variable as constant, since this would be -- illegal by virtue of RM C.6(13). if (Is_Volatile (E1) or else Has_Volatile_Components (E1)) and then not Is_Imported (E1) then Error_Msg_N ("& is not modified, volatile has no effect?", E1); else Error_Msg_N ("& is not modified, could be declared constant?", E1); end if; end if; -- Check for unset reference, note that we exclude access -- types from this check, since access types do always have -- a null value, and that seems legitimate in this case. if Warn_On_No_Value_Assigned and then Present (UR) then -- For other than access type, go back to original node -- to deal with case where original unset reference -- has been rewritten during expansion. UR := Original_Node (UR); -- In some cases, the original node may be a type -- conversion or qualification, and in this case -- we want the object entity inside. while Nkind (UR) = N_Type_Conversion or else Nkind (UR) = N_Qualified_Expression loop UR := Expression (UR); end loop; -- Here we issue the warning, all checks completed If the -- unset reference is prefix of a selected component that -- comes from source, mention the component as well. If the -- selected component comes from expansion, all we know is -- that the entity is not fully initialized at the point of -- the reference. Locate an unintialized component to get a -- better error message. if Nkind (Parent (UR)) = N_Selected_Component then Error_Msg_Node_2 := Selector_Name (Parent (UR)); if not Comes_From_Source (Parent (UR)) then declare Comp : Entity_Id; begin Comp := First_Entity (Etype (E1)); while Present (Comp) loop if Ekind (Comp) = E_Component and then Nkind (Parent (Comp)) = N_Component_Declaration and then No (Expression (Parent (Comp))) then Error_Msg_Node_2 := Comp; exit; end if; Next_Entity (Comp); end loop; end; end if; Error_Msg_N ("`&.&` may be referenced before it has a value?", UR); else Error_Msg_N ("& may be referenced before it has a value?", UR); end if; goto Continue; end if; end if; -- Then check for unreferenced entities. Note that we are only -- interested in entities which do not have the Referenced flag -- set. The Referenced_As_LHS flag is interesting only if the -- Referenced flag is not set. if not Referenced (E1) -- Check that warnings on unreferenced entities are enabled and then ((Check_Unreferenced and then not Is_Formal (E1)) or else (Check_Unreferenced_Formals and then Is_Formal (E1)) or else (Warn_On_Modified_Unread and then Referenced_As_LHS (E1))) -- Labels, and enumeration literals, and exceptions. The -- warnings are also placed on local packages that cannot be -- referenced from elsewhere, including those declared within a -- package body. and then (Is_Object (E1) or else Is_Type (E1) or else Ekind (E1) = E_Label or else Ekind (E1) = E_Exception or else Ekind (E1) = E_Named_Integer or else Ekind (E1) = E_Named_Real or else Is_Overloadable (E1) or else (Ekind (E1) = E_Package and then (Ekind (E) = E_Function or else Ekind (E) = E_Package_Body or else Ekind (E) = E_Procedure or else Ekind (E) = E_Subprogram_Body or else Ekind (E) = E_Block))) -- Exclude instantiations, since there is no reason why every -- entity in an instantiation should be referenced. and then Instantiation_Location (Sloc (E1)) = No_Location -- Exclude formal parameters from bodies if the corresponding -- spec entity has been referenced in the case where there is -- a separate spec. and then not (Is_Formal (E1) and then Ekind (Scope (E1)) = E_Subprogram_Body and then Present (Spec_Entity (E1)) and then Referenced (Spec_Entity (E1))) -- Consider private type referenced if full view is referenced -- If there is not full view, this is a generic type on which -- warnings are also useful. and then not (Is_Private_Type (E1) and then Present (Full_View (E1)) and then Referenced (Full_View (E1))) -- Don't worry about full view, only about private type and then not Has_Private_Declaration (E1) -- Eliminate dispatching operations from consideration, we -- cannot tell if these are referenced or not in any easy -- manner (note this also catches Adjust/Finalize/Initialize) and then not Is_Dispatching_Operation (E1) -- Check entity that can be publicly referenced (we do not give -- messages for such entities, since there could be other -- units, not involved in this compilation, that contain -- relevant references. and then not Publicly_Referenceable (E1) -- Class wide types are marked as source entities, but they are -- not really source entities, and are always created, so we do -- not care if they are not referenced. and then Ekind (E1) /= E_Class_Wide_Type -- Objects other than parameters of task types are allowed to -- be non-referenced, since they start up tasks! and then ((Ekind (E1) /= E_Variable and then Ekind (E1) /= E_Constant and then Ekind (E1) /= E_Component) or else not Is_Task_Type (Etype (E1))) -- For subunits, only place warnings on the main unit itself, -- since parent units are not completely compiled and then (Nkind (Unit (Cunit (Main_Unit))) /= N_Subunit or else Get_Source_Unit (E1) = Main_Unit) then -- Suppress warnings in internal units if not in -gnatg mode -- (these would be junk warnings for an applications program, -- since they refer to problems in internal units) if GNAT_Mode or else not Is_Internal_File_Name (Unit_File_Name (Get_Source_Unit (E1))) then -- We do not immediately flag the error. This is because we -- have not expanded generic bodies yet, and they may have -- the missing reference. So instead we park the entity on a -- list, for later processing. However, for the accept case, -- post the error right here, since we have the information -- now in this case. if Present (Anod) then Output_Reference_Error ("& is not referenced?"); else Unreferenced_Entities.Increment_Last; Unreferenced_Entities.Table (Unreferenced_Entities.Last) := E1; end if; end if; -- Generic units are referenced in the generic body, but if they -- are not public and never instantiated we want to force a -- warning on them. We treat them as redundant constructs to -- minimize noise. elsif Is_Generic_Subprogram (E1) and then not Is_Instantiated (E1) and then not Publicly_Referenceable (E1) and then Instantiation_Depth (Sloc (E1)) = 0 and then Warn_On_Redundant_Constructs then Unreferenced_Entities.Increment_Last; Unreferenced_Entities.Table (Unreferenced_Entities.Last) := E1; -- Force warning on entity Set_Referenced (E1, False); end if; end if; -- Recurse into nested package or block. Do not recurse into a -- formal package, because the correponding body is not analyzed. <<Continue>> if ((Ekind (E1) = E_Package or else Ekind (E1) = E_Generic_Package) and then Nkind (Parent (E1)) = N_Package_Specification and then Nkind (Original_Node (Unit_Declaration_Node (E1))) /= N_Formal_Package_Declaration) or else Ekind (E1) = E_Block then Check_References (E1); end if; Next_Entity (E1); end loop; end Check_References; --------------------------- -- Check_Unset_Reference -- --------------------------- procedure Check_Unset_Reference (N : Node_Id) is begin -- Nothing to do if warnings suppressed if Warning_Mode = Suppress then return; end if; -- Ignore reference to non-scalar if not from source. Almost always such -- references are bogus (e.g. calls to init procs to set default -- discriminant values). if not Comes_From_Source (N) and then not Is_Scalar_Type (Etype (N)) then return; end if; -- Otherwise see what kind of node we have. If the entity already -- has an unset reference, it is not necessarily the earliest in -- the text, because resolution of the prefix of selected components -- is completed before the resolution of the selected component itself. -- as a result, given (R /= null and then R.X > 0), the occurrences -- of R are examined in right-to-left order. If there is already an -- unset reference, we check whether N is earlier before proceeding. case Nkind (N) is when N_Identifier | N_Expanded_Name => declare E : constant Entity_Id := Entity (N); begin if (Ekind (E) = E_Variable or else Ekind (E) = E_Out_Parameter) and then Never_Set_In_Source (E) and then (No (Unset_Reference (E)) or else Earlier_In_Extended_Unit (Sloc (N), Sloc (Unset_Reference (E)))) and then not Warnings_Off (E) then -- We may have an unset reference. The first test is whether -- we are accessing a discriminant of a record or a -- component with default initialization. Both of these -- cases can be ignored, since the actual object that is -- referenced is definitely initialized. Note that this -- covers the case of reading discriminants of an out -- parameter, which is OK even in Ada 83. -- Note that we are only interested in a direct reference to -- a record component here. If the reference is via an -- access type, then the access object is being referenced, -- not the record, and still deserves an unset reference. if Nkind (Parent (N)) = N_Selected_Component and not Is_Access_Type (Etype (N)) then declare ES : constant Entity_Id := Entity (Selector_Name (Parent (N))); begin if Ekind (ES) = E_Discriminant or else Present (Expression (Declaration_Node (ES))) then return; end if; end; end if; -- Here we have a potential unset reference. But before we -- get worried about it, we have to make sure that the -- entity declaration is in the same procedure as the -- reference, since if they are in separate procedures, then -- we have no idea about sequential execution. -- The tests in the loop below catch all such cases, but do -- allow the reference to appear in a loop, block, or -- package spec that is nested within the declaring scope. -- As always, it is possible to construct cases where the -- warning is wrong, that is why it is a warning! declare SR : Entity_Id; SE : constant Entity_Id := Scope (E); begin SR := Current_Scope; while SR /= SE loop if SR = Standard_Standard or else Is_Subprogram (SR) or else Is_Concurrent_Body (SR) or else Is_Concurrent_Type (SR) then return; end if; SR := Scope (SR); end loop; -- Case of reference has an access type. This is special -- case since access types are always set to null so -- cannot be truly uninitialized, but we still want to -- warn about cases of obvious null dereference. if Is_Access_Type (Etype (N)) then Access_Type_Case : declare P : Node_Id; function Process (N : Node_Id) return Traverse_Result; -- Process function for instantation of Traverse -- below. Checks if N contains reference to other -- than a dereference. function Ref_In (Nod : Node_Id) return Boolean; -- Determines whether Nod contains a reference to -- the entity E that is not a dereference. ------------- -- Process -- ------------- function Process (N : Node_Id) return Traverse_Result is begin if Is_Entity_Name (N) and then Entity (N) = E and then not Is_Dereferenced (N) then return Abandon; else return OK; end if; end Process; ------------ -- Ref_In -- ------------ function Ref_In (Nod : Node_Id) return Boolean is function Traverse is new Traverse_Func (Process); begin return Traverse (Nod) = Abandon; end Ref_In; -- Start of processing for Access_Type_Case begin -- Don't bother if we are inside an instance, -- since the compilation of the generic template -- is where the warning should be issued. if In_Instance then return; end if; -- Don't bother if this is not the main unit. -- If we try to give this warning for with'ed -- units, we get some false positives, since -- we do not record references in other units. if not In_Extended_Main_Source_Unit (E) or else not In_Extended_Main_Source_Unit (N) then return; end if; -- We are only interested in deferences if not Is_Dereferenced (N) then return; end if; -- One more check, don't bother with references -- that are inside conditional statements or while -- loops if the condition references the entity in -- question. This avoids most false positives. P := Parent (N); loop P := Parent (P); exit when No (P); if (Nkind (P) = N_If_Statement or else Nkind (P) = N_Elsif_Part) and then Ref_In (Condition (P)) then return; elsif Nkind (P) = N_Loop_Statement and then Present (Iteration_Scheme (P)) and then Ref_In (Condition (Iteration_Scheme (P))) then return; end if; end loop; end Access_Type_Case; end if; -- Here we definitely have a case for giving a warning -- for a reference to an unset value. But we don't give -- the warning now. Instead we set the Unset_Reference -- field of the identifier involved. The reason for this -- is that if we find the variable is never ever assigned -- a value then that warning is more important and there -- is no point in giving the reference warning. -- If this is an identifier, set the field directly if Nkind (N) = N_Identifier then Set_Unset_Reference (E, N); -- Otherwise it is an expanded name, so set the field -- of the actual identifier for the reference. else Set_Unset_Reference (E, Selector_Name (N)); end if; end; end if; end; when N_Indexed_Component | N_Slice => Check_Unset_Reference (Prefix (N)); when N_Selected_Component => if Present (Entity (Selector_Name (N))) and then Ekind (Entity (Selector_Name (N))) = E_Discriminant then -- A discriminant is always initialized null; else Check_Unset_Reference (Prefix (N)); end if; when N_Type_Conversion | N_Qualified_Expression => Check_Unset_Reference (Expression (N)); when others => null; end case; end Check_Unset_Reference; ------------------------ -- Check_Unused_Withs -- ------------------------ procedure Check_Unused_Withs (Spec_Unit : Unit_Number_Type := No_Unit) is Cnode : Node_Id; Item : Node_Id; Lunit : Node_Id; Ent : Entity_Id; Munite : constant Entity_Id := Cunit_Entity (Main_Unit); -- This is needed for checking the special renaming case procedure Check_One_Unit (Unit : Unit_Number_Type); -- Subsidiary procedure, performs checks for specified unit -------------------- -- Check_One_Unit -- -------------------- procedure Check_One_Unit (Unit : Unit_Number_Type) is Is_Visible_Renaming : Boolean := False; Pack : Entity_Id; procedure Check_Inner_Package (Pack : Entity_Id); -- Pack is a package local to a unit in a with_clause. Both the -- unit and Pack are referenced. If none of the entities in Pack -- are referenced, then the only occurrence of Pack is in a use -- clause or a pragma, and a warning is worthwhile as well. function Check_System_Aux return Boolean; -- Before giving a warning on a with_clause for System, check -- whether a system extension is present. function Find_Package_Renaming (P : Entity_Id; L : Entity_Id) return Entity_Id; -- The only reference to a context unit may be in a renaming -- declaration. If this renaming declares a visible entity, do -- not warn that the context clause could be moved to the body, -- because the renaming may be intented to re-export the unit. ------------------------- -- Check_Inner_Package -- ------------------------- procedure Check_Inner_Package (Pack : Entity_Id) is E : Entity_Id; Un : constant Node_Id := Sinfo.Unit (Cnode); function Check_Use_Clause (N : Node_Id) return Traverse_Result; -- If N is a use_clause for Pack, emit warning procedure Check_Use_Clauses is new Traverse_Proc (Check_Use_Clause); ---------------------- -- Check_Use_Clause -- ---------------------- function Check_Use_Clause (N : Node_Id) return Traverse_Result is Nam : Node_Id; begin if Nkind (N) = N_Use_Package_Clause then Nam := First (Names (N)); while Present (Nam) loop if Entity (Nam) = Pack then Error_Msg_Qual_Level := 1; Error_Msg_NE ("no entities of package& are referenced?", Nam, Pack); Error_Msg_Qual_Level := 0; end if; Next (Nam); end loop; end if; return OK; end Check_Use_Clause; -- Start of processing for Check_Inner_Package begin E := First_Entity (Pack); while Present (E) loop if Referenced (E) then return; end if; Next_Entity (E); end loop; -- No entities of the package are referenced. Check whether the -- reference to the package itself is a use clause, and if so -- place a warning on it. Check_Use_Clauses (Un); end Check_Inner_Package; ---------------------- -- Check_System_Aux -- ---------------------- function Check_System_Aux return Boolean is Ent : Entity_Id; begin if Chars (Lunit) = Name_System and then Scope (Lunit) = Standard_Standard and then Present_System_Aux then Ent := First_Entity (System_Aux_Id); while Present (Ent) loop if Referenced (Ent) then return True; end if; Next_Entity (Ent); end loop; end if; return False; end Check_System_Aux; --------------------------- -- Find_Package_Renaming -- --------------------------- function Find_Package_Renaming (P : Entity_Id; L : Entity_Id) return Entity_Id is E1 : Entity_Id; R : Entity_Id; begin Is_Visible_Renaming := False; E1 := First_Entity (P); while Present (E1) loop if Ekind (E1) = E_Package and then Renamed_Object (E1) = L then Is_Visible_Renaming := not Is_Hidden (E1); return E1; elsif Ekind (E1) = E_Package and then No (Renamed_Object (E1)) and then not Is_Generic_Instance (E1) then R := Find_Package_Renaming (E1, L); if Present (R) then Is_Visible_Renaming := not Is_Hidden (R); return R; end if; end if; Next_Entity (E1); end loop; return Empty; end Find_Package_Renaming; -- Start of processing for Check_One_Unit begin Cnode := Cunit (Unit); -- Only do check in units that are part of the extended main unit. -- This is actually a necessary restriction, because in the case of -- subprogram acting as its own specification, there can be with's in -- subunits that we will not see. if not In_Extended_Main_Source_Unit (Cnode) then return; -- In configurable run time mode, we remove the bodies of non-inlined -- subprograms, which may lead to spurious warnings, which are -- clearly undesirable. elsif Configurable_Run_Time_Mode and then Is_Predefined_File_Name (Unit_File_Name (Unit)) then return; end if; -- Loop through context items in this unit Item := First (Context_Items (Cnode)); while Present (Item) loop if Nkind (Item) = N_With_Clause and then not Implicit_With (Item) and then In_Extended_Main_Source_Unit (Item) then Lunit := Entity (Name (Item)); -- Check if this unit is referenced if not Referenced (Lunit) then -- Suppress warnings in internal units if not in -gnatg mode -- (these would be junk warnings for an application program, -- since they refer to problems in internal units) if GNAT_Mode or else not Is_Internal_File_Name (Unit_File_Name (Unit)) then -- Here we definitely have a non-referenced unit. If it -- is the special call for a spec unit, then just set the -- flag to be read later. if Unit = Spec_Unit then Set_Unreferenced_In_Spec (Item); -- Otherwise simple unreferenced message else Error_Msg_N ("unit& is not referenced?", Name (Item)); end if; end if; -- If main unit is a renaming of this unit, then we consider -- the with to be OK (obviously it is needed in this case!) elsif Present (Renamed_Entity (Munite)) and then Renamed_Entity (Munite) = Lunit then null; -- If this unit is referenced, and it is a package, we do -- another test, to see if any of the entities in the package -- are referenced. If none of the entities are referenced, we -- still post a warning. This occurs if the only use of the -- package is in a use clause, or in a package renaming -- declaration. elsif Ekind (Lunit) = E_Package then -- If Is_Instantiated is set, it means that the package is -- implicitly instantiated (this is the case of parent -- instance or an actual for a generic package formal), and -- this counts as a reference. if Is_Instantiated (Lunit) then null; -- If no entities in package, and there is a pragma -- Elaborate_Body present, then assume that this with is -- done for purposes of this elaboration. elsif No (First_Entity (Lunit)) and then Has_Pragma_Elaborate_Body (Lunit) then null; -- Otherwise see if any entities have been referenced else if Limited_Present (Item) then Ent := First_Entity (Limited_View (Lunit)); else Ent := First_Entity (Lunit); end if; loop -- No more entities, and we did not find one that was -- referenced. Means we have a definite case of a with -- none of whose entities was referenced. if No (Ent) then -- If in spec, just set the flag if Unit = Spec_Unit then Set_No_Entities_Ref_In_Spec (Item); elsif Check_System_Aux then null; -- Else give the warning else Error_Msg_N ("no entities of & are referenced?", Name (Item)); -- Look for renamings of this package, and flag -- them as well. If the original package has -- warnings off, we suppress the warning on the -- renaming as well. Pack := Find_Package_Renaming (Munite, Lunit); if Present (Pack) and then not Warnings_Off (Lunit) then Error_Msg_NE ("no entities of & are referenced?", Unit_Declaration_Node (Pack), Pack); end if; end if; exit; -- Case of next entity is referenced elsif Referenced (Ent) or else Referenced_As_LHS (Ent) then -- This means that the with is indeed fine, in that -- it is definitely needed somewhere, and we can -- quite worrying about this one. -- Except for one little detail, if either of the -- flags was set during spec processing, this is -- where we complain that the with could be moved -- from the spec. If the spec contains a visible -- renaming of the package, inhibit warning to move -- with_clause to body. if Ekind (Munite) = E_Package_Body then Pack := Find_Package_Renaming (Spec_Entity (Munite), Lunit); end if; if Unreferenced_In_Spec (Item) then Error_Msg_N ("unit& is not referenced in spec?", Name (Item)); elsif No_Entities_Ref_In_Spec (Item) then Error_Msg_N ("no entities of & are referenced in spec?", Name (Item)); else if Ekind (Ent) = E_Package then Check_Inner_Package (Ent); end if; exit; end if; if not Is_Visible_Renaming then Error_Msg_N ("\with clause might be moved to body?", Name (Item)); end if; exit; -- Move to next entity to continue search else Next_Entity (Ent); end if; end loop; end if; -- For a generic package, the only interesting kind of -- reference is an instantiation, since entities cannot be -- referenced directly. elsif Is_Generic_Unit (Lunit) then -- Unit was never instantiated, set flag for case of spec -- call, or give warning for normal call. if not Is_Instantiated (Lunit) then if Unit = Spec_Unit then Set_Unreferenced_In_Spec (Item); else Error_Msg_N ("unit& is never instantiated?", Name (Item)); end if; -- If unit was indeed instantiated, make sure that flag is -- not set showing it was uninstantiated in the spec, and if -- so, give warning. elsif Unreferenced_In_Spec (Item) then Error_Msg_N ("unit& is not instantiated in spec?", Name (Item)); Error_Msg_N ("\with clause can be moved to body?", Name (Item)); end if; end if; end if; Next (Item); end loop; end Check_One_Unit; -- Start of processing for Check_Unused_Withs begin if not Opt.Check_Withs or else Operating_Mode = Check_Syntax then return; end if; -- Flag any unused with clauses, but skip this step if we are compiling -- a subunit on its own, since we do not have enough information to -- determine whether with's are used. We will get the relevant warnings -- when we compile the parent. This is the normal style of GNAT -- compilation in any case. if Nkind (Unit (Cunit (Main_Unit))) = N_Subunit then return; end if; -- Process specified units if Spec_Unit = No_Unit then -- For main call, check all units for Unit in Main_Unit .. Last_Unit loop Check_One_Unit (Unit); end loop; else -- For call for spec, check only the spec Check_One_Unit (Spec_Unit); end if; end Check_Unused_Withs; --------------------------------- -- Generic_Package_Spec_Entity -- --------------------------------- function Generic_Package_Spec_Entity (E : Entity_Id) return Boolean is S : Entity_Id; begin if Is_Package_Body_Entity (E) then return False; else S := Scope (E); loop if S = Standard_Standard then return False; elsif Ekind (S) = E_Generic_Package then return True; elsif Ekind (S) = E_Package then S := Scope (S); else return False; end if; end loop; end if; end Generic_Package_Spec_Entity; ------------------------------------- -- Operand_Has_Warnings_Suppressed -- ------------------------------------- function Operand_Has_Warnings_Suppressed (N : Node_Id) return Boolean is function Check_For_Warnings (N : Node_Id) return Traverse_Result; -- Function used to check one node to see if it is or was originally -- a reference to an entity for which Warnings are off. If so, Abandon -- is returned, otherwise OK_Orig is returned to continue the traversal -- of the original expression. function Traverse is new Traverse_Func (Check_For_Warnings); -- Function used to traverse tree looking for warnings ------------------------ -- Check_For_Warnings -- ------------------------ function Check_For_Warnings (N : Node_Id) return Traverse_Result is R : constant Node_Id := Original_Node (N); begin if Nkind (R) in N_Has_Entity and then Present (Entity (R)) and then Warnings_Off (Entity (R)) then return Abandon; else return OK_Orig; end if; end Check_For_Warnings; -- Start of processing for Operand_Has_Warnings_Suppressed begin return Traverse (N) = Abandon; -- If any exception occurs, then something has gone wrong, and this is -- only a minor aesthetic issue anyway, so just say we did not find what -- we are looking for, rather than blow up. exception when others => return False; end Operand_Has_Warnings_Suppressed; ---------------------------------- -- Output_Unreferenced_Messages -- ---------------------------------- procedure Output_Unreferenced_Messages is E : Entity_Id; begin for J in Unreferenced_Entities.First .. Unreferenced_Entities.Last loop E := Unreferenced_Entities.Table (J); if not Referenced (E) and then not Warnings_Off (E) then case Ekind (E) is when E_Variable => -- Case of variable that is assigned but not read. We -- suppress the message if the variable is volatile, has an -- address clause, or is imported. if Referenced_As_LHS (E) and then No (Address_Clause (E)) and then not Is_Volatile (E) then if Warn_On_Modified_Unread and then not Is_Imported (E) -- Suppress the message for aliased or renamed -- variables, since there may be other entities read -- the same memory location. and then not Is_Aliased (E) and then No (Renamed_Object (E)) then Error_Msg_N ("variable & is assigned but never read?", E); end if; -- Normal case of neither assigned nor read else if Present (Renamed_Object (E)) and then Comes_From_Source (Renamed_Object (E)) then Error_Msg_N ("renamed variable & is not referenced?", E); else Error_Msg_N ("variable & is not referenced?", E); end if; end if; when E_Constant => if Present (Renamed_Object (E)) and then Comes_From_Source (Renamed_Object (E)) then Error_Msg_N ("renamed constant & is not referenced?", E); else Error_Msg_N ("constant & is not referenced?", E); end if; when E_In_Parameter | E_Out_Parameter | E_In_Out_Parameter => -- Do not emit message for formals of a renaming, because -- they are never referenced explicitly. if Nkind (Original_Node (Unit_Declaration_Node (Scope (E)))) /= N_Subprogram_Renaming_Declaration then Error_Msg_N ("formal parameter & is not referenced?", E); end if; when E_Named_Integer | E_Named_Real => Error_Msg_N ("named number & is not referenced?", E); when E_Enumeration_Literal => Error_Msg_N ("literal & is not referenced?", E); when E_Function => Error_Msg_N ("function & is not referenced?", E); when E_Procedure => Error_Msg_N ("procedure & is not referenced?", E); when E_Generic_Procedure => Error_Msg_N ("generic procedure & is never instantiated?", E); when E_Generic_Function => Error_Msg_N ("generic function & is never instantiated?", E); when Type_Kind => Error_Msg_N ("type & is not referenced?", E); when others => Error_Msg_N ("& is not referenced?", E); end case; Set_Warnings_Off (E); end if; end loop; end Output_Unreferenced_Messages; ------------------------ -- Set_Warning_Switch -- ------------------------ function Set_Warning_Switch (C : Character) return Boolean is begin case C is when 'a' => Check_Unreferenced := True; Check_Unreferenced_Formals := True; Check_Withs := True; Constant_Condition_Warnings := True; Implementation_Unit_Warnings := True; Ineffective_Inline_Warnings := True; Warn_On_Ada_2005_Compatibility := True; Warn_On_Bad_Fixed_Value := True; Warn_On_Constant := True; Warn_On_Export_Import := True; Warn_On_Modified_Unread := True; Warn_On_No_Value_Assigned := True; Warn_On_Obsolescent_Feature := True; Warn_On_Redundant_Constructs := True; Warn_On_Unchecked_Conversion := True; Warn_On_Unrecognized_Pragma := True; when 'A' => Check_Unreferenced := False; Check_Unreferenced_Formals := False; Check_Withs := False; Constant_Condition_Warnings := False; Elab_Warnings := False; Implementation_Unit_Warnings := False; Ineffective_Inline_Warnings := False; Warn_On_Ada_2005_Compatibility := False; Warn_On_Bad_Fixed_Value := False; Warn_On_Constant := False; Warn_On_Dereference := False; Warn_On_Export_Import := False; Warn_On_Hiding := False; Warn_On_Modified_Unread := False; Warn_On_No_Value_Assigned := False; Warn_On_Obsolescent_Feature := False; Warn_On_Redundant_Constructs := False; Warn_On_Unchecked_Conversion := False; Warn_On_Unrecognized_Pragma := False; when 'b' => Warn_On_Bad_Fixed_Value := True; when 'B' => Warn_On_Bad_Fixed_Value := False; when 'c' => Constant_Condition_Warnings := True; when 'C' => Constant_Condition_Warnings := False; when 'd' => Warn_On_Dereference := True; when 'D' => Warn_On_Dereference := False; when 'e' => Warning_Mode := Treat_As_Error; when 'f' => Check_Unreferenced_Formals := True; when 'F' => Check_Unreferenced_Formals := False; when 'g' => Warn_On_Unrecognized_Pragma := True; when 'G' => Warn_On_Unrecognized_Pragma := False; when 'h' => Warn_On_Hiding := True; when 'H' => Warn_On_Hiding := False; when 'i' => Implementation_Unit_Warnings := True; when 'I' => Implementation_Unit_Warnings := False; when 'j' => Warn_On_Obsolescent_Feature := True; when 'J' => Warn_On_Obsolescent_Feature := False; when 'k' => Warn_On_Constant := True; when 'K' => Warn_On_Constant := False; when 'l' => Elab_Warnings := True; when 'L' => Elab_Warnings := False; when 'm' => Warn_On_Modified_Unread := True; when 'M' => Warn_On_Modified_Unread := False; when 'n' => Warning_Mode := Normal; when 'o' => Address_Clause_Overlay_Warnings := True; when 'O' => Address_Clause_Overlay_Warnings := False; when 'p' => Ineffective_Inline_Warnings := True; when 'P' => Ineffective_Inline_Warnings := False; when 'r' => Warn_On_Redundant_Constructs := True; when 'R' => Warn_On_Redundant_Constructs := False; when 's' => Warning_Mode := Suppress; when 'u' => Check_Unreferenced := True; Check_Withs := True; Check_Unreferenced_Formals := True; when 'U' => Check_Unreferenced := False; Check_Withs := False; Check_Unreferenced_Formals := False; when 'v' => Warn_On_No_Value_Assigned := True; when 'V' => Warn_On_No_Value_Assigned := False; when 'x' => Warn_On_Export_Import := True; when 'X' => Warn_On_Export_Import := False; when 'y' => Warn_On_Ada_2005_Compatibility := True; when 'Y' => Warn_On_Ada_2005_Compatibility := False; when 'z' => Warn_On_Unchecked_Conversion := True; when 'Z' => Warn_On_Unchecked_Conversion := False; -- Allow and ignore 'w' so that the old -- format (e.g. -gnatwuwl) will work. when 'w' => null; when others => return False; end case; return True; end Set_Warning_Switch; ----------------------------- -- Warn_On_Known_Condition -- ----------------------------- procedure Warn_On_Known_Condition (C : Node_Id) is P : Node_Id; begin -- Argument replacement in an inlined body can make conditions static. -- Do not emit warnings in this case. if In_Inlined_Body then return; end if; if Constant_Condition_Warnings and then Nkind (C) = N_Identifier and then (Entity (C) = Standard_False or else Entity (C) = Standard_True) and then Comes_From_Source (Original_Node (C)) and then not In_Instance then -- See if this is in a statement or a declaration P := Parent (C); loop -- If tree is not attached, do not issue warning (this is very -- peculiar, and probably arises from some other error condition) if No (P) then return; -- If we are in a declaration, then no warning, since in practice -- conditionals in declarations are used for intended tests which -- may be known at compile time, e.g. things like -- x : constant Integer := 2 + (Word'Size = 32); -- And a warning is annoying in such cases elsif Nkind (P) in N_Declaration or else Nkind (P) in N_Later_Decl_Item then return; -- Don't warn in assert pragma, since presumably tests in such -- a context are very definitely intended, and might well be -- known at compile time. Note that we have to test the original -- node, since assert pragmas get rewritten at analysis time. elsif Nkind (Original_Node (P)) = N_Pragma and then Chars (Original_Node (P)) = Name_Assert then return; end if; exit when Is_Statement (P); P := Parent (P); end loop; -- Here we issue the warning unless some sub-operand has warnings -- set off, in which case we suppress the warning for the node. If -- the original expression is an inequality, it has been expanded -- into a negation, and the value of the original expression is the -- negation of the equality. If the expression is an entity that -- appears within a negation, it is clearer to flag the negation -- itself, and report on its constant value. if not Operand_Has_Warnings_Suppressed (C) then declare True_Branch : Boolean := Entity (C) = Standard_True; Cond : Node_Id := C; begin if Present (Parent (C)) and then Nkind (Parent (C)) = N_Op_Not then True_Branch := not True_Branch; Cond := Parent (C); end if; if True_Branch then if Is_Entity_Name (Original_Node (C)) and then Nkind (Cond) /= N_Op_Not then Error_Msg_NE ("object & is always True?", Cond, Original_Node (C)); else Error_Msg_N ("condition is always True?", Cond); end if; else Error_Msg_N ("condition is always False?", Cond); end if; end; end if; end if; end Warn_On_Known_Condition; end Sem_Warn;
with Orka.Features.Atmosphere.Earth; with Orka.Features.Atmosphere.Rendering; with Orka.Resources.Locations; with Orka.Behaviors; with Orka.Cameras; with Orka.Rendering.Programs.Modules; with Planets; package Demo.Atmospheres is type Atmosphere is tagged limited private; function Create (Planet_Model : aliased Orka.Features.Atmosphere.Model_Data; Planet_Data : Planets.Planet_Characteristics; Location_Shaders : Orka.Resources.Locations.Location_Ptr; Location_Precomputed : Orka.Resources.Locations.Writable_Location_Ptr) return Atmosphere; function Shader_Module (Object : Atmosphere) return Orka.Rendering.Programs.Modules.Module; procedure Render (Object : in out Atmosphere; Camera : Orka.Cameras.Camera_Ptr; Planet, Star : Orka.Behaviors.Behavior_Ptr); private type Atmosphere is tagged limited record Program : Orka.Features.Atmosphere.Rendering.Atmosphere; Textures : Orka.Features.Atmosphere.Precomputed_Textures; end record; end Demo.Atmospheres;
----------------------------------------------------------------------- -- asf.requests -- ASF Requests -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Status; with AWS.Headers; package ASF.Requests.Web is type Request is new ASF.Requests.Request with private; type Request_Access is access all Request'Class; function Get_Parameter (R : Request; Name : String) return String; -- Iterate over the request parameters and executes the <b>Process</b> procedure. procedure Iterate_Parameters (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)); -- Set the AWS data received to initialize the request object. procedure Set_Request (Req : in out Request; Data : access AWS.Status.Data); -- Returns the name of the HTTP method with which this request was made, -- for example, GET, POST, or PUT. Same as the value of the CGI variable -- REQUEST_METHOD. function Get_Method (Req : in Request) return String; -- Returns the name and version of the protocol the request uses in the form -- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets, -- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL. function Get_Protocol (Req : in Request) return String; -- Returns the part of this request's URL from the protocol name up to the query -- string in the first line of the HTTP request. The web container does not decode -- this String. For example: -- First line of HTTP request Returned Value -- POST /some/path.html HTTP/1.1 /some/path.html -- GET http://foo.bar/a.html HTTP/1.0 /a.html -- HEAD /xyz?a=b HTTP/1.1 /xyz function Get_Request_URI (Req : in Request) return String; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any request header. function Get_Header (Req : in Request; Name : in String) return String; -- Returns all the values of the specified request header as an Enumeration -- of String objects. -- -- Some headers, such as Accept-Language can be sent by clients as several headers -- each with a different value rather than sending the header as a comma -- separated list. -- -- If the request did not include any headers of the specified name, this method -- returns an empty Enumeration. The header name is case insensitive. You can use -- this method with any request header. function Get_Headers (Req : in Request; Name : in String) return String; -- Iterate over the request headers and executes the <b>Process</b> procedure. procedure Iterate_Headers (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)); -- Returns the Internet Protocol (IP) address of the client or last proxy that -- sent the request. For HTTP servlets, same as the value of the CGI variable -- REMOTE_ADDR. function Get_Remote_Addr (Req : in Request) return String; -- Get the number of parts included in the request. function Get_Part_Count (Req : in Request) return Natural; -- Process the part at the given position and executes the <b>Process</b> operation -- with the part object. procedure Process_Part (Req : in out Request; Position : in Positive; Process : not null access procedure (Data : in ASF.Parts.Part'Class)); -- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation -- with the part object. procedure Process_Part (Req : in out Request; Id : in String; Process : not null access procedure (Data : in ASF.Parts.Part'Class)); private type Request is new ASF.Requests.Request with record Data : access AWS.Status.Data; Headers : AWS.Headers.List; end record; end ASF.Requests.Web;
package App is procedure Main with Export, Convention => C, External_Name => "app_main"; end App;
with RASCAL.ToolboxQuit; use RASCAL.ToolboxQuit; with RASCAL.Toolbox; use RASCAL.Toolbox; with RASCAL.OS; use RASCAL.OS; package Controller_MainWindow is type TEL_OpenWindow_Type is new Toolbox_UserEventListener(16#14#,-1,-1) with null record; type TEL_OKButtonPressed_Type is new Toolbox_UserEventListener(16#30#,-1,-1) with null record; type TEL_EscapeButtonPressed_Type is new Toolbox_UserEventListener(16#31#,-1,-1) with null record; type TEL_RenewSelected_Type is new Toolbox_UserEventListener(16#33#,-1,-1) with null record; -- -- -- procedure Handle (The : in TEL_OKButtonPressed_Type); -- -- -- procedure Handle (The : in TEL_EscapeButtonPressed_Type); -- -- -- procedure Handle (The : in TEL_RenewSelected_Type); -- -- The user has clicked on the iconbar icon - open the amin window. -- procedure Handle (The : in TEL_OpenWindow_Type); end Controller_MainWindow;
-- C43004A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK THAT CONSTRAINT_ERROR IS RAISED IF A VALUE FOR A -- NON-DISCRIMINANT SCALAR COMPONENT OF AN AGGREGATE IS NOT -- WITHIN THE RANGE OF THE COMPONENT'S SUBTYPE. -- HISTORY: -- BCB 01/22/88 CREATED ORIGINAL TEST. -- RJW 06/27/90 CORRECTED CONSTRAINTS OF TYPE DFIX. -- LDC 09/25/90 ADDED A BLOCK IN THE EXCEPTION HANDLER SO IT CAN -- NOT OPTIMIZE IT AWAY, ALSO INITIALIZED EACH -- OBJECT TO VALID DATA BEFORE DOING THE INVALID, -- MADE 'IDENT_XXX' FUNCTIONS SO THE COMPILER CAN -- NOT JUST EVALUATE THE ASSIGNMENT AND PUT IN CODE -- FOR A CONSTRAINT ERROR IN IS PLACE. -- JRL 06/07/96 Changed value in aggregate in subtest 4 to value -- guaranteed to be in the base range of the type FIX. -- Corrected typo. WITH REPORT; USE REPORT; PROCEDURE C43004A IS TYPE INT IS RANGE 1 .. 8; SUBTYPE SINT IS INT RANGE 2 .. 7; TYPE ENUM IS (VINCE, JOHN, TOM, PHIL, ROSA, JODIE, BRIAN, DAVE); SUBTYPE SENUM IS ENUM RANGE JOHN .. BRIAN; TYPE FL IS DIGITS 5 RANGE 0.0 .. 10.0; SUBTYPE SFL IS FL RANGE 1.0 .. 9.0; TYPE FIX IS DELTA 0.25 RANGE 0.0 .. 8.0; SUBTYPE SFIX IS FIX RANGE 1.0 .. 7.0; TYPE DINT IS NEW INTEGER RANGE 1 .. 8; SUBTYPE SDINT IS DINT RANGE 2 .. 7; TYPE DENUM IS NEW ENUM RANGE VINCE .. DAVE; SUBTYPE SDENUM IS DENUM RANGE JOHN .. BRIAN; TYPE DFL IS NEW FLOAT RANGE 0.0 .. 10.0; SUBTYPE SDFL IS DFL RANGE 1.0 .. 9.0; TYPE DFIX IS NEW FIX RANGE 0.5 .. 7.5; SUBTYPE SDFIX IS DFIX RANGE 1.0 .. 7.0; TYPE REC1 IS RECORD E1, E2, E3, E4, E5 : SENUM; END RECORD; TYPE REC2 IS RECORD E1, E2, E3, E4, E5 : SFIX; END RECORD; TYPE REC3 IS RECORD E1, E2, E3, E4, E5 : SDENUM; END RECORD; TYPE REC4 IS RECORD E1, E2, E3, E4, E5 : SDFIX; END RECORD; ARRAY_OBJ : ARRAY(1..2) OF INTEGER; A : ARRAY(1..5) OF SINT; B : REC1; C : ARRAY(1..5) OF SFL; D : REC2; E : ARRAY(1..5) OF SDINT; F : REC3; G : ARRAY(1..5) OF SDFL; H : REC4; GENERIC TYPE GENERAL_PURPOSE IS PRIVATE; FUNCTION GENEQUAL(ONE, TWO : GENERAL_PURPOSE) RETURN BOOLEAN; FUNCTION GENEQUAL(ONE, TWO : GENERAL_PURPOSE) RETURN BOOLEAN IS BEGIN IF EQUAL(3,3) THEN RETURN ONE = TWO; ELSE RETURN ONE /= TWO; END IF; END GENEQUAL; FUNCTION EQUAL IS NEW GENEQUAL(SENUM); FUNCTION EQUAL IS NEW GENEQUAL(SFL); FUNCTION EQUAL IS NEW GENEQUAL(SFIX); FUNCTION EQUAL IS NEW GENEQUAL(SDENUM); FUNCTION EQUAL IS NEW GENEQUAL(SDFL); FUNCTION EQUAL IS NEW GENEQUAL(SDFIX); GENERIC TYPE GENERAL_PURPOSE IS PRIVATE; WITH FUNCTION EQUAL_GENERAL(ONE, TWO : GENERAL_PURPOSE) RETURN BOOLEAN; FUNCTION GEN_IDENT (X : GENERAL_PURPOSE) RETURN GENERAL_PURPOSE; FUNCTION GEN_IDENT (X : GENERAL_PURPOSE) RETURN GENERAL_PURPOSE IS BEGIN IF EQUAL_GENERAL (X, X) THEN -- ALWAYS EQUAL. RETURN X; -- ALWAYS EXECUTED. END IF; -- NEVER EXECUTED. RETURN X; END GEN_IDENT; FUNCTION IDENT_FL IS NEW GEN_IDENT(FL, EQUAL); FUNCTION IDENT_FIX IS NEW GEN_IDENT(FIX, EQUAL); FUNCTION IDENT_DFL IS NEW GEN_IDENT(DFL, EQUAL); FUNCTION IDENT_DFIX IS NEW GEN_IDENT(DFIX, EQUAL); BEGIN TEST ("C43004A", "CHECK THAT CONSTRAINT_ERROR IS RAISED IF A " & "VALUE FOR A NON-DISCRIMINANT SCALAR COMPONENT " & "OF AN AGGREGATE IS NOT WITHIN THE RANGE OF " & "THE COMPONENT'S SUBTYPE"); ARRAY_OBJ := (1, 2); BEGIN A := (2,3,4,5,6); -- OK IF EQUAL (INTEGER (A(IDENT_INT(1))), INTEGER (A(IDENT_INT(2)))) THEN COMMENT ("DON'T OPTIMIZE A"); END IF; A := (SINT(IDENT_INT(1)),2,3,4,7); -- CONSTRAINT_ERROR BY AGGREGATE -- WITH INTEGER COMPONENTS. FAILED ("CONSTRAINT_ERROR WAS NOT RAISED - 1"); IF EQUAL (INTEGER (A(IDENT_INT(1))), INTEGER (A(IDENT_INT(1)))) THEN COMMENT ("DON'T OPTIMIZE A"); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => IF EQUAL (ARRAY_OBJ(IDENT_INT(1)), ARRAY_OBJ(IDENT_INT(2))) THEN COMMENT ("DON'T OPTIMIZE EXCEPTION HANDLER"); END IF; WHEN OTHERS => FAILED ("AN EXCEPTION OTHER THAN CONSTRAINT_ERROR " & "WAS RAISED - 1"); END; BEGIN B := (JOHN,TOM,PHIL,ROSA,JOHN); -- OK IF EQUAL (B.E1, B.E2) THEN COMMENT ("DON'T OPTIMIZE B"); END IF; B := (ENUM'VAL(IDENT_INT(ENUM'POS(DAVE))), TOM, PHIL, ROSA, JODIE); -- CONSTRAINT_ERROR BY AGGREGATE -- WITH COMPONENTS OF AN -- ENUMERATION TYPE. FAILED ("CONSTRAINT_ERROR WAS NOT RAISED - 2"); IF NOT EQUAL (B.E1, B.E1) THEN COMMENT ("DON'T OPTIMIZE B"); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => IF EQUAL (ARRAY_OBJ(IDENT_INT(1)), ARRAY_OBJ(IDENT_INT(2))) THEN COMMENT ("DON'T OPTIMIZE EXCEPTION HANDLER"); END IF; WHEN OTHERS => FAILED ("AN EXCEPTION OTHER THAN CONSTRAINT_ERROR " & "WAS RAISED - 2"); END; BEGIN C := (2.0,3.0,4.0,5.0,6.0); -- OK IF EQUAL (C(IDENT_INT(1)), C(IDENT_INT(2))) THEN COMMENT ("DON'T OPTIMIZE C"); END IF; C := (IDENT_FL(1.0),2.0,3.0,4.0,IDENT_FL(10.0)); -- CONSTRAINT_ERROR BY AGGREGATE -- WITH FLOATING POINT COMPONENTS. FAILED ("CONSTRAINT_ERROR WAS NOT RAISED - 3"); IF NOT EQUAL (C(IDENT_INT(1)), C(IDENT_INT(1))) THEN COMMENT ("DON'T OPTIMIZE C"); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => IF EQUAL (ARRAY_OBJ(IDENT_INT(1)), ARRAY_OBJ(IDENT_INT(2))) THEN COMMENT ("DON'T OPTIMIZE EXCEPTION HANDLER"); END IF; WHEN OTHERS => FAILED ("AN EXCEPTION OTHER THAN CONSTRAINT_ERROR " & "WAS RAISED - 3"); END; BEGIN D := (2.2,3.3,4.4,5.5,6.6); -- OK IF EQUAL (D.E1, D.E5) THEN COMMENT ("DON'T OPTIMIZE D"); END IF; D := (IDENT_FIX(1.0),2.1,3.3,4.4,IDENT_FIX(7.75)); -- CONSTRAINT_ERROR BY AGGREGATE -- WITH FIXED POINT COMPONENTS. FAILED ("CONSTRAINT_ERROR WAS NOT RAISED - 4"); IF NOT EQUAL (D.E5, D.E5) THEN COMMENT ("DON'T OPTIMIZE D"); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => IF EQUAL (ARRAY_OBJ(IDENT_INT(1)), ARRAY_OBJ(IDENT_INT(2))) THEN COMMENT ("DON'T OPTIMIZE EXCEPTION HANDLER"); END IF; WHEN OTHERS => FAILED ("AN EXCEPTION OTHER THAN CONSTRAINT_ERROR " & "WAS RAISED - 4"); END; BEGIN E := (2,3,4,5,6); -- OK IF EQUAL (INTEGER (E(IDENT_INT(1))), INTEGER (E(IDENT_INT(2)))) THEN COMMENT ("DON'T OPTIMIZE E"); END IF; E := (SDINT(IDENT_INT(1)),2,3,4,7); -- CONSTRAINT_ERROR BY AGGREGATE -- WITH DERIVED INTEGER COMPONENTS. FAILED ("CONSTRAINT_ERROR WAS NOT RAISED - 5"); IF NOT EQUAL (INTEGER (E(IDENT_INT(1))), INTEGER (E(IDENT_INT(1)))) THEN COMMENT ("DON'T OPTIMIZE E"); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => IF EQUAL (ARRAY_OBJ(IDENT_INT(1)), ARRAY_OBJ(IDENT_INT(2))) THEN COMMENT ("DON'T OPTIMIZE EXCEPTION HANDLER"); END IF; WHEN OTHERS => FAILED ("AN EXCEPTION OTHER THAN CONSTRAINT_ERROR " & "WAS RAISED - 5"); END; BEGIN F := (JOHN,TOM,PHIL,ROSA,JOHN); -- OK IF EQUAL (F.E1, F.E2) THEN COMMENT ("DON'T OPTIMIZE F"); END IF; F := (DENUM'VAL(IDENT_INT(DENUM'POS(VINCE))), TOM, PHIL, ROSA, JODIE); -- CONSTRAINT_ERROR BY AGGREGATE -- WITH COMPONENTS OF A DERIVED -- ENUMERATION TYPE. FAILED ("CONSTRAINT_ERROR WAS NOT RAISED - 6"); IF NOT EQUAL (F.E1, F.E1) THEN COMMENT ("DON'T OPTIMIZE F"); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => IF EQUAL (ARRAY_OBJ(IDENT_INT(1)), ARRAY_OBJ(IDENT_INT(2))) THEN COMMENT ("DON'T OPTIMIZE EXCEPTION HANDLER"); END IF; WHEN OTHERS => FAILED ("AN EXCEPTION OTHER THAN CONSTRAINT_ERROR " & "WAS RAISED - 6"); END; BEGIN G := (2.0,3.0,4.0,5.0,6.0); -- OK IF EQUAL (G(IDENT_INT(1)), G(IDENT_INT(2))) THEN COMMENT ("DON'T OPTIMIZE G"); END IF; G := (IDENT_DFL(1.0),2.0,3.0,4.0,IDENT_DFL(10.0)); -- CONSTRAINT_ERROR BY AGGREGATE -- WITH DERIVED FLOATING POINT -- COMPONENTS. FAILED ("CONSTRAINT_ERROR WAS NOT RAISED - 7"); IF NOT EQUAL (G(IDENT_INT(1)), G(IDENT_INT(1))) THEN COMMENT ("DON'T OPTIMIZE G"); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => IF EQUAL (ARRAY_OBJ(IDENT_INT(1)), ARRAY_OBJ(IDENT_INT(2))) THEN COMMENT ("DON'T OPTIMIZE EXCEPTION HANDLER"); END IF; WHEN OTHERS => FAILED ("AN EXCEPTION OTHER THAN CONSTRAINT_ERROR " & "WAS RAISED - 7"); END; BEGIN H := (2.2,3.3,4.4,5.5,6.6); -- OK IF EQUAL (H.E1, H.E2) THEN COMMENT ("DON'T OPTIMIZE H"); END IF; H := (IDENT_DFIX(2.0),2.5,3.5,4.3,IDENT_DFIX(7.4)); -- CONSTRAINT_ERROR BY AGGREGATE -- WITH DERIVED FIXED POINT -- COMPONENTS. FAILED ("CONSTRAINT_ERROR WAS NOT RAISED - 8"); IF EQUAL (H.E1, H.E5) THEN COMMENT ("DON'T OPTIMIZE H"); END IF; EXCEPTION WHEN CONSTRAINT_ERROR => IF EQUAL (ARRAY_OBJ(IDENT_INT(1)), ARRAY_OBJ(IDENT_INT(2))) THEN COMMENT ("DON'T OPTIMIZE EXCEPTION HANDLER"); END IF; WHEN OTHERS => FAILED ("AN EXCEPTION OTHER THAN CONSTRAINT_ERROR " & "WAS RAISED - 8"); END; RESULT; END C43004A;
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A 4 G . E X P R _ S E M -- -- -- -- B o d y -- -- -- -- Copyright (C) 1995-2012, Free Software Foundation, Inc. -- -- -- -- ASIS-for-GNAT is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2, or (at your option) any later -- -- version. ASIS-for-GNAT is distributed in the hope that it will be use- -- -- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- -- -- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General -- -- Public License for more details. You should have received a copy of the -- -- GNU General Public License distributed with ASIS-for-GNAT; see file -- -- COPYING. If not, write to the Free Software Foundation, 51 Franklin -- -- Street, Fifth Floor, Boston, MA 02110-1301, USA. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the -- -- Software Engineering Laboratory of the Swiss Federal Institute of -- -- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the -- -- Scientific Research Computer Center of Moscow State University (SRCC -- -- MSU), Russia, with funding partially provided by grants from the Swiss -- -- National Science Foundation and the Swiss Academy of Engineering -- -- Sciences. ASIS-for-GNAT is now maintained by AdaCore -- -- (http://www.adacore.com). -- -- -- ------------------------------------------------------------------------------ with Ada.Wide_Characters.Unicode; with Asis.Clauses; use Asis.Clauses; with Asis.Compilation_Units; use Asis.Compilation_Units; with Asis.Declarations; use Asis.Declarations; with Asis.Elements; use Asis.Elements; with Asis.Expressions; use Asis.Expressions; with Asis.Extensions; use Asis.Extensions; with Asis.Iterator; use Asis.Iterator; with Asis.Statements; use Asis.Statements; with Asis.Set_Get; use Asis.Set_Get; with A4G.A_Debug; use A4G.A_Debug; with A4G.A_Output; use A4G.A_Output; with A4G.A_Sem; use A4G.A_Sem; with A4G.A_Stand; use A4G.A_Stand; with A4G.A_Types; use A4G.A_Types; with A4G.Asis_Tables; use A4G.Asis_Tables; with A4G.Contt.UT; use A4G.Contt.UT; with A4G.Int_Knds; use A4G.Int_Knds; with A4G.Knd_Conv; use A4G.Knd_Conv; with A4G.Mapping; use A4G.Mapping; with Atree; use Atree; with Einfo; use Einfo; with Namet; use Namet; with Nlists; use Nlists; with Output; use Output; with Sem_Aux; use Sem_Aux; with Sinfo; use Sinfo; with Snames; use Snames; with Stand; use Stand; with Types; use Types; package body A4G.Expr_Sem is ----------------------- -- Local subprograms -- ----------------------- function Explicit_Type_Declaration (Entity_Node : Node_Id) return Node_Id; -- Taking the Entity node obtained as a result of some call to Etype -- function, this function yields the node for corresponding explicit -- type or subtype declaration. This means that this function traverses all -- the internal types generated by the compiler. -- -- In case of an anonymous access type, this function returns the entity -- node which is created by the compiler for this type (there is no tree -- type structure for the type declaration in this case), and a caller is -- responsible for further analysis -- -- SHOULD WE MOVE THIS FUNCTION IN THE SPEC??? function Explicit_Type_Declaration_Unwound (Entity_Node : Node_Id; Reference_Node : Node_Id := Empty) return Node_Id; -- Does the same as Explicit_Type_Declaration and unwinds all the -- subtypings (if any), resulting in a root type declaration. -- Reference_Node is a node representing a "place" from which this function -- is called. If the result type is private, but from the "place" of the -- call the full view is visible, the full view is returned. If -- Reference_Node is Empty, no private/full view check is made function Explicit_Type_Declaration_Unwound_Unaccess (Entity_Node : Node_Id; Reference_Node : Node_Id := Empty) return Node_Id; -- Does the same as Explicit_Type_Declaration_Unwound and in case of access -- types goes from the access to the designated type. --??? -- -- In case of an anonymous access type returns directly designated type. function Rewritten_Image (Selector_Name : Node_Id) return Node_Id; pragma Unreferenced (Rewritten_Image); -- this is an example of the tricky programming needed because of the -- tree rewriting. The problem is, that in the original tree structure -- for a record aggregate a N_Identifier node for a component selector -- name does not have an Entity field set. So we have to go to the -- corresponding (that is, to representing the same component selector -- name) node in the rewritten structure. -- -- It is an error to use this function for a node which is does not -- represent a component selector name in the original tree structure -- for a record aggregate -- -- This function is not used now, it is replaced by Search_Record_Comp function Search_Record_Comp (Selector_Name : Node_Id) return Entity_Id; -- This function looks for the entity node corresponding to a name from a -- choices list from a record or extension aggregate. The problem here is -- that an aggregate node is rewritten, and in the original tree structure -- the nodes corresponding to component names do not have the Entity -- field set. This function locates the corresponding entity node by -- detecting the aggregate type and searching the component defining -- identifier with the same name in the record definition. -- It might be the case (because of the absence of some semantic -- information in the tree or because of the ASIS bug) that Selector_Name -- actually does not represent a name from the aggregate choice list, in -- this case this function raises Assert_Failure or (if assertions are off) -- returns the Empty node. function Get_Statement_Identifier (Def_Id : Node_Id) return Node_Id; -- For Int_Node which should represent the defining identifier from an -- implicit declaration of a label (or a statement name?) (otherwise it -- is an error to use this function), this function returns the "defining" -- name representing the definition of this statement identifier in the -- ASIS sense. function GFP_Declaration (Par_Id : Node_Id) return Node_Id; -- this is (I hope, temporary) fix for the problem 14: the Entity -- field is not set for N_Identifier node representing the parameter -- name in a named generic association, so we need this function to -- compute the Entity for such an N_Identifier node. -- ??? what about formal parameters in associations like -- ??? "*" => Some_Function -- -- This function is supposed to be called for an actual representing -- the name of a generic formal parameter in a named formal parameter -- association (it's an error to call it for any other actual) function Is_Explicit_Type_Component (Comp_Def_Name : Node_Id; Type_Decl : Node_Id) return Boolean; -- Expects Comp_Def_Name to be a defining identifier of a record component -- and Type_Decl to be a type declaration. Checks if Comp_Def_Name denotes -- a component explicitly declared by this type declaration. (This function -- is useful for discriminants and components explicitly declared in -- derived type declarations. function Is_Type_Discriminant (Discr_Node : Node_Id; Type_Node : Node_Id) return Boolean; -- Assuming that Discr_Node is N_Defining_Identifier node and Type_Node -- represents a type declaration, this function checks if Discr_Node is -- a discriminant of this type (we cannot just use Parent to check this -- because of tree rewriting for discriminant types. function Full_View_Visible (Priv_Type : Node_Id; Ref : Node_Id) return Boolean; -- Assuming that Priv_Type is a node representing a private type -- declaration, checks, that in place of Ref the full view of the type is -- visible function Reset_To_Full_View (Full_View : Node_Id; Discr : Node_Id) return Node_Id; -- Assuming that Full_View is the full type declaration for some private -- type and Discr is a defining name of a discriminant of the type -- (probably, from its private view), this function returns the defining -- name of this discriminant in the full view function Is_Part_Of_Defining_Unit_Name (Name_Node : Node_Id) return Boolean; -- Assuming that Name_Node is of N_Identifier kind, this function checks, -- if it is a part of a defining program unit name function Reset_To_Spec (Name_Node : Node_Id) return Node_Id; -- Assuming that Name_Node is a part of a defining unit name which in turn -- is a part of a compilation unit body (for such nodes Entity field is not -- set), this function resets it to the node pointing to the same part of -- the defining unit name, but in the spec of the corresponding library -- unit function Reference_Kind (Name : Asis.Element) return Internal_Element_Kinds; -- If Name is of A_Defining_Name kind then this function returns the kind -- of An_Expression elements which may be simple-name-form references to -- the given name (that is, A_Defining_Identifier -> An_Identifier, -- A_Defining_And_Operator -> An_And_Operator), otherwise returns -- Not_An_Element. Note, that the result can never be -- A_Selected_Component, because only references which are simple names -- are considered. function Get_Specificed_Component (Comp : Node_Id; Rec_Type : Entity_Id) return Entity_Id; -- Provided that Comp is the reference to a record component from the -- component clause being a component of a record representation clause -- for the record type Rec_Type, this function computes the corresponding -- component entity function Get_Entity_From_Long_Name (N : Node_Id) return Entity_Id; -- Supposing that N denotes some component of a long expanded name -- and for N and for its prefix the Entity fields are not set, this -- function computes the corresponding entity node by traversing -- the "chain" of definitions corresponding to this expanded name function Get_Rewritten_Discr_Ref (N : Node_Id) return Node_Id; pragma Unreferenced (Get_Rewritten_Discr_Ref); -- This function is supposed to be called for a discriminant reference -- from the discriminant constraint from derived type, in case if the -- parent type is a task or protected type. In this case -- N_Subtype_Indication node from the derived type definition is rewritten -- in a subtype mark pointing to the internal subtype. The original -- structure is not decorated, so we have to go to the corresponding -- node in the definition of this internal subtype to get the semantic -- information. See F407-011 -- Do we need this after fixing the regression caused by K120-031 function Get_Discriminant_From_Type (N : Node_Id) return Entity_Id; -- Starting from the reference to discriminant in a discriminant -- constraint, tries to compute the corresponding discriminant entity by -- getting to the declaration of the corresponding type and traversing -- its discriminant part. function Is_Limited_Withed (E : Entity_Id; Reference : Asis.Element) return Boolean; -- Assuming that Reference is an_Identifier Element and E is the entity -- node for the entity denoted by Reference, checks if this entity is -- defined in a compilation unit that is limited withed by the unit -- containing Reference function To_Upper_Case (S : Wide_String) return Wide_String; -- Folds the argument to upper case, may be used for string normalization -- before comparing strings if the casing is not important for comparing -- (Copied from ASIS_UL.Misc to avoid dependencies on ASIS UL in "pure" -- ASIS. --------------------------------------- -- Character_Literal_Name_Definition -- --------------------------------------- function Character_Literal_Name_Definition (Reference_Ch : Element) return Asis.Defining_Name is -- for now, the code is very similar to the code -- for Identifier_Name_Definition. Any aggregation has been -- put off till everything will work Arg_Node : Node_Id; Special_Case : Special_Cases := Not_A_Special_Case; Result_Element : Asis.Defining_Name := Nil_Element; Is_Inherited : Boolean := False; Association_Type : Node_Id := Empty; Set_Char_Code : Boolean := False; Result_Node : Node_Id; Result_Unit : Compilation_Unit; Result_Kind : constant Internal_Element_Kinds := A_Defining_Character_Literal; begin -- We have to distinguish and to treat separately four (???) -- different situations: -- -- 1. a literal from user-defined character type (fully implemented -- for now); -- -- 2. a literal from a type derived from some user-defined character -- type (not implemented for now as related to Implicit Elements); -- -- 3. a literal from a character type defined in Standard (not -- implemented for now); -- -- 4. a literal from a type derived a character type defined in -- Standard (not implemented for now as related to Implicit -- Elements); Arg_Node := Node (Reference_Ch); -- if Reference_Ch is a Selector_Name in some N_Expanded_Name, -- the corresponding Entity field is set not for the Node on which -- this Reference_En is based, but for the whole expanded name. -- (The same for Etype) So: if Nkind (Parent (Arg_Node)) = N_Expanded_Name or else Nkind (Parent (Arg_Node)) = N_Character_Literal then -- the last alternative of the condition corresponds to an expanded -- name of a predefined character literal or to an expanded name -- of a literal of a type derived from a predefined character type - -- such an expanded name is rewritten into (another) "instance" -- of the same literal Arg_Node := Parent (Arg_Node); end if; Result_Node := Entity (Arg_Node); -- will be Empty for any character literal belonging to -- Standard.Character, Standard.Whide_Character or any type -- derived (directly or indirectly) from any of these types Association_Type := Etype (Arg_Node); if No (Result_Node) and then No (Association_Type) and then Is_From_Unknown_Pragma (R_Node (Reference_Ch)) then return Nil_Element; end if; if No (Association_Type) then -- this may be the case if some character literals are -- rewritten into a string constant Association_Type := Arg_Node; while Present (Association_Type) loop exit when Nkind (Association_Type) = N_String_Literal; Association_Type := Parent (Association_Type); end loop; pragma Assert (Present (Association_Type)); Association_Type := Etype (Association_Type); Association_Type := Component_Type (Association_Type); end if; Association_Type := Explicit_Type_Declaration_Unwound (Association_Type); if No (Result_Node) then Set_Char_Code := True; Result_Node := Association_Type; Result_Node := Sinfo.Type_Definition (Result_Node); if Char_Defined_In_Standard (Arg_Node) then Special_Case := Stand_Char_Literal; else Is_Inherited := True; end if; elsif not Comes_From_Source (Result_Node) then Is_Inherited := True; end if; if Char_Defined_In_Standard (Arg_Node) then Result_Unit := Get_Comp_Unit (Standard_Id, Encl_Cont_Id (Reference_Ch)); else Result_Unit := Enclosing_Unit (Encl_Cont_Id (Reference_Ch), Result_Node); end if; Result_Element := Node_To_Element_New (Node => Result_Node, Node_Field_1 => Association_Type, Internal_Kind => Result_Kind, Spec_Case => Special_Case, Inherited => Is_Inherited, In_Unit => Result_Unit); if Set_Char_Code then Set_Character_Code (Result_Element, Character_Code (Reference_Ch)); end if; return Result_Element; end Character_Literal_Name_Definition; --------------------------------- -- Collect_Overloaded_Entities -- --------------------------------- procedure Collect_Overloaded_Entities (Reference : Asis.Element) is Arg_Node : Node_Id; Arg_Pragma_Chars : Name_Id; Next_Entity : Entity_Id; Result_Unit : Asis.Compilation_Unit; Result_Context : constant Context_Id := Encl_Cont_Id (Reference); Res_Node : Node_Id; Res_NF_1 : Node_Id; Res_Ekind : Entity_Kind; Res_Inherited : Boolean; Is_Program_Unit_Pragma : Boolean := False; Enclosing_Scope_Entity : Entity_Id; Enclosing_List : List_Id; function Should_Be_Collected (Ent : Entity_Id) return Boolean; -- When traversing the chain of homonyms potentially referred by -- Reference, it checks if Ent should be used to create the next -- Element in the Result list function Should_Be_Collected (Ent : Entity_Id) return Boolean is Result : Boolean := False; N : Node_Id; begin if not (Ekind (Ent) = E_Operator and then Is_Predefined (Ent)) then if Is_Program_Unit_Pragma then Result := Scope (Ent) = Enclosing_Scope_Entity; else N := Parent (Ent); while Present (N) and then not (Is_List_Member (N)) loop N := Parent (N); end loop; if Present (N) and then Is_List_Member (N) then Result := List_Containing (N) = Enclosing_List; end if; end if; end if; return Result; end Should_Be_Collected; begin -- First, we decide what kind of pragma we have, because the search -- depends on this: Arg_Node := Node (Reference); Arg_Pragma_Chars := Pragma_Name (Parent (Parent (Arg_Node))); if Arg_Pragma_Chars = Name_Inline then Is_Program_Unit_Pragma := True; -- ??? is it enough? what about GNAT-specific pragmas? -- In this case we have to search in the same declarative region -- (in the same scope): Enclosing_Scope_Entity := Scope (Entity (Arg_Node)); -- This is no more than a trick: actually, we have to compute -- the scope node for the declarative region which encloses -- Arg_Node, but entry bodies makes a serious problem (at the -- moment of writing this code there is no semantic links between -- protected entry declarations and bodies). So we just assume -- that Arg_Node has the Entity field set, and this field -- points to some correct (from the point of view of -- Corresponding_Name_Definition_List query) entity, so we -- just take the Scope of this entity... else Enclosing_List := List_Containing (Parent (Parent (Arg_Node))); end if; Next_Entity := Entity (Arg_Node); while Present (Next_Entity) and then Should_Be_Collected (Next_Entity) loop Result_Unit := Enclosing_Unit (Result_Context, Next_Entity); Res_Ekind := Ekind (Next_Entity); if Res_Ekind in Subprogram_Kind then if Comes_From_Source (Next_Entity) then Res_Node := Next_Entity; Res_NF_1 := Empty; Res_Inherited := False; else Res_Node := Alias (Next_Entity); while Present (Alias (Res_Node)) loop Res_Node := Alias (Res_Node); end loop; Res_NF_1 := Next_Entity; Res_Inherited := True; end if; Asis_Element_Table.Append (Node_To_Element_New (Node => Res_Node, Node_Field_1 => Res_NF_1, Inherited => Res_Inherited, In_Unit => Result_Unit)); end if; Next_Entity := Homonym (Next_Entity); end loop; end Collect_Overloaded_Entities; --------------------------- -- Correct_Impl_Form_Par -- --------------------------- procedure Correct_Impl_Form_Par (Result : in out Element; Reference : Element) is Res_Node : Node_Id := Node (Result); Subprogram_Name : Element; Subprogram_Node : Node_Id := Node (Result); Res_Sloc : Source_Ptr; Top_Node : Node_Id; Result_Unit : Compilation_Unit; begin Res_Node := Defining_Identifier (Parent (Res_Node)); Subprogram_Name := Enclosing_Element (Enclosing_Element (Reference)); case Int_Kind (Subprogram_Name) is when A_Function_Call => Subprogram_Name := Prefix (Subprogram_Name); when A_Procedure_Call_Statement | An_Entry_Call_Statement => Subprogram_Name := Called_Name (Subprogram_Name); when others => null; pragma Assert (False); end case; Subprogram_Node := Node (Subprogram_Name); Subprogram_Node := Associated_Node (Subprogram_Node); Top_Node := Parent (Subprogram_Node); while Nkind (Top_Node) /= N_Compilation_Unit loop Top_Node := Parent (Top_Node); end loop; Res_Sloc := Sloc (Res_Node) - Sloc (Top_Node); Result_Unit := Enclosing_Unit (Encl_Cont_Id (Reference), Subprogram_Node); Set_Node (Result, Res_Node); Set_R_Node (Result, Res_Node); Set_From_Implicit (Result, True); Set_From_Inherited (Result, True); Set_From_Instance (Result, Is_From_Instance (Subprogram_Node)); Set_Node_Field_1 (Result, Subprogram_Node); Set_Rel_Sloc (Result, Res_Sloc); Set_Encl_Unit_Id (Result, Get_Unit_Id (Result_Unit)); end Correct_Impl_Form_Par; -------------------- -- Correct_Result -- -------------------- procedure Correct_Result (Result : in out Element; Reference : Element) is Enclosing_Generic : Element := Nil_Element; Tmp : Element; Tmp_Generic : Element; Is_From_Body : Boolean := False; Instance : Element := Nil_Element; procedure Check_Number_Name (Element : Asis.Element; Control : in out Traverse_Control; State : in out No_State); -- Check if the argument is the defining name of the named number -- defining the same named number as Result, but in the template. -- As soon as the check is successful, replace Result with this -- defining name and terminates the traversal Control : Traverse_Control := Continue; State : No_State := Not_Used; procedure Traverse_Instance is new Traverse_Element (State_Information => No_State, Pre_Operation => Check_Number_Name, Post_Operation => No_Op); procedure Check_Number_Name (Element : Asis.Element; Control : in out Traverse_Control; State : in out No_State) is pragma Unreferenced (State); El_Kind : constant Internal_Element_Kinds := Int_Kind (Element); begin case El_Kind is when A_Defining_Identifier => if Int_Kind (Enclosing_Element (Element)) in An_Integer_Number_Declaration .. A_Real_Number_Declaration and then Chars (Node (Result)) = Chars (Node (Element)) then Result := Element; Control := Terminate_Immediately; end if; when An_Integer_Number_Declaration | A_Real_Number_Declaration | A_Procedure_Body_Declaration | A_Function_Body_Declaration | A_Package_Declaration | A_Package_Body_Declaration | A_Task_Body_Declaration | A_Protected_Body_Declaration | An_Entry_Body_Declaration | A_Generic_Package_Declaration | A_Block_Statement => null; when others => Control := Abandon_Children; end case; end Check_Number_Name; begin -- First, check if Result is declared in a template Tmp := Enclosing_Element (Result); while not Is_Nil (Tmp) loop if Int_Kind (Tmp) in An_Internal_Generic_Declaration or else (Int_Kind (Tmp) in A_Procedure_Body_Declaration .. A_Package_Body_Declaration and then Int_Kind (Corresponding_Declaration (Tmp)) in An_Internal_Generic_Declaration) then if Int_Kind (Tmp) in A_Procedure_Body_Declaration .. A_Package_Body_Declaration then Enclosing_Generic := Corresponding_Declaration (Tmp); Is_From_Body := True; else Enclosing_Generic := Tmp; end if; exit; end if; Tmp := Enclosing_Element (Tmp); end loop; if Is_Nil (Enclosing_Generic) then -- No need to correct anything! return; end if; -- Now, traversing the instantiation chain from the Reference, looking -- for the instantiation of Enlosing_Generic: Tmp := Enclosing_Element (Reference); while not Is_Nil (Tmp) loop if Int_Kind (Tmp) in An_Internal_Generic_Instantiation then Tmp_Generic := Generic_Unit_Name (Tmp); if Int_Kind (Tmp_Generic) = A_Selected_Component then Tmp_Generic := Selector (Tmp_Generic); end if; Tmp_Generic := Corresponding_Name_Declaration (Tmp_Generic); if Is_Equal (Enclosing_Generic, Tmp_Generic) then Instance := Tmp; exit; end if; end if; Tmp := Enclosing_Element (Tmp); end loop; if Is_Nil (Instance) then -- No need to correct anything - we do not have a nested generics! return; end if; -- And now we have to find the "image' of Result in expanded Instance if Is_From_Body then Instance := Corresponding_Body (Instance); else Instance := Corresponding_Declaration (Instance); end if; Traverse_Instance (Instance, Control, State); end Correct_Result; ------------------------------- -- Explicit_Type_Declaration -- ------------------------------- function Explicit_Type_Declaration (Entity_Node : Node_Id) return Node_Id is Next_Node : Node_Id; Result_Node : Node_Id; Res_Ekind : Entity_Kind; function Is_Explicit_Type_Declaration (Type_Entity_Node : Node_Id) return Boolean; -- checks if Type_Entity_Node corresponds to the explicit type -- declaration which is looked for (that is, the needed type declaration -- node is Parent (Type_Entity_Node) ) function Is_Explicit_Type_Declaration (Type_Entity_Node : Node_Id) return Boolean is Type_Decl_Node : constant Node_Id := Parent (Type_Entity_Node); Type_Decl_Nkind : Node_Kind; Is_Full_Type_Decl : Boolean := False; Is_Derived_Type_Decl : Boolean := False; Is_Formal_Type_Decl : Boolean := False; begin if not Is_Itype (Entity_Node) and then Present (Type_Decl_Node) then Is_Full_Type_Decl := Comes_From_Source (Type_Decl_Node) and then (not Is_Rewrite_Substitution (Type_Decl_Node)); if not Is_Full_Type_Decl and then Is_Rewrite_Substitution (Type_Decl_Node) then -- The second part of the condition is common for all the cases -- which require special analysis Type_Decl_Nkind := Nkind (Type_Decl_Node); Is_Derived_Type_Decl := (Type_Decl_Nkind = N_Subtype_Declaration or else Type_Decl_Nkind = N_Full_Type_Declaration or else Type_Decl_Nkind = N_Formal_Type_Declaration) and then (Nkind (Original_Node (Type_Decl_Node)) = N_Full_Type_Declaration and then Nkind (Sinfo.Type_Definition (Original_Node (Type_Decl_Node))) = N_Derived_Type_Definition); if not Is_Derived_Type_Decl then Is_Formal_Type_Decl := (Type_Decl_Nkind = N_Private_Extension_Declaration or else Type_Decl_Nkind = N_Full_Type_Declaration) and then Nkind (Original_Node (Type_Decl_Node)) = N_Formal_Type_Declaration; end if; end if; end if; return Is_Full_Type_Decl or else Is_Derived_Type_Decl or else Is_Formal_Type_Decl; end Is_Explicit_Type_Declaration; begin -- well, here we have a (sub)type entity node passed as an actual... -- the aim is to return the _explicit_ type declaration corresponding -- to this (sub)type entity. It should be such a declaration, if this -- function is called... -- -- We try to organize the processing in a recursive way - may be, -- not the most effective one, but easy-to maintain if Is_Explicit_Type_Declaration (Entity_Node) then -- the first part of the condition is the protection from -- non-accurate settings of Comes_From_Source flag :(( Result_Node := Parent (Entity_Node); elsif Sloc (Entity_Node) <= Standard_Location then -- here we have a predefined type declared in Standard. -- it may be the type entity or the entity for its 'Base -- type. In the latter case we have to go to the type -- entity if Present (Parent (Entity_Node)) then -- type entity, therefore simply Result_Node := Parent (Entity_Node); else -- 'Base type, so we have to compute the first named -- type. The code which does it looks tricky, but for now we -- do not know any better solution: Result_Node := Parent (Parent (Scalar_Range (Entity_Node))); end if; elsif Etype (Entity_Node) = Entity_Node and then Present (Associated_Node_For_Itype (Entity_Node)) and then Nkind (Associated_Node_For_Itype (Entity_Node)) = N_Object_Declaration then -- this corresponds to an anonymous array subtype created by an -- object declaration with array_type_definition Result_Node := Empty; else -- Entity_Node corresponds to some internal or implicit type created -- by the compiler. Here we have to traverse the tree till the -- explicit type declaration being the cause for generating this -- implicit type will be found Res_Ekind := Ekind (Entity_Node); if Res_Ekind = E_Anonymous_Access_Type then -- There is no type declaration node in this case at all, -- so we just return this N_Defining_Identifier node for -- further analysis in the calling context: return Entity_Node; -- ??? Why do not we return Empty in this case??? elsif Res_Ekind = E_Anonymous_Access_Subprogram_Type then -- No explicit type declaration, so return Empty; elsif Res_Ekind = E_String_Literal_Subtype or else (Res_Ekind = E_Array_Subtype and then Present (Parent (Entity_Node))) then -- The first part of the condition corresponds to a special case -- E_String_Literal_Subtype is created for, see Einfo (spec) for -- the details. The second part corresponds to the access to -- string type, see E626-002 Result_Node := Parent (Etype (Entity_Node)); if No (Result_Node) then Result_Node := Associated_Node_For_Itype (Etype (Entity_Node)); end if; elsif Ekind (Entity_Node) = E_Enumeration_Type then if Present (Associated_Node_For_Itype (Entity_Node)) then Result_Node := Associated_Node_For_Itype (Entity_Node); else -- Entity_Node represents an implicit type created for -- a derived enumeration type. we have to go down to this -- derived type Result_Node := Parent (Entity_Node); while Present (Result_Node) loop Result_Node := Next (Result_Node); exit when Nkind (Result_Node) = N_Subtype_Declaration and then Is_Rewrite_Substitution (Result_Node); end loop; end if; pragma Assert (Present (Result_Node)); elsif (No (Parent (Entity_Node)) or else not Comes_From_Source (Parent (Entity_Node))) and then Etype (Entity_Node) /= Entity_Node and then not (Ekind (Entity_Node) = E_Floating_Point_Type or else Ekind (Entity_Node) = E_Signed_Integer_Type or else Ekind (Entity_Node) = E_Array_Type or else Ekind (Entity_Node) = E_Private_Type or else Ekind (Entity_Node) = E_Limited_Private_Type) then if Is_Itype (Entity_Node) and then Nkind (Associated_Node_For_Itype (Entity_Node)) = N_Subtype_Declaration then Next_Node := Defining_Identifier (Associated_Node_For_Itype (Entity_Node)); if Next_Node = Entity_Node then Next_Node := Etype (Entity_Node); end if; else -- subtypes created for objects when an explicit constraint -- presents in the object declaration ??? Next_Node := Etype (Entity_Node); end if; Result_Node := Explicit_Type_Declaration (Next_Node); else Next_Node := Associated_Node_For_Itype (Entity_Node); pragma Assert (Present (Next_Node)); if Nkind (Original_Node (Next_Node)) = N_Full_Type_Declaration or else Nkind (Original_Node (Next_Node)) = N_Formal_Type_Declaration then Result_Node := Next_Node; elsif Nkind (Next_Node) = N_Loop_Parameter_Specification then -- here we have to traverse the loop parameter specification, -- because otherwise we may get the base type instead of -- the actually needed named subtype. Result_Node := Next_Node; Result_Node := Sinfo.Discrete_Subtype_Definition (Result_Node); case Nkind (Result_Node) is when N_Subtype_Indication => Result_Node := Sinfo.Subtype_Mark (Result_Node); Result_Node := Parent (Entity (Result_Node)); when N_Identifier | N_Expanded_Name => Result_Node := Parent (Entity (Result_Node)); when N_Range => -- and here we have to use the Etype field of -- the implicit type itself, because we do not have -- any type mark to start from in the loop parameter -- specification: Result_Node := Explicit_Type_Declaration (Etype (Entity_Node)); when others => null; pragma Assert (False); -- this is definitely wrong! Should be corrected -- during debugging!!! end case; else if Etype (Entity_Node) /= Entity_Node then -- otherwise we will be in dead circle Result_Node := Etype (Entity_Node); Result_Node := Explicit_Type_Declaration (Result_Node); else -- for now, the only guess is that we have an object -- defined by an object declaration with constrained -- array definition, or an initialization expression -- from such a declaration pragma Assert ( Nkind (Next_Node) = N_Object_Declaration and then Nkind (Object_Definition (Next_Node)) = N_Constrained_Array_Definition); return Empty; -- what else could we return here? end if; end if; end if; end if; return Result_Node; end Explicit_Type_Declaration; --------------------------------------- -- Explicit_Type_Declaration_Unwound -- --------------------------------------- function Explicit_Type_Declaration_Unwound (Entity_Node : Node_Id; Reference_Node : Node_Id := Empty) return Node_Id is Result_Node : Node_Id; Subtype_Mark_Node : Node_Id; begin Result_Node := Explicit_Type_Declaration (Entity_Node); while Nkind (Original_Node (Result_Node)) = N_Subtype_Declaration loop Subtype_Mark_Node := Sinfo.Subtype_Indication (Original_Node (Result_Node)); if Nkind (Subtype_Mark_Node) = N_Subtype_Indication then Subtype_Mark_Node := Sinfo.Subtype_Mark (Subtype_Mark_Node); end if; Result_Node := Explicit_Type_Declaration (Entity (Subtype_Mark_Node)); end loop; if Present (Reference_Node) and then (Nkind (Original_Node (Result_Node)) = N_Private_Type_Declaration or else Nkind (Original_Node (Result_Node)) = N_Private_Extension_Declaration) and then Full_View_Visible (Result_Node, Reference_Node) then Result_Node := Parent (Full_View (Defining_Identifier (Result_Node))); end if; return Result_Node; end Explicit_Type_Declaration_Unwound; ------------------------------------------------ -- Explicit_Type_Declaration_Unwound_Unaccess -- ------------------------------------------------ function Explicit_Type_Declaration_Unwound_Unaccess (Entity_Node : Node_Id; Reference_Node : Node_Id := Empty) return Node_Id is Result_Node : Node_Id; Subtype_Mark_Node : Node_Id; Tmp : Node_Id; begin Result_Node := Explicit_Type_Declaration_Unwound ( Entity_Node, Reference_Node); if Nkind (Result_Node) = N_Defining_Identifier and then Ekind (Result_Node) = E_Anonymous_Access_Type then Result_Node := Explicit_Type_Declaration_Unwound ( Directly_Designated_Type (Result_Node), Reference_Node); end if; -- This loop unwinds accessing^ while (Nkind (Original_Node (Result_Node)) = N_Full_Type_Declaration and then Nkind (Sinfo.Type_Definition (Original_Node (Result_Node))) = N_Access_To_Object_Definition) or else (Nkind (Original_Node (Result_Node)) = N_Formal_Type_Declaration and then Nkind (Sinfo.Formal_Type_Definition (Original_Node ( Result_Node))) = N_Access_To_Object_Definition) loop Subtype_Mark_Node := Original_Node (Result_Node); if Nkind (Subtype_Mark_Node) = N_Full_Type_Declaration then Subtype_Mark_Node := Sinfo.Subtype_Indication ( Sinfo.Type_Definition (Subtype_Mark_Node)); else Subtype_Mark_Node := Sinfo.Subtype_Indication ( Sinfo.Formal_Type_Definition (Subtype_Mark_Node)); end if; if Nkind (Subtype_Mark_Node) = N_Subtype_Indication then Subtype_Mark_Node := Sinfo.Subtype_Mark (Subtype_Mark_Node); end if; Result_Node := Explicit_Type_Declaration_Unwound ( Entity (Subtype_Mark_Node), Reference_Node); if Nkind (Result_Node) = N_Incomplete_Type_Declaration then -- To be 100% honest, we have to check that at place of -- Reference_Node the full view is visible. But we could hardly -- call this routine (for a legal code) if we do not see the full -- view from Reference_Node. Tmp := Full_View (Defining_Identifier (Result_Node)); if Present (Tmp) then Result_Node := Parent (Tmp); end if; end if; end loop; -- If we have a type derived from an access type, we have to go through -- this derivation and unwind accessing if Nkind (Result_Node) = N_Full_Type_Declaration and then Nkind (Sinfo.Type_Definition (Result_Node)) = N_Derived_Type_Definition then Tmp := Defining_Identifier (Result_Node); if Ekind (Tmp) in Access_Kind then Result_Node := Explicit_Type_Declaration_Unwound_Unaccess (Directly_Designated_Type (Tmp), Reference_Node); end if; end if; return Result_Node; end Explicit_Type_Declaration_Unwound_Unaccess; --------------- -- Expr_Type -- --------------- function Expr_Type (Expression : Asis.Expression) return Asis.Declaration is Arg_Node : Node_Id; Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Expression); Result_Entity : Node_Id; Result_Node : Node_Id; Result_Unit : Compilation_Unit; Res_Spec_Case : Special_Cases := Not_A_Special_Case; Encl_Cont : constant Context_Id := Encl_Cont_Id (Expression); begin -- first, we should check whether Expression has a universal -- numeric type and return the corresponding ASIS universal type. -- For now, this check includes numeric literals and some of the -- attribute references is: if Arg_Kind = An_Integer_Literal or else Arg_Kind = An_Alignment_Attribute or else Arg_Kind = A_Component_Size_Attribute or else Arg_Kind = A_Digits_Attribute or else Arg_Kind = A_Count_Attribute or else Arg_Kind = An_Exponent_Attribute or else Arg_Kind = A_First_Bit_Attribute or else Arg_Kind = A_Fore_Attribute or else Arg_Kind = A_Last_Bit_Attribute or else Arg_Kind = A_Length_Attribute or else Arg_Kind = A_Machine_Emax_Attribute or else Arg_Kind = A_Machine_Emin_Attribute or else Arg_Kind = A_Machine_Mantissa_Attribute or else Arg_Kind = A_Machine_Radix_Attribute or else Arg_Kind = A_Max_Size_In_Storage_Elements_Attribute or else Arg_Kind = A_Model_Emin_Attribute or else Arg_Kind = A_Model_Mantissa_Attribute or else Arg_Kind = A_Modulus_Attribute or else Arg_Kind = A_Partition_ID_Attribute or else Arg_Kind = A_Pos_Attribute or else Arg_Kind = A_Position_Attribute or else Arg_Kind = A_Scale_Attribute or else Arg_Kind = A_Size_Attribute or else Arg_Kind = A_Storage_Size_Attribute or else Arg_Kind = A_Wide_Width_Attribute or else Arg_Kind = A_Width_Attribute or else (Special_Case (Expression) = Rewritten_Named_Number and then Nkind (R_Node (Expression)) = N_Integer_Literal) then return Set_Root_Type_Declaration (A_Universal_Integer_Definition, Encl_Cont); elsif Arg_Kind = A_Real_Literal or else Arg_Kind = A_Delta_Attribute or else Arg_Kind = A_Model_Epsilon_Attribute or else Arg_Kind = A_Model_Small_Attribute or else Arg_Kind = A_Safe_First_Attribute or else Arg_Kind = A_Safe_Last_Attribute or else Arg_Kind = A_Small_Attribute or else (Special_Case (Expression) = Rewritten_Named_Number and then Nkind (R_Node (Expression)) = N_Real_Literal) then return Set_Root_Type_Declaration (A_Universal_Real_Definition, Encl_Cont); end if; Arg_Node := Node (Expression); -- In some cases we have to use the rewritten node if Is_Rewrite_Substitution (R_Node (Expression)) and then (Nkind (Arg_Node) = N_Aggregate and then Nkind (R_Node (Expression)) = N_String_Literal) then Arg_Node := R_Node (Expression); end if; while Nkind (Arg_Node) = N_String_Literal and then Nkind (Parent (Arg_Node)) = N_String_Literal loop -- Trick for F109-A24: for string literals in a static expression, -- Etype points to some dummy subtype node (the tree structure is -- rewritten for the whole expression, and the original subtree is -- not fully decorated), so we take the type information from the -- rewritten result of the expression Arg_Node := Parent (Arg_Node); end loop; -- if the expression node is rewritten, all the semantic -- information can be found only through the rewritten node if Nkind (Parent (Arg_Node)) = N_Expanded_Name and then Arg_Node = Selector_Name (Parent (Arg_Node)) then -- selector in an expanded name - all the semantic fields -- are set for the whole name, but not for this selector. -- So: Arg_Node := Parent (Arg_Node); end if; -- ??? <tree problem 1> -- this fragment should be revised when the problem is fixed (as it should) if Nkind (Arg_Node) = N_Selected_Component then if Etype (Arg_Node) = Any_Type then -- for now (GNAT 3.05) this means, that Expression is an expanded -- name of the character literal of ether a predefined character -- type or of the type derived from a predefined character type Arg_Node := R_Node (Expression); -- resetting Arg_Node pointing to the rewritten node for the -- expanded name -- -- ??? -- This looks strange... Should be revised else Arg_Node := Selector_Name (Arg_Node); -- here the actual type is! end if; elsif Nkind (Arg_Node) = N_Character_Literal and then No (Etype (Arg_Node)) -- for now (GNAT 3.05) this means, that Expression is the -- selector in an expanded name of the character literal of -- ether a predefined character type or of the type derived -- from a predefined character type then Arg_Node := Parent (Arg_Node); -- resetting Arg_Node pointing to the rewritten node for the whole -- expanded name end if; -- ??? <tree problem 1> - end -- now the idea is to take the Etype attribute of the expression -- and to go to the corresponding type declaration. But -- special processing for computing the right Etype is -- required for some cases if Nkind (Parent (Arg_Node)) = N_Qualified_Expression and then Arg_Node = Sinfo.Expression (Parent (Arg_Node)) then Result_Entity := Etype (Sinfo.Subtype_Mark (Parent (Arg_Node))); -- we'll keep the commented code below for a while... -- elsif (Arg_Kind = A_First_Attribute or else -- Arg_Kind = A_Last_Attribute) -- and then not Comes_From_Source (Etype (Arg_Node)) -- and then Sloc (Etype (Arg_Node)) > Standard_Location -- and then Etype (Etype (Arg_Node)) = Etype (Arg_Node) -- then -- -- this tricky condition corresponds to the situation, when -- -- 'First or 'Last attribute is applied to a formal discrete -- -- type @:-( -- -- In this case we simply use the attribute prefix to define -- -- the result type -- Result_Entity := Etype (Prefix (Arg_Node)); else -- how nice it would be if *everything* would be so simple Result_Entity := Etype (Arg_Node); end if; if Result_Entity = Any_Composite then -- Here we have an aggregate in some original tree structure that has -- not been properly decorated. All the semantic decorations are in -- the corresponding rewritten structure, so we have to find the -- corresponding node there. declare Tmp : Node_Id; New_Arg_Node : Node_Id := Empty; Arg_Kind : constant Node_Kind := Nkind (Arg_Node); Arg_Sloc : constant Source_Ptr := Sloc (Arg_Node); function Find (Node : Node_Id) return Traverse_Result; -- Check if its argument represents the same construct as -- Arg_Node, and if it does, stores Node in New_Arg_Node and -- returns Abandon, otherwise returns OK. procedure Find_Rewr_Aggr is new Traverse_Proc (Find); function Find (Node : Node_Id) return Traverse_Result is begin if Nkind (Node) = Arg_Kind and then Sloc (Node) = Arg_Sloc then New_Arg_Node := Node; return Abandon; else return OK; end if; end Find; begin Tmp := Parent (Arg_Node); while not Is_Rewrite_Substitution (Tmp) loop Tmp := Parent (Tmp); end loop; Find_Rewr_Aggr (Tmp); pragma Assert (Present (New_Arg_Node)); Result_Entity := Etype (New_Arg_Node); end; end if; Result_Node := Explicit_Type_Declaration (Result_Entity); if No (Result_Node) then return Nil_Element; -- we cannot represent the type declaration in ASIS; -- for example, an object defined by an object declaration -- with constrained array definition end if; if Sloc (Result_Entity) <= Standard_Location then Result_Unit := Get_Comp_Unit (Standard_Id, Encl_Cont_Id (Expression)); Res_Spec_Case := Explicit_From_Standard; else Result_Unit := Enclosing_Unit (Encl_Cont_Id (Expression), Result_Node); end if; return Node_To_Element_New (Node => Result_Node, Spec_Case => Res_Spec_Case, In_Unit => Result_Unit); end Expr_Type; ----------------------- -- Full_View_Visible -- ----------------------- function Full_View_Visible (Priv_Type : Node_Id; Ref : Node_Id) return Boolean is Type_Scope : constant Node_Id := Scope (Defining_Identifier (Priv_Type)); Type_Scope_Body : Node_Id; Type_Full_View : Node_Id; Scope_Node : Node_Id := Empty; Next_Node : Node_Id := Parent (Ref); Next_Node_Inner : Node_Id := Ref; Result : Boolean := False; begin Type_Scope_Body := Parent (Type_Scope); if Nkind (Type_Scope_Body) = N_Defining_Program_Unit_Name then Type_Scope_Body := Parent (Type_Scope_Body); end if; Type_Scope_Body := Corresponding_Body (Parent (Type_Scope_Body)); if Nkind (Parent (Type_Scope_Body)) = N_Defining_Program_Unit_Name then Type_Scope_Body := Parent (Type_Scope_Body); end if; while Present (Next_Node) loop if (Nkind (Next_Node) = N_Package_Specification and then Defining_Unit_Name (Next_Node) = Type_Scope) or else (Nkind (Next_Node) = N_Package_Body and then Defining_Unit_Name (Next_Node) = Type_Scope_Body) then Scope_Node := Next_Node; exit; end if; Next_Node_Inner := Next_Node; Next_Node := Parent (Next_Node); end loop; if Present (Scope_Node) then if Nkind (Scope_Node) = N_Package_Body then Result := True; elsif List_Containing (Next_Node_Inner) = Private_Declarations (Scope_Node) then -- That is, Ref is in the private part of the package where -- Priv_Type is declared, and we have to check what goes first: -- Ref (or a construct it is enclosed into - it is pointed by -- Next_Node_Inner) or the full view of the private type: Type_Full_View := Parent (Full_View (Defining_Identifier (Priv_Type))); Next_Node := First_Non_Pragma (Private_Declarations (Scope_Node)); while Present (Next_Node) loop if Next_Node = Type_Full_View then Result := True; exit; elsif Next_Node = Next_Node_Inner then exit; else Next_Node := Next_Non_Pragma (Next_Node); end if; end loop; end if; end if; return Result; end Full_View_Visible; -------------------------------- -- Get_Discriminant_From_Type -- -------------------------------- function Get_Discriminant_From_Type (N : Node_Id) return Entity_Id is Type_Entity : Entity_Id := Parent (N); Res_Chars : constant Name_Id := Chars (N); Result : Entity_Id; begin while not (Nkind (Type_Entity) = N_Subtype_Declaration or else Nkind (Type_Entity) = N_Subtype_Indication) loop Type_Entity := Parent (Type_Entity); if Nkind (Type_Entity) = N_Allocator then Type_Entity := Etype (Type_Entity); while Ekind (Type_Entity) in Access_Kind loop Type_Entity := Directly_Designated_Type (Type_Entity); end loop; exit; end if; end loop; if Nkind (Type_Entity) = N_Subtype_Indication and then Nkind (Parent (Type_Entity)) = N_Subtype_Declaration then Type_Entity := Parent (Type_Entity); end if; if Nkind (Type_Entity) = N_Subtype_Declaration then Type_Entity := Defining_Identifier (Type_Entity); else Type_Entity := Entity (Sinfo.Subtype_Mark (Type_Entity)); end if; while Type_Entity /= Etype (Type_Entity) loop exit when Comes_From_Source (Type_Entity) and then Comes_From_Source (Original_Node (Parent (Type_Entity))) and then Nkind (Parent (Type_Entity)) /= N_Subtype_Declaration; Type_Entity := Etype (Type_Entity); if Ekind (Type_Entity) = E_Access_Type then Type_Entity := Directly_Designated_Type (Type_Entity); elsif (Ekind (Type_Entity) = E_Private_Type or else Ekind (Type_Entity) = E_Limited_Private_Type) and then Present (Full_View (Type_Entity)) then Type_Entity := Full_View (Type_Entity); end if; end loop; -- Take care of a private type with unknown discriminant part: if Nkind (Parent (Type_Entity)) in N_Private_Extension_Declaration .. N_Private_Type_Declaration and then Unknown_Discriminants_Present (Parent (Type_Entity)) then Type_Entity := Full_View (Type_Entity); end if; -- In case of a derived types, we may have discriminants declared for an -- ansector type and then redefined for some child type Search_Discriminant : loop Result := Original_Node (Parent (Type_Entity)); Result := First (Discriminant_Specifications (Result)); while Present (Result) loop if Chars (Defining_Identifier (Result)) = Res_Chars then Result := Defining_Identifier (Result); exit Search_Discriminant; else Result := Next (Result); end if; end loop; exit Search_Discriminant when Type_Entity = Etype (Type_Entity); Type_Entity := Etype (Type_Entity); end loop Search_Discriminant; pragma Assert (Present (Result)); return Result; end Get_Discriminant_From_Type; ------------------------------- -- Get_Entity_From_Long_Name -- ------------------------------- function Get_Entity_From_Long_Name (N : Node_Id) return Entity_Id is Result : Entity_Id := Empty; Arg_Chars : constant Name_Id := Chars (N); Res_Chars : Name_Id; P : Node_Id; Next_Entity : Entity_Id; begin P := Parent (N); while No (Entity (P)) loop P := Parent (P); end loop; Next_Entity := Entity (P); Res_Chars := Chars (Next_Entity); loop if Res_Chars = Arg_Chars then Result := Next_Entity; exit; end if; if Nkind (Parent (Next_Entity)) = N_Defining_Program_Unit_Name then P := Sinfo.Name (Parent (Next_Entity)); Next_Entity := Entity (P); Res_Chars := Chars (Next_Entity); else exit; end if; end loop; pragma Assert (Present (Result)); return Result; end Get_Entity_From_Long_Name; ----------------------------- -- Get_Rewritten_Discr_Ref -- ----------------------------- function Get_Rewritten_Discr_Ref (N : Node_Id) return Node_Id is Res_Chars : constant Name_Id := Chars (N); Result : Node_Id := Parent (N); begin while not (Nkind (Result) = N_Identifier and then Is_Rewrite_Substitution (Result) and then Nkind (Original_Node (Result)) = N_Subtype_Indication) loop Result := Parent (Result); end loop; -- Go to the declaration of this internal subtype Result := Parent (Entity (Result)); -- Now - no the constraint Result := Sinfo.Constraint (Sinfo.Subtype_Indication (Result)); -- And iterating through discriminant names Result := First (Constraints (Result)); Result := First (Selector_Names (Result)); while Present (Result) loop if Chars (Result) = Res_Chars then exit; end if; -- Get to the next discriminant if Present (Next (Result)) then Result := Next (Result); else Result := Next (Parent (Result)); if Present (Result) then Result := First (Selector_Names (Result)); end if; end if; end loop; pragma Assert (Present (Result)); return Result; end Get_Rewritten_Discr_Ref; ------------------------------ -- Get_Specificed_Component -- ------------------------------ function Get_Specificed_Component (Comp : Node_Id; Rec_Type : Entity_Id) return Entity_Id is Rec_Type_Entity : Entity_Id; Result : Entity_Id := Empty; Res_Chars : constant Name_Id := Chars (Comp); Next_Comp : Node_Id; begin if Ekind (Rec_Type) = E_Private_Type or else Ekind (Rec_Type) = E_Limited_Private_Type then Rec_Type_Entity := Full_View (Rec_Type); else Rec_Type_Entity := Rec_Type; end if; Next_Comp := First_Entity (Rec_Type_Entity); while Present (Next_Comp) loop if Chars (Next_Comp) = Res_Chars then Result := Next_Comp; exit; end if; Next_Comp := Next_Entity (Next_Comp); end loop; pragma Assert (Present (Result)); return Result; end Get_Specificed_Component; ------------------------------ -- Get_Statement_Identifier -- ------------------------------ function Get_Statement_Identifier (Def_Id : Node_Id) return Node_Id is Result_Node : Node_Id := Empty; -- List_Elem : Node_Id; begin Result_Node := Label_Construct (Parent (Def_Id)); if not (Nkind (Result_Node) = N_Label) then -- this means, that Result_Node is of N_Block_Statement or -- of N_Loop_Statement kind, therefore Result_Node := Sinfo.Identifier (Result_Node); end if; return Result_Node; end Get_Statement_Identifier; --------------------- -- GFP_Declaration -- --------------------- function GFP_Declaration (Par_Id : Node_Id) return Node_Id is Par_Chars : constant Name_Id := Chars (Par_Id); Result_Node : Node_Id; Gen_Par_Decl : Node_Id; begin -- First, going up to the generic instantiation itself: Result_Node := Parent (Parent (Par_Id)); -- then taking the name of the generic unit being instantiated -- and going to its definition - and declaration: Result_Node := Parent (Parent (Entity (Sinfo.Name (Result_Node)))); -- and now - searching the declaration of the corresponding -- generic parameter: Gen_Par_Decl := First_Non_Pragma (Generic_Formal_Declarations (Result_Node)); while Present (Gen_Par_Decl) loop if Nkind (Gen_Par_Decl) in N_Formal_Subprogram_Declaration then Result_Node := Defining_Unit_Name (Specification (Gen_Par_Decl)); else Result_Node := Defining_Identifier (Gen_Par_Decl); end if; if Chars (Result_Node) = Par_Chars then exit; else Gen_Par_Decl := Next_Non_Pragma (Gen_Par_Decl); end if; end loop; return Result_Node; end GFP_Declaration; -------------------------------- -- Identifier_Name_Definition -- -------------------------------- function Identifier_Name_Definition (Reference_I : Element) return Asis.Defining_Name is Arg_Node : Node_Id; Arg_Node_Kind : Node_Kind; Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Reference_I); Result_Node : Node_Id := Empty; Result_Unit : Compilation_Unit; Spec_Case : Special_Cases := Not_A_Special_Case; Result_Kind : Internal_Element_Kinds := Not_An_Element; Is_Inherited : Boolean := False; Association_Type : Node_Id := Empty; -- ??? Is it a good name for a parameter? Componnet_Name : Node_Id := Empty; Tmp_Node : Node_Id; Result : Asis.Element; function Ekind (N : Node_Id) return Entity_Kind; -- This function differs from Atree.Ekind in that it can operate -- with N_Defining_Program_Unit_Name (in this case it returns -- Atree.Ekind for the corresponding Defining_Identifier node. function Ekind (N : Node_Id) return Entity_Kind is Arg_Node : Node_Id := N; begin if Nkind (Arg_Node) = N_Defining_Program_Unit_Name then Arg_Node := Defining_Identifier (Arg_Node); end if; return Atree.Ekind (Arg_Node); end Ekind; begin -- this function is currently integrated with -- Enumeration_Literal_Name_Definition and -- Operator_Symbol_Name_Definition -- The implementation approach is very similar to that one of -- A4G.A_Sem.Get_Corr_Called_Entity. Now the implicit *predefined* -- operations are turned off for a while ------------------------------------------------------------------ -- 1. Defining Result_Node (and adjusting Arg_Node, if needed) -- ------------------------------------------------------------------ if Arg_Kind = An_Identifier then Result_Kind := A_Defining_Identifier; -- may be changed to A_Defining_Expanded_Name later elsif Arg_Kind = An_Enumeration_Literal then Result_Kind := A_Defining_Enumeration_Literal; elsif Arg_Kind in Internal_Operator_Symbol_Kinds then Result_Kind := Def_Operator_Kind (Int_Kind (Reference_I)); end if; if Special_Case (Reference_I) = Rewritten_Named_Number then Arg_Node := R_Node (Reference_I); else -- Arg_Node := Get_Actual_Type_Name (Node (Reference_I)); Arg_Node := Node (Reference_I); end if; -- the code below is really awful! In some future we'll have -- to revise this "patch on patch" approach!!! if Is_Part_Of_Defining_Unit_Name (Arg_Node) and then Kind (Encl_Unit (Reference_I)) in A_Library_Unit_Body then -- this means, that we have a part of a prefix of a defining -- unit name which is a part of a body. These components do not -- have Entity field set, so we have to go to the spec: Arg_Node := Reset_To_Spec (Arg_Node); end if; if Nkind (Arg_Node) in N_Entity then -- This is the case of the reference to a formal type inside -- the expanded code when the actual type is a derived type -- In this case Get_Actual_Type_Name returns the entity node -- (see 8924-006) Result_Node := Arg_Node; Arg_Node := Node (Reference_I); -- For the rest of the processing we need Arg_Node properly set as -- the reference, but not as an entity node elsif Special_Case (Reference_I) = Rewritten_Named_Number then -- See BB10-002 Result_Node := Original_Entity (Arg_Node); elsif No (Entity (Arg_Node)) then Arg_Node_Kind := Nkind (Original_Node (Parent (Arg_Node))); -- in some cases we can try to "repair" the situation: if Arg_Node_Kind = N_Expanded_Name then -- the Entity field is set for the whole expanded name: if Entity_Present (Original_Node (Parent (Arg_Node))) or else Entity_Present (Parent (Arg_Node)) then Arg_Node := Parent (Arg_Node); -- In case of renamings, here we may have the expanded name -- rewritten, and the Entity field for the new name pointing -- to the renamed entity, but not to the entity defined by -- the renamed declaration, see B924-A13 if Is_Rewrite_Substitution (Arg_Node) and then Entity_Present (Original_Node (Arg_Node)) then Arg_Node := Original_Node (Arg_Node); end if; else -- Trying to "traverse a "long" defining program unit -- name (see 7917-005) Result_Node := Get_Entity_From_Long_Name (Arg_Node); end if; elsif Arg_Node_Kind = N_Component_Definition and then Sloc (Arg_Node) = Standard_Location then -- Special case of Subtype_Indication for predefined String -- and Wide_String types: Result_Node := Parent (Parent (Parent (Arg_Node))); -- Here we are in N_Full_Type_Declaration node Result_Node := Defining_Identifier (Result_Node); Result_Node := Component_Type (Result_Node); Spec_Case := Explicit_From_Standard; elsif Arg_Node_Kind = N_Function_Call then -- this is a special case of a parameterless function call -- of the form P.F Arg_Node := Sinfo.Name (Original_Node (Parent (Arg_Node))); elsif Arg_Node_Kind = N_Integer_Literal or else Arg_Node_Kind = N_Real_Literal or else Arg_Node_Kind = N_Character_Literal or else Arg_Node_Kind = N_String_Literal or else Arg_Node_Kind = N_Identifier then -- All but last conditions are a result of some compile-time -- optimization. The last one is a kind of -- semantically-transparent transformation which loses some -- semantic information for replaced structures (see the test -- for 9429-006). -- -- The last condition may need some more attention in case if new -- Corresponding_Name_Definition problems are detected Arg_Node := Original_Node (Parent (Arg_Node)); elsif Arg_Node_Kind = N_Component_Association and then Nkind (Parent (Parent (Arg_Node))) = N_Raise_Constraint_Error then -- A whole aggregate is rewritten into N_Raise_Constraint_Error -- node, see G628-026 Tmp_Node := Parent (Parent (Arg_Node)); Tmp_Node := Etype (Tmp_Node); Tmp_Node := First_Entity (Tmp_Node); while Present (Tmp_Node) loop if Chars (Tmp_Node) = Chars (Arg_Node) then Result_Node := Tmp_Node; exit; end if; Tmp_Node := Next_Entity (Tmp_Node); end loop; pragma Assert (Present (Result_Node)); if not (Comes_From_Source (Result_Node)) and then Comes_From_Source (Parent (Result_Node)) then Result_Node := Defining_Identifier (Parent (Result_Node)); end if; elsif Arg_Node_Kind = N_Component_Association and then Nkind (Sinfo.Expression (Parent (Arg_Node))) = N_Raise_Constraint_Error then -- here we are guessing for the situation when a compiler -- optimization take place. We can probably be non-accurate -- for inherited record components, but what can we do.... -- -- first, defining the corresponding Entity Node, we assume -- it to be a record component definition Result_Node := Parent (Parent (Arg_Node)); -- aggregate Association_Type := Etype (Result_Node); if Ekind (Association_Type) in Private_Kind then Association_Type := Full_View (Association_Type); end if; Result_Node := First_Entity (Association_Type); while Chars (Result_Node) /= Chars (Arg_Node) loop Result_Node := Next_Entity (Result_Node); end loop; elsif Arg_Node_Kind = N_Parameter_Association and then Arg_Node = Selector_Name (Parent (Arg_Node)) then -- Currently we assume, that this corresponds to the case of -- formal parameters of predefined operations return Nil_Element; elsif Arg_Node_Kind = N_Component_Clause then -- Component clause in record representation clause - Entity -- field is not set, we have to traverse the list of components -- of the record type Association_Type := Entity (Sinfo.Identifier (Parent (Parent (Arg_Node)))); if Ekind (Association_Type) = E_Record_Subtype then -- In case of a subtype it may be the case that some components -- depending on discriminant are skipped in case of a static -- discriminnat constraint, see also -- A4G.Mapping.Set_Inherited_Components Association_Type := Etype (Association_Type); end if; Result_Node := Get_Specificed_Component (Arg_Node, Association_Type); Association_Type := Empty; -- Association_Type is set back to Empty to make it possible -- to use the general approach for computing Association_Type -- later elsif Nkind (Arg_Node) = N_Identifier and then Sloc (Parent (Arg_Node)) = Standard_ASCII_Location then -- reference to Character in a constant definition in the -- ASCII package, see 8303-011 Result_Node := Standard_Character; elsif not (Arg_Node_Kind = N_Discriminant_Association or else Arg_Node_Kind = N_Generic_Association) and then not Is_From_Unknown_Pragma (R_Node (Reference_I)) then -- now we are considering all the other cases as component simple -- names in a (rewritten!) record aggregate, and we go from the -- original to the rewritten structure (because the original -- structure is not decorated). If this is not the case, we should -- get the Assert_Failure raised in Rewritten_Image -- Arg_Node := Rewritten_Image (Arg_Node); Result_Node := Search_Record_Comp (Arg_Node); end if; end if; if No (Result_Node) and then No (Entity (Arg_Node)) and then not (Nkind (Parent (Arg_Node)) = N_Discriminant_Association or else Nkind (Parent (Arg_Node)) = N_Generic_Association or else Is_From_Unknown_Pragma (R_Node (Reference_I))) then if Debug_Flag_S then Write_Str ("A4G.Expr_Sem.Identifier_Name_Definition:"); Write_Eol; Write_Str ("no Entity field is set for Node "); Write_Int (Int (Arg_Node)); Write_Eol; Write_Str (" the debug image of the query argument is:"); Write_Eol; Debug_String (Reference_I); Write_Str (Debug_Buffer (1 .. Debug_Buffer_Len)); Write_Eol; end if; raise Internal_Implementation_Error; end if; if Present (Result_Node) then null; elsif Is_From_Unknown_Pragma (R_Node (Reference_I)) then return Nil_Element; elsif Nkind (Parent (Arg_Node)) = N_Discriminant_Association and then Arg_Node /= Original_Node (Sinfo.Expression (Parent (Arg_Node))) then -- We use Original_Node (Sinfo.Expression (Parent (Arg_Node))) -- because of C730-016 (named numbers rewritten into their values) if No (Original_Discriminant (Arg_Node)) then Result_Node := Get_Discriminant_From_Type (Arg_Node); else Result_Node := Original_Discriminant (Arg_Node); if Present (Corresponding_Discriminant (Result_Node)) then Result_Node := Corresponding_Discriminant (Result_Node); end if; end if; elsif No (Entity (Arg_Node)) and then Nkind (Parent (Arg_Node)) = N_Generic_Association then -- this is the problem up to 3.10p. We have to compute -- N_Defining_Identifier_Node for this generic formal -- parameter "by hands" -- ??? should be rechecked for 3.11w!!! Result_Node := GFP_Declaration (Arg_Node); else Result_Node := Entity (Arg_Node); end if; -- Here we have Result_Node set. And now we have a whole bunch of -- situations when we have to correct Result_Node because of different -- reasons -- If Result_Node is the type reference, and the type has both private -- and full view, Result_Node will point to the private view. In some -- situations we have to replace it with the full view. if Ekind (Result_Node) in Einfo.Type_Kind and then Nkind (Original_Node (Parent (Result_Node))) in N_Private_Extension_Declaration .. N_Private_Type_Declaration and then Full_View_Visible (Priv_Type => Parent (Result_Node), Ref => Arg_Node) then Result_Node := Full_View (Result_Node); end if; -- FB02-015: Ada 2005 - reference to a record type with self-referencing -- components, The front-end creates an incomplete type -- declaration, and the Entity field may point to this -- incomplete type. if Ekind (Result_Node) = E_Incomplete_Type and then not Comes_From_Source (Result_Node) and then Nkind (Parent (Result_Node)) = N_Incomplete_Type_Declaration then Tmp_Node := Full_View (Result_Node); if Present (Tmp_Node) then Result_Node := Full_View (Result_Node); end if; end if; -- F818-A05: reference to a formal parameter of a child subprogram in -- case when the subprogram does not have a separate spec. -- The front-end creates some artificial data structures to -- represent this separate spec, so the entity field of a -- parameter reference points to some artificial node if Nkind (Parent (Result_Node)) = N_Parameter_Specification and then not (Comes_From_Source (Result_Node)) then -- Check if we are in the artificial spec created for child -- subprogram body: Tmp_Node := Scope (Result_Node); Tmp_Node := Parent (Parent (Parent (Tmp_Node))); if Nkind (Tmp_Node) = N_Subprogram_Declaration and then not Comes_From_Source (Tmp_Node) and then Present (Parent_Spec (Tmp_Node)) and then Present (Corresponding_Body (Tmp_Node)) then -- Go to the defining identifier of this parameter in subprogram -- body: Tmp_Node := Corresponding_Body (Tmp_Node); Tmp_Node := Parent (Parent (Tmp_Node)); Tmp_Node := First_Non_Pragma (Parameter_Specifications (Tmp_Node)); while Present (Tmp_Node) loop if Chars (Defining_Identifier (Tmp_Node)) = Chars (Result_Node) then Result_Node := Defining_Identifier (Tmp_Node); exit; end if; Tmp_Node := Next_Non_Pragma (Tmp_Node); end loop; pragma Assert (Present (Tmp_Node)); end if; end if; -- E802-015: for a protected operation items that do not have separate -- specs the front-end creates these specs and sets all the Entity -- fields pointing to the entities from these artificial specs. if Is_Artificial_Protected_Op_Item_Spec (Result_Node) then if Ekind (Result_Node) in Formal_Kind then Tmp_Node := Parent (Parent (Parent (Result_Node))); Tmp_Node := Parent (Corresponding_Body (Tmp_Node)); Tmp_Node := First_Non_Pragma (Parameter_Specifications (Tmp_Node)); while Present (Tmp_Node) loop if Chars (Defining_Identifier (Tmp_Node)) = Chars (Result_Node) then Result_Node := Defining_Identifier (Tmp_Node); exit; else Tmp_Node := Next_Non_Pragma (Tmp_Node); end if; end loop; else -- The only possibility - the protected operation entity Result_Node := Corresponding_Body (Parent (Parent (Result_Node))); end if; end if; -- See E421-006: problem with reference to a formal type in an expanded -- code. if Present (Result_Node) and then Is_Itype (Result_Node) -- and then Present (Cloned_Subtype (Result_Node)) then if Special_Case (Reference_I) = Dummy_Base_Attribute_Prefix then Result_Node := Associated_Node_For_Itype (Result_Node); else Result_Node := Etype (Result_Node); end if; -- This is for E912-013 if No (Parent (Result_Node)) and then Present (Associated_Node_For_Itype (Result_Node)) then Result_Node := Defining_Identifier (Associated_Node_For_Itype (Result_Node)); elsif Special_Case (Reference_I) = Dummy_Base_Attribute_Prefix then Result_Node := Defining_Identifier (Result_Node); end if; end if; -- Problem with System redefined with Extend_System pragma (E315-001) if Nkind (Arg_Node) in N_Has_Chars and then Chars (Arg_Node) = Name_System and then Chars (Result_Node) /= Name_System and then Nkind (Parent (Result_Node)) = N_Defining_Program_Unit_Name then Result_Node := Entity (Sinfo.Name (Parent (Result_Node))); pragma Assert (Chars (Result_Node) = Name_System); end if; -- Problem with tasks defined by a single task definition: for such a -- definition the front-end creates an artificial variable declaration -- node, and for the references to such task, the Entity field points to -- the entity node from this artificial variable declaration (E224-024). -- The same problem exists for a single protected declaration -- (E418-015) Tmp_Node := Parent (Result_Node); if Comes_From_Source (Result_Node) and then not Comes_From_Source (Tmp_Node) and then Nkind (Tmp_Node) = N_Object_Declaration and then not Constant_Present (Tmp_Node) and then No (Corresponding_Generic_Association (Tmp_Node)) then Tmp_Node := Etype (Result_Node); if Ekind (Tmp_Node) in Concurrent_Kind then Result_Node := Parent (Result_Node); while not (Nkind (Result_Node) = N_Task_Type_Declaration or else Nkind (Result_Node) = N_Protected_Type_Declaration) loop Result_Node := Prev (Result_Node); end loop; end if; Result_Node := Defining_Identifier (Original_Node (Result_Node)); end if; -- F703-020: see the comment marked by this TN in the body of -- A4G.A_Sem.Get_Corr_Called_Entity if not Comes_From_Source (Result_Node) and then Is_Overloadable (Result_Node) and then Present (Alias (Result_Node)) and then not (Is_Intrinsic_Subprogram (Result_Node)) and then Pass_Generic_Actual (Parent (Result_Node)) then -- ??? Result_Node := Alias (Result_Node); end if; -- and here we have to solve the problem with generic instances: -- for them Result_Node as it has been obtained above points not -- to the defining identifier from the corresponding instantiation, -- but to an entity defined in a "implicit" package created by the -- compiler if Is_Generic_Instance (Result_Node) then Result_Node := Get_Instance_Name (Result_Node); end if; -- If the argument is Is_Part_Of_Implicit reference to a type, we -- have to check if it is the reference to a type mark in parameter -- or parameter and result profile of inherited subprogram and if it -- should be substituted by the reference to the corresponding -- derived type Tmp_Node := Node_Field_1 (Reference_I); if Ekind (Result_Node) in Einfo.Type_Kind and then Is_From_Inherited (Reference_I) and then Nkind (Tmp_Node) in Sinfo.N_Entity and then (Ekind (Tmp_Node) = E_Procedure or else Ekind (Tmp_Node) = E_Function) then Result_Node := Get_Derived_Type (Type_Entity => Result_Node, Inherited_Subpr => Tmp_Node); end if; -- labels (and, probably, statement names!!) makes another problem: -- we have to return not the implicit label (statement identifier??) -- declaration, but the label (statement name) attached to the -- corresponding statement if Nkind (Parent (Result_Node)) = N_Implicit_Label_Declaration then Result_Node := Get_Statement_Identifier (Result_Node); end if; Tmp_Node := Original_Node (Parent (Parent (Result_Node))); while Nkind (Tmp_Node) = N_Subprogram_Renaming_Declaration and then not (Comes_From_Source (Tmp_Node)) and then not Pass_Generic_Actual (Tmp_Node) loop -- Result_Node is a defining name from the artificial renaming -- declarations created by the compiler in the for wrapper -- package for expanded subprogram instantiation. We -- have to go to expanded subprogram spec which is renamed. -- -- We have to do this in a loop in case of nested instantiations Result_Node := Sinfo.Name (Tmp_Node); if Nkind (Result_Node) = N_Selected_Component then Result_Node := Selector_Name (Result_Node); end if; Result_Node := Entity (Result_Node); Tmp_Node := Parent (Parent (Result_Node)); end loop; -- -- ??? -- if Ekind (Result_Node) = E_Operator then -- Result_Kind := N_Defining_Identifier_Mapping (Result_Node); -- end if; if Nkind (Parent (Result_Node)) = N_Defining_Program_Unit_Name or else Nkind (Result_Node) = N_Defining_Program_Unit_Name then -- if we are processing the reference to a child unit, we have to -- go from a defining identifier to the corresponding defining -- unit name (the first part of the condition). -- If this is a reference to a child subprogram, for which -- the separate subprogram specification does not exist, -- GNAT generates the tree structure corresponding to such a -- separate subprogram specification, and it set the Entity -- field for all references to this subprogram pointing -- to the defining identifier in this inserted subprogram -- specification. This case may be distinguished by the fact, -- that Comes_From_Source field for this defining identifier -- is set OFF. And in this case we have to go to the defining -- identifier in the subprogram body: if not Comes_From_Source (Result_Node) then -- we have to go to the defining identifier in the -- corresponding body: while not (Nkind (Result_Node) = N_Subprogram_Declaration) loop Result_Node := Parent (Result_Node); end loop; Result_Node := Corresponding_Body (Result_Node); end if; if Nkind (Result_Node) /= N_Defining_Program_Unit_Name then Result_Node := Parent (Result_Node); end if; Result_Kind := A_Defining_Expanded_Name; if not Comes_From_Source (Result_Node) then -- now it means that we have a library level instantiation -- of a generic child package Result_Node := Parent (Parent (Result_Node)); Result_Node := Original_Node (Result_Node); if Nkind (Result_Node) = N_Package_Declaration then Result_Node := Sinfo.Corresponding_Body (Result_Node); while Nkind (Result_Node) /= N_Package_Body loop Result_Node := Parent (Result_Node); end loop; Result_Node := Original_Node (Result_Node); end if; Result_Node := Defining_Unit_Name (Result_Node); end if; end if; if Nkind (Result_Node) = N_Defining_Identifier and then (Ekind (Result_Node) = E_In_Parameter or else Ekind (Result_Node) = E_Constant) and then Present (Discriminal_Link (Result_Node)) then -- here we have to go to an original discriminant Result_Node := Discriminal_Link (Result_Node); end if; -- FA13-008: subtype mark in parameter specification in implicit "/=" -- declaration in case if in the corresponding "=" the parameter is -- specified by 'Class attribute: if Nkind (Arg_Node) = N_Identifier and then not Comes_From_Source (Arg_Node) and then Ekind (Result_Node) = E_Class_Wide_Type and then Result_Node /= Defining_Identifier (Parent (Result_Node)) then Result_Node := Defining_Identifier (Parent (Result_Node)); end if; -- Now we have Result_Node pointing to some defining name. There are -- some kinds of entities which require special processing. For -- implicitly declared entities we have to set Association_Type -- pointing to a type which "generates" the corresponding implicit -- declaration (there is no harm to set Association_Type for explicitly -- declared entities, but for them it is of no use). For predefined -- entities the special case attribute should be set. ---------------------------------------- -- temporary solution for 5522-003 ???-- ---------------------------------------- -- The problem for record components: -- -- 1. The Entity field for references to record components and -- disciminants may point to field of some implicit types created -- by the compiler -- -- 2. The Entity field for the references to the (implicitly declared!) -- components of a derived record type point to the explicit -- declarations of the component of the ancestor record type -- -- 3. Probably, all this stuff should be incapsulated in a separate -- subprogram??? -- Here we already have Result_Node: if Nkind (Result_Node) = N_Defining_Identifier and then (Ekind (Result_Node) = E_Component or else Ekind (Result_Node) = E_Discriminant or else Ekind (Result_Node) = E_Entry or else Ekind (Result_Node) = E_Procedure or else Ekind (Result_Node) = E_Function) then -- first, we compute Association_Type as pointed to a type -- declaration for which Agr_Node is a component: if No (Association_Type) then Association_Type := Parent (Arg_Node); if Nkind (Association_Type) = N_Function_Call then Association_Type := Sinfo.Name (Association_Type); end if; case Nkind (Association_Type) is when N_Component_Clause => Association_Type := Sinfo.Identifier (Parent (Association_Type)); when N_Selected_Component => Association_Type := Prefix (Association_Type); if Nkind (Association_Type) = N_Attribute_Reference and then (Attribute_Name (Association_Type) = Name_Unrestricted_Access or else Attribute_Name (Association_Type) = Name_Access) then -- See G222-012 Association_Type := Prefix (Association_Type); end if; if Nkind (Association_Type) = N_Selected_Component then Association_Type := Selector_Name (Association_Type); end if; when N_Component_Association => Association_Type := Parent (Association_Type); when N_Discriminant_Association => if Arg_Node = Sinfo.Expression (Association_Type) then -- using a discriminant in initialization expression Association_Type := Empty; else Association_Type := Scope (Result_Node); end if; when others => -- We set Association_Type as Empty to indicate the case of -- a definitely explicit result Association_Type := Empty; end case; end if; if Present (Association_Type) then if not (Comes_From_Source (Association_Type) and then Nkind (Association_Type) in N_Entity and then Ekind (Association_Type) in Einfo.Type_Kind) then Association_Type := Etype (Association_Type); end if; if Nkind (Original_Node (Parent (Association_Type))) = N_Single_Task_Declaration or else Nkind (Original_Node (Parent (Association_Type))) = N_Single_Protected_Declaration then Association_Type := Empty; else if Ekind (Result_Node) = E_Component and then not Comes_From_Source (Parent (Result_Node)) and then Ekind (Association_Type) in Private_Kind then Association_Type := Full_View (Association_Type); end if; Association_Type := Explicit_Type_Declaration_Unwound_Unaccess (Association_Type, Arg_Node); if Nkind (Original_Node (Association_Type)) in N_Protected_Type_Declaration .. N_Private_Extension_Declaration then Association_Type := Parent (Full_View (Defining_Identifier (Original_Node (Association_Type)))); end if; end if; end if; -- then, we have to adjust result Node: if Ekind (Result_Node) = E_Discriminant and then Chars (Discriminal (Result_Node)) /= Chars (Original_Record_Component (Result_Node)) then -- This condition is the clue for discriminants explicitly -- declared in declarations of derived types. -- These assignments below resets Result_Node to -- N_Defining_Identifier node which denotes the same discriminant -- but has a properly set bottom-up chain of Parent nodes Result_Node := Discriminal (Result_Node); Result_Node := Discriminal_Link (Result_Node); else -- There we have to come from an implicit type to a explicitly -- declared type: Tmp_Node := Scope (Result_Node); if Ekind (Tmp_Node) = E_Record_Subtype then Tmp_Node := Etype (Tmp_Node); end if; if (Ekind (Result_Node) = E_Component or else Ekind (Result_Node) = E_Discriminant) and then not (Comes_From_Source (Result_Node) and then not Comes_From_Source (Parent (Result_Node))) then -- This condition leaves unchanged inherited discriminants -- of derived record types Tmp_Node := First_Entity (Tmp_Node); while Present (Tmp_Node) loop if Chars (Tmp_Node) = Chars (Result_Node) then Result_Node := Tmp_Node; exit; end if; Tmp_Node := Next_Entity (Tmp_Node); end loop; end if; end if; -- A private type may require some special adjustment in case if -- full view is visible: if Result_Node is a discriminant: -- it points to a discriminant in a private view, and we have -- to reset it to point to the discriminant in the full view if Present (Association_Type) and then Has_Private_Declaration (Defining_Identifier (Association_Type)) and then Ekind (Result_Node) = E_Discriminant and then Nkind (Association_Type) /= N_Private_Type_Declaration and then Nkind (Association_Type) /= N_Private_Extension_Declaration and then Is_Type_Discriminant (Result_Node, Original_Node (Association_Type)) then Result_Node := Reset_To_Full_View (Association_Type, Result_Node); end if; -- Now, we have to define if we have an implicit component here. -- Result_Context_Node is finally supposed to be set to the -- declaration of the type to which the argument component belongs if No (Association_Type) then -- definitely explicit result: Is_Inherited := False; elsif Is_Rewrite_Substitution (Association_Type) then -- here we have a derived type with no record extension part -- but it can have an explicitly declared discriminant if Ekind (Result_Node) = E_Discriminant then Is_Inherited := not (Is_Type_Discriminant ( Result_Node, Original_Node (Association_Type))); else Is_Inherited := True; end if; elsif Nkind (Association_Type) = N_Incomplete_Type_Declaration or else Nkind (Association_Type) = N_Private_Extension_Declaration or else Nkind (Association_Type) = N_Private_Type_Declaration or else Nkind (Association_Type) = N_Task_Type_Declaration or else Nkind (Association_Type) = N_Protected_Type_Declaration or else (Nkind (Association_Type) = N_Formal_Type_Declaration and then Nkind (Sinfo.Formal_Type_Definition (Association_Type)) = N_Formal_Private_Type_Definition) or else Nkind (Sinfo.Type_Definition (Association_Type)) = N_Record_Definition then -- should be an explicit component Is_Inherited := False; -- Patch for E407-A08 if Ekind (Result_Node) = E_Component then Result_Node := Original_Record_Component (Result_Node); end if; elsif Nkind (Sinfo.Type_Definition (Association_Type)) = N_Derived_Type_Definition then -- it may be an inherited component or an explicitly declared -- discriminant or a component from a record extension part if Is_Explicit_Type_Component (Result_Node, Association_Type) then Is_Inherited := False; else Is_Inherited := True; end if; else -- ??? this Assert pragma - only for development/debug period -- ??? what else except N_Selected_Component could be here null; pragma Assert (False); end if; end if; ------------------------------------------------- -- end for the temporary solution for 5522-003 -- ------------------------------------------------- -------------------------- -- Enumeration literals -- -------------------------- if not (Defined_In_Standard (Arg_Node)) and then Nkind (Result_Node) = N_Defining_Identifier -- or else -- Nkind (Result_Node) = N_Defining_Character_Literal) and then Ekind (Result_Node) = E_Enumeration_Literal and then (not Comes_From_Source (Result_Node)) then -- an enumeration literal inherited by a derived type definition -- (character literals are still processed by a separate function -- Character_Literal_Name_Definition, that's why the corresponding -- part of the condition is commented out) -- ???Needs revising for the new model of implicit Elements Is_Inherited := True; Association_Type := Etype (Arg_Node); Association_Type := Explicit_Type_Declaration_Unwound (Association_Type); end if; --------------------------------------- -- The rest of special processing: -- -- somewhat messy and needs revising -- --------------------------------------- -- We have to turn off for a while the full processing of the -- implicit elements (Hope to fix this soon). if Defined_In_Standard (Arg_Node) or else Sloc (Arg_Node) <= Standard_Location or else Sloc (Result_Node) <= Standard_Location then -- We need the second part of the condition for references to -- Standard.Characters which are parts of the definitions in -- the ASCII package if Ekind (Result_Node) = E_Operator then return Nil_Element; else -- I hope, that I'm right, that all the *identifiers* declared -- in standard are declared explicitly, and all the rest -- (which are defined in Standard) are implicit -- Root and universal types can make a problem, but let's -- see it before... Spec_Case := Explicit_From_Standard; end if; else if Result_Kind in Internal_Defining_Operator_Kinds then if Is_Predefined (Result_Node) then Spec_Case := Predefined_Operation; -- -- note, that Predefined_Operation corresponds to an -- -- implicitly declared operation of a type, which is defined -- -- not in the Standard package -- Association_Type := Enclosed_Type (Result_Node); -- -- we have to use namely Association_Type, but not Result_Node -- -- to define Result_Unit, because sometimes Result_Node -- -- does not have the Parent field set return Nil_Element; -- ???!!! this turns off all the predefined operations -- !!!??? defined not in Standard elsif Is_Impl_Neq (Result_Node) then Spec_Case := Is_From_Imp_Neq_Declaration; end if; end if; end if; ------------------- -- Limited views -- ------------------- if Spec_Case = Not_A_Special_Case then Tmp_Node := Result_Node; if Nkind (Tmp_Node) = N_Defining_Program_Unit_Name then Tmp_Node := Defining_Identifier (Tmp_Node); end if; if Nkind (Tmp_Node) in N_Entity then case Ekind (Tmp_Node) is when Einfo.Type_Kind => if not Comes_From_Source (Tmp_Node) and then Ekind (Tmp_Node) in Incomplete_Kind and then Present (Non_Limited_View (Tmp_Node)) then Spec_Case := From_Limited_View; Result_Node := Non_Limited_View (Result_Node); end if; when E_Package => if not Is_Generic_Instance (Tmp_Node) then if not Analyzed (Parent (Result_Node)) then Spec_Case := From_Limited_View; elsif Is_Limited_Withed (Result_Node, Reference_I) then Spec_Case := From_Limited_View; end if; end if; when others => null; end case; end if; end if; if Spec_Case not in Predefined and then Spec_Case /= Is_From_Imp_Neq_Declaration and then Spec_Case /= From_Limited_View and then not Comes_From_Source (Result_Node) and then No (Association_Type) and then not Part_Of_Pass_Generic_Actual (Result_Node) then -- Here we may have the following possibilities: -- - library-level subprogram instantiation; -- - artificial entity created for an inner package from a package -- "withed" by a limited with clause; -- - defining name from the artificial spec created for subprogram -- body which acts as a spec; -- - prefix of the artificial 'Class attribute reference (ASIS has -- to emulate such an attribute reference in case if a class-wide -- type is use as an actual type in the instantiation); -- - index (sub)type in case if the corresponding type is declared as -- private (F424-A01); -- - F619-024; -- - F627-001 -- - inherited subprogram; if Nkind (Parent (Result_Node)) in N_Subprogram_Specification then if Is_Generic_Instance (Result_Node) then -- Library-level subprogram instantiation -- Here we have to go from the rewritten to the original -- tree structure -- This code appeared at some point, but it seems that it is -- of no real need. Will be for a while - just in case. -- It does not allow to fix G312-006 -- ??? -- Result_Node := Parent (Parent (Parent (Parent (Result_Node)))); -- Result_Node := Original_Node (Result_Node); -- Result_Node := Sinfo.Defining_Unit_Name (Result_Node); null; else -- Artificial subprogram spec created for the body acting -- as spec Result_Node := Parent (Parent (Result_Node)); Result_Node := Corresponding_Body (Result_Node); end if; elsif Nkind (Parent (Result_Node)) = N_Package_Specification and then Comes_From_Source (Parent (Result_Node)) then -- An artificial internal entity created for a local package -- from a package that is "withed" by limited with clause -- We go to the entity node the package spec points to. -- See F310-025 and F311-003. Result_Node := Defining_Unit_Name (Parent (Result_Node)); elsif Special_Case (Reference_I) = Dummy_Class_Attribute_Prefix and then Ekind (Result_Node) = E_Class_Wide_Type then Result_Node := Defining_Identifier (Parent (Result_Node)); elsif Ekind (Result_Node) in Discrete_Kind and then Nkind (Parent (Result_Node)) = N_Subtype_Declaration then -- Go to the full view of the corresponding private type: Result_Node := Sinfo.Subtype_Indication (Parent (Result_Node)); Result_Node := Entity (Result_Node); pragma Assert (Ekind (Result_Node) in Private_Kind); Result_Node := Full_View (Result_Node); elsif Ekind (Result_Node) = E_Package and then Is_Hidden (Result_Node) and then Is_Rewrite_Substitution (R_Node (Reference_I)) then -- This is the case when we have a reference to the instantiation -- of generic parent in the instantiation of generic child, -- see F619-024 Result_Node := Entity (R_Node (Reference_I)); if Nkind (Parent (Result_Node)) = N_Defining_Program_Unit_Name then Result_Node := Parent (Result_Node); Result_Kind := A_Defining_Expanded_Name; end if; elsif Ekind (Result_Node) = E_Package and then Nkind (Parent (Result_Node)) = N_Package_Renaming_Declaration and then not Comes_From_Source (Parent (Result_Node)) then -- Reference_I is the reference to the name of the instantiation -- inside an expanded template, but the name of the template is -- the defining expanded name. In this case we have to use the -- entity of the rewritten node (F627-001) Result_Node := Entity (R_Node (Reference_I)); else -- It should be inherited! -- The last condition is needed to filter out already processed -- cases. This case corresponds to inherited user-defined -- subprograms Is_Inherited := True; if Ekind (Result_Node) = E_Function or else Ekind (Result_Node) = E_Procedure then Association_Type := Result_Node; -- Points to the defining identifier of implicit inherited -- subprogram Result_Node := Explicit_Parent_Subprogram (Result_Node); -- Now Result_Node points to the defining identifier of -- explicit subprogram which is inherited else -- ??? Probably will need revising when inherited record -- components and enumeration literals are fully -- implemented Association_Type := Defining_Identifier (Parent (Result_Node)); Association_Type := First_Subtype (Association_Type); end if; end if; end if; if Defined_In_Standard (Arg_Node) then -- Here we may need to adjust the result node in case if it is an -- entity representing an unconstrained base type for a signed -- integer type (see Cstand.Create_Unconstrained_Base_Type) if No (Parent (Result_Node)) and then Ekind (Result_Node) = E_Signed_Integer_Type then Result_Node := Parent (Scalar_Range (Result_Node)); end if; Result_Unit := Get_Comp_Unit (Standard_Id, Encl_Cont_Id (Reference_I)); else if Result_Kind in Internal_Defining_Operator_Kinds and then Is_Predefined (Result_Node) then null; -- -- note, that Predefined_Operation corresponds to an -- -- implicitly declared operation of a type, which is defined -- -- not in the Standard package -- Association_Type := Enclosed_Type (Result_Node); -- -- we have to use namely Association_Type, but not Result_Node -- -- to define Result_Unit, because sometimes Result_Node -- -- does not have the Parent field set -- Result_Unit := -- Enclosing_Unit (Encl_Cont_Id (Reference_I), Association_Type); return Nil_Element; -- ???!!! this turns off all the predefined operations -- !!!??? defined not in Standard elsif Is_Inherited then Result_Unit := Enclosing_Unit (Encl_Cont_Id (Reference_I), Association_Type); else Result_Unit := Enclosing_Unit (Encl_Cont_Id (Reference_I), Result_Node); end if; end if; if Is_Inherited and then (Ekind (Result_Node) = E_Component or else Ekind (Result_Node) = E_Discriminant) then Componnet_Name := Result_Node; end if; -- A special case of fake Numeric_Error renaming is handled -- separately (see B712-0050) if Result_Node = Standard_Constraint_Error and then Chars (Result_Node) /= Chars (Arg_Node) then Result := Get_Numeric_Error_Renaming; Set_Int_Kind (Result, A_Defining_Identifier); else Result := Node_To_Element_New (Node => Result_Node, Node_Field_1 => Association_Type, Node_Field_2 => Componnet_Name, Internal_Kind => Result_Kind, Spec_Case => Spec_Case, Inherited => Is_Inherited, In_Unit => Result_Unit); end if; -- See the comment in the body of A4G.A_Sem.Get_Corr_Called_Entity if Present (Association_Type) then if Is_From_Instance (Association_Type) then Set_From_Instance (Result, True); else Set_From_Instance (Result, False); end if; end if; if Spec_Case = From_Limited_View then Set_From_Implicit (Result, True); end if; return Result; end Identifier_Name_Definition; -------------------------------- -- Is_Explicit_Type_Component -- -------------------------------- function Is_Explicit_Type_Component (Comp_Def_Name : Node_Id; Type_Decl : Node_Id) return Boolean is Result : Boolean := False; Cont_Node : Node_Id; begin Cont_Node := Parent (Comp_Def_Name); while Present (Cont_Node) loop if Cont_Node = Type_Decl then Result := True; exit; end if; Cont_Node := Parent (Cont_Node); end loop; return Result; end Is_Explicit_Type_Component; ------------------------------ -- Is_From_Dispatching_Call -- ------------------------------ function Is_From_Dispatching_Call (Reference : Element) return Boolean is Can_Be_Dynamically_Identified : Boolean := False; Ref_Node : Node_Id; Parent_Ref_Node : Node_Id; Ref_Entity : Entity_Id; Parent_Call : Node_Id := Empty; Result : Boolean := False; begin Ref_Node := R_Node (Reference); if not (Nkind (Ref_Node) = N_Identifier or else Nkind (Ref_Node) = N_Operator_Symbol) then return False; end if; Parent_Ref_Node := Parent (Ref_Node); if Nkind (Parent_Ref_Node) = N_Expanded_Name and then Ref_Node = Selector_Name (Parent_Ref_Node) then Ref_Node := Parent (Ref_Node); Parent_Ref_Node := Parent (Ref_Node); end if; -- First, detect if Reference indeed can be dynamically identified, that -- is, it is either a subprogram name in a call or a formal parameter -- name in a parameter association. Because of the performance reasons, -- we do this on the tree structures, but not using ASIS queries case Nkind (Parent_Ref_Node) is when N_Parameter_Association => if Selector_Name (Parent_Ref_Node) = Ref_Node then Can_Be_Dynamically_Identified := True; end if; when N_Procedure_Call_Statement | N_Function_Call => if Sinfo.Name (Parent_Ref_Node) = Ref_Node then Can_Be_Dynamically_Identified := True; end if; when others => null; end case; if Can_Be_Dynamically_Identified then Ref_Entity := Entity (Ref_Node); if No (Ref_Entity) and then Nkind (Parent (Ref_Node)) = N_Expanded_Name and then Ref_Node = Selector_Name (Parent (Ref_Node)) then Ref_Node := Parent (Ref_Node); Ref_Entity := Entity (Ref_Node); end if; if Present (Ref_Entity) then case Ekind (Ref_Entity) is when Formal_Kind => Parent_Call := Parent (Parent (Ref_Node)); when Subprogram_Kind => Parent_Call := Parent (Ref_Node); when others => null; end case; end if; if Present (Parent_Call) and then (Nkind (Parent_Call) = N_Procedure_Call_Statement or else Nkind (Parent_Call) = N_Function_Call) and then Present (Controlling_Argument (Parent_Call)) then Result := True; end if; end if; return Result; end Is_From_Dispatching_Call; ---------------------------- -- Is_Implicit_Formal_Par -- ---------------------------- function Is_Implicit_Formal_Par (Result_El : Element) return Boolean is Result : Boolean := False; Res_Node : constant Node_Id := Node (Result_El); Parent_Node : Node_Id; begin if Nkind (Res_Node) in N_Entity and then Ekind (Res_Node) in Formal_Kind then Parent_Node := Parent (Res_Node); if Present (Parent_Node) and then Nkind (Parent_Node) = N_Parameter_Specification and then Res_Node /= Defining_Identifier (Parent_Node) then -- The condition is no more than just a clue... Result := True; end if; end if; return Result; end Is_Implicit_Formal_Par; ----------------------- -- Is_Limited_Withed -- ----------------------- function Is_Limited_Withed (E : Entity_Id; Reference : Asis.Element) return Boolean is Result : Boolean := False; CU_E : Asis.Compilation_Unit; CU_R : Asis.Compilation_Unit; begin CU_E := Enclosing_Unit (Encl_Cont_Id (Reference), E); if Unit_Kind (CU_E) = A_Package then CU_R := Enclosing_Compilation_Unit (Reference); if not Is_Equal (CU_R, CU_E) then declare CU_E_Name : constant Program_Text := To_Upper_Case (Unit_Full_Name (CU_E)); Comp_Clauses : constant Asis.Element_List := Context_Clause_Elements (CU_R); Name_List : Element_List_Access; begin for C in Comp_Clauses'Range loop if Trait_Kind (Comp_Clauses (C)) in A_Limited_Trait .. A_Limited_Private_Trait then Name_List := new Asis.Element_List'(Clause_Names (Comp_Clauses (C))); for N in Name_List'Range loop if To_Upper_Case (Full_Name_Image (Name_List (N))) = CU_E_Name then Free (Name_List); Result := True; exit; end if; end loop; Free (Name_List); end if; end loop; end; end if; end if; return Result; end Is_Limited_Withed; ----------------------------------- -- Is_Part_Of_Defining_Unit_Name -- ----------------------------------- function Is_Part_Of_Defining_Unit_Name (Name_Node : Node_Id) return Boolean is Result : Boolean := False; Next_Node : Node_Id := Parent (Name_Node); begin while Present (Next_Node) loop if Nkind (Next_Node) = N_Defining_Program_Unit_Name then Result := True; exit; elsif not (Nkind (Next_Node) = N_Expanded_Name or else Nkind (Next_Node) = N_Selected_Component) then -- theoretically, we need only the first part of the condition, -- but the unit name in the body is not fully decorated and, -- therefore, has the wrong syntax structure, so we need the -- second part. We are keeping both in order to have the correct -- code if it is changed in the tree. exit; else Next_Node := Parent (Next_Node); end if; end loop; return Result; end Is_Part_Of_Defining_Unit_Name; ------------------ -- Is_Reference -- ------------------ function Is_Reference (Name : Asis.Element; Ref : Asis.Element) return Boolean is Ref_Kind : constant Internal_Element_Kinds := Reference_Kind (Name); Result : Boolean := False; begin if Int_Kind (Ref) = Ref_Kind then begin if Is_Equal (Corresponding_Name_Definition (Ref), Name) then Result := True; end if; exception -- Corresponding_Name_Definition may raise Asis_Failed with -- Value_Error status when applied to identifiers which -- cannot have definitions (see section 17.6). Here we -- have to skip such Elements paying no attention to -- exception raising when others => null; end; end if; return Result; end Is_Reference; -------------------------- -- Is_Type_Discriminant -- -------------------------- function Is_Type_Discriminant (Discr_Node : Node_Id; Type_Node : Node_Id) return Boolean is Discr_Chars : constant Name_Id := Chars (Discr_Node); Discr_List : List_Id; Next_Discr_Spec : Node_Id; Result : Boolean := False; begin Discr_List := Discriminant_Specifications (Type_Node); if Present (Discr_List) then Next_Discr_Spec := First (Discr_List); while Present (Next_Discr_Spec) loop if Chars (Defining_Identifier (Next_Discr_Spec)) = Discr_Chars then Result := True; exit; end if; Next_Discr_Spec := Next (Next_Discr_Spec); end loop; end if; return Result; end Is_Type_Discriminant; ---------------- -- Needs_List -- ---------------- function Needs_List (Reference : Asis.Element) return Boolean is Result : Boolean := False; N : Node_Id := R_Node (Reference); Entity_N : Entity_Id; Pragma_Name_Id : Name_Id; begin if Nkind (Parent (N)) = N_Pragma_Argument_Association then Pragma_Name_Id := Pragma_Name (Parent (Parent (N))); if Pragma_Name_Id = Name_Asynchronous or else Pragma_Name_Id = Name_Convention or else Pragma_Name_Id = Name_Export or else Pragma_Name_Id = Name_Import or else Pragma_Name_Id = Name_Inline then Entity_N := Entity (N); if Present (Entity_N) and then Is_Overloadable (Entity_N) and then Has_Homonym (Entity_N) then -- ??? Is this the right condition??? -- ??? At the moment we do not consider any GNAT-specific -- pragma N := Homonym (Entity_N); if Present (N) and then (not (Sloc (N) <= Standard_Location -- !!! Note, that this check filters out the predefined -- implicitly declared operations!!! or else Part_Of_Pass_Generic_Actual (N) or else (Ekind (N) in Subprogram_Kind and then Is_Formal_Subprogram (N)))) then Result := True; end if; end if; end if; end if; return Result; end Needs_List; -------------------- -- Reference_Kind -- -------------------- function Reference_Kind (Name : Asis.Element) return Internal_Element_Kinds is Arg_Kind : Internal_Element_Kinds := Int_Kind (Name); Result : Internal_Element_Kinds := Not_An_Element; begin if Arg_Kind in Internal_Defining_Name_Kinds then if Arg_Kind = A_Defining_Expanded_Name then Arg_Kind := Int_Kind (Defining_Selector (Name)); end if; end if; case Arg_Kind is when A_Defining_Identifier => Result := An_Identifier; when A_Defining_Character_Literal => Result := A_Character_Literal; when A_Defining_Enumeration_Literal => Result := An_Enumeration_Literal; when A_Defining_And_Operator => Result := An_And_Operator; when A_Defining_Or_Operator => Result := An_Or_Operator; when A_Defining_Xor_Operator => Result := An_Xor_Operator; when A_Defining_Equal_Operator => Result := An_Equal_Operator; when A_Defining_Not_Equal_Operator => Result := A_Not_Equal_Operator; when A_Defining_Less_Than_Operator => Result := A_Less_Than_Operator; when A_Defining_Less_Than_Or_Equal_Operator => Result := A_Less_Than_Or_Equal_Operator; when A_Defining_Greater_Than_Operator => Result := A_Greater_Than_Operator; when A_Defining_Greater_Than_Or_Equal_Operator => Result := A_Greater_Than_Or_Equal_Operator; when A_Defining_Plus_Operator => Result := A_Plus_Operator; when A_Defining_Minus_Operator => Result := A_Minus_Operator; when A_Defining_Concatenate_Operator => Result := A_Concatenate_Operator; when A_Defining_Unary_Plus_Operator => Result := A_Unary_Plus_Operator; when A_Defining_Unary_Minus_Operator => Result := A_Unary_Minus_Operator; when A_Defining_Multiply_Operator => Result := A_Multiply_Operator; when A_Defining_Divide_Operator => Result := A_Divide_Operator; when A_Defining_Mod_Operator => Result := A_Mod_Operator; when A_Defining_Rem_Operator => Result := A_Rem_Operator; when A_Defining_Exponentiate_Operator => Result := An_Exponentiate_Operator; when A_Defining_Abs_Operator => Result := An_Abs_Operator; when A_Defining_Not_Operator => Result := A_Not_Operator; when others => null; end case; return Result; end Reference_Kind; ------------------------ -- Reset_To_Full_View -- ------------------------ function Reset_To_Full_View (Full_View : Node_Id; Discr : Node_Id) return Node_Id is Result : Node_Id; Discr_Chars : constant Name_Id := Chars (Discr); begin Result := First (Discriminant_Specifications (Full_View)); while Present (Result) loop exit when Chars (Defining_Identifier (Result)) = Discr_Chars; Result := Next (Result); end loop; pragma Assert (Present (Result)); Result := Defining_Identifier (Result); return Result; end Reset_To_Full_View; ------------------- -- Reset_To_Spec -- ------------------- function Reset_To_Spec (Name_Node : Node_Id) return Node_Id is Result : Node_Id := Empty; Next_Node : Node_Id := Parent (Name_Node); Name_Chars : constant Name_Id := Chars (Name_Node); begin while Nkind (Next_Node) /= N_Defining_Program_Unit_Name loop Next_Node := Parent (Next_Node); end loop; if Nkind (Parent (Next_Node)) in N_Subprogram_Specification then Next_Node := Parent (Next_Node); end if; Next_Node := Corresponding_Spec (Parent (Next_Node)); while Nkind (Next_Node) /= N_Defining_Program_Unit_Name loop Next_Node := Parent (Next_Node); end loop; Next_Node := Parent (Next_Node); Next_Node := Defining_Unit_Name (Next_Node); -- Now Next_Node should point to the defining program unit name in the -- spec: Next_Node := Sinfo.Name (Next_Node); while Present (Next_Node) loop if Nkind (Next_Node) = N_Expanded_Name then Next_Node := Selector_Name (Next_Node); end if; if Name_Chars = Chars (Next_Node) then Result := Next_Node; exit; end if; Next_Node := Parent (Next_Node); if Nkind (Next_Node) = N_Expanded_Name then Next_Node := Prefix (Next_Node); else exit; end if; end loop; pragma Assert (Present (Result)); return Result; end Reset_To_Spec; --------------------- -- Rewritten_Image -- --------------------- function Rewritten_Image (Selector_Name : Node_Id) return Node_Id is Name_Chars : constant Name_Id := Chars (Selector_Name); Aggr_Node : Node_Id; Result_Node : Node_Id := Empty; Association_Node : Node_Id; Choice_Node : Node_Id; begin -- may be, we have to be more smart for aggregates in aggregates... Aggr_Node := Parent (Selector_Name); -- we are in N_Component_Association node, and its Parent points not -- to the original, but to the rewritten structure for aggregate Aggr_Node := Parent (Aggr_Node); -- we are in the rewritten node for the aggregate pragma Assert ( (Nkind (Aggr_Node) = N_Aggregate or else Nkind (Aggr_Node) = N_Extension_Aggregate) and then Is_Rewrite_Substitution (Aggr_Node)); -- and now - traversing the rewritten structure Association_Node := First_Non_Pragma (Component_Associations (Aggr_Node)); Associations : while Present (Association_Node) loop Choice_Node := First_Non_Pragma (Choices (Association_Node)); -- in the rewritten aggregate it is exactly one choice in any -- component association if Chars (Choice_Node) = Name_Chars then Result_Node := Choice_Node; exit Associations; end if; Association_Node := Next_Non_Pragma (Association_Node); end loop Associations; pragma Assert (Present (Result_Node)); return Result_Node; end Rewritten_Image; ------------------------ -- Search_Record_Comp -- ------------------------ function Search_Record_Comp (Selector_Name : Node_Id) return Entity_Id is Result : Entity_Id := Empty; Res_Chars : constant Name_Id := Chars (Selector_Name); Aggr_Type : Entity_Id; begin Aggr_Type := Parent (Selector_Name); while not (Nkind (Aggr_Type) = N_Extension_Aggregate or else Nkind (Aggr_Type) = N_Aggregate or else No (Aggr_Type)) loop Aggr_Type := Parent (Aggr_Type); end loop; if No (Aggr_Type) then -- This definitely means that something went wrong... pragma Assert (False); return Empty; end if; Aggr_Type := Etype (Aggr_Type); while Ekind (Aggr_Type) /= E_Record_Type loop if Ekind (Aggr_Type) = E_Private_Type or else Ekind (Aggr_Type) = E_Limited_Private_Type or else Ekind (Aggr_Type) = E_Record_Type_With_Private then Aggr_Type := Full_View (Aggr_Type); else Aggr_Type := Etype (Aggr_Type); end if; end loop; Result := First_Entity (Aggr_Type); while Chars (Result) /= Res_Chars loop Result := Next_Entity (Result); end loop; pragma Assert (Present (Result)); return Result; end Search_Record_Comp; ------------------- -- To_Upper_Case -- ------------------- function To_Upper_Case (S : Wide_String) return Wide_String is Result : Wide_String (S'Range); begin for J in Result'Range loop Result (J) := Ada.Wide_Characters.Unicode.To_Upper_Case (S (J)); end loop; return Result; end To_Upper_Case; end A4G.Expr_Sem;
-- SPDX-License-Identifier: MIT -- -- Copyright (c) 2008 - 2018 Gautier de Montmollin (maintainer) -- SWITZERLAND -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. with Ada.IO_Exceptions; package body DCF.Streams is function Open (File_Name : String) return Open_File is begin return Result : Open_File do Stream_IO.Open (Result.File, Stream_IO.File_Mode (In_File), File_Name); end return; end Open; function Create (File_Name : String) return Open_File is begin return Result : Open_File do Stream_IO.Create (Result.File, Stream_IO.File_Mode (Out_File), File_Name); end return; end Create; overriding procedure Finalize (Object : in out Open_File) is begin if not Object.Finalized then if Stream_IO.Is_Open (Object.File) then Stream_IO.Close (Object.File); end if; Object.Finalized := True; end if; end Finalize; ----------------------------------------------------------------------------- procedure Set_Name (S : in out Root_Zipstream_Type; Name : String; UTF_8 : Boolean := False) is begin S.Name := To_Unbounded_String (Name); S.UTF_8 := UTF_8; end Set_Name; function Get_Name (S : in Root_Zipstream_Type) return String is begin return To_String (S.Name); end Get_Name; function UTF_8_Encoding (S : in Root_Zipstream_Type) return Boolean is (S.UTF_8); procedure Set_Time (S : in out Root_Zipstream_Type; Modification_Time : Time) is begin S.Modification_Time := Modification_Time; end Set_Time; function Get_Time (S : in Root_Zipstream_Type) return Time is begin return S.Modification_Time; end Get_Time; function Convert (Date : in Dos_Time) return Time is begin return Time (Date); -- Currently a trivial conversion end Convert; function Convert (Date : in Time) return Dos_Time is begin return Dos_Time (Date); -- Currently a trivial conversion end Convert; ---------------------------------------------- -- File_Zipstream: stream based on a file -- ---------------------------------------------- function Open (File_Name : String) return File_Zipstream is begin return (Root_Stream_Type with File => Open (File_Name), Name => To_Unbounded_String (File_Name), others => <>); end Open; function Create (File_Name : String) return File_Zipstream is begin return (Root_Stream_Type with File => Create (File_Name), Name => To_Unbounded_String (File_Name), others => <>); end Create; overriding procedure Read (Stream : in out File_Zipstream; Item : out Stream_Element_Array; Last : out Stream_Element_Offset) is begin Ada.Streams.Stream_IO.Read (Stream.File.File, Item, Last); end Read; overriding procedure Write (Stream : in out File_Zipstream; Item : Stream_Element_Array) is begin Ada.Streams.Stream_IO.Write (Stream.File.File, Item); end Write; overriding procedure Set_Index (S : in out File_Zipstream; To : Zs_Index_Type) is begin Ada.Streams.Stream_IO.Set_Index (S.File.File, Ada.Streams.Stream_IO.Positive_Count (To)); end Set_Index; overriding function Size (S : in File_Zipstream) return Zs_Size_Type is begin return Zs_Size_Type (Ada.Streams.Stream_IO.Size (S.File.File)); end Size; overriding function Index (S : in File_Zipstream) return Zs_Index_Type is begin return Zs_Index_Type (Ada.Streams.Stream_IO.Index (S.File.File)); end Index; overriding function End_Of_Stream (S : in File_Zipstream) return Boolean is begin return Ada.Streams.Stream_IO.End_Of_File (S.File.File); end End_Of_Stream; -------------------------------------------------------------- -- Array_Zipstream: stream based on a Stream_Element_Array -- -------------------------------------------------------------- overriding procedure Read (Stream : in out Array_Zipstream; Item : out Stream_Element_Array; Last : out Stream_Element_Offset) is begin if Stream.EOF then -- No elements transferred: Last := Item'First - 1 (See RM 13.13.1 (8)) -- T'Read will raise End_Error (See RM 13.13.2 (37)) if Item'First > Stream_Element_Offset'First then Last := Item'First - 1; return; else -- RM 13.13.1 (11) requires Read to raise Constraint_Error -- if Item'First = Stream_Element_Offset'First raise Constraint_Error; end if; end if; if Stream.Elements'Last - Stream.Index >= Item'Length then -- Normal case: even after reading, the index will be in the range Last := Item'Last; Item := Stream.Elements (Stream.Index .. Stream.Index + Item'Length - 1); Stream.Index := Stream.Index + Item'Length; pragma Assert (Stream.Index <= Stream.Elements'Last); -- At least one element is left to be read, EOF not possible else -- Special case: we exhaust the buffer Last := Item'First + (Stream.Elements'Last - Stream.Index); Item (Item'First .. Last) := Stream.Elements (Stream.Index .. Stream.Elements'Last); Stream.EOF := True; -- If Last < Item'Last, the T'Read attribute raises End_Error -- because of the incomplete reading end if; end Read; overriding procedure Write (Stream : in out Array_Zipstream; Item : Stream_Element_Array) is begin if Stream.EOF then raise Ada.IO_Exceptions.End_Error; end if; if Stream.Elements'Last - Stream.Index >= Item'Length then Stream.Elements (Stream.Index .. Stream.Index + Item'Length - 1) := Item; Stream.Index := Stream.Index + Item'Length; pragma Assert (Stream.Index <= Stream.Elements'Last); -- At least one element is left to be written, EOF not possible elsif Stream.Elements'Last - Stream.Index + 1 = Item'Length then Stream.Elements (Stream.Index .. Stream.Elements'Last) := Item; Stream.EOF := True; else -- RM 13.13.1 (9) requires the item to be appended to the stream, -- but this might fail because the Stream_Element_Array is bounded. -- -- Don't write if writing would be incomplete raise Ada.IO_Exceptions.End_Error; end if; end Write; overriding procedure Set_Index (Stream : in out Array_Zipstream; To : Zs_Index_Type) is Index : constant Stream_Element_Offset := Stream_Element_Offset (To); begin if (if Stream.Elements'Length > 0 then Index not in Stream.Elements'Range else Index /= Stream.Elements'First) then raise Constraint_Error; end if; Stream.Index := Index; Stream.EOF := False; end Set_Index; end DCF.Streams;
pragma License (Unrestricted); package Ada.Text_IO.Editing is type Picture is private; function Valid ( Pic_String : String; Blank_When_Zero : Boolean := False) return Boolean; function To_Picture ( Pic_String : String; Blank_When_Zero : Boolean := False) return Picture; function Pic_String (Pic : Picture) return String; function Blank_When_Zero (Pic : Picture) return Boolean; pragma Inline (Blank_When_Zero); Max_Picture_Length : constant := 30; -- implementation_defined Picture_Error : exception; Default_Currency : constant String := "$"; Default_Fill : constant Character := '*'; Default_Separator : constant Character := ','; Default_Radix_Mark : constant Character := '.'; generic type Num is delta <> digits <>; Default_Currency : String := Editing.Default_Currency; Default_Fill : Character := Editing.Default_Fill; Default_Separator : Character := Editing.Default_Separator; Default_Radix_Mark : Character := Editing.Default_Radix_Mark; package Decimal_Output is -- extended function Overloaded_Length (Pic : Picture; Currency : String) return Natural; function Overloaded_Length (Pic : Picture; Currency : Wide_String) return Natural; function Overloaded_Length (Pic : Picture; Currency : Wide_Wide_String) return Natural; function Length (Pic : Picture; Currency : String := Default_Currency) return Natural renames Overloaded_Length; -- extended function Overloaded_Valid ( Item : Num; Pic : Picture; Currency : String) return Boolean; function Overloaded_Valid ( Item : Num; Pic : Picture; Currency : Wide_String) return Boolean; function Overloaded_Valid ( Item : Num; Pic : Picture; Currency : Wide_Wide_String) return Boolean; function Valid ( Item : Num; Pic : Picture; Currency : String := Default_Currency) return Boolean renames Overloaded_Valid; -- extended function Overloaded_Image ( Item : Num; Pic : Picture; Currency : String; Fill : Character; Separator : Character; Radix_Mark : Character) return String; function Overloaded_Image ( Item : Num; Pic : Picture; Currency : Wide_String; Fill : Wide_Character; Separator : Wide_Character; Radix_Mark : Wide_Character) return Wide_String; function Overloaded_Image ( Item : Num; Pic : Picture; Currency : Wide_Wide_String; Fill : Wide_Wide_Character; Separator : Wide_Wide_Character; Radix_Mark : Wide_Wide_Character) return Wide_Wide_String; function Image ( Item : Num; Pic : Picture; Currency : String := Default_Currency; Fill : Character := Default_Fill; Separator : Character := Default_Separator; Radix_Mark : Character := Default_Radix_Mark) return String renames Overloaded_Image; -- extended procedure Overloaded_Put ( File : File_Type; -- Output_File_Type Item : Num; Pic : Picture; Currency : String; Fill : Character; Separator : Character; Radix_Mark : Character); procedure Overloaded_Put ( File : File_Type; -- Output_File_Type Item : Num; Pic : Picture; Currency : Wide_String; Fill : Wide_Character; Separator : Wide_Character; Radix_Mark : Wide_Character); procedure Overloaded_Put ( File : File_Type; -- Output_File_Type Item : Num; Pic : Picture; Currency : Wide_Wide_String; Fill : Wide_Wide_Character; Separator : Wide_Wide_Character; Radix_Mark : Wide_Wide_Character); procedure Put ( File : File_Type; -- Output_File_Type Item : Num; Pic : Picture; Currency : String := Default_Currency; Fill : Character := Default_Fill; Separator : Character := Default_Separator; Radix_Mark : Character := Default_Radix_Mark) renames Overloaded_Put; -- extended procedure Overloaded_Put ( Item : Num; Pic : Picture; Currency : String; Fill : Character; Separator : Character; Radix_Mark : Character); procedure Overloaded_Put ( Item : Num; Pic : Picture; Currency : Wide_String; Fill : Wide_Character; Separator : Wide_Character; Radix_Mark : Wide_Character); procedure Overloaded_Put ( Item : Num; Pic : Picture; Currency : Wide_Wide_String; Fill : Wide_Wide_Character; Separator : Wide_Wide_Character; Radix_Mark : Wide_Wide_Character); procedure Put ( Item : Num; Pic : Picture; Currency : String := Default_Currency; Fill : Character := Default_Fill; Separator : Character := Default_Separator; Radix_Mark : Character := Default_Radix_Mark) renames Overloaded_Put; -- extended procedure Overloaded_Put ( To : out String; Item : Num; Pic : Picture; Currency : String; Fill : Character; Separator : Character; Radix_Mark : Character); procedure Overloaded_Put ( To : out Wide_String; Item : Num; Pic : Picture; Currency : Wide_String; Fill : Wide_Character; Separator : Wide_Character; Radix_Mark : Wide_Character); procedure Overloaded_Put ( To : out Wide_Wide_String; Item : Num; Pic : Picture; Currency : Wide_Wide_String; Fill : Wide_Wide_Character; Separator : Wide_Wide_Character; Radix_Mark : Wide_Wide_Character); procedure Put ( To : out String; Item : Num; Pic : Picture; Currency : String := Default_Currency; Fill : Character := Default_Fill; Separator : Character := Default_Separator; Radix_Mark : Character := Default_Radix_Mark) renames Overloaded_Put; end Decimal_Output; private type Dollar_Position is (None, Previous); pragma Discard_Names (Dollar_Position); type Picture is record Expanded : String (1 .. Max_Picture_Length); Length : Natural; Has_V : Boolean; -- zero width Has_Dollar : Dollar_Position; -- replaced to Currency Blank_When_Zero : Boolean; Real_Blank_When_Zero : Boolean; First_Sign_Position : Natural; Radix_Position : Positive; Aft : Natural; end record; end Ada.Text_IO.Editing;
package Problem_56 is -- A googol (10^100) is a massive number: one followed by one-hundred zeros; -- 100^100 is almost unimaginably large: one followed by two-hundred zeros. -- Despite their size, the sum of the digits in each number is only 1. -- -- Considering natural numbers of the form, a^b, where a, b < 100, what is the -- maximum digital sum? procedure Solve; end Problem_56;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- Purpose: -- Name : CRC-16 [CCITT] -- Width : 16 -- Poly : 0x1021 x^16 + x^12 + x^5 + 1 -- Init : 0xFFFF -- RefIn : False -- RefOut: False -- XorOut: 0x0000 -- Check : 0x29B1 ("123456789") -- MaxLen: 4095 byte (32767 bit) with Ada.Streams; with Interfaces; package Gela.Hash.CRC.b16 is type CRC16 is new Interfaces.Unsigned_16; type Hasher is private; Initial_Hasher : constant Hasher; procedure Update (This : in out Hasher; Value : in String); procedure Wide_Update (This : in out Hasher; Value : in Wide_String); procedure Wide_Wide_Update (This : in out Hasher; Value : in Wide_Wide_String); procedure Update (This : in out Hasher; Value : in Ada.Streams.Stream_Element_Array); function Result (This : in Hasher) return CRC16; function Calculate (Value : in String) return CRC16; function Wide_Calculate (Value : in Wide_String) return CRC16; function Wide_Wide_Calculate (Value : in Wide_Wide_String) return CRC16; function Calculate (Value : in Ada.Streams.Stream_Element_Array) return CRC16; function To_Hash (T : in CRC16) return Hash_Type; pragma Inline (To_Hash); function Calculate (Value : in String) return Hash_Type; pragma Inline (Calculate); function Wide_Calculate (Value : in Wide_String) return Hash_Type; pragma Inline (Calculate); function Wide_Wide_Calculate (Value : in Wide_Wide_String) return Hash_Type; pragma Inline (Calculate); function Calculate (Value : in Ada.Streams.Stream_Element_Array) return Hash_Type; pragma Inline (Calculate); private type Hasher is record Length : Integer := 0; Cm_Reg : CRC16 := 16#FFFF#; end record; Initial_Hasher : constant Hasher := (Length => 0, Cm_Reg => 16#FFFF#); end Gela.Hash.CRC.b16; ------------------------------------------------------------------------------ -- Copyright (c) 2006, Andry Ogorodnik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- * this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- * notice, this list of conditions and the following disclaimer in the -- * documentation and/or other materials provided with the distribution. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
with STM32GD.USART.Peripheral; with Drivers.Text_IO; package STM32GD.Board is pragma Preelaborate; package USART is new STM32GD.USART.Peripheral (Filename => "Test"); package Text_IO is new Drivers.Text_IO (USART => STM32GD.Board.USART); procedure Init; end STM32GD.Board;
----------------------------------------------------------------------- -- util-commands-consoles-text -- Text console interface -- Copyright (C) 2014, 2015, 2017, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; package body Util.Commands.Consoles.Text is procedure Set_Col (Console : in out Console_Type; Col : in Positive) is begin while Console.Cur_Col < Col loop Ada.Text_IO.Put (" "); Console.Cur_Col := Console.Cur_Col + 1; end loop; end Set_Col; procedure Put (Console : in out Console_Type; Content : in String) is use type Interfaces.Unsigned_8; begin Ada.Text_IO.Put (Content); for C of Content loop declare Val : constant Interfaces.Unsigned_8 := Character'Pos (C); begin -- Take into account only the first byte of the UTF-8 sequence. if Val < 16#80# or Val >= 16#C0# then Console.Cur_Col := Console.Cur_Col + 1; end if; end; end loop; end Put; -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is begin Ada.Text_IO.Put_Line (Message); Console.Cur_Col := 1; end Error; -- ------------------------------ -- Report a notice message. -- ------------------------------ overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is pragma Unreferenced (Kind); begin Ada.Text_IO.Put_Line (Message); Console.Cur_Col := 1; end Notice; -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT) is Pos : constant Positive := Console.Cols (Field); Size : constant Natural := Console.Sizes (Field); Start : Natural := Value'First; Last : constant Natural := Value'Last; Pad : Natural := 0; begin case Justify is when J_LEFT => if Value'Length >= Size and Size > 0 then Start := Last - Size + 1 + 1; end if; when J_RIGHT => if Value'Length < Size then Pad := Size - Value'Length - 1; else Start := Last - Size + 1; end if; when J_CENTER => if Value'Length < Size then Pad := (Size - Value'Length) / 2; else Start := Last - Size + 1; end if; when J_RIGHT_NO_FILL => if Value'Length >= Size then Start := Last - Size + 1; end if; end case; if Pad > 0 then Console.Set_Col (Pos + Pad); elsif Pos > 1 then Console.Set_Col (Pos); end if; Console.Put (Value (Start .. Last)); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is Pos : constant Positive := Console.Cols (Field); begin if Pos > 1 then Console.Set_Col (Pos); end if; Console.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; Console.Cur_Col := 1; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; Console.Cur_Col := 1; end End_Row; end Util.Commands.Consoles.Text;
------------------------------------------------------------------------------ -- -- -- Copyright (c) 2014-2017 Vitalij Bondarenko <vibondare@gmail.com> -- -- -- ------------------------------------------------------------------------------ -- -- -- The MIT License (MIT) -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining a -- -- copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, sublicense, and/or sell copies of the Software, and to -- -- permit persons to whom the Software is furnished to do so, subject to -- -- the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be included -- -- in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- ------------------------------------------------------------------------------ -- The functions to access the information for the locale. with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings; package L10n.Localeinfo is -- The record whose components contain information about how numeric and -- monetary values should be formatted in the current locale. type Lconv_Record is record -- Numeric (non-monetary) information. --------------------------------------- Decimal_Point : Unbounded_String; -- The radix character used to format non-monetary quantities. Thousands_Sep : Unbounded_String; -- The character used to separate groups of digits before the -- decimal-point character in formatted non-monetary quantities. Grouping : Unbounded_String; -- A string whose elements taken as one-byte integer values indicate the -- size of each group of digits in formatted non-monetary quantities. -- Use either Thousands_Sep to separate the digit groups. -- Each element is the number of digits in each group; -- elements with higher indices are farther left. -- An element with value Interfaces.C.UCHAR_MAX means that no further -- grouping is done. -- An element with value 0 means that the previous element is used -- for all groups farther left. -- Monetary information. ------------------------- Int_Curr_Symbol : Unbounded_String; -- The international currency symbol applicable to the current locale. -- The first three characters contain the alphabetic international -- currency symbol in accordance with those specified in the -- ISO 4217:1995 standard. The fourth character (immediately preceding -- the null byte) is the character used to separate the international -- currency symbol from the monetary quantity. Currency_Symbol : Unbounded_String; -- The local currency symbol applicable to the current locale. Mon_Decimal_Point : Unbounded_String; -- The radix character used to format monetary quantities. Mon_Thousands_Sep : Unbounded_String; -- The separator for groups of digits before the decimal-point in -- formatted monetary quantities. Mon_Grouping : Unbounded_String; -- A string whose elements taken as one-byte integer values indicate the -- size of each group of digits in formatted monetary quantities. -- Use either Mon_Thousands_Sep to separate the digit groups. -- Each element is the number of digits in each group; -- elements with higher indices are farther left. -- An element with value Interfaces.C.UCHAR_MAX means that no further -- grouping is done. -- An element with value 0 means that the previous element is used -- for all groups farther left. Positive_Sign : Unbounded_String; -- The string used to indicate a non-negative valued formatted monetary -- quantity. Negative_Sign : Unbounded_String; -- The string used to indicate a negative valued formatted monetary -- quantity. Int_Frac_Digits : Natural; -- The number of fractional digits (those after the decimal-point) to be -- displayed in an internationally formatted monetary quantity. Frac_Digits : Natural; -- The number of fractional digits (those after the decimal-point) to be -- displayed in a formatted monetary quantity. P_Cs_Precedes : Natural; -- Set to 1 if the Currency_Symbol precedes the value for a non-negative -- formatted monetary quantity. -- Set to 0 if the symbol succeeds the value. P_Sep_By_Space : Natural; -- Set to a value indicating the separation of the Currency_Symbol, the -- sign string, and the value for a non-negative formatted monetary -- quantity. -- 0 No space separates the currency symbol and value. -- 1 If the currency symbol and sign string are adjacent, a space -- separates them from the value; otherwise, a space separates the -- currency symbol from the value. -- 2 If the currency symbol and sign string are adjacent, a space -- separates them; otherwise, a space separates the sign string from -- the value. N_Cs_Precedes : Natural; -- Set to 1 if the Currency_Symbol precedes the value for a negative -- formatted monetary quantity. Set to 0 if the symbol succeeds the -- value. N_Sep_By_Space : Natural; -- Set to a value indicating the separation of the Currency_Symbol, the -- sign string, and the value for a negative formatted monetary quantity. -- 0 No space separates the currency symbol and value. -- 1 If the currency symbol and sign string are adjacent, a space -- separates them from the value; otherwise, a space separates the -- currency symbol from the value. -- 2 If the currency symbol and sign string are adjacent, a space -- separates them; otherwise, a space separates the sign string from -- the value. P_Sign_Posn : Natural; -- Set to a value indicating the positioning of the Positive_Sign for a -- non-negative formatted monetary quantity. -- 0 Parentheses surround the quantity and Currency_Symbol. -- 1 The sign string precedes the quantity and Currency_Symbol. -- 2 The sign string follows the quantity and Currency_Symbol. -- 3 The sign string immediately precedes the Currency_Symbol. -- 4 The sign string immediately follows the Currency_Symbol. N_Sign_Posn : Natural; -- Set to a value indicating the positioning of the negative_sign for a -- negative formatted monetary quantity. -- 0 Parentheses surround the quantity and Currency_Symbol. -- 1 The sign string precedes the quantity and Currency_Symbol. -- 2 The sign string follows the quantity and Currency_Symbol. -- 3 The sign string immediately precedes the Currency_Symbol. -- 4 The sign string immediately follows the Currency_Symbol. -- Int_P_Cs_Precedes : Natural; -- Set to 1 or 0 if the Int_Curr_Symbol respectively precedes or -- succeeds the value for a non-negative internationally formatted -- monetary quantity. Int_P_Sep_By_Space : Natural; -- Set to a value indicating the separation of the Int_Curr_Symbol, the -- sign string, and the value for a negative internationally formatted -- monetary quantity. -- 0 No space separates the currency symbol and value. -- 1 If the currency symbol and sign string are adjacent, a space -- separates them from the value; otherwise, a space separates the -- currency symbol from the value. -- 2 If the currency symbol and sign string are adjacent, a space -- separates them; otherwise, a space separates the sign string from -- the value. Int_N_Cs_Precedes : Natural; -- Set to 1 or 0 if the Int_Curr_Symbol respectively precedes or -- succeeds the value for a negative internationally formatted monetary -- quantity. Int_N_Sep_By_Space : Natural; -- Set to a value indicating the separation of the Int_Curr_Symbol, the -- sign string, and the value for a negative internationally formatted -- monetary quantity. -- 0 No space separates the currency symbol and value. -- 1 If the currency symbol and sign string are adjacent, a space -- separates them from the value; otherwise, a space separates the -- currency symbol from the value. -- 2 If the currency symbol and sign string are adjacent, a space -- separates them; otherwise, a space separates the sign string from -- the value. Int_P_Sign_Posn : Natural; -- Set to a value indicating the positioning of the Positive_Sign for a -- non-negative internationally formatted monetary quantity. -- 0 Parentheses surround the quantity and Int_Curr_Symbol. -- 1 The sign string precedes the quantity and Int_Curr_Symbol. -- 2 The sign string follows the quantity and Int_Curr_Symbol. -- 3 The sign string immediately precedes the Int_Curr_Symbol. -- 4 The sign string immediately follows the Int_Curr_Symbol. Int_N_Sign_Posn : Natural; -- Set to a value indicating the positioning of the Negative_Sign for a -- negative internationally formatted monetary quantity. -- 0 Parentheses surround the quantity and Int_Curr_Symbol. -- 1 The sign string precedes the quantity and Int_Curr_Symbol. -- 2 The sign string follows the quantity and Int_Curr_Symbol. -- 3 The sign string immediately precedes the Int_Curr_Symbol. -- 4 The sign string immediately follows the Int_Curr_Symbol. end record; type Lconv_Access is access all Lconv_Record; function Localeconv return Lconv_Access; -- Returns a record whose components contain information about how numeric -- and monetary values should be formatted in the current locale. -- Localeinfo in C-types -- -- The record whose components contain information about how numeric and -- monetary values should be formatted in the current locale. type C_Lconv_Record is record Decimal_Point : chars_ptr; Thousands_Sep : chars_ptr; Grouping : chars_ptr; Int_Curr_Symbol : chars_ptr; Currency_Symbol : chars_ptr; Mon_Decimal_Point : chars_ptr; Mon_Thousands_Sep : chars_ptr; Mon_Grouping : chars_ptr; Positive_Sign : chars_ptr; Negative_Sign : chars_ptr; Int_Frac_Digits : unsigned_char; Frac_Digits : unsigned_char; P_Cs_Precedes : unsigned_char; P_Sep_By_Space : unsigned_char; N_Cs_Precedes : unsigned_char; N_Sep_By_Space : unsigned_char; P_Sign_Posn : unsigned_char; N_Sign_Posn : unsigned_char; Int_P_Cs_Precedes : unsigned_char; Int_P_Sep_By_Space : unsigned_char; Int_N_Cs_Precedes : unsigned_char; Int_N_Sep_By_Space : unsigned_char; Int_P_Sign_Posn : unsigned_char; Int_N_Sign_Posn : unsigned_char; end record; pragma Convention (C, C_Lconv_Record); type C_Lconv_Access is access all C_Lconv_Record; function C_Localeconv return C_Lconv_Access; pragma Import (C, C_Localeconv, "localeconv"); end L10n.Localeinfo;
package Incomplete3 is type Output_T; type Output_T is abstract tagged private; type Tracer_T is tagged private; function Get_Tracer (This : access Output_T'Class) return Tracer_T'class; function Get_Output (This : in Tracer_T) return access Output_T'Class; private type Output_T is abstract tagged record B : Boolean := True; end record; type Tracer_T is tagged record Output : access Output_T'Class := null; end record; end Incomplete3;
with OpenGL.Thin; package OpenGL.Texture is type Index_t is new Thin.Unsigned_Integer_t; type Index_Array_t is array (Natural range <>) of aliased Index_t; type Border_Width_t is range 0 .. 1; type Internal_Format_t is (Alpha, Alpha_4, Alpha_8, Alpha_12, Alpha_16, Compressed_Alpha, Compressed_Luminance, Compressed_Luminance_Alpha, Compressed_Intensity, Compressed_RGB, Compressed_RGBA, Luminance, Luminance_4, Luminance_8, Luminance_12, Luminance_16, Luminance_Alpha, Luminance_4_Alpha_4, Luminance_6_Alpha_2, Luminance_8_Alpha_8, Luminance_12_Alpha_4, Luminance_12_Alpha_12, Luminance_16_Alpha_16, Intensity, Intensity_4, Intensity_8, Intensity_12, Intensity_16, R3_G3_B2, RGB, RGB_4, RGB_5, RGB_8, RGB_10, RGB_12, RGB_16, RGBA, RGBA_2, RGBA_4, RGB5_A1, RGBA_8, RGB10_A2, RGBA_12, RGBA_16, SLuminance, SLuminance_8, SLuminance_Alpha, SLuminance_8_Alpha_8, SRGB, SRGB_8, SRGB_Alpha, SRGB_8_Alpha_8); type Format_t is (Color_Index, Red, Green, Blue, Alpha, RGB, BGR, RGBA, BGRA, Luminance, Luminance_Alpha); type Data_Type_t is (Unsigned_Byte, Byte, Bitmap, Unsigned_Short, Short, Unsigned_Integer, Integer, Float, Unsigned_Byte_3_3_2, Unsigned_Byte_2_3_3_Rev, Unsigned_Short_5_6_5, Unsigned_Short_5_6_5_Rev, Unsigned_Short_4_4_4_4, Unsigned_Short_4_4_4_4_Rev, Unsigned_Short_5_5_5_1, Unsigned_Short_1_5_5_5_Rev, Unsigned_Integer_8_8_8_8, Unsigned_Integer_8_8_8_8_Rev, Unsigned_Integer_10_10_10_2, Unsigned_Integer_2_10_10_10_Rev); type Storage_Parameter_t is (Pack_Swap_Bytes, Pack_LSB_First, Pack_Row_Length, Pack_Image_Height, Pack_Skip_Pixels, Pack_Skip_Rows, Pack_Skip_Images, Pack_Alignment, Unpack_Swap_Bytes, Unpack_LSB_First, Unpack_Row_Length, Unpack_Image_Height, Unpack_Skip_Pixels, Unpack_Skip_Rows, Unpack_Skip_Images, Unpack_Alignment); -- -- Pixel_Store -- -- proc_map : glPixelStorei procedure Pixel_Store (Parameter : in Storage_Parameter_t; Value : in Standard.Integer); -- proc_map : glPixelStoref procedure Pixel_Store (Parameter : in Storage_Parameter_t; Value : in Standard.Float); -- -- Parameter -- type Target_t is (Texture_1D, Texture_2D, Texture_3D, Texture_Cube_Map, Texture_Rectangle_ARB); type Texture_Parameter_t is (Texture_Min_Filter, Texture_Mag_Filter, Texture_Min_LOD, Texture_Max_LOD, Texture_Base_Level, Texture_Max_Level, Texture_Wrap_S, Texture_Wrap_T, Texture_Wrap_R, Texture_Priority, Texture_Compare_Mode, Texture_Compare_Func, Depth_Texture_Mode, Generate_Mipmap); Linear : constant := Thin.GL_LINEAR; Linear_Mipmap_Linear : constant := Thin.GL_LINEAR_MIPMAP_LINEAR; Linear_Mipmap_Nearest : constant := Thin.GL_LINEAR_MIPMAP_NEAREST; Nearest : constant := Thin.GL_NEAREST; Nearest_Mipmap_Linear : constant := Thin.GL_NEAREST_MIPMAP_LINEAR; Nearest_Mipmap_Nearest : constant := Thin.GL_NEAREST_MIPMAP_NEAREST; Clamp : constant := Thin.GL_CLAMP; Clamp_To_Border : constant := Thin.GL_CLAMP_TO_BORDER; Clamp_To_Edge : constant := Thin.GL_CLAMP_TO_EDGE; Mirrored_Repeat : constant := Thin.GL_MIRRORED_REPEAT; Repeat : constant := Thin.GL_REPEAT; Always : constant := Thin.GL_ALWAYS; Equal : constant := Thin.GL_EQUAL; Greater_Than : constant := Thin.GL_GREATER; Greater_Than_Or_Equal : constant := Thin.GL_GEQUAL; Less_Than : constant := Thin.GL_LESS; Less_Than_Or_Equal : constant := Thin.GL_LEQUAL; Never : constant := Thin.GL_NEVER; Not_Equal : constant := Thin.GL_NOTEQUAL; -- proc_map : glTexParameteri procedure Parameter (Target : in Target_t; Parameter : in Texture_Parameter_t; Value : in Standard.Integer); -- proc_map : glTexParameterf procedure Parameter (Target : in Target_t; Parameter : in Texture_Parameter_t; Value : in Standard.Float); -- -- Environment -- type Environment_Target_t is (Texture_Environment, Texture_Filter_Control, Point_Sprite); type Environment_Parameter_t is (Texture_Env_Mode, Texture_LOD_Bias, Combine_RGB, Combine_Alpha, Source0_RGB, Source1_RGB, Source2_RGB, Source0_Alpha, Source1_Alpha, Source2_Alpha, Operand0_RGB, Operand1_RGB, Operand2_RGB, Operand0_Alpha, Operand1_Alpha, Operand2_Alpha, RGB_Scale, Alpha_Scale, Coord_Replace); Add : constant := Thin.GL_ADD; Add_Signed : constant := Thin.GL_ADD_SIGNED; Interpolate : constant := Thin.GL_INTERPOLATE; Modulate : constant := Thin.GL_MODULATE; Decal : constant := Thin.GL_DECAL; Blend : constant := Thin.GL_BLEND; Replace : constant := Thin.GL_REPLACE; Subtract : constant := Thin.GL_SUBTRACT; Combine : constant := Thin.GL_COMBINE; Texture : constant := Thin.GL_TEXTURE; GL_Constant : constant := Thin.GL_CONSTANT; Primary_Color : constant := Thin.GL_PRIMARY_COLOR; Previous : constant := Thin.GL_PREVIOUS; Source_Color : constant := Thin.GL_SRC_COLOR; One_Minus_Source_Color : constant := Thin.GL_ONE_MINUS_SRC_COLOR; Source_Alpha : constant := Thin.GL_SRC_ALPHA; One_Minus_Source_Alpha : constant := Thin.GL_ONE_MINUS_SRC_ALPHA; -- proc_map : glTexEnvi procedure Environment (Target : in Environment_Target_t; Parameter : in Environment_Parameter_t; Value : in Standard.Integer); -- proc_map : glTexEnvf procedure Environment (Target : in Environment_Target_t; Parameter : in Environment_Parameter_t; Value : in Standard.Float); -- -- Generate -- -- proc_map : glGenTextures procedure Generate (Textures : in out Index_Array_t); -- -- Image3D -- type Target_3D_t is (Texture_3D, Proxy_Texture_3D, Texture_Rectangle_ARB); generic type Data_Element_t is private; type Data_Index_t is range <>; type Data_Array_t is array (Data_Index_t range <>) of aliased Data_Element_t; -- proc_map : glTexImage3D procedure Image_3D (Target : in Target_3D_t; Level : in Natural; Internal_Format : in Internal_Format_t; Width : in Positive; Height : in Positive; Depth : in Positive; Border : in Border_Width_t; Format : in Format_t; Data : in Data_Array_t; Data_Type : in Data_Type_t); -- -- Image2D -- type Target_2D_t is (Texture_2D, Proxy_Texture_2D, Texture_Cube_Map_Positive_X, Texture_Cube_Map_Negative_X, Texture_Cube_Map_Positive_Y, Texture_Cube_Map_Negative_Y, Texture_Cube_Map_Positive_Z, Texture_Cube_Map_Negative_Z, Proxy_Texture_Cube_Map, Texture_Rectangle_ARB); generic type Data_Element_t is private; type Data_Index_t is range <>; type Data_Array_t is array (Data_Index_t range <>) of aliased Data_Element_t; -- proc_map : glTexImage2D procedure Image_2D (Target : in Target_2D_t; Level : in Natural; Internal_Format : in Internal_Format_t; Width : in Positive; Height : in Positive; Border : in Border_Width_t; Format : in Format_t; Data : in Data_Array_t; Data_Type : in Data_Type_t); -- -- Image1D -- type Target_1D_t is (Texture_1D, Proxy_Texture_1D, Texture_Rectangle_ARB); generic type Data_Element_t is private; type Data_Index_t is range <>; type Data_Array_t is array (Data_Index_t range <>) of aliased Data_Element_t; -- proc_map : glTexImage1D procedure Image_1D (Target : in Target_1D_t; Level : in Natural; Internal_Format : in Internal_Format_t; Width : in Positive; Border : in Border_Width_t; Format : in Format_t; Data : in Data_Array_t; Data_Type : in Data_Type_t); -- -- Bind -- -- proc_map : glBindTexture procedure Bind (Target : in Target_t; Texture : in Index_t); -- -- Blend_Function -- type Blend_Factor_t is (Blend_Constant_Alpha, Blend_Constant_Color, Blend_One, Blend_One_Minus_Constant_Alpha, Blend_One_Minus_Constant_Color, Blend_One_Minus_Source_Alpha, Blend_One_Minus_Source_Color, Blend_One_Minus_Target_Alpha, Blend_One_Minus_Target_Color, Blend_Source_Alpha, Blend_Source_Alpha_Saturate, Blend_Source_Color, Blend_Target_Alpha, Blend_Target_Color, Blend_Zero); -- proc_map : glBlendFunc procedure Blend_Function (Source_Factor : in Blend_Factor_t; Target_Factor : in Blend_Factor_t); end OpenGL.Texture;
pragma Style_Checks (Off); -- This spec has been automatically generated from STM32G474xx.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package STM32_SVD.CRS is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CR_TRIM_Field is HAL.UInt7; -- CRS control register type CR_Register is record -- SYNC event OK interrupt enable SYNCOKIE : Boolean := False; -- SYNC warning interrupt enable SYNCWARNIE : Boolean := False; -- Synchronization or trimming error interrupt enable ERRIE : Boolean := False; -- Expected SYNC interrupt enable ESYNCIE : Boolean := False; -- unspecified Reserved_4_4 : HAL.Bit := 16#0#; -- Frequency error counter enable This bit enables the oscillator clock -- for the frequency error counter. When this bit is set, the CRS_CFGR -- register is write-protected and cannot be modified. CEN : Boolean := False; -- Automatic trimming enable This bit enables the automatic hardware -- adjustment of TRIM bits according to the measured frequency error -- between two SYNC events. If this bit is set, the TRIM bits are -- read-only. The TRIM value can be adjusted by hardware by one or two -- steps at a time, depending on the measured frequency error value. -- Refer to Section7.3.4: Frequency error evaluation and automatic -- trimming for more details. AUTOTRIMEN : Boolean := False; -- Generate software SYNC event This bit is set by software in order to -- generate a software SYNC event. It is automatically cleared by -- hardware. SWSYNC : Boolean := False; -- HSI48 oscillator smooth trimming These bits provide a -- user-programmable trimming value to the HSI48 oscillator. They can be -- programmed to adjust to variations in voltage and temperature that -- influence the frequency of the HSI48. The default value is 32, which -- corresponds to the middle of the trimming interval. The trimming step -- is around 67 kHz between two consecutive TRIM steps. A higher TRIM -- value corresponds to a higher output frequency. When the AUTOTRIMEN -- bit is set, this field is controlled by hardware and is read-only. TRIM : CR_TRIM_Field := 16#40#; -- unspecified Reserved_15_31 : HAL.UInt17 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record SYNCOKIE at 0 range 0 .. 0; SYNCWARNIE at 0 range 1 .. 1; ERRIE at 0 range 2 .. 2; ESYNCIE at 0 range 3 .. 3; Reserved_4_4 at 0 range 4 .. 4; CEN at 0 range 5 .. 5; AUTOTRIMEN at 0 range 6 .. 6; SWSYNC at 0 range 7 .. 7; TRIM at 0 range 8 .. 14; Reserved_15_31 at 0 range 15 .. 31; end record; subtype CFGR_RELOAD_Field is HAL.UInt16; subtype CFGR_FELIM_Field is HAL.UInt8; subtype CFGR_SYNCDIV_Field is HAL.UInt3; subtype CFGR_SYNCSRC_Field is HAL.UInt2; -- This register can be written only when the frequency error counter is -- disabled (CEN bit is cleared in CRS_CR). When the counter is enabled, -- this register is write-protected. type CFGR_Register is record -- Counter reload value RELOAD is the value to be loaded in the -- frequency error counter with each SYNC event. Refer to Section7.3.3: -- Frequency error measurement for more details about counter behavior. RELOAD : CFGR_RELOAD_Field := 16#BB7F#; -- Frequency error limit FELIM contains the value to be used to evaluate -- the captured frequency error value latched in the FECAP[15:0] bits of -- the CRS_ISR register. Refer to Section7.3.4: Frequency error -- evaluation and automatic trimming for more details about FECAP -- evaluation. FELIM : CFGR_FELIM_Field := 16#22#; -- SYNC divider These bits are set and cleared by software to control -- the division factor of the SYNC signal. SYNCDIV : CFGR_SYNCDIV_Field := 16#0#; -- unspecified Reserved_27_27 : HAL.Bit := 16#0#; -- SYNC signal source selection These bits are set and cleared by -- software to select the SYNC signal source. Note: When using USB LPM -- (Link Power Management) and the device is in Sleep mode, the periodic -- USB SOF will not be generated by the host. No SYNC signal will -- therefore be provided to the CRS to calibrate the HSI48 on the run. -- To guarantee the required clock precision after waking up from Sleep -- mode, the LSE or reference clock on the GPIOs should be used as SYNC -- signal. SYNCSRC : CFGR_SYNCSRC_Field := 16#2#; -- unspecified Reserved_30_30 : HAL.Bit := 16#0#; -- SYNC polarity selection This bit is set and cleared by software to -- select the input polarity for the SYNC signal source. SYNCPOL : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CFGR_Register use record RELOAD at 0 range 0 .. 15; FELIM at 0 range 16 .. 23; SYNCDIV at 0 range 24 .. 26; Reserved_27_27 at 0 range 27 .. 27; SYNCSRC at 0 range 28 .. 29; Reserved_30_30 at 0 range 30 .. 30; SYNCPOL at 0 range 31 .. 31; end record; subtype ISR_FECAP_Field is HAL.UInt16; -- CRS interrupt and status register type ISR_Register is record -- Read-only. SYNC event OK flag This flag is set by hardware when the -- measured frequency error is smaller than FELIM * 3. This means that -- either no adjustment of the TRIM value is needed or that an -- adjustment by one trimming step is enough to compensate the frequency -- error. An interrupt is generated if the SYNCOKIE bit is set in the -- CRS_CR register. It is cleared by software by setting the SYNCOKC bit -- in the CRS_ICR register. SYNCOKF : Boolean; -- Read-only. SYNC warning flag This flag is set by hardware when the -- measured frequency error is greater than or equal to FELIM * 3, but -- smaller than FELIM * 128. This means that to compensate the frequency -- error, the TRIM value must be adjusted by two steps or more. An -- interrupt is generated if the SYNCWARNIE bit is set in the CRS_CR -- register. It is cleared by software by setting the SYNCWARNC bit in -- the CRS_ICR register. SYNCWARNF : Boolean; -- Read-only. Error flag This flag is set by hardware in case of any -- synchronization or trimming error. It is the logical OR of the -- TRIMOVF, SYNCMISS and SYNCERR bits. An interrupt is generated if the -- ERRIE bit is set in the CRS_CR register. It is cleared by software in -- reaction to setting the ERRC bit in the CRS_ICR register, which -- clears the TRIMOVF, SYNCMISS and SYNCERR bits. ERRF : Boolean; -- Read-only. Expected SYNC flag This flag is set by hardware when the -- frequency error counter reached a zero value. An interrupt is -- generated if the ESYNCIE bit is set in the CRS_CR register. It is -- cleared by software by setting the ESYNCC bit in the CRS_ICR -- register. ESYNCF : Boolean; -- unspecified Reserved_4_7 : HAL.UInt4; -- Read-only. SYNC error This flag is set by hardware when the SYNC -- pulse arrives before the ESYNC event and the measured frequency error -- is greater than or equal to FELIM * 128. This means that the -- frequency error is too big (internal frequency too low) to be -- compensated by adjusting the TRIM value, and that some other action -- should be taken. An interrupt is generated if the ERRIE bit is set in -- the CRS_CR register. It is cleared by software by setting the ERRC -- bit in the CRS_ICR register. SYNCERR : Boolean; -- Read-only. SYNC missed This flag is set by hardware when the -- frequency error counter reached value FELIM * 128 and no SYNC was -- detected, meaning either that a SYNC pulse was missed or that the -- frequency error is too big (internal frequency too high) to be -- compensated by adjusting the TRIM value, and that some other action -- should be taken. At this point, the frequency error counter is -- stopped (waiting for a next SYNC) and an interrupt is generated if -- the ERRIE bit is set in the CRS_CR register. It is cleared by -- software by setting the ERRC bit in the CRS_ICR register. SYNCMISS : Boolean; -- Read-only. Trimming overflow or underflow This flag is set by -- hardware when the automatic trimming tries to over- or under-flow the -- TRIM value. An interrupt is generated if the ERRIE bit is set in the -- CRS_CR register. It is cleared by software by setting the ERRC bit in -- the CRS_ICR register. TRIMOVF : Boolean; -- unspecified Reserved_11_14 : HAL.UInt4; -- Read-only. Frequency error direction FEDIR is the counting direction -- of the frequency error counter latched in the time of the last SYNC -- event. It shows whether the actual frequency is below or above the -- target. FEDIR : Boolean; -- Read-only. Frequency error capture FECAP is the frequency error -- counter value latched in the time ofthe last SYNC event. Refer to -- Section7.3.4: Frequency error evaluation and automatic trimming for -- more details about FECAP usage. FECAP : ISR_FECAP_Field; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ISR_Register use record SYNCOKF at 0 range 0 .. 0; SYNCWARNF at 0 range 1 .. 1; ERRF at 0 range 2 .. 2; ESYNCF at 0 range 3 .. 3; Reserved_4_7 at 0 range 4 .. 7; SYNCERR at 0 range 8 .. 8; SYNCMISS at 0 range 9 .. 9; TRIMOVF at 0 range 10 .. 10; Reserved_11_14 at 0 range 11 .. 14; FEDIR at 0 range 15 .. 15; FECAP at 0 range 16 .. 31; end record; -- CRS interrupt flag clear register type ICR_Register is record -- SYNC event OK clear flag Writing 1 to this bit clears the SYNCOKF -- flag in the CRS_ISR register. SYNCOKC : Boolean := False; -- SYNC warning clear flag Writing 1 to this bit clears the SYNCWARNF -- flag in the CRS_ISR register. SYNCWARNC : Boolean := False; -- Error clear flag Writing 1 to this bit clears TRIMOVF, SYNCMISS and -- SYNCERR bits and consequently also the ERRF flag in the CRS_ISR -- register. ERRC : Boolean := False; -- Expected SYNC clear flag Writing 1 to this bit clears the ESYNCF flag -- in the CRS_ISR register. ESYNCC : Boolean := False; -- unspecified Reserved_4_31 : HAL.UInt28 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ICR_Register use record SYNCOKC at 0 range 0 .. 0; SYNCWARNC at 0 range 1 .. 1; ERRC at 0 range 2 .. 2; ESYNCC at 0 range 3 .. 3; Reserved_4_31 at 0 range 4 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- CRS type CRS_Peripheral is record -- CRS control register CR : aliased CR_Register; -- This register can be written only when the frequency error counter is -- disabled (CEN bit is cleared in CRS_CR). When the counter is enabled, -- this register is write-protected. CFGR : aliased CFGR_Register; -- CRS interrupt and status register ISR : aliased ISR_Register; -- CRS interrupt flag clear register ICR : aliased ICR_Register; end record with Volatile; for CRS_Peripheral use record CR at 16#0# range 0 .. 31; CFGR at 16#4# range 0 .. 31; ISR at 16#8# range 0 .. 31; ICR at 16#C# range 0 .. 31; end record; -- CRS CRS_Periph : aliased CRS_Peripheral with Import, Address => CRS_Base; end STM32_SVD.CRS;
select A.Z; or delay 5.0; Put("Komunikat"); end select;
-- C52104L.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK THAT LENGTHS MUST MATCH IN ARRAY AND SLICE ASSIGNMENTS. -- MORE SPECIFICALLY, TEST THAT ATTEMPTED ASSIGNMENTS BETWEEN -- ARRAYS WITH NON-MATCHING LENGTHS LEAVE THE DESTINATION ARRAY -- INTACT AND CAUSE CONSTRAINT_ERROR TO BE RAISED. -- (OVERLAPS BETWEEN THE OPERANDS OF THE ASSIGNMENT STATEMENT -- ARE TREATED ELSEWHERE.) -- THIS IS THE SECOND FILE IN -- DIVISION C : NON-NULL LENGTHS NOT DETERMINABLE STATICALLY. -- HISTORY: -- RM 07/20/81 CREATED ORIGINAL TEST. -- SPS 03/22/83 -- DHH 10/20/87 SHORTENED LINES CONTAINING MORE THAN 72 CHARACTERS. WITH REPORT; PROCEDURE C52104L IS USE REPORT ; BEGIN TEST( "C52104L" , "CHECK THAT IN ARRAY ASSIGNMENTS AND IN SLICE" & " ASSIGNMENTS THE LENGTHS MUST MATCH" ); -- ( EACH DIVISION COMPRISES 3 FILES, -- COVERING RESPECTIVELY THE FIRST -- 3 , NEXT 2 , AND LAST 3 OF THE 8 -- SELECTIONS FOR THE DIVISION.) ------------------------------------------------------------------- -- (13) UNSLICED ONE-DIMENSIONAL ARRAY OBJECTS WHOSE TYPEMARKS -- WERE DEFINED USING THE "BOX" SYMBOL -- AND FOR WHICH THE COMPONENT TYPE IS 'CHARACTER' . DECLARE TYPE TABOX3 IS ARRAY( INTEGER RANGE <> ) OF CHARACTER ; ARRX31 : TABOX3( IDENT_INT(2)..IDENT_INT(6) ) := "QUINC" ; BEGIN -- ARRAY ASSIGNMENT (WITH STRING AGGREGATE): ARRX31 := "ABCD" ; FAILED( "NO EXCEPTION RAISED (13)" ); EXCEPTION WHEN CONSTRAINT_ERROR => -- CHECKING THE VALUES AFTER THE ASSIGNMENT: IF ARRX31 /= "QUINC" OR ARRX31( IDENT_INT(2)..IDENT_INT(6) ) /= "QUINC" THEN FAILED( "LHS ARRAY ALTERED (13)" ); END IF; WHEN OTHERS => FAILED( "WRONG EXCEPTION RAISED - SUBTEST 13" ); END ; ------------------------------------------------------------------- -- (14) SLICED ONE-DIMENSIONAL ARRAY OBJECTS WHOSE TYPEMARKS -- WERE DEFINED USING THE "BOX" SYMBOL -- AND FOR WHICH THE COMPONENT TYPE IS 'CHARACTER' . DECLARE TYPE TABOX4 IS ARRAY( INTEGER RANGE <> ) OF CHARACTER ; SUBTYPE TABOX42 IS TABOX4( IDENT_INT(5)..IDENT_INT(9) ); ARRX42 : TABOX42 ; BEGIN -- INITIALIZATION OF LHS ARRAY: ARRX42 := "QUINC" ; -- SLICE ASSIGNMENT: ARRX42( IDENT_INT(6)..IDENT_INT(9) ) := "ABCDEFGH" ; FAILED( "NO EXCEPTION RAISED (14)" ); EXCEPTION WHEN CONSTRAINT_ERROR => -- CHECKING THE VALUES AFTER THE ASSIGNMENT: IF ARRX42 /= "QUINC" OR ARRX42( IDENT_INT(5)..IDENT_INT(9) ) /= "QUINC" THEN FAILED( "LHS ARRAY ALTERED (14)" ); END IF; WHEN OTHERS => FAILED( "WRONG EXCEPTION RAISED - SUBTEST 14" ); END ; ------------------------------------------------------------------- RESULT ; END C52104L;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ C A S E -- -- -- -- B o d y -- -- -- -- Copyright (C) 1996-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Einfo; use Einfo; with Errout; use Errout; with Namet; use Namet; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Sem; use Sem; with Sem_Aux; use Sem_Aux; with Sem_Eval; use Sem_Eval; with Sem_Res; use Sem_Res; with Sem_Util; use Sem_Util; with Sem_Type; use Sem_Type; with Snames; use Snames; with Stand; use Stand; with Sinfo; use Sinfo; with Tbuild; use Tbuild; with Uintp; use Uintp; with Ada.Unchecked_Deallocation; with GNAT.Heap_Sort_G; package body Sem_Case is type Choice_Bounds is record Lo : Node_Id; Hi : Node_Id; Node : Node_Id; end record; -- Represent one choice bounds entry with Lo and Hi values, Node points -- to the choice node itself. type Choice_Table_Type is array (Nat range <>) of Choice_Bounds; -- Table type used to sort the choices present in a case statement or -- record variant. The actual entries are stored in 1 .. Last, but we -- have a 0 entry for use in sorting. ----------------------- -- Local Subprograms -- ----------------------- procedure Check_Choice_Set (Choice_Table : in out Choice_Table_Type; Bounds_Type : Entity_Id; Subtyp : Entity_Id; Others_Present : Boolean; Case_Node : Node_Id); -- This is the procedure which verifies that a set of case alternatives -- or record variant choices has no duplicates, and covers the range -- specified by Bounds_Type. Choice_Table contains the discrete choices -- to check. These must start at position 1. -- -- Furthermore Choice_Table (0) must exist. This element is used by -- the sorting algorithm as a temporary. Others_Present is a flag -- indicating whether or not an Others choice is present. Finally -- Msg_Sloc gives the source location of the construct containing the -- choices in the Choice_Table. -- -- Bounds_Type is the type whose range must be covered by the alternatives -- -- Subtyp is the subtype of the expression. If its bounds are non-static -- the alternatives must cover its base type. function Choice_Image (Value : Uint; Ctype : Entity_Id) return Name_Id; -- Given a Pos value of enumeration type Ctype, returns the name -- ID of an appropriate string to be used in error message output. procedure Expand_Others_Choice (Case_Table : Choice_Table_Type; Others_Choice : Node_Id; Choice_Type : Entity_Id); -- The case table is the table generated by a call to Check_Choices -- (with just 1 .. Last_Choice entries present). Others_Choice is a -- pointer to the N_Others_Choice node (this routine is only called if -- an others choice is present), and Choice_Type is the discrete type -- of the bounds. The effect of this call is to analyze the cases and -- determine the set of values covered by others. This choice list is -- set in the Others_Discrete_Choices field of the N_Others_Choice node. ---------------------- -- Check_Choice_Set -- ---------------------- procedure Check_Choice_Set (Choice_Table : in out Choice_Table_Type; Bounds_Type : Entity_Id; Subtyp : Entity_Id; Others_Present : Boolean; Case_Node : Node_Id) is Predicate_Error : Boolean := False; -- Flag to prevent cascaded errors when a static predicate is known to -- be violated by one choice. Num_Choices : constant Nat := Choice_Table'Last; procedure Check_Against_Predicate (Pred : in out Node_Id; Choice : Choice_Bounds; Prev_Lo : in out Uint; Prev_Hi : in out Uint; Error : in out Boolean); -- Determine whether a choice covers legal values as defined by a static -- predicate set. Pred is a static predicate range. Choice is the choice -- to be examined. Prev_Lo and Prev_Hi are the bounds of the previous -- choice that covered a predicate set. Error denotes whether the check -- found an illegal intersection. procedure Check_Duplicates; -- Check for duplicate choices, and call Dup_Choice if there are any -- such errors. Note that predicates are irrelevant here. procedure Dup_Choice (Lo, Hi : Uint; C : Node_Id); -- Post message "duplication of choice value(s) bla bla at xx". Message -- is posted at location C. Caller sets Error_Msg_Sloc for xx. procedure Explain_Non_Static_Bound; -- Called when we find a non-static bound, requiring the base type to -- be covered. Provides where possible a helpful explanation of why the -- bounds are non-static, since this is not always obvious. function Lt_Choice (C1, C2 : Natural) return Boolean; -- Comparison routine for comparing Choice_Table entries. Use the lower -- bound of each Choice as the key. procedure Missing_Choice (Value1 : Node_Id; Value2 : Node_Id); procedure Missing_Choice (Value1 : Node_Id; Value2 : Uint); procedure Missing_Choice (Value1 : Uint; Value2 : Node_Id); procedure Missing_Choice (Value1 : Uint; Value2 : Uint); -- Issue an error message indicating that there are missing choices, -- followed by the image of the missing choices themselves which lie -- between Value1 and Value2 inclusive. procedure Missing_Choices (Pred : Node_Id; Prev_Hi : Uint); -- Emit an error message for each non-covered static predicate set. -- Prev_Hi denotes the upper bound of the last choice covering a set. procedure Move_Choice (From : Natural; To : Natural); -- Move routine for sorting the Choice_Table package Sorting is new GNAT.Heap_Sort_G (Move_Choice, Lt_Choice); ----------------------------- -- Check_Against_Predicate -- ----------------------------- procedure Check_Against_Predicate (Pred : in out Node_Id; Choice : Choice_Bounds; Prev_Lo : in out Uint; Prev_Hi : in out Uint; Error : in out Boolean) is procedure Illegal_Range (Loc : Source_Ptr; Lo : Uint; Hi : Uint); -- Emit an error message regarding a choice that clashes with the -- legal static predicate sets. Loc is the location of the choice -- that introduced the illegal range. Lo .. Hi is the range. function Inside_Range (Lo : Uint; Hi : Uint; Val : Uint) return Boolean; -- Determine whether position Val within a discrete type is within -- the range Lo .. Hi inclusive. ------------------- -- Illegal_Range -- ------------------- procedure Illegal_Range (Loc : Source_Ptr; Lo : Uint; Hi : Uint) is begin Error_Msg_Name_1 := Chars (Bounds_Type); -- Single value if Lo = Hi then if Is_Integer_Type (Bounds_Type) then Error_Msg_Uint_1 := Lo; Error_Msg ("static predicate on % excludes value ^!", Loc); else Error_Msg_Name_2 := Choice_Image (Lo, Bounds_Type); Error_Msg ("static predicate on % excludes value %!", Loc); end if; -- Range else if Is_Integer_Type (Bounds_Type) then Error_Msg_Uint_1 := Lo; Error_Msg_Uint_2 := Hi; Error_Msg ("static predicate on % excludes range ^ .. ^!", Loc); else Error_Msg_Name_2 := Choice_Image (Lo, Bounds_Type); Error_Msg_Name_3 := Choice_Image (Hi, Bounds_Type); Error_Msg ("static predicate on % excludes range % .. %!", Loc); end if; end if; end Illegal_Range; ------------------ -- Inside_Range -- ------------------ function Inside_Range (Lo : Uint; Hi : Uint; Val : Uint) return Boolean is begin return Lo <= Val and then Val <= Hi; end Inside_Range; -- Local variables Choice_Hi : constant Uint := Expr_Value (Choice.Hi); Choice_Lo : constant Uint := Expr_Value (Choice.Lo); Loc : Source_Ptr; LocN : Node_Id; Next_Hi : Uint; Next_Lo : Uint; Pred_Hi : Uint; Pred_Lo : Uint; -- Start of processing for Check_Against_Predicate begin -- Find the proper error message location if Present (Choice.Node) then LocN := Choice.Node; else LocN := Case_Node; end if; Loc := Sloc (LocN); if Present (Pred) then Pred_Lo := Expr_Value (Low_Bound (Pred)); Pred_Hi := Expr_Value (High_Bound (Pred)); -- Previous choices managed to satisfy all static predicate sets else Illegal_Range (Loc, Choice_Lo, Choice_Hi); Error := True; return; end if; -- Step 1: Ignore duplicate choices, other than to set the flag, -- because these were already detected by Check_Duplicates. if Inside_Range (Choice_Lo, Choice_Hi, Prev_Lo) or else Inside_Range (Choice_Lo, Choice_Hi, Prev_Hi) then Error := True; -- Step 2: Detect full coverage -- Choice_Lo Choice_Hi -- +============+ -- Pred_Lo Pred_Hi elsif Choice_Lo = Pred_Lo and then Choice_Hi = Pred_Hi then Prev_Lo := Choice_Lo; Prev_Hi := Choice_Hi; Next (Pred); -- Step 3: Detect all cases where a choice mentions values that are -- not part of the static predicate sets. -- Choice_Lo Choice_Hi Pred_Lo Pred_Hi -- +-----------+ . . . . . +=========+ -- ^ illegal ^ elsif Choice_Lo < Pred_Lo and then Choice_Hi < Pred_Lo then Illegal_Range (Loc, Choice_Lo, Choice_Hi); Error := True; -- Choice_Lo Pred_Lo Choice_Hi Pred_Hi -- +-----------+=========+===========+ -- ^ illegal ^ elsif Choice_Lo < Pred_Lo and then Inside_Range (Pred_Lo, Pred_Hi, Choice_Hi) then Illegal_Range (Loc, Choice_Lo, Pred_Lo - 1); Error := True; -- Pred_Lo Pred_Hi Choice_Lo Choice_Hi -- +=========+ . . . . +-----------+ -- ^ illegal ^ elsif Pred_Lo < Choice_Lo and then Pred_Hi < Choice_Lo then if Others_Present then -- Current predicate set is covered by others clause. null; else Missing_Choice (Pred_Lo, Pred_Hi); Error := True; end if; -- There may be several static predicate sets between the current -- one and the choice. Inspect the next static predicate set. Next (Pred); Check_Against_Predicate (Pred => Pred, Choice => Choice, Prev_Lo => Prev_Lo, Prev_Hi => Prev_Hi, Error => Error); -- Pred_Lo Choice_Lo Pred_Hi Choice_Hi -- +=========+===========+-----------+ -- ^ illegal ^ elsif Pred_Hi < Choice_Hi and then Inside_Range (Pred_Lo, Pred_Hi, Choice_Lo) then Next (Pred); -- The choice may fall in a static predicate set. If this is the -- case, avoid mentioning legal values in the error message. if Present (Pred) then Next_Lo := Expr_Value (Low_Bound (Pred)); Next_Hi := Expr_Value (High_Bound (Pred)); -- The next static predicate set is to the right of the choice if Choice_Hi < Next_Lo and then Choice_Hi < Next_Hi then Illegal_Range (Loc, Pred_Hi + 1, Choice_Hi); else Illegal_Range (Loc, Pred_Hi + 1, Next_Lo - 1); end if; else Illegal_Range (Loc, Pred_Hi + 1, Choice_Hi); end if; Error := True; -- Choice_Lo Pred_Lo Pred_Hi Choice_Hi -- +-----------+=========+-----------+ -- ^ illegal ^ ^ illegal ^ -- Emit an error on the low gap, disregard the upper gap elsif Choice_Lo < Pred_Lo and then Pred_Hi < Choice_Hi then Illegal_Range (Loc, Choice_Lo, Pred_Lo - 1); Error := True; -- Step 4: Detect all cases of partial or missing coverage -- Pred_Lo Choice_Lo Choice_Hi Pred_Hi -- +=========+==========+===========+ -- ^ gap ^ ^ gap ^ else -- An "others" choice covers all gaps if Others_Present then Prev_Lo := Choice_Lo; Prev_Hi := Choice_Hi; -- Check whether predicate set is fully covered by choice if Pred_Hi = Choice_Hi then Next (Pred); end if; -- Choice_Lo Choice_Hi Pred_Hi -- +===========+===========+ -- Pred_Lo ^ gap ^ -- The upper gap may be covered by a subsequent choice elsif Pred_Lo = Choice_Lo then Prev_Lo := Choice_Lo; Prev_Hi := Choice_Hi; -- Pred_Lo Prev_Hi Choice_Lo Choice_Hi Pred_Hi -- +===========+=========+===========+===========+ -- ^ covered ^ ^ gap ^ else pragma Assert (Pred_Lo < Choice_Lo); -- A previous choice covered the gap up to the current choice if Prev_Hi = Choice_Lo - 1 then Prev_Lo := Choice_Lo; Prev_Hi := Choice_Hi; if Choice_Hi = Pred_Hi then Next (Pred); end if; -- The previous choice did not intersect with the current -- static predicate set. elsif Prev_Hi < Pred_Lo then Missing_Choice (Pred_Lo, Choice_Lo - 1); Error := True; -- The previous choice covered part of the static predicate set -- but there is a gap after Prev_Hi. else Missing_Choice (Prev_Hi + 1, Choice_Lo - 1); Error := True; end if; end if; end if; end Check_Against_Predicate; ---------------------- -- Check_Duplicates -- ---------------------- procedure Check_Duplicates is Choice : Node_Id; Choice_Hi : Uint; Choice_Lo : Uint; Prev_Choice : Node_Id := Empty; Prev_Hi : Uint; begin Prev_Hi := Expr_Value (Choice_Table (1).Hi); for Outer_Index in 2 .. Num_Choices loop Choice_Lo := Expr_Value (Choice_Table (Outer_Index).Lo); Choice_Hi := Expr_Value (Choice_Table (Outer_Index).Hi); -- Choices overlap; this is an error if Choice_Lo <= Prev_Hi then Choice := Choice_Table (Outer_Index).Node; -- Find first previous choice that overlaps for Inner_Index in 1 .. Outer_Index - 1 loop if Choice_Lo <= Expr_Value (Choice_Table (Inner_Index).Hi) then Prev_Choice := Choice_Table (Inner_Index).Node; exit; end if; end loop; pragma Assert (Present (Prev_Choice)); if Sloc (Prev_Choice) <= Sloc (Choice) then Error_Msg_Sloc := Sloc (Prev_Choice); Dup_Choice (Choice_Lo, UI_Min (Choice_Hi, Prev_Hi), Choice); else Error_Msg_Sloc := Sloc (Choice); Dup_Choice (Choice_Lo, UI_Min (Choice_Hi, Prev_Hi), Prev_Choice); end if; end if; if Choice_Hi > Prev_Hi then Prev_Hi := Choice_Hi; end if; end loop; end Check_Duplicates; ---------------- -- Dup_Choice -- ---------------- procedure Dup_Choice (Lo, Hi : Uint; C : Node_Id) is begin -- In some situations, we call this with a null range, and obviously -- we don't want to complain in this case. if Lo > Hi then return; end if; -- Case of only one value that is duplicated if Lo = Hi then -- Integer type if Is_Integer_Type (Bounds_Type) then -- We have an integer value, Lo, but if the given choice -- placement is a constant with that value, then use the -- name of that constant instead in the message: if Nkind (C) = N_Identifier and then Compile_Time_Known_Value (C) and then Expr_Value (C) = Lo then Error_Msg_N ("duplication of choice value: &#!", C); -- Not that special case, so just output the integer value else Error_Msg_Uint_1 := Lo; Error_Msg_N ("duplication of choice value: ^#!", C); end if; -- Enumeration type else Error_Msg_Name_1 := Choice_Image (Lo, Bounds_Type); Error_Msg_N ("duplication of choice value: %#!", C); end if; -- More than one choice value, so print range of values else -- Integer type if Is_Integer_Type (Bounds_Type) then -- Similar to the above, if C is a range of known values which -- match Lo and Hi, then use the names. We have to go to the -- original nodes, since the values will have been rewritten -- to their integer values. if Nkind (C) = N_Range and then Nkind (Original_Node (Low_Bound (C))) = N_Identifier and then Nkind (Original_Node (High_Bound (C))) = N_Identifier and then Compile_Time_Known_Value (Low_Bound (C)) and then Compile_Time_Known_Value (High_Bound (C)) and then Expr_Value (Low_Bound (C)) = Lo and then Expr_Value (High_Bound (C)) = Hi then Error_Msg_Node_2 := Original_Node (High_Bound (C)); Error_Msg_N ("duplication of choice values: & .. &#!", Original_Node (Low_Bound (C))); -- Not that special case, output integer values else Error_Msg_Uint_1 := Lo; Error_Msg_Uint_2 := Hi; Error_Msg_N ("duplication of choice values: ^ .. ^#!", C); end if; -- Enumeration type else Error_Msg_Name_1 := Choice_Image (Lo, Bounds_Type); Error_Msg_Name_2 := Choice_Image (Hi, Bounds_Type); Error_Msg_N ("duplication of choice values: % .. %#!", C); end if; end if; end Dup_Choice; ------------------------------ -- Explain_Non_Static_Bound -- ------------------------------ procedure Explain_Non_Static_Bound is Expr : Node_Id; begin if Nkind (Case_Node) = N_Variant_Part then Expr := Name (Case_Node); else Expr := Expression (Case_Node); end if; if Bounds_Type /= Subtyp then -- If the case is a variant part, the expression is given by the -- discriminant itself, and the bounds are the culprits. if Nkind (Case_Node) = N_Variant_Part then Error_Msg_NE ("bounds of & are not static, " & "alternatives must cover base type!", Expr, Expr); -- If this is a case statement, the expression may be non-static -- or else the subtype may be at fault. elsif Is_Entity_Name (Expr) then Error_Msg_NE ("bounds of & are not static, " & "alternatives must cover base type!", Expr, Expr); else Error_Msg_N ("subtype of expression is not static, " & "alternatives must cover base type!", Expr); end if; -- Otherwise the expression is not static, even if the bounds of the -- type are, or else there are missing alternatives. If both, the -- additional information may be redundant but harmless. Examine -- whether original node is an entity, because it may have been -- constant-folded to a literal if value is known. elsif not Is_Entity_Name (Original_Node (Expr)) then Error_Msg_N ("subtype of expression is not static, " & "alternatives must cover base type!", Expr); end if; end Explain_Non_Static_Bound; --------------- -- Lt_Choice -- --------------- function Lt_Choice (C1, C2 : Natural) return Boolean is begin return Expr_Value (Choice_Table (Nat (C1)).Lo) < Expr_Value (Choice_Table (Nat (C2)).Lo); end Lt_Choice; -------------------- -- Missing_Choice -- -------------------- procedure Missing_Choice (Value1 : Node_Id; Value2 : Node_Id) is begin Missing_Choice (Expr_Value (Value1), Expr_Value (Value2)); end Missing_Choice; procedure Missing_Choice (Value1 : Node_Id; Value2 : Uint) is begin Missing_Choice (Expr_Value (Value1), Value2); end Missing_Choice; procedure Missing_Choice (Value1 : Uint; Value2 : Node_Id) is begin Missing_Choice (Value1, Expr_Value (Value2)); end Missing_Choice; -------------------- -- Missing_Choice -- -------------------- procedure Missing_Choice (Value1 : Uint; Value2 : Uint) is Msg_Sloc : constant Source_Ptr := Sloc (Case_Node); begin -- AI05-0188 : within an instance the non-others choices do not have -- to belong to the actual subtype. if Ada_Version >= Ada_2012 and then In_Instance then return; -- In some situations, we call this with a null range, and obviously -- we don't want to complain in this case. elsif Value1 > Value2 then return; -- If predicate is already known to be violated, do no check for -- coverage error, to prevent cascaded messages. elsif Predicate_Error then return; end if; -- Case of only one value that is missing if Value1 = Value2 then if Is_Integer_Type (Bounds_Type) then Error_Msg_Uint_1 := Value1; Error_Msg ("missing case value: ^!", Msg_Sloc); else Error_Msg_Name_1 := Choice_Image (Value1, Bounds_Type); Error_Msg ("missing case value: %!", Msg_Sloc); end if; -- More than one choice value, so print range of values else if Is_Integer_Type (Bounds_Type) then Error_Msg_Uint_1 := Value1; Error_Msg_Uint_2 := Value2; Error_Msg ("missing case values: ^ .. ^!", Msg_Sloc); else Error_Msg_Name_1 := Choice_Image (Value1, Bounds_Type); Error_Msg_Name_2 := Choice_Image (Value2, Bounds_Type); Error_Msg ("missing case values: % .. %!", Msg_Sloc); end if; end if; end Missing_Choice; --------------------- -- Missing_Choices -- --------------------- procedure Missing_Choices (Pred : Node_Id; Prev_Hi : Uint) is Hi : Uint; Lo : Uint; Set : Node_Id; begin Set := Pred; while Present (Set) loop Lo := Expr_Value (Low_Bound (Set)); Hi := Expr_Value (High_Bound (Set)); -- A choice covered part of a static predicate set if Lo <= Prev_Hi and then Prev_Hi < Hi then Missing_Choice (Prev_Hi + 1, Hi); else Missing_Choice (Lo, Hi); end if; Next (Set); end loop; end Missing_Choices; ----------------- -- Move_Choice -- ----------------- procedure Move_Choice (From : Natural; To : Natural) is begin Choice_Table (Nat (To)) := Choice_Table (Nat (From)); end Move_Choice; -- Local variables Bounds_Hi : constant Node_Id := Type_High_Bound (Bounds_Type); Bounds_Lo : constant Node_Id := Type_Low_Bound (Bounds_Type); Has_Predicate : constant Boolean := Is_OK_Static_Subtype (Bounds_Type) and then Has_Static_Predicate (Bounds_Type); Choice_Hi : Uint; Choice_Lo : Uint; Pred : Node_Id; Prev_Lo : Uint; Prev_Hi : Uint; -- Start of processing for Check_Choice_Set begin -- If the case is part of a predicate aspect specification, do not -- recheck it against itself. if Present (Parent (Case_Node)) and then Nkind (Parent (Case_Node)) = N_Aspect_Specification then return; end if; -- Choice_Table must start at 0 which is an unused location used by the -- sorting algorithm. However the first valid position for a discrete -- choice is 1. pragma Assert (Choice_Table'First = 0); -- The choices do not cover the base range. Emit an error if "others" is -- not available and return as there is no need for further processing. if Num_Choices = 0 then if not Others_Present then Missing_Choice (Bounds_Lo, Bounds_Hi); end if; return; end if; Sorting.Sort (Positive (Choice_Table'Last)); -- First check for duplicates. This involved the choices; predicates, if -- any, are irrelevant. Check_Duplicates; -- Then check for overlaps -- If the subtype has a static predicate, the predicate defines subsets -- of legal values and requires finer-grained analysis. -- Note that in GNAT the predicate is considered static if the predicate -- expression is static, independently of whether the aspect mentions -- Static explicitly. if Has_Predicate then Pred := First (Static_Discrete_Predicate (Bounds_Type)); -- Make initial value smaller than 'First of type, so that first -- range comparison succeeds. This applies both to integer types -- and to enumeration types. Prev_Lo := Expr_Value (Type_Low_Bound (Bounds_Type)) - 1; Prev_Hi := Prev_Lo; declare Error : Boolean := False; begin for Index in 1 .. Num_Choices loop Check_Against_Predicate (Pred => Pred, Choice => Choice_Table (Index), Prev_Lo => Prev_Lo, Prev_Hi => Prev_Hi, Error => Error); -- The analysis detected an illegal intersection between a -- choice and a static predicate set. Do not examine other -- choices unless all errors are requested. if Error then Predicate_Error := True; if not All_Errors_Mode then return; end if; end if; end loop; end; if Predicate_Error then return; end if; -- The choices may legally cover some of the static predicate sets, -- but not all. Emit an error for each non-covered set. if not Others_Present then Missing_Choices (Pred, Prev_Hi); end if; -- Default analysis else Choice_Lo := Expr_Value (Choice_Table (1).Lo); Choice_Hi := Expr_Value (Choice_Table (1).Hi); Prev_Hi := Choice_Hi; if not Others_Present and then Expr_Value (Bounds_Lo) < Choice_Lo then Missing_Choice (Bounds_Lo, Choice_Lo - 1); -- If values are missing outside of the subtype, add explanation. -- No additional message if only one value is missing. if Expr_Value (Bounds_Lo) < Choice_Lo - 1 then Explain_Non_Static_Bound; end if; end if; for Index in 2 .. Num_Choices loop Choice_Lo := Expr_Value (Choice_Table (Index).Lo); Choice_Hi := Expr_Value (Choice_Table (Index).Hi); if Choice_Lo > Prev_Hi + 1 and then not Others_Present then Missing_Choice (Prev_Hi + 1, Choice_Lo - 1); end if; if Choice_Hi > Prev_Hi then Prev_Hi := Choice_Hi; end if; end loop; if not Others_Present and then Expr_Value (Bounds_Hi) > Prev_Hi then Missing_Choice (Prev_Hi + 1, Bounds_Hi); if Expr_Value (Bounds_Hi) > Prev_Hi + 1 then Explain_Non_Static_Bound; end if; end if; end if; end Check_Choice_Set; ------------------ -- Choice_Image -- ------------------ function Choice_Image (Value : Uint; Ctype : Entity_Id) return Name_Id is Rtp : constant Entity_Id := Root_Type (Ctype); Lit : Entity_Id; C : Int; begin -- For character, or wide [wide] character. If 7-bit ASCII graphic -- range, then build and return appropriate character literal name if Is_Standard_Character_Type (Ctype) then C := UI_To_Int (Value); if C in 16#20# .. 16#7E# then Set_Character_Literal_Name (Char_Code (UI_To_Int (Value))); return Name_Find; end if; -- For user defined enumeration type, find enum/char literal else Lit := First_Literal (Rtp); for J in 1 .. UI_To_Int (Value) loop Next_Literal (Lit); end loop; -- If enumeration literal, just return its value if Nkind (Lit) = N_Defining_Identifier then return Chars (Lit); -- For character literal, get the name and use it if it is -- for a 7-bit ASCII graphic character in 16#20#..16#7E#. else Get_Decoded_Name_String (Chars (Lit)); if Name_Len = 3 and then Name_Buffer (2) in Character'Val (16#20#) .. Character'Val (16#7E#) then return Chars (Lit); end if; end if; end if; -- If we fall through, we have a character literal which is not in -- the 7-bit ASCII graphic set. For such cases, we construct the -- name "type'val(nnn)" where type is the choice type, and nnn is -- the pos value passed as an argument to Choice_Image. Get_Name_String (Chars (First_Subtype (Ctype))); Add_Str_To_Name_Buffer ("'val("); UI_Image (Value); Add_Str_To_Name_Buffer (UI_Image_Buffer (1 .. UI_Image_Length)); Add_Char_To_Name_Buffer (')'); return Name_Find; end Choice_Image; -------------------------- -- Expand_Others_Choice -- -------------------------- procedure Expand_Others_Choice (Case_Table : Choice_Table_Type; Others_Choice : Node_Id; Choice_Type : Entity_Id) is Loc : constant Source_Ptr := Sloc (Others_Choice); Choice_List : constant List_Id := New_List; Choice : Node_Id; Exp_Lo : Node_Id; Exp_Hi : Node_Id; Hi : Uint; Lo : Uint; Previous_Hi : Uint; function Build_Choice (Value1, Value2 : Uint) return Node_Id; -- Builds a node representing the missing choices given by Value1 and -- Value2. A N_Range node is built if there is more than one literal -- value missing. Otherwise a single N_Integer_Literal, N_Identifier -- or N_Character_Literal is built depending on what Choice_Type is. function Lit_Of (Value : Uint) return Node_Id; -- Returns the Node_Id for the enumeration literal corresponding to the -- position given by Value within the enumeration type Choice_Type. The -- returned value has its Is_Static_Expression flag set to true. ------------------ -- Build_Choice -- ------------------ function Build_Choice (Value1, Value2 : Uint) return Node_Id is Lit_Node : Node_Id; Lo, Hi : Node_Id; begin -- If there is only one choice value missing between Value1 and -- Value2, build an integer or enumeration literal to represent it. if Value1 = Value2 then if Is_Integer_Type (Choice_Type) then Lit_Node := Make_Integer_Literal (Loc, Value1); Set_Etype (Lit_Node, Choice_Type); Set_Is_Static_Expression (Lit_Node); else Lit_Node := Lit_Of (Value1); end if; -- Otherwise is more that one choice value that is missing between -- Value1 and Value2, therefore build a N_Range node of either -- integer or enumeration literals. else if Is_Integer_Type (Choice_Type) then Lo := Make_Integer_Literal (Loc, Value1); Set_Etype (Lo, Choice_Type); Set_Is_Static_Expression (Lo); Hi := Make_Integer_Literal (Loc, Value2); Set_Etype (Hi, Choice_Type); Set_Is_Static_Expression (Hi); Lit_Node := Make_Range (Loc, Low_Bound => Lo, High_Bound => Hi); else Lit_Node := Make_Range (Loc, Low_Bound => Lit_Of (Value1), High_Bound => Lit_Of (Value2)); end if; end if; return Lit_Node; end Build_Choice; ------------ -- Lit_Of -- ------------ function Lit_Of (Value : Uint) return Node_Id is Lit : Entity_Id; begin -- In the case where the literal is of type Character, there needs -- to be some special handling since there is no explicit chain -- of literals to search. Instead, a N_Character_Literal node -- is created with the appropriate Char_Code and Chars fields. if Is_Standard_Character_Type (Choice_Type) then Set_Character_Literal_Name (Char_Code (UI_To_Int (Value))); Lit := New_Node (N_Character_Literal, Loc); Set_Chars (Lit, Name_Find); Set_Char_Literal_Value (Lit, Value); Set_Etype (Lit, Choice_Type); Set_Is_Static_Expression (Lit, True); return Lit; -- Otherwise, iterate through the literals list of Choice_Type -- "Value" number of times until the desired literal is reached -- and then return an occurrence of it. else Lit := First_Literal (Choice_Type); for J in 1 .. UI_To_Int (Value) loop Next_Literal (Lit); end loop; return New_Occurrence_Of (Lit, Loc); end if; end Lit_Of; -- Start of processing for Expand_Others_Choice begin if Case_Table'Last = 0 then -- Special case: only an others case is present. The others case -- covers the full range of the type. if Is_OK_Static_Subtype (Choice_Type) then Choice := New_Occurrence_Of (Choice_Type, Loc); else Choice := New_Occurrence_Of (Base_Type (Choice_Type), Loc); end if; Set_Others_Discrete_Choices (Others_Choice, New_List (Choice)); return; end if; -- Establish the bound values for the choice depending upon whether the -- type of the case statement is static or not. if Is_OK_Static_Subtype (Choice_Type) then Exp_Lo := Type_Low_Bound (Choice_Type); Exp_Hi := Type_High_Bound (Choice_Type); else Exp_Lo := Type_Low_Bound (Base_Type (Choice_Type)); Exp_Hi := Type_High_Bound (Base_Type (Choice_Type)); end if; Lo := Expr_Value (Case_Table (1).Lo); Hi := Expr_Value (Case_Table (1).Hi); Previous_Hi := Expr_Value (Case_Table (1).Hi); -- Build the node for any missing choices that are smaller than any -- explicit choices given in the case. if Expr_Value (Exp_Lo) < Lo then Append (Build_Choice (Expr_Value (Exp_Lo), Lo - 1), Choice_List); end if; -- Build the nodes representing any missing choices that lie between -- the explicit ones given in the case. for J in 2 .. Case_Table'Last loop Lo := Expr_Value (Case_Table (J).Lo); Hi := Expr_Value (Case_Table (J).Hi); if Lo /= (Previous_Hi + 1) then Append_To (Choice_List, Build_Choice (Previous_Hi + 1, Lo - 1)); end if; Previous_Hi := Hi; end loop; -- Build the node for any missing choices that are greater than any -- explicit choices given in the case. if Expr_Value (Exp_Hi) > Hi then Append (Build_Choice (Hi + 1, Expr_Value (Exp_Hi)), Choice_List); end if; Set_Others_Discrete_Choices (Others_Choice, Choice_List); -- Warn on null others list if warning option set if Warn_On_Redundant_Constructs and then Comes_From_Source (Others_Choice) and then Is_Empty_List (Choice_List) then Error_Msg_N ("?r?OTHERS choice is redundant", Others_Choice); Error_Msg_N ("\?r?previous choices cover all values", Others_Choice); end if; end Expand_Others_Choice; ----------- -- No_OP -- ----------- procedure No_OP (C : Node_Id) is begin if Nkind (C) = N_Range and then Warn_On_Redundant_Constructs then Error_Msg_N ("choice is an empty range?r?", C); end if; end No_OP; ----------------------------- -- Generic_Analyze_Choices -- ----------------------------- package body Generic_Analyze_Choices is -- The following type is used to gather the entries for the choice -- table, so that we can then allocate the right length. type Link; type Link_Ptr is access all Link; type Link is record Val : Choice_Bounds; Nxt : Link_Ptr; end record; --------------------- -- Analyze_Choices -- --------------------- procedure Analyze_Choices (Alternatives : List_Id; Subtyp : Entity_Id) is Choice_Type : constant Entity_Id := Base_Type (Subtyp); -- The actual type against which the discrete choices are resolved. -- Note that this type is always the base type not the subtype of the -- ruling expression, index or discriminant. Expected_Type : Entity_Id; -- The expected type of each choice. Equal to Choice_Type, except if -- the expression is universal, in which case the choices can be of -- any integer type. Alt : Node_Id; -- A case statement alternative or a variant in a record type -- declaration. Choice : Node_Id; Kind : Node_Kind; -- The node kind of the current Choice begin -- Set Expected type (= choice type except for universal integer, -- where we accept any integer type as a choice). if Choice_Type = Universal_Integer then Expected_Type := Any_Integer; else Expected_Type := Choice_Type; end if; -- Now loop through the case alternatives or record variants Alt := First (Alternatives); while Present (Alt) loop -- If pragma, just analyze it if Nkind (Alt) = N_Pragma then Analyze (Alt); -- Otherwise we have an alternative. In most cases the semantic -- processing leaves the list of choices unchanged -- Check each choice against its base type else Choice := First (Discrete_Choices (Alt)); while Present (Choice) loop Analyze (Choice); Kind := Nkind (Choice); -- Choice is a Range if Kind = N_Range or else (Kind = N_Attribute_Reference and then Attribute_Name (Choice) = Name_Range) then Resolve (Choice, Expected_Type); -- Choice is a subtype name, nothing further to do now elsif Is_Entity_Name (Choice) and then Is_Type (Entity (Choice)) then null; -- Choice is a subtype indication elsif Kind = N_Subtype_Indication then Resolve_Discrete_Subtype_Indication (Choice, Expected_Type); -- Others choice, no analysis needed elsif Kind = N_Others_Choice then null; -- Only other possibility is an expression else Resolve (Choice, Expected_Type); end if; -- Move to next choice Next (Choice); end loop; Process_Associated_Node (Alt); end if; Next (Alt); end loop; end Analyze_Choices; end Generic_Analyze_Choices; --------------------------- -- Generic_Check_Choices -- --------------------------- package body Generic_Check_Choices is -- The following type is used to gather the entries for the choice -- table, so that we can then allocate the right length. type Link; type Link_Ptr is access all Link; type Link is record Val : Choice_Bounds; Nxt : Link_Ptr; end record; procedure Free is new Ada.Unchecked_Deallocation (Link, Link_Ptr); ------------------- -- Check_Choices -- ------------------- procedure Check_Choices (N : Node_Id; Alternatives : List_Id; Subtyp : Entity_Id; Others_Present : out Boolean) is E : Entity_Id; Raises_CE : Boolean; -- Set True if one of the bounds of a choice raises CE Enode : Node_Id; -- This is where we post error messages for bounds out of range Choice_List : Link_Ptr := null; -- Gather list of choices Num_Choices : Nat := 0; -- Number of entries in Choice_List Choice_Type : constant Entity_Id := Base_Type (Subtyp); -- The actual type against which the discrete choices are resolved. -- Note that this type is always the base type not the subtype of the -- ruling expression, index or discriminant. Bounds_Type : Entity_Id; -- The type from which are derived the bounds of the values covered -- by the discrete choices (see 3.8.1 (4)). If a discrete choice -- specifies a value outside of these bounds we have an error. Bounds_Lo : Uint; Bounds_Hi : Uint; -- The actual bounds of the above type Expected_Type : Entity_Id; -- The expected type of each choice. Equal to Choice_Type, except if -- the expression is universal, in which case the choices can be of -- any integer type. Alt : Node_Id; -- A case statement alternative or a variant in a record type -- declaration. Choice : Node_Id; Kind : Node_Kind; -- The node kind of the current Choice Others_Choice : Node_Id := Empty; -- Remember others choice if it is present (empty otherwise) procedure Check (Choice : Node_Id; Lo, Hi : Node_Id); -- Checks the validity of the bounds of a choice. When the bounds -- are static and no error occurred the bounds are collected for -- later entry into the choices table so that they can be sorted -- later on. procedure Handle_Static_Predicate (Typ : Entity_Id; Lo : Node_Id; Hi : Node_Id); -- If the type of the alternative has predicates, we must examine -- each subset of the predicate rather than the bounds of the type -- itself. This is relevant when the choice is a subtype mark or a -- subtype indication. ----------- -- Check -- ----------- procedure Check (Choice : Node_Id; Lo, Hi : Node_Id) is Lo_Val : Uint; Hi_Val : Uint; begin -- First check if an error was already detected on either bounds if Etype (Lo) = Any_Type or else Etype (Hi) = Any_Type then return; -- Do not insert non static choices in the table to be sorted elsif not Is_OK_Static_Expression (Lo) or else not Is_OK_Static_Expression (Hi) then Process_Non_Static_Choice (Choice); return; -- Ignore range which raise constraint error elsif Raises_Constraint_Error (Lo) or else Raises_Constraint_Error (Hi) then Raises_CE := True; return; -- AI05-0188 : Within an instance the non-others choices do not -- have to belong to the actual subtype. elsif Ada_Version >= Ada_2012 and then In_Instance then return; -- Otherwise we have an OK static choice else Lo_Val := Expr_Value (Lo); Hi_Val := Expr_Value (Hi); -- Do not insert null ranges in the choices table if Lo_Val > Hi_Val then Process_Empty_Choice (Choice); return; end if; end if; -- Check for low bound out of range if Lo_Val < Bounds_Lo then -- If the choice is an entity name, then it is a type, and we -- want to post the message on the reference to this entity. -- Otherwise post it on the lower bound of the range. if Is_Entity_Name (Choice) then Enode := Choice; else Enode := Lo; end if; -- Specialize message for integer/enum type if Is_Integer_Type (Bounds_Type) then Error_Msg_Uint_1 := Bounds_Lo; Error_Msg_N ("minimum allowed choice value is^", Enode); else Error_Msg_Name_1 := Choice_Image (Bounds_Lo, Bounds_Type); Error_Msg_N ("minimum allowed choice value is%", Enode); end if; end if; -- Check for high bound out of range if Hi_Val > Bounds_Hi then -- If the choice is an entity name, then it is a type, and we -- want to post the message on the reference to this entity. -- Otherwise post it on the upper bound of the range. if Is_Entity_Name (Choice) then Enode := Choice; else Enode := Hi; end if; -- Specialize message for integer/enum type if Is_Integer_Type (Bounds_Type) then Error_Msg_Uint_1 := Bounds_Hi; Error_Msg_N ("maximum allowed choice value is^", Enode); else Error_Msg_Name_1 := Choice_Image (Bounds_Hi, Bounds_Type); Error_Msg_N ("maximum allowed choice value is%", Enode); end if; end if; -- Collect bounds in the list -- Note: we still store the bounds, even if they are out of range, -- since this may prevent unnecessary cascaded errors for values -- that are covered by such an excessive range. Choice_List := new Link'(Val => (Lo, Hi, Choice), Nxt => Choice_List); Num_Choices := Num_Choices + 1; end Check; ----------------------------- -- Handle_Static_Predicate -- ----------------------------- procedure Handle_Static_Predicate (Typ : Entity_Id; Lo : Node_Id; Hi : Node_Id) is P : Node_Id; C : Node_Id; begin -- Loop through entries in predicate list, checking each entry. -- Note that if the list is empty, corresponding to a False -- predicate, then no choices are checked. If the choice comes -- from a subtype indication, the given range may have bounds -- that narrow the predicate choices themselves, so we must -- consider only those entries within the range of the given -- subtype indication.. P := First (Static_Discrete_Predicate (Typ)); while Present (P) loop -- Check that part of the predicate choice is included in the -- given bounds. if Expr_Value (High_Bound (P)) >= Expr_Value (Lo) and then Expr_Value (Low_Bound (P)) <= Expr_Value (Hi) then C := New_Copy (P); Set_Sloc (C, Sloc (Choice)); if Expr_Value (Low_Bound (C)) < Expr_Value (Lo) then Set_Low_Bound (C, Lo); end if; if Expr_Value (High_Bound (C)) > Expr_Value (Hi) then Set_High_Bound (C, Hi); end if; Check (C, Low_Bound (C), High_Bound (C)); end if; Next (P); end loop; Set_Has_SP_Choice (Alt); end Handle_Static_Predicate; -- Start of processing for Check_Choices begin Raises_CE := False; Others_Present := False; -- If Subtyp is not a discrete type or there was some other error, -- then don't try any semantic checking on the choices since we have -- a complete mess. if not Is_Discrete_Type (Subtyp) or else Subtyp = Any_Type then return; end if; -- If Subtyp is not a static subtype Ada 95 requires then we use the -- bounds of its base type to determine the values covered by the -- discrete choices. -- In Ada 2012, if the subtype has a non-static predicate the full -- range of the base type must be covered as well. if Is_OK_Static_Subtype (Subtyp) then if not Has_Predicates (Subtyp) or else Has_Static_Predicate (Subtyp) then Bounds_Type := Subtyp; else Bounds_Type := Choice_Type; end if; else Bounds_Type := Choice_Type; end if; -- Obtain static bounds of type, unless this is a generic formal -- discrete type for which all choices will be non-static. if not Is_Generic_Type (Root_Type (Bounds_Type)) or else Ekind (Bounds_Type) /= E_Enumeration_Type then Bounds_Lo := Expr_Value (Type_Low_Bound (Bounds_Type)); Bounds_Hi := Expr_Value (Type_High_Bound (Bounds_Type)); end if; if Choice_Type = Universal_Integer then Expected_Type := Any_Integer; else Expected_Type := Choice_Type; end if; -- Now loop through the case alternatives or record variants Alt := First (Alternatives); while Present (Alt) loop -- If pragma, just analyze it if Nkind (Alt) = N_Pragma then Analyze (Alt); -- Otherwise we have an alternative. In most cases the semantic -- processing leaves the list of choices unchanged -- Check each choice against its base type else Choice := First (Discrete_Choices (Alt)); while Present (Choice) loop Kind := Nkind (Choice); -- Choice is a Range if Kind = N_Range or else (Kind = N_Attribute_Reference and then Attribute_Name (Choice) = Name_Range) then Check (Choice, Low_Bound (Choice), High_Bound (Choice)); -- Choice is a subtype name elsif Is_Entity_Name (Choice) and then Is_Type (Entity (Choice)) then -- Check for inappropriate type if not Covers (Expected_Type, Etype (Choice)) then Wrong_Type (Choice, Choice_Type); -- Type is OK, so check further else E := Entity (Choice); -- Case of predicated subtype if Has_Predicates (E) then -- Use of non-static predicate is an error if not Is_Discrete_Type (E) or else not Has_Static_Predicate (E) or else Has_Dynamic_Predicate_Aspect (E) then Bad_Predicated_Subtype_Use ("cannot use subtype& with non-static " & "predicate as case alternative", Choice, E, Suggest_Static => True); -- Static predicate case. The bounds are those of -- the given subtype. else Handle_Static_Predicate (E, Type_Low_Bound (E), Type_High_Bound (E)); end if; -- Not predicated subtype case elsif not Is_OK_Static_Subtype (E) then Process_Non_Static_Choice (Choice); else Check (Choice, Type_Low_Bound (E), Type_High_Bound (E)); end if; end if; -- Choice is a subtype indication elsif Kind = N_Subtype_Indication then Resolve_Discrete_Subtype_Indication (Choice, Expected_Type); if Etype (Choice) /= Any_Type then declare C : constant Node_Id := Constraint (Choice); R : constant Node_Id := Range_Expression (C); L : constant Node_Id := Low_Bound (R); H : constant Node_Id := High_Bound (R); begin E := Entity (Subtype_Mark (Choice)); if not Is_OK_Static_Subtype (E) then Process_Non_Static_Choice (Choice); else if Is_OK_Static_Expression (L) and then Is_OK_Static_Expression (H) then if Expr_Value (L) > Expr_Value (H) then Process_Empty_Choice (Choice); else if Is_Out_Of_Range (L, E) then Apply_Compile_Time_Constraint_Error (L, "static value out of range", CE_Range_Check_Failed); end if; if Is_Out_Of_Range (H, E) then Apply_Compile_Time_Constraint_Error (H, "static value out of range", CE_Range_Check_Failed); end if; end if; end if; -- Check applicable predicate values within the -- bounds of the given range. if Has_Static_Predicate (E) then Handle_Static_Predicate (E, L, H); else Check (Choice, L, H); end if; end if; end; end if; -- The others choice is only allowed for the last -- alternative and as its only choice. elsif Kind = N_Others_Choice then if not (Choice = First (Discrete_Choices (Alt)) and then Choice = Last (Discrete_Choices (Alt)) and then Alt = Last (Alternatives)) then Error_Msg_N ("the choice OTHERS must appear alone and last", Choice); return; end if; Others_Present := True; Others_Choice := Choice; -- Only other possibility is an expression else Check (Choice, Choice, Choice); end if; -- Move to next choice Next (Choice); end loop; Process_Associated_Node (Alt); end if; Next (Alt); end loop; -- Now we can create the Choice_Table, since we know how long -- it needs to be so we can allocate exactly the right length. declare Choice_Table : Choice_Table_Type (0 .. Num_Choices); begin -- Now copy the items we collected in the linked list into this -- newly allocated table (leave entry 0 unused for sorting). declare T : Link_Ptr; begin for J in 1 .. Num_Choices loop T := Choice_List; Choice_List := T.Nxt; Choice_Table (J) := T.Val; Free (T); end loop; end; Check_Choice_Set (Choice_Table, Bounds_Type, Subtyp, Others_Present or else (Choice_Type = Universal_Integer), N); -- If no others choice we are all done, otherwise we have one more -- step, which is to set the Others_Discrete_Choices field of the -- others choice (to contain all otherwise unspecified choices). -- Skip this if CE is known to be raised. if Others_Present and not Raises_CE then Expand_Others_Choice (Case_Table => Choice_Table, Others_Choice => Others_Choice, Choice_Type => Bounds_Type); end if; end; end Check_Choices; end Generic_Check_Choices; end Sem_Case;
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A 4 G . G N A T _ I N T -- -- -- -- B o d y -- -- -- -- Copyright (C) 1995-2012, Free Software Foundation, Inc. -- -- -- -- ASIS-for-GNAT is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2, or (at your option) any later -- -- version. ASIS-for-GNAT is distributed in the hope that it will be use- -- -- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- -- -- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General -- -- Public License for more details. You should have received a copy of the -- -- GNU General Public License distributed with ASIS-for-GNAT; see file -- -- COPYING. If not, write to the Free Software Foundation, 51 Franklin -- -- Street, Fifth Floor, Boston, MA 02110-1301, USA. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the -- -- Software Engineering Laboratory of the Swiss Federal Institute of -- -- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the -- -- Scientific Research Computer Center of Moscow State University (SRCC -- -- MSU), Russia, with funding partially provided by grants from the Swiss -- -- National Science Foundation and the Swiss Academy of Engineering -- -- Sciences. ASIS-for-GNAT is now maintained by AdaCore -- -- (http://www.adacore.com). -- -- -- ------------------------------------------------------------------------------ with Ada.Exceptions; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Text_IO; use Ada.Text_IO; with GNAT.Directory_Operations; use GNAT.Directory_Operations; with Asis.Errors; with Asis.Exceptions; use Asis.Exceptions; with Asis.Extensions; use Asis.Extensions; with A4G.A_Debug; use A4G.A_Debug; with A4G.A_Opt; use A4G.A_Opt; with A4G.A_Output; use A4G.A_Output; with A4G.Contt; use A4G.Contt; with A4G.Vcheck; use A4G.Vcheck; with Aspects; with Atree; with Csets; with Elists; with Fname; with Gnatvsn; with Lib; with Namet; with Nlists; with Opt; use Opt; with Repinfo; with Sem_Aux; with Sinput; with Stand; with Stringt; with Uintp; with Urealp; with Tree_IO; package body A4G.GNAT_Int is LT : String renames ASIS_Line_Terminator; Standard_GCC : constant String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("gcc"); ----------------- -- Create_Tree -- ----------------- procedure Create_Tree (Source_File : String_Access; Context : Context_Id; Is_Predefined : Boolean; Success : out Boolean) is begin if Is_Predefined then Compile (Source_File => Source_File, Args => (1 => GNAT_Flag), Success => Success, GCC => Gcc_To_Call (Context)); else Compile (Source_File => Source_File, Args => I_Options (Context), Success => Success, GCC => Gcc_To_Call (Context)); end if; exception when others => Raise_ASIS_Failed ("A4G.GNAT_Int.Create_Tree:" & LT & " check the path and environment settings for gcc!"); end Create_Tree; ------------- -- Execute -- ------------- function Execute (Program : String_Access; Args : Argument_List; Compiler_Out : String := ""; Display_Call : Boolean := A4G.A_Debug.Debug_Mode) return Boolean is Success : Boolean; Return_Code : Integer; Execute : String_Access := Program; begin if Execute = null then Execute := Standard_GCC; end if; if Display_Call then Put (Standard_Error, Execute.all); for J in Args'Range loop Put (Standard_Error, " "); Put (Standard_Error, Args (J).all); end loop; New_Line (Standard_Error); end if; if Execute = null then Ada.Exceptions.Raise_Exception (Program_Error'Identity, "A4G.GNAT_Int.Execute: Can not locate program to execute"); end if; if Compiler_Out /= "" then GNAT.OS_Lib.Spawn (Execute.all, Args, Compiler_Out, Success, Return_Code); Success := Return_Code = 0; else GNAT.OS_Lib.Spawn (Execute.all, Args, Success); end if; return Success; end Execute; ---------------------------------------------- -- General Interfaces between GNAT and ASIS -- ---------------------------------------------- function A_Time (T : Time_Stamp_Type) return Time is Year : Year_Number; Month : Month_Number; Day : Day_Number; Hours : Integer range 0 .. 23; Minutes : Integer range 0 .. 59; Seconds : Integer range 0 .. 59; Day_Time : Day_Duration; begin Split_Time_Stamp (TS => T, Year => Nat (Year), Month => Nat (Month), Day => Nat (Day), Hour => Nat (Hours), Minutes => Nat (Minutes), Seconds => Nat (Seconds)); Day_Time := Duration (Seconds + 60 * Minutes + 3600 * Hours); return Time_Of (Year, Month, Day, Day_Time); end A_Time; -------------------------------- -- Tree_In_With_Version_Check -- -------------------------------- procedure Tree_In_With_Version_Check (Desc : File_Descriptor; Cont : Context_Id; Success : out Boolean) is Cont_Mode : constant Context_Mode := Context_Processing_Mode (Cont); File_Closed : Boolean := False; ASIS_GNAT_V : constant String := Gnatvsn.Gnat_Version_String; First_A_Idx : Natural := ASIS_GNAT_V'First; Last_A_Idx : Natural; First_T_Idx : Natural; Last_T_Idx : Natural; begin Success := False; Tree_IO.Tree_Read_Initialize (Desc); Opt.Tree_Read; -- GNAT/ASIS version check first if Tree_ASIS_Version_Number /= Tree_IO.ASIS_Version_Number then Close (Desc, File_Closed); Ada.Exceptions.Raise_Exception (Program_Error'Identity, "Inconsistent versions of GNAT and ASIS"); end if; -- Check that ASIS Pro uses the tree created by GNAT Pro First_T_Idx := Tree_Version_String'First; if ASIS_GNAT_V (First_A_Idx .. First_A_Idx + 2) = "Pro" and then Tree_Version_String (First_T_Idx .. First_T_Idx + 2) /= "Pro" then Close (Desc, File_Closed); Ada.Exceptions.Raise_Exception (Program_Error'Identity, "ASIS Pro can be used with GNAT Pro only"); end if; if Strong_Version_Check then -- We check only the dates here! First_A_Idx := Index (Source => ASIS_GNAT_V, Pattern => "(") + 1; First_T_Idx := Index (Source => Tree_Version_String.all, Pattern => "(") + 1; Last_A_Idx := Index (Source => ASIS_GNAT_V, Pattern => ")") - 1; if Index (Source => ASIS_GNAT_V, Pattern => "-") /= 0 then Last_A_Idx := Index (Source => ASIS_GNAT_V, Pattern => "-") - 1; end if; Last_T_Idx := Index (Source => Tree_Version_String.all, Pattern => ")") - 1; if Index (Source => Tree_Version_String.all, Pattern => "-") /= 0 then Last_T_Idx := Index (Source => Tree_Version_String.all, Pattern => "-") - 1; end if; if ASIS_GNAT_V (First_A_Idx .. Last_A_Idx) /= Tree_Version_String (First_T_Idx .. Last_T_Idx) then Close (Desc, File_Closed); Ada.Exceptions.Raise_Exception (Program_Error'Identity, "Inconsistent versions of GNAT [" & Tree_Version_String.all & "] and ASIS [" & ASIS_GNAT_V & ']'); end if; end if; -- Check if we are in Ada 2012 mode and need aspects... -- if Opt.Ada_Version_Config = Ada_2012 then -- -- For now, reading aspects is protected by the debug '.A' flag -- Debug.Debug_Flag_Dot_AA := True; -- end if; if Operating_Mode /= Check_Semantics then if Cont_Mode = One_Tree then -- If in one-tree mode we can not read the only tree we have, -- there is no reason to continue, so raising an exception -- is the only choice: Close (Desc, File_Closed); -- We did not check File_Closed here, because the fact that the -- tree is not compile-only seems to be more important for ASIS Set_Error_Status (Status => Asis.Errors.Use_Error, Diagnosis => "Asis.Ada_Environments.Open:" & ASIS_Line_Terminator & "tree file " & Base_Name (A_Name_Buffer (1 .. A_Name_Len)) & " is not compile-only"); raise ASIS_Failed; elsif Cont_Mode = N_Trees or else Cont_Mode = All_Trees then -- no need to read the rest of this tree file, but -- we can continue even if we can not read some trees... ASIS_Warning (Message => "Asis.Ada_Environments.Open: " & ASIS_Line_Terminator & "tree file " & Base_Name (A_Name_Buffer (1 .. A_Name_Len)) & " is not compile-only, ignored", Error => Asis.Errors.Use_Error); end if; -- debug stuff... if (Debug_Flag_O or else Debug_Lib_Model or else Debug_Mode) and then Cont_Mode /= One_Tree and then Cont_Mode /= N_Trees then Put (Standard_Error, "The tree file "); Put (Standard_Error, Base_Name (A_Name_Buffer (1 .. A_Name_Len))); Put (Standard_Error, " is not compile-only"); New_Line (Standard_Error); end if; else Atree.Tree_Read; Elists.Tree_Read; Fname.Tree_Read; Lib.Tree_Read; Namet.Tree_Read; Nlists.Tree_Read; Sem_Aux.Tree_Read; Sinput.Tree_Read; Stand.Tree_Read; Stringt.Tree_Read; Uintp.Tree_Read; Urealp.Tree_Read; Repinfo.Tree_Read; Aspects.Tree_Read; Csets.Initialize; -- debug stuff... if Debug_Flag_O or else Debug_Lib_Model or else Debug_Mode then Put (Standard_Error, "The tree file "); Put (Standard_Error, Base_Name (A_Name_Buffer (1 .. A_Name_Len))); Put (Standard_Error, " is OK"); New_Line (Standard_Error); end if; Success := True; end if; Close (Desc, File_Closed); if not File_Closed then Raise_ASIS_Failed (Diagnosis => "Asis.Ada_Environments.Open: " & "Can not close tree file: " & Base_Name (A_Name_Buffer (1 .. A_Name_Len)) & ASIS_Line_Terminator & "disk is full or file may be used by other program", Stat => Asis.Errors.Data_Error); end if; exception when Tree_IO.Tree_Format_Error => Close (Desc, File_Closed); Ada.Exceptions.Raise_Exception (Program_Error'Identity, "Inconsistent versions of GNAT and ASIS"); end Tree_In_With_Version_Check; end A4G.GNAT_Int;
with System.UTF_Conversions.From_8_To_16; with System.UTF_Conversions.From_8_To_32; package body System.WCh_StW is procedure String_To_Wide_String ( S : String; R : out Wide_String; L : out Natural; EM : WC_Encoding_Method) is pragma Unreferenced (EM); begin UTF_Conversions.From_8_To_16.Convert (S, R, L); end String_To_Wide_String; procedure String_To_Wide_Wide_String ( S : String; R : out Wide_Wide_String; L : out Natural; EM : WC_Encoding_Method) is pragma Unreferenced (EM); begin UTF_Conversions.From_8_To_32.Convert (S, R, L); end String_To_Wide_Wide_String; end System.WCh_StW;
pragma License (Unrestricted); with Ada.Numerics.Generic_Real_Arrays; package Ada.Numerics.Long_Real_Arrays is new Generic_Real_Arrays (Long_Float); pragma Pure (Ada.Numerics.Long_Real_Arrays);
-- This package has been generated automatically by GNATtest. -- You are allowed to add your code to the bodies of test routines. -- Such changes will be kept during further regeneration of this file. -- All code placed outside of test routine bodies will be lost. The -- code intended to set up and tear down the test environment should be -- placed into Stories.Test_Data. with AUnit.Assertions; use AUnit.Assertions; with System.Assertions; -- begin read only -- id:2.2/00/ -- -- This section can be used to add with clauses if necessary. -- -- end read only -- begin read only -- end read only package body Stories.Test_Data.Tests is -- begin read only -- id:2.2/01/ -- -- This section can be used to add global variables and other elements. -- -- end read only -- begin read only -- end read only -- begin read only procedure Wrap_Test_StartStory_edaf80_b2037e (FactionName: Unbounded_String; Condition: StartConditionType) is begin begin pragma Assert(FactionName /= Null_Unbounded_String); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(stories.ads:0):Test_StartStory test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Stories.StartStory (FactionName, Condition); begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(stories.ads:0:):Test_StartStory test commitment violated"); end; end Wrap_Test_StartStory_edaf80_b2037e; -- end read only -- begin read only procedure Test_StartStory_test_startstory(Gnattest_T: in out Test); procedure Test_StartStory_edaf80_b2037e(Gnattest_T: in out Test) renames Test_StartStory_test_startstory; -- id:2.2/edaf80b58d7d34e7/StartStory/1/0/test_startstory/ procedure Test_StartStory_test_startstory(Gnattest_T: in out Test) is procedure StartStory (FactionName: Unbounded_String; Condition: StartConditionType) renames Wrap_Test_StartStory_edaf80_b2037e; -- end read only pragma Unreferenced(Gnattest_T); begin loop StartStory(To_Unbounded_String("Undead"), DROPITEM); exit when CurrentStory.Index /= Null_Unbounded_String; end loop; Assert(True, "This test can only crash or hang."); -- begin read only end Test_StartStory_test_startstory; -- end read only -- begin read only procedure Wrap_Test_ClearCurrentStory_0648d1_6d4eff is begin begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(stories.ads:0):Test_ClearCurrentStory test requirement violated"); end; GNATtest_Generated.GNATtest_Standard.Stories.ClearCurrentStory; begin pragma Assert(CurrentStory.Index = Null_Unbounded_String); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(stories.ads:0:):Test_ClearCurrentStory test commitment violated"); end; end Wrap_Test_ClearCurrentStory_0648d1_6d4eff; -- end read only -- begin read only procedure Test_ClearCurrentStory_test_clearcurrentstory (Gnattest_T: in out Test); procedure Test_ClearCurrentStory_0648d1_6d4eff (Gnattest_T: in out Test) renames Test_ClearCurrentStory_test_clearcurrentstory; -- id:2.2/0648d16dba1bb959/ClearCurrentStory/1/0/test_clearcurrentstory/ procedure Test_ClearCurrentStory_test_clearcurrentstory (Gnattest_T: in out Test) is procedure ClearCurrentStory renames Wrap_Test_ClearCurrentStory_0648d1_6d4eff; -- end read only pragma Unreferenced(Gnattest_T); OldStory: constant CurrentStory_Data := CurrentStory; begin ClearCurrentStory; Assert (CurrentStory.Index = Null_Unbounded_String, "Failed to clear current story."); CurrentStory := OldStory; -- begin read only end Test_ClearCurrentStory_test_clearcurrentstory; -- end read only -- begin read only function Wrap_Test_ProgressStory_80c408_14aed6 (NextStep: Boolean := False) return Boolean is begin declare Test_ProgressStory_80c408_14aed6_Result: constant Boolean := GNATtest_Generated.GNATtest_Standard.Stories.ProgressStory (NextStep); begin return Test_ProgressStory_80c408_14aed6_Result; end; end Wrap_Test_ProgressStory_80c408_14aed6; -- end read only -- begin read only procedure Test_ProgressStory_test_progressstory(Gnattest_T: in out Test); procedure Test_ProgressStory_80c408_14aed6(Gnattest_T: in out Test) renames Test_ProgressStory_test_progressstory; -- id:2.2/80c4088c0068e59a/ProgressStory/1/0/test_progressstory/ procedure Test_ProgressStory_test_progressstory(Gnattest_T: in out Test) is function ProgressStory(NextStep: Boolean := False) return Boolean renames Wrap_Test_ProgressStory_80c408_14aed6; -- end read only pragma Unreferenced(Gnattest_T); begin if ProgressStory then null; end if; Assert(True, "This test can only crash."); -- begin read only end Test_ProgressStory_test_progressstory; -- end read only -- begin read only function Wrap_Test_GetCurrentStoryText_b9136f_8f71b5 return Unbounded_String is begin declare Test_GetCurrentStoryText_b9136f_8f71b5_Result: constant Unbounded_String := GNATtest_Generated.GNATtest_Standard.Stories.GetCurrentStoryText; begin return Test_GetCurrentStoryText_b9136f_8f71b5_Result; end; end Wrap_Test_GetCurrentStoryText_b9136f_8f71b5; -- end read only -- begin read only procedure Test_GetCurrentStoryText_tets_getcurrentstorytext (Gnattest_T: in out Test); procedure Test_GetCurrentStoryText_b9136f_8f71b5 (Gnattest_T: in out Test) renames Test_GetCurrentStoryText_tets_getcurrentstorytext; -- id:2.2/b9136fdf6bb9efe6/GetCurrentStoryText/1/0/tets_getcurrentstorytext/ procedure Test_GetCurrentStoryText_tets_getcurrentstorytext (Gnattest_T: in out Test) is function GetCurrentStoryText return Unbounded_String renames Wrap_Test_GetCurrentStoryText_b9136f_8f71b5; -- end read only pragma Unreferenced(Gnattest_T); begin Assert (GetCurrentStoryText /= Null_Unbounded_String, "Failed to get text of current story step."); -- begin read only end Test_GetCurrentStoryText_tets_getcurrentstorytext; -- end read only -- begin read only function Wrap_Test_GetStepData_8e5120_456123 (FinishData: StepData_Container.Vector; Name: String) return Unbounded_String is begin begin pragma Assert(Name'Length > 0); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "req_sloc(stories.ads:0):Test_GetStepData test requirement violated"); end; declare Test_GetStepData_8e5120_456123_Result: constant Unbounded_String := GNATtest_Generated.GNATtest_Standard.Stories.GetStepData (FinishData, Name); begin begin pragma Assert(True); null; exception when System.Assertions.Assert_Failure => AUnit.Assertions.Assert (False, "ens_sloc(stories.ads:0:):Test_GetStepData test commitment violated"); end; return Test_GetStepData_8e5120_456123_Result; end; end Wrap_Test_GetStepData_8e5120_456123; -- end read only -- begin read only procedure Test_GetStepData_test_getstepdata(Gnattest_T: in out Test); procedure Test_GetStepData_8e5120_456123(Gnattest_T: in out Test) renames Test_GetStepData_test_getstepdata; -- id:2.2/8e51209e243a2f63/GetStepData/1/0/test_getstepdata/ procedure Test_GetStepData_test_getstepdata(Gnattest_T: in out Test) is function GetStepData (FinishData: StepData_Container.Vector; Name: String) return Unbounded_String renames Wrap_Test_GetStepData_8e5120_456123; -- end read only pragma Unreferenced(Gnattest_T); begin Assert (GetStepData (Stories_List(To_Unbounded_String("1")).Steps(1).FinishData, "condition") = To_Unbounded_String("Rhetoric"), "Failed to get finish data of selected step."); Assert (GetStepData (Stories_List(To_Unbounded_String("1")).Steps(1).FinishData, "sdfdsf") = Null_Unbounded_String, "Failed to not get non existing finish data of selected step."); -- begin read only end Test_GetStepData_test_getstepdata; -- end read only -- begin read only procedure Wrap_Test_GetStoryLocation_eee8ee_b0f396 (StoryX: out Map_X_Range; StoryY: out Map_Y_Range) is begin GNATtest_Generated.GNATtest_Standard.Stories.GetStoryLocation (StoryX, StoryY); end Wrap_Test_GetStoryLocation_eee8ee_b0f396; -- end read only -- begin read only procedure Test_GetStoryLocation_test_getstorylocation (Gnattest_T: in out Test); procedure Test_GetStoryLocation_eee8ee_b0f396 (Gnattest_T: in out Test) renames Test_GetStoryLocation_test_getstorylocation; -- id:2.2/eee8eefa7464e271/GetStoryLocation/1/0/test_getstorylocation/ procedure Test_GetStoryLocation_test_getstorylocation (Gnattest_T: in out Test) is procedure GetStoryLocation (StoryX: out Map_X_Range; StoryY: out Map_Y_Range) renames Wrap_Test_GetStoryLocation_eee8ee_b0f396; -- end read only pragma Unreferenced(Gnattest_T); X, Y: Positive := 1; begin GetStoryLocation(X, Y); Assert(True, "This test can only crash."); -- begin read only end Test_GetStoryLocation_test_getstorylocation; -- end read only -- begin read only -- id:2.2/02/ -- -- This section can be used to add elaboration code for the global state. -- begin -- end read only null; -- begin read only -- end read only end Stories.Test_Data.Tests;
with Tkmrpc.Servers.Ike; with Tkmrpc.Results; with Tkmrpc.Request.Ike.Nc_Create.Convert; with Tkmrpc.Response.Ike.Nc_Create.Convert; package body Tkmrpc.Operation_Handlers.Ike.Nc_Create is ------------------------------------------------------------------------- procedure Handle (Req : Request.Data_Type; Res : out Response.Data_Type) is Specific_Req : Request.Ike.Nc_Create.Request_Type; Specific_Res : Response.Ike.Nc_Create.Response_Type; begin Specific_Res := Response.Ike.Nc_Create.Null_Response; Specific_Req := Request.Ike.Nc_Create.Convert.From_Request (S => Req); if Specific_Req.Data.Nc_Id'Valid and Specific_Req.Data.Nonce_Length'Valid then Servers.Ike.Nc_Create (Result => Specific_Res.Header.Result, Nc_Id => Specific_Req.Data.Nc_Id, Nonce_Length => Specific_Req.Data.Nonce_Length, Nonce => Specific_Res.Data.Nonce); Res := Response.Ike.Nc_Create.Convert.To_Response (S => Specific_Res); else Res.Header.Result := Results.Invalid_Parameter; end if; end Handle; end Tkmrpc.Operation_Handlers.Ike.Nc_Create;
-- { dg-do compile } package body TF_Interface_1 is procedure Get_It (Handle : Stream_Access; It : out CF_Interface_1'class) is begin CF_Interface_1'Class'Read (Handle, It); end; end;
with Ada.Text_IO; with Ada.Integer_Text_IO; with Ada.Containers.Vectors; use Ada.Text_IO; use Ada.Integer_Text_IO; use Ada.Containers; procedure Euler is package Long_Integer_Vectors is new Vectors(Natural, Long_Integer); package Long_IO is new Ada.Text_IO.Integer_IO(Long_Integer); use Long_IO; function Prime_Factors(N : in Long_Integer) return Long_Integer_Vectors.Vector is Result : Long_Integer_Vectors.Vector; Found : Boolean := False; V : Long_Integer := 2; I : Long_Integer := 2; begin Factor_Loop : while I < (N - 1) and Found = False loop if (N mod I) = 0 then Found := True; V := I; end if; I := I + 1; end loop Factor_Loop; if Found = True then Long_Integer_Vectors.Append(Result, V); Long_Integer_Vectors.Append(Result, Prime_Factors(N / V)); else Long_Integer_Vectors.Append(Result, N); end if; return Result; end Prime_Factors; begin declare Factors : Long_Integer_Vectors.Vector; Cursor : Long_Integer_Vectors.Cursor; Max : Long_Integer; begin Factors := Prime_Factors(600851475143); Cursor := Long_Integer_Vectors.First(Factors); Max := Long_Integer_Vectors.Element(Cursor); Cursor := Long_Integer_Vectors.Next(Cursor); while Long_Integer_Vectors.Has_Element(Cursor) loop if Long_Integer_Vectors.Element(Cursor) > Max then Max := Long_Integer_Vectors.Element(Cursor); end if; Cursor := Long_Integer_Vectors.Next(Cursor); end loop; Put(Item => Max, Width => 1); New_Line; end; end Euler;
package body Logger is task body LoggerReceiver is subtype RangeN is Natural range 1..n; subtype RangeNE is Natural range 0..(n-1); subtype RangeD is Natural range 1..d; subtype RangeK is Natural range 1..k; -- gather stats type NodeStats is array (RangeN, RangeK) of Boolean; type pNodeStats is access NodeStats; type MessageStats is array (RangeK, RangeN) of Boolean; type pMessageStats is access MessageStats; nodeSeen: pNodeStats := new NodeStats; messageVisited: pMessageStats := new MessageStats; exitTask: Boolean := False; begin loop select accept Log(message: string) do PrintBounded(message); end Log; or accept LogMessageInTransit(msg: Natural; node: Natural) do if msg in RangeK'Range and node in RangeNE'Range then nodeSeen(node+1, msg) := True; messageVisited(msg, node+1) := True; PrintBounded("message" & Natural'Image(msg) & " has arrived at node" & Natural'Image(node)); end if; end LogMessageInTransit; or accept Stop do PrintBounded(""); PrintBounded("Stats:"); PrintBounded(""); for I in RangeK'Range loop PrintBounded("message" & Natural'Image(I) & " visited:"); for J in RangeN'Range loop if messageVisited(I, J) then PrintBounded(" node" & Natural'Image(J-1)); end if; end loop; end loop; PrintBounded(""); for I in RangeN'Range loop PrintBounded("node" & Natural'Image(I-1) & " seen:"); for J in RangeK'Range loop if nodeSeen(I, J) then PrintBounded(" message" & Natural'Image(J)); end if; end loop; end loop; exitTask := True; end Stop; end select; if exitTask then exit; end if; end loop; end LoggerReceiver; end Logger;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with System.Storage_Pools.Subpools; with Ada.Containers.Vectors; with Program.Compilation_Units; with Program.Compilations; with Program.Elements; with Program.Lexical_Elements; limited private with Program.Parsers.Nodes; package Program.Parsers is pragma Preelaborate; package Element_Vectors is new Ada.Containers.Vectors (Positive, Program.Elements.Element_Access, Program.Elements."="); package Unit_Vectors is new Ada.Containers.Vectors (Positive, Program.Compilation_Units.Compilation_Unit_Access, Program.Compilation_Units."="); procedure Parse (Compilation : not null Program.Compilations.Compilation_Access; Tokens : not null Lexical_Elements.Lexical_Element_Vector_Access; Subpool : not null System.Storage_Pools.Subpools.Subpool_Handle; Units : out Unit_Vectors.Vector; Pragmas : out Element_Vectors.Vector); private type Parse_Context is record Factory : not null access Program.Parsers.Nodes.Node_Factory; Tokens : not null Lexical_Elements.Lexical_Element_Vector_Access; Index : Positive := 1; end record; end Program.Parsers;
-- { dg-do compile } package Null_Aggr_Bug is type Rec1 is null record; type Rec2 is tagged null record; type Rec3 is new Rec2 with null record; X1 : Rec1 := (null record); Y1 : Rec1 := (others => <>); X2 : Rec2 := (null record); Y2 : Rec2 := (others => <>); X3 : Rec3 := (null record); Y3 : Rec3 := (others => <>); Z3 : Rec3 := (Rec2 with others => <>); end Null_Aggr_Bug;
package body Loop_Optimization4_Pkg is procedure Add (Phrase : String) is begin if Debug_Buffer_Len = Max_Debug_Buffer_Len then return; end if; for I in Phrase'Range loop Debug_Buffer_Len := Debug_Buffer_Len + 1; Debug_Buffer (Debug_Buffer_Len) := Phrase (I); if Debug_Buffer_Len = Max_Debug_Buffer_Len then exit; end if; end loop; end Add; end Loop_Optimization4_Pkg;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2011, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.Atomics.Counters; with Matreshka.Internals.Strings; with Matreshka.Internals.Unicode.Ucd; with Matreshka.Internals.Utf16; package Matreshka.Internals.Regexps is pragma Preelaborate; ------------- -- Pattern -- ------------- -- Abstract Syntax Tree type General_Category_Flags is array (Matreshka.Internals.Unicode.Ucd.General_Category) of Boolean; pragma Pack (General_Category_Flags); type Property_Kinds is (None, General_Category, Binary); type Property_Value (Kind : Property_Kinds := None) is record case Kind is when None => null; when General_Category => GC_Flags : General_Category_Flags; when Binary => Property : Matreshka.Internals.Unicode.Ucd.Boolean_Properties; end case; end record; type Node_List is record Parent : Natural; Head : Natural; Tail : Natural; end record; type Node_List_Count is new Natural; subtype Node_List_Index is Node_List_Count range 1 .. Node_List_Count'Last; type Node_Kinds is (N_None, N_Subexpression, N_Match_Any, N_Match_Code, N_Match_Property, N_Member_Code, N_Member_Range, N_Member_Property, N_Character_Class, N_Multiplicity, N_Alternation, N_Anchor); type Node (Kind : Node_Kinds := N_None) is record case Kind is when N_None => null; when others => List : Node_List_Count; Previous : Natural; Next : Natural; -- Doubly linked list of nodes. case Kind is when N_None => null; when N_Subexpression => Subexpression : Node_List_Count; Capture : Boolean; Index : Natural; when N_Match_Any => null; when N_Match_Code | N_Member_Code => Code : Matreshka.Internals.Unicode.Code_Point; -- Code point to match or code point as member of character -- class. when N_Match_Property | N_Member_Property => Value : Property_Value; Negative : Boolean; when N_Member_Range => Low : Matreshka.Internals.Unicode.Code_Point; High : Matreshka.Internals.Unicode.Code_Point; -- Range of code points as member of character class when N_Character_Class => Negated : Boolean; Members : Node_List_Count; when N_Multiplicity => Item : Node_List_Count; -- Link to expression Greedy : Boolean; Lower : Natural; Upper : Natural; when N_Alternation => Preferred : Node_List_Count; Fallback : Node_List_Count; when N_Anchor => Start_Of_Line : Boolean; End_Of_Line : Boolean; end case; end case; end record; type AST_Array is array (Positive range <>) of Node; type Node_List_Array is array (Node_List_Index range <>) of Node_List; type Shared_Pattern (Size : Natural; List_Size : Node_List_Count) is limited record Counter : Matreshka.Atomics.Counters.Counter; -- Atomic reference counter. AST : AST_Array (1 .. Size); List : Node_List_Array (1 .. List_Size); Last : Natural := 0; Last_List : Node_List_Count := 0; Start : Node_List_Count := 0; Captures : Natural := 0; end record; type Shared_Pattern_Access is access all Shared_Pattern; Empty_Shared_Pattern : aliased Shared_Pattern (0, 0); procedure Reference (Item : not null Shared_Pattern_Access); procedure Dereference (Item : in out Shared_Pattern_Access); ----------- -- Match -- ----------- type Shared_String_Array is array (Natural range <>) of aliased Matreshka.Internals.Strings.Shared_String_Access; type Slice is record First_Position : Matreshka.Internals.Utf16.Utf16_String_Index; First_Index : Positive; Next_Position : Matreshka.Internals.Utf16.Utf16_String_Index; Next_Index : Positive; end record; -- Slice represent slice in the source Shared_String. Next points to the -- first character after the slice. type Slice_Array is array (Natural range <>) of Slice; type Shared_Match (Groups : Natural) is limited record Counter : Matreshka.Atomics.Counters.Counter; -- Atomic reference counter. Is_Matched : Boolean := False; -- Flag is object contains match information or not. Source : Matreshka.Internals.Strings.Shared_String_Access; -- Reference to source string. Number : Natural; -- Number of actual subexpression captures. Slices : Slice_Array (0 .. Groups); -- Slices of captured data. Captures : Shared_String_Array (0 .. Groups); pragma Volatile (Captures); -- Actual captured data. end record; -- Shared match is a results of the match of the string to pattern. When -- shared object is constructed, only slices information is filled. Actual -- captures is constructed lazy on request. type Shared_Match_Access is access all Shared_Match; Empty_Shared_Match : aliased Shared_Match := (Groups => 0, Counter => <>, Is_Matched => False, Source => null, Number => 0, Slices => (others => (0, 1, 0, 1)), Captures => (others => null)); procedure Reference (Item : not null Shared_Match_Access); procedure Dereference (Item : in out Shared_Match_Access); function Capture (Item : not null Shared_Match_Access; Number : Natural) return not null Matreshka.Internals.Strings.Shared_String_Access; end Matreshka.Internals.Regexps;
package agar.gui.widget.separator is type type_t is (SEPARATOR_HORIZ, SEPARATOR_VERT); for type_t use (SEPARATOR_HORIZ => 0, SEPARATOR_VERT => 1); for type_t'size use c.unsigned'size; pragma convention (c, type_t); type separator_t is limited private; type separator_access_t is access all separator_t; pragma convention (c, separator_access_t); function allocate (parent : widget_access_t; separator_type : type_t) return separator_access_t; pragma import (c, allocate, "AG_SeparatorNew"); function allocate_spacer (parent : widget_access_t; separator_type : type_t) return separator_access_t; pragma import (c, allocate_spacer, "AG_SpacerNew"); procedure set_padding (separator : separator_access_t; pixels : natural); pragma inline (set_padding); function widget (separator : separator_access_t) return widget_access_t; pragma inline (widget); private type separator_t is record widget : aliased widget_t; sep_type : type_t; padding : c.unsigned; visible : c.int; end record; pragma convention (c, separator_t); end agar.gui.widget.separator;
-- C85005A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK THAT A VARIABLE CREATED BY AN OBJECT DECLARATION CAN BE -- RENAMED AND HAS THE CORRECT VALUE, AND THAT THE NEW NAME CAN -- BE USED IN AN ASSIGNMENT STATEMENT AND PASSED ON AS AN ACTUAL -- SUBPROGRAM OR ENTRY 'IN OUT' OR 'OUT' PARAMETER, AND AS AN -- ACTUAL GENERIC 'IN OUT' PARAMETER, AND THAT WHEN THE VALUE OF -- THE RENAMED VARIABLE IS CHANGED, THE NEW VALUE IS REFLECTED -- BY THE VALUE OF THE NEW NAME. -- HISTORY: -- JET 03/15/88 CREATED ORIGINAL TEST. WITH REPORT; USE REPORT; PROCEDURE C85005A IS TYPE ARRAY1 IS ARRAY (POSITIVE RANGE <>) OF INTEGER; TYPE RECORD1 (D : INTEGER) IS RECORD FIELD1 : INTEGER := 1; END RECORD; TYPE POINTER1 IS ACCESS INTEGER; PACKAGE PACK1 IS K1 : INTEGER := 0; TYPE PRIVY IS PRIVATE; ZERO : CONSTANT PRIVY; ONE : CONSTANT PRIVY; TWO : CONSTANT PRIVY; THREE : CONSTANT PRIVY; FOUR : CONSTANT PRIVY; FIVE : CONSTANT PRIVY; FUNCTION IDENT (I : PRIVY) RETURN PRIVY; FUNCTION NEXT (I : PRIVY) RETURN PRIVY; PRIVATE TYPE PRIVY IS RANGE 0..127; ZERO : CONSTANT PRIVY := 0; ONE : CONSTANT PRIVY := 1; TWO : CONSTANT PRIVY := 2; THREE : CONSTANT PRIVY := 3; FOUR : CONSTANT PRIVY := 4; FIVE : CONSTANT PRIVY := 5; END PACK1; TASK TYPE TASK1 IS ENTRY ASSIGN (J : IN INTEGER); ENTRY VALU (J : OUT INTEGER); ENTRY NEXT; ENTRY STOP; END TASK1; TASK TYPE TASK2 IS ENTRY ENTRY1 (TI1 : OUT INTEGER; TA1 : OUT ARRAY1; TR1 : OUT RECORD1; TP1 : IN OUT POINTER1; TV1 : IN OUT PACK1.PRIVY; TT1 : IN OUT TASK1; TK1 : IN OUT INTEGER); END TASK2; I1 : INTEGER := 0; A1 : ARRAY1(1..3) := (OTHERS => 0); R1 : RECORD1(1) := (D => 1, FIELD1 => 0); P1 : POINTER1 := NEW INTEGER'(0); V1 : PACK1.PRIVY := PACK1.ZERO; T1 : TASK1; XI1 : INTEGER RENAMES I1; XA1 : ARRAY1 RENAMES A1; XR1 : RECORD1 RENAMES R1; XP1 : POINTER1 RENAMES P1; XV1 : PACK1.PRIVY RENAMES V1; XT1 : TASK1 RENAMES T1; XK1 : INTEGER RENAMES PACK1.K1; I : INTEGER; CHK_TASK : TASK2; GENERIC GI1 : IN OUT INTEGER; GA1 : IN OUT ARRAY1; GR1 : IN OUT RECORD1; GP1 : IN OUT POINTER1; GV1 : IN OUT PACK1.PRIVY; GT1 : IN OUT TASK1; GK1 : IN OUT INTEGER; PACKAGE GENERIC1 IS END GENERIC1; FUNCTION IDENT (P : POINTER1) RETURN POINTER1 IS BEGIN IF EQUAL (3,3) THEN RETURN P; ELSE RETURN NULL; END IF; END IDENT; PROCEDURE PROC1 (PI1 : IN OUT INTEGER; PA1 : IN OUT ARRAY1; PR1 : IN OUT RECORD1; PP1 : OUT POINTER1; PV1 : OUT PACK1.PRIVY; PT1 : IN OUT TASK1; PK1 : OUT INTEGER) IS BEGIN PI1 := PI1 + 1; PA1 := (PA1(1)+1, PA1(2)+1, PA1(3)+1); PR1 := (D => 1, FIELD1 => PR1.FIELD1 + 1); PP1 := NEW INTEGER'(P1.ALL + 1); PV1 := PACK1.NEXT(V1); PT1.NEXT; PK1 := PACK1.K1 + 1; END PROC1; PACKAGE BODY PACK1 IS FUNCTION IDENT (I : PRIVY) RETURN PRIVY IS BEGIN IF EQUAL(3,3) THEN RETURN I; ELSE RETURN PRIVY'(0); END IF; END IDENT; FUNCTION NEXT (I : PRIVY) RETURN PRIVY IS BEGIN RETURN I+1; END NEXT; END PACK1; PACKAGE BODY GENERIC1 IS BEGIN GI1 := GI1 + 1; GA1 := (GA1(1)+1, GA1(2)+1, GA1(3)+1); GR1 := (D => 1, FIELD1 => GR1.FIELD1+1); GP1 := NEW INTEGER'(GP1.ALL + 1); GV1 := PACK1.NEXT(GV1); GT1.NEXT; GK1 := GK1 + 1; END GENERIC1; TASK BODY TASK1 IS TASK_VALUE : INTEGER := 0; ACCEPTING_ENTRIES : BOOLEAN := TRUE; BEGIN WHILE ACCEPTING_ENTRIES LOOP SELECT ACCEPT ASSIGN (J : IN INTEGER) DO TASK_VALUE := J; END ASSIGN; OR ACCEPT VALU (J : OUT INTEGER) DO J := TASK_VALUE; END VALU; OR ACCEPT NEXT DO TASK_VALUE := TASK_VALUE + 1; END NEXT; OR ACCEPT STOP DO ACCEPTING_ENTRIES := FALSE; END STOP; END SELECT; END LOOP; END TASK1; TASK BODY TASK2 IS BEGIN ACCEPT ENTRY1 (TI1 : OUT INTEGER; TA1 : OUT ARRAY1; TR1 : OUT RECORD1; TP1 : IN OUT POINTER1; TV1 : IN OUT PACK1.PRIVY; TT1 : IN OUT TASK1; TK1 : IN OUT INTEGER) DO TI1 := I1 + 1; TA1 := (A1(1)+1, A1(2)+1, A1(3)+1); TR1 := (D => 1, FIELD1 => R1.FIELD1 + 1); TP1 := NEW INTEGER'(TP1.ALL + 1); TV1 := PACK1.NEXT(TV1); TT1.NEXT; TK1 := TK1 + 1; END ENTRY1; END TASK2; BEGIN TEST ("C85005A", "CHECK THAT A VARIABLE CREATED BY AN OBJECT " & "DECLARATION CAN BE RENAMED AND HAS THE " & "CORRECT VALUE, AND THAT THE NEW NAME CAN " & "BE USED IN AN ASSIGNMENT STATEMENT " & "AND PASSED ON AS AN ACTUAL SUBPROGRAM OR " & "ENTRY 'IN OUT' OR 'OUT' PARAMETER, AND AS AN " & "ACTUAL GENERIC 'IN OUT' PARAMETER, AND THAT " & "WHEN THE VALUE OF THE RENAMED VARIABLE IS " & "CHANGED, THE NEW VALUE IS REFLECTED BY THE " & "VALUE OF THE NEW NAME"); DECLARE PACKAGE GENPACK1 IS NEW GENERIC1 (XI1, XA1, XR1, XP1, XV1, XT1, XK1); BEGIN NULL; END; IF XI1 /= IDENT_INT(1) THEN FAILED ("INCORRECT VALUE OF XI1 (1)"); END IF; IF XA1 /= (IDENT_INT(1),IDENT_INT(1),IDENT_INT(1)) THEN FAILED ("INCORRECT VALUE OF XA1 (1)"); END IF; IF XR1 /= (D => 1, FIELD1 => IDENT_INT(1)) THEN FAILED ("INCORRECT VALUE OF XR1 (1)"); END IF; IF XP1 /= IDENT(P1) OR XP1.ALL /= IDENT_INT(1) THEN FAILED ("INCORRECT VALUE OF XP1 (1)"); END IF; IF PACK1."/=" (XV1, PACK1.IDENT(PACK1.ONE)) THEN FAILED ("INCORRECT VALUE OF XV1 (1)"); END IF; XT1.VALU(I); IF I /= IDENT_INT(1) THEN FAILED ("INCORRECT RETURN VALUE OF XT1.VALU (1)"); END IF; IF XK1 /= IDENT_INT(1) THEN FAILED ("INCORRECT VALUE OF XK1 (1)"); END IF; PROC1(XI1, XA1, XR1, XP1, XV1, XT1, XK1); IF XI1 /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE OF XI1 (2)"); END IF; IF XA1 /= (IDENT_INT(2),IDENT_INT(2),IDENT_INT(2)) THEN FAILED ("INCORRECT VALUE OF XA1 (2)"); END IF; IF XR1 /= (D => 1, FIELD1 => IDENT_INT(2)) THEN FAILED ("INCORRECT VALUE OF XR1 (2)"); END IF; IF XP1 /= IDENT(P1) OR XP1.ALL /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE OF XP1 (2)"); END IF; IF PACK1."/=" (XV1, PACK1.IDENT(PACK1.TWO)) THEN FAILED ("INCORRECT VALUE OF XV1 (2)"); END IF; XT1.VALU(I); IF I /= IDENT_INT(2) THEN FAILED ("INCORRECT RETURN VALUE FROM XT1.VALU (2)"); END IF; IF XK1 /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE OF XK1 (2)"); END IF; CHK_TASK.ENTRY1(XI1, XA1, XR1, XP1, XV1, XT1, XK1); IF XI1 /= IDENT_INT(3) THEN FAILED ("INCORRECT VALUE OF XI1 (3)"); END IF; IF XA1 /= (IDENT_INT(3),IDENT_INT(3),IDENT_INT(3)) THEN FAILED ("INCORRECT VALUE OF XA1 (3)"); END IF; IF XR1 /= (D => 1, FIELD1 => IDENT_INT(3)) THEN FAILED ("INCORRECT VALUE OF XR1 (3)"); END IF; IF XP1 /= IDENT(P1) OR XP1.ALL /= IDENT_INT(3) THEN FAILED ("INCORRECT VALUE OF XP1 (3)"); END IF; IF PACK1."/=" (XV1, PACK1.IDENT(PACK1.THREE)) THEN FAILED ("INCORRECT VALUE OF XV1 (3)"); END IF; XT1.VALU(I); IF I /= IDENT_INT(3) THEN FAILED ("INCORRECT RETURN VALUE OF XT1.VALU (3)"); END IF; IF XK1 /= IDENT_INT(3) THEN FAILED ("INCORRECT VALUE OF XK1 (3)"); END IF; XI1 := XI1 + 1; XA1 := (XA1(1)+1, XA1(2)+1, XA1(3)+1); XR1 := (D => 1, FIELD1 => XR1.FIELD1 + 1); XP1 := NEW INTEGER'(XP1.ALL + 1); XV1 := PACK1.NEXT(XV1); XT1.NEXT; XK1 := XK1 + 1; IF XI1 /= IDENT_INT(4) THEN FAILED ("INCORRECT VALUE OF XI1 (4)"); END IF; IF XA1 /= (IDENT_INT(4),IDENT_INT(4),IDENT_INT(4)) THEN FAILED ("INCORRECT VALUE OF XA1 (4)"); END IF; IF XR1 /= (D => 1, FIELD1 => IDENT_INT(4)) THEN FAILED ("INCORRECT VALUE OF XR1 (4)"); END IF; IF XP1 /= IDENT(P1) OR XP1.ALL /= IDENT_INT(4) THEN FAILED ("INCORRECT VALUE OF XP1 (4)"); END IF; IF PACK1."/=" (XV1, PACK1.IDENT(PACK1.FOUR)) THEN FAILED ("INCORRECT VALUE OF XV1 (4)"); END IF; XT1.VALU(I); IF I /= IDENT_INT(4) THEN FAILED ("INCORRECT RETURN VALUE OF XT1.VALU (4)"); END IF; IF XK1 /= IDENT_INT(4) THEN FAILED ("INCORRECT VALUE OF XK1 (4)"); END IF; I1 := I1 + 1; A1 := (A1(1)+1, A1(2)+1, A1(3)+1); R1 := (D => 1, FIELD1 => R1.FIELD1 + 1); P1 := NEW INTEGER'(P1.ALL + 1); V1 := PACK1.NEXT(V1); T1.NEXT; PACK1.K1 := PACK1.K1 + 1; IF XI1 /= IDENT_INT(5) THEN FAILED ("INCORRECT VALUE OF XI1 (5)"); END IF; IF XA1 /= (IDENT_INT(5),IDENT_INT(5),IDENT_INT(5)) THEN FAILED ("INCORRECT VALUE OF XA1 (5)"); END IF; IF XR1 /= (D => 1, FIELD1 => IDENT_INT(5)) THEN FAILED ("INCORRECT VALUE OF XR1 (5)"); END IF; IF XP1 /= IDENT(P1) OR XP1.ALL /= IDENT_INT(5) THEN FAILED ("INCORRECT VALUE OF XP1 (5)"); END IF; IF PACK1."/=" (XV1, PACK1.IDENT(PACK1.FIVE)) THEN FAILED ("INCORRECT VALUE OF XV1 (5)"); END IF; XT1.VALU(I); IF I /= IDENT_INT(5) THEN FAILED ("INCORRECT RETURN VALUE OF XT1.VALU (5)"); END IF; IF XK1 /= IDENT_INT(5) THEN FAILED ("INCORRECT VALUE OF XK1 (5)"); END IF; T1.STOP; RESULT; END C85005A;
case Today is when Saturday | Sunday => null; -- don't do anything, if Today is Saturday or Sunday when Monday => Compute_Starting_Balance; when Friday => Compute_Ending_Balance; when Tuesday .. Thursday => Accumulate_Sales; end case;
package body ACO.Protocols.Network_Management is function Is_Allowed_Transition (Current : ACO.States.State; Next : ACO.States.State) return Boolean is use ACO.States; begin case Current is when Initializing => return Next = Pre_Operational; when Pre_Operational | Operational | Stopped | Unknown_State => return True; end case; end Is_Allowed_Transition; procedure Set (This : in out NMT; State : in ACO.States.State) is use ACO.States; begin if This.Od.Get_Node_State /= State then This.Od.Set_Node_State (State); case State is when Initializing => This.Od.Set_Node_State (Pre_Operational); when Pre_Operational | Operational | Stopped | Unknown_State => null; end case; end if; end Set; function Get (This : NMT) return ACO.States.State is begin return This.Od.Get_Node_State; end Get; overriding function Is_Valid (This : in out NMT; Msg : in ACO.Messages.Message) return Boolean is pragma Unreferenced (This); use type ACO.Messages.Id_Type; begin return ACO.Messages.CAN_Id (Msg) = NMT_CAN_Id; end Is_Valid; procedure On_NMT_Command (This : in out NMT; Msg : in ACO.Messages.Message) is use ACO.States; use type ACO.Messages.Node_Nr; Cmd : constant NMT_Commands.NMT_Command := NMT_Commands.To_NMT_Command (Msg); begin if Cmd.Node_Id = This.Id or else Cmd.Node_Id = ACO.Messages.Broadcast_Id then case Cmd.Command_Specifier is when NMT_Commands.Start => This.Set (Operational); when NMT_Commands.Stop => This.Set (Stopped); when NMT_Commands.Pre_Op => This.Set (Pre_Operational); when NMT_Commands.Reset_Node | NMT_Commands.Reset_Communication => This.Set (Initializing); when others => null; end case; end if; end On_NMT_Command; procedure Message_Received (This : in out NMT; Msg : in ACO.Messages.Message) is use ACO.States; begin case This.Get is when Initializing | Unknown_State => return; when Pre_Operational | Operational | Stopped => null; end case; if NMT_Commands.Is_Valid_Command (Msg) then This.On_NMT_Command (Msg); end if; end Message_Received; overriding procedure On_Event (This : in out Node_State_Change_Subscriber; Data : in ACO.Events.Event_Data) is begin This.Ref.NMT_Log (ACO.Log.Info, Data.State.Previous'Img & " => " & Data.State.Current'Img); end On_Event; overriding procedure Initialize (This : in out NMT) is begin Protocol (This).Initialize; This.Od.Events.Node_Events.Attach (This.State_Change'Unchecked_Access); end Initialize; overriding procedure Finalize (This : in out NMT) is begin Protocol (This).Finalize; This.Od.Events.Node_Events.Detach (This.State_Change'Unchecked_Access); end Finalize; procedure NMT_Log (This : in out NMT; Level : in ACO.Log.Log_Level; Message : in String) is pragma Unreferenced (This); begin ACO.Log.Put_Line (Level, "(NMT) " & Message); end NMT_Log; end ACO.Protocols.Network_Management;
with Ahven.Framework; with Unknown.Api; package Test_Foreign.Read is package Skill renames Unknown.Api; use Unknown; use Unknown.Api; type Test is new Ahven.Framework.Test_Case with null record; procedure Initialize (T : in out Test); procedure Aircraft; procedure Annotation_Test; procedure Colored_Nodes; procedure Constant_Maybe_Wrong; procedure Container; procedure Date_Example; procedure Four_Colored_Nodes; procedure Local_Base_Pool_Start_Index; procedure Node; procedure Null_Annotation; procedure Two_Node_Blocks; end Test_Foreign.Read;
-- Copyright (c) 2021 Devin Hill -- zlib License -- see LICENSE for details. with GBA.Display.Backgrounds.Refs; package GBA.Refs is subtype BG_Ref is GBA.Display.Backgrounds.Refs.BG_Ref; subtype Reg_BG_Ref is GBA.Display.Backgrounds.Refs.Reg_BG_Ref; subtype Aff_BG_Ref is GBA.Display.Backgrounds.Refs.Aff_BG_Ref; end GBA.Refs;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2012, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ package body AMF.Internals.Tables.CMOF_Metamodel is ------------------ -- MM_CMOF_CMOF -- ------------------ function MM_CMOF_CMOF return AMF.Internals.CMOF_Element is begin return Base + 189; end MM_CMOF_CMOF; --------------------- -- MC_CMOF_Boolean -- --------------------- function MC_CMOF_Boolean return AMF.Internals.CMOF_Element is begin return Base + 192; end MC_CMOF_Boolean; --------------------- -- MC_CMOF_Integer -- --------------------- function MC_CMOF_Integer return AMF.Internals.CMOF_Element is begin return Base + 190; end MC_CMOF_Integer; -------------------------------------- -- MC_CMOF_Parameter_Direction_Kind -- -------------------------------------- function MC_CMOF_Parameter_Direction_Kind return AMF.Internals.CMOF_Element is begin return Base + 737; end MC_CMOF_Parameter_Direction_Kind; -------------------- -- MC_CMOF_String -- -------------------- function MC_CMOF_String return AMF.Internals.CMOF_Element is begin return Base + 194; end MC_CMOF_String; ------------------------------- -- MC_CMOF_Unlimited_Natural -- ------------------------------- function MC_CMOF_Unlimited_Natural return AMF.Internals.CMOF_Element is begin return Base + 196; end MC_CMOF_Unlimited_Natural; ----------------------------- -- MC_CMOF_Visibility_Kind -- ----------------------------- function MC_CMOF_Visibility_Kind return AMF.Internals.CMOF_Element is begin return Base + 747; end MC_CMOF_Visibility_Kind; ------------------------- -- MC_CMOF_Association -- ------------------------- function MC_CMOF_Association return AMF.Internals.CMOF_Element is begin return Base + 1; end MC_CMOF_Association; -------------------------------- -- MC_CMOF_Behavioral_Feature -- -------------------------------- function MC_CMOF_Behavioral_Feature return AMF.Internals.CMOF_Element is begin return Base + 2; end MC_CMOF_Behavioral_Feature; ------------------- -- MC_CMOF_Class -- ------------------- function MC_CMOF_Class return AMF.Internals.CMOF_Element is begin return Base + 3; end MC_CMOF_Class; ------------------------ -- MC_CMOF_Classifier -- ------------------------ function MC_CMOF_Classifier return AMF.Internals.CMOF_Element is begin return Base + 4; end MC_CMOF_Classifier; --------------------- -- MC_CMOF_Comment -- --------------------- function MC_CMOF_Comment return AMF.Internals.CMOF_Element is begin return Base + 5; end MC_CMOF_Comment; ------------------------ -- MC_CMOF_Constraint -- ------------------------ function MC_CMOF_Constraint return AMF.Internals.CMOF_Element is begin return Base + 6; end MC_CMOF_Constraint; ----------------------- -- MC_CMOF_Data_Type -- ----------------------- function MC_CMOF_Data_Type return AMF.Internals.CMOF_Element is begin return Base + 7; end MC_CMOF_Data_Type; ----------------------------------- -- MC_CMOF_Directed_Relationship -- ----------------------------------- function MC_CMOF_Directed_Relationship return AMF.Internals.CMOF_Element is begin return Base + 8; end MC_CMOF_Directed_Relationship; --------------------- -- MC_CMOF_Element -- --------------------- function MC_CMOF_Element return AMF.Internals.CMOF_Element is begin return Base + 9; end MC_CMOF_Element; ---------------------------- -- MC_CMOF_Element_Import -- ---------------------------- function MC_CMOF_Element_Import return AMF.Internals.CMOF_Element is begin return Base + 10; end MC_CMOF_Element_Import; ------------------------- -- MC_CMOF_Enumeration -- ------------------------- function MC_CMOF_Enumeration return AMF.Internals.CMOF_Element is begin return Base + 11; end MC_CMOF_Enumeration; --------------------------------- -- MC_CMOF_Enumeration_Literal -- --------------------------------- function MC_CMOF_Enumeration_Literal return AMF.Internals.CMOF_Element is begin return Base + 12; end MC_CMOF_Enumeration_Literal; ------------------------ -- MC_CMOF_Expression -- ------------------------ function MC_CMOF_Expression return AMF.Internals.CMOF_Element is begin return Base + 13; end MC_CMOF_Expression; --------------------- -- MC_CMOF_Feature -- --------------------- function MC_CMOF_Feature return AMF.Internals.CMOF_Element is begin return Base + 14; end MC_CMOF_Feature; ---------------------------------- -- MC_CMOF_Multiplicity_Element -- ---------------------------------- function MC_CMOF_Multiplicity_Element return AMF.Internals.CMOF_Element is begin return Base + 15; end MC_CMOF_Multiplicity_Element; --------------------------- -- MC_CMOF_Named_Element -- --------------------------- function MC_CMOF_Named_Element return AMF.Internals.CMOF_Element is begin return Base + 16; end MC_CMOF_Named_Element; ----------------------- -- MC_CMOF_Namespace -- ----------------------- function MC_CMOF_Namespace return AMF.Internals.CMOF_Element is begin return Base + 17; end MC_CMOF_Namespace; ------------------------------- -- MC_CMOF_Opaque_Expression -- ------------------------------- function MC_CMOF_Opaque_Expression return AMF.Internals.CMOF_Element is begin return Base + 18; end MC_CMOF_Opaque_Expression; ----------------------- -- MC_CMOF_Operation -- ----------------------- function MC_CMOF_Operation return AMF.Internals.CMOF_Element is begin return Base + 19; end MC_CMOF_Operation; --------------------- -- MC_CMOF_Package -- --------------------- function MC_CMOF_Package return AMF.Internals.CMOF_Element is begin return Base + 20; end MC_CMOF_Package; ---------------------------- -- MC_CMOF_Package_Import -- ---------------------------- function MC_CMOF_Package_Import return AMF.Internals.CMOF_Element is begin return Base + 21; end MC_CMOF_Package_Import; --------------------------- -- MC_CMOF_Package_Merge -- --------------------------- function MC_CMOF_Package_Merge return AMF.Internals.CMOF_Element is begin return Base + 22; end MC_CMOF_Package_Merge; --------------------------------- -- MC_CMOF_Packageable_Element -- --------------------------------- function MC_CMOF_Packageable_Element return AMF.Internals.CMOF_Element is begin return Base + 23; end MC_CMOF_Packageable_Element; ----------------------- -- MC_CMOF_Parameter -- ----------------------- function MC_CMOF_Parameter return AMF.Internals.CMOF_Element is begin return Base + 24; end MC_CMOF_Parameter; ---------------------------- -- MC_CMOF_Primitive_Type -- ---------------------------- function MC_CMOF_Primitive_Type return AMF.Internals.CMOF_Element is begin return Base + 25; end MC_CMOF_Primitive_Type; ---------------------- -- MC_CMOF_Property -- ---------------------- function MC_CMOF_Property return AMF.Internals.CMOF_Element is begin return Base + 26; end MC_CMOF_Property; --------------------------------- -- MC_CMOF_Redefinable_Element -- --------------------------------- function MC_CMOF_Redefinable_Element return AMF.Internals.CMOF_Element is begin return Base + 27; end MC_CMOF_Redefinable_Element; -------------------------- -- MC_CMOF_Relationship -- -------------------------- function MC_CMOF_Relationship return AMF.Internals.CMOF_Element is begin return Base + 28; end MC_CMOF_Relationship; -------------------------------- -- MC_CMOF_Structural_Feature -- -------------------------------- function MC_CMOF_Structural_Feature return AMF.Internals.CMOF_Element is begin return Base + 29; end MC_CMOF_Structural_Feature; ----------------- -- MC_CMOF_Tag -- ----------------- function MC_CMOF_Tag return AMF.Internals.CMOF_Element is begin return Base + 30; end MC_CMOF_Tag; ------------------ -- MC_CMOF_Type -- ------------------ function MC_CMOF_Type return AMF.Internals.CMOF_Element is begin return Base + 31; end MC_CMOF_Type; --------------------------- -- MC_CMOF_Typed_Element -- --------------------------- function MC_CMOF_Typed_Element return AMF.Internals.CMOF_Element is begin return Base + 32; end MC_CMOF_Typed_Element; --------------------------------- -- MC_CMOF_Value_Specification -- --------------------------------- function MC_CMOF_Value_Specification return AMF.Internals.CMOF_Element is begin return Base + 33; end MC_CMOF_Value_Specification; ------------------------------------------------ -- MP_CMOF_Association_End_Type_A_Association -- ------------------------------------------------ function MP_CMOF_Association_End_Type_A_Association return AMF.Internals.CMOF_Element is begin return Base + 34; end MP_CMOF_Association_End_Type_A_Association; ------------------------------------ -- MP_CMOF_Association_Is_Derived -- ------------------------------------ function MP_CMOF_Association_Is_Derived return AMF.Internals.CMOF_Element is begin return Base + 79; end MP_CMOF_Association_Is_Derived; --------------------------------------------------------- -- MP_CMOF_Association_Member_End_Property_Association -- --------------------------------------------------------- function MP_CMOF_Association_Member_End_Property_Association return AMF.Internals.CMOF_Element is begin return Base + 35; end MP_CMOF_Association_Member_End_Property_Association; ----------------------------------------------------------- -- MP_CMOF_Association_Navigable_Owned_End_A_Association -- ----------------------------------------------------------- function MP_CMOF_Association_Navigable_Owned_End_A_Association return AMF.Internals.CMOF_Element is begin return Base + 36; end MP_CMOF_Association_Navigable_Owned_End_A_Association; --------------------------------------------------------------- -- MP_CMOF_Association_Owned_End_Property_Owning_Association -- --------------------------------------------------------------- function MP_CMOF_Association_Owned_End_Property_Owning_Association return AMF.Internals.CMOF_Element is begin return Base + 37; end MP_CMOF_Association_Owned_End_Property_Owning_Association; --------------------------------------------------------------------- -- MP_CMOF_Behavioral_Feature_Owned_Parameter_A_Owner_Formal_Param -- --------------------------------------------------------------------- function MP_CMOF_Behavioral_Feature_Owned_Parameter_A_Owner_Formal_Param return AMF.Internals.CMOF_Element is begin return Base + 38; end MP_CMOF_Behavioral_Feature_Owned_Parameter_A_Owner_Formal_Param; ---------------------------------------------------------------------- -- MP_CMOF_Behavioral_Feature_Raised_Exception_A_Behavioral_Feature -- ---------------------------------------------------------------------- function MP_CMOF_Behavioral_Feature_Raised_Exception_A_Behavioral_Feature return AMF.Internals.CMOF_Element is begin return Base + 39; end MP_CMOF_Behavioral_Feature_Raised_Exception_A_Behavioral_Feature; ------------------------------- -- MP_CMOF_Class_Is_Abstract -- ------------------------------- function MP_CMOF_Class_Is_Abstract return AMF.Internals.CMOF_Element is begin return Base + 80; end MP_CMOF_Class_Is_Abstract; -------------------------------------------------- -- MP_CMOF_Class_Owned_Attribute_Property_Class -- -------------------------------------------------- function MP_CMOF_Class_Owned_Attribute_Property_Class return AMF.Internals.CMOF_Element is begin return Base + 40; end MP_CMOF_Class_Owned_Attribute_Property_Class; --------------------------------------------------- -- MP_CMOF_Class_Owned_Operation_Operation_Class -- --------------------------------------------------- function MP_CMOF_Class_Owned_Operation_Operation_Class return AMF.Internals.CMOF_Element is begin return Base + 41; end MP_CMOF_Class_Owned_Operation_Operation_Class; --------------------------------------- -- MP_CMOF_Class_Super_Class_A_Class -- --------------------------------------- function MP_CMOF_Class_Super_Class_A_Class return AMF.Internals.CMOF_Element is begin return Base + 42; end MP_CMOF_Class_Super_Class_A_Class; ----------------------------------------------- -- MP_CMOF_Classifier_Attribute_A_Classifier -- ----------------------------------------------- function MP_CMOF_Classifier_Attribute_A_Classifier return AMF.Internals.CMOF_Element is begin return Base + 43; end MP_CMOF_Classifier_Attribute_A_Classifier; ------------------------------------------------------------- -- MP_CMOF_Classifier_Feature_Feature_Featuring_Classifier -- ------------------------------------------------------------- function MP_CMOF_Classifier_Feature_Feature_Featuring_Classifier return AMF.Internals.CMOF_Element is begin return Base + 44; end MP_CMOF_Classifier_Feature_Feature_Featuring_Classifier; --------------------------------------------- -- MP_CMOF_Classifier_General_A_Classifier -- --------------------------------------------- function MP_CMOF_Classifier_General_A_Classifier return AMF.Internals.CMOF_Element is begin return Base + 45; end MP_CMOF_Classifier_General_A_Classifier; ------------------------------------------------------ -- MP_CMOF_Classifier_Inherited_Member_A_Classifier -- ------------------------------------------------------ function MP_CMOF_Classifier_Inherited_Member_A_Classifier return AMF.Internals.CMOF_Element is begin return Base + 46; end MP_CMOF_Classifier_Inherited_Member_A_Classifier; ------------------------------------------------ -- MP_CMOF_Classifier_Is_Final_Specialization -- ------------------------------------------------ function MP_CMOF_Classifier_Is_Final_Specialization return AMF.Internals.CMOF_Element is begin return Base + 81; end MP_CMOF_Classifier_Is_Final_Specialization; ------------------------------------------------- -- MP_CMOF_Comment_Annotated_Element_A_Comment -- ------------------------------------------------- function MP_CMOF_Comment_Annotated_Element_A_Comment return AMF.Internals.CMOF_Element is begin return Base + 47; end MP_CMOF_Comment_Annotated_Element_A_Comment; -------------------------- -- MP_CMOF_Comment_Body -- -------------------------- function MP_CMOF_Comment_Body return AMF.Internals.CMOF_Element is begin return Base + 82; end MP_CMOF_Comment_Body; --------------------------------------------------------- -- MP_CMOF_Constraint_Constrained_Element_A_Constraint -- --------------------------------------------------------- function MP_CMOF_Constraint_Constrained_Element_A_Constraint return AMF.Internals.CMOF_Element is begin return Base + 48; end MP_CMOF_Constraint_Constrained_Element_A_Constraint; ----------------------------------------------------- -- MP_CMOF_Constraint_Context_Namespace_Owned_Rule -- ----------------------------------------------------- function MP_CMOF_Constraint_Context_Namespace_Owned_Rule return AMF.Internals.CMOF_Element is begin return Base + 83; end MP_CMOF_Constraint_Context_Namespace_Owned_Rule; ---------------------------------------------------------- -- MP_CMOF_Constraint_Specification_A_Owning_Constraint -- ---------------------------------------------------------- function MP_CMOF_Constraint_Specification_A_Owning_Constraint return AMF.Internals.CMOF_Element is begin return Base + 84; end MP_CMOF_Constraint_Specification_A_Owning_Constraint; --------------------------------------------------------- -- MP_CMOF_Data_Type_Owned_Attribute_Property_Datatype -- --------------------------------------------------------- function MP_CMOF_Data_Type_Owned_Attribute_Property_Datatype return AMF.Internals.CMOF_Element is begin return Base + 49; end MP_CMOF_Data_Type_Owned_Attribute_Property_Datatype; ---------------------------------------------------------- -- MP_CMOF_Data_Type_Owned_Operation_Operation_Datatype -- ---------------------------------------------------------- function MP_CMOF_Data_Type_Owned_Operation_Operation_Datatype return AMF.Internals.CMOF_Element is begin return Base + 50; end MP_CMOF_Data_Type_Owned_Operation_Operation_Datatype; ------------------------------------------------------------------ -- MP_CMOF_Directed_Relationship_Source_A_Directed_Relationship -- ------------------------------------------------------------------ function MP_CMOF_Directed_Relationship_Source_A_Directed_Relationship return AMF.Internals.CMOF_Element is begin return Base + 51; end MP_CMOF_Directed_Relationship_Source_A_Directed_Relationship; ------------------------------------------------------------------ -- MP_CMOF_Directed_Relationship_Target_A_Directed_Relationship -- ------------------------------------------------------------------ function MP_CMOF_Directed_Relationship_Target_A_Directed_Relationship return AMF.Internals.CMOF_Element is begin return Base + 52; end MP_CMOF_Directed_Relationship_Target_A_Directed_Relationship; ---------------------------------------------------- -- MP_CMOF_Element_Owned_Comment_A_Owning_Element -- ---------------------------------------------------- function MP_CMOF_Element_Owned_Comment_A_Owning_Element return AMF.Internals.CMOF_Element is begin return Base + 53; end MP_CMOF_Element_Owned_Comment_A_Owning_Element; ------------------------------------------------- -- MP_CMOF_Element_Owned_Element_Element_Owner -- ------------------------------------------------- function MP_CMOF_Element_Owned_Element_Element_Owner return AMF.Internals.CMOF_Element is begin return Base + 54; end MP_CMOF_Element_Owned_Element_Element_Owner; ------------------------------------------------- -- MP_CMOF_Element_Owner_Element_Owned_Element -- ------------------------------------------------- function MP_CMOF_Element_Owner_Element_Owned_Element return AMF.Internals.CMOF_Element is begin return Base + 85; end MP_CMOF_Element_Owner_Element_Owned_Element; ---------------------------------- -- MP_CMOF_Element_Import_Alias -- ---------------------------------- function MP_CMOF_Element_Import_Alias return AMF.Internals.CMOF_Element is begin return Base + 86; end MP_CMOF_Element_Import_Alias; -------------------------------------------------------------- -- MP_CMOF_Element_Import_Imported_Element_A_Element_Import -- -------------------------------------------------------------- function MP_CMOF_Element_Import_Imported_Element_A_Element_Import return AMF.Internals.CMOF_Element is begin return Base + 87; end MP_CMOF_Element_Import_Imported_Element_A_Element_Import; ------------------------------------------------------------------------- -- MP_CMOF_Element_Import_Importing_Namespace_Namespace_Element_Import -- ------------------------------------------------------------------------- function MP_CMOF_Element_Import_Importing_Namespace_Namespace_Element_Import return AMF.Internals.CMOF_Element is begin return Base + 88; end MP_CMOF_Element_Import_Importing_Namespace_Namespace_Element_Import; --------------------------------------- -- MP_CMOF_Element_Import_Visibility -- --------------------------------------- function MP_CMOF_Element_Import_Visibility return AMF.Internals.CMOF_Element is begin return Base + 89; end MP_CMOF_Element_Import_Visibility; ----------------------------------------------------------------------- -- MP_CMOF_Enumeration_Owned_Literal_Enumeration_Literal_Enumeration -- ----------------------------------------------------------------------- function MP_CMOF_Enumeration_Owned_Literal_Enumeration_Literal_Enumeration return AMF.Internals.CMOF_Element is begin return Base + 55; end MP_CMOF_Enumeration_Owned_Literal_Enumeration_Literal_Enumeration; ----------------------------------------------------------------------- -- MP_CMOF_Enumeration_Literal_Enumeration_Enumeration_Owned_Literal -- ----------------------------------------------------------------------- function MP_CMOF_Enumeration_Literal_Enumeration_Enumeration_Owned_Literal return AMF.Internals.CMOF_Element is begin return Base + 90; end MP_CMOF_Enumeration_Literal_Enumeration_Enumeration_Owned_Literal; --------------------------------------------- -- MP_CMOF_Expression_Operand_A_Expression -- --------------------------------------------- function MP_CMOF_Expression_Operand_A_Expression return AMF.Internals.CMOF_Element is begin return Base + 56; end MP_CMOF_Expression_Operand_A_Expression; ------------------------------------------------------------- -- MP_CMOF_Feature_Featuring_Classifier_Classifier_Feature -- ------------------------------------------------------------- function MP_CMOF_Feature_Featuring_Classifier_Classifier_Feature return AMF.Internals.CMOF_Element is begin return Base + 57; end MP_CMOF_Feature_Featuring_Classifier_Classifier_Feature; --------------------------------------------- -- MP_CMOF_Multiplicity_Element_Is_Ordered -- --------------------------------------------- function MP_CMOF_Multiplicity_Element_Is_Ordered return AMF.Internals.CMOF_Element is begin return Base + 91; end MP_CMOF_Multiplicity_Element_Is_Ordered; -------------------------------------------- -- MP_CMOF_Multiplicity_Element_Is_Unique -- -------------------------------------------- function MP_CMOF_Multiplicity_Element_Is_Unique return AMF.Internals.CMOF_Element is begin return Base + 92; end MP_CMOF_Multiplicity_Element_Is_Unique; ---------------------------------------- -- MP_CMOF_Multiplicity_Element_Lower -- ---------------------------------------- function MP_CMOF_Multiplicity_Element_Lower return AMF.Internals.CMOF_Element is begin return Base + 93; end MP_CMOF_Multiplicity_Element_Lower; ---------------------------------------- -- MP_CMOF_Multiplicity_Element_Upper -- ---------------------------------------- function MP_CMOF_Multiplicity_Element_Upper return AMF.Internals.CMOF_Element is begin return Base + 94; end MP_CMOF_Multiplicity_Element_Upper; -------------------------------- -- MP_CMOF_Named_Element_Name -- -------------------------------- function MP_CMOF_Named_Element_Name return AMF.Internals.CMOF_Element is begin return Base + 95; end MP_CMOF_Named_Element_Name; ------------------------------------------------------------ -- MP_CMOF_Named_Element_Namespace_Namespace_Owned_Member -- ------------------------------------------------------------ function MP_CMOF_Named_Element_Namespace_Namespace_Owned_Member return AMF.Internals.CMOF_Element is begin return Base + 96; end MP_CMOF_Named_Element_Namespace_Namespace_Owned_Member; ------------------------------------------ -- MP_CMOF_Named_Element_Qualified_Name -- ------------------------------------------ function MP_CMOF_Named_Element_Qualified_Name return AMF.Internals.CMOF_Element is begin return Base + 97; end MP_CMOF_Named_Element_Qualified_Name; -------------------------------------- -- MP_CMOF_Named_Element_Visibility -- -------------------------------------- function MP_CMOF_Named_Element_Visibility return AMF.Internals.CMOF_Element is begin return Base + 98; end MP_CMOF_Named_Element_Visibility; ------------------------------------------------------------------------- -- MP_CMOF_Namespace_Element_Import_Element_Import_Importing_Namespace -- ------------------------------------------------------------------------- function MP_CMOF_Namespace_Element_Import_Element_Import_Importing_Namespace return AMF.Internals.CMOF_Element is begin return Base + 58; end MP_CMOF_Namespace_Element_Import_Element_Import_Importing_Namespace; --------------------------------------------------- -- MP_CMOF_Namespace_Imported_Member_A_Namespace -- --------------------------------------------------- function MP_CMOF_Namespace_Imported_Member_A_Namespace return AMF.Internals.CMOF_Element is begin return Base + 59; end MP_CMOF_Namespace_Imported_Member_A_Namespace; ------------------------------------------ -- MP_CMOF_Namespace_Member_A_Namespace -- ------------------------------------------ function MP_CMOF_Namespace_Member_A_Namespace return AMF.Internals.CMOF_Element is begin return Base + 60; end MP_CMOF_Namespace_Member_A_Namespace; ------------------------------------------------------------ -- MP_CMOF_Namespace_Owned_Member_Named_Element_Namespace -- ------------------------------------------------------------ function MP_CMOF_Namespace_Owned_Member_Named_Element_Namespace return AMF.Internals.CMOF_Element is begin return Base + 61; end MP_CMOF_Namespace_Owned_Member_Named_Element_Namespace; ----------------------------------------------------- -- MP_CMOF_Namespace_Owned_Rule_Constraint_Context -- ----------------------------------------------------- function MP_CMOF_Namespace_Owned_Rule_Constraint_Context return AMF.Internals.CMOF_Element is begin return Base + 62; end MP_CMOF_Namespace_Owned_Rule_Constraint_Context; ------------------------------------------------------------------------- -- MP_CMOF_Namespace_Package_Import_Package_Import_Importing_Namespace -- ------------------------------------------------------------------------- function MP_CMOF_Namespace_Package_Import_Package_Import_Importing_Namespace return AMF.Internals.CMOF_Element is begin return Base + 63; end MP_CMOF_Namespace_Package_Import_Package_Import_Importing_Namespace; ------------------------------------ -- MP_CMOF_Opaque_Expression_Body -- ------------------------------------ function MP_CMOF_Opaque_Expression_Body return AMF.Internals.CMOF_Element is begin return Base + 99; end MP_CMOF_Opaque_Expression_Body; ---------------------------------------- -- MP_CMOF_Opaque_Expression_Language -- ---------------------------------------- function MP_CMOF_Opaque_Expression_Language return AMF.Internals.CMOF_Element is begin return Base + 100; end MP_CMOF_Opaque_Expression_Language; ----------------------------------------------------- -- MP_CMOF_Operation_Body_Condition_A_Body_Context -- ----------------------------------------------------- function MP_CMOF_Operation_Body_Condition_A_Body_Context return AMF.Internals.CMOF_Element is begin return Base + 101; end MP_CMOF_Operation_Body_Condition_A_Body_Context; --------------------------------------------------- -- MP_CMOF_Operation_Class_Class_Owned_Operation -- --------------------------------------------------- function MP_CMOF_Operation_Class_Class_Owned_Operation return AMF.Internals.CMOF_Element is begin return Base + 102; end MP_CMOF_Operation_Class_Class_Owned_Operation; ---------------------------------------------------------- -- MP_CMOF_Operation_Datatype_Data_Type_Owned_Operation -- ---------------------------------------------------------- function MP_CMOF_Operation_Datatype_Data_Type_Owned_Operation return AMF.Internals.CMOF_Element is begin return Base + 103; end MP_CMOF_Operation_Datatype_Data_Type_Owned_Operation; ---------------------------------- -- MP_CMOF_Operation_Is_Ordered -- ---------------------------------- function MP_CMOF_Operation_Is_Ordered return AMF.Internals.CMOF_Element is begin return Base + 104; end MP_CMOF_Operation_Is_Ordered; -------------------------------- -- MP_CMOF_Operation_Is_Query -- -------------------------------- function MP_CMOF_Operation_Is_Query return AMF.Internals.CMOF_Element is begin return Base + 105; end MP_CMOF_Operation_Is_Query; --------------------------------- -- MP_CMOF_Operation_Is_Unique -- --------------------------------- function MP_CMOF_Operation_Is_Unique return AMF.Internals.CMOF_Element is begin return Base + 106; end MP_CMOF_Operation_Is_Unique; ----------------------------- -- MP_CMOF_Operation_Lower -- ----------------------------- function MP_CMOF_Operation_Lower return AMF.Internals.CMOF_Element is begin return Base + 107; end MP_CMOF_Operation_Lower; ----------------------------------------------------------- -- MP_CMOF_Operation_Owned_Parameter_Parameter_Operation -- ----------------------------------------------------------- function MP_CMOF_Operation_Owned_Parameter_Parameter_Operation return AMF.Internals.CMOF_Element is begin return Base + 64; end MP_CMOF_Operation_Owned_Parameter_Parameter_Operation; ---------------------------------------------------- -- MP_CMOF_Operation_Postcondition_A_Post_Context -- ---------------------------------------------------- function MP_CMOF_Operation_Postcondition_A_Post_Context return AMF.Internals.CMOF_Element is begin return Base + 65; end MP_CMOF_Operation_Postcondition_A_Post_Context; -------------------------------------------------- -- MP_CMOF_Operation_Precondition_A_Pre_Context -- -------------------------------------------------- function MP_CMOF_Operation_Precondition_A_Pre_Context return AMF.Internals.CMOF_Element is begin return Base + 66; end MP_CMOF_Operation_Precondition_A_Pre_Context; ---------------------------------------------------- -- MP_CMOF_Operation_Raised_Exception_A_Operation -- ---------------------------------------------------- function MP_CMOF_Operation_Raised_Exception_A_Operation return AMF.Internals.CMOF_Element is begin return Base + 67; end MP_CMOF_Operation_Raised_Exception_A_Operation; ------------------------------------------------------- -- MP_CMOF_Operation_Redefined_Operation_A_Operation -- ------------------------------------------------------- function MP_CMOF_Operation_Redefined_Operation_A_Operation return AMF.Internals.CMOF_Element is begin return Base + 68; end MP_CMOF_Operation_Redefined_Operation_A_Operation; ---------------------------------------- -- MP_CMOF_Operation_Type_A_Operation -- ---------------------------------------- function MP_CMOF_Operation_Type_A_Operation return AMF.Internals.CMOF_Element is begin return Base + 108; end MP_CMOF_Operation_Type_A_Operation; ----------------------------- -- MP_CMOF_Operation_Upper -- ----------------------------- function MP_CMOF_Operation_Upper return AMF.Internals.CMOF_Element is begin return Base + 109; end MP_CMOF_Operation_Upper; ------------------------------------------------------------ -- MP_CMOF_Package_Nested_Package_Package_Nesting_Package -- ------------------------------------------------------------ function MP_CMOF_Package_Nested_Package_Package_Nesting_Package return AMF.Internals.CMOF_Element is begin return Base + 69; end MP_CMOF_Package_Nested_Package_Package_Nesting_Package; ------------------------------------------------------------ -- MP_CMOF_Package_Nesting_Package_Package_Nested_Package -- ------------------------------------------------------------ function MP_CMOF_Package_Nesting_Package_Package_Nested_Package return AMF.Internals.CMOF_Element is begin return Base + 110; end MP_CMOF_Package_Nesting_Package_Package_Nested_Package; --------------------------------------------- -- MP_CMOF_Package_Owned_Type_Type_Package -- --------------------------------------------- function MP_CMOF_Package_Owned_Type_Type_Package return AMF.Internals.CMOF_Element is begin return Base + 70; end MP_CMOF_Package_Owned_Type_Type_Package; ------------------------------------------------------------------- -- MP_CMOF_Package_Package_Merge_Package_Merge_Receiving_Package -- ------------------------------------------------------------------- function MP_CMOF_Package_Package_Merge_Package_Merge_Receiving_Package return AMF.Internals.CMOF_Element is begin return Base + 71; end MP_CMOF_Package_Package_Merge_Package_Merge_Receiving_Package; ------------------------------------------------------- -- MP_CMOF_Package_Packaged_Element_A_Owning_Package -- ------------------------------------------------------- function MP_CMOF_Package_Packaged_Element_A_Owning_Package return AMF.Internals.CMOF_Element is begin return Base + 72; end MP_CMOF_Package_Packaged_Element_A_Owning_Package; ------------------------- -- MP_CMOF_Package_Uri -- ------------------------- function MP_CMOF_Package_Uri return AMF.Internals.CMOF_Element is begin return Base + 111; end MP_CMOF_Package_Uri; -------------------------------------------------------------- -- MP_CMOF_Package_Import_Imported_Package_A_Package_Import -- -------------------------------------------------------------- function MP_CMOF_Package_Import_Imported_Package_A_Package_Import return AMF.Internals.CMOF_Element is begin return Base + 112; end MP_CMOF_Package_Import_Imported_Package_A_Package_Import; ------------------------------------------------------------------------- -- MP_CMOF_Package_Import_Importing_Namespace_Namespace_Package_Import -- ------------------------------------------------------------------------- function MP_CMOF_Package_Import_Importing_Namespace_Namespace_Package_Import return AMF.Internals.CMOF_Element is begin return Base + 113; end MP_CMOF_Package_Import_Importing_Namespace_Namespace_Package_Import; --------------------------------------- -- MP_CMOF_Package_Import_Visibility -- --------------------------------------- function MP_CMOF_Package_Import_Visibility return AMF.Internals.CMOF_Element is begin return Base + 114; end MP_CMOF_Package_Import_Visibility; ---------------------------------------------------------- -- MP_CMOF_Package_Merge_Merged_Package_A_Package_Merge -- ---------------------------------------------------------- function MP_CMOF_Package_Merge_Merged_Package_A_Package_Merge return AMF.Internals.CMOF_Element is begin return Base + 115; end MP_CMOF_Package_Merge_Merged_Package_A_Package_Merge; ------------------------------------------------------------------- -- MP_CMOF_Package_Merge_Receiving_Package_Package_Package_Merge -- ------------------------------------------------------------------- function MP_CMOF_Package_Merge_Receiving_Package_Package_Package_Merge return AMF.Internals.CMOF_Element is begin return Base + 116; end MP_CMOF_Package_Merge_Receiving_Package_Package_Package_Merge; ------------------------------- -- MP_CMOF_Parameter_Default -- ------------------------------- function MP_CMOF_Parameter_Default return AMF.Internals.CMOF_Element is begin return Base + 117; end MP_CMOF_Parameter_Default; --------------------------------- -- MP_CMOF_Parameter_Direction -- --------------------------------- function MP_CMOF_Parameter_Direction return AMF.Internals.CMOF_Element is begin return Base + 118; end MP_CMOF_Parameter_Direction; ----------------------------------------------------------- -- MP_CMOF_Parameter_Operation_Operation_Owned_Parameter -- ----------------------------------------------------------- function MP_CMOF_Parameter_Operation_Operation_Owned_Parameter return AMF.Internals.CMOF_Element is begin return Base + 119; end MP_CMOF_Parameter_Operation_Operation_Owned_Parameter; --------------------------------------------------------- -- MP_CMOF_Property_Association_Association_Member_End -- --------------------------------------------------------- function MP_CMOF_Property_Association_Association_Member_End return AMF.Internals.CMOF_Element is begin return Base + 120; end MP_CMOF_Property_Association_Association_Member_End; -------------------------------------------------- -- MP_CMOF_Property_Class_Class_Owned_Attribute -- -------------------------------------------------- function MP_CMOF_Property_Class_Class_Owned_Attribute return AMF.Internals.CMOF_Element is begin return Base + 121; end MP_CMOF_Property_Class_Class_Owned_Attribute; --------------------------------------------------------- -- MP_CMOF_Property_Datatype_Data_Type_Owned_Attribute -- --------------------------------------------------------- function MP_CMOF_Property_Datatype_Data_Type_Owned_Attribute return AMF.Internals.CMOF_Element is begin return Base + 122; end MP_CMOF_Property_Datatype_Data_Type_Owned_Attribute; ------------------------------ -- MP_CMOF_Property_Default -- ------------------------------ function MP_CMOF_Property_Default return AMF.Internals.CMOF_Element is begin return Base + 123; end MP_CMOF_Property_Default; ----------------------------------- -- MP_CMOF_Property_Is_Composite -- ----------------------------------- function MP_CMOF_Property_Is_Composite return AMF.Internals.CMOF_Element is begin return Base + 124; end MP_CMOF_Property_Is_Composite; --------------------------------- -- MP_CMOF_Property_Is_Derived -- --------------------------------- function MP_CMOF_Property_Is_Derived return AMF.Internals.CMOF_Element is begin return Base + 125; end MP_CMOF_Property_Is_Derived; --------------------------------------- -- MP_CMOF_Property_Is_Derived_Union -- --------------------------------------- function MP_CMOF_Property_Is_Derived_Union return AMF.Internals.CMOF_Element is begin return Base + 126; end MP_CMOF_Property_Is_Derived_Union; ----------------------------------- -- MP_CMOF_Property_Is_Read_Only -- ----------------------------------- function MP_CMOF_Property_Is_Read_Only return AMF.Internals.CMOF_Element is begin return Base + 127; end MP_CMOF_Property_Is_Read_Only; ------------------------------------------ -- MP_CMOF_Property_Opposite_A_Property -- ------------------------------------------ function MP_CMOF_Property_Opposite_A_Property return AMF.Internals.CMOF_Element is begin return Base + 128; end MP_CMOF_Property_Opposite_A_Property; --------------------------------------------------------------- -- MP_CMOF_Property_Owning_Association_Association_Owned_End -- --------------------------------------------------------------- function MP_CMOF_Property_Owning_Association_Association_Owned_End return AMF.Internals.CMOF_Element is begin return Base + 129; end MP_CMOF_Property_Owning_Association_Association_Owned_End; ---------------------------------------------------- -- MP_CMOF_Property_Redefined_Property_A_Property -- ---------------------------------------------------- function MP_CMOF_Property_Redefined_Property_A_Property return AMF.Internals.CMOF_Element is begin return Base + 73; end MP_CMOF_Property_Redefined_Property_A_Property; ---------------------------------------------------- -- MP_CMOF_Property_Subsetted_Property_A_Property -- ---------------------------------------------------- function MP_CMOF_Property_Subsetted_Property_A_Property return AMF.Internals.CMOF_Element is begin return Base + 74; end MP_CMOF_Property_Subsetted_Property_A_Property; ----------------------------------------- -- MP_CMOF_Redefinable_Element_Is_Leaf -- ----------------------------------------- function MP_CMOF_Redefinable_Element_Is_Leaf return AMF.Internals.CMOF_Element is begin return Base + 130; end MP_CMOF_Redefinable_Element_Is_Leaf; ------------------------------------------------------------------------- -- MP_CMOF_Redefinable_Element_Redefined_Element_A_Redefinable_Element -- ------------------------------------------------------------------------- function MP_CMOF_Redefinable_Element_Redefined_Element_A_Redefinable_Element return AMF.Internals.CMOF_Element is begin return Base + 75; end MP_CMOF_Redefinable_Element_Redefined_Element_A_Redefinable_Element; ---------------------------------------------------------------------------- -- MP_CMOF_Redefinable_Element_Redefinition_Context_A_Redefinable_Element -- ---------------------------------------------------------------------------- function MP_CMOF_Redefinable_Element_Redefinition_Context_A_Redefinable_Element return AMF.Internals.CMOF_Element is begin return Base + 76; end MP_CMOF_Redefinable_Element_Redefinition_Context_A_Redefinable_Element; --------------------------------------------------------- -- MP_CMOF_Relationship_Related_Element_A_Relationship -- --------------------------------------------------------- function MP_CMOF_Relationship_Related_Element_A_Relationship return AMF.Internals.CMOF_Element is begin return Base + 77; end MP_CMOF_Relationship_Related_Element_A_Relationship; ------------------------------- -- MP_CMOF_Tag_Element_A_Tag -- ------------------------------- function MP_CMOF_Tag_Element_A_Tag return AMF.Internals.CMOF_Element is begin return Base + 78; end MP_CMOF_Tag_Element_A_Tag; ---------------------- -- MP_CMOF_Tag_Name -- ---------------------- function MP_CMOF_Tag_Name return AMF.Internals.CMOF_Element is begin return Base + 131; end MP_CMOF_Tag_Name; --------------------------------------- -- MP_CMOF_Tag_Tag_Owner_A_Owned_Tag -- --------------------------------------- function MP_CMOF_Tag_Tag_Owner_A_Owned_Tag return AMF.Internals.CMOF_Element is begin return Base + 132; end MP_CMOF_Tag_Tag_Owner_A_Owned_Tag; ----------------------- -- MP_CMOF_Tag_Value -- ----------------------- function MP_CMOF_Tag_Value return AMF.Internals.CMOF_Element is begin return Base + 133; end MP_CMOF_Tag_Value; --------------------------------------------- -- MP_CMOF_Type_Package_Package_Owned_Type -- --------------------------------------------- function MP_CMOF_Type_Package_Package_Owned_Type return AMF.Internals.CMOF_Element is begin return Base + 134; end MP_CMOF_Type_Package_Package_Owned_Type; ------------------------------------------------ -- MP_CMOF_Typed_Element_Type_A_Typed_Element -- ------------------------------------------------ function MP_CMOF_Typed_Element_Type_A_Typed_Element return AMF.Internals.CMOF_Element is begin return Base + 135; end MP_CMOF_Typed_Element_Type_A_Typed_Element; -------------------------------------------------------------- -- MP_CMOF_A_Element_Import_Element_Import_Imported_Element -- -------------------------------------------------------------- function MP_CMOF_A_Element_Import_Element_Import_Imported_Element return AMF.Internals.CMOF_Element is begin return Base + 776; end MP_CMOF_A_Element_Import_Element_Import_Imported_Element; ------------------------------------------------------- -- MP_CMOF_A_Owning_Package_Package_Packaged_Element -- ------------------------------------------------------- function MP_CMOF_A_Owning_Package_Package_Packaged_Element return AMF.Internals.CMOF_Element is begin return Base + 777; end MP_CMOF_A_Owning_Package_Package_Packaged_Element; ------------------------------- -- MP_CMOF_A_Tag_Tag_Element -- ------------------------------- function MP_CMOF_A_Tag_Tag_Element return AMF.Internals.CMOF_Element is begin return Base + 797; end MP_CMOF_A_Tag_Tag_Element; --------------------------------------- -- MP_CMOF_A_Owned_Tag_Tag_Tag_Owner -- --------------------------------------- function MP_CMOF_A_Owned_Tag_Tag_Tag_Owner return AMF.Internals.CMOF_Element is begin return Base + 798; end MP_CMOF_A_Owned_Tag_Tag_Tag_Owner; ---------------------------------------- -- MP_CMOF_A_Operation_Operation_Type -- ---------------------------------------- function MP_CMOF_A_Operation_Operation_Type return AMF.Internals.CMOF_Element is begin return Base + 778; end MP_CMOF_A_Operation_Operation_Type; ---------------------------------------------------------- -- MP_CMOF_A_Package_Merge_Package_Merge_Merged_Package -- ---------------------------------------------------------- function MP_CMOF_A_Package_Merge_Package_Merge_Merged_Package return AMF.Internals.CMOF_Element is begin return Base + 779; end MP_CMOF_A_Package_Merge_Package_Merge_Merged_Package; ------------------------------------------------- -- MP_CMOF_A_Comment_Comment_Annotated_Element -- ------------------------------------------------- function MP_CMOF_A_Comment_Comment_Annotated_Element return AMF.Internals.CMOF_Element is begin return Base + 780; end MP_CMOF_A_Comment_Comment_Annotated_Element; --------------------------------------------------------- -- MP_CMOF_A_Relationship_Relationship_Related_Element -- --------------------------------------------------------- function MP_CMOF_A_Relationship_Relationship_Related_Element return AMF.Internals.CMOF_Element is begin return Base + 781; end MP_CMOF_A_Relationship_Relationship_Related_Element; ------------------------------------------------------------------ -- MP_CMOF_A_Directed_Relationship_Directed_Relationship_Source -- ------------------------------------------------------------------ function MP_CMOF_A_Directed_Relationship_Directed_Relationship_Source return AMF.Internals.CMOF_Element is begin return Base + 782; end MP_CMOF_A_Directed_Relationship_Directed_Relationship_Source; ------------------------------------------------------------------ -- MP_CMOF_A_Directed_Relationship_Directed_Relationship_Target -- ------------------------------------------------------------------ function MP_CMOF_A_Directed_Relationship_Directed_Relationship_Target return AMF.Internals.CMOF_Element is begin return Base + 783; end MP_CMOF_A_Directed_Relationship_Directed_Relationship_Target; ------------------------------------------------ -- MP_CMOF_A_Typed_Element_Typed_Element_Type -- ------------------------------------------------ function MP_CMOF_A_Typed_Element_Typed_Element_Type return AMF.Internals.CMOF_Element is begin return Base + 763; end MP_CMOF_A_Typed_Element_Typed_Element_Type; ---------------------------------------------------------------------------- -- MP_CMOF_A_Redefinable_Element_Redefinable_Element_Redefinition_Context -- ---------------------------------------------------------------------------- function MP_CMOF_A_Redefinable_Element_Redefinable_Element_Redefinition_Context return AMF.Internals.CMOF_Element is begin return Base + 784; end MP_CMOF_A_Redefinable_Element_Redefinable_Element_Redefinition_Context; ------------------------------------------------------------------------- -- MP_CMOF_A_Redefinable_Element_Redefinable_Element_Redefined_Element -- ------------------------------------------------------------------------- function MP_CMOF_A_Redefinable_Element_Redefinable_Element_Redefined_Element return AMF.Internals.CMOF_Element is begin return Base + 785; end MP_CMOF_A_Redefinable_Element_Redefinable_Element_Redefined_Element; ----------------------------------------------- -- MP_CMOF_A_Classifier_Classifier_Attribute -- ----------------------------------------------- function MP_CMOF_A_Classifier_Classifier_Attribute return AMF.Internals.CMOF_Element is begin return Base + 764; end MP_CMOF_A_Classifier_Classifier_Attribute; --------------------------------------------------------- -- MP_CMOF_A_Constraint_Constraint_Constrained_Element -- --------------------------------------------------------- function MP_CMOF_A_Constraint_Constraint_Constrained_Element return AMF.Internals.CMOF_Element is begin return Base + 786; end MP_CMOF_A_Constraint_Constraint_Constrained_Element; ---------------------------------------------------- -- MP_CMOF_A_Property_Property_Redefined_Property -- ---------------------------------------------------- function MP_CMOF_A_Property_Property_Redefined_Property return AMF.Internals.CMOF_Element is begin return Base + 765; end MP_CMOF_A_Property_Property_Redefined_Property; ---------------------------------------------------------- -- MP_CMOF_A_Owning_Constraint_Constraint_Specification -- ---------------------------------------------------------- function MP_CMOF_A_Owning_Constraint_Constraint_Specification return AMF.Internals.CMOF_Element is begin return Base + 787; end MP_CMOF_A_Owning_Constraint_Constraint_Specification; ---------------------------------------------------- -- MP_CMOF_A_Property_Property_Subsetted_Property -- ---------------------------------------------------- function MP_CMOF_A_Property_Property_Subsetted_Property return AMF.Internals.CMOF_Element is begin return Base + 766; end MP_CMOF_A_Property_Property_Subsetted_Property; --------------------------------------------- -- MP_CMOF_A_Classifier_Classifier_General -- --------------------------------------------- function MP_CMOF_A_Classifier_Classifier_General return AMF.Internals.CMOF_Element is begin return Base + 788; end MP_CMOF_A_Classifier_Classifier_General; ------------------------------------------ -- MP_CMOF_A_Property_Property_Opposite -- ------------------------------------------ function MP_CMOF_A_Property_Property_Opposite return AMF.Internals.CMOF_Element is begin return Base + 767; end MP_CMOF_A_Property_Property_Opposite; --------------------------------------- -- MP_CMOF_A_Class_Class_Super_Class -- --------------------------------------- function MP_CMOF_A_Class_Class_Super_Class return AMF.Internals.CMOF_Element is begin return Base + 768; end MP_CMOF_A_Class_Class_Super_Class; ------------------------------------------ -- MP_CMOF_A_Namespace_Namespace_Member -- ------------------------------------------ function MP_CMOF_A_Namespace_Namespace_Member return AMF.Internals.CMOF_Element is begin return Base + 789; end MP_CMOF_A_Namespace_Namespace_Member; ------------------------------------------------ -- MP_CMOF_A_Association_Association_End_Type -- ------------------------------------------------ function MP_CMOF_A_Association_Association_End_Type return AMF.Internals.CMOF_Element is begin return Base + 769; end MP_CMOF_A_Association_Association_End_Type; --------------------------------------------- -- MP_CMOF_A_Expression_Expression_Operand -- --------------------------------------------- function MP_CMOF_A_Expression_Expression_Operand return AMF.Internals.CMOF_Element is begin return Base + 790; end MP_CMOF_A_Expression_Expression_Operand; ----------------------------------------------------------- -- MP_CMOF_A_Association_Association_Navigable_Owned_End -- ----------------------------------------------------------- function MP_CMOF_A_Association_Association_Navigable_Owned_End return AMF.Internals.CMOF_Element is begin return Base + 791; end MP_CMOF_A_Association_Association_Navigable_Owned_End; ---------------------------------------------------- -- MP_CMOF_A_Operation_Operation_Raised_Exception -- ---------------------------------------------------- function MP_CMOF_A_Operation_Operation_Raised_Exception return AMF.Internals.CMOF_Element is begin return Base + 770; end MP_CMOF_A_Operation_Operation_Raised_Exception; ---------------------------------------------------- -- MP_CMOF_A_Owning_Element_Element_Owned_Comment -- ---------------------------------------------------- function MP_CMOF_A_Owning_Element_Element_Owned_Comment return AMF.Internals.CMOF_Element is begin return Base + 792; end MP_CMOF_A_Owning_Element_Element_Owned_Comment; ------------------------------------------------------- -- MP_CMOF_A_Operation_Operation_Redefined_Operation -- ------------------------------------------------------- function MP_CMOF_A_Operation_Operation_Redefined_Operation return AMF.Internals.CMOF_Element is begin return Base + 771; end MP_CMOF_A_Operation_Operation_Redefined_Operation; ------------------------------------------------------ -- MP_CMOF_A_Classifier_Classifier_Inherited_Member -- ------------------------------------------------------ function MP_CMOF_A_Classifier_Classifier_Inherited_Member return AMF.Internals.CMOF_Element is begin return Base + 793; end MP_CMOF_A_Classifier_Classifier_Inherited_Member; --------------------------------------------------------------------- -- MP_CMOF_A_Owner_Formal_Param_Behavioral_Feature_Owned_Parameter -- --------------------------------------------------------------------- function MP_CMOF_A_Owner_Formal_Param_Behavioral_Feature_Owned_Parameter return AMF.Internals.CMOF_Element is begin return Base + 772; end MP_CMOF_A_Owner_Formal_Param_Behavioral_Feature_Owned_Parameter; -------------------------------------------------- -- MP_CMOF_A_Pre_Context_Operation_Precondition -- -------------------------------------------------- function MP_CMOF_A_Pre_Context_Operation_Precondition return AMF.Internals.CMOF_Element is begin return Base + 794; end MP_CMOF_A_Pre_Context_Operation_Precondition; ---------------------------------------------------------------------- -- MP_CMOF_A_Behavioral_Feature_Behavioral_Feature_Raised_Exception -- ---------------------------------------------------------------------- function MP_CMOF_A_Behavioral_Feature_Behavioral_Feature_Raised_Exception return AMF.Internals.CMOF_Element is begin return Base + 773; end MP_CMOF_A_Behavioral_Feature_Behavioral_Feature_Raised_Exception; ---------------------------------------------------- -- MP_CMOF_A_Post_Context_Operation_Postcondition -- ---------------------------------------------------- function MP_CMOF_A_Post_Context_Operation_Postcondition return AMF.Internals.CMOF_Element is begin return Base + 795; end MP_CMOF_A_Post_Context_Operation_Postcondition; --------------------------------------------------- -- MP_CMOF_A_Namespace_Namespace_Imported_Member -- --------------------------------------------------- function MP_CMOF_A_Namespace_Namespace_Imported_Member return AMF.Internals.CMOF_Element is begin return Base + 774; end MP_CMOF_A_Namespace_Namespace_Imported_Member; ----------------------------------------------------- -- MP_CMOF_A_Body_Context_Operation_Body_Condition -- ----------------------------------------------------- function MP_CMOF_A_Body_Context_Operation_Body_Condition return AMF.Internals.CMOF_Element is begin return Base + 796; end MP_CMOF_A_Body_Context_Operation_Body_Condition; -------------------------------------------------------------- -- MP_CMOF_A_Package_Import_Package_Import_Imported_Package -- -------------------------------------------------------------- function MP_CMOF_A_Package_Import_Package_Import_Imported_Package return AMF.Internals.CMOF_Element is begin return Base + 775; end MP_CMOF_A_Package_Import_Package_Import_Imported_Package; ------------------------------------------------------------ -- MA_CMOF_Element_Import_Imported_Element_Element_Import -- ------------------------------------------------------------ function MA_CMOF_Element_Import_Imported_Element_Element_Import return AMF.Internals.CMOF_Element is begin return Base + 136; end MA_CMOF_Element_Import_Imported_Element_Element_Import; ---------------------------------------------------------- -- MA_CMOF_Namespace_Element_Import_Importing_Namespace -- ---------------------------------------------------------- function MA_CMOF_Namespace_Element_Import_Importing_Namespace return AMF.Internals.CMOF_Element is begin return Base + 137; end MA_CMOF_Namespace_Element_Import_Importing_Namespace; ---------------------------------------------------------- -- MA_CMOF_Namespace_Package_Import_Importing_Namespace -- ---------------------------------------------------------- function MA_CMOF_Namespace_Package_Import_Importing_Namespace return AMF.Internals.CMOF_Element is begin return Base + 138; end MA_CMOF_Namespace_Package_Import_Importing_Namespace; ----------------------------------------------------- -- MA_CMOF_Package_Packaged_Element_Owning_Package -- ----------------------------------------------------- function MA_CMOF_Package_Packaged_Element_Owning_Package return AMF.Internals.CMOF_Element is begin return Base + 139; end MA_CMOF_Package_Packaged_Element_Owning_Package; ----------------------------- -- MA_CMOF_Tag_Element_Tag -- ----------------------------- function MA_CMOF_Tag_Element_Tag return AMF.Internals.CMOF_Element is begin return Base + 140; end MA_CMOF_Tag_Element_Tag; ---------------------------------------- -- MA_CMOF_Package_Owned_Type_Package -- ---------------------------------------- function MA_CMOF_Package_Owned_Type_Package return AMF.Internals.CMOF_Element is begin return Base + 141; end MA_CMOF_Package_Owned_Type_Package; ------------------------------------- -- MA_CMOF_Tag_Tag_Owner_Owned_Tag -- ------------------------------------- function MA_CMOF_Tag_Tag_Owner_Owned_Tag return AMF.Internals.CMOF_Element is begin return Base + 142; end MA_CMOF_Tag_Tag_Owner_Owned_Tag; ------------------------------------------------ -- MA_CMOF_Association_Member_End_Association -- ------------------------------------------------ function MA_CMOF_Association_Member_End_Association return AMF.Internals.CMOF_Element is begin return Base + 143; end MA_CMOF_Association_Member_End_Association; ---------------------------------------------------- -- MA_CMOF_Package_Nested_Package_Nesting_Package -- ---------------------------------------------------- function MA_CMOF_Package_Nested_Package_Nesting_Package return AMF.Internals.CMOF_Element is begin return Base + 144; end MA_CMOF_Package_Nested_Package_Nesting_Package; -------------------------------------- -- MA_CMOF_Operation_Type_Operation -- -------------------------------------- function MA_CMOF_Operation_Type_Operation return AMF.Internals.CMOF_Element is begin return Base + 145; end MA_CMOF_Operation_Type_Operation; ----------------------------------------------------- -- MA_CMOF_Package_Package_Merge_Receiving_Package -- ----------------------------------------------------- function MA_CMOF_Package_Package_Merge_Receiving_Package return AMF.Internals.CMOF_Element is begin return Base + 146; end MA_CMOF_Package_Package_Merge_Receiving_Package; -------------------------------------------------------- -- MA_CMOF_Package_Merge_Merged_Package_Package_Merge -- -------------------------------------------------------- function MA_CMOF_Package_Merge_Merged_Package_Package_Merge return AMF.Internals.CMOF_Element is begin return Base + 147; end MA_CMOF_Package_Merge_Merged_Package_Package_Merge; ----------------------------------------- -- MA_CMOF_Element_Owned_Element_Owner -- ----------------------------------------- function MA_CMOF_Element_Owned_Element_Owner return AMF.Internals.CMOF_Element is begin return Base + 148; end MA_CMOF_Element_Owned_Element_Owner; ----------------------------------------------- -- MA_CMOF_Comment_Annotated_Element_Comment -- ----------------------------------------------- function MA_CMOF_Comment_Annotated_Element_Comment return AMF.Internals.CMOF_Element is begin return Base + 149; end MA_CMOF_Comment_Annotated_Element_Comment; ------------------------------------------------------- -- MA_CMOF_Relationship_Related_Element_Relationship -- ------------------------------------------------------- function MA_CMOF_Relationship_Related_Element_Relationship return AMF.Internals.CMOF_Element is begin return Base + 150; end MA_CMOF_Relationship_Related_Element_Relationship; ---------------------------------------------------------------- -- MA_CMOF_Directed_Relationship_Source_Directed_Relationship -- ---------------------------------------------------------------- function MA_CMOF_Directed_Relationship_Source_Directed_Relationship return AMF.Internals.CMOF_Element is begin return Base + 151; end MA_CMOF_Directed_Relationship_Source_Directed_Relationship; ---------------------------------------------------------------- -- MA_CMOF_Directed_Relationship_Target_Directed_Relationship -- ---------------------------------------------------------------- function MA_CMOF_Directed_Relationship_Target_Directed_Relationship return AMF.Internals.CMOF_Element is begin return Base + 152; end MA_CMOF_Directed_Relationship_Target_Directed_Relationship; ---------------------------------------------- -- MA_CMOF_Typed_Element_Type_Typed_Element -- ---------------------------------------------- function MA_CMOF_Typed_Element_Type_Typed_Element return AMF.Internals.CMOF_Element is begin return Base + 153; end MA_CMOF_Typed_Element_Type_Typed_Element; -------------------------------------------------------------------------- -- MA_CMOF_Redefinable_Element_Redefinition_Context_Redefinable_Element -- -------------------------------------------------------------------------- function MA_CMOF_Redefinable_Element_Redefinition_Context_Redefinable_Element return AMF.Internals.CMOF_Element is begin return Base + 154; end MA_CMOF_Redefinable_Element_Redefinition_Context_Redefinable_Element; ----------------------------------------- -- MA_CMOF_Class_Owned_Attribute_Class -- ----------------------------------------- function MA_CMOF_Class_Owned_Attribute_Class return AMF.Internals.CMOF_Element is begin return Base + 155; end MA_CMOF_Class_Owned_Attribute_Class; ----------------------------------------- -- MA_CMOF_Class_Owned_Operation_Class -- ----------------------------------------- function MA_CMOF_Class_Owned_Operation_Class return AMF.Internals.CMOF_Element is begin return Base + 156; end MA_CMOF_Class_Owned_Operation_Class; ----------------------------------------------------------------------- -- MA_CMOF_Redefinable_Element_Redefined_Element_Redefinable_Element -- ----------------------------------------------------------------------- function MA_CMOF_Redefinable_Element_Redefined_Element_Redefinable_Element return AMF.Internals.CMOF_Element is begin return Base + 157; end MA_CMOF_Redefinable_Element_Redefined_Element_Redefinable_Element; ------------------------------------------------------ -- MA_CMOF_Association_Owned_End_Owning_Association -- ------------------------------------------------------ function MA_CMOF_Association_Owned_End_Owning_Association return AMF.Internals.CMOF_Element is begin return Base + 158; end MA_CMOF_Association_Owned_End_Owning_Association; --------------------------------------------- -- MA_CMOF_Classifier_Attribute_Classifier -- --------------------------------------------- function MA_CMOF_Classifier_Attribute_Classifier return AMF.Internals.CMOF_Element is begin return Base + 159; end MA_CMOF_Classifier_Attribute_Classifier; ----------------------------------------------------- -- MA_CMOF_Classifier_Feature_Featuring_Classifier -- ----------------------------------------------------- function MA_CMOF_Classifier_Feature_Featuring_Classifier return AMF.Internals.CMOF_Element is begin return Base + 160; end MA_CMOF_Classifier_Feature_Featuring_Classifier; ------------------------------------------------------- -- MA_CMOF_Constraint_Constrained_Element_Constraint -- ------------------------------------------------------- function MA_CMOF_Constraint_Constrained_Element_Constraint return AMF.Internals.CMOF_Element is begin return Base + 161; end MA_CMOF_Constraint_Constrained_Element_Constraint; -------------------------------------------------- -- MA_CMOF_Property_Redefined_Property_Property -- -------------------------------------------------- function MA_CMOF_Property_Redefined_Property_Property return AMF.Internals.CMOF_Element is begin return Base + 162; end MA_CMOF_Property_Redefined_Property_Property; -------------------------------------------------------- -- MA_CMOF_Constraint_Specification_Owning_Constraint -- -------------------------------------------------------- function MA_CMOF_Constraint_Specification_Owning_Constraint return AMF.Internals.CMOF_Element is begin return Base + 163; end MA_CMOF_Constraint_Specification_Owning_Constraint; -------------------------------------------------- -- MA_CMOF_Property_Subsetted_Property_Property -- -------------------------------------------------- function MA_CMOF_Property_Subsetted_Property_Property return AMF.Internals.CMOF_Element is begin return Base + 164; end MA_CMOF_Property_Subsetted_Property_Property; ------------------------------------------- -- MA_CMOF_Classifier_General_Classifier -- ------------------------------------------- function MA_CMOF_Classifier_General_Classifier return AMF.Internals.CMOF_Element is begin return Base + 165; end MA_CMOF_Classifier_General_Classifier; ---------------------------------------- -- MA_CMOF_Property_Opposite_Property -- ---------------------------------------- function MA_CMOF_Property_Opposite_Property return AMF.Internals.CMOF_Element is begin return Base + 166; end MA_CMOF_Property_Opposite_Property; ---------------------------------------------- -- MA_CMOF_Namespace_Owned_Member_Namespace -- ---------------------------------------------- function MA_CMOF_Namespace_Owned_Member_Namespace return AMF.Internals.CMOF_Element is begin return Base + 167; end MA_CMOF_Namespace_Owned_Member_Namespace; ------------------------------------- -- MA_CMOF_Class_Super_Class_Class -- ------------------------------------- function MA_CMOF_Class_Super_Class_Class return AMF.Internals.CMOF_Element is begin return Base + 168; end MA_CMOF_Class_Super_Class_Class; ---------------------------------------- -- MA_CMOF_Namespace_Member_Namespace -- ---------------------------------------- function MA_CMOF_Namespace_Member_Namespace return AMF.Internals.CMOF_Element is begin return Base + 169; end MA_CMOF_Namespace_Member_Namespace; ---------------------------------------------- -- MA_CMOF_Association_End_Type_Association -- ---------------------------------------------- function MA_CMOF_Association_End_Type_Association return AMF.Internals.CMOF_Element is begin return Base + 170; end MA_CMOF_Association_End_Type_Association; ------------------------------------------- -- MA_CMOF_Expression_Operand_Expression -- ------------------------------------------- function MA_CMOF_Expression_Operand_Expression return AMF.Internals.CMOF_Element is begin return Base + 171; end MA_CMOF_Expression_Operand_Expression; --------------------------------------------------- -- MA_CMOF_Enumeration_Owned_Literal_Enumeration -- --------------------------------------------------- function MA_CMOF_Enumeration_Owned_Literal_Enumeration return AMF.Internals.CMOF_Element is begin return Base + 172; end MA_CMOF_Enumeration_Owned_Literal_Enumeration; --------------------------------------------------------- -- MA_CMOF_Association_Navigable_Owned_End_Association -- --------------------------------------------------------- function MA_CMOF_Association_Navigable_Owned_End_Association return AMF.Internals.CMOF_Element is begin return Base + 173; end MA_CMOF_Association_Navigable_Owned_End_Association; ------------------------------------------------ -- MA_CMOF_Data_Type_Owned_Attribute_Datatype -- ------------------------------------------------ function MA_CMOF_Data_Type_Owned_Attribute_Datatype return AMF.Internals.CMOF_Element is begin return Base + 174; end MA_CMOF_Data_Type_Owned_Attribute_Datatype; ------------------------------------------------ -- MA_CMOF_Data_Type_Owned_Operation_Datatype -- ------------------------------------------------ function MA_CMOF_Data_Type_Owned_Operation_Datatype return AMF.Internals.CMOF_Element is begin return Base + 175; end MA_CMOF_Data_Type_Owned_Operation_Datatype; ------------------------------------------------- -- MA_CMOF_Operation_Owned_Parameter_Operation -- ------------------------------------------------- function MA_CMOF_Operation_Owned_Parameter_Operation return AMF.Internals.CMOF_Element is begin return Base + 176; end MA_CMOF_Operation_Owned_Parameter_Operation; -------------------------------------------------- -- MA_CMOF_Operation_Raised_Exception_Operation -- -------------------------------------------------- function MA_CMOF_Operation_Raised_Exception_Operation return AMF.Internals.CMOF_Element is begin return Base + 177; end MA_CMOF_Operation_Raised_Exception_Operation; -------------------------------------------------- -- MA_CMOF_Element_Owned_Comment_Owning_Element -- -------------------------------------------------- function MA_CMOF_Element_Owned_Comment_Owning_Element return AMF.Internals.CMOF_Element is begin return Base + 178; end MA_CMOF_Element_Owned_Comment_Owning_Element; ----------------------------------------------------- -- MA_CMOF_Operation_Redefined_Operation_Operation -- ----------------------------------------------------- function MA_CMOF_Operation_Redefined_Operation_Operation return AMF.Internals.CMOF_Element is begin return Base + 179; end MA_CMOF_Operation_Redefined_Operation_Operation; ---------------------------------------------------- -- MA_CMOF_Classifier_Inherited_Member_Classifier -- ---------------------------------------------------- function MA_CMOF_Classifier_Inherited_Member_Classifier return AMF.Internals.CMOF_Element is begin return Base + 180; end MA_CMOF_Classifier_Inherited_Member_Classifier; ------------------------------------------------------------------- -- MA_CMOF_Behavioral_Feature_Owned_Parameter_Owner_Formal_Param -- ------------------------------------------------------------------- function MA_CMOF_Behavioral_Feature_Owned_Parameter_Owner_Formal_Param return AMF.Internals.CMOF_Element is begin return Base + 181; end MA_CMOF_Behavioral_Feature_Owned_Parameter_Owner_Formal_Param; ------------------------------------------------ -- MA_CMOF_Operation_Precondition_Pre_Context -- ------------------------------------------------ function MA_CMOF_Operation_Precondition_Pre_Context return AMF.Internals.CMOF_Element is begin return Base + 182; end MA_CMOF_Operation_Precondition_Pre_Context; -------------------------------------------------------------------- -- MA_CMOF_Behavioral_Feature_Raised_Exception_Behavioral_Feature -- -------------------------------------------------------------------- function MA_CMOF_Behavioral_Feature_Raised_Exception_Behavioral_Feature return AMF.Internals.CMOF_Element is begin return Base + 183; end MA_CMOF_Behavioral_Feature_Raised_Exception_Behavioral_Feature; -------------------------------------------------- -- MA_CMOF_Operation_Postcondition_Post_Context -- -------------------------------------------------- function MA_CMOF_Operation_Postcondition_Post_Context return AMF.Internals.CMOF_Element is begin return Base + 184; end MA_CMOF_Operation_Postcondition_Post_Context; ------------------------------------------------- -- MA_CMOF_Namespace_Imported_Member_Namespace -- ------------------------------------------------- function MA_CMOF_Namespace_Imported_Member_Namespace return AMF.Internals.CMOF_Element is begin return Base + 185; end MA_CMOF_Namespace_Imported_Member_Namespace; --------------------------------------------------- -- MA_CMOF_Operation_Body_Condition_Body_Context -- --------------------------------------------------- function MA_CMOF_Operation_Body_Condition_Body_Context return AMF.Internals.CMOF_Element is begin return Base + 186; end MA_CMOF_Operation_Body_Condition_Body_Context; ------------------------------------------------------------ -- MA_CMOF_Package_Import_Imported_Package_Package_Import -- ------------------------------------------------------------ function MA_CMOF_Package_Import_Imported_Package_Package_Import return AMF.Internals.CMOF_Element is begin return Base + 187; end MA_CMOF_Package_Import_Imported_Package_Package_Import; ------------------------------------------ -- MA_CMOF_Namespace_Owned_Rule_Context -- ------------------------------------------ function MA_CMOF_Namespace_Owned_Rule_Context return AMF.Internals.CMOF_Element is begin return Base + 188; end MA_CMOF_Namespace_Owned_Rule_Context; ------------- -- MB_CMOF -- ------------- function MB_CMOF return AMF.Internals.AMF_Element is begin return Base; end MB_CMOF; ------------- -- MB_CMOF -- ------------- function ML_CMOF return AMF.Internals.AMF_Element is begin return Base + 800; end ML_CMOF; end AMF.Internals.Tables.CMOF_Metamodel;
with ada.text_io, ada.Integer_text_IO, Ada.Text_IO.Text_Streams, Ada.Strings.Fixed, Interfaces.C; use ada.text_io, ada.Integer_text_IO, Ada.Strings, Ada.Strings.Fixed, Interfaces.C; procedure euler36 is type stringptr is access all char_array; procedure PString(s : stringptr) is begin String'Write (Text_Streams.Stream (Current_Output), To_Ada(s.all)); end; procedure PInt(i : in Integer) is begin String'Write (Text_Streams.Stream (Current_Output), Trim(Integer'Image(i), Left)); end; type e is Array (Integer range <>) of Boolean; type e_PTR is access e; type f is Array (Integer range <>) of Integer; type f_PTR is access f; function palindrome2(pow2 : in f_PTR; n : in Integer) return Boolean is t : e_PTR; nnum : Integer; begin t := new e (0..19); for i in integer range 0..19 loop t(i) := n / pow2(i) rem 2 = 1; end loop; nnum := 0; for j in integer range 1..19 loop if t(j) then nnum := j; end if; end loop; for k in integer range 0..nnum / 2 loop if t(k) /= t(nnum - k) then return FALSE; end if; end loop; return TRUE; end; sum : Integer; pow2 : f_PTR; p : Integer; num3 : Integer; num2 : Integer; num1 : Integer; num0 : Integer; a : Integer; begin p := 1; pow2 := new f (0..19); for i in integer range 0..19 loop p := p * 2; pow2(i) := p / 2; end loop; sum := 0; for d in integer range 1..9 loop if palindrome2(pow2, d) then PInt(d); PString(new char_array'( To_C("" & Character'Val(10)))); sum := sum + d; end if; if palindrome2(pow2, d * 10 + d) then PInt(d * 10 + d); PString(new char_array'( To_C("" & Character'Val(10)))); sum := sum + d * 10 + d; end if; end loop; for a0 in integer range 0..4 loop a := a0 * 2 + 1; for b in integer range 0..9 loop for c in integer range 0..9 loop num0 := a * 100000 + b * 10000 + c * 1000 + c * 100 + b * 10 + a; if palindrome2(pow2, num0) then PInt(num0); PString(new char_array'( To_C("" & Character'Val(10)))); sum := sum + num0; end if; num1 := a * 10000 + b * 1000 + c * 100 + b * 10 + a; if palindrome2(pow2, num1) then PInt(num1); PString(new char_array'( To_C("" & Character'Val(10)))); sum := sum + num1; end if; end loop; num2 := a * 100 + b * 10 + a; if palindrome2(pow2, num2) then PInt(num2); PString(new char_array'( To_C("" & Character'Val(10)))); sum := sum + num2; end if; num3 := a * 1000 + b * 100 + b * 10 + a; if palindrome2(pow2, num3) then PInt(num3); PString(new char_array'( To_C("" & Character'Val(10)))); sum := sum + num3; end if; end loop; end loop; PString(new char_array'( To_C("sum="))); PInt(sum); PString(new char_array'( To_C("" & Character'Val(10)))); end;