content
stringlengths
23
1.05M
with AUnit.Test_Suites; package GStreamer.tests.Rtsp_Suit is function Suit return AUnit.Test_Suites.Access_Test_Suite; end GStreamer.tests.Rtsp_Suit;
-- Copyright (c) 2020 Raspberry Pi (Trading) Ltd. -- -- SPDX-License-Identifier: BSD-3-Clause -- This spec has been automatically generated from rp2040.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; -- Controls the crystal oscillator package RP_SVD.XOSC is pragma Preelaborate; --------------- -- Registers -- --------------- -- Frequency range. This resets to 0xAA0 and cannot be changed. type CTRL_FREQ_RANGE_Field is (-- Reset value for the field Ctrl_Freq_Range_Field_Reset, Val_1_15Mhz, Reserved_1, Reserved_2, Reserved_3) with Size => 12; for CTRL_FREQ_RANGE_Field use (Ctrl_Freq_Range_Field_Reset => 0, Val_1_15Mhz => 2720, Reserved_1 => 2721, Reserved_2 => 2722, Reserved_3 => 2723); -- On power-up this field is initialised to DISABLE and the chip runs from -- the ROSC.\n If the chip has subsequently been programmed to run from the -- XOSC then setting this field to DISABLE may lock-up the chip. If this is -- a concern then run the clk_ref from the ROSC and enable the clk_sys -- RESUS feature.\n The 12-bit code is intended to give some protection -- against accidental writes. An invalid setting will enable the -- oscillator. type CTRL_ENABLE_Field is (-- Reset value for the field Ctrl_Enable_Field_Reset, Disable, Enable) with Size => 12; for CTRL_ENABLE_Field use (Ctrl_Enable_Field_Reset => 0, Disable => 3358, Enable => 4011); -- Crystal Oscillator Control type CTRL_Register is record -- Frequency range. This resets to 0xAA0 and cannot be changed. FREQ_RANGE : CTRL_FREQ_RANGE_Field := Ctrl_Freq_Range_Field_Reset; -- On power-up this field is initialised to DISABLE and the chip runs -- from the ROSC.\n If the chip has subsequently been programmed to run -- from the XOSC then setting this field to DISABLE may lock-up the -- chip. If this is a concern then run the clk_ref from the ROSC and -- enable the clk_sys RESUS feature.\n The 12-bit code is intended to -- give some protection against accidental writes. An invalid setting -- will enable the oscillator. ENABLE : CTRL_ENABLE_Field := Ctrl_Enable_Field_Reset; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CTRL_Register use record FREQ_RANGE at 0 range 0 .. 11; ENABLE at 0 range 12 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; -- The current frequency range setting, always reads 0 type STATUS_FREQ_RANGE_Field is (Val_1_15Mhz, Reserved_1, Reserved_2, Reserved_3) with Size => 2; for STATUS_FREQ_RANGE_Field use (Val_1_15Mhz => 0, Reserved_1 => 1, Reserved_2 => 2, Reserved_3 => 3); -- Crystal Oscillator Status type STATUS_Register is record -- Read-only. The current frequency range setting, always reads 0 FREQ_RANGE : STATUS_FREQ_RANGE_Field := RP_SVD.XOSC.Val_1_15Mhz; -- unspecified Reserved_2_11 : HAL.UInt10 := 16#0#; -- Read-only. Oscillator is enabled but not necessarily running and -- stable, resets to 0 ENABLED : Boolean := False; -- unspecified Reserved_13_23 : HAL.UInt11 := 16#0#; -- Write data bit of one shall clear (set to zero) the corresponding bit -- in the field. An invalid value has been written to CTRL_ENABLE or -- CTRL_FREQ_RANGE or DORMANT BADWRITE : Boolean := False; -- unspecified Reserved_25_30 : HAL.UInt6 := 16#0#; -- Read-only. Oscillator is running and stable STABLE : Boolean := False; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for STATUS_Register use record FREQ_RANGE at 0 range 0 .. 1; Reserved_2_11 at 0 range 2 .. 11; ENABLED at 0 range 12 .. 12; Reserved_13_23 at 0 range 13 .. 23; BADWRITE at 0 range 24 .. 24; Reserved_25_30 at 0 range 25 .. 30; STABLE at 0 range 31 .. 31; end record; subtype STARTUP_DELAY_Field is HAL.UInt14; -- Controls the startup delay type STARTUP_Register is record -- in multiples of 256*xtal_period DELAY_k : STARTUP_DELAY_Field := 16#0#; -- unspecified Reserved_14_19 : HAL.UInt6 := 16#0#; -- Multiplies the startup_delay by 4. This is of little value to the -- user given that the delay can be programmed directly X4 : Boolean := False; -- unspecified Reserved_21_31 : HAL.UInt11 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for STARTUP_Register use record DELAY_k at 0 range 0 .. 13; Reserved_14_19 at 0 range 14 .. 19; X4 at 0 range 20 .. 20; Reserved_21_31 at 0 range 21 .. 31; end record; subtype COUNT_COUNT_Field is HAL.UInt8; -- A down counter running at the xosc frequency which counts to zero and -- stops.\n To start the counter write a non-zero value.\n Can be used for -- short software pauses when setting up time sensitive hardware. type COUNT_Register is record COUNT : COUNT_COUNT_Field := 16#0#; -- unspecified Reserved_8_31 : HAL.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for COUNT_Register use record COUNT at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Controls the crystal oscillator type XOSC_Peripheral is record -- Crystal Oscillator Control CTRL : aliased CTRL_Register; -- Crystal Oscillator Status STATUS : aliased STATUS_Register; -- Crystal Oscillator pause control\n This is used to save power by -- pausing the XOSC\n On power-up this field is initialised to WAKE\n An -- invalid write will also select WAKE\n WARNING: stop the PLLs before -- selecting dormant mode\n WARNING: setup the irq before selecting -- dormant mode DORMANT : aliased HAL.UInt32; -- Controls the startup delay STARTUP : aliased STARTUP_Register; -- A down counter running at the xosc frequency which counts to zero and -- stops.\n To start the counter write a non-zero value.\n Can be used -- for short software pauses when setting up time sensitive hardware. COUNT : aliased COUNT_Register; end record with Volatile; for XOSC_Peripheral use record CTRL at 16#0# range 0 .. 31; STATUS at 16#4# range 0 .. 31; DORMANT at 16#8# range 0 .. 31; STARTUP at 16#C# range 0 .. 31; COUNT at 16#1C# range 0 .. 31; end record; -- Controls the crystal oscillator XOSC_Periph : aliased XOSC_Peripheral with Import, Address => XOSC_Base; end RP_SVD.XOSC;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- P R J . P P -- -- -- -- B o d y -- -- -- -- Copyright (C) 2001-2005, 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 Ada.Characters.Handling; use Ada.Characters.Handling; with Hostparm; with Namet; use Namet; with Output; use Output; with Snames; package body Prj.PP is use Prj.Tree; Not_Tested : array (Project_Node_Kind) of Boolean := (others => True); Max_Line_Length : constant := Hostparm.Max_Line_Length - 5; -- Maximum length of a line Column : Natural := 0; -- Column number of the last character in the line. Used to avoid -- outputing lines longer than Max_Line_Length. First_With_In_List : Boolean := True; -- Indicate that the next with clause is first in a list such as -- with "A", "B"; -- First_With_In_List will be True for "A", but not for "B". procedure Indicate_Tested (Kind : Project_Node_Kind); -- Set the corresponding component of array Not_Tested to False. -- Only called by pragmas Debug. --------------------- -- Indicate_Tested -- --------------------- procedure Indicate_Tested (Kind : Project_Node_Kind) is begin Not_Tested (Kind) := False; end Indicate_Tested; ------------------ -- Pretty_Print -- ------------------ procedure Pretty_Print (Project : Prj.Tree.Project_Node_Id; In_Tree : Prj.Tree.Project_Node_Tree_Ref; Increment : Positive := 3; Eliminate_Empty_Case_Constructions : Boolean := False; Minimize_Empty_Lines : Boolean := False; W_Char : Write_Char_Ap := null; W_Eol : Write_Eol_Ap := null; W_Str : Write_Str_Ap := null; Backward_Compatibility : Boolean) is procedure Print (Node : Project_Node_Id; Indent : Natural); -- A recursive procedure that traverses a project file tree and outputs -- its source. Current_Prj is the project that we are printing. This -- is used when printing attributes, since in nested packages they -- need to use a fully qualified name. procedure Output_Attribute_Name (Name : Name_Id); -- Outputs an attribute name, taking into account the value of -- Backward_Compatibility. procedure Output_Name (Name : Name_Id; Capitalize : Boolean := True); -- Outputs a name procedure Start_Line (Indent : Natural); -- Outputs the indentation at the beginning of the line procedure Output_String (S : Name_Id); -- Outputs a string using the default output procedures procedure Write_Empty_Line (Always : Boolean := False); -- Outputs an empty line, only if the previous line was not empty -- already and either Always is True or Minimize_Empty_Lines is False. procedure Write_Line (S : String); -- Outputs S followed by a new line procedure Write_String (S : String; Truncated : Boolean := False); -- Outputs S using Write_Str, starting a new line if line would -- become too long, when Truncated = False. -- When Truncated = True, only the part of the string that can fit on -- the line is output. procedure Write_End_Of_Line_Comment (Node : Project_Node_Id); Write_Char : Write_Char_Ap := Output.Write_Char'Access; Write_Eol : Write_Eol_Ap := Output.Write_Eol'Access; Write_Str : Write_Str_Ap := Output.Write_Str'Access; -- These three access to procedure values are used for the output Last_Line_Is_Empty : Boolean := False; -- Used to avoid two consecutive empty lines --------------------------- -- Output_Attribute_Name -- --------------------------- procedure Output_Attribute_Name (Name : Name_Id) is begin if Backward_Compatibility then case Name is when Snames.Name_Spec => Output_Name (Snames.Name_Specification); when Snames.Name_Spec_Suffix => Output_Name (Snames.Name_Specification_Suffix); when Snames.Name_Body => Output_Name (Snames.Name_Implementation); when Snames.Name_Body_Suffix => Output_Name (Snames.Name_Implementation_Suffix); when others => Output_Name (Name); end case; else Output_Name (Name); end if; end Output_Attribute_Name; ----------------- -- Output_Name -- ----------------- procedure Output_Name (Name : Name_Id; Capitalize : Boolean := True) is Capital : Boolean := Capitalize; begin Get_Name_String (Name); -- If line would become too long, create new line if Column + Name_Len > Max_Line_Length then Write_Eol.all; Column := 0; end if; for J in 1 .. Name_Len loop if Capital then Write_Char (To_Upper (Name_Buffer (J))); else Write_Char (Name_Buffer (J)); end if; if Capitalize then Capital := Name_Buffer (J) = '_' or else Is_Digit (Name_Buffer (J)); end if; end loop; Column := Column + Name_Len; end Output_Name; ------------------- -- Output_String -- ------------------- procedure Output_String (S : Name_Id) is begin Get_Name_String (S); -- If line could become too long, create new line. -- Note that the number of characters on the line could be -- twice the number of character in the string (if every -- character is a '"') plus two (the initial and final '"'). if Column + Name_Len + Name_Len + 2 > Max_Line_Length then Write_Eol.all; Column := 0; end if; Write_Char ('"'); Column := Column + 1; Get_Name_String (S); for J in 1 .. Name_Len loop if Name_Buffer (J) = '"' then Write_Char ('"'); Write_Char ('"'); Column := Column + 2; else Write_Char (Name_Buffer (J)); Column := Column + 1; end if; -- If the string does not fit on one line, cut it in parts -- and concatenate. if J < Name_Len and then Column >= Max_Line_Length then Write_Str (""" &"); Write_Eol.all; Write_Char ('"'); Column := 1; end if; end loop; Write_Char ('"'); Column := Column + 1; end Output_String; ---------------- -- Start_Line -- ---------------- procedure Start_Line (Indent : Natural) is begin if not Minimize_Empty_Lines then Write_Str ((1 .. Indent => ' ')); Column := Column + Indent; end if; end Start_Line; ---------------------- -- Write_Empty_Line -- ---------------------- procedure Write_Empty_Line (Always : Boolean := False) is begin if (Always or else not Minimize_Empty_Lines) and then not Last_Line_Is_Empty then Write_Eol.all; Column := 0; Last_Line_Is_Empty := True; end if; end Write_Empty_Line; ------------------------------- -- Write_End_Of_Line_Comment -- ------------------------------- procedure Write_End_Of_Line_Comment (Node : Project_Node_Id) is Value : constant Name_Id := End_Of_Line_Comment (Node, In_Tree); begin if Value /= No_Name then Write_String (" --"); Write_String (Get_Name_String (Value), Truncated => True); end if; Write_Line (""); end Write_End_Of_Line_Comment; ---------------- -- Write_Line -- ---------------- procedure Write_Line (S : String) is begin Write_String (S); Last_Line_Is_Empty := False; Write_Eol.all; Column := 0; end Write_Line; ------------------ -- Write_String -- ------------------ procedure Write_String (S : String; Truncated : Boolean := False) is Length : Natural := S'Length; begin -- If the string would not fit on the line, -- start a new line. if Column + Length > Max_Line_Length then if Truncated then Length := Max_Line_Length - Column; else Write_Eol.all; Column := 0; end if; end if; Write_Str (S (S'First .. S'First + Length - 1)); Column := Column + Length; end Write_String; ----------- -- Print -- ----------- procedure Print (Node : Project_Node_Id; Indent : Natural) is begin if Node /= Empty_Node then case Kind_Of (Node, In_Tree) is when N_Project => pragma Debug (Indicate_Tested (N_Project)); if First_With_Clause_Of (Node, In_Tree) /= Empty_Node then -- with clause(s) First_With_In_List := True; Print (First_With_Clause_Of (Node, In_Tree), Indent); Write_Empty_Line (Always => True); end if; Print (First_Comment_Before (Node, In_Tree), Indent); Start_Line (Indent); Write_String ("project "); Output_Name (Name_Of (Node, In_Tree)); -- Check if this project extends another project if Extended_Project_Path_Of (Node, In_Tree) /= No_Name then Write_String (" extends "); if Is_Extending_All (Node, In_Tree) then Write_String ("all "); end if; Output_String (Extended_Project_Path_Of (Node, In_Tree)); end if; Write_String (" is"); Write_End_Of_Line_Comment (Node); Print (First_Comment_After (Node, In_Tree), Indent + Increment); Write_Empty_Line (Always => True); -- Output all of the declarations in the project Print (Project_Declaration_Of (Node, In_Tree), Indent); Print (First_Comment_Before_End (Node, In_Tree), Indent + Increment); Start_Line (Indent); Write_String ("end "); Output_Name (Name_Of (Node, In_Tree)); Write_Line (";"); Print (First_Comment_After_End (Node, In_Tree), Indent); when N_With_Clause => pragma Debug (Indicate_Tested (N_With_Clause)); -- The with clause will sometimes contain an invalid name -- when we are importing a virtual project from an -- extending all project. Do not output anything in this -- case if Name_Of (Node, In_Tree) /= No_Name and then String_Value_Of (Node, In_Tree) /= No_Name then if First_With_In_List then Print (First_Comment_Before (Node, In_Tree), Indent); Start_Line (Indent); if Non_Limited_Project_Node_Of (Node, In_Tree) = Empty_Node then Write_String ("limited "); end if; Write_String ("with "); end if; Output_String (String_Value_Of (Node, In_Tree)); if Is_Not_Last_In_List (Node, In_Tree) then Write_String (", "); First_With_In_List := False; else Write_String (";"); Write_End_Of_Line_Comment (Node); Print (First_Comment_After (Node, In_Tree), Indent); First_With_In_List := True; end if; end if; Print (Next_With_Clause_Of (Node, In_Tree), Indent); when N_Project_Declaration => pragma Debug (Indicate_Tested (N_Project_Declaration)); if First_Declarative_Item_Of (Node, In_Tree) /= Empty_Node then Print (First_Declarative_Item_Of (Node, In_Tree), Indent + Increment); Write_Empty_Line (Always => True); end if; when N_Declarative_Item => pragma Debug (Indicate_Tested (N_Declarative_Item)); Print (Current_Item_Node (Node, In_Tree), Indent); Print (Next_Declarative_Item (Node, In_Tree), Indent); when N_Package_Declaration => pragma Debug (Indicate_Tested (N_Package_Declaration)); Write_Empty_Line (Always => True); Print (First_Comment_Before (Node, In_Tree), Indent); Start_Line (Indent); Write_String ("package "); Output_Name (Name_Of (Node, In_Tree)); if Project_Of_Renamed_Package_Of (Node, In_Tree) /= Empty_Node then Write_String (" renames "); Output_Name (Name_Of (Project_Of_Renamed_Package_Of (Node, In_Tree), In_Tree)); Write_String ("."); Output_Name (Name_Of (Node, In_Tree)); Write_String (";"); Write_End_Of_Line_Comment (Node); Print (First_Comment_After_End (Node, In_Tree), Indent); else Write_String (" is"); Write_End_Of_Line_Comment (Node); Print (First_Comment_After (Node, In_Tree), Indent + Increment); if First_Declarative_Item_Of (Node, In_Tree) /= Empty_Node then Print (First_Declarative_Item_Of (Node, In_Tree), Indent + Increment); end if; Print (First_Comment_Before_End (Node, In_Tree), Indent + Increment); Start_Line (Indent); Write_String ("end "); Output_Name (Name_Of (Node, In_Tree)); Write_Line (";"); Print (First_Comment_After_End (Node, In_Tree), Indent); Write_Empty_Line; end if; when N_String_Type_Declaration => pragma Debug (Indicate_Tested (N_String_Type_Declaration)); Print (First_Comment_Before (Node, In_Tree), Indent); Start_Line (Indent); Write_String ("type "); Output_Name (Name_Of (Node, In_Tree)); Write_Line (" is"); Start_Line (Indent + Increment); Write_String ("("); declare String_Node : Project_Node_Id := First_Literal_String (Node, In_Tree); begin while String_Node /= Empty_Node loop Output_String (String_Value_Of (String_Node, In_Tree)); String_Node := Next_Literal_String (String_Node, In_Tree); if String_Node /= Empty_Node then Write_String (", "); end if; end loop; end; Write_String (");"); Write_End_Of_Line_Comment (Node); Print (First_Comment_After (Node, In_Tree), Indent); when N_Literal_String => pragma Debug (Indicate_Tested (N_Literal_String)); Output_String (String_Value_Of (Node, In_Tree)); if Source_Index_Of (Node, In_Tree) /= 0 then Write_String (" at "); Write_String (Source_Index_Of (Node, In_Tree)'Img); end if; when N_Attribute_Declaration => pragma Debug (Indicate_Tested (N_Attribute_Declaration)); Print (First_Comment_Before (Node, In_Tree), Indent); Start_Line (Indent); Write_String ("for "); Output_Attribute_Name (Name_Of (Node, In_Tree)); if Associative_Array_Index_Of (Node, In_Tree) /= No_Name then Write_String (" ("); Output_String (Associative_Array_Index_Of (Node, In_Tree)); if Source_Index_Of (Node, In_Tree) /= 0 then Write_String (" at "); Write_String (Source_Index_Of (Node, In_Tree)'Img); end if; Write_String (")"); end if; Write_String (" use "); Print (Expression_Of (Node, In_Tree), Indent); Write_String (";"); Write_End_Of_Line_Comment (Node); Print (First_Comment_After (Node, In_Tree), Indent); when N_Typed_Variable_Declaration => pragma Debug (Indicate_Tested (N_Typed_Variable_Declaration)); Print (First_Comment_Before (Node, In_Tree), Indent); Start_Line (Indent); Output_Name (Name_Of (Node, In_Tree)); Write_String (" : "); Output_Name (Name_Of (String_Type_Of (Node, In_Tree), In_Tree)); Write_String (" := "); Print (Expression_Of (Node, In_Tree), Indent); Write_String (";"); Write_End_Of_Line_Comment (Node); Print (First_Comment_After (Node, In_Tree), Indent); when N_Variable_Declaration => pragma Debug (Indicate_Tested (N_Variable_Declaration)); Print (First_Comment_Before (Node, In_Tree), Indent); Start_Line (Indent); Output_Name (Name_Of (Node, In_Tree)); Write_String (" := "); Print (Expression_Of (Node, In_Tree), Indent); Write_String (";"); Write_End_Of_Line_Comment (Node); Print (First_Comment_After (Node, In_Tree), Indent); when N_Expression => pragma Debug (Indicate_Tested (N_Expression)); declare Term : Project_Node_Id := First_Term (Node, In_Tree); begin while Term /= Empty_Node loop Print (Term, Indent); Term := Next_Term (Term, In_Tree); if Term /= Empty_Node then Write_String (" & "); end if; end loop; end; when N_Term => pragma Debug (Indicate_Tested (N_Term)); Print (Current_Term (Node, In_Tree), Indent); when N_Literal_String_List => pragma Debug (Indicate_Tested (N_Literal_String_List)); Write_String ("("); declare Expression : Project_Node_Id := First_Expression_In_List (Node, In_Tree); begin while Expression /= Empty_Node loop Print (Expression, Indent); Expression := Next_Expression_In_List (Expression, In_Tree); if Expression /= Empty_Node then Write_String (", "); end if; end loop; end; Write_String (")"); when N_Variable_Reference => pragma Debug (Indicate_Tested (N_Variable_Reference)); if Project_Node_Of (Node, In_Tree) /= Empty_Node then Output_Name (Name_Of (Project_Node_Of (Node, In_Tree), In_Tree)); Write_String ("."); end if; if Package_Node_Of (Node, In_Tree) /= Empty_Node then Output_Name (Name_Of (Package_Node_Of (Node, In_Tree), In_Tree)); Write_String ("."); end if; Output_Name (Name_Of (Node, In_Tree)); when N_External_Value => pragma Debug (Indicate_Tested (N_External_Value)); Write_String ("external ("); Print (External_Reference_Of (Node, In_Tree), Indent); if External_Default_Of (Node, In_Tree) /= Empty_Node then Write_String (", "); Print (External_Default_Of (Node, In_Tree), Indent); end if; Write_String (")"); when N_Attribute_Reference => pragma Debug (Indicate_Tested (N_Attribute_Reference)); if Project_Node_Of (Node, In_Tree) /= Empty_Node and then Project_Node_Of (Node, In_Tree) /= Project then Output_Name (Name_Of (Project_Node_Of (Node, In_Tree), In_Tree)); if Package_Node_Of (Node, In_Tree) /= Empty_Node then Write_String ("."); Output_Name (Name_Of (Package_Node_Of (Node, In_Tree), In_Tree)); end if; elsif Package_Node_Of (Node, In_Tree) /= Empty_Node then Output_Name (Name_Of (Package_Node_Of (Node, In_Tree), In_Tree)); else Write_String ("project"); end if; Write_String ("'"); Output_Attribute_Name (Name_Of (Node, In_Tree)); declare Index : constant Name_Id := Associative_Array_Index_Of (Node, In_Tree); begin if Index /= No_Name then Write_String (" ("); Output_String (Index); Write_String (")"); end if; end; when N_Case_Construction => pragma Debug (Indicate_Tested (N_Case_Construction)); declare Case_Item : Project_Node_Id; Is_Non_Empty : Boolean := False; begin Case_Item := First_Case_Item_Of (Node, In_Tree); while Case_Item /= Empty_Node loop if First_Declarative_Item_Of (Case_Item, In_Tree) /= Empty_Node or else not Eliminate_Empty_Case_Constructions then Is_Non_Empty := True; exit; end if; Case_Item := Next_Case_Item (Case_Item, In_Tree); end loop; if Is_Non_Empty then Write_Empty_Line; Print (First_Comment_Before (Node, In_Tree), Indent); Start_Line (Indent); Write_String ("case "); Print (Case_Variable_Reference_Of (Node, In_Tree), Indent); Write_String (" is"); Write_End_Of_Line_Comment (Node); Print (First_Comment_After (Node, In_Tree), Indent + Increment); declare Case_Item : Project_Node_Id := First_Case_Item_Of (Node, In_Tree); begin while Case_Item /= Empty_Node loop pragma Assert (Kind_Of (Case_Item, In_Tree) = N_Case_Item); Print (Case_Item, Indent + Increment); Case_Item := Next_Case_Item (Case_Item, In_Tree); end loop; end; Print (First_Comment_Before_End (Node, In_Tree), Indent + Increment); Start_Line (Indent); Write_Line ("end case;"); Print (First_Comment_After_End (Node, In_Tree), Indent); end if; end; when N_Case_Item => pragma Debug (Indicate_Tested (N_Case_Item)); if First_Declarative_Item_Of (Node, In_Tree) /= Empty_Node or else not Eliminate_Empty_Case_Constructions then Write_Empty_Line; Print (First_Comment_Before (Node, In_Tree), Indent); Start_Line (Indent); Write_String ("when "); if First_Choice_Of (Node, In_Tree) = Empty_Node then Write_String ("others"); else declare Label : Project_Node_Id := First_Choice_Of (Node, In_Tree); begin while Label /= Empty_Node loop Print (Label, Indent); Label := Next_Literal_String (Label, In_Tree); if Label /= Empty_Node then Write_String (" | "); end if; end loop; end; end if; Write_String (" =>"); Write_End_Of_Line_Comment (Node); Print (First_Comment_After (Node, In_Tree), Indent + Increment); declare First : constant Project_Node_Id := First_Declarative_Item_Of (Node, In_Tree); begin if First = Empty_Node then Write_Empty_Line; else Print (First, Indent + Increment); end if; end; end if; when N_Comment_Zones => -- Nothing to do, because it will not be processed directly null; when N_Comment => pragma Debug (Indicate_Tested (N_Comment)); if Follows_Empty_Line (Node, In_Tree) then Write_Empty_Line; end if; Start_Line (Indent); Write_String ("--"); Write_String (Get_Name_String (String_Value_Of (Node, In_Tree)), Truncated => True); Write_Line (""); if Is_Followed_By_Empty_Line (Node, In_Tree) then Write_Empty_Line; end if; Print (Next_Comment (Node, In_Tree), Indent); end case; end if; end Print; -- Start of processing for Pretty_Print begin if W_Char = null then Write_Char := Output.Write_Char'Access; else Write_Char := W_Char; end if; if W_Eol = null then Write_Eol := Output.Write_Eol'Access; else Write_Eol := W_Eol; end if; if W_Str = null then Write_Str := Output.Write_Str'Access; else Write_Str := W_Str; end if; Print (Project, 0); if W_Char = null or else W_Str = null then Output.Write_Eol; end if; end Pretty_Print; ----------------------- -- Output_Statistics -- ----------------------- procedure Output_Statistics is begin Output.Write_Line ("Project_Node_Kinds not tested:"); for Kind in Project_Node_Kind loop if Kind /= N_Comment_Zones and then Not_Tested (Kind) then Output.Write_Str (" "); Output.Write_Line (Project_Node_Kind'Image (Kind)); end if; end loop; Output.Write_Eol; end Output_Statistics; end Prj.PP;
separate (Numerics.Sparse_Matrices) function Has_Same_Dimensions (Left, Right : in Sparse_Matrix) return Boolean is begin if Left.N_Row /= Right.N_Row or else Left.N_Col /= Right.N_Col then return False; end if; return True; end Has_Same_Dimensions;
with Ada.Interrupts.Names; with System; package EVB1000.USB with SPARK_Mode => On is Driver_Priority : constant System.Interrupt_Priority := System.Interrupt_Priority'First; -- By default, use lowest interrupt priority. -- Any interrupt priority value can be used, though. Rx_Buffer_Size : constant Positive := 1024; -- Configures the size of the USB receive buffer. subtype Rx_Length_Number is Natural range 0 .. Rx_Buffer_Size; type Rx_Index is mod Rx_Buffer_Size; protected Buffer with Interrupt_Priority => Driver_Priority is function Is_Connected return Boolean; -- Check if the USB is currently connected. function Can_Read return Boolean with Global => null; -- Check if there is received data waiting to be read. entry Read (Str : in out String; Count : out Natural) with Global => null, Depends => (Buffer => + Str, Count => (Buffer, Str), Str => + Buffer), Contract_Cases => (Str'Length = 0 => Count = 0, Str'Length > 0 => Count in 1 .. Str'Length); -- Read data received over USB. -- -- Data is written to the @Str@ buffer. The number of characters read is -- written to @Count@. This subprogram will try to fill the @Str@ buffer -- but will only read as many characters as available. -- -- This entry blocks until at least 1 byte is available to be read. procedure Write (Str : in String); -- Write data to be sent via USB. -- -- If the USB is not currently connected then the data is discarded -- and this procedure has no effect. procedure Data_Received (Str : in String); -- Notifies this protected object of data received via USB. -- -- This procedure is called by the USB drivers. It should not be called -- by the user. private Rx_Buffer : String (1 .. Rx_Buffer_Size) := (others => Character'First); Rx_Length : Rx_Length_Number := 0; Rx_First : Rx_Index := 0; Has_Data : Boolean := False; end Buffer; private protected Driver with Interrupt_Priority => Driver_Priority is procedure Write (Str : in String); procedure USB_OTG_Interrupt_Handler with Attach_Handler => Ada.Interrupts.Names.OTG_FS_Interrupt; end Driver; end EVB1000.USB;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Calendar.Formatting; with Ada.Text_IO; with Coroutines.Timeouts; procedure Timeout_Proc is begin Ada.Text_IO.Put_Line (Ada.Calendar.Formatting.Image (Ada.Calendar.Clock)); Coroutines.Yield (Coroutines.Timeouts.Timeout (5.0)); Ada.Text_IO.Put_Line (Ada.Calendar.Formatting.Image (Ada.Calendar.Clock)); end Timeout_Proc;
pragma Ada_2012; with Ada.Strings.Fixed; with Ada.Text_Io; use Ada.Text_Io; package body Protypo.Code_Trees is function To_Expression_Vector (X : Tree_Array; Void_Accepted : Boolean := False) return Node_Vectors.Vector; function Capture (Name : Unbounded_Id; Parameters : Tree_Array; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Capture_Call, Name => Name, Params => To_Expression_Vector (Parameters), Source_Position => Position); begin return (Pt => Result); end Capture; ---------------- -- Definition -- ---------------- function Definition (Name : String; Parameter_List : Parsed_Code; Function_Body : Parsed_Code; Is_Function : Boolean; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Defun, Is_Function => Is_Function, Definition_Name => To_Unbounded_String (Name), Function_Body => <>, Parameters => <>, Source_Position => Position); begin if Function_Body.Pt.Class /= Statement_Sequence then raise Program_Error; end if; if Parameter_List.Pt.Class /= Parameter_Signature then raise Program_Error; end if; Result.Function_Body := Function_Body.Pt.Statements; Result.Parameters := Parameter_List.Pt.Signature; return (Pt => Result); end Definition; -------------------------- -- To_Expression_Vector -- -------------------------- function To_Expression_Vector (X : Tree_Array; Void_Accepted : Boolean := False) return Node_Vectors.Vector is Result : Node_Vectors.Vector; begin for Item of X loop if Is_Empty (Item) then if not Void_Accepted then raise Program_Error; end if; else if not (Item.Pt.Class in Expression) then raise Program_Error; end if; end if; Result.Append (Item.Pt); end loop; return Result; end To_Expression_Vector; -------------------- -- Parameter_List -- -------------------- function Parameter_List (Names : Id_List; Default : Tree_Array; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is begin return (Pt => new Node'(Class => Parameter_Signature, Signature => Parameter_Specs' (Names => Names, Default => To_Expression_Vector (Default, True)), Source_Position => Position)); end Parameter_List; ----------- -- Class -- ----------- function Class (X : Parsed_Code) return Non_Terminal is begin return X.Pt.Class; end Class; ------------------ -- If_Then_Else -- ------------------ function If_Then_Else (Conditions : Tree_Array; Then_Branches : Tree_Array; Else_Branch : Parsed_Code) return Parsed_Code is Result : constant Node_Access := new Node (If_Block); Shift : constant Integer := Then_Branches'First - Conditions'First; begin if Conditions'Length /= Then_Branches'Length then raise Program_Error; end if; for Idx in Conditions'Range loop Result.Branches.Append (Conditional_Branch'(Condition => Conditions (Idx).Pt, Code => Then_Branches (Idx + Shift).Pt)); end loop; Result.Else_Branch := Else_Branch.Pt; return (Pt => Result); end If_Then_Else; ---------------- -- Assignment -- ---------------- function Assignment (Lhs : Tree_Array; Value : Tree_Array) return Parsed_Code is Result : constant Node_Access := new Node (Assignment); begin for Lvalue of Lhs loop if not (Lvalue.Pt.Class in Name) then raise Program_Error; end if; Result.Lhs.Append (Lvalue.Pt); end loop; for Rvalue of Value loop if not (Rvalue.Pt.Class in Expression) then raise Program_Error; end if; Result.Rvalues.Append (Rvalue.Pt); end loop; return (Pt => Result); end Assignment; ------------------------ -- Statement_Sequence -- ------------------------ function Statement_Sequence (Statements : Tree_Array; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Statement_Sequence, Source_Position => Position, Statements => <>); begin for Statement of Statements loop if not (Statement.Pt.Class in Statement_Classes) then raise Program_Error with "Expected Statement_Classes, found " & Statement.Pt.Class'Image; end if; Result.Statements.Append (Statement.Pt); end loop; return (Pt => Result); end Statement_Sequence; ---------------------- -- Binary_Operation -- ---------------------- function Binary_Operation (Left : Parsed_Code; Right : Parsed_Code; Operation : Tokens.Binary_Operator; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Binary_Op, Left => Left.Pt, Right => Right.Pt, Operator => Operation, Source_Position => Position); begin if not ((Left.Pt.Class in Expression) and (Right.Pt.Class in Expression)) then raise Program_Error; end if; return (Pt => Result); end Binary_Operation; --------------------- -- Unary_Operation -- --------------------- function Unary_Operation (X : Parsed_Code; Operation : Tokens.Unary_Operator; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Unary_Op, Operand => X.Pt, Uni_Op => Operation, Source_Position => Position); begin if not (X.Pt.Class in Expression) then raise Program_Error; end if; return (Pt => Result); end Unary_Operation; --------------------- -- String_Constant -- --------------------- function String_Constant (Val : String; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Text_Constant, S => To_Unbounded_String (Val), Source_Position => Position); begin return (Pt => Result); end String_Constant; ---------------------- -- Integer_Constant -- ---------------------- function Integer_Constant (Val : String; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Int_Constant, N => Integer'Value (Val), Source_Position => Position); begin return (Pt => Result); end Integer_Constant; -------------------- -- Float_Constant -- -------------------- function Float_Constant (Val : String; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Real_Constant, X => Float'Value (Val), Source_Position => Position); begin return (Pt => Result); end Float_Constant; ---------------- -- Identifier -- ---------------- function Identifier (Id : String; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Identifier, Id_Value => To_Unbounded_String (Id), Source_Position => Position); begin return (Pt => Result); end Identifier; ------------------ -- Indexed_Name -- ------------------ function Indexed_Name (Function_Ref : Parsed_Code; Parameters : Tree_Array; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Indexed, Indexed_Var => Function_Ref.Pt, Indexes => To_Expression_Vector (Parameters), Source_Position => Position); begin if not (Result.Indexed_Var.Class in Name) then raise Program_Error; end if; return (Pt => Result); end Indexed_Name; -------------------- -- Procedure_Call -- -------------------- function Procedure_Call (Procedure_Name : String; Parameters : Tree_Array; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is begin return (Pt => new Node'(Class => Procedure_Call, Name => To_Unbounded_String (Procedure_Name), Params => To_Expression_Vector (Parameters), Source_Position => Position)); end Procedure_Call; function Procedure_Call (Procedure_Name : String) return Parsed_Code is (Procedure_Call (Procedure_Name, Empty_Tree_Array)); -------------- -- Selector -- -------------- function Selector (Ref : Parsed_Code; Field : String; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Selected, Record_Var => Ref.Pt, Field_Name => To_Unbounded_String (Field), Source_Position => Position); begin if not (Result.Record_Var.Class in Name) then raise Program_Error; end if; return (Pt => Result); end Selector; --------------- -- Loop_Exit -- --------------- function Loop_Exit (Label : String; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Exit_Statement, Loop_Label => To_Unbounded_String (Label), Source_Position => Position); begin return (Pt => Result); end Loop_Exit; ---------------- -- Basic_Loop -- ---------------- function Basic_Loop (Loop_Body : Parsed_Code; Label : String; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => Loop_Block, Loop_Body => <>, Labl => To_Unbounded_String (Label), Source_Position => Position); begin if Loop_Body.Pt.Class /= Statement_Sequence then raise Program_Error; else Result.Loop_Body := Loop_Body.Pt.Statements; end if; return (Pt => Result); end Basic_Loop; -- -------------- -- -- Get_Name -- -- -------------- -- -- function Get_Name (X : Parsed_Code) return Node_Access -- is -- begin -- if not (X.Pt.Class in Name) then -- raise Program_Error; -- end if; -- -- return X.Pt; -- end Get_Name; -------------------- -- Get_expression -- -------------------- function Get_Expression (X : Parsed_Code) return Node_Access is begin if not (X.Pt.Class in Expression) then raise Program_Error; end if; return X.Pt; end Get_Expression; -------------- -- For_Loop -- -------------- function For_Loop (Variable : String; Iterator : Parsed_Code; Loop_Body : Parsed_Code; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => For_Block, Loop_Body => <>, Labl => <>, Variable => To_Unbounded_String (Variable), Iterator => Get_Expression (Iterator), Source_Position => Position); begin if Loop_Body.Pt.Class /= Loop_Block then raise Program_Error; else Result.Loop_Body := Loop_Body.Pt.Loop_Body; Result.Labl := Loop_Body.Pt.Labl; end if; return (Pt => Result); end For_Loop; ---------------- -- While_Loop -- ---------------- function While_Loop (Condition : Parsed_Code; Loop_Body : Parsed_Code; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is Result : constant Node_Access := new Node'(Class => While_Block, Loop_Body => <>, Labl => <>, Condition => Get_Expression (Condition), Source_Position => Position); begin if Loop_Body.Pt.Class /= Loop_Block then raise Program_Error; else Result.Loop_Body := Loop_Body.Pt.Loop_Body; Result.Labl := Loop_Body.Pt.Labl; end if; return (Pt => Result); end While_Loop; ---------------------- -- Return_To_Caller -- ---------------------- function Return_To_Caller (Values : Tree_Array; Position : Tokens.Token_Position := Tokens.No_Position) return Parsed_Code is begin return (Pt => new Node'(Class => Return_Statement, Return_Values => To_Expression_Vector (Values), Source_Position => Position)); end Return_To_Caller; ------------ -- Delete -- ------------ procedure Delete (Code : in out Parsed_Code) is begin Delete (Code.Pt); end Delete; ------------ -- Delete -- ------------ procedure Delete (Item : in out Node_Vectors.Vector) is begin for Pos in Item.Iterate loop Delete (Item (Pos)); end loop; end Delete; ------------ -- Delete -- ------------ procedure Delete (Item : in out Parameter_Specs) is begin Delete (Item.Default); end Delete; ------------ -- Delete -- ------------ procedure Delete (Item : in out Node_Access) is begin if Item = null then return; end if; case Item.Class is when Parameter_Signature => Delete (Item.Signature); when Defun => Delete (Item.Function_Body); Delete (Item.Parameters); when Statement_Sequence => Delete (Item.Statements); -- when Naked => -- Delete (Item.Naked_Values); when Assignment => Delete (Item.Lhs); Delete (Item.Rvalues); when Return_Statement => Delete (Item.Return_Values); when Procedure_Call | Capture_Call => Delete (Item.Params); when Exit_Statement => null; when If_Block => if Item.Else_Branch /= null then Delete (Item.Else_Branch); end if; when List_Of_Names => Delete (Item.Names); when List_Of_Expressions => Delete (Item.Exprs); when Binary_Op => Delete (Item.Left); Delete (Item.Right); when Unary_Op => Delete (Item.Operand); when Int_Constant | Real_Constant | Text_Constant | Identifier => null; when Selected => Delete (Item.Record_Var); when Indexed => Delete (Item.Indexed_Var); Delete (Item.Indexes); when Loop_Block => Delete (Item.Loop_Body); when For_Block => Delete (Item.Loop_Body); Delete (Item.Iterator); when While_Block => Delete (Item.Loop_Body); end case; Free (Item); end Delete; ---------- -- Dump -- ---------- procedure Dump (Item : Node_Vectors.Vector; Level : Natural; Label : String := "") is begin for El of Item loop Dump (El, Level, Label); end loop; end Dump; ---------- -- Dump -- ---------- procedure Dump (Branches : Conditional_Branch_Vectors.Vector; Level : Natural; Label : String) is begin for Branch of Branches loop Dump (Branch.Condition, Level, Label & "(condition)"); Dump (Branch.Code, Level, Label & "(branch)"); end loop; end Dump; ---------- -- Dump -- ---------- procedure Dump (Item : Node_Access; Level : Natural; Label : String := "") is use Ada.Strings.Fixed; function Tabbing (N : Natural) return String is ((N * 3) * " "); procedure Dump (Item : Unbounded_String; Level : Natural) is begin Put_Line (Tabbing (Level) & To_String (Item)); end Dump; procedure Dump (Item : Parameter_Specs; Level : Natural) is begin for Name of Item.Names loop Put_Line (Tabbing (Level + 1) & String (Name)); end loop; Dump (Item.Default, Level + 1); end Dump; function Full_Label return String is (Item.Class'Image & (if Label = "" then "" else " (" & Label & ")")); begin if Item = null then Put_Line (Tabbing (Level) & "(void)"); return; end if; Put_Line (Tabbing (Level) & "[" & Full_Label & "]"); case Item.Class is when Parameter_Signature => Dump (Item.Signature, Level); when Defun => Put_Line (Tabbing (Level) & (if Item.Is_Function then "FUNCTION" else "PROCEDURE")); Put_Line (Tabbing (Level) & "Name = '" & To_String (Item.Definition_Name) & "'"); Dump (Item.Parameters, Level); Dump (Item.Function_Body, Level + 1); when Statement_Sequence => Dump (Item.Statements, Level + 1); -- when Naked => -- Dump (Item.Naked_Values, Level + 1); when Assignment => Dump (Item.Lhs, Level + 1, "LHS"); Dump (Item.Rvalues, Level + 1, "RHS"); when Return_Statement => Dump (Item.Return_Values, Level + 1); when Procedure_Call | Capture_Call => Dump (Unbounded_String (Item.Name), Level + 1); Dump (Item.Params, Level + 1, (if Item.Class = Procedure_Call then "procedure" else "capture")); when Exit_Statement => null; when If_Block => Dump (Item.Branches, Level + 1, "branches"); if Item.Else_Branch /= null then Dump (Item.Else_Branch, Level + 1, "else branch"); end if; when List_Of_Names => Dump (Item.Names, Level + 1); when List_Of_Expressions => Dump (Item.Exprs, Level + 1); when Binary_Op => Put_Line (Tabbing (Level) & Item.Operator'Image); Dump (Item.Left, Level + 1, "left"); Dump (Item.Right, Level + 1, "right"); when Unary_Op => Put_Line (Tabbing (Level) & Item.Uni_Op'Image); Dump (Item.Operand, Level + 1); when Int_Constant => Put_Line (Tabbing (Level) & Item.N'Image); when Real_Constant => Put_Line (Tabbing (Level) & Item.X'Image); when Text_Constant => Put_Line (Tabbing (Level) & """" & To_String (Item.S) & """"); when Identifier => Put_Line (Tabbing (Level) & "<" & To_String (Item.Id_Value) & ">"); when Selected => Dump (Item.Record_Var, Level + 1); Put_Line (Tabbing (Level + 1) & "." & To_String (Item.Field_Name)); when Indexed => Dump (Item.Indexed_Var, Level + 1); Dump (Item.Indexes, Level + 1, "index"); when Loop_Block => Put_Line (Tabbing (Level + 1) & "Label: <" & To_String (Item.Labl) & ">"); Dump (Item.Loop_Body, Level + 1); when For_Block => Put_Line (Tabbing (Level + 1) & "Label: <" & To_String (Item.Labl) & ">"); Dump (Item.Loop_Body, Level + 1); Dump (Item.Variable, Level + 1); Dump (Item.Iterator, Level + 1); when While_Block => Put_Line (Tabbing (Level + 1) & "Label: <" & To_String (Item.Labl) & ">"); Dump (Item.Loop_Body, Level + 1); Dump (Item.Condition, Level + 1); end case; Put_Line (Tabbing (Level) & "[/" & Full_Label & "]"); end Dump; procedure Dump (Code : Parsed_Code) is begin Put_Line ("<<INTERNAL FORM DUMP>>"); Dump (Code.Pt, 0); Put_Line ("<</ INTERNAL FORM DUMP>>"); end Dump; end Protypo.Code_Trees;
----------------------------------------------------------------------- -- package body Predictor_2, 20th order Predictor-Corrector -- Copyright (C) 2008-2018 Jonathan S. Parker. -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ----------------------------------------------------------------------- with pc_2_interface; with Runge_pc_2; package body Predictor_2 is package Runge_pc is new Runge_pc_2 (Real, Dyn_Index, Dynamical_Variable, F); package Coeffs is new pc_2_interface.Predictor_Corrector_Rules (Real); use Coeffs; type Second_Deriv_History is array(PC_Rule_Range) of Dynamical_Variable; --------------- -- Integrate -- --------------- procedure Integrate (Final_Y : out Dynamical_Variable; Final_deriv_Of_Y : out Dynamical_Variable; Final_Time : in Real; Initial_Y : in Dynamical_Variable; Initial_deriv_Of_Y : in Dynamical_Variable; Initial_Time : in Real; No_Of_Steps : in Real) is Delta_t : constant Real := (Final_Time - Initial_Time) / No_Of_Steps; Final_Time_Test : constant Real := Abs (Final_Time-Initial_Time + 0.9*Delta_t); -- Notice Delta_t can be negative, (when itegrating backward in time). New_t, Previous_t : Real; New_Y_Corrector, Predict_Last, Correct_Last, Integral_Last : Real; Predictor, Corrector : Integration_Rule; Integrate_to_End, First_Integral : Integration_Rule; Previous_Deriv_of_Y_x_dt : Dynamical_Variable; Previous_Deriv_of_Y : Dynamical_Variable; New_Deriv_of_Y_x_dt : Dynamical_Variable; New_Deriv_of_Y : Dynamical_Variable; New_Y, Previous_Y : Dynamical_Variable; Index_Of_Oldest_Deriv : PC_Rule_Range := PC_Rule_Range'First; Second_Deriv_Storage : Second_Deriv_History; -------------------------- -- Vectors_x_Matrix -- -------------------------- -- in applications where Predictor_Corrector's are appropriate, -- Second_Deriv_History is usually a giant array that spills out -- cache. Fetching it from mem is slow, so below we fetch it -- once, rather than 3 times. subtype Matrix is Second_Deriv_History; subtype Matrix_Row is Dynamical_Variable; subtype Vector is Integration_Rule; procedure Vectors_x_Matrix (Mat : in Matrix; Vector1 : in Vector; Vector2 : in Vector; Vector3 : in Vector; Product1 : out Matrix_Row; Product2 : out Matrix_Row; Product3 : out Matrix_Row) is Row_ID : PC_Rule_Range'Base; Sum1, Sum2, Sum3 : Real; begin for Col in Dyn_Index loop Row_ID := PC_Rule_Range'First; Sum1 := 0.0; Sum2 := 0.0; Sum3 := 0.0; for i in PC_Rule_Range loop Sum1 := Sum1 + Mat(Row_ID)(Col) * Vector1(Row_ID); Sum2 := Sum2 + Mat(Row_ID)(Col) * Vector2(Row_ID); Sum3 := Sum3 + Mat(Row_ID)(Col) * Vector3(Row_ID); Row_ID := Row_ID + 1; end loop; Product1(Col) := Sum1; Product2(Col) := Sum2; Product3(Col) := Sum3; end loop; end Vectors_x_Matrix; --------------------------------- -- First_Integral_of_2nd_deriv -- --------------------------------- function First_Integral_of_2nd_deriv (New_Deriv_of_Y_x_dt : in Dynamical_Variable; Index_Of_Oldest_Deriv : in PC_Rule_Range; Delta_t : in Real) return Dynamical_Variable is Product1 : Dynamical_Variable; Shift, i : PC_Rule_Range'Base; Sum1 : Real; Inverse_Delta_t : Real := 1.0 / Delta_t; begin Shift := PC_Rule_Range'First; for k in Index_Of_Oldest_Deriv .. PC_Rule_Range'Last loop Integrate_to_End(k) := Delta_t * Center_to_End_Integration(Shift); Shift := Shift + 1; end loop; if Index_Of_Oldest_Deriv > PC_Rule_Range'First then for k in PC_Rule_Range'First .. Index_Of_Oldest_Deriv-1 loop Integrate_to_End(k) := Delta_t * Center_to_End_Integration(Shift); Shift := Shift + 1; end loop; end if; for Col in Dyn_Index loop i := PC_Rule_Range'First; Sum1 := 0.0; for k in PC_Rule_Range loop Sum1 := Sum1 + Second_Deriv_Storage(i)(Col) * Integrate_to_End(i); i := i + 1; end loop; Product1(Col) := Sum1; end loop; return Product1 + Inverse_Delta_t * New_Deriv_of_Y_x_dt; end First_Integral_of_2nd_deriv; begin -- Integrate -- always init out params: Final_Y := Initial_Y; Final_deriv_Of_Y := Initial_deriv_Of_Y; for i in PC_Rule_Range loop Predictor(i) := Delta_t**2 * Predictor_Rule(i); end loop; for i in PC_Rule_Range loop Corrector(i) := Delta_t**2 * Corrector_Rule(i); end loop; New_Y_Corrector := Delta_t**2 * Final_Step_Corrector; for i in PC_Rule_Range loop First_Integral(i) := Delta_t**2 * Center_Integration(i); end loop; Previous_Y := Initial_Y; Previous_deriv_Of_Y := Initial_deriv_Of_Y; Previous_t := Initial_Time; Index_Of_Oldest_Deriv := PC_Rule_Range'First; Second_Deriv_Storage(PC_Rule_Range'First) := F (Previous_t, Previous_Y); for I in PC_Rule_Range'First+1 .. PC_Rule_Range'Last loop New_t := Previous_t + Delta_t; if Abs (New_t - Initial_Time) > Final_Time_Test then Final_Y := Previous_Y; Final_deriv_Of_Y := Previous_deriv_Of_Y; return; end if; Runge_pc.Integrate (Final_Y => New_Y, Final_deriv_Of_Y => New_Deriv_of_Y, Final_Time => New_t, Initial_Y => Previous_Y, Initial_deriv_Of_Y => Previous_Deriv_of_Y, Initial_Time => Previous_t, No_Of_Steps => 4.0); -- Use 7th order method and small Delta_t for better accuracy? if I = Starting_Id_of_First_Deriv_of_Y then Previous_Deriv_of_Y_x_dt := Delta_t * New_Deriv_of_Y; end if; Second_Deriv_Storage(i) := F (New_t, New_Y); Previous_Y := New_Y; Previous_deriv_Of_Y := New_deriv_Of_Y; Previous_t := New_t; end loop; Time_Steps: Loop New_t := Previous_t + Delta_t; if Abs (New_t - Initial_Time) > Final_Time_Test then -- tried to go too far Final_Y := Previous_Y; Final_deriv_Of_Y := First_Integral_of_2nd_deriv (Previous_Deriv_of_Y_x_dt, Index_Of_Oldest_Deriv, Delta_t); exit Time_Steps; end if; Predict_and_Correct: declare Predictor_Delta_Y : Dynamical_Variable; Corrector_Delta_Y : Dynamical_Variable; Delta_Deriv_of_Y_x_dt : Dynamical_Variable; Predicted_New_Y : Dynamical_Variable; Almost_New_Y : Dynamical_Variable; Error_in_New_Y : Dynamical_Variable; New_2nd_Deriv_Val : Dynamical_Variable; begin Vectors_x_Matrix (Mat => Second_Deriv_Storage, Vector1 => Predictor, Vector2 => Corrector, Vector3 => First_Integral, Product1 => Predictor_Delta_Y, Product2 => Corrector_Delta_Y, Product3 => Delta_Deriv_of_Y_x_dt); New_Deriv_of_Y_x_dt := Previous_Deriv_of_Y_x_dt + Delta_Deriv_of_Y_x_dt; Predicted_New_Y := Predictor_Delta_Y + Previous_Y + New_Deriv_of_Y_x_dt; New_2nd_Deriv_Val := F (New_t, Predicted_New_Y); Almost_New_Y := Corrector_Delta_Y + Previous_Y + New_Deriv_of_Y_x_dt; for I in 1 .. No_Of_Corrector_Evaluate_Iterations loop New_Y := Almost_New_Y + New_Y_Corrector * New_2nd_Deriv_Val; New_2nd_Deriv_Val := F (New_t, New_Y); end loop; if Final_Corrector_Desired then New_Y := Almost_New_Y + New_Y_Corrector * New_2nd_Deriv_Val; end if; if Extrapolation_Desired then Error_in_New_Y := Extrap_Factor * (New_Y - Predicted_New_Y); New_Y := New_Y - Error_in_New_Y; end if; Second_Deriv_Storage(Index_Of_Oldest_Deriv) := New_2nd_Deriv_Val; end Predict_and_Correct; -- rotate the rule arrays. seems as fast as shifting the index -- during the dot product with the derivatives. if Index_Of_Oldest_Deriv = PC_Rule_Range'Last then Index_Of_Oldest_Deriv := PC_Rule_Range'First; else Index_Of_Oldest_Deriv := Index_Of_Oldest_Deriv + 1; end if; Predict_Last := Predictor(PC_Rule_Range'Last); for I in reverse PC_Rule_Range'First+1 .. PC_Rule_Range'Last loop Predictor(I) := Predictor(I-1); end loop; Predictor(PC_Rule_Range'First) := Predict_Last; Correct_Last := Corrector(PC_Rule_Range'Last); for I in reverse PC_Rule_Range'First+1 .. PC_Rule_Range'Last loop Corrector(I) := Corrector(I-1); end loop; Corrector(PC_Rule_Range'First) := Correct_Last; Integral_Last := First_Integral(PC_Rule_Range'Last); for I in reverse PC_Rule_Range'First+1 .. PC_Rule_Range'Last loop First_Integral(I) := First_Integral(I-1); end loop; First_Integral(PC_Rule_Range'First) := Integral_Last; Previous_Deriv_of_Y_x_dt := New_Deriv_of_Y_x_dt; Previous_Y := New_Y; Previous_t := New_t; end loop Time_Steps; end Integrate; end Predictor_2;
pragma License (Unrestricted); with Ada.Characters.Conversions; with Ada.Strings.Generic_Hash; function Ada.Strings.Wide_Wide_Hash is new Generic_Hash ( Wide_Wide_Character, Wide_Wide_String, Characters.Conversions.Get); pragma Pure (Ada.Strings.Wide_Wide_Hash);
-- C37211E.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. --* -- CHECK THAT CONSTRAINT_ERROR IS RAISED BY A DISCRIMINANT CONSTRAINT -- IF A VALUE SPECIFIED FOR A DISCRIMINANT DOES NOT LIE IN THE RANGE -- OF THE DISCRIMINANT. -- R.WILLIAMS 8/28/86 -- PWN 10/27/95 REMOVED CHECK WHERE CONSTRAINT RULES HAVE CHANGED. -- PWN 12/03/95 CORRECTED FORMATING PROBLEM. -- TMB 11/20/96 REINTRODUCED CHECK REMOVED ON 10/27 WITH ADA95 CHANGES -- TMB 12/2/96 DELETED CHECK OF CONSTRAINED ACCESS TYPE -- EDS 07/14/98 AVOID OPTIMIZATION WITH REPORT; USE REPORT; PROCEDURE C37211E IS TYPE REC (D : POSITIVE) IS RECORD NULL; END RECORD; TYPE ACC IS ACCESS REC; BEGIN TEST ( "C37211E", "CHECK THAT CONSTRAINT_ERROR IS RAISED BY " & "A DISCRIMINANT CONSTRAINT IF A VALUE " & "SPECIFIED FOR A DISCRIMINANT DOES NOT LIE " & "IN THE RANGE OF THE DISCRIMINANT WHERE THE " & "TYPE MARK DENOTES AN ACCESS TYPE" ); BEGIN DECLARE SUBTYPE SUBACC IS ACC (IDENT_INT (-1)); BEGIN DECLARE SA : SUBACC; BEGIN FAILED ( "NO EXCEPTION RAISED AT THE " & "ELABORATION OF SUBTYPE SUBACC " & INTEGER'IMAGE(SA.D)); END; EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED AT DECLARATION OF " & "OBJECT SA" ); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED AT ELABORATION OF " & "SUBTYPE SUBACC" ); END; BEGIN DECLARE TYPE ARR IS ARRAY (1 .. 10) OF ACC (IDENT_INT (-1)); BEGIN DECLARE AR : ARR; BEGIN FAILED ( "NO EXCEPTION RAISED AT THE " & "ELABORATION OF TYPE ARR " & INTEGER'IMAGE(AR(1).D)); END; EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED AT DECLARATION OF " & "OBJECT AR" ); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED AT ELABORATION OF " & "TYPE ARR" ); END; BEGIN DECLARE TYPE REC1 IS RECORD X : ACC (IDENT_INT (-1)); END RECORD; BEGIN DECLARE R1 : REC1; BEGIN FAILED ( "NO EXCEPTION RAISED AT THE " & "ELABORATION OF TYPE REC1 " & INTEGER'IMAGE(R1.X.D)); END; EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED AT DECLARATION OF " & "OBJECT R1" ); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED AT ELABORATION OF " & "TYPE REC1" ); END; BEGIN DECLARE TYPE ACCA IS ACCESS ACC (IDENT_INT (-1)); BEGIN DECLARE ACA : ACCA; BEGIN FAILED ( "NO EXCEPTION RAISED AT THE " & "ELABORATION OF TYPE ACCA " & INTEGER'IMAGE(ACA.ALL.D)); END; EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED AT DECLARATION OF " & "OBJECT ACA" ); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED AT ELABORATION OF " & "TYPE ACCA" ); END; BEGIN DECLARE TYPE NEWACC IS NEW ACC (IDENT_INT (-1)); BEGIN DECLARE NA : NEWACC; BEGIN FAILED ( "NO EXCEPTION RAISED AT THE " & "ELABORATION OF TYPE NEWACC " & INTEGER'IMAGE(NA.D)); END; EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED AT DECLARATION OF " & "OBJECT NA" ); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED AT ELABORATION OF " & "TYPE NEWACC" ); END; BEGIN DECLARE A : ACC (IDENT_INT (-1)); BEGIN FAILED ( "NO EXCEPTION RAISED AT THE DECLARATION OF " & "A " & INTEGER'IMAGE(A.D)); EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED INSIDE BLOCK " & "CONTAINING A" ); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED AT DECLARATION OF " & "A" ); END; BEGIN DECLARE TYPE BAD_ACC (D : POSITIVE := IDENT_INT (-1)) IS RECORD NULL; END RECORD; BEGIN DECLARE BAC : BAD_ACC; BEGIN FAILED ( "NO EXCEPTION RAISED AT THE " & "DECLARATION OF OBJECT BAC " & INTEGER'IMAGE(BAC.D)); EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED INSIDE BLOCK " & "DECLARING BAC" ); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ( "WRONG EXCEPTION RAISED AT DECLARATION " & "OF OBJECT BAC" ); END; EXCEPTION WHEN OTHERS => FAILED ( "EXCEPTION RAISED AT ELABORATION OF TYPE " & "BAD_ACC" ); END; RESULT; END C37211E;
-- auto generated - do not edit package PGAda.Errors is pragma Preelaborate; type Error_Value_t is ( Successful_Completion, Warning, Warn_Dynamic_Result_Sets_Returned, Warn_Implicit_Zero_Bit_Padding, Warn_Null_Value_Eliminated_In_Set_Function, Warn_Privilege_Not_Granted, Warn_Privilege_Not_Revoked, Warn_String_Data_Right_Truncation, Deprecated_Feature, No_Data, No_Additional_Dynamic_Result_Sets_Returned, SQL_Statement_Not_Yet_Complete, Connection_Exception, Connection_Does_Not_Exist, Connection_Failure, SQL_Client_Unable_To_Establish_SQL_Connection, SQL_Server_Rejected_Establishment_Of_SQL_Connection, Transaction_Resolution_Unknown, Protocol_Violation, Triggered_Action_Exception, Feature_Not_Supported, Invalid_Transaction_Initiation, Locator_Exception, Invalid_Locator_Specification, Invalid_Grantor, Invalid_Grant_Operation, Invalid_Role_Specification, Cardinality_Violation, Data_Exception, Array_Subscript_Error, Character_Not_In_Repertoire, Datetime_Field_Overflow, Division_By_Zero, Error_In_Assignment, Escape_Character_Conflict, Indicator_Overflow, Interval_Field_Overflow, Invalid_Argument_For_Logarithm, Invalid_Argument_For_Power_Function, Invalid_Argument_For_Width_Bucket_Function, Invalid_Character_Value_For_Cast, Invalid_Datetime_Format, Invalid_Escape_Character, Invalid_Escape_Octet, Invalid_Escape_Sequence, Nonstandard_Use_Of_Escape_Character, Invalid_Indicator_Parameter_Value, Invalid_Limit_Value, Invalid_Parameter_Value, Invalid_Regular_Expression, Invalid_Time_Zone_Displacement_Value, Invalid_Use_Of_Escape_Character, Most_Specific_Type_Mismatch, Null_Value_Not_Allowed, Null_Value_No_Indicator_Parameter, Numeric_Value_Out_Of_Range, String_Data_Length_Mismatch, String_Data_Right_Truncation, Substring_Error, Trim_Error, Unterminated_C_String, Zero_Length_Character_String, Floating_Point_Exception, Invalid_Text_Representation, Invalid_Binary_Representation, Bad_Copy_File_Format, Untranslatable_Character, Not_An_XML_Document, Invalid_XML_Document, Invalid_XML_Content, Invalid_XML_Comment, Invalid_XML_Processing_Instruction, Integrity_Constraint_Violation, Restrict_Violation, Not_Null_Violation, Foreign_Key_Violation, Unique_Violation, Check_Violation, Invalid_Cursor_State, Invalid_Transaction_State, Active_SQL_Transaction, Branch_Transaction_Already_Active, Held_Cursor_Requires_Same_Isolation_Level, Inappropriate_Access_Mode_For_Branch_Transaction, Inappropriate_Isolation_Level_For_Branch_Transaction, No_Active_SQL_Transaction_For_Branch_Transaction, Read_Only_SQL_Transaction, Schema_And_Data_Statement_Mixing_Not_Supported, No_Active_SQL_Transaction, In_Failed_SQL_Transaction, Invalid_SQL_Statement_Name, Triggered_Data_Change_Violation, Invalid_Authorization_Specification, Dependent_Privilege_Descriptors_Still_Exist, Dependent_Objects_Still_Exist, Invalid_Transaction_Termination, SRE_SQL_Routine_Exception, SRE_Function_Executed_No_Return_Statement, SRE_Modifying_SQL_Data_Not_Permitted, SRE_Prohibited_SQL_Statement_Attempted, SRE_Reading_SQL_Data_Not_Permitted, Invalid_Cursor_Name, ERE_External_Routine_Exception, ERE_Containing_SQL_Not_Permitted, ERE_Modifying_SQL_Data_Not_Permitted, ERE_Prohibited_SQL_Statement_Attempted, ERE_Reading_SQL_Data_Not_Permitted, ERI_External_Routine_Invocation_Exception, ERI_Invalid_SQLstate_Returned, ERI_Null_Value_Not_Allowed, ERI_Trigger_Protocol_Violated, ERI_SRF_Protocol_Violated, Savepoint_Exception, Invalid_Savepoint_Specification, Invalid_Catalog_Name, Invalid_Schema_Name, Transaction_Rollback, Transaction_Integrity_Constraint_Violation, Serialization_Failure, Statement_Completion_Unknown, Deadlock_Detected, Syntax_Error_Or_Access_Rule_Violation, Syntax_Error, Insufficient_Privilege, Cannot_Coerce, Grouping_Error, Invalid_Foreign_Key, Invalid_Name, Name_Too_Long, Reserved_Name, Datatype_Mismatch, Indeterminate_Datatype, Wrong_Object_Type, Undefined_Column, Undefined_Function, Undefined_Table, Undefined_Parameter, Undefined_Object, Duplicate_Column, Duplicate_Cursor, Duplicate_Database, Duplicate_Function, Duplicate_Prepared_Statement, Duplicate_Schema, Duplicate_Table, Duplicate_Alias, Duplicate_Object, Ambiguous_Column, Ambiguous_Function, Ambiguous_Parameter, Ambiguous_Alias, Invalid_Column_Reference, Invalid_Column_Definition, Invalid_Cursor_Definition, Invalid_Database_Definition, Invalid_Function_Definition, Invalid_Prepared_Statement_Definition, Invalid_Schema_Definition, Invalid_Table_Definition, Invalid_Object_Definition, With_Check_Option_Violation, Insufficient_Resources, Disk_Full, Out_Of_Memory, Too_Many_Connections, Program_Limit_Exceeded, Statement_Too_Complex, Too_Many_Columns, Too_Many_Arguments, Object_Not_In_Prerequisite_State, Object_In_Use, Cant_Change_Runtime_Param, Lock_Not_Available, Operator_Intervention, Query_Canceled, Admin_Shutdown, Crash_Shutdown, Cannot_Connect_Now, IO_Error, Undefined_File, Duplicate_File, Config_File_Error, Lock_File_Exists, Plpgsql_Error, Raise_Exception, No_Data_Found, Too_Many_Rows, Internal_Error, Data_Corrupted, Index_Corrupted, Unknown_Error ); function Error_Value (code : String) return Error_Value_t; end PGAda.Errors;
package Discr34_Pkg is function N return Natural; type Enum is (One, Two); type Rec (D : Enum := One) is record case D is when One => S : String (1 .. N); when Two => null; end case; end record; function F return Rec; end Discr34_Pkg;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. with Ada.Assertions, Apsepp.Debug_Trace, Apsepp.Debug_Trace_Class.Standard, Apsepp.Generic_Shared_Instance.Access_Setter, Apsepp.Test_Node_Class.Abstract_Simu_Case, Apsepp.Test_Node_Class.Runner_Sequential.Create, Apsepp.Test_Node_Class.Runner_Sequential.W_Slave_Nodes.Create, Apsepp_Test_Node_Barrier.Create_Test_Reporter; package body Apsepp_Testing_System_Test_Fixture is use Apsepp.Test_Node_Class.Abstract_Simu_Case, Apsepp.Test_Node_Class.Runner_Sequential, Apsepp.Test_Node_Class.Runner_Sequential.W_Slave_Nodes, Apsepp.Test_Node_Class, Apsepp_Test_Node_Barrier; ---------------------------------------------------------------------------- function Char_Name_Image (Char : ISO_646) return String is (" (" & To_Upper (Char) & (if Is_Lower (Char) then "_R" else "") & "): "); ---------------------------------------------------------------------------- subtype Simu_Case_Char_Name is ISO_646_Upper_Letter range 'A' .. 'E'; type Test_Node_Char_Array is array (ISO_646_Upper_Letter range <>) of Test_Node_Access; ---------------------------------------------------------------------------- type Simu_Test_Case_A is limited new Simu_Test_Case with null record; ----------------------------------------------------- overriding function Story (Obj : Simu_Test_Case_A) return Simu_Test_Case_Story; overriding function Story (Obj : Simu_Test_Case_A) return Simu_Test_Case_Story is ((Kind => No_Failure, Successful_Test_Assert_Count => 3), (Kind => Test_Assertion_Failure, Successful_Test_Assert_Count => 2), (Kind => No_Failure, Successful_Test_Assert_Count => 1), (Kind => No_Failure, Successful_Test_Assert_Count => 0)); ----------------------------------------------------- type Simu_Test_Case_B is limited new Simu_Test_Case with null record; overriding function Story (Obj : Simu_Test_Case_B) return Simu_Test_Case_Story; overriding function Story (Obj : Simu_Test_Case_B) return Simu_Test_Case_Story is ((Kind => Other_Failure, Successful_Test_Assert_Count => 5), (Kind => No_Failure, Successful_Test_Assert_Count => 0)); -- 2nd test routine not run (unexpected failure on 1st test routine causes -- the following test routines to be cancelled). ----------------------------------------------------- type Simu_Test_Case_C is limited new Simu_Test_Case with null record; overriding function Story (Obj : Simu_Test_Case_C) return Simu_Test_Case_Story; overriding function Story (Obj : Simu_Test_Case_C) return Simu_Test_Case_Story is ((Kind => No_Failure, Successful_Test_Assert_Count => 7), (Kind => No_Failure, Successful_Test_Assert_Count => 6)); ----------------------------------------------------- type Simu_Test_Case_D is limited new Simu_Test_Case with null record; overriding function Story (Obj : Simu_Test_Case_D) return Simu_Test_Case_Story; overriding function Story (Obj : Simu_Test_Case_D) return Simu_Test_Case_Story is ((Kind => No_Failure, Successful_Test_Assert_Count => 1), (Kind => Access_Failure, Successful_Test_Assert_Count => 0), (Kind => No_Failure, Successful_Test_Assert_Count => 0)); -- 3rd test routine not run (access failure on 2nd test routine causes the -- following test routines to be cancelled). ----------------------------------------------------- type Simu_Test_Case_E is limited new Simu_Test_Case with null record; overriding function Story (Obj : Simu_Test_Case_E) return Simu_Test_Case_Story; overriding function Story (Obj : Simu_Test_Case_E) return Simu_Test_Case_Story is ((Kind => Handled_Test_Failure, Successful_Test_Assert_Count => 3), (Kind => No_Failure, Successful_Test_Assert_Count => 2), (Kind => Contract_Failure, Successful_Test_Assert_Count => 4), (Kind => Setup_Failure, Successful_Test_Assert_Count => 0), (Kind => No_Failure, Successful_Test_Assert_Count => 0)); -- 4th test routine not run (setup failure on 4th test routine causes the -- following test routines to be cancelled). ----------------------------------------------------- Simu_Case_A : aliased Simu_Test_Case_A; Simu_Case_B : aliased Simu_Test_Case_B; Simu_Case_C : aliased Simu_Test_Case_C; Simu_Case_D : aliased Simu_Test_Case_D; Simu_Case_E : aliased Simu_Test_Case_E; Simu_Case : constant Test_Node_Char_Array (Simu_Case_Char_Name) := (Simu_Case_A'Access, Simu_Case_B'Access, Simu_Case_C'Access, Simu_Case_D'Access, Simu_Case_E'Access); ---------------------------------------------------------------------------- type Test_Runner_Sequential_B is limited new Test_Runner_Sequential with null record; type Test_Runner_Sequential_C is limited new Test_Runner_Sequential with null record; type Test_Runner_Sequential_D is limited new Test_Runner_Sequential with null record; type Test_Runner_Sequential_E is limited new Test_Runner_Sequential with null record; ----------------------------------------------------- -- Runner "A" is created in procedure Run_Test. Runner_B : aliased Test_Runner_Sequential_B := (Apsepp.Test_Node_Class.Runner_Sequential.Create (Simu_Case('B')) with null record); Runner_C : aliased Test_Runner_Sequential_C := (Apsepp.Test_Node_Class.Runner_Sequential.Create (Simu_Case('C')) with null record); Runner_D : aliased Test_Runner_Sequential_D := (Apsepp.Test_Node_Class.Runner_Sequential.Create (Simu_Case('D')) with null record); Runner_E : aliased Test_Runner_Sequential_E := (Apsepp.Test_Node_Class.Runner_Sequential.Create (Simu_Case('E')) with null record); Slave_Runner_Arr : constant Test_Node_Char_Array (ISO_646_Upper_Letter'Succ (Simu_Case_Char_Name'First) .. Simu_Case_Char_Name'Last) := (Runner_B'Access, Runner_C'Access, Runner_D'Access, Runner_E'Access); ---------------------------------------------------------------------------- function Runner_Tag (Char : ISO_646_Upper_Letter) return Tag is (if Char = Simu_Case_Char_Name'First then Test_Runner_Sequential_W_Slave_Tasks'Tag else Slave_Runner_Arr(Char)'Tag); ---------------------------------------------------------------------------- function Tag_To_Char (T : Tag) return ISO_646 is First : Boolean := True; Found, Loop_Done, Is_Runner_Tag : Boolean := False; Ret : ISO_646 := Simu_Case'First; begin -- TODO: Write function Find or Find_First in Generic_Array_Operations. -- <2019-06-09> while not (Found or else Loop_Done) loop Loop_Done := Ret >= Simu_Case'Last; if not (Loop_Done or else First) then Ret := ISO_646'Succ (Ret); end if; First := False; if Ret <= Simu_Case'Last then if Simu_Case(Ret)'Tag = T then Found := True; elsif Runner_Tag(Ret) = T then Found := True; Is_Runner_Tag := True; end if; end if; end loop; Ada.Assertions.Assert (Found, "Unexpected tag: " & (if T = No_Tag then "No_Tag" else Expanded_Name (T))); if Is_Runner_Tag then Ret := To_Lower (Ret); end if; return Ret; end Tag_To_Char; ---------------------------------------------------------------------------- function Char_To_Tag (Char : ISO_646_Upper_Letter) return Tag is K : Simu_Case_Char_Name := Simu_Case_Char_Name'First; Last_Done : Boolean := False; function Done return Boolean is (Last_Done or else Char not in Simu_Case_Char_Name); begin Ada.Assertions.Assert (not Done, Char & " not in " & K & " .. " & Simu_Case_Char_Name'Last); while not Done loop if Tag_To_Char (Simu_Case(K)'Tag) = Char or else K = Simu_Case_Char_Name'Last then Last_Done := True; else K := Simu_Case_Char_Name'Succ (K); end if; end loop; Ada.Assertions.Assert (Tag_To_Char (Simu_Case(K)'Tag) = Char, "Cannot find tag corresponding to '" & Char & "'"); return Simu_Case(K)'Tag; end Char_To_Tag; ---------------------------------------------------------------------------- not overriding function A (Obj : Testing_System_Test_Fixture) return Tag is (Simu_Case('A')'Tag); not overriding function B (Obj : Testing_System_Test_Fixture) return Tag is (Simu_Case('B')'Tag); not overriding function C (Obj : Testing_System_Test_Fixture) return Tag is (Simu_Case('C')'Tag); not overriding function D (Obj : Testing_System_Test_Fixture) return Tag is (Simu_Case('D')'Tag); not overriding function E (Obj : Testing_System_Test_Fixture) return Tag is (Simu_Case('E')'Tag); not overriding function A_R (Obj : Testing_System_Test_Fixture) return Tag is (Test_Runner_Sequential_W_Slave_Tasks'Tag); not overriding function B_R (Obj : Testing_System_Test_Fixture) return Tag is (Slave_Runner_Arr('B')'Tag); not overriding function C_R (Obj : Testing_System_Test_Fixture) return Tag is (Slave_Runner_Arr('C')'Tag); not overriding function D_R (Obj : Testing_System_Test_Fixture) return Tag is (Slave_Runner_Arr('D')'Tag); not overriding function E_R (Obj : Testing_System_Test_Fixture) return Tag is (Slave_Runner_Arr('E')'Tag); ---------------------------------------------------------------------------- procedure Assert_Node_Tags is Not_All_Desc : constant String := " elements are not all descendant of "; Dup_Tag : constant String := "Duplicate tag in array "; begin Ada.Assertions.Assert ((for all E of Simu_Case => Is_Descendant_At_Same_Level (E'Tag, Simu_Test_Case'Tag)), "Simu_Case" & Not_All_Desc & "Simu_Test_Case"); Ada.Assertions.Assert ((for all K_1 in Simu_Case'Range => (for all K_2 in Simu_Case'Range => K_1 = K_2 or else Simu_Case(K_1)'Tag /= Simu_Case(K_2)'Tag)), Dup_Tag & "Simu_Case"); Ada.Assertions.Assert ((for all E of Slave_Runner_Arr => Is_Descendant_At_Same_Level (E'Tag, Test_Runner_Sequential'Tag)), "Slave_Runner_Arr" & Not_All_Desc & "Test_Runner_Sequential"); Ada.Assertions.Assert (not (for some E of Slave_Runner_Arr => E'Tag = Test_Runner_Sequential_W_Slave_Tasks'Tag), "No element in Slave_Runner_Arr should have the tag of " & "Test_Runner_Sequential_W_Slave_Tasks"); Ada.Assertions.Assert ((for all K_1 in Slave_Runner_Arr'Range => (for all K_2 in Slave_Runner_Arr'Range => K_1 = K_2 or else Slave_Runner_Arr(K_1)'Tag /= Slave_Runner_Arr(K_2)'Tag)), Dup_Tag & "Slave_Runner_Arr"); end Assert_Node_Tags; ---------------------------------------------------------------------------- procedure Assert_Barrier_Status (Barrier : not null Test_Node_Barrier_Access; Expected_Tag_Length : Natural) is F : constant Boolean := Barrier.Timed_Out; N : constant Natural := Barrier.Cross_Count_On_Time_Out; M : constant String := (if F then (if N = 0 then ", no crossing happened" else " after crossing ") else ""); Image_N : String := (if F and then N > 0 then Positive'Image (N) else ""); begin if Image_N'Length > 0 then Image_N(Image_N'First) := '#'; end if; Ada.Assertions.Assert (not Barrier.Timed_Out, "Barrier timed out" & M & Image_N); Ada.Assertions.Assert (not Barrier.Saturated, "Barrier saturated (quite an exploit)"); Ada.Assertions.Assert (not Barrier.Overflowed, "Barrier overflowed, " & "looks like Expected_Tag.all'Length should be greater (than" & Integer'Image (Barrier.Cross_Count_On_Overflow) & ")"); Ada.Assertions.Assert (Barrier.Completed, "Expected_Tag'Length is" & Integer'Image (Expected_Tag_Length) & (if Barrier.Cross_Count = 0 then ", O crossing done" else ", only" & Natural'Image (Barrier.Cross_Count) & " crossing(s) done")); Ada.Assertions.Assert (not Barrier.Failed_Validation, "Failed validation, please analyse trace for details"); end Assert_Barrier_Status; ---------------------------------------------------------------------------- function Ind (A : Test_Node_Char_Array) return Test_Node_Array is Ret : Test_Node_Array (1 .. A'Length) := (others => A(A'First)); K : Test_Node_Count := 0; begin for E of A loop K := K + 1; Ret(K) := E; end loop; return Ret; end; ---------------------------------------------------------------------------- Debug_Trace : Apsepp.Debug_Trace_Class.Standard.Debug_Trace_Standard; Barrier : aliased Test_Node_Barrier; Reporter : aliased Test_Reporter_W_Barrier := Create_Test_Reporter (Barrier'Access, Char_Name_Image'Access, Tag_To_Char'Access); not overriding procedure Run_Test (Obj : Testing_System_Test_Fixture; Exp : Tag_Array_Access; V : Validate_Proc) is package Debug_Trace_Standard_Access_Setter is new Apsepp.Debug_Trace.Shared_Instance.Access_Setter (Inst_Access => Debug_Trace'Access); Unused_Outcome : Test_Outcome; pragma Unreferenced (Obj, Debug_Trace_Standard_Access_Setter); begin Assert_Node_Tags; Barrier.Setup (Char_Name_Image'Access, Tag_To_Char'Access, Char_To_Tag'Access, V, Exp); declare Monitor : Test_Node_Barrier_Monitor; Runner_A : Test_Runner_Sequential_W_Slave_Tasks := Create (Root_Node_Access => Simu_Case('A'), Test_Reporter_Instance_Access => Reporter'Access, Slaves => Ind (Slave_Runner_Arr)); begin Monitor.Setup (Barrier'Access); Runner_A.Run (Unused_Outcome); abort Monitor; exception when others => abort Monitor; end; Assert_Barrier_Status (Barrier'Access, Exp'Length); end Run_Test; ---------------------------------------------------------------------------- end Apsepp_Testing_System_Test_Fixture;
------------------------------------------------------------------------------- -- Copyright (c) 2016 Daniel King -- -- 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.Real_Time; use Ada.Real_Time; with Interfaces; use Interfaces; with STM32.AFIO; with STM32.EXTI; with STM32.GPIO; with STM32.NVIC; with STM32.RCC; with STM32.SPI; -- BSP implementation for the EVB1000 eval board. -- -- This BSP is designed for a Ravenscar runtime, and makes use of a protected -- object to satisfy the Synchronous requirement of the abstract Device_State. -- The use of a protected object protects against races between tasks -- and the DW1000 IRQ, which both may attempt to access the SPI bus. -- -- To adapt this runtime for a ZFP profile (where protected objects are -- prohibited) another mechanim must be used. For example, interrupts may -- be disabled during SPI transactions. package body DW1000.BSP with SPARK_Mode => Off is procedure Select_Device is begin STM32.GPIO.GPIOA_Periph.BSRR.BR := STM32.GPIO.BSRR_BR_Field'(As_Array => True, Arr => (4 => 1, others => 0)); end Select_Device; procedure Deselect_Device is begin STM32.GPIO.GPIOA_Periph.BSRR.BS := STM32.GPIO.BSRR_BS_Field'(As_Array => True, Arr => (4 => 1, others => 0)); end Deselect_Device; procedure Reset_DW1000 is begin -- Configure RSTn GPIO as output STM32.GPIO.GPIOA_Periph.CRL.MODE0 := 2#11#; -- Output 50 MHz STM32.GPIO.GPIOA_Periph.CRL.CNF0 := 2#00#; -- Output push-pull -- Drive the RSTn line low STM32.GPIO.GPIOA_Periph.BSRR.BR := STM32.GPIO.BSRR_BR_Field'(As_Array => True, Arr => (1 => 1, others => 0)); -- Put the RSTn line to hi-Z STM32.GPIO.GPIOA_Periph.CRL.MODE0 := 2#00#; -- Input STM32.GPIO.GPIOA_Periph.CRL.CNF0 := 2#01#; -- Floating input end Reset_DW1000; procedure Get_Reset_State (State : out DW1000.Types.Bits_1) is begin State := DW1000.Types.Bits_1 (STM32.GPIO.GPIOA_Periph.IDR.IDR.Arr(0)); end Get_Reset_State; procedure Acknowledge_DW1000_IRQ is begin STM32.EXTI.EXTI_Periph.PR.PR.Arr (5) := 1; end Acknowledge_DW1000_IRQ; procedure Disable_DW1000_IRQ is begin -- Disable IRQ #25 (EXTI9_5_Interrupt) STM32.NVIC.NVIC_Periph.ICER0 := 16#0200_0000#; end Disable_DW1000_IRQ; procedure Enable_DW1000_IRQ is begin -- Enable IRQ #25 (EXTI9_5_Interrupt) STM32.NVIC.NVIC_Periph.ISER0 := 16#0200_0000#; end Enable_DW1000_IRQ; procedure Use_Slow_SPI_Clock is begin -- Use /32 prescaler (72 MHz / 32 = 2.25 MHz clock) STM32.SPI.SPI1_Periph.CR1.BR := 2#100#; end Use_Slow_SPI_Clock; procedure Use_Fast_SPI_Clock is begin -- Use /4 prescaler (72 MHz / 4 = 18 MHz clock) STM32.SPI.SPI1_Periph.CR1.BR := 2#001#; end Use_Fast_SPI_Clock; procedure Assert_WAKEUP is begin STM32.GPIO.GPIOB_Periph.BSRR.BS := STM32.GPIO.BSRR_BS_Field'(As_Array => True, Arr => (0 => 1, others => 0)); end Assert_WAKEUP; procedure Deassert_WAKEUP is begin STM32.GPIO.GPIOB_Periph.BSRR.BR := STM32.GPIO.BSRR_BR_Field'(As_Array => True, Arr => (0 => 1, others => 0)); end Deassert_WAKEUP; procedure Write_Transaction(Header : in DW1000.Types.Byte_Array; Data : in DW1000.Types.Byte_Array) is use type STM32.Bit; begin Disable_DW1000_IRQ; Select_Device; -- Send header for I in Header'Range loop STM32.SPI.SPI1_Periph.DR.DR := Unsigned_16 (Header (I) ); loop exit when STM32.SPI.SPI1_Periph.SR.TXE = 1; end loop; end loop; -- Send data for I in Data'Range loop loop exit when STM32.SPI.SPI1_Periph.SR.TXE = 1; end loop; STM32.SPI.SPI1_Periph.DR.DR := Unsigned_16 (Data (I) ); end loop; -- Wait for the last byte to finish transmitting. loop exit when STM32.SPI.SPI1_Periph.SR.BSY = 0; end loop; Deselect_Device; Enable_DW1000_IRQ; end Write_Transaction; procedure Read_Transaction(Header : in DW1000.Types.Byte_Array; Data : out DW1000.Types.Byte_Array) is use type STM32.Bit; begin Disable_DW1000_IRQ; Select_Device; -- Send header for I in Header'Range loop STM32.SPI.SPI1_Periph.DR.DR := Unsigned_16 (Header (I)); loop exit when STM32.SPI.SPI1_Periph.SR.TXE = 1; end loop; end loop; loop exit when STM32.SPI.SPI1_Periph.SR.BSY = 0; end loop; -- Read data for I in Data'Range loop -- Send a dummy byte to begin the transfer STM32.SPI.SPI1_Periph.DR.DR := 16#0000#; loop exit when STM32.SPI.SPI1_Periph.SR.BSY = 0; end loop; Data (I) := Unsigned_8 (STM32.SPI.SPI1_Periph.DR.DR and 16#FF#); end loop; Deselect_Device; Enable_DW1000_IRQ; end Read_Transaction; begin -- Enable peripheral clocks STM32.RCC.RCC_Periph.APB2ENR.SPI1EN := 1; STM32.RCC.RCC_Periph.APB2ENR.AFIOEN := 1; STM32.RCC.RCC_Periph.APB2ENR.IOPAEN := 1; STM32.RCC.RCC_Periph.APB2ENR.IOPBEN := 1; -- Configure GPIO STM32.GPIO.GPIOA_Periph.CRL.MODE4 := 2#11#; STM32.GPIO.GPIOA_Periph.CRL.MODE5 := 2#11#; STM32.GPIO.GPIOA_Periph.CRL.MODE6 := 2#00#; STM32.GPIO.GPIOA_Periph.CRL.MODE7 := 2#11#; STM32.GPIO.GPIOA_Periph.CRL.CNF4 := 2#00#; STM32.GPIO.GPIOA_Periph.CRL.CNF5 := 2#10#; STM32.GPIO.GPIOA_Periph.CRL.CNF6 := 2#10#; STM32.GPIO.GPIOA_Periph.CRL.CNF7 := 2#10#; STM32.GPIO.GPIOB_Periph.CRL.MODE0 := 2#11#; STM32.GPIO.GPIOB_Periph.CRL.CNF0 := 2#00#; Deselect_Device; Deassert_WAKEUP; -- Configure SPI STM32.SPI.SPI1_Periph.CR1 := STM32.SPI.CR1_Register'(CPHA => 0, CPOL => 0, MSTR => 1, BR => 2#100#, -- /32 prescaler SPE => 0, LSBFIRST => 0, -- MSB first SSI => 1, SSM => 1, RXONLY => 0, -- Full duplex DFF => 0, -- 8-bit data CRCNEXT => 0, CRCEN => 0, -- No CRC BIDIOE => 0, BIDIMODE => 0, -- Bidirectional Reserved_16_31 => 0); STM32.SPI.SPI1_Periph.CRCPR.CRCPOLY := 7; STM32.SPI.SPI1_Periph.CR1.SPE := 1; -- Configure IRQ STM32.GPIO.GPIOB_Periph.CRL.CNF5 := 2#10#; -- Input with pull-up/down STM32.GPIO.GPIOB_Periph.CRL.MODE5 := 2#00#; -- Input mode STM32.GPIO.GPIOB_Periph.BRR.BR.Arr (5) := 1; -- Pull-down STM32.AFIO.AFIO_Periph.EXTICR2.EXTI.Arr (5) := 2#0001#; -- GPIOB STM32.EXTI.EXTI_Periph.IMR.MR.Arr (5) := 1; -- Enable interrupt STM32.EXTI.EXTI_Periph.EMR.MR.Arr (5) := 0; STM32.EXTI.EXTI_Periph.RTSR.TR.Arr (5) := 1; -- Rising edge enabled STM32.EXTI.EXTI_Periph.FTSR.TR.Arr (5) := 0; -- Falling edge disabled -- Device might be sleeping, so assert the WAKEUP pin to wake it. -- WAKEUP pin must be asserted for at least 500 microseconds. Assert_WAKEUP; declare use type DW1000.Types.Bits_1; Now : Ada.Real_Time.Time; WAKEUP_End : Ada.Real_Time.Time; RSTn_State : DW1000.Types.Bits_1; begin Now := Ada.Real_Time.Clock; WAKEUP_End := Now + Microseconds (500); delay until WAKEUP_End; Deassert_WAKEUP; -- Reset the device. This only has an effect if the device wasn't asleep. -- Since if the device was asleep then it is now in the WAKEUP state for -- approx. 4 ms, and during this state it keeps the RSTn line low anyway. Reset_DW1000; -- Delay for 4 ms to allow the DW1000 to transition into the INIT state. -- Otherwise, user code may not be able to communicate with the DW1000 -- if elaboration finishes within 4 ms and the user immediately tries to -- use the DW1000, since it will still be in the WAKEUP state. Now := Ada.Real_Time.Clock; WAKEUP_End := Now + Milliseconds (4); loop -- The DW1000 de-asserts the RSTn line when it exits the WAKEUP state -- which lets us exit early. Get_Reset_State (RSTn_State); exit when RSTn_State = 1; -- Otherwise, exit anyway after 4 ms. Now := Ada.Real_Time.Clock; exit when Now >= WAKEUP_End; end loop; end; end DW1000.BSP;
with System; with Ada.Unchecked_Conversion; -- ============================================================================= -- Package AVR.USART -- -- Implements Universal Asynchronous Receiver/Transmitter (UART) communication -- for the MCU micro-controller. -- ============================================================================= package AVR.USART is type USART_Control_And_Register_Status_Register_A_Type is record MPCM : Boolean; -- Multi-processor Communication Mode U2X : Boolean; -- Double the USART Transmission Speed UPE : Boolean; -- USART Parity Error DOR : Boolean; -- Data OverRun FE : Boolean; -- Frame Error UDRE : Boolean; -- USART Data Register Empty TXC : Boolean; -- USART Transmit Complete RXC : Boolean; -- USART Receive Complete end record; pragma Pack (USART_Control_And_Register_Status_Register_A_Type); for USART_Control_And_Register_Status_Register_A_Type'Size use BYTE_SIZE; type USART_Control_And_Register_Status_Register_B_Type is record TXB8 : Boolean; -- Transmit Data Bit 8 RXB8 : Boolean; -- Receive Data Bit 8 UCSZ2 : Boolean; -- Character Size Bit 2 TXEN : Boolean; -- Transmitter Enable RXEN : Boolean; -- Receiver Enable UDRIE : Boolean; -- USART Data Register Empty Interrupt Flag TXCIE : Boolean; -- Tx Complete Interrupt Flag RXCIE : Boolean; -- Rx Complete Interrupt Flag end record; pragma Pack (USART_Control_And_Register_Status_Register_B_Type); for USART_Control_And_Register_Status_Register_B_Type'Size use BYTE_SIZE; type USART_Control_And_Register_Status_Register_C_Type is record UCPOL : Boolean; -- Clock Polarity UCSZ0 : Boolean; -- Character Size Bit 0 UCSZ1 : Boolean; -- Character Size Bit 1 USBS : Boolean; -- Stop Bit Select UPM : Bit_Array_Type (0 .. 1); -- Parity Mode Bits UMSEL : Bit_Array_Type (0 .. 1); -- Mode Select end record; pragma Pack (USART_Control_And_Register_Status_Register_C_Type); for USART_Control_And_Register_Status_Register_C_Type'Size use BYTE_SIZE; type USART_Type is record UCSRA : USART_Control_And_Register_Status_Register_A_Type; UCSRB : USART_Control_And_Register_Status_Register_B_Type; UCSRC : USART_Control_And_Register_Status_Register_C_Type; Spare : Spare_Type (0 .. 7); UBRR : Byte_Array_Type (0 .. 1); -- USART Baud Rate Register L/H Bytes UDR : Byte_Type; -- USART I/O Data Register end record; pragma Pack (USART_Type); for USART_Type'Size use 7 * BYTE_SIZE; Reg_USART0 : USART_Type; for Reg_USART0'Address use System'To_Address (16#C0#); #if MCU="ATMEGA2560" then Reg_USART1 : USART_Type; for Reg_USART1'Address use System'To_Address (16#C8#); Reg_USART2 : USART_Type; for Reg_USART2'Address use System'To_Address (16#D0#); Reg_USART3 : USART_Type; for Reg_USART3'Address use System'To_Address (16#130#); #end if; -- ====================== -- General Public Section -- ====================== -- Mode of data processing type Model_Type is (POLLING, INTERRUPTIVE); -- Define the USART ports #if MCU="ATMEGA2560" then type Port_Type is (USART0, USART1, USART2, USART3); #elsif MCU="ATMEGA328P" then type Port_Type is (USART0); #end if; -- Define the USART modes type Sync_Mode_Type is (ASYNCHRONOUS, SYNCHRONOUS, MASTER_SPI); -- Define the number of bits in data communication type Data_Bits_Type is (BITS_5, BITS_6, BITS_7, BITS_8, BITS_9); for Data_Bits_Type'Size use 3; for Data_Bits_Type use (BITS_5 => 2#000#, BITS_6 => 2#001#, BITS_7 => 2#010#, BITS_8 => 2#011#, BITS_9 => 2#111#); -- Define the parity type Parity_Type is (NONE, EVEN, ODD); -- Define the number of stop bits subtype Stop_Bits_Type is Integer range 1 .. 2; -- Define the USART type for initialization type Setup_Type is record Sync_Mode : Sync_Mode_Type; Double_Speed : Boolean; Baud_Rate : Unsigned_32; Data_Bits : Data_Bits_Type; Parity : Parity_type; Stop_Bits : Stop_Bits_Type; Model : Model_Type; end record; type String_U8 is array (Unsigned_8 range <>) of Character; -- Default for USART setup #if MCU="ATMEGA2560" then USART_PORT_DEFAULT : constant Port_Type := USART0; #else USART_PORT_DEFAULT : constant Port_Type := USART0; #end if; USART_SETUP_DEFAULT : constant Setup_Type := (Sync_Mode => ASYNCHRONOUS, Double_Speed => True, Baud_Rate => 9600, Data_Bits => BITS_8, Parity => NONE, Stop_Bits => 1, Model => POLLING); -- To enable/disable write or receive for USART type Tx_Rx_Type is (TX, RX); -- To bufferize the Usart input type Buffer_Array_Port_Type is array (Port_Type) of Byte_Type; -- Initialize the general parameters of the USART procedure Initialize (In_Port : Port_Type; In_Setup : Setup_Type); -- ================= -- Tx Public Section -- ================= -- Transmit data over USART procedure Write (In_Port : Port_Type; In_Data : Unsigned_8); procedure Write_Char (In_Port : Port_Type; In_Data : Character); procedure Write_String_U8 (In_Port : Port_Type; In_Data : String_U8); procedure Write_Line (In_Port : Port_Type; In_Data : String_U8); procedure New_Line (In_Port : Port_Type); -- ================= -- Rx Public Section -- ================= -- Receive data from USART function Receive (In_Port : in Port_Type; Out_Data : out Unsigned_8) return Boolean; function Receive_Char (In_Port : in Port_Type; Out_Data : out Character) return Boolean; function Receive_String_U8 (In_Port : in Port_Type; Out_Data : out String_U8) return Boolean; procedure Receive_Char_Polled (In_Port : in Port_Type := USART0; Out_Data : out Character); procedure Receive_Char_Polled_Until_Flag_Char (In_Port : in AVR.USART.Port_Type; In_Char : in Character; Out_Data : out AVR.USART.String_U8); function Receive_Char_Tries (In_Port : in Port_Type := USART0; In_Tries : in Unsigned_8; Out_Data : out Character) return Boolean; procedure Handle_ISR_RXC (In_Port : in Port_Type); function Get_Setup (In_Port : Port_Type) return Setup_Type; function To_Char is new Ada.Unchecked_Conversion (Target => Character, Source => Unsigned_8); function To_Char is new Ada.Unchecked_Conversion (Target => Character, Source => AVR.Byte_Type); function To_Unsigned_8 is new Ada.Unchecked_Conversion (Target => Unsigned_8, Source => Character); private -- ======================= -- General Private Section -- ======================= -- Used to keep the information of Usart configurations Priv_Setup : array (Port_Type) of Setup_Type; -- ================== -- Tx Private Section -- ================== -- ================== -- Rx Private Section -- ================== Priv_Receive_Buffer : Buffer_Array_Port_Type := (others => 23); Priv_Receive_Flag : array (Port_Type) of Boolean := (others => False); end AVR.USART;
with TEXT_IO; use TEXT_IO; with Strings_Package; use Strings_Package; with LATIN_FILE_NAMES; use LATIN_FILE_NAMES; with CONFIG; with WORD_PARAMETERS; use WORD_PARAMETERS; with Inflections_Package; use Inflections_Package; with Dictionary_Package; use Dictionary_Package; with DEVELOPER_PARAMETERS; use DEVELOPER_PARAMETERS; with WORD_PACKAGE; use WORD_PACKAGE; with ENGLISH_SUPPORT_PACKAGE; use ENGLISH_SUPPORT_PACKAGE; with DICTIONARY_FORM; procedure SEARCH_ENGLISH(INPUT_ENGLISH_WORD : STRING; POFS : PART_OF_SPEECH_TYPE := X) is use EWDS_DIRECT_IO; INPUT_WORD : EWORD := LOWER_CASE(HEAD(INPUT_ENGLISH_WORD, EWORD_SIZE)); INPUT_POFS : PART_OF_SPEECH_TYPE := POFS; OUTPUT_ARRAY : EWDS_ARRAY(1..500) := (others => NULL_EWDS_RECORD); NUMBER_OF_HITS : INTEGER := 0; J1, J2, J, JJ : EWDS_DIRECT_IO.COUNT := 0; D_K : DICTIONARY_KIND := GENERAL; -- For the moment EWDS : EWDS_RECORD := NULL_EWDS_RECORD; FIRST_TRY, SECOND_TRY : BOOLEAN := TRUE; procedure LOAD_OUTPUT_ARRAY(EWDS : in EWDS_RECORD) is begin --PUT("LOAD a " & PART_OF_SPEECH_TYPE'IMAGE(INPUT_POFS)); --PUT("LOAD b " & PART_OF_SPEECH_TYPE'IMAGE(INPUT_POFS)); if EWDS.POFS <= INPUT_POFS then NUMBER_OF_HITS := NUMBER_OF_HITS + 1; OUTPUT_ARRAY(NUMBER_OF_HITS) := EWDS; -- PUT("$ " & INTEGER'IMAGE(NUMBER_OF_HITS)); -- EWDS_RECORD_IO.PUT(OUTPUT_ARRAY(NUMBER_OF_HITS)); -- TEXT_IO.NEW_LINE; end if; end LOAD_OUTPUT_ARRAY; --procedure TRIM_OUTPUT_ARRAY is procedure SORT_OUTPUT_ARRAY is HITS : INTEGER := 0; begin -- Bubble sort HIT_LOOP: loop HITS := 0; SWITCH: declare DW, EW : EWDS_RECORD := NULL_EWDS_RECORD; begin INNER_LOOP: -- Order by RANK, FREQ, SEMI for I in 1..NUMBER_OF_HITS-1 loop if OUTPUT_ARRAY(I+1).RANK > OUTPUT_ARRAY(I).RANK or else (OUTPUT_ARRAY(I+1).RANK = OUTPUT_ARRAY(I).RANK and then OUTPUT_ARRAY(I+1).FREQ < OUTPUT_ARRAY(I).FREQ) or else (OUTPUT_ARRAY(I+1).RANK = OUTPUT_ARRAY(I).RANK and then OUTPUT_ARRAY(I+1).FREQ = OUTPUT_ARRAY(I).FREQ and then OUTPUT_ARRAY(I+1).SEMI < OUTPUT_ARRAY(I).SEMI) then DW := OUTPUT_ARRAY(I); OUTPUT_ARRAY(I) := OUTPUT_ARRAY(I+1); OUTPUT_ARRAY(I+1) := DW; HITS := HITS + 1; --PUT_LINE("HITS " & INTEGER'IMAGE(HITS)); end if; end loop INNER_LOOP; end SWITCH; exit when HITS = 0; end loop HIT_LOOP; end SORT_OUTPUT_ARRAY; -- begin -- SORT_OUTPUT_ARRAY; -- end TRIM_OUTPUT_ARRAY; procedure DUMP_OUTPUT_ARRAY(OUTPUT : in TEXT_IO.FILE_TYPE) is DE : DICTIONARY_ENTRY := NULL_DICTIONARY_ENTRY; NUMBER_TO_SHOW : INTEGER := NUMBER_OF_HITS; ONE_SCREEN : INTEGER := 6; begin --TEXT_IO.PUT_LINE("DUMP_OUTPUT"); if NUMBER_OF_HITS = 0 then TEXT_IO.PUT_LINE(OUTPUT, "No Match"); else --PUT_LINE("Unsorted EWDS"); --for I in 1..NUMBER_TO_SHOW loop -- PUT(INTEGER'IMAGE(I)); PUT("*"); EWDS_RECORD_IO.PUT(OUTPUT_ARRAY(I)); NEW_LINE; --end loop; SORT_OUTPUT_ARRAY; --TEXT_IO.PUT_LINE("DUMP_OUTPUT SORTED"); TRIMMED := FALSE; if WORDS_MODE(TRIM_OUTPUT) then if NUMBER_OF_HITS > ONE_SCREEN then NUMBER_TO_SHOW := ONE_SCREEN; TRIMMED := TRUE; else NUMBER_TO_SHOW := NUMBER_OF_HITS; end if; end if; for I in 1..NUMBER_TO_SHOW loop TEXT_IO.NEW_LINE(OUTPUT); DO_PAUSE: begin --PUT(INTEGER'IMAGE(INTEGER(TEXT_IO.LINE(OUTPUT))) & " "); --PUT(INTEGER'IMAGE(INTEGER(SCROLL_LINE_NUMBER)) & " "); --PUT(INTEGER'IMAGE(INTEGER(CONFIG.OUTPUT_SCREEN_SIZE)) & " "); if (INTEGER(TEXT_IO.LINE(OUTPUT)) > SCROLL_LINE_NUMBER + CONFIG.OUTPUT_SCREEN_SIZE) then PAUSE(OUTPUT); SCROLL_LINE_NUMBER := INTEGER(TEXT_IO.LINE(OUTPUT)); end if; end DO_PAUSE; -- EWDS_RECORD_IO.PUT(OUTPUT_ARRAY(I)); -- TEXT_IO.NEW_LINE; DICT_IO.READ(DICT_FILE(GENERAL), DE, DICT_IO.COUNT(OUTPUT_ARRAY(I).N)); --TEXT_IO.PUT_LINE("DUMP_OUTPUT READ"); -- DICTIONARY_ENTRY_IO.PUT(DE); TEXT_IO.NEW_LINE; PUT(OUTPUT, DICTIONARY_FORM(DE)); TEXT_IO.PUT(OUTPUT, " "); --PART_ENTRY_IO.PUT(OUTPUT, DE.PART); --TEXT_IO.PUT_LINE("DUMP_OUTPUT PART"); if DE.PART.POFS = N then TEXT_IO.PUT(OUTPUT, " "); DECN_RECORD_IO.PUT(OUTPUT, DE.PART.N.DECL); TEXT_IO.PUT(OUTPUT, " " & GENDER_TYPE'IMAGE(DE.PART.N.GENDER) & " "); end if; if (DE.PART.POFS = V) then TEXT_IO.PUT(OUTPUT, " "); DECN_RECORD_IO.PUT(OUTPUT, DE.PART.V.CON); end if; if (DE.PART.POFS = V) and then (DE.PART.V.KIND in GEN..PERFDEF) then TEXT_IO.PUT(OUTPUT, " " & VERB_KIND_TYPE'IMAGE(DE.PART.V.KIND) & " "); end if; --TEXT_IO.PUT_LINE("DUMP_OUTPUT CODE"); if WORDS_MDEV(SHOW_DICTIONARY_CODES) then TEXT_IO.PUT(OUTPUT, " ["); AGE_TYPE_IO.PUT(OUTPUT, DE.TRAN.AGE); AREA_TYPE_IO.PUT(OUTPUT, DE.TRAN.AREA); GEO_TYPE_IO.PUT(OUTPUT, DE.TRAN.GEO); FREQUENCY_TYPE_IO.PUT(OUTPUT, DE.TRAN.FREQ); SOURCE_TYPE_IO.PUT(OUTPUT, DE.TRAN.SOURCE); TEXT_IO.PUT(OUTPUT, "] "); end if; if WORDS_MDEV(SHOW_DICTIONARY) then TEXT_IO.PUT(OUTPUT, EXT(D_K) & ">"); end if; --TEXT_IO.PUT_LINE("DUMP_OUTPUT SHOW"); if WORDS_MDEV(SHOW_DICTIONARY_LINE) then TEXT_IO.PUT(OUTPUT, "(" & TRIM(INTEGER'IMAGE(OUTPUT_ARRAY(I).N)) & ")"); end if; TEXT_IO.NEW_LINE(OUTPUT); --TEXT_IO.PUT_LINE("DUMP_OUTPUT MEAN"); TEXT_IO.PUT(OUTPUT, TRIM(DE.MEAN)); TEXT_IO.NEW_LINE(OUTPUT); end loop; --TEXT_IO.PUT_LINE("DUMP_OUTPUT TRIMMED"); if TRIMMED then PUT_LINE(OUTPUT, "*"); end if; end if; -- On HITS = 0 exception when others => null; -- If N not in DICT_FILE end DUMP_OUTPUT_ARRAY; begin J1 := 1; J2 := SIZE(EWDS_FILE); FIRST_TRY := TRUE; SECOND_TRY := TRUE; J := (J1 + J2) / 2; BINARY_SEARCH: loop -- TEXT_IO.PUT_LINE("J = " & INTEGER'IMAGE(INTEGER(J))); if (J1 = J2-1) or (J1 = J2) then if FIRST_TRY then -- TEXT_IO.PUT_LINE("FIRST_TRY"); J := J1; FIRST_TRY := FALSE; elsif SECOND_TRY then -- TEXT_IO.PUT_LINE("SECOND_TRY"); J := J2; SECOND_TRY := FALSE; else -- TEXT_IO.PUT_LINE("THIRD_TRY exit BINARY_SEARCH"); JJ := J; exit BINARY_SEARCH; end if; end if; -- Should D_K SET_INDEX(EWDS_FILE, EWDS_DIRECT_IO.COUNT(J)); READ(EWDS_FILE, EWDS); -- EWDS_RECORD_IO.PUT(EWDS); -- TEXT_IO.NEW_LINE; -- PUT_LINE(LOWER_CASE(EWDS.W)); -- PUT_LINE(INPUT_WORD); -- TEXT_IO.PUT_LINE("J = " & INTEGER'IMAGE(INTEGER(J)) & -- " J1 = " & INTEGER'IMAGE(INTEGER(J1)) & -- " J2 = " & INTEGER'IMAGE(INTEGER(J2))); -- if "<"(LOWER_CASE(EWDS.W), INPUT_WORD) then -- Not LTU, not u=v J1 := J; J := (J1 + J2) / 2; elsif ">"(LOWER_CASE(EWDS.W), INPUT_WORD) then J2 := J; J := (J1 + J2) / 2; else for I in reverse J1..J loop SET_INDEX(EWDS_FILE, EWDS_DIRECT_IO.COUNT(I)); READ(EWDS_FILE, EWDS); -- Reads and advances index!! if "="(LOWER_CASE(EWDS.W), INPUT_WORD) then JJ := I; -- PUT(INTEGER'IMAGE(INTEGER(I))); PUT("-"); EWDS_RECORD_IO.PUT(EWDS); NEW_LINE; LOAD_OUTPUT_ARRAY(EWDS); else exit; end if; end loop; for I in J+1..J2 loop SET_INDEX(EWDS_FILE, EWDS_DIRECT_IO.COUNT(I)); READ(EWDS_FILE, EWDS); if "="(LOWER_CASE(EWDS.W), INPUT_WORD) then JJ := I; -- PUT(INTEGER'IMAGE(INTEGER(I))); PUT("+"); EWDS_RECORD_IO.PUT(EWDS); NEW_LINE; LOAD_OUTPUT_ARRAY(EWDS); else exit BINARY_SEARCH; end if; end loop; exit BINARY_SEARCH; end if; end loop BINARY_SEARCH; if WORDS_MODE(WRITE_OUTPUT_TO_FILE) then DUMP_OUTPUT_ARRAY(OUTPUT); else DUMP_OUTPUT_ARRAY(CURRENT_OUTPUT); end if; -- DUMP_OUTPUT_ARRAY(; -- TEXT_IO.PUT_LINE("Leaving SEARCH NUMBER_OF_HITS = " & -- INTEGER'IMAGE(NUMBER_OF_HITS)); exception when others => TEXT_IO.PUT_LINE("exception SEARCH NUMBER_OF_HITS = " & INTEGER'IMAGE(NUMBER_OF_HITS)); raise; end SEARCH_ENGLISH;
------------------------------------------------------------------------------ -- philosophers.adb -- -- Implementation of the philosophers. ------------------------------------------------------------------------------ with Randoms, Meals, Chopsticks, Host, Orders, Reporter, Waiters; use Randoms, Meals, Chopsticks, Host, Orders, Reporter, Waiters; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; package body Philosophers is task body Philosopher is My_Index : Philosopher_Name; My_Name : Unbounded_String; Wealth : Float := 30.00; Left : Chopstick_Name; Right : Chopstick_Name; My_Order : Order; Cooking : Boolean; begin accept Here_Is_Your_Name (Name: Philosopher_Name) do My_Index := Name; My_Name := To_Unbounded_String(Philosopher_Name'Image(Name)); end Here_Is_Your_Name; Left := Chopstick_Name(Philosopher_Name'Pos(My_Index)); Right := (Chopstick_Name'Pos(Left) + 1) mod (Chopstick_Name'Last + 1); while Wealth > 0.0 loop Norman_Bates.Enter; Report (My_Name & " enters the cafe"); Report (My_Name & " is thinking"); delay Duration(Random(1,3)); My_Order := (My_Index, Random_Meal); Report (My_Name & " has decided to order " & My_Order.Food); select Waiter_Array(Waiter_Name'Val(Random(0,1))).Place_Order(My_Order, My_Index, Cooking); or delay 35.0; Report (My_Name & " cancels order and complains about lousy service"); end select; if Cooking then accept Here_Is_Your_Food; Chopstick_Array(Right).Pick_Up; Chopstick_Array(Left).Pick_Up; Report (My_Name & " is eating " & My_Order.Food); delay (12.0); Chopstick_Array(Right).Put_Down; Chopstick_Array(Left).Put_Down; Report (My_Name & " pays for the " & My_Order.Food); Wealth := Wealth - Price(My_Order.Food); else Report (My_Name & " receives a coupon"); Wealth := Wealth + 5.00; end if; Report (My_Name & " leaves the restaurant"); Norman_Bates.Leave; end loop; Report (My_Name & " died a normal death from overeating"); Norman_Bates.Death_Announcement; exception when others => Report ("Error: " & My_Name & " dead unexpectedly"); end Philosopher; end Philosophers;
----------------------------------------------------------------------- -- bean - A simple bean example -- Copyright (C) 2009, 2010 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.Beans.Factory; with EL.Methods.Func_String; with EL.Methods.Func_Unbounded; with Ada.Unchecked_Deallocation; package body Bean is use EL.Objects; use Util.Beans.Methods; use EL.Methods; FIRST_NAME : constant String := "firstName"; LAST_NAME : constant String := "lastName"; AGE : constant String := "age"; Null_Object : Object; function Create_Person (First_Name, Last_Name : String; Age : Natural) return Person_Access is begin return new Person '(First_Name => To_Unbounded_String (First_Name), Last_Name => To_Unbounded_String (Last_Name), Age => Age); end Create_Person; -- Get the value identified by the name. function Get_Value (From : Person; Name : String) return EL.Objects.Object is begin if Name = FIRST_NAME then return To_Object (From.First_Name); elsif Name = LAST_NAME then return To_Object (From.Last_Name); elsif Name = AGE then return To_Object (From.Age); else return Null_Object; end if; end Get_Value; -- Set the value identified by the name. procedure Set_Value (From : in out Person; Name : in String; Value : in EL.Objects.Object) is begin if Name = FIRST_NAME then From.First_Name := To_Unbounded_String (Value); elsif Name = LAST_NAME then From.Last_Name := To_Unbounded_String (Value); elsif Name = AGE then From.Age := Natural (To_Integer (Value)); end if; end Set_Value; -- function Save (P : in Person; Name : in Unbounded_String) return Unbounded_String is Result : Unbounded_String; begin Result := P.Last_Name & Name; return Result; end Save; function Compute (B : Util.Beans.Basic.Bean'Class; P1 : EL.Objects.Object) return EL.Objects.Object is P : Person := Person (B); begin return P1; end Compute; -- Function to format a string function Format (Arg : EL.Objects.Object) return EL.Objects.Object is S : constant String := To_String (Arg); begin return To_Object ("[" & S & "]"); end Format; function Print (P : in Person; Title : in String) return String is begin return Title & " [" & "Name=" & To_String (P.First_Name) & ", " & "Last_name=" & To_String (P.Last_Name) & "]"; end Print; package Save_Binding is new Func_Unbounded.Bind (Bean => Person, Method => Save, Name => "save"); package Print_Binding is new Func_String.Bind (Bean => Person, Method => Print, Name => "print"); type Bean_Definition is new Util.Beans.Factory.Bean_Definition with null record; -- Create a bean. overriding function Create (Def : in Bean_Definition) return Util.Beans.Basic.Readonly_Bean_Access; -- Free the bean instance. overriding procedure Destroy (Def : in Bean_Definition; Bean : in out Util.Beans.Basic.Readonly_Bean_Access); -- Create a bean. overriding function Create (Def : in Bean_Definition) return Util.Beans.Basic.Readonly_Bean_Access is Result : Person_Access := new Person; begin return Result.all'Access; end Create; -- Free the bean instance. overriding procedure Destroy (Def : in Bean_Definition; Bean : in out Util.Beans.Basic.Readonly_Bean_Access) is begin null; end Destroy; B : aliased Bean_Definition := Bean_Definition '(Method_Count => 2, Methods => (Save_Binding.Proxy'Access, null) ); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Print_Binding.Proxy'Access); function Get_Method_Bindings (From : in Person) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; procedure Free (Object : in out Person_Access) is procedure Free is new Ada.Unchecked_Deallocation (Object => Person'Class, Name => Person_Access); begin Free (Object); end Free; end Bean;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- SYSTEM.MACHINE_STATE_OPERATIONS -- -- -- -- B o d y -- -- (Version for x86) -- -- -- -- $Revision$ -- -- -- Copyright (C) 1999-2001 Ada Core Technologies, 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. -- -- It is now maintained by Ada Core Technologies Inc (http://www.gnat.com). -- -- -- ------------------------------------------------------------------------------ -- Note: it is very important that this unit not generate any exception -- tables of any kind. Otherwise we get a nasty rtsfind recursion problem. -- This means no subprograms, including implicitly generated ones. with Unchecked_Conversion; with System.Storage_Elements; with System.Machine_Code; use System.Machine_Code; package body System.Machine_State_Operations is use System.Exceptions; type Uns8 is mod 2 ** 8; type Uns32 is mod 2 ** 32; type Bits5 is mod 2 ** 5; type Bits6 is mod 2 ** 6; function To_Address is new Unchecked_Conversion (Uns32, Address); function To_Uns32 is new Unchecked_Conversion (Integer, Uns32); function To_Uns32 is new Unchecked_Conversion (Address, Uns32); type Uns32_Ptr is access all Uns32; function To_Uns32_Ptr is new Unchecked_Conversion (Address, Uns32_Ptr); function To_Uns32_Ptr is new Unchecked_Conversion (Uns32, Uns32_Ptr); -- Note: the type Uns32 has an alignment of 4. However, in some cases -- values of type Uns32_Ptr will not be aligned (notably in the case -- where we get the immediate field from an instruction). However this -- does not matter in practice, since the x86 does not require that -- operands be aligned. ---------------------- -- General Approach -- ---------------------- -- For the x86 version of this unit, the Subprogram_Info_Type values -- are simply the starting code address for the subprogram. Popping -- of stack frames works by analyzing the code in the prolog, and -- deriving from this analysis the necessary information for restoring -- the registers, including the return point. --------------------------- -- Description of Prolog -- --------------------------- -- If a frame pointer is present, the prolog looks like -- pushl %ebp -- movl %esp,%ebp -- subl $nnn,%esp omitted if nnn = 0 -- pushl %edi omitted if edi not used -- pushl %esi omitted if esi not used -- pushl %ebx omitted if ebx not used -- If a frame pointer is not present, the prolog looks like -- subl $nnn,%esp omitted if nnn = 0 -- pushl %ebp omitted if ebp not used -- pushl %edi omitted if edi not used -- pushl %esi omitted if esi not used -- pushl %ebx omitted if ebx not used -- Note: any or all of the save over call registers may be used and -- if so, will be saved using pushl as shown above. The order of the -- pushl instructions will be as shown above for gcc generated code, -- but the code in this unit does not assume this. ------------------------- -- Description of Call -- ------------------------- -- A call looks like: -- pushl ... push parameters -- pushl ... -- call ... perform the call -- addl $nnn,%esp omitted if no parameters -- Note that we are not absolutely guaranteed that the call is always -- followed by an addl operation that readjusts %esp for this particular -- call. There are two reasons for this: -- 1) The addl can be delayed and combined in the case where more than -- one call appears in sequence. This can be suppressed by using the -- switch -fno-defer-pop and for Ada code, we automatically use -- this switch, but we could still be dealing with C code that was -- compiled without using this switch. -- 2) Scheduling may result in moving the addl instruction away from -- the call. It is not clear if this actually can happen at the -- current time, but it is certainly conceptually possible. -- The addl after the call is important, since we need to be able to -- restore the proper %esp value when we pop the stack. However, we do -- not try to compensate for either of the above effects. As noted above, -- case 1 does not occur for Ada code, and it does not appear in practice -- that case 2 occurs with any significant frequency (we have never seen -- an example so far for gcc generated code). -- Furthermore, it is only in the case of -fomit-frame-pointer that we -- really get into trouble from not properly restoring %esp. If we have -- a frame pointer, then the worst that happens is that %esp is slightly -- more depressed than it should be. This could waste a bit of space on -- the stack, and even in some cases cause a storage leak on the stack, -- but it will not affect the functional correctness of the processing. ---------------------------------------- -- Definitions of Instruction Formats -- ---------------------------------------- type Rcode is (eax, ecx, edx, ebx, esp, ebp, esi, edi); pragma Warnings (Off, Rcode); -- Code indicating which register is referenced in an instruction -- The following define the format of a pushl instruction Op_pushl : constant Bits5 := 2#01010#; type Ins_pushl is record Op : Bits5 := Op_pushl; Reg : Rcode; end record; for Ins_pushl use record Op at 0 range 3 .. 7; Reg at 0 range 0 .. 2; end record; Ins_pushl_ebp : constant Ins_pushl := (Op_pushl, Reg => ebp); type Ins_pushl_Ptr is access all Ins_pushl; -- For the movl %esp,%ebp instruction, we only need to know the length -- because we simply skip past it when we analyze the prolog. Ins_movl_length : constant := 2; -- The following define the format of addl/subl esp instructions Op_Immed : constant Bits6 := 2#100000#; Op2_addl_Immed : constant Bits5 := 2#11100#; Op2_subl_Immed : constant Bits5 := 2#11101#; type Word_Byte is (Word, Byte); type Ins_addl_subl_byte is record Op : Bits6; -- Set to Op_Immed w : Word_Byte; -- Word/Byte flag (set to 1 = byte) s : Boolean; -- Sign extension bit (1 = extend) Op2 : Bits5; -- Secondary opcode Reg : Rcode; -- Register Imm8 : Uns8; -- Immediate operand end record; for Ins_addl_subl_byte use record Op at 0 range 2 .. 7; w at 0 range 1 .. 1; s at 0 range 0 .. 0; Op2 at 1 range 3 .. 7; Reg at 1 range 0 .. 2; Imm8 at 2 range 0 .. 7; end record; type Ins_addl_subl_word is record Op : Bits6; -- Set to Op_Immed w : Word_Byte; -- Word/Byte flag (set to 0 = word) s : Boolean; -- Sign extension bit (1 = extend) Op2 : Bits5; -- Secondary opcode Reg : Rcode; -- Register Imm32 : Uns32; -- Immediate operand end record; for Ins_addl_subl_word use record Op at 0 range 2 .. 7; w at 0 range 1 .. 1; s at 0 range 0 .. 0; Op2 at 1 range 3 .. 7; Reg at 1 range 0 .. 2; Imm32 at 2 range 0 .. 31; end record; type Ins_addl_subl_byte_Ptr is access all Ins_addl_subl_byte; type Ins_addl_subl_word_Ptr is access all Ins_addl_subl_word; --------------------- -- Prolog Analysis -- --------------------- -- The analysis of the prolog answers the following questions: -- 1. Is %ebp used as a frame pointer? -- 2. How far is SP depressed (i.e. what is the stack frame size) -- 3. Which registers are saved in the prolog, and in what order -- The following data structure stores the answers to these questions subtype SOC is Rcode range ebx .. edi; -- Possible save over call registers SOC_Max : constant := 4; -- Max number of SOC registers that can be pushed type SOC_Push_Regs_Type is array (1 .. 4) of Rcode; -- Used to hold the register codes of pushed SOC registers type Prolog_Type is record Frame_Reg : Boolean; -- This is set to True if %ebp is used as a frame register, and -- False otherwise (in the False case, %ebp may be saved in the -- usual manner along with the other SOC registers). Frame_Length : Uns32; -- Amount by which ESP is decremented on entry, includes the effects -- of push's of save over call registers as indicated above, e.g. if -- the prolog of a routine is: -- -- pushl %ebp -- movl %esp,%ebp -- subl $424,%esp -- pushl %edi -- pushl %esi -- pushl %ebx -- -- Then the value of Frame_Length would be 436 (424 + 3 * 4). A -- precise definition is that it is: -- -- %esp on entry minus %esp after last SOC push -- -- That definition applies both in the frame pointer present and -- the frame pointer absent cases. Num_SOC_Push : Integer range 0 .. SOC_Max; -- Number of save over call registers actually saved by pushl -- instructions (other than the initial pushl to save the frame -- pointer if a frame pointer is in use). SOC_Push_Regs : SOC_Push_Regs_Type; -- The First Num_SOC_Push entries of this array are used to contain -- the codes for the SOC registers, in the order in which they were -- pushed. Note that this array excludes %ebp if it is used as a frame -- register, since although %ebp is still considered an SOC register -- in this case, it is saved and restored by a separate mechanism. -- Also we will never see %esp represented in this list. Again, it is -- true that %esp is saved over call, but it is restored by a separate -- mechanism. end record; procedure Analyze_Prolog (A : Address; Prolog : out Prolog_Type); -- Given the address of the start of the prolog for a procedure, -- analyze the instructions of the prolog, and set Prolog to contain -- the information obtained from this analysis. ---------------------------------- -- Machine_State_Representation -- ---------------------------------- -- The type Machine_State is defined in the body of Ada.Exceptions as -- a Storage_Array of length 1 .. Machine_State_Length. But really it -- has structure as defined here. We use the structureless declaration -- in Ada.Exceptions to avoid this unit from being implementation -- dependent. The actual definition of Machine_State is as follows: type SOC_Regs_Type is array (SOC) of Uns32; type MState is record eip : Uns32; -- The instruction pointer location (which is the return point -- value from the next level down in all cases). Regs : SOC_Regs_Type; -- Values of the save over call registers end record; for MState use record eip at 0 range 0 .. 31; Regs at 4 range 0 .. 5 * 32 - 1; end record; -- Note: the routines Enter_Handler, and Set_Machine_State reference -- the fields in this structure non-symbolically. type MState_Ptr is access all MState; function To_MState_Ptr is new Unchecked_Conversion (Machine_State, MState_Ptr); ---------------------------- -- Allocate_Machine_State -- ---------------------------- function Allocate_Machine_State return Machine_State is use System.Storage_Elements; function Gnat_Malloc (Size : Storage_Offset) return Machine_State; pragma Import (C, Gnat_Malloc, "__gnat_malloc"); begin return Gnat_Malloc (MState'Max_Size_In_Storage_Elements); end Allocate_Machine_State; -------------------- -- Analyze_Prolog -- -------------------- procedure Analyze_Prolog (A : Address; Prolog : out Prolog_Type) is Ptr : Address; Ppl : Ins_pushl_Ptr; Pas : Ins_addl_subl_byte_Ptr; function To_Ins_pushl_Ptr is new Unchecked_Conversion (Address, Ins_pushl_Ptr); function To_Ins_addl_subl_byte_Ptr is new Unchecked_Conversion (Address, Ins_addl_subl_byte_Ptr); function To_Ins_addl_subl_word_Ptr is new Unchecked_Conversion (Address, Ins_addl_subl_word_Ptr); begin Ptr := A; Prolog.Frame_Length := 0; if Ptr = Null_Address then Prolog.Num_SOC_Push := 0; Prolog.Frame_Reg := True; return; end if; if To_Ins_pushl_Ptr (Ptr).all = Ins_pushl_ebp then Ptr := Ptr + 1 + Ins_movl_length; Prolog.Frame_Reg := True; else Prolog.Frame_Reg := False; end if; Pas := To_Ins_addl_subl_byte_Ptr (Ptr); if Pas.Op = Op_Immed and then Pas.Op2 = Op2_subl_Immed and then Pas.Reg = esp then if Pas.w = Word then Prolog.Frame_Length := Prolog.Frame_Length + To_Ins_addl_subl_word_Ptr (Ptr).Imm32; Ptr := Ptr + 6; else Prolog.Frame_Length := Prolog.Frame_Length + Uns32 (Pas.Imm8); Ptr := Ptr + 3; -- Note: we ignore sign extension, since a sign extended -- value that was negative would imply a ludicrous frame size. end if; end if; -- Now scan push instructions for SOC registers Prolog.Num_SOC_Push := 0; loop Ppl := To_Ins_pushl_Ptr (Ptr); if Ppl.Op = Op_pushl and then Ppl.Reg in SOC then Prolog.Num_SOC_Push := Prolog.Num_SOC_Push + 1; Prolog.SOC_Push_Regs (Prolog.Num_SOC_Push) := Ppl.Reg; Prolog.Frame_Length := Prolog.Frame_Length + 4; Ptr := Ptr + 1; else exit; end if; end loop; end Analyze_Prolog; ------------------- -- Enter_Handler -- ------------------- procedure Enter_Handler (M : Machine_State; Handler : Handler_Loc) is begin Asm ("mov %0,%%edx", Inputs => Machine_State'Asm_Input ("r", M)); Asm ("mov %0,%%eax", Inputs => Handler_Loc'Asm_Input ("r", Handler)); Asm ("mov 4(%%edx),%%ebx"); -- M.Regs (ebx) Asm ("mov 12(%%edx),%%ebp"); -- M.Regs (ebp) Asm ("mov 16(%%edx),%%esi"); -- M.Regs (esi) Asm ("mov 20(%%edx),%%edi"); -- M.Regs (edi) Asm ("mov 8(%%edx),%%esp"); -- M.Regs (esp) Asm ("jmp %*%%eax"); end Enter_Handler; ---------------- -- Fetch_Code -- ---------------- function Fetch_Code (Loc : Code_Loc) return Code_Loc is begin return Loc; end Fetch_Code; ------------------------ -- Free_Machine_State -- ------------------------ procedure Free_Machine_State (M : in out Machine_State) is procedure Gnat_Free (M : in Machine_State); pragma Import (C, Gnat_Free, "__gnat_free"); begin Gnat_Free (M); M := Machine_State (Null_Address); end Free_Machine_State; ------------------ -- Get_Code_Loc -- ------------------ function Get_Code_Loc (M : Machine_State) return Code_Loc is Asm_Call_Size : constant := 2; -- Minimum size for a call instruction under ix86. Using the minimum -- size is safe here as the call point computed from the return point -- will always be inside the call instruction. MS : constant MState_Ptr := To_MState_Ptr (M); begin if MS.eip = 0 then return To_Address (MS.eip); else -- When doing a call the return address is pushed to the stack. -- We want to return the call point address, so we subtract -- Asm_Call_Size from the return address. This value is set -- to 5 as an asm call takes 5 bytes on x86 architectures. return To_Address (MS.eip - Asm_Call_Size); end if; end Get_Code_Loc; -------------------------- -- Machine_State_Length -- -------------------------- function Machine_State_Length return System.Storage_Elements.Storage_Offset is begin return MState'Max_Size_In_Storage_Elements; end Machine_State_Length; --------------- -- Pop_Frame -- --------------- procedure Pop_Frame (M : Machine_State; Info : Subprogram_Info_Type) is MS : constant MState_Ptr := To_MState_Ptr (M); PL : Prolog_Type; SOC_Ptr : Uns32; -- Pointer to stack location after last SOC push Rtn_Ptr : Uns32; -- Pointer to stack location containing return address begin Analyze_Prolog (Info, PL); -- Case of frame register, use EBP, safer than ESP if PL.Frame_Reg then SOC_Ptr := MS.Regs (ebp) - PL.Frame_Length; Rtn_Ptr := MS.Regs (ebp) + 4; MS.Regs (ebp) := To_Uns32_Ptr (MS.Regs (ebp)).all; -- No frame pointer, use ESP, and hope we have it exactly right! else SOC_Ptr := MS.Regs (esp); Rtn_Ptr := SOC_Ptr + PL.Frame_Length; end if; -- Get saved values of SOC registers for J in reverse 1 .. PL.Num_SOC_Push loop MS.Regs (PL.SOC_Push_Regs (J)) := To_Uns32_Ptr (SOC_Ptr).all; SOC_Ptr := SOC_Ptr + 4; end loop; MS.eip := To_Uns32_Ptr (Rtn_Ptr).all; MS.Regs (esp) := Rtn_Ptr + 4; end Pop_Frame; ----------------------- -- Set_Machine_State -- ----------------------- procedure Set_Machine_State (M : Machine_State) is N : constant Asm_Output_Operand := No_Output_Operands; begin Asm ("mov %0,%%edx", N, Machine_State'Asm_Input ("r", M)); -- At this stage, we have the following situation (note that we -- are assuming that the -fomit-frame-pointer switch has not been -- used in compiling this procedure. -- (value of M) -- return point -- old ebp <------ current ebp/esp value -- The values of registers ebx/esi/edi are unchanged from entry -- so they have the values we want, and %edx points to the parameter -- value M, so we can store these values directly. Asm ("mov %%ebx,4(%%edx)"); -- M.Regs (ebx) Asm ("mov %%esi,16(%%edx)"); -- M.Regs (esi) Asm ("mov %%edi,20(%%edx)"); -- M.Regs (edi) -- The desired value of ebp is the old value Asm ("mov 0(%%ebp),%%eax"); Asm ("mov %%eax,12(%%edx)"); -- M.Regs (ebp) -- The return point is the desired eip value Asm ("mov 4(%%ebp),%%eax"); Asm ("mov %%eax,(%%edx)"); -- M.eip -- Finally, the desired %esp value is the value at the point of -- call to this routine *before* pushing the parameter value. Asm ("lea 12(%%ebp),%%eax"); Asm ("mov %%eax,8(%%edx)"); -- M.Regs (esp) end Set_Machine_State; ------------------------------ -- Set_Signal_Machine_State -- ------------------------------ procedure Set_Signal_Machine_State (M : Machine_State; Context : System.Address) is begin null; end Set_Signal_Machine_State; end System.Machine_State_Operations;
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A S I S . D A T A _ D E C O M P O S I T I O N . D E B U G -- -- -- -- S p e c -- -- -- -- Copyright (c) 1995-2006, 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). -- -- -- ------------------------------------------------------------------------------ -- This package contains routines forming debug images for bstractions -- declared in Asis.Data_Decomposition. package Asis.Data_Decomposition.Debug is function Debug_Image (RC : Record_Component) return Wide_String; function Debug_Image (AC : Array_Component) return Wide_String; -- Returns a string value containing implementation-defined debug -- information associated with the element. -- -- The return value uses Asis.Text.Delimiter_Image to separate the lines -- of multi-line results. The return value does not end with -- Asis.Text.Delimiter_Image. function Is_Derived_From_Record (TD : Element) return Boolean; function Is_Derived_From_Array (TD : Element) return Boolean; -- The public renaming of -- Asis.Data_Decomposition.Aux.Is_Derived_From_Record/ -- Asis.Data_Decomposition.Aux.Is_Derived_From_Array -- May be, we should have it in Asis.Extensions function Dimension (Comp : Array_Component) return ASIS_Natural; -- The public renaming of -- Asis.Data_Decomposition.Set_Get.Dimension -- May be, we should have it in Asis.Extensions -- function Linear_Index -- (Inds : Dimension_Indexes; -- D : ASIS_Natural; -- Ind_Lengths : Dimention_Length; -- Conv : Convention_Id := Convention_Ada) -- return Asis.ASIS_Natural; -- function De_Linear_Index -- (Index : Asis.ASIS_Natural; -- D : ASIS_Natural; -- Ind_Lengths : Dimention_Length; -- Conv : Convention_Id := Convention_Ada) -- return Dimension_Indexes; -- The public renaming of -- Asis.Data_Decomposition.Aux.Linear_Index and -- Asis.Data_Decomposition.Aux.De_Linear_Index end Asis.Data_Decomposition.Debug;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Plugin.Base; use Plugin.Base; with Plugin.URL; use Plugin.URL; with IRC; package Plugin_Management is type Callback is access procedure (Message : IRC.Message); type Plugins is (Say, Title, Join, Leave, Nick); Callbacks : constant array (Plugins) of Callback := (Say => Say'Access, Title => URL_Title'Access, Join => Join'Access, Leave => Leave'Access, Nick => Nick'Access); type Options is (Contextual, Secure); type Options_Arguments is array (Options) of Boolean; Settings : constant array (Plugins) of Options_Arguments := (Say => (Contextual => False, Secure => True), Title => (True, False), Join => (False, True), Leave => (False, True), Nick => (False, True)); function Get_Command (Message : IRC.Message) return Unbounded_String; procedure Execute_Commands (Message : IRC.Message; Owner : Unbounded_String; Prefix : Character); end Plugin_Management;
----------------------------------------------------------------------- -- util-serialize-io -- IO Drivers for serialization -- Copyright (C) 2010, 2011 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.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; package body Util.Serialize.IO is -- use Util.Log; use type Util.Log.Loggers.Logger_Access; -- The logger' Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO", Util.Log.WARN_LEVEL); -- ------------------------------ -- Read the file and parse it using the JSON parser. -- ------------------------------ procedure Parse (Handler : in out Parser; File : in String) is Stream : aliased Util.Streams.Files.File_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.Error_Logger.Info ("Reading file {0}", File); Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File); Buffer.Initialize (Output => null, Input => Stream'Unchecked_Access, Size => 1024); Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File); Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Buffer); exception when Util.Serialize.Mappers.Field_Fatal_Error => null; when Ada.IO_Exceptions.Name_Error => Parser'Class (Handler).Error ("File '" & File & "' does not exist."); when E : others => Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end Parse; -- ------------------------------ -- Parse the content string. -- ------------------------------ procedure Parse_String (Handler : in out Parser; Content : in String) is Stream : aliased Util.Streams.Buffered.Buffered_Stream; begin if Handler.Error_Logger = null then Handler.Error_Logger := Log'Access; end if; Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>"); Stream.Initialize (Content => Content); Context_Stack.Clear (Handler.Stack); Parser'Class (Handler).Parse (Stream); exception when Util.Serialize.Mappers.Field_Fatal_Error => null; when E : others => Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E)); end Parse_String; -- ------------------------------ -- Returns true if the <b>Parse</b> operation detected at least one error. -- ------------------------------ function Has_Error (Handler : in Parser) return Boolean is begin return Handler.Error_Flag; end Has_Error; -- ------------------------------ -- Set the error logger to report messages while parsing and reading the input file. -- ------------------------------ procedure Set_Logger (Handler : in out Parser; Logger : in Util.Log.Loggers.Logger_Access) is begin Handler.Error_Logger := Logger; end Set_Logger; -- ------------------------------ -- Push the current context when entering in an element. -- ------------------------------ procedure Push (Handler : in out Parser) is use type Util.Serialize.Mappers.Mapper_Access; begin Context_Stack.Push (Handler.Stack); end Push; -- ------------------------------ -- Pop the context and restore the previous context when leaving an element -- ------------------------------ procedure Pop (Handler : in out Parser) is begin Context_Stack.Pop (Handler.Stack); end Pop; function Find_Mapper (Handler : in Parser; Name : in String) return Util.Serialize.Mappers.Mapper_Access is pragma Unreferenced (Handler, Name); begin return null; end Find_Mapper; -- ------------------------------ -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ------------------------------ procedure Start_Object (Handler : in out Parser; Name : in String) is use type Util.Serialize.Mappers.Mapper_Access; Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); Next : Element_Context_Access; Pos : Positive; begin Log.Debug ("Start object {0}", Name); Context_Stack.Push (Handler.Stack); Next := Context_Stack.Current (Handler.Stack); if Current /= null then Pos := 1; -- Notify we are entering in the given node for each active mapping. for I in Current.Active_Nodes'Range loop declare Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I); Child : Mappers.Mapper_Access; begin exit when Node = null; Child := Node.Find_Mapper (Name => Name); if Child = null and then Node.Is_Wildcard then Child := Node; end if; if Child /= null then Log.Debug ("{0} is matching {1}", Name, Child.Get_Name); Child.Start_Object (Handler, Name); Next.Active_Nodes (Pos) := Child; Pos := Pos + 1; end if; end; end loop; while Pos <= Next.Active_Nodes'Last loop Next.Active_Nodes (Pos) := null; Pos := Pos + 1; end loop; else Next.Active_Nodes (1) := Handler.Mapping_Tree.Find_Mapper (Name); end if; end Start_Object; -- ------------------------------ -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ------------------------------ procedure Finish_Object (Handler : in out Parser; Name : in String) is use type Util.Serialize.Mappers.Mapper_Access; begin Log.Debug ("Finish object {0}", Name); declare Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); begin if Current /= null then -- Notify we are leaving the given node for each active mapping. for I in Current.Active_Nodes'Range loop declare Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I); begin exit when Node = null; Node.Finish_Object (Handler, Name); end; end loop; end if; end; Handler.Pop; end Finish_Object; procedure Start_Array (Handler : in out Parser; Name : in String) is pragma Unreferenced (Name); begin Handler.Push; end Start_Array; procedure Finish_Array (Handler : in out Parser; Name : in String) is pragma Unreferenced (Name); begin Handler.Pop; end Finish_Array; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- procedure Set_Member (Handler : in out Parser; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is use Util.Serialize.Mappers; Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); begin Log.Debug ("Set member {0}", Name); if Current /= null then -- Look each active mapping node. for I in Current.Active_Nodes'Range loop declare Node : constant Mapper_Access := Current.Active_Nodes (I); begin exit when Node = null; Node.Set_Member (Name => Name, Value => Value, Attribute => Attribute, Context => Handler); exception when E : Util.Serialize.Mappers.Field_Error => Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E)); when E : Util.Serialize.Mappers.Field_Fatal_Error => Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E)); raise; -- For other exception, report an error with the field name and value. when E : others => Parser'Class (Handler).Error (Message => "Cannot set field '" & Name & "' to '" & Util.Beans.Objects.To_String (Value) & "': " & Ada.Exceptions.Exception_Message (E)); raise; end; end loop; end if; end Set_Member; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return Ada.Strings.Unbounded.To_String (Handler.File); end Get_Location; -- ------------------------------ -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. -- ------------------------------ procedure Error (Handler : in out Parser; Message : in String) is begin Handler.Error_Logger.Error ("{0}: {1}", Parser'Class (Handler).Get_Location, Message); Handler.Error_Flag := True; end Error; procedure Add_Mapping (Handler : in out Parser; Path : in String; Mapper : in Util.Serialize.Mappers.Mapper_Access) is begin Handler.Mapping_Tree.Add_Mapping (Path, Mapper); end Add_Mapping; -- ------------------------------ -- Dump the mapping tree on the logger using the INFO log level. -- ------------------------------ procedure Dump (Handler : in Parser'Class; Logger : in Util.Log.Loggers.Logger'Class) is begin Util.Serialize.Mappers.Dump (Handler.Mapping_Tree, Logger, "Mapping "); end Dump; end Util.Serialize.IO;
with Ada.Containers.Vectors, Ada.Containers.Bounded_Hashed_Maps, Ada.Exceptions, Ada.Integer_Text_IO, Ada.Text_IO; with Utils; procedure Main is use Ada.Text_IO; use Utils; package Integer_Vectors is new Ada.Containers.Vectors (Natural, Integer); use Integer_Vectors; subtype Hegihtmap_Values is Natural range 0 .. 10; subtype Hegiht is Hegihtmap_Values range 0 .. 9; type Cave_Heightmap_Array is array (Natural range <>, Natural range <>) of Hegihtmap_Values; File : File_Type; Values : Vector := Empty_Vector; Array_Width, Array_Height : Natural := Natural'First; begin Get_File (File); -- Get all values while not End_Of_File (File) loop Array_Height := Array_Height + 1; declare Str : constant String := Get_Line (File); Value : Hegiht; Last : Positive; begin if Array_Width = Natural'First then Array_Width := Str'Length; end if; for Char of Str loop Ada.Integer_Text_IO.Get (Char & "", Value, Last); Values.Append (Value); end loop; end; end loop; -- Exit the program if there is no values if Values.Is_Empty then Close_If_Open (File); Put_Line ("The input file is empty."); return; end if; declare Cave_Heightmap : Cave_Heightmap_Array (Natural'First .. Array_Height + 1, Natural'First .. Array_Width + 1) := (others => (others => Hegihtmap_Values'Last)); Curs : Cursor := Values.First; Result : Natural := Natural'First; begin -- Initialize Array for Line in 1 .. Array_Height loop for Column in 1 .. Array_Width loop Cave_Heightmap (Line, Column) := Element (Curs); Curs := Next (Curs); end loop; end loop; -- Do the puzzle Solve_Puzzle : declare Current : Hegihtmap_Values; begin for Line in 1 .. Array_Height loop for Column in 1 .. Array_Width loop Current := Cave_Heightmap (Line, Column); if Current < Cave_Heightmap (Line - 1, Column) and then Current < Cave_Heightmap (Line + 1, Column) and then Current < Cave_Heightmap (Line, Column - 1) and then Current < Cave_Heightmap (Line, Column + 1) then Result := Result + Current + 1; end if; end loop; end loop; end Solve_Puzzle; Put ("Result: "); Ada.Integer_Text_IO.Put (Item => Result, Width => 0); New_Line; end; Close_If_Open (File); exception when Occur : others => Put_Line ("Error: " & Ada.Exceptions.Exception_Message (Occur)); Close_If_Open (File); end Main;
-- package Quadrature -- -- The equation is dY/dt = F (t). -- The solution is just the area under the curve - quadrature. -- F(t) is input as a generic formal function called Integrand. -- -- If you want (d/dt)**N Y = F(t), then N is written as -- -- N = Order_of_Equation -- -- Then the integrated Y(0) is solution of (d/dt)**N Y = F(t), -- Then the integrated Y(1) is solution of (d/dt)**N-1 Y = F(t), -- and so on. generic type Real is digits <>; with function Integrand (X : Real) return Real is <>; package Quadrature is Order_of_Equation : constant Positive := 1; type Dyn_Index is range 0 .. Order_of_Equation-1; type Dynamical_Variable is array(Dyn_Index) of Real; DynZero : constant Dynamical_Variable := (others => (+0.0)); function F (Time : Real; Y : Dynamical_Variable) return Dynamical_Variable; -- Defines the equation to be integrated, -- dY/dt = F (t, Y). Even if the equation is t or Y -- independent, it must be entered in this form. function "*" (Left : Real; Right : Dynamical_Variable) return Dynamical_Variable; function "+" (Left : Dynamical_Variable; Right : Dynamical_Variable) return Dynamical_Variable; function "-" (Left : Dynamical_Variable; Right : Dynamical_Variable) return Dynamical_Variable; function Norm (Y : Dynamical_Variable) return Real; pragma Inline (F, "*", "+", "-", Norm); end Quadrature;
-- Abstract : -- -- See spec. -- -- Copyright (C) 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.Strings.Unbounded; use Ada.Strings.Unbounded; function SAL.Gen_Unconstrained_Array_Image (Item : in Array_Type) return String is Result : Unbounded_String := To_Unbounded_String ("("); begin for I in Item'Range loop Result := Result & Element_Image (Item (I)); if I = Item'Last then Result := Result & ")"; else Result := Result & ", "; end if; end loop; return To_String (Result); end SAL.Gen_Unconstrained_Array_Image;
with Ada.Text_IO; use Ada.Text_IO; with Employee; procedure Main is function Read (Prompt : String) return String is begin Put (Prompt & "> "); return Get_Line; end Read; function Read_Date (Prompt : String) return String is (Read (Prompt & " (YYYY-MM-DD)")); Applicant : Employee.Person_T; -- Create objects to store information for an Employee and Position begin Employee.Set_Attribute (Applicant, Read ("Attribute")); Employee.Print (Applicant); -- set attributes / print contents for employee and position end Main;
package Sub_Derived_Types is subtype smallSub is Integer range -10 .. 10; type smallDerived is new Integer range -10 .. 10; type smallRange is range -10 .. 10; subtype bigSub is Integer; type bigDerived is new Integer; type bigRange is range -2**10 .. 2**10; end Sub_Derived_Types;
-- { dg-do compile } pragma Restrictions (No_Default_Initialization); package Array_No_Def_Init is type Int_Array is array (Natural range <>) of Integer; IA : Int_Array (1 .. 10); end Array_No_Def_Init;
with NXP.GPIO; use NXP.GPIO; with NXP_SVD; use NXP_SVD; with NXP_SVD.SYSCON; use NXP_SVD.SYSCON; with NXP_SVD.IOCON; use NXP_SVD.IOCON; with System; package NXP.Device is pragma Elaborate_Body; Unknown_Port : exception; procedure Enable_Clock (This : aliased in out GPIO_Port; Port : Ports); procedure Enable_Clock (Point : GPIO_Point); procedure Enable_Clock (Points : GPIO_Points); procedure Disable_Clock (This : aliased in out GPIO_Port; Port : Ports); procedure Disable_Clock (Point : GPIO_Point); procedure Disable_Clock (Points : GPIO_Points); procedure Reset (This : aliased in out GPIO_Port) with Inline; procedure Reset (Point : GPIO_Point) with Inline; procedure Reset (Points : GPIO_Points) with Inline; function S_NS_Periph (Addr : System.Address) return System.Address with Inline; GPIO : aliased GPIO_Port with Import, Volatile, Address => S_NS_Periph (GPIO_Base); SECGPIO : aliased GPIO_Port with Import, Volatile, Address => S_NS_Periph (SECGPIO_Base); SYSCON : aliased SYSCON_Peripheral with Import, Address => S_NS_Periph (SYSCON_Base); P0_0 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_0); P0_1 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_1); P0_2 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_2); P0_3 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_3); P0_4 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_4); P0_5 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_5); P0_6 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_6); P0_7 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_7); P0_8 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_8); P0_9 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_9); P0_10 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_10); P0_11 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_11); P0_12 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_12); P0_13 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_13); P0_14 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_14); P0_15 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_15); P0_16 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_16); P0_17 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_17); P0_18 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_18); P0_19 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_19); P0_20 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_20); P0_21 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_21); P0_22 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_22); P0_23 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_23); P0_24 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_24); P0_25 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_25); P0_26 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_26); P0_27 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_27); P0_28 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_28); P0_29 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_29); P0_30 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_30); P0_31 : aliased GPIO_Point := (GPIO'Access, Port_0, Pin_31); P1_0 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_0); P1_1 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_1); P1_2 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_2); P1_3 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_3); P1_4 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_4); P1_5 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_5); P1_6 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_6); P1_7 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_7); P1_8 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_8); P1_9 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_9); P1_10 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_10); P1_11 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_11); P1_12 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_12); P1_13 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_13); P1_14 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_14); P1_15 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_15); P1_16 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_16); P1_17 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_17); P1_18 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_18); P1_19 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_19); P1_20 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_20); P1_21 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_21); P1_22 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_22); P1_23 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_23); P1_24 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_24); P1_25 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_25); P1_26 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_26); P1_27 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_27); P1_28 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_28); P1_29 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_29); P1_30 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_30); P1_31 : aliased GPIO_Point := (GPIO'Access, Port_1, Pin_31); GPIO_AF_FC0_USART : constant GPIO_Alternate_Function; private GPIO_AF_FC0_USART : constant GPIO_Alternate_Function := 1; end NXP.Device;
with Extraction.Graph_Operations; private package Extraction.File_System is procedure Extract_Nodes (Directory : VFS.Virtual_File; Graph : Graph_Operations.Graph_Context); procedure Extract_Edges (Directory : VFS.Virtual_File; Graph : Graph_Operations.Graph_Context); end Extraction.File_System;
-- Copyright (c) 1990 Regents of the University of California. -- All rights reserved. -- -- This software was developed by John Self of the Arcadia project -- at the University of California, Irvine. -- -- Redistribution and use in source and binary forms are permitted -- provided that the above copyright notice and this paragraph are -- duplicated in all such forms and that any documentation, -- advertising materials, and other materials related to such -- distribution and use acknowledge that the software was developed -- by the University of California, Irvine. The name of the -- University may not be used to endorse or promote products derived -- from this software without specific prior written permission. -- THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED -- WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. -- TITLE external_file_manager -- AUTHOR: John Self (UCI) -- DESCRIPTION opens external files for other functions -- NOTES This package opens external files, and thus may be system dependent -- because of limitations on file names. -- This version is for the VADS 5.5 Ada development system. -- $Header: /co/ua/self/arcadia/aflex/ada/src/RCS/file_managerB.a,v 1.5 90/01/12 15:19:58 self Exp Locker: self $ with Ada.Characters.Conversions; with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with MISC_DEFS, MISC; use MISC_DEFS; package body External_File_Manager is use Ada.Characters.Conversions; use Ada.Strings.Unbounded; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Wide_Wide_Text_IO; function "+" (Item : Unbounded_String) return String renames To_String; function "+" (Item : String) return Unbounded_String renames To_Unbounded_String; function "+" (Item : Unbounded_Wide_Wide_String) return Wide_Wide_String renames To_Wide_Wide_String; -- FIX comment about compiler dependent Ada_Spec_Suffix : constant String := "ads"; Ada_Body_Suffix : constant String := "adb"; ---------------------- -- Get_IO_Spec_File -- ---------------------- procedure Get_IO_Spec_File (File : in out Ada.Wide_Wide_Text_IO.File_Type) is begin if Length (In_File_Name) /= 0 then Create (File, Out_File, To_String (+Misc.Basename) & "-io." & Ada_Spec_Suffix); else Create (File, Out_File, "aflex_yy-io." & Ada_Spec_Suffix); end if; exception when Use_Error | Name_Error => Misc.Aflex_Fatal ("could not create IO package file"); end Get_IO_Spec_File; ---------------------- -- Get_IO_Body_File -- ---------------------- procedure Get_IO_Body_File (File : in out Ada.Wide_Wide_Text_IO.File_Type) is begin if Length (In_File_Name) /= 0 then Create (File, Out_File, To_String (+Misc.Basename) & "-io." & Ada_Body_Suffix); else Create (File, Out_File, "aflex_yy-io." & Ada_Body_Suffix); end if; exception when Use_Error | Name_Error => Misc.Aflex_Fatal ("could not create IO package file"); end Get_IO_Body_File; ----------------------- -- Get_DFA_Spec_File -- ----------------------- procedure Get_DFA_Spec_File (File : in out Ada.Wide_Wide_Text_IO.File_Type) is begin if Length (In_File_Name) /= 0 then Create (File, Out_File, To_String (+Misc.Basename) & "-dfa." & Ada_Spec_Suffix); else Create (File, Out_File, "aflex_yy-dfa." & Ada_Spec_Suffix); end if; exception when Use_Error | Name_Error => Misc.Aflex_Fatal ("could not create DFA package file"); end Get_DFA_Spec_File; ----------------------- -- Get_DFA_Body_File -- ----------------------- procedure Get_DFA_Body_File (File : in out Ada.Wide_Wide_Text_IO.File_Type) is begin if Length (In_File_Name) /= 0 then Create (File, Out_File, To_String (+Misc.Basename) & "-dfa." & Ada_Body_Suffix); else Create (File, Out_File, "aflex_yy-dfa." & Ada_Body_Suffix); end if; exception when Use_Error | Name_Error => Misc.Aflex_Fatal ("could not create DFA package file"); end Get_DFA_Body_File; --------------------------- -- Get_Scanner_Spec_File -- --------------------------- procedure Get_Scanner_Spec_File (File : in out Ada.Wide_Wide_Text_IO.File_Type) is Out_File_Name : Unbounded_String; begin if Length (In_File_Name) /= 0 then -- give out infile + ada_suffix Out_File_Name := +To_String (+Misc.Basename) & "." & Ada_Spec_Suffix; else Out_File_Name := +"aflex_yy." & Ada_Spec_Suffix; end if; Create (File, Out_File, +Out_File_Name); Set_Output (File); exception when Name_Error | Use_Error => Misc.Aflex_Fatal ("can't create scanner file " & To_Wide_Wide_String (To_String (Out_File_Name))); end Get_Scanner_Spec_File; --------------------------- -- Get_Scanner_Body_File -- --------------------------- procedure Get_Scanner_Body_File (File : in out Ada.Wide_Wide_Text_IO.File_Type) is Out_File_Name : Unbounded_String; begin if Length (In_File_Name) /= 0 then -- give out infile + ada_suffix Out_File_Name := +To_String (+Misc.Basename) & "." & Ada_Body_Suffix; else Out_File_Name := +"aflex_yy." & Ada_Body_Suffix; end if; Create (File, Out_File, +Out_File_Name); Set_Output (File); exception when Name_Error | Use_Error => Misc.Aflex_Fatal ("can't create scanner file " & To_Wide_Wide_String (To_String (Out_File_Name))); end Get_Scanner_Body_File; ------------------------ -- Get_Backtrack_File -- ------------------------ procedure Get_Backtrack_File (File : in out Ada.Wide_Wide_Text_IO.File_Type) is begin CREATE (File, OUT_FILE, "aflex.backtrack"); exception when USE_ERROR | NAME_ERROR => Misc.Aflex_Fatal ("could not create backtrack file"); end GET_Backtrack_File; procedure INITIALIZE_FILES is begin null; -- doesn't need to do anything on Verdix end INITIALIZE_FILES; end EXTERNAL_FILE_MANAGER;
-- MIT License -- Copyright (c) 2021 Stephen Merrony -- 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.Text_IO; use Ada.Text_IO; with Debug_Logs; use Debug_Logs; with Resolver; use Resolver; package body Processor.Eclipse_Stack_P is procedure Do_Eclipse_Stack (I : in Decoded_Instr_T; CPU : in out CPU_T) is Ring : Phys_Addr_T := CPU.PC and 16#7000_0000#; First, Last, This_Ac : Natural; Addr : Phys_Addr_T; begin case I.Instruction is when I_POP => First := Natural(I.Acs); Last := Natural(I.Acd); if Last > First then First := First + 4; end if; This_Ac := First; loop if CPU.Debug_Logging then Loggers.Debug_Print (Debug_Log, "POP popping AC" & This_AC'Image); end if; CPU.AC(AC_Circle(This_AC)) := Dword_T(Narrow_Stack.Pop (Ring)); exit when This_Ac = Last; This_Ac := This_Ac -1; end loop; when I_POPJ => Addr := Phys_Addr_T(Narrow_Stack.Pop(Ring)); CPU.PC := (Addr and 16#7fff#) or Ring; return; -- because PC has been set when I_PSH => First := Natural(I.Acs); Last := Natural(I.Acd); if Last < First then Last := Last + 4; end if; for This_AC in First .. Last loop if CPU.Debug_Logging then Loggers.Debug_Print (Debug_Log, "PSH pushing AC" & This_AC'Image); end if; Narrow_Stack.Push (Ring, DG_Types.Lower_Word(CPU.AC(AC_Circle(This_AC)))); end loop; when I_PSHJ => Narrow_Stack.Push (Ring, DG_Types.Lower_Word(DWord_T(CPU.PC)) + 2); Addr := (Resolve_15bit_Disp (CPU, I.Ind, I.Mode, I.Disp_15, I.Disp_Offset) and 16#7fff#) or Ring; CPU.PC := Addr; return; -- because PC has been set when I_RTN => -- complement of I_SAVE below declare NFP_Sav, Popped_Wd : Word_T; begin NFP_Sav := RAM.Read_Word (NFP_Loc or Ring); RAM.Write_Word (NSP_Loc or Ring, NFP_Sav); Popped_Wd := Narrow_Stack.Pop (Ring); -- 5 CPU.Carry := Test_W_Bit (Popped_Wd, 0); CPU.PC := Phys_Addr_T(Popped_Wd and 16#7fff#) or Ring; CPU.AC(3) := Dword_T(Narrow_Stack.Pop(Ring)); -- 4 CPU.AC(2) := Dword_T(Narrow_Stack.Pop(Ring)); -- 3 CPU.AC(1) := Dword_T(Narrow_Stack.Pop(Ring)); -- 2 CPU.AC(0) := Dword_T(Narrow_Stack.Pop(Ring)); -- 1 RAM.Write_Word (NFP_Loc or Ring, DG_Types.Lower_Word(CPU.AC(3))); return; -- because PC has been set end; when I_SAVE => declare NFP_Sav, NSP_Sav, Word : Word_T; begin NFP_Sav := RAM.Read_Word (NFP_Loc or Ring); NSP_Sav := RAM.Read_Word (NSP_Loc or Ring); Narrow_Stack.Push(Ring, DG_Types.Lower_Word(CPU.AC(0))); -- 1 Narrow_Stack.Push(Ring, DG_Types.Lower_Word(CPU.AC(1))); -- 2 Narrow_Stack.Push(Ring, DG_Types.Lower_Word(CPU.AC(2))); -- 3 Narrow_Stack.Push(Ring, NFP_Sav); -- 4 Word := DG_Types.Lower_Word(CPU.AC(3)); if CPU.Carry then Word := Word or 16#8000#; else Word := Word and 16#7fff#; end if; Narrow_Stack.Push(Ring, Word); -- 5 RAM.Write_Word (NSP_Loc or Ring, NSP_Sav + 5 + Word_T(I.Imm_U16)); RAM.Write_Word (NFP_Loc or Ring, NSP_Sav + 5); CPU.AC(3) := Dword_T(NSP_Sav) + 5; end; when others => Put_Line ("ERROR: Eclipse_Stack instruction " & To_String(I.Mnemonic) & " not yet implemented"); raise Execution_Failure with "ERROR: Eclipse_Stack instruction " & To_String(I.Mnemonic) & " not yet implemented"; end case; CPU.PC := CPU.PC + Phys_Addr_T(I.Instr_Len); end Do_Eclipse_Stack; end Processor.Eclipse_Stack_P;
-- { dg-do compile } -- { dg-options "-flto" { target lto } } package body Lto4 is procedure SS_Allocate (Stack : Stack_Ptr) is Chunk : Chunk_Ptr := Stack.Current_Chunk; begin Chunk := new Chunk_Id (First => Chunk.Last, Last => Chunk.Last); end; end Lto4;
with Ahven.Framework; package JSA.Tests is function Suite return Ahven.Framework.Test_Suite; end JSA.Tests;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . N U M E R I C S . G E N E R I C _ C O M P L E X _ T Y P E S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2019, 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. -- -- -- ------------------------------------------------------------------------------ generic type Real is digits <>; package Ada.Numerics.Generic_Complex_Types is pragma Pure; type Complex is record Re, Im : Real'Base; end record; pragma Complex_Representation (Complex); type Imaginary is private; pragma Preelaborable_Initialization (Imaginary); i : constant Imaginary; j : constant Imaginary; function Re (X : Complex) return Real'Base; function Im (X : Complex) return Real'Base; function Im (X : Imaginary) return Real'Base; procedure Set_Re (X : in out Complex; Re : Real'Base); procedure Set_Im (X : in out Complex; Im : Real'Base); procedure Set_Im (X : out Imaginary; Im : Real'Base); function Compose_From_Cartesian (Re, Im : Real'Base) return Complex; function Compose_From_Cartesian (Re : Real'Base) return Complex; function Compose_From_Cartesian (Im : Imaginary) return Complex; function Modulus (X : Complex) return Real'Base; function "abs" (Right : Complex) return Real'Base renames Modulus; function Argument (X : Complex) return Real'Base; function Argument (X : Complex; Cycle : Real'Base) return Real'Base; function Compose_From_Polar ( Modulus, Argument : Real'Base) return Complex; function Compose_From_Polar ( Modulus, Argument, Cycle : Real'Base) return Complex; function "+" (Right : Complex) return Complex; function "-" (Right : Complex) return Complex; function Conjugate (X : Complex) return Complex; function "+" (Left, Right : Complex) return Complex; function "-" (Left, Right : Complex) return Complex; function "*" (Left, Right : Complex) return Complex; function "/" (Left, Right : Complex) return Complex; function "**" (Left : Complex; Right : Integer) return Complex; function "+" (Right : Imaginary) return Imaginary; function "-" (Right : Imaginary) return Imaginary; function Conjugate (X : Imaginary) return Imaginary renames "-"; function "abs" (Right : Imaginary) return Real'Base; function "+" (Left, Right : Imaginary) return Imaginary; function "-" (Left, Right : Imaginary) return Imaginary; function "*" (Left, Right : Imaginary) return Real'Base; function "/" (Left, Right : Imaginary) return Real'Base; function "**" (Left : Imaginary; Right : Integer) return Complex; function "<" (Left, Right : Imaginary) return Boolean; function "<=" (Left, Right : Imaginary) return Boolean; function ">" (Left, Right : Imaginary) return Boolean; function ">=" (Left, Right : Imaginary) return Boolean; function "+" (Left : Complex; Right : Real'Base) return Complex; function "+" (Left : Real'Base; Right : Complex) return Complex; function "-" (Left : Complex; Right : Real'Base) return Complex; function "-" (Left : Real'Base; Right : Complex) return Complex; function "*" (Left : Complex; Right : Real'Base) return Complex; function "*" (Left : Real'Base; Right : Complex) return Complex; function "/" (Left : Complex; Right : Real'Base) return Complex; function "/" (Left : Real'Base; Right : Complex) return Complex; function "+" (Left : Complex; Right : Imaginary) return Complex; function "+" (Left : Imaginary; Right : Complex) return Complex; function "-" (Left : Complex; Right : Imaginary) return Complex; function "-" (Left : Imaginary; Right : Complex) return Complex; function "*" (Left : Complex; Right : Imaginary) return Complex; function "*" (Left : Imaginary; Right : Complex) return Complex; function "/" (Left : Complex; Right : Imaginary) return Complex; function "/" (Left : Imaginary; Right : Complex) return Complex; function "+" (Left : Imaginary; Right : Real'Base) return Complex; function "+" (Left : Real'Base; Right : Imaginary) return Complex; function "-" (Left : Imaginary; Right : Real'Base) return Complex; function "-" (Left : Real'Base; Right : Imaginary) return Complex; function "*" (Left : Imaginary; Right : Real'Base) return Imaginary; function "*" (Left : Real'Base; Right : Imaginary) return Imaginary; function "/" (Left : Imaginary; Right : Real'Base) return Imaginary; function "/" (Left : Real'Base; Right : Imaginary) return Imaginary; private type Imaginary is new Real'Base; i : constant Imaginary := 1.0; j : constant Imaginary := 1.0; pragma Inline ("+"); pragma Inline ("-"); pragma Inline ("*"); pragma Inline ("<"); pragma Inline ("<="); pragma Inline (">"); pragma Inline (">="); pragma Inline ("abs"); pragma Inline (Compose_From_Cartesian); pragma Inline (Conjugate); pragma Inline (Im); pragma Inline (Re); pragma Inline (Set_Im); pragma Inline (Set_Re); end Ada.Numerics.Generic_Complex_Types;
package body Logic is function Sum(T: Table) return Natural is Result: Natural := 0; begin for I in T'Range loop if T(I) then Result := Result + 1; end if; end loop; return Result; end Sum; function Half(T: Table; Which: Even_Odd) return Table is Result: Table(T'Range); Last: Natural := Result'First - 1; begin for I in T'Range loop if I mod 2 = (if (Which=Odd) then 1 else 0) then Last := Last+1; Result(Last) := T(I); end if; end loop; return Result(Result'First .. Last); end Half; end Logic;
-- with -- glx.Pointers; with OSMesa_C.Binding, System; package body openGL.Context is procedure define (Self : in out Item; the_Display : access openGL.Display.item'Class; the_surface_Profile : in openGL.surface_Profile.item'Class) is pragma Unreferenced (the_surface_Profile); -- use Glx, -- glx.Pointers; use OSMesa_C.Binding; use type System.Address; begin Self.Context := OSMesaCreateContext (format => GL.GL_RGBA, -- OSMESA_RGBA, sharelist => system.Null_Address); if Self.Context = System.Null_Address then raise Program_Error with "no openGL context"; end if; Self.Display := the_Display; end define; procedure make_Current (Self : in Item; read_Surface : in openGL.Surface.item; write_Surface : in openGL.Surface.item) is pragma Unreferenced (write_Surface); -- Success : glx.Bool; pragma Unreferenced (Success); begin null; end make_Current; -- function glx_Context_debug (Self : in Item'Class) return GLX.GLXContext.item -- is -- begin -- return self.glx_Context; -- end glx_Context_debug; end openGL.Context;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . C A L E N D A R -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2005, 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 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. -- -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ -- This is the Alpha/VMS version with System.OS_Primitives; package Ada.Calendar is package OSP renames System.OS_Primitives; type Time is private; -- Declarations representing limits of allowed local time values. Note that -- these do NOT constrain the possible stored values of time which may well -- permit a larger range of times (this is explicitly allowed in Ada 95). subtype Year_Number is Integer range 1901 .. 2099; subtype Month_Number is Integer range 1 .. 12; subtype Day_Number is Integer range 1 .. 31; subtype Day_Duration is Duration range 0.0 .. 86_400.0; function Clock return Time; function Year (Date : Time) return Year_Number; function Month (Date : Time) return Month_Number; function Day (Date : Time) return Day_Number; function Seconds (Date : Time) return Day_Duration; procedure Split (Date : Time; Year : out Year_Number; Month : out Month_Number; Day : out Day_Number; Seconds : out Day_Duration); function Time_Of (Year : Year_Number; Month : Month_Number; Day : Day_Number; Seconds : Day_Duration := 0.0) return Time; function "+" (Left : Time; Right : Duration) return Time; function "+" (Left : Duration; Right : Time) return Time; function "-" (Left : Time; Right : Duration) return Time; function "-" (Left : Time; Right : Time) return Duration; function "<" (Left, Right : Time) return Boolean; function "<=" (Left, Right : Time) return Boolean; function ">" (Left, Right : Time) return Boolean; function ">=" (Left, Right : Time) return Boolean; Time_Error : exception; private pragma Inline (Clock); pragma Inline (Year); pragma Inline (Month); pragma Inline (Day); pragma Inline ("+"); pragma Inline ("-"); pragma Inline ("<"); pragma Inline ("<="); pragma Inline (">"); pragma Inline (">="); -- Time is represented as the number of 100-nanosecond (ns) units offset -- from the system base date and time, which is 00:00 o'clock, -- November 17, 1858 (the Smithsonian base date and time for the -- astronomic calendar). -- The time value stored is typically a GMT value, as provided in standard -- Unix environments. If this is the case then Split and Time_Of perform -- required conversions to and from local times. type Time is new OSP.OS_Time; -- Notwithstanding this definition, Time is not quite the same as OS_Time. -- Relative Time is positive, whereas relative OS_Time is negative, -- but this declaration makes for easier conversion. end Ada.Calendar;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- G N A T . C A L E N D A R . T I M E _ I O -- -- -- -- S p e c -- -- -- -- $Revision$ -- -- -- Copyright (C) 1999-2001 Ada Core Technologies, 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 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. -- -- It is now maintained by Ada Core Technologies Inc (http://www.gnat.com). -- -- -- ------------------------------------------------------------------------------ -- This package augments standard Ada.Text_IO with facilities for input -- and output of time values in standardized format. package GNAT.Calendar.Time_IO is Picture_Error : exception; type Picture_String is new String; -- This is a string to describe date and time output format. The string is -- a set of standard character and special tag that are replaced by the -- corresponding values. It follows the GNU Date specification. Here are -- the recognized directives : -- -- % a literal % -- n a newline -- t a horizontal tab -- -- Time fields: -- -- %H hour (00..23) -- %I hour (01..12) -- %k hour ( 0..23) -- %l hour ( 1..12) -- %M minute (00..59) -- %p locale's AM or PM -- %r time, 12-hour (hh:mm:ss [AP]M) -- %s seconds since 1970-01-01 00:00:00 UTC -- (a nonstandard extension) -- %S second (00..59) -- %T time, 24-hour (hh:mm:ss) -- -- Date fields: -- -- %a locale's abbreviated weekday name (Sun..Sat) -- %A locale's full weekday name, variable length -- (Sunday..Saturday) -- %b locale's abbreviated month name (Jan..Dec) -- %B locale's full month name, variable length -- (January..December) -- %c locale's date and time (Sat Nov 04 12:02:33 EST 1989) -- %d day of month (01..31) -- %D date (mm/dd/yy) -- %h same as %b -- %j day of year (001..366) -- %m month (01..12) -- %U week number of year with Sunday as first day of week -- (00..53) -- %w day of week (0..6) with 0 corresponding to Sunday -- %W week number of year with Monday as first day of week -- (00..53) -- %x locale's date representation (mm/dd/yy) -- %y last two digits of year (00..99) -- %Y year (1970...) -- -- By default, date pads numeric fields with zeroes. GNU date -- recognizes the following nonstandard numeric modifiers: -- -- - (hyphen) do not pad the field -- _ (underscore) pad the field with spaces ISO_Date : constant Picture_String; -- This format follow the ISO 8601 standard. The format is "YYYY-MM-DD", -- four digits year, month and day number separated by minus. US_Date : constant Picture_String; -- This format is the common US date format: "MM/DD/YY", -- month and day number, two digits year separated by slashes. European_Date : constant Picture_String; -- This format is the common European date format: "DD/MM/YY", -- day and month number, two digits year separated by slashes. function Image (Date : Ada.Calendar.Time; Picture : Picture_String) return String; -- Return Date as a string with format Picture. -- raise Picture_Error if picture string is wrong procedure Put_Time (Date : Ada.Calendar.Time; Picture : Picture_String); -- Put Date with format Picture. -- raise Picture_Error if picture string is wrong private ISO_Date : constant Picture_String := "%Y-%m-%d"; US_Date : constant Picture_String := "%m/%d/%y"; European_Date : constant Picture_String := "%d/%m/%y"; end GNAT.Calendar.Time_IO;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . S T R I N G S . F I X E D -- -- -- -- S p e c -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. In accordance with the copyright of that document, you can freely -- -- copy and modify this specification, provided that if you redistribute a -- -- modified version, any changes that you have made are clearly indicated. -- -- -- ------------------------------------------------------------------------------ -- Preconditions in this unit are meant for analysis only, not for run-time -- checking, so that the expected exceptions are raised. This is enforced by -- setting the corresponding assertion policy to Ignore. pragma Assertion_Policy (Pre => Ignore); with Ada.Strings.Maps; -- The language-defined package Strings.Fixed provides string-handling -- subprograms for fixed-length strings; that is, for values of type -- Standard.String. Several of these subprograms are procedures that modify -- the contents of a String that is passed as an out or an in out parameter; -- each has additional parameters to control the effect when the logical -- length of the result differs from the parameter's length. -- -- For each function that returns a String, the lower bound of the returned -- value is 1. -- -- The basic model embodied in the package is that a fixed-length string -- comprises significant characters and possibly padding (with space -- characters) on either or both ends. When a shorter string is copied to a -- longer string, padding is inserted, and when a longer string is copied to a -- shorter one, padding is stripped. The Move procedure in Strings.Fixed, -- which takes a String as an out parameter, allows the programmer to control -- these effects. Similar control is provided by the string transformation -- procedures. package Ada.Strings.Fixed with SPARK_Mode is pragma Preelaborate; -------------------------------------------------------------- -- Copy Procedure for Strings of Possibly Different Lengths -- -------------------------------------------------------------- procedure Move (Source : String; Target : out String; Drop : Truncation := Error; Justify : Alignment := Left; Pad : Character := Space) with -- Incomplete contract Global => null; -- The Move procedure copies characters from Source to Target. If Source -- has the same length as Target, then the effect is to assign Source to -- Target. If Source is shorter than Target then: -- -- * If Justify=Left, then Source is copied into the first Source'Length -- characters of Target. -- -- * If Justify=Right, then Source is copied into the last Source'Length -- characters of Target. -- -- * If Justify=Center, then Source is copied into the middle Source'Length -- characters of Target. In this case, if the difference in length -- between Target and Source is odd, then the extra Pad character is on -- the right. -- -- * Pad is copied to each Target character not otherwise assigned. -- -- If Source is longer than Target, then the effect is based on Drop. -- -- * If Drop=Left, then the rightmost Target'Length characters of Source -- are copied into Target. -- -- * If Drop=Right, then the leftmost Target'Length characters of Source -- are copied into Target. -- -- * If Drop=Error, then the effect depends on the value of the Justify -- parameter and also on whether any characters in Source other than Pad -- would fail to be copied: -- -- * If Justify=Left, and if each of the rightmost -- Source'Length-Target'Length characters in Source is Pad, then the -- leftmost Target'Length characters of Source are copied to Target. -- -- * If Justify=Right, and if each of the leftmost -- Source'Length-Target'Length characters in Source is Pad, then the -- rightmost Target'Length characters of Source are copied to Target. -- -- * Otherwise, Length_Error is propagated. ------------------------ -- Search Subprograms -- ------------------------ function Index (Source : String; Pattern : String; From : Positive; Going : Direction := Forward; Mapping : Maps.Character_Mapping_Function) return Natural with Pre => Pattern'Length /= 0 and then (if Source'Length /= 0 then From in Source'Range), Post => Index'Result in 0 | Source'Range, Contract_Cases => -- If no slice in the considered range of Source matches Pattern, -- then 0 is returned. ((for all J in Source'Range => (if (if Going = Forward then J in From .. Source'Last - Pattern'Length + 1 else J <= From - Pattern'Length + 1) then Translate (Source (J .. J - 1 + Pattern'Length), Mapping) /= Pattern)) => Index'Result = 0, -- Otherwise, a valid index is returned others => -- The result is in the considered range of Source (if Going = Forward then Index'Result in From .. Source'Last - Pattern'Length + 1 else Index'Result in Source'First .. From - Pattern'Length + 1) -- The slice beginning at the returned index matches Pattern and then Translate (Source (Index'Result .. Index'Result - 1 + Pattern'Length), Mapping) = Pattern -- The result is the smallest or largest index which satisfies the -- matching, respectively when Going = Forward and -- Going = Backwards. and then (for all J in Source'Range => (if (if Going = Forward then J in From .. Index'Result - 1 else J - 1 in Index'Result .. From - Pattern'Length) then Translate (Source (J .. J - 1 + Pattern'Length), Mapping) /= Pattern))), Global => null; pragma Ada_05 (Index); function Index (Source : String; Pattern : String; From : Positive; Going : Direction := Forward; Mapping : Maps.Character_Mapping := Maps.Identity) return Natural with Pre => Pattern'Length /= 0 and then (if Source'Length /= 0 then From in Source'Range), Post => Index'Result in 0 | Source'Range, Contract_Cases => -- If no slice in the considered range of Source matches Pattern, -- then 0 is returned. ((for all J in Source'Range => (if (if Going = Forward then J in From .. Source'Last - Pattern'Length + 1 else J <= From - Pattern'Length + 1) then Translate (Source (J .. J - 1 + Pattern'Length), Mapping) /= Pattern)) => Index'Result = 0, -- Otherwise, a valid index is returned others => -- The result is in the considered range of Source (if Going = Forward then Index'Result in From .. Source'Last - Pattern'Length + 1 else Index'Result in Source'First .. From - Pattern'Length + 1) -- The slice beginning at the returned index matches Pattern and then Translate (Source (Index'Result .. Index'Result - 1 + Pattern'Length), Mapping) = Pattern -- The result is the smallest or largest index which satisfies the -- matching, respectively when Going = Forward and -- Going = Backwards. and then (for all J in Source'Range => (if (if Going = Forward then J in From .. Index'Result - 1 else J - 1 in Index'Result .. From - Pattern'Length) then Translate (Source (J .. J - 1 + Pattern'Length), Mapping) /= Pattern))), Global => null; pragma Ada_05 (Index); -- Each Index function searches, starting from From, for a slice of -- Source, with length Pattern'Length, that matches Pattern with respect to -- Mapping; the parameter Going indicates the direction of the lookup. If -- Source is the null string, Index returns 0; otherwise, if From is not in -- Source'Range, then Index_Error is propagated. If Going = Forward, then -- Index returns the smallest index I which is greater than or equal to -- From such that the slice of Source starting at I matches Pattern. If -- Going = Backward, then Index returns the largest index I such that the -- slice of Source starting at I matches Pattern and has an upper bound -- less than or equal to From. If there is no such slice, then 0 is -- returned. If Pattern is the null string, then Pattern_Error is -- propagated. function Index (Source : String; Pattern : String; Going : Direction := Forward; Mapping : Maps.Character_Mapping := Maps.Identity) return Natural with Pre => Pattern'Length > 0, Post => Index'Result in 0 | Source'Range, Contract_Cases => -- If Source is empty, or if no slice of Source matches Pattern, then -- 0 is returned. (Source'Length = 0 or else (for all J in Source'First .. Source'Last - Pattern'Length + 1 => Translate (Source (J .. J - 1 + Pattern'Length), Mapping) /= Pattern) => Index'Result = 0, -- Otherwise, a valid index is returned others => -- The result is in the considered range of Source Index'Result in Source'First .. Source'Last - Pattern'Length + 1 -- The slice beginning at the returned index matches Pattern and then Translate (Source (Index'Result .. Index'Result - 1 + Pattern'Length), Mapping) = Pattern -- The result is the smallest or largest index which satisfies the -- matching, respectively when Going = Forward and -- Going = Backwards. and then (for all J in Source'Range => (if (if Going = Forward then J <= Index'Result - 1 else J - 1 in Index'Result .. Source'Last - Pattern'Length) then Translate (Source (J .. J - 1 + Pattern'Length), Mapping) /= Pattern))), Global => null; function Index (Source : String; Pattern : String; Going : Direction := Forward; Mapping : Maps.Character_Mapping_Function) return Natural with Pre => Pattern'Length > 0, Post => Index'Result in 0 | Source'Range, Contract_Cases => -- If Source is empty, or if no slice of Source matches Pattern, then -- 0 is returned. (Source'Length = 0 or else (for all J in Source'First .. Source'Last - Pattern'Length + 1 => Translate (Source (J .. J - 1 + Pattern'Length), Mapping) /= Pattern) => Index'Result = 0, -- Otherwise, a valid index is returned others => -- The result is in the considered range of Source Index'Result in Source'First .. Source'Last - Pattern'Length + 1 -- The slice beginning at the returned index matches Pattern and then Translate (Source (Index'Result .. Index'Result - 1 + Pattern'Length), Mapping) = Pattern -- The result is the smallest or largest index which satisfies the -- matching, respectively when Going = Forward and -- Going = Backwards. and then (for all J in Source'Range => (if (if Going = Forward then J <= Index'Result - 1 else J - 1 in Index'Result .. Source'Last - Pattern'Length) then Translate (Source (J .. J - 1 + Pattern'Length), Mapping) /= Pattern))), Global => null; -- If Going = Forward, returns: -- -- Index (Source, Pattern, Source'First, Forward, Mapping) -- -- otherwise, returns: -- -- Index (Source, Pattern, Source'Last, Backward, Mapping). function Index (Source : String; Set : Maps.Character_Set; Test : Membership := Inside; Going : Direction := Forward) return Natural with Post => Index'Result in 0 | Source'Range, Contract_Cases => -- If no character of Source satisfies the property Test on Set, then -- 0 is returned. ((for all C of Source => (Test = Inside) /= Ada.Strings.Maps.Is_In (C, Set)) => Index'Result = 0, -- Otherwise, a index in the range of Source is returned others => -- The result is in the range of Source Index'Result in Source'Range -- The character at the returned index satisfies the property -- Test on Set and then (Test = Inside) = Ada.Strings.Maps.Is_In (Source (Index'Result), Set) -- The result is the smallest or largest index which satisfies the -- property, respectively when Going = Forward and -- Going = Backwards. and then (for all J in Source'Range => (if J /= Index'Result and then (J < Index'Result) = (Going = Forward) then (Test = Inside) /= Ada.Strings.Maps.Is_In (Source (J), Set)))), Global => null; function Index (Source : String; Set : Maps.Character_Set; From : Positive; Test : Membership := Inside; Going : Direction := Forward) return Natural with Pre => (if Source'Length /= 0 then From in Source'Range), Post => Index'Result in 0 | Source'Range, Contract_Cases => -- If no character in the considered slice of Source satisfies the -- property Test on Set, then 0 is returned. ((for all I in Source'Range => (if I = From or else (I > From) = (Going = Forward) then (Test = Inside) /= Ada.Strings.Maps.Is_In (Source (I), Set))) => Index'Result = 0, -- Otherwise, an index in the range of Source is returned others => -- The result is in the considered range of Source Index'Result in Source'Range and then (Index'Result = From or else (Index'Result > From) = (Going = Forward)) -- The character at the returned index satisfies the property -- Test on Set. and then (Test = Inside) = Ada.Strings.Maps.Is_In (Source (Index'Result), Set) -- The result is the smallest or largest index which satisfies the -- property, respectively when Going = Forward and -- Going = Backwards. and then (for all J in Source'Range => (if J /= Index'Result and then (J < Index'Result) = (Going = Forward) and then (J = From or else (J > From) = (Going = Forward)) then (Test = Inside) /= Ada.Strings.Maps.Is_In (Source (J), Set)))), Global => null; pragma Ada_05 (Index); -- Index searches for the first or last occurrence of any of a set of -- characters (when Test=Inside), or any of the complement of a set of -- characters (when Test=Outside). If Source is the null string, Index -- returns 0; otherwise, if From is not in Source'Range, then Index_Error -- is propagated. Otherwise, it returns the smallest index I >= From (if -- Going=Forward) or the largest index I <= From (if Going=Backward) such -- that Source(I) satisfies the Test condition with respect to Set; it -- returns 0 if there is no such Character in Source. function Index_Non_Blank (Source : String; From : Positive; Going : Direction := Forward) return Natural with Pre => (if Source'Length /= 0 then From in Source'Range), Post => Index_Non_Blank'Result in 0 | Source'Range, Contract_Cases => -- If all characters in the considered slice of Source are Space -- characters, then 0 is returned. ((for all J in Source'Range => (if J = From or else (J > From) = (Going = Forward) then Source (J) = ' ')) => Index_Non_Blank'Result = 0, -- Otherwise, a valid index is returned others => -- The result is in the considered range of Source Index_Non_Blank'Result in Source'Range and then (Index_Non_Blank'Result = From or else (Index_Non_Blank'Result > From) = (Going = Forward)) -- The character at the returned index is not a Space character and then Source (Index_Non_Blank'Result) /= ' ' -- The result is the smallest or largest index which is not a -- Space character, respectively when Going = Forward and -- Going = Backwards. and then (for all J in Source'Range => (if J /= Index_Non_Blank'Result and then (J < Index_Non_Blank'Result) = (Going = Forward) and then (J = From or else (J > From) = (Going = Forward)) then Source (J) = ' '))), Global => null; pragma Ada_05 (Index_Non_Blank); -- Returns Index (Source, Maps.To_Set(Space), From, Outside, Going) function Index_Non_Blank (Source : String; Going : Direction := Forward) return Natural with Post => Index_Non_Blank'Result in 0 | Source'Range, Contract_Cases => -- If all characters of Source are Space characters, then 0 is -- returned. ((for all C of Source => C = ' ') => Index_Non_Blank'Result = 0, -- Otherwise, a valid index is returned others => -- The result is in the range of Source Index_Non_Blank'Result in Source'Range -- The character at the returned index is not a Space character and then Source (Index_Non_Blank'Result) /= ' ' -- The result is the smallest or largest index which is not a -- Space character, respectively when Going = Forward and -- Going = Backwards. and then (for all J in Source'Range => (if J /= Index_Non_Blank'Result and then (J < Index_Non_Blank'Result) = (Going = Forward) then Source (J) = ' '))), Global => null; -- Returns Index (Source, Maps.To_Set(Space), Outside, Going) function Count (Source : String; Pattern : String; Mapping : Maps.Character_Mapping := Maps.Identity) return Natural with Pre => Pattern'Length /= 0, Global => null; function Count (Source : String; Pattern : String; Mapping : Maps.Character_Mapping_Function) return Natural with Pre => Pattern'Length /= 0, Global => null; -- Returns the maximum number of nonoverlapping slices of Source that match -- Pattern with respect to Mapping. If Pattern is the null string then -- Pattern_Error is propagated. function Count (Source : String; Set : Maps.Character_Set) return Natural with Global => null; -- Returns the number of occurrences in Source of characters that are in -- Set. procedure Find_Token (Source : String; Set : Maps.Character_Set; From : Positive; Test : Membership; First : out Positive; Last : out Natural) with Pre => (if Source'Length /= 0 then From in Source'Range), Contract_Cases => -- If Source is the empty string, or if no character of the considered -- slice of Source satisfies the property Test on Set, then First is -- set to From and Last is set to 0. (Source'Length = 0 or else (for all C of Source (From .. Source'Last) => (Test = Inside) /= Ada.Strings.Maps.Is_In (C, Set)) => First = From and then Last = 0, -- Otherwise, First and Last are set to valid indexes others => -- First and Last are in the considered range of Source First in From .. Source'Last and then Last in First .. Source'Last -- No character between From and First satisfies the property Test -- on Set. and then (for all C of Source (From .. First - 1) => (Test = Inside) /= Ada.Strings.Maps.Is_In (C, Set)) -- All characters between First and Last satisfy the property Test -- on Set. and then (for all C of Source (First .. Last) => (Test = Inside) = Ada.Strings.Maps.Is_In (C, Set)) -- If Last is not Source'Last, then the character at position -- Last + 1 does not satify the property Test on Set. and then (if Last < Source'Last then (Test = Inside) /= Ada.Strings.Maps.Is_In (Source (Last + 1), Set))), Global => null; pragma Ada_2012 (Find_Token); -- If Source is not the null string and From is not in Source'Range, then -- Index_Error is raised. Otherwise, First is set to the index of the first -- character in Source(From .. Source'Last) that satisfies the Test -- condition. Last is set to the largest index such that all characters in -- Source(First .. Last) satisfy the Test condition. If no characters in -- Source(From .. Source'Last) satisfy the Test condition, First is set to -- From, and Last is set to 0. procedure Find_Token (Source : String; Set : Maps.Character_Set; Test : Membership; First : out Positive; Last : out Natural) with Contract_Cases => -- If Source is the empty string, or if no character of Source -- satisfies the property Test on Set, then First is set to From and -- Last is set to 0. (Source'Length = 0 or else (for all C of Source => (Test = Inside) /= Ada.Strings.Maps.Is_In (C, Set)) => First = Source'First and then Last = 0, -- Otherwise, First and Last are set to valid indexes others => -- First and Last are in the considered range of Source First in Source'Range and then Last in First .. Source'Last -- No character before First satisfies the property Test on Set and then (for all C of Source (Source'First .. First - 1) => (Test = Inside) /= Ada.Strings.Maps.Is_In (C, Set)) -- All characters between First and Last satisfy the property Test -- on Set. and then (for all C of Source (First .. Last) => (Test = Inside) = Ada.Strings.Maps.Is_In (C, Set)) -- If Last is not Source'Last, then the character at position -- Last + 1 does not satify the property Test on Set. and then (if Last < Source'Last then (Test = Inside) /= Ada.Strings.Maps.Is_In (Source (Last + 1), Set))), Global => null; -- Equivalent to Find_Token (Source, Set, Source'First, Test, First, Last) ------------------------------------ -- String Translation Subprograms -- ------------------------------------ function Translate (Source : String; Mapping : Maps.Character_Mapping_Function) return String with Post => -- Lower bound of the returned string is 1 Translate'Result'First = 1 -- The returned string has the same length as Source and then Translate'Result'Last = Source'Length -- Each character in the returned string is the translation of the -- character at the same position in Source through Mapping. and then (for all J in Source'Range => Translate'Result (J - Source'First + 1) = Mapping (Source (J))), Global => null; function Translate (Source : String; Mapping : Maps.Character_Mapping) return String with Post => -- Lower bound of the returned string is 1 Translate'Result'First = 1 -- The returned string has the same length as Source and then Translate'Result'Last = Source'Length -- Each character in the returned string is the translation of the -- character at the same position in Source through Mapping. and then (for all J in Source'Range => Translate'Result (J - Source'First + 1) = Ada.Strings.Maps.Value (Mapping, Source (J))), Global => null; -- Returns the string S whose length is Source'Length and such that S (I) -- is the character to which Mapping maps the corresponding element of -- Source, for I in 1 .. Source'Length. procedure Translate (Source : in out String; Mapping : Maps.Character_Mapping_Function) with Post => -- Each character in Source after the call is the translation of -- the character at the same position before the call, through Mapping. (for all J in Source'Range => Source (J) = Mapping (Source'Old (J))), Global => null; procedure Translate (Source : in out String; Mapping : Maps.Character_Mapping) with Post => -- Each character in Source after the call is the translation of -- the character at the same position before the call, through Mapping. (for all J in Source'Range => Source (J) = Ada.Strings.Maps.Value (Mapping, Source'Old (J))), Global => null; -- Equivalent to Source := Translate(Source, Mapping) --------------------------------------- -- String Transformation Subprograms -- --------------------------------------- procedure Replace_Slice (Source : in out String; Low : Positive; High : Natural; By : String; Drop : Truncation := Error; Justify : Alignment := Left; Pad : Character := Space) with Pre => -- Incomplete contract Low - 1 <= Source'Last and then High >= Source'First - 1, Global => null; -- If Low > Source'Last+1, or High < Source'First - 1, then Index_Error is -- propagated. Otherwise: -- -- * If High >= Low, then the returned string comprises -- Source (Source'First .. Low - 1) -- & By & Source(High + 1 .. Source'Last), but with lower bound 1. -- -- * If High < Low, then the returned string is -- Insert (Source, Before => Low, New_Item => By). function Replace_Slice (Source : String; Low : Positive; High : Natural; By : String) return String with Pre => Low - 1 <= Source'Last and then High >= Source'First - 1 and then (if High >= Low then Natural'Max (0, Low - Source'First) <= Natural'Last - By'Length - Natural'Max (Source'Last - High, 0) else Source'Length <= Natural'Last - By'Length), -- Lower bound of the returned string is 1 Post => Replace_Slice'Result'First = 1, Contract_Cases => -- If High >= Low, then the returned string comprises -- Source (Source'First .. Low - 1) & By -- & Source(High + 1 .. Source'Last). (High >= Low => -- Length of the returned string Replace_Slice'Result'Length = Natural'Max (0, Low - Source'First) + By'Length + Natural'Max (Source'Last - High, 0) -- Elements starting at Low are replaced by elements of By and then Replace_Slice'Result (1 .. Natural'Max (0, Low - Source'First)) = Source (Source'First .. Low - 1) and then Replace_Slice'Result (Natural'Max (0, Low - Source'First) + 1 .. Natural'Max (0, Low - Source'First) + By'Length) = By -- When there are remaining characters after the replaced slice, -- they are appended to the result. and then (if High < Source'Last then Replace_Slice'Result (Natural'Max (0, Low - Source'First) + By'Length + 1 .. Replace_Slice'Result'Last) = Source (High + 1 .. Source'Last)), -- If High < Low, then the returned string is -- Insert (Source, Before => Low, New_Item => By). others => -- Length of the returned string Replace_Slice'Result'Length = Source'Length + By'Length -- Elements of By are inserted after the element at Low and then Replace_Slice'Result (1 .. Low - Source'First) = Source (Source'First .. Low - 1) and then Replace_Slice'Result (Low - Source'First + 1 .. Low - Source'First + By'Length) = By -- When there are remaining characters after Low in Source, they -- are appended to the result. and then (if Low < Source'Last then Replace_Slice'Result (Low - Source'First + By'Length + 1 .. Replace_Slice'Result'Last) = Source (Low .. Source'Last))), Global => null; -- Equivalent to: -- -- Move (Replace_Slice (Source, Low, High, By), -- Source, Drop, Justify, Pad). function Insert (Source : String; Before : Positive; New_Item : String) return String with Pre => Before - 1 in Source'First - 1 .. Source'Last and then Source'Length <= Natural'Last - New_Item'Length, Post => -- Lower bound of the returned string is 1 Insert'Result'First = 1 -- Length of the returned string and then Insert'Result'Length = Source'Length + New_Item'Length -- Elements of New_Item are inserted after element at Before and then Insert'Result (1 .. Before - Source'First) = Source (Source'First .. Before - 1) and then Insert'Result (Before - Source'First + 1 .. Before - Source'First + New_Item'Length) = New_Item -- When there are remaining characters after Before in Source, they -- are appended to the returned string. and then (if Before - 1 < Source'Last then Insert'Result (Before - Source'First + New_Item'Length + 1 .. Insert'Result'Last) = Source (Before .. Source'Last)), Global => null; -- Propagates Index_Error if Before is not in -- Source'First .. Source'Last+1; otherwise, returns -- Source (Source'First .. Before - 1) -- & New_Item & Source(Before..Source'Last), but with lower bound 1. procedure Insert (Source : in out String; Before : Positive; New_Item : String; Drop : Truncation := Error) with Pre => Before - 1 in Source'First - 1 .. Source'Last, -- Incomplete contract Global => null; -- Equivalent to Move (Insert (Source, Before, New_Item), Source, Drop) function Overwrite (Source : String; Position : Positive; New_Item : String) return String with Pre => Position - 1 in Source'First - 1 .. Source'Last and then (if Position - Source'First >= Source'Length - New_Item'Length then Position - Source'First <= Natural'Last - New_Item'Length), Post => -- Lower bound of the returned string is 1 Overwrite'Result'First = 1 -- Length of the returned string and then Overwrite'Result'Length = Integer'Max (Source'Length, Position - Source'First + New_Item'Length) -- Elements after Position are replaced by elements of New_Item and then Overwrite'Result (1 .. Position - Source'First) = Source (Source'First .. Position - 1) and then Overwrite'Result (Position - Source'First + 1 .. Position - Source'First + New_Item'Length) = New_Item -- If the end of Source is reached before the characters in New_Item -- are exhausted, the remaining characters from New_Item are appended -- to the string. and then (if Position <= Source'Last - New_Item'Length then Overwrite'Result (Position - Source'First + New_Item'Length + 1 .. Overwrite'Result'Last) = Source (Position + New_Item'Length .. Source'Last)), Global => null; -- Propagates Index_Error if Position is not in -- Source'First .. Source'Last + 1; otherwise, returns the string obtained -- from Source by consecutively replacing characters starting at Position -- with corresponding characters from New_Item. If the end of Source is -- reached before the characters in New_Item are exhausted, the remaining -- characters from New_Item are appended to the string. procedure Overwrite (Source : in out String; Position : Positive; New_Item : String; Drop : Truncation := Right) with Pre => Position - 1 in Source'First - 1 .. Source'Last, -- Incomplete contract Global => null; -- Equivalent to Move(Overwrite(Source, Position, New_Item), Source, Drop) function Delete (Source : String; From : Positive; Through : Natural) return String with Pre => (if From <= Through then (From in Source'Range and then Through <= Source'Last)), -- Lower bound of the returned string is 1 Post => Delete'Result'First = 1, Contract_Cases => -- If From <= Through, the characters between From and Through are -- removed. (From <= Through => -- Length of the returned string Delete'Result'Length = Source'Length - (Through - From + 1) -- Elements before From are preserved and then Delete'Result (1 .. From - Source'First) = Source (Source'First .. From - 1) -- If there are remaining characters after Through, they are -- appended to the returned string. and then (if Through < Source'Last then Delete'Result (From - Source'First + 1 .. Delete'Result'Last) = Source (Through + 1 .. Source'Last)), -- Otherwise, the returned string is Source with lower bound 1 others => Delete'Result'Length = Source'Length and then Delete'Result = Source), Global => null; -- If From <= Through, the returned string is -- Replace_Slice(Source, From, Through, ""); otherwise, it is Source with -- lower bound 1. procedure Delete (Source : in out String; From : Positive; Through : Natural; Justify : Alignment := Left; Pad : Character := Space) with Pre => (if From <= Through then (From in Source'Range and then Through <= Source'Last)), -- Incomplete contract Global => null; -- Equivalent to: -- -- Move (Delete (Source, From, Through), -- Source, Justify => Justify, Pad => Pad). --------------------------------- -- String Selector Subprograms -- --------------------------------- function Trim (Source : String; Side : Trim_End) return String with Post => -- Lower bound of the returned string is 1 Trim'Result'First = 1 -- If all characters in Source are Space, the returned string is -- empty. and then (if (for all J in Source'Range => Source (J) = ' ') then Trim'Result = "" -- Otherwise, the returned string is a slice of Source else (for some Low in Source'Range => (for some High in Source'Range => -- Trim returns the slice of Source between Low and High Trim'Result = Source (Low .. High) -- Values of Low and High and the characters at their -- position depend on Side. and then (if Side = Left then High = Source'Last else Source (High) /= ' ') and then (if Side = Right then Low = Source'First else Source (Low) /= ' ') -- All characters outside range Low .. High are -- Space characters. and then (for all J in Source'Range => (if J < Low then Source (J) = ' ') and then (if J > High then Source (J) = ' '))))), Global => null; -- Returns the string obtained by removing from Source all leading Space -- characters (if Side = Left), all trailing Space characters (if -- Side = Right), or all leading and trailing Space characters (if -- Side = Both). procedure Trim (Source : in out String; Side : Trim_End; Justify : Alignment := Left; Pad : Character := Space) with -- Incomplete contract Global => null; -- Equivalent to: -- -- Move (Trim (Source, Side), Source, Justify=>Justify, Pad=>Pad). function Trim (Source : String; Left : Maps.Character_Set; Right : Maps.Character_Set) return String with Post => -- Lower bound of the returned string is 1 Trim'Result'First = 1 -- If all characters are contained in one of the sets Left and Right, -- then the returned string is empty. and then (if (for all K in Source'Range => Ada.Strings.Maps.Is_In (Source (K), Left)) or (for all K in Source'Range => Ada.Strings.Maps.Is_In (Source (K), Right)) then Trim'Result = "" -- Otherwise, the returned string is a slice of Source else (for some Low in Source'Range => (for some High in Source'Range => -- Trim returns the slice of Source between Low and High Trim'Result = Source (Low .. High) -- Characters at the bounds of the returned string are -- not contained in Left or Right. and then not Ada.Strings.Maps.Is_In (Source (Low), Left) and then not Ada.Strings.Maps.Is_In (Source (High), Right) -- All characters before Low are contained in Left. -- All characters after High are contained in Right. and then (for all K in Source'Range => (if K < Low then Ada.Strings.Maps.Is_In (Source (K), Left)) and then (if K > High then Ada.Strings.Maps.Is_In (Source (K), Right)))))), Global => null; -- Returns the string obtained by removing from Source all leading -- characters in Left and all trailing characters in Right. procedure Trim (Source : in out String; Left : Maps.Character_Set; Right : Maps.Character_Set; Justify : Alignment := Strings.Left; Pad : Character := Space) with -- Incomplete contract Global => null; -- Equivalent to: -- -- Move (Trim (Source, Left, Right), -- Source, Justify => Justify, Pad=>Pad). function Head (Source : String; Count : Natural; Pad : Character := Space) return String with Post => -- Lower bound of the returned string is 1 Head'Result'First = 1 -- Length of the returned string is Count. and then Head'Result'Length = Count, Contract_Cases => -- If Count <= Source'Length, then the first Count characters of -- Source are returned. (Count <= Source'Length => Head'Result = Source (Source'First .. Source'First - 1 + Count), -- Otherwise, the returned string is Source concatenated with -- Count - Source'Length Pad characters. others => Head'Result (1 .. Source'Length) = Source and then Head'Result (Source'Length + 1 .. Count) = (1 .. Count - Source'Length => Pad)), Global => null; -- Returns a string of length Count. If Count <= Source'Length, the string -- comprises the first Count characters of Source. Otherwise, its contents -- are Source concatenated with Count - Source'Length Pad characters. procedure Head (Source : in out String; Count : Natural; Justify : Alignment := Left; Pad : Character := Space) with -- Incomplete contract Global => null; -- Equivalent to: -- -- Move (Head (Source, Count, Pad), -- Source, Drop => Error, Justify => Justify, Pad => Pad). function Tail (Source : String; Count : Natural; Pad : Character := Space) return String with Post => -- Lower bound of the returned string is 1 Tail'Result'First = 1 -- Length of the returned string is Count and then Tail'Result'Length = Count, Contract_Cases => -- If Count is zero, then the returned string is empty (Count = 0 => Tail'Result = "", -- Otherwise, if Count <= Source'Length, then the last Count -- characters of Source are returned. (Count in 1 .. Source'Length) => Tail'Result = Source (Source'Last - Count + 1 .. Source'Last), -- Otherwise, the returned string is Count - Source'Length Pad -- characters concatenated with Source. others => -- If Source is empty, then the returned string is Count Pad -- characters. (if Source'Length = 0 then Tail'Result = (1 .. Count => Pad) else Tail'Result (1 .. Count - Source'Length) = (1 .. Count - Source'Length => Pad) and then Tail'Result (Count - Source'Length + 1 .. Tail'Result'Last) = Source)), Global => null; -- Returns a string of length Count. If Count <= Source'Length, the string -- comprises the last Count characters of Source. Otherwise, its contents -- are Count-Source'Length Pad characters concatenated with Source. procedure Tail (Source : in out String; Count : Natural; Justify : Alignment := Left; Pad : Character := Space) with -- Incomplete contract Global => null; -- Equivalent to: -- -- Move (Tail (Source, Count, Pad), -- Source, Drop => Error, Justify => Justify, Pad => Pad). ---------------------------------- -- String Constructor Functions -- ---------------------------------- function "*" (Left : Natural; Right : Character) return String with Post => -- Lower bound of the returned string is 1 "*"'Result'First = 1 -- Length of the returned string and then "*"'Result'Length = Left -- All characters of the returned string are Right and then (for all C of "*"'Result => C = Right), Global => null; function "*" (Left : Natural; Right : String) return String with Pre => (if Right'Length /= 0 then Left <= Natural'Last / Right'Length), Post => -- Lower bound of the returned string is 1 "*"'Result'First = 1 -- Length of the returned string and then "*"'Result'Length = Left * Right'Length -- Content of the string is Right concatenated with itself Left times and then (for all J in 0 .. Left - 1 => "*"'Result (J * Right'Length + 1 .. (J + 1) * Right'Length) = Right), Global => null; -- These functions replicate a character or string a specified number of -- times. The first function returns a string whose length is Left and each -- of whose elements is Right. The second function returns a string whose -- length is Left * Right'Length and whose value is the null string if -- Left = 0 and otherwise is (Left - 1)*Right & Right with lower bound 1. end Ada.Strings.Fixed;
with TEXT_IO; use TEXT_IO; with TASK_CONTROL; use TASK_CONTROL; procedure AB is task A; task B; task C; task D; -- -- -- End of type declairations. -- -- -- task body A is begin delay(0.01); loop PUT("A"); NEW_LINE; end loop; end A; task body B is begin delay(0.01); loop PUT(" B"); NEW_LINE; end loop; end B; task body C is begin delay(0.01); loop PUT(" C"); NEW_LINE; end loop; end C; task body D is begin delay(0.01); loop PUT(" D"); NEW_LINE; end loop; end D; -- The tasks become active as soon as the procedure under which -- their scope falls becomes active. (i.e. when procedure HW -- becomes active then it's tasks are started. begin -- AB task_control.pre_emption_on; task_control.set_time_slice(0.001); end AB;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ U T I L -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-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. -- -- -- ------------------------------------------------------------------------------ -- Package containing utility procedures used throughout the expander with Exp_Tss; use Exp_Tss; with Rtsfind; use Rtsfind; with Sinfo; use Sinfo; with Types; use Types; package Exp_Util is -- An enumeration type used to capture all the possible interface -- kinds and their hierarchical relation. These values are used in -- Find_Implemented_Interface and Implements_Interface. type Interface_Kind is ( Any_Interface, -- Any interface Any_Limited_Interface, -- Only limited interfaces Any_Synchronized_Interface, -- Only synchronized interfaces Iface, -- Individual kinds Limited_Interface, Protected_Interface, Synchronized_Interface, Task_Interface); ----------------------------------------------- -- Handling of Actions Associated with Nodes -- ----------------------------------------------- -- The evaluation of certain expression nodes involves the elaboration -- of associated types and other declarations, and the execution of -- statement sequences. Expansion routines generating such actions must -- find an appropriate place in the tree to hang the actions so that -- they will be evaluated at the appropriate point. -- Some cases are simple: -- For an expression occurring in a simple statement that is in a list -- of statements, the actions are simply inserted into the list before -- the associated statement. -- For an expression occurring in a declaration (declarations always -- appear in lists), the actions are similarly inserted into the list -- just before the associated declaration. -- The following special cases arise: -- For actions associated with the right operand of a short circuit -- form, the actions are first stored in the short circuit form node -- in the Actions field. The expansion of these forms subsequently -- expands the short circuit forms into if statements which can then -- be moved as described above. -- For actions appearing in the Condition expression of a while loop, -- or an elsif clause, the actions are similarly temporarily stored in -- in the node (N_Elsif_Part or N_Iteration_Scheme) associated with -- the expression using the Condition_Actions field. Subsequently, the -- expansion of these nodes rewrites the control structures involved to -- reposition the actions in normal statement sequence. -- For actions appearing in the then or else expression of a conditional -- expression, these actions are similarly placed in the node, using the -- Then_Actions or Else_Actions field as appropriate. Once again the -- expansion of the N_Conditional_Expression node rewrites the node so -- that the actions can be normally positioned. -- Basically what we do is to climb up to the tree looking for the -- proper insertion point, as described by one of the above cases, -- and then insert the appropriate action or actions. -- Note if more than one insert call is made specifying the same -- Assoc_Node, then the actions are elaborated in the order of the -- calls, and this guarantee is preserved for the special cases above. procedure Insert_Action (Assoc_Node : Node_Id; Ins_Action : Node_Id); -- Insert the action Ins_Action at the appropriate point as described -- above. The action is analyzed using the default checks after it is -- inserted. Assoc_Node is the node with which the action is associated. procedure Insert_Action (Assoc_Node : Node_Id; Ins_Action : Node_Id; Suppress : Check_Id); -- Insert the action Ins_Action at the appropriate point as described -- above. The action is analyzed using the default checks as modified -- by the given Suppress argument after it is inserted. Assoc_Node is -- the node with which the action is associated. procedure Insert_Actions (Assoc_Node : Node_Id; Ins_Actions : List_Id); -- Insert the list of action Ins_Actions at the appropriate point as -- described above. The actions are analyzed using the default checks -- after they are inserted. Assoc_Node is the node with which the actions -- are associated. Ins_Actions may be No_List, in which case the call has -- no effect. procedure Insert_Actions (Assoc_Node : Node_Id; Ins_Actions : List_Id; Suppress : Check_Id); -- Insert the list of action Ins_Actions at the appropriate point as -- described above. The actions are analyzed using the default checks -- as modified by the given Suppress argument after they are inserted. -- Assoc_Node is the node with which the actions are associated. -- Ins_Actions may be No_List, in which case the call has no effect. procedure Insert_Actions_After (Assoc_Node : Node_Id; Ins_Actions : List_Id); -- Assoc_Node must be a node in a list. Same as Insert_Actions but -- actions will be inserted after N in a manner that is compatible with -- the transient scope mechanism. This procedure must be used instead -- of Insert_List_After if Assoc_Node may be in a transient scope. -- -- Implementation limitation: Assoc_Node must be a statement. We can -- generalize to expressions if there is a need but this is tricky to -- implement because of short-circuits (among other things).??? procedure Insert_Library_Level_Action (N : Node_Id); -- This procedure inserts and analyzes the node N as an action at the -- library level for the current unit (i.e. it is attached to the -- Actions field of the N_Compilation_Aux node for the main unit). procedure Insert_Library_Level_Actions (L : List_Id); -- Similar, but inserts a list of actions ----------------------- -- Other Subprograms -- ----------------------- procedure Adjust_Condition (N : Node_Id); -- The node N is an expression whose root-type is Boolean, and which -- represents a boolean value used as a condition (i.e. a True/False -- value). This routine handles the case of C and Fortran convention -- boolean types, which have zero/non-zero semantics rather than the normal -- 0/1 semantics, and also the case of an enumeration rep clause that -- specifies a non-standard representation. On return, node N always has -- the type Standard.Boolean, with a value that is a standard Boolean -- values of 0/1 for False/True. This procedure is used in two situations. -- First, the processing for a condition field always calls -- Adjust_Condition, so that the boolean value presented to the backend is -- a standard value. Second, for the code for boolean operations such as -- AND, Adjust_Condition is called on both operands, and then the operation -- is done in the domain of Standard_Boolean, then Adjust_Result_Type is -- called on the result to possibly reset the original type. This procedure -- also takes care of validity checking if Validity_Checks = Tests. procedure Adjust_Result_Type (N : Node_Id; T : Entity_Id); -- The processing of boolean operations like AND uses the procedure -- Adjust_Condition so that it can operate on Standard.Boolean, which is -- the only boolean type on which the backend needs to be able to implement -- such operators. This means that the result is also of type -- Standard.Boolean. In general the type must be reset back to the original -- type to get proper semantics, and that is the purpose of this procedure. -- N is the node (of type Standard.Boolean), and T is the desired type. As -- an optimization, this procedure leaves the type as Standard.Boolean in -- contexts where this is permissible (in particular for Condition fields, -- and for operands of other logical operations higher up the tree). The -- call to this procedure is completely ignored if the argument N is not of -- type Boolean. procedure Append_Freeze_Action (T : Entity_Id; N : Node_Id); -- Add a new freeze action for the given type. The freeze action is -- attached to the freeze node for the type. Actions will be elaborated in -- the order in which they are added. Note that the added node is not -- analyzed. The analyze call is found in Sem_Ch13.Expand_N_Freeze_Entity. procedure Append_Freeze_Actions (T : Entity_Id; L : List_Id); -- Adds the given list of freeze actions (declarations or statements) for -- the given type. The freeze actions are attached to the freeze node for -- the type. Actions will be elaborated in the order in which they are -- added, and the actions within the list will be elaborated in list order. -- Note that the added nodes are not analyzed. The analyze call is found in -- Sem_Ch13.Expand_N_Freeze_Entity. function Build_Runtime_Call (Loc : Source_Ptr; RE : RE_Id) return Node_Id; -- Build an N_Procedure_Call_Statement calling the given runtime entity. -- The call has no parameters. The first argument provides the location -- information for the tree and for error messages. The call node is not -- analyzed on return, the caller is responsible for analyzing it. function Build_Task_Image_Decls (Loc : Source_Ptr; Id_Ref : Node_Id; A_Type : Entity_Id) return List_Id; -- Build declaration for a variable that holds an identifying string to be -- used as a task name. Id_Ref is an identifier if the task is a variable, -- and a selected or indexed component if the task is component of an -- object. If it is an indexed component, A_Type is the corresponding array -- type. Its index types are used to build the string as an image of the -- index values. For composite types, the result includes two declarations: -- one for a generated function that computes the image without using -- concatenation, and one for the variable that holds the result. function Component_May_Be_Bit_Aligned (Comp : Entity_Id) return Boolean; -- This function is in charge of detecting record components that may cause -- trouble in the back end if an attempt is made to assign the component. -- The back end can handle such assignments with no problem if the -- components involved are small (64-bits or less) records or scalar items -- (including bit-packed arrays represented with modular types) or are both -- aligned on a byte boundary (starting on a byte boundary, and occupying -- an integral number of bytes). -- -- However, problems arise for records larger than 64 bits, or for arrays -- (other than bit-packed arrays represented with a modular type) if the -- component starts on a non-byte boundary, or does not occupy an integral -- number of bytes (i.e. there are some bits possibly shared with fields at -- the start or beginning of the component). The back end cannot handle -- loading and storing such components in a single operation. -- -- This function is used to detect the troublesome situation. it is -- conservative in the sense that it produces True unless it knows for sure -- that the component is safe (as outlined in the first paragraph above). -- The code generation for record and array assignment checks for trouble -- using this function, and if so the assignment is generated -- component-wise, which the back end is required to handle correctly. -- -- Note that in GNAT 3, the back end will reject such components anyway, so -- the hard work in checking for this case is wasted in GNAT 3, but it's -- harmless, so it is easier to do it in all cases, rather than -- conditionalize it in GNAT 5 or beyond. procedure Convert_To_Actual_Subtype (Exp : Node_Id); -- The Etype of an expression is the nominal type of the expression, not -- the actual subtype. Often these are the same, but not always. For -- example, a reference to a formal of unconstrained type has the -- unconstrained type as its Etype, but the actual subtype is obtained by -- applying the actual bounds. This routine is given an expression, Exp, -- and (if necessary), replaces it using Rewrite, with a conversion to the -- actual subtype, building the actual subtype if necessary. If the -- expression is already of the requested type, then it is unchanged. function Current_Sem_Unit_Declarations return List_Id; -- Return the a place where it is fine to insert declarations for the -- current semantic unit. If the unit is a package body, return the -- visible declarations of the corresponding spec. For RCI stubs, this -- is necessary because the point at which they are generated may not -- be the earliest point at which they are used. function Duplicate_Subexpr (Exp : Node_Id; Name_Req : Boolean := False) return Node_Id; -- Given the node for a subexpression, this function makes a logical copy -- of the subexpression, and returns it. This is intended for use when the -- expansion of an expression needs to repeat part of it. For example, -- replacing a**2 by a*a requires two references to a which may be a -- complex subexpression. Duplicate_Subexpr guarantees not to duplicate -- side effects. If necessary, it generates actions to save the expression -- value in a temporary, inserting these actions into the tree using -- Insert_Actions with Exp as the insertion location. The original -- expression and the returned result then become references to this saved -- value. Exp must be analyzed on entry. On return, Exp is analyzed, but -- the caller is responsible for analyzing the returned copy after it is -- attached to the tree. The Name_Req flag is set to ensure that the result -- is suitable for use in a context requiring name (e.g. the prefix of an -- attribute reference). -- -- Note that if there are any run time checks in Exp, these same checks -- will be duplicated in the returned duplicated expression. The two -- following functions allow this behavior to be modified. function Duplicate_Subexpr_No_Checks (Exp : Node_Id; Name_Req : Boolean := False) return Node_Id; -- Identical in effect to Duplicate_Subexpr, except that Remove_Checks -- is called on the result, so that the duplicated expression does not -- include checks. This is appropriate for use when Exp, the original -- expression is unconditionally elaborated before the duplicated -- expression, so that there is no need to repeat any checks. function Duplicate_Subexpr_Move_Checks (Exp : Node_Id; Name_Req : Boolean := False) return Node_Id; -- Identical in effect to Duplicate_Subexpr, except that Remove_Checks is -- called on Exp after the duplication is complete, so that the original -- expression does not include checks. In this case the result returned -- (the duplicated expression) will retain the original checks. This is -- appropriate for use when the duplicated expression is sure to be -- elaborated before the original expression Exp, so that there is no need -- to repeat the checks. procedure Ensure_Defined (Typ : Entity_Id; N : Node_Id); -- This procedure ensures that type referenced by Typ is defined. For the -- case of a type other than an Itype, nothing needs to be done, since -- all such types have declaration nodes. For Itypes, an N_Itype_Reference -- node is generated and inserted at the given node N. This is typically -- used to ensure that an Itype is properly defined outside a conditional -- construct when it is referenced in more than one branch. procedure Evolve_And_Then (Cond : in out Node_Id; Cond1 : Node_Id); -- Rewrites Cond with the expression: Cond and then Cond1. If Cond is -- Empty, then simply returns Cond1 (this allows the use of Empty to -- initialize a series of checks evolved by this routine, with a final -- result of Empty indicating that no checks were required). The Sloc field -- of the constructed N_And_Then node is copied from Cond1. procedure Evolve_Or_Else (Cond : in out Node_Id; Cond1 : Node_Id); -- Rewrites Cond with the expression: Cond or else Cond1. If Cond is Empty, -- then simply returns Cond1 (this allows the use of Empty to initialize a -- series of checks evolved by this routine, with a final result of Empty -- indicating that no checks were required). The Sloc field of the -- constructed N_Or_Else node is copied from Cond1. procedure Expand_Subtype_From_Expr (N : Node_Id; Unc_Type : Entity_Id; Subtype_Indic : Node_Id; Exp : Node_Id); -- Build a constrained subtype from the initial value in object -- declarations and/or allocations when the type is indefinite (including -- class-wide). function Find_Interface (T : Entity_Id; Comp : Entity_Id) return Entity_Id; -- Ada 2005 (AI-251): Given a tagged type and one of its components -- associated with the secondary dispatch table of an abstract interface -- type, return the associated abstract interface type. function Find_Interface_ADT (T : Entity_Id; Iface : Entity_Id) return Entity_Id; -- Ada 2005 (AI-251): Given a type T implementing the interface Iface, -- return the Access_Disp_Table value of the interface. function Find_Interface_Tag (T : Entity_Id; Iface : Entity_Id) return Entity_Id; -- Ada 2005 (AI-251): Given a type T implementing the interface Iface, -- return the record component containing the tag of Iface. function Find_Implemented_Interface (Typ : Entity_Id; Kind : Interface_Kind; Check_Parent : Boolean := False) return Entity_Id; -- Ada 2005 (AI-345): Find a designated kind of interface implemented by -- Typ or any parent subtype. Return the first encountered interface that -- correspond to the selected class. Return Empty if no such interface is -- found. Use Check_Parent to climb a potential derivation chain and -- examine the parent subtypes for any implementation. function Find_Prim_Op (T : Entity_Id; Name : Name_Id) return Entity_Id; -- Find the first primitive operation of type T whose name is 'Name'. -- This function allows the use of a primitive operation which is not -- directly visible. If T is a class wide type, then the reference is -- to an operation of the corresponding root type. function Find_Prim_Op (T : Entity_Id; Name : TSS_Name_Type) return Entity_Id; -- Find the first primitive operation of type T whose name has the form -- indicated by the name parameter (i.e. is a type support subprogram -- with the indicated suffix). This function allows use of a primitive -- operation which is not directly visible. If T is a class wide type, -- then the reference is to an operation of the corresponding root type. procedure Force_Evaluation (Exp : Node_Id; Name_Req : Boolean := False); -- Force the evaluation of the expression right away. Similar behavior -- to Remove_Side_Effects when Variable_Ref is set to TRUE. That is to -- say, it removes the side-effects and capture the values of the -- variables. Remove_Side_Effects guarantees that multiple evaluations -- of the same expression won't generate multiple side effects, whereas -- Force_Evaluation further guarantees that all evaluations will yield -- the same result. procedure Generate_Poll_Call (N : Node_Id); -- If polling is active, then a call to the Poll routine is built, -- and then inserted before the given node N and analyzed. procedure Get_Current_Value_Condition (Var : Node_Id; Op : out Node_Kind; Val : out Node_Id); -- This routine processes the Current_Value field of the variable Var. If -- the Current_Value field is null or if it represents a known value, then -- on return Cond is set to N_Empty, and Val is set to Empty. -- -- The other case is when Current_Value points to an N_If_Statement or an -- N_Elsif_Part (while statement). Such a setting only occurs if the -- condition of an IF or ELSIF is of the form X op Y, where is the variable -- in question, Y is a compile-time known value, and op is one of the six -- possible relational operators. -- -- In this case, Get_Current_Condition digs out the condition, and then -- checks if the condition is known false, known true, or not known at all. -- In the first two cases, Get_Current_Condition will return with Op set to -- the appropriate conditional operator (inverted if the condition is known -- false), and Val set to the constant value. If the condition is not -- known, then Cond and Val are set for the empty case (N_Empty and Empty). -- -- The check for whether the condition is true/false unknown depends -- on the case: -- -- For an IF, the condition is known true in the THEN part, known false -- in any ELSIF or ELSE part, and not known outside the IF statement in -- question. -- -- For an ELSIF, the condition is known true in the ELSIF part, known -- FALSE in any subsequent ELSIF, or ELSE part, and not known before the -- ELSIF, or after the end of the IF statement. -- -- The caller can use this result to determine the value (for the case of -- N_Op_Eq), or to determine the result of some other test in other cases -- (e.g. no access check required if N_Op_Ne Null). function Homonym_Number (Subp : Entity_Id) return Nat; -- Here subp is the entity for a subprogram. This routine returns the -- homonym number used to disambiguate overloaded subprograms in the same -- scope (the number is used as part of constructed names to make sure that -- they are unique). The number is the ordinal position on the Homonym -- chain, counting only entries in the curren scope. If an entity is not -- overloaded, the returned number will be one. function Implements_Interface (Typ : Entity_Id; Kind : Interface_Kind; Check_Parent : Boolean := False) return Boolean; -- Ada 2005 (AI-345): Determine whether Typ implements a designated kind -- of interface. Use Check_Parent to climb a potential derivation chain -- and examine the parent subtypes for any implementation. function Inside_Init_Proc return Boolean; -- Returns True if current scope is within an init proc function In_Unconditional_Context (Node : Node_Id) return Boolean; -- Node is the node for a statement or a component of a statement. This -- function deteermines if the statement appears in a context that is -- unconditionally executed, i.e. it is not within a loop or a conditional -- or a case statement etc. function Is_All_Null_Statements (L : List_Id) return Boolean; -- Return True if all the items of the list are N_Null_Statement nodes. -- False otherwise. True for an empty list. It is an error to call this -- routine with No_List as the argument. function Is_Predefined_Dispatching_Operation (E : Entity_Id) return Boolean; -- Ada 2005 (AI-251): Determines if E is a predefined primitive operation. function Is_Ref_To_Bit_Packed_Array (N : Node_Id) return Boolean; -- Determine whether the node P is a reference to a bit packed array, i.e. -- whether the designated object is a component of a bit packed array, or a -- subcomponent of such a component. If so, then all subscripts in P are -- evaluated with a call to Force_Evaluation, and True is returned. -- Otherwise False is returned, and P is not affected. function Is_Ref_To_Bit_Packed_Slice (N : Node_Id) return Boolean; -- Determine whether the node P is a reference to a bit packed slice, i.e. -- whether the designated object is bit packed slice or a component of a -- bit packed slice. Return True if so. function Is_Possibly_Unaligned_Slice (N : Node_Id) return Boolean; -- Determine whether the node P is a slice of an array where the slice -- result may cause alignment problems because it has an alignment that -- is not compatible with the type. Return True if so. function Is_Possibly_Unaligned_Object (N : Node_Id) return Boolean; -- Node N is an object reference. This function returns True if it is -- possible that the object may not be aligned according to the normal -- default alignment requirement for its type (e.g. if it appears in a -- packed record, or as part of a component that has a component clause. function Is_Renamed_Object (N : Node_Id) return Boolean; -- Returns True if the node N is a renamed object. An expression is -- considered to be a renamed object if either it is the Name of an object -- renaming declaration, or is the prefix of a name which is a renamed -- object. For example, in: -- -- x : r renames a (1 .. 2) (1); -- -- We consider that a (1 .. 2) is a renamed object since it is the prefix -- of the name in the renaming declaration. function Is_Untagged_Derivation (T : Entity_Id) return Boolean; -- Returns true if type T is not tagged and is a derived type, -- or is a private type whose completion is such a type. procedure Kill_Dead_Code (N : Node_Id); -- N represents a node for a section of code that is known to be dead. The -- node is deleted, and any exception handler references and warning -- messages relating to this code are removed. procedure Kill_Dead_Code (L : List_Id); -- Like the above procedure, but applies to every element in the given -- list. Each of the entries is removed from the list before killing it. function Known_Non_Negative (Opnd : Node_Id) return Boolean; -- Given a node for a subexpression, determines if it represents a value -- that cannot possibly be negative, and if so returns True. A value of -- False means that it is not known if the value is positive or negative. function Known_Non_Null (N : Node_Id) return Boolean; -- Given a node N for a subexpression of an access type, determines if -- this subexpression yields a value that is known at compile time to -- be non-null and returns True if so. Returns False otherwise. It is -- an error to call this function if N is not of an access type. function Known_Null (N : Node_Id) return Boolean; -- Given a node N for a subexpression of an access type, determines if this -- subexpression yields a value that is known at compile time to be null -- and returns True if so. Returns False otherwise. It is an error to call -- this function if N is not of an access type. function Make_Subtype_From_Expr (E : Node_Id; Unc_Typ : Entity_Id) return Node_Id; -- Returns a subtype indication corresponding to the actual type of an -- expression E. Unc_Typ is an unconstrained array or record, or -- a classwide type. function May_Generate_Large_Temp (Typ : Entity_Id) return Boolean; -- Determines if the given type, Typ, may require a large temporary of the -- kind that causes back-end trouble if stack checking is enabled. The -- result is True only the size of the type is known at compile time and -- large, where large is defined heuristically by the body of this routine. -- The purpose of this routine is to help avoid generating troublesome -- temporaries that interfere with stack checking mechanism. Note that the -- caller has to check whether stack checking is actually enabled in order -- to guide the expansion (typically of a function call). function OK_To_Do_Constant_Replacement (E : Entity_Id) return Boolean; -- This function is used when testing whether or not to replace a reference -- to entity E by a known constant value. Such replacement must be done -- only in a scope known to be safe for such replacements. In particular, -- if we are within a subprogram and the entity E is declared outside the -- subprogram then we cannot do the replacement, since we do not attempt to -- trace subprogram call flow. It is also unsafe to replace statically -- allocated values (since they can be modified outside the scope), and we -- also inhibit replacement of Volatile or aliased objects since their -- address might be captured in a way we do not detect. A value of True is -- returned only if the replacement is safe. procedure Remove_Side_Effects (Exp : Node_Id; Name_Req : Boolean := False; Variable_Ref : Boolean := False); -- Given the node for a subexpression, this function replaces the node if -- necessary by an equivalent subexpression that is guaranteed to be side -- effect free. This is done by extracting any actions that could cause -- side effects, and inserting them using Insert_Actions into the tree to -- which Exp is attached. Exp must be analyzed and resolved before the call -- and is analyzed and resolved on return. The Name_Req may only be set to -- True if Exp has the form of a name, and the effect is to guarantee that -- any replacement maintains the form of name. If Variable_Ref is set to -- TRUE, a variable is considered as side effect (used in implementing -- Force_Evaluation). Note: after call to Remove_Side_Effects, it is safe -- to call New_Copy_Tree to obtain a copy of the resulting expression. function Represented_As_Scalar (T : Entity_Id) return Boolean; -- Returns True iff the implementation of this type in code generation -- terms is scalar. This is true for scalars in the Ada sense, and for -- packed arrays which are represented by a scalar (modular) type. function Safe_Unchecked_Type_Conversion (Exp : Node_Id) return Boolean; -- Given the node for an N_Unchecked_Type_Conversion, return True if this -- is an unchecked conversion that Gigi can handle directly. Otherwise -- return False if it is one for which the front end must provide a -- temporary. Note that the node need not be analyzed, and thus the Etype -- field may not be set, but in that case it must be the case that the -- Subtype_Mark field of the node is set/analyzed. procedure Set_Elaboration_Flag (N : Node_Id; Spec_Id : Entity_Id); -- N is the node for a subprogram or generic body, and Spec_Id is the -- entity for the corresponding spec. If an elaboration entity is defined, -- then this procedure generates an assignment statement to set it True, -- immediately after the body is elaborated. However, no assignment is -- generated in the case of library level procedures, since the setting of -- the flag in this case is generated in the binder. We do that so that we -- can detect cases where this is the only elaboration action that is -- required. procedure Set_Renamed_Subprogram (N : Node_Id; E : Entity_Id); -- N is an node which is an entity name that represents the name of a -- renamed subprogram. The node is rewritten to be an identifier that -- refers directly to the renamed subprogram, given by entity E. function Target_Has_Fixed_Ops (Left_Typ : Entity_Id; Right_Typ : Entity_Id; Result_Typ : Entity_Id) return Boolean; -- Returns True if and only if the target machine has direct support -- for fixed-by-fixed multiplications and divisions for the given -- operand and result types. This is called in package Exp_Fixd to -- determine whether to expand such operations. function Type_May_Have_Bit_Aligned_Components (Typ : Entity_Id) return Boolean; -- Determines if Typ is a composite type that has within it (looking down -- recursively at any subcomponents), a record type which has component -- that may be bit aligned (see Possible_Bit_Aligned_Component). The result -- is conservative, in that a result of False is decisive. A result of True -- means that such a component may or may not be present. procedure Wrap_Cleanup_Procedure (N : Node_Id); -- Given an N_Subprogram_Body node, this procedure adds an Abort_Defer call -- at the start of the statement sequence, and an Abort_Undefer call at the -- end of the statement sequence. All cleanup routines (i.e. those that are -- called from "at end" handlers) must defer abort on entry and undefer -- abort on exit. Note that it is assumed that the code for the procedure -- does not contain any return statements which would allow the flow of -- control to escape doing the undefer call. private pragma Inline (Force_Evaluation); pragma Inline (Duplicate_Subexpr); end Exp_Util;
with Lv.Area; with Lv.Style; with Lv.Color; use Lv.Color; package Lv.Objx is type Obj_T is new System.Address; No_Obj : constant Obj_T := Obj_T (System.Null_Address); Anim_In : constant := 16#00#; Anim_Out : constant := 16#80#; Anim_Dir_Mask : constant := 16#80#; Lv_Max_Ancestor_Num : constant := 8; Res_Inv : constant := 0; Res_Ok : constant := 1; type Align_T is (Align_Center, Align_In_Top_Left, Align_In_Top_Mid, Align_In_Top_Right, Align_In_Bottom_Left, Align_In_Bottom_Mid, Align_In_Bottom_Right, Align_In_Left_Mid, Align_In_Right_Mid, Align_Out_Top_Left, Align_Out_Top_Mid, Align_Out_Top_Right, Align_Out_Bottom_Left, Align_Out_Bottom_Mid, Align_Out_Bottom_Right, Align_Out_Left_Top, Align_Out_Left_Mid, Align_Out_Left_Bottom, Align_Out_Right_Top, Align_Out_Right_Mid, Align_Out_Right_Bottom) with Size => 8; for Align_T use (Align_Center => 0, Align_In_Top_Left => 1, Align_In_Top_Mid => 2, Align_In_Top_Right => 3, Align_In_Bottom_Left => 4, Align_In_Bottom_Mid => 5, Align_In_Bottom_Right => 6, Align_In_Left_Mid => 7, Align_In_Right_Mid => 8, Align_Out_Top_Left => 9, Align_Out_Top_Mid => 10, Align_Out_Top_Right => 11, Align_Out_Bottom_Left => 12, Align_Out_Bottom_Mid => 13, Align_Out_Bottom_Right => 14, Align_Out_Left_Top => 15, Align_Out_Left_Mid => 16, Align_Out_Left_Bottom => 17, Align_Out_Right_Top => 18, Align_Out_Right_Mid => 19, Align_Out_Right_Bottom => 20); subtype Design_Mode_T is Uint8_T; type Design_Func_T is access function (Arg1 : System.Address; Arg2 : access constant Lv.Area.Area_T; Arg3 : Design_Mode_T) return U_Bool; pragma Convention (C, Design_Func_T); subtype Res_T is Uint8_T; subtype Signal_T is Uint8_T; type Signal_Func_T is access function (Arg1 : System.Address; Arg2 : Signal_T; Arg3 : System.Address) return Res_T; pragma Convention (C, Signal_Func_T); type Action_Func_T is access function (Arg1 : Obj_T) return Res_T; pragma Convention (C, Action_Func_T); subtype Protect_T is Uint8_T; type Obj_Type_T_C_Type_Array is array (0 .. 7) of C_String_Ptr; type Obj_Type_T is record C_Type : Obj_Type_T_C_Type_Array; end record; pragma Convention (C_Pass_By_Copy, Obj_Type_T); subtype Anim_Builtin_T is Uint8_T; Anim_None : constant Anim_Builtin_T := 0; Anim_Float_Top : constant Anim_Builtin_T := 1; Anim_Float_Left : constant Anim_Builtin_T := 2; Anim_Float_Bottom : constant Anim_Builtin_T := 3; Anim_Float_Right : constant Anim_Builtin_T := 4; Anim_Grow_H : constant Anim_Builtin_T := 5; Anim_Grow_V : constant Anim_Builtin_T := 6; ----------------------- -- Create and delete -- ----------------------- -- Create a basic object -- @param parent pointer to a parent object. -- If NULL then a screen will be created -- @param copy pointer to a base object, if not NULL then the new object will be copied from it -- @return pointer to the new object function Create (Parent : Obj_T; Copy : Obj_T) return Obj_T; -- Delete 'obj' and all of its children -- @param self pointer to an object to delete -- @return LV_RES_INV because the object is deleted function Del (Self : Obj_T) return Res_T; -- Delete all children of an object -- @param self pointer to an object procedure Clean (Self : Obj_T); -- Mark the object as invalid therefore its current position will be redrawn by 'lv_refr_task' -- @param self pointer to an object procedure Invalidate (Self : Obj_T); -- Load a new screen -- @param scr pointer to a screen procedure Scr_Load (Scr : Obj_T); ---------------------- -- Setter functions -- ---------------------- ------------------------- -- Parent/children set -- ------------------------- -- Set a new parent for an object. Its relative position will be the same. -- @param self pointer to an object. Can't be a screen. -- @param parent pointer to the new parent object. (Can't be NULL) procedure Set_Parent (Self : Obj_T; Parent : Obj_T); -------------------- -- Coordinate set -- -------------------- -- Set relative the position of an object (relative to the parent) -- @param self pointer to an object -- @param x new distance from the left side of the parent -- @param y new distance from the top of the parent procedure Set_Pos (Self : Obj_T; X : Lv.Area.Coord_T; Y : Lv.Area.Coord_T); -- Set the x coordinate of a object -- @param self pointer to an object -- @param x new distance from the left side from the parent procedure Set_X (Self : Obj_T; X : Lv.Area.Coord_T); -- Set the y coordinate of a object -- @param self pointer to an object -- @param y new distance from the top of the parent procedure Set_Y (Self : Obj_T; Y : Lv.Area.Coord_T); -- Set the size of an object -- @param self pointer to an object -- @param w new width -- @param h new height procedure Set_Size (Self : Obj_T; X : Lv.Area.Coord_T; Y : Lv.Area.Coord_T); -- Set the width of an object -- @param self pointer to an object -- @param w new width procedure Set_Width (Self : Obj_T; W : Lv.Area.Coord_T); -- Set the height of an object -- @param self pointer to an object -- @param h new height procedure Set_Height (Self : Obj_T; H : Lv.Area.Coord_T); -- Align an object to an other object. -- @param self pointer to an object to align -- @param base pointer to an object (if NULL the parent is used). 'obj' will be aligned to it. -- @param align type of alignment (see 'lv_align_t' enum) -- @param x_mod x coordinate shift after alignment -- @param y_mod y coordinate shift after alignment procedure Align (Self : Obj_T; Base : Obj_T; Align : Align_T; X_Mod : Lv.Area.Coord_T; Y_Mod : Lv.Area.Coord_T); -------------------- -- Appearance set -- -------------------- -- Set a new style for an object -- @param self pointer to an object -- @param style_p pointer to the new style procedure Set_Style (Self : Obj_T; Style_P : access Lv.Style.Style); -- Notify an object about its style is modified -- @param obj pointer to an object procedure Refresh_Style (Self : Obj_T); -- Notify all object if a style is modified -- @param style pointer to a style. Only the objects with this style will be notified -- (NULL to notify all objects) procedure Report_Style_Mod (Style_P : access Lv.Style.Style); ------------------- -- Attribute set -- ------------------- -- Hide an object. It won't be visible and clickable. -- @param self pointer to an object -- @param en true: hide the object procedure Set_Hidden (Self : Obj_T; En: U_Bool); -- Enable or disable the clicking of an object -- @param self pointer to an object -- @param en true: make the object clickable procedure Set_Click (Self : Obj_T; En : U_Bool); -- Enable to bring this object to the foreground if it -- or any of its children is clicked -- @param self pointer to an object -- @param en true: enable the auto top feature procedure Set_Top (Self : Obj_T; En : U_Bool); -- Enable the dragging of an object -- @param self pointer to an object -- @param en true: make the object dragable procedure Set_Drag (Self : Obj_T; En : U_Bool); -- Enable the throwing of an object after is is dragged -- @param self pointer to an object -- @param en true: enable the drag throw procedure Set_Drag_Throw (Self : Obj_T; En : U_Bool); -- Enable to use parent for drag related operations. -- If trying to drag the object the parent will be moved instead -- @param self pointer to an object -- @param en true: enable the 'drag parent' for the object procedure Set_Drag_Parent (Self : Obj_T; En : U_Bool); -- Set editable parameter Used by groups and keyboard/encoder control. -- Editable object has something inside to choose (the elements of a list) -- @param self pointer to an object -- @param en true: enable editing procedure Set_Editable (Self : Obj_T; En : U_Bool); -- Set the opa scale enable parameter (required to set opa_scale with `lv_obj_set_opa_scale()`) -- @param self pointer to an object -- @param en true: opa scaling is enabled for this object and all children; false: no opa scaling procedure Set_Opa_Scale_Enable (Self : Obj_T; En : U_Bool); -- Set the opa scale of an object -- @param self pointer to an object -- @param opa_scale a factor to scale down opacity [0..255] procedure Set_Opa_Scale (Self : Obj_T; Opa_Scale : Lv.Color.Opa_T); -- Set a bit or bits in the protect filed -- @param self pointer to an object -- @param prot 'OR'-ed values from `lv_protect_t` procedure Set_Protect (Self : Obj_T; Prot : Protect_T); -- Clear a bit or bits in the protect filed -- @param self pointer to an object -- @param prot 'OR'-ed values from `lv_protect_t` procedure Clear_Protect (Self : Obj_T; Prot : Protect_T); -- Set the signal function of an object. -- Always call the previous signal function in the new. -- @param self pointer to an object -- @param fp the new signal function procedure Set_Signal_Func (Self : Obj_T; Fp : Signal_Func_T); -- Set a new design function for an object -- @param self pointer to an object -- @param fp the new design function procedure Set_Design_Func (Self : Obj_T; Fp : Design_Func_T); --------------- -- Other set -- --------------- -- Allocate a new ext. data for an object -- @param self pointer to an object -- @param ext_size the size of the new ext. data -- @return pointer to the allocated ext function Allocate_Ext_Attr (Self : Obj_T; Ext_Size : Uint16_T) return System.Address; -- Send a 'LV_SIGNAL_REFR_EXT_SIZE' signal to the object -- @param self pointer to an object procedure Refresh_Ext_Size (Self : Obj_T); -- Set an application specific number for an object. -- It can help to identify objects in the application. -- @param self pointer to an object -- @param free_num the new free number procedure Set_Free_Num (Self : Obj_T; Free_Num : Uint32_T); -- Set an application specific pointer for an object. -- It can help to identify objects in the application. -- @param self pointer to an object -- @param free_p the new free pinter procedure Set_Free_Ptr (Self : Obj_T; Free_P : System.Address); -- Animate an object -- @param self pointer to an object to animate -- @param type_p type of animation from 'lv_anim_builtin_t'. 'OR' it with ANIM_IN or ANIM_OUT -- @param time time of animation in milliseconds -- @param delay_p delay before the animation in milliseconds -- @param cb a function to call when the animation is ready procedure Animate (Self : Obj_T; Type_P : Anim_Builtin_T; Time : Uint16_T; Delay_P : Uint16_T; Cb : access procedure (Arg1 : Obj_T)); ---------------------- -- Getter functions -- ---------------------- ---------------- -- Screen get -- ---------------- -- Return with a pointer to the active screen -- @return pointer to the active screen object (loaded by 'lv_scr_load()') function Scr_Act return Obj_T; -- Return with the top layer. (Same on every screen and it is above the normal screen layer) -- @return pointer to the top layer object (transparent screen sized lv_obj) function Layer_Top return Obj_T; -- Return with the system layer. (Same on every screen and it is above the all other layers) -- It is used for example by the cursor -- @return pointer to the system layer object (transparent screen sized lv_obj) function Layer_Sys return Obj_T; -- Return with the screen of an object -- @param obj pointer to an object -- @return pointer to a screen function Screen (Arg1 : Obj_T) return Obj_T; ------------------------- -- Parent/children get -- ------------------------- -- Returns with the parent of an object -- @param self pointer to an object -- @return pointer to the parent of 'obj' function Parent (Self : Obj_T) return Obj_T; -- Iterate through the children of an object (start from the "youngest, lastly created") -- @param self pointer to an object -- @param child NULL at first call to get the next children -- and the previous return value later -- @return the child after 'act_child' or NULL if no more child function Child (Self : Obj_T; Child : Obj_T) return Obj_T; -- Iterate through the children of an object (start from the "oldest", firstly created) -- @param self pointer to an object -- @param child NULL at first call to get the next children -- and the previous return value later -- @return the child after 'act_child' or NULL if no more child function Child_Back (Self : Obj_T; Child : Obj_T) return Obj_T; -- Count the children of an object (only children directly on 'obj') -- @param self pointer to an object -- @return children number of 'obj' function Count_Children (Self : Obj_T) return Uint16_T; -------------------- -- Coordinate get -- -------------------- -- Copy the coordinates of an object to an area -- @param self pointer to an object -- @param cords_p pointer to an area to store the coordinates procedure Coords (Self : Obj_T; Cords_P : access Lv.Area.Area_T); -- Get the x coordinate of object -- @param self pointer to an object -- @return distance of 'obj' from the left side of its parent function X (Self : Obj_T) return Lv.Area.Coord_T; -- Get the y coordinate of object -- @param self pointer to an object -- @return distance of 'obj' from the top of its parent function Y (Self : Obj_T) return Lv.Area.Coord_T; -- Get the width of an object -- @param self pointer to an object -- @return the width function Width (Self : Obj_T) return Lv.Area.Coord_T; -- Get the height of an object -- @param self pointer to an object -- @return the height function Height (Self : Obj_T) return Lv.Area.Coord_T; -- Get the extended size attribute of an object -- @param self pointer to an object -- @return the extended size attribute function Ext_Size (Self : Obj_T) return Lv.Area.Coord_T; -------------------- -- Appearance get -- -------------------- -- Get the style pointer of an object (if NULL get style of the parent) -- @param self pointer to an object -- @return pointer to a style function Style (Self : Obj_T) return Lv.Style.Style; ------------------- -- Attribute get -- ------------------- -- Get the hidden attribute of an object -- @param self pointer to an object -- @return true: the object is hidden function Hidden (Self : Obj_T) return U_Bool; -- Get the click enable attribute of an object -- @param self pointer to an object -- @return true: the object is clickable function Click (Self : Obj_T) return U_Bool; -- Get the top enable attribute of an object -- @param self pointer to an object -- @return true: the auto top feture is enabled function Top (Self : Obj_T) return U_Bool; -- Get the drag enable attribute of an object -- @param self pointer to an object -- @return true: the object is dragable function Drag (Self : Obj_T) return U_Bool; -- Get the drag thow enable attribute of an object -- @param self pointer to an object -- @return true: drag throw is enabled function Drag_Throw (Self : Obj_T) return U_Bool; -- Get the drag parent attribute of an object -- @param self pointer to an object -- @return true: drag parent is enabled function Drag_Parent (Self : Obj_T) return U_Bool; -- Get the opa scale parameter of an object -- @param self pointer to an object -- @return opa scale [0..255] function Opa_Scale (Self : Obj_T) return Lv.Color.Opa_T; -- Get the protect field of an object -- @param self pointer to an object -- @return protect field ('OR'ed values of `lv_protect_t`) function Protect (Self : Obj_T) return Uint8_T; -- Check at least one bit of a given protect bitfield is set -- @param self pointer to an object -- @param prot protect bits to test ('OR'ed values of `lv_protect_t`) -- @return false: none of the given bits are set, true: at least one bit is set function Is_Protected (Self : Obj_T; Prot : Protect_T) return U_Bool; -- Get the signal function of an object -- @param self pointer to an object -- @return the signal function function Signal_Func (Self : Obj_T) return Signal_Func_T; -- Get the design function of an object -- @param self pointer to an object -- @return the design function function Design_Func (Self : Obj_T) return Design_Func_T; --------------- -- Other get -- --------------- -- Get the ext pointer -- @param self pointer to an object -- @return the ext pointer but not the dynamic version -- Use it as ext->data1, and NOT da(ext)->data1 function Ext_Attr (Self : Obj_T) return System.Address; -- Get object's and its ancestors type. Put their name in `type_buf` starting with the current type. -- E.g. buf.type[0]="lv_btn", buf.type[1]="lv_cont", buf.type[2]="lv_obj" -- @param self pointer to an object which type should be get -- @param buf pointer to an `lv_obj_type_t` buffer to store the types procedure Obj_Type (Self : Obj_T; Buf : access Obj_Type_T); -- Get the free number -- @param self pointer to an object -- @return the free number function Free_Num (Self : Obj_T) return Uint32_T; -- Get the free pointer -- @param self pointer to an object -- @return the free pointer function Free_Ptr (Self : Obj_T) return System.Address; -- Get the group of the object -- @param self pointer to an object -- @return the pointer to group of the object function Group (Self : Obj_T) return System.Address; -- Tell whether the ohe object is the focused object of a group or not. -- @param self pointer to an object -- @return true: the object is focused, false: the object is not focused or not in a group function Is_Focused (Self : Obj_T) return U_Bool; ------------- -- Imports -- ------------- pragma Import (C, Create, "lv_obj_create"); pragma Import (C, Del, "lv_obj_del"); pragma Import (C, Clean, "lv_obj_clean"); pragma Import (C, Invalidate, "lv_obj_invalidate"); pragma Import (C, Scr_Load, "lv_scr_load"); pragma Import (C, Set_Parent, "lv_obj_set_parent"); pragma Import (C, Set_Pos, "lv_obj_set_pos"); pragma Import (C, Set_X, "lv_obj_set_x"); pragma Import (C, Set_Y, "lv_obj_set_y"); pragma Import (C, Set_Size, "lv_obj_set_size"); pragma Import (C, Set_Width, "lv_obj_set_width"); pragma Import (C, Set_Height, "lv_obj_set_height"); pragma Import (C, Align, "lv_obj_align"); pragma Import (C, Set_Style, "lv_obj_set_style"); pragma Import (C, Refresh_Style, "lv_obj_refresh_style"); pragma Import (C, Report_Style_Mod, "lv_obj_report_style_mod"); pragma Import (C, Set_Hidden, "lv_obj_set_hidden"); pragma Import (C, Set_Click, "lv_obj_set_click"); pragma Import (C, Set_Top, "lv_obj_set_top"); pragma Import (C, Set_Drag, "lv_obj_set_drag"); pragma Import (C, Set_Drag_Throw, "lv_obj_set_drag_throw"); pragma Import (C, Set_Drag_Parent, "lv_obj_set_drag_parent"); pragma Import (C, Set_Editable, "lv_obj_set_editable"); pragma Import (C, Set_Opa_Scale_Enable, "lv_obj_set_opa_scale_enable"); pragma Import (C, Set_Opa_Scale, "lv_obj_set_opa_scale"); pragma Import (C, Set_Protect, "lv_obj_set_protect"); pragma Import (C, Clear_Protect, "lv_obj_clear_protect"); pragma Import (C, Set_Signal_Func, "lv_obj_set_signal_func"); pragma Import (C, Set_Design_Func, "lv_obj_set_design_func"); pragma Import (C, Allocate_Ext_Attr, "lv_obj_allocate_ext_attr"); pragma Import (C, Refresh_Ext_Size, "lv_obj_refresh_ext_size"); pragma Import (C, Set_Free_Num, "lv_obj_set_free_num"); pragma Import (C, Set_Free_Ptr, "lv_obj_set_free_ptr"); pragma Import (C, Animate, "lv_obj_animate"); pragma Import (C, Scr_Act, "lv_scr_act"); pragma Import (C, Layer_Top, "lv_layer_top"); pragma Import (C, Layer_Sys, "lv_layer_sys"); pragma Import (C, Screen, "lv_obj_get_screen"); pragma Import (C, Parent, "lv_obj_get_parent"); pragma Import (C, Child, "lv_obj_get_child"); pragma Import (C, Child_Back, "lv_obj_get_child_back"); pragma Import (C, Count_Children, "lv_obj_count_children"); pragma Import (C, Coords, "lv_obj_get_coords"); pragma Import (C, X, "lv_obj_get_x"); pragma Import (C, Y, "lv_obj_get_y"); pragma Import (C, Width, "lv_obj_get_width"); pragma Import (C, Height, "lv_obj_get_height"); pragma Import (C, Ext_Size, "lv_obj_get_ext_size"); pragma Import (C, Style, "lv_obj_get_style"); pragma Import (C, Hidden, "lv_obj_get_hidden"); pragma Import (C, Click, "lv_obj_get_click"); pragma Import (C, Top, "lv_obj_get_top"); pragma Import (C, Drag, "lv_obj_get_drag"); pragma Import (C, Drag_Throw, "lv_obj_get_drag_throw"); pragma Import (C, Drag_Parent, "lv_obj_get_drag_parent"); pragma Import (C, Opa_Scale, "lv_obj_get_opa_scale"); pragma Import (C, Protect, "lv_obj_get_protect"); pragma Import (C, Is_Protected, "lv_obj_is_protected"); pragma Import (C, Signal_Func, "lv_obj_get_signal_func"); pragma Import (C, Design_Func, "lv_obj_get_design_func"); pragma Import (C, Ext_Attr, "lv_obj_get_ext_attr"); pragma Import (C, Obj_Type, "lv_obj_get_type"); pragma Import (C, Free_Num, "lv_obj_get_free_num"); pragma Import (C, Free_Ptr, "lv_obj_get_free_ptr"); pragma Import (C, Group, "lv_obj_get_group"); pragma Import (C, Is_Focused, "lv_obj_is_focused"); end Lv.Objx;
with Ada.Unchecked_Conversion; with Ada.Unchecked_Deallocation; package body Ada.Containers.Access_Holders is use type Weak_Access_Holders.Data_Access; subtype Nonnull_Data_Access is not null Data_Access; function Upcast is new Unchecked_Conversion ( Nonnull_Data_Access, System.Reference_Counting.Container); function Downcast is new Unchecked_Conversion ( System.Reference_Counting.Container, Nonnull_Data_Access); type Data_Access_Access is access all Nonnull_Data_Access; type Container_Access is access all System.Reference_Counting.Container; function Upcast is new Unchecked_Conversion (Data_Access_Access, Container_Access); procedure Free_Data (X : in out System.Reference_Counting.Data_Access); procedure Free_Data (X : in out System.Reference_Counting.Data_Access) is procedure Unchecked_Free is new Unchecked_Deallocation (Data, Data_Access); Y : Data_Access := Downcast (X); begin Weak_Access_Holders.Clear_Weaks ( Y.Super, Null_Data.Super'Unrestricted_Access); Free (Y.Item); Unchecked_Free (Y); X := null; end Free_Data; -- implementation function Null_Holder return Holder is begin return (Finalization.Controlled with Data => Null_Data'Unrestricted_Access); end Null_Holder; overriding function "=" (Left, Right : Holder) return Boolean is begin return Left.Data = Right.Data; end "="; function To_Holder (Source : Name) return Holder is begin return Result : Holder do if Source /= Null_Data.Item then Result.Data := new Data'((1, null), Source); end if; end return; end To_Holder; function Is_Null (Container : Holder) return Boolean is begin return Container.Data = Null_Data'Unrestricted_Access; end Is_Null; procedure Clear (Container : in out Holder) is begin Finalize (Container); Container.Data := Null_Data'Unrestricted_Access; end Clear; function Element (Container : Holder'Class) return Name is begin return Constant_Reference (Holder (Container)); end Element; procedure Replace_Element (Target : in out Holder; Source : Name) is begin Clear (Target); if Source /= Null_Data.Item then Target.Data := new Data'((1, null), Source); end if; end Replace_Element; function Constant_Reference (Container : Holder) return Name is begin return Container.Data.Item; end Constant_Reference; procedure Assign (Target : in out Holder; Source : Holder) is begin System.Reference_Counting.Assign ( Target => Upcast (Target.Data'Unchecked_Access), Source => Upcast (Source.Data'Unrestricted_Access), Free => Free_Data'Access); end Assign; procedure Move (Target : in out Holder; Source : in out Holder) is begin System.Reference_Counting.Move ( Target => Upcast (Target.Data'Unchecked_Access), Source => Upcast (Source.Data'Unchecked_Access), Sentinel => Upcast (Null_Data'Unrestricted_Access), Free => Free_Data'Access); end Move; procedure Swap (I, J : in out Holder) is Temp : constant Data_Access := I.Data; begin I.Data := J.Data; J.Data := Temp; end Swap; overriding procedure Adjust (Object : in out Holder) is begin System.Reference_Counting.Adjust (Upcast (Object.Data'Unchecked_Access)); end Adjust; overriding procedure Finalize (Object : in out Holder) is begin System.Reference_Counting.Clear ( Target => Upcast (Object.Data'Unchecked_Access), Free => Free_Data'Access); end Finalize; package body Weak is function Downcast is new Unchecked_Conversion ( Weak_Access_Holders.Data_Access, Data_Access); overriding function "=" (Left, Right : Weak_Holder) return Boolean is begin return Left.Super.Data = Right.Super.Data; end "="; function To_Weak_Holder (Source : Holder) return Weak_Holder is begin return Result : Weak_Holder := (Finalization.Controlled with Super => ( Data => Source.Data.Super'Unchecked_Access, Previous => <>, Next => <>)) do Adjust (Result); end return; end To_Weak_Holder; function Null_Weak_Holder return Weak_Holder is begin return (Finalization.Controlled with others => <>); end Null_Weak_Holder; function To_Holder (Source : Weak_Holder) return Holder is begin return Result : Holder do if not Is_Null (Source) then Result.Data := Downcast (Source.Super.Data); Adjust (Result); end if; end return; end To_Holder; function Is_Null (Container : Weak_Holder) return Boolean is begin return Container.Super.Data = Null_Data.Super'Unrestricted_Access; end Is_Null; procedure Clear (Container : in out Weak_Holder) is begin Finalize (Container); Initialize (Container); end Clear; procedure Assign (Target : in out Weak_Holder; Source : Holder) is begin Clear (Target); Target.Super.Data := Source.Data.Super'Unchecked_Access; Adjust (Target); end Assign; procedure Assign (Target : in out Holder; Source : Weak_Holder) is begin Clear (Target); Target.Data := Downcast (Source.Super.Data); Adjust (Target); end Assign; overriding procedure Initialize (Object : in out Weak_Holder) is begin Object.Super.Data := Null_Data.Super'Unrestricted_Access; Object.Super.Previous := null; Object.Super.Next := null; end Initialize; overriding procedure Adjust (Object : in out Weak_Holder) is begin if not Is_Null (Object) then Weak_Access_Holders.Add_Weak (Object.Super'Unchecked_Access); end if; end Adjust; overriding procedure Finalize (Object : in out Weak_Holder) is begin if not Is_Null (Object) then Weak_Access_Holders.Remove_Weak (Object.Super'Unchecked_Access); end if; end Finalize; end Weak; end Ada.Containers.Access_Holders;
package freetype_c.Pointers is type FT_UShort_Pointer is access all FT_UShort; type FT_Int_Pointer is access all FT_Int; type FT_UInt_Pointer is access all FT_UInt; type FT_Long_Pointer is access all FT_Long; type FT_ULong_Pointer is access all FT_ULong; type FT_Fixed_Pointer is access all FT_Fixed; type FT_Pos_Pointer is access all FT_Pos; type FT_Error_Pointer is access all FT_Error; type FT_Encoding_Pointer is access all FT_Encoding; type FT_Int32_Pointer is access all FT_Int32; type FT_F26Dot6_Pointer is access all FT_F26Dot6; type FT_UInt32_Pointer is access all FT_UInt32; type FT_Render_Mode_Pointer is access all FT_Render_Mode; type FT_Outline_Pointer is access all FT_Outline; type FT_LibraryRec_Pointer is access all FT_LibraryRec; type FT_GlyphSlotRec_Pointer is access all FT_GlyphSlotRec; type FT_FaceRec_Pointer is access all FT_FaceRec; type FT_Kerning_Mode_Pointer is access all FT_Kerning_Mode; type FT_SizeRec_Pointer is access all FT_SizeRec; type FT_UShort_Pointer_array is array (C.Size_t range <>) of aliased FT_UShort_Pointer; type FT_Int_Pointer_array is array (C.Size_t range <>) of aliased FT_Int_Pointer; type FT_UInt_Pointer_array is array (C.Size_t range <>) of aliased FT_UInt_Pointer; type FT_Long_Pointer_array is array (C.Size_t range <>) of aliased FT_Long_Pointer; type FT_ULong_Pointer_array is array (C.Size_t range <>) of aliased FT_ULong_Pointer; type FT_Fixed_Pointer_array is array (C.Size_t range <>) of aliased FT_Fixed_Pointer; type FT_Pos_Pointer_array is array (C.Size_t range <>) of aliased FT_Pos_Pointer; type FT_Error_Pointer_array is array (C.Size_t range <>) of aliased FT_Error_Pointer; type FT_Encoding_Pointer_array is array (C.Size_t range <>) of aliased FT_Encoding_Pointer; type FT_F26Dot6_Pointer_array is array (C.Size_t range <>) of aliased FT_F26Dot6_Pointer; type FT_Int32_Pointer_array is array (C.Size_t range <>) of aliased FT_Int32_Pointer; type FT_UInt32_Pointer_array is array (C.Size_t range <>) of aliased FT_UInt32_Pointer; type FT_Render_Mode_Pointer_array is array (C.Size_t range <>) of aliased FT_Render_Mode_Pointer; type FT_Outline_Pointer_array is array (C.Size_t range <>) of aliased FT_Outline_Pointer; type FT_LibraryRec_Pointer_array is array (C.Size_t range <>) of aliased FT_LibraryRec_Pointer; type FT_GlyphSlotRec_Pointer_array is array (C.Size_t range <>) of aliased FT_GlyphSlotRec_Pointer; type FT_FaceRec_Pointer_array is array (C.Size_t range <>) of aliased FT_FaceRec_Pointer; type FT_Kerning_Mode_Pointer_array is array (C.Size_t range <>) of aliased FT_Kerning_Mode_Pointer; type FT_SizeRec_Pointer_array is array (C.Size_t range <>) of aliased FT_SizeRec_Pointer; end freetype_c.Pointers;
with Ada.Text_IO; package body Sets.IO is procedure Put (Set : in Set_Type) is use Ada.Text_IO; begin if Set = Null_Set then Put ("<null>"); else for Bit of Set.all loop if Bit then Put ("1"); else Put (" "); end if; end loop; end if; end Put; end Sets.IO;
with Ada.Numerics.Generic_Real_Arrays; generic with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>); package Decomposition is -- decompose a square matrix A by PA = LU procedure Decompose (A : Matrix.Real_Matrix; P, L, U : out Matrix.Real_Matrix); end Decomposition;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; -- Exemple d'utilisation des Unbonded_String procedure Exemple_Unbounded_String is Chaine: Unbounded_String; begin -- Intialiser une Unbounded_String à partir d'une String Chaine := To_Unbounded_String ("Exemple"); -- Afficher une Unbounded_String Put_Line ("La chaine est : " & Chaine); --! & concaténation des chaînes -- Longueur d'une Unbounded_String Put ("Sa longueur est : "); Put (Length (Chaine), 1); New_Line; -- L'initiale de la chaîne Put_Line ("Son initiale est " & To_String (Chaine) (1)); -- Ajouter une chaîne à la fin d'une Unbounded_String Append (Chaine, " final"); Put_Line ("La chaine après concaténation est : " & Chaine); -- Lire au clavier une Unbounded_String Put ("Donner une chaîne : "); Chaine := Get_Line; Put_Line ("La chaine lu est : " & Chaine); end Exemple_Unbounded_String;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . T A S K _ T E R M I N A T I O N -- -- -- -- S p e c -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. In accordance with the copyright of that document, you can freely -- -- copy and modify this specification, provided that if you redistribute a -- -- modified version, any changes that you have made are clearly indicated. -- -- -- ------------------------------------------------------------------------------ with Ada.Task_Identification; with Ada.Exceptions; package Ada.Task_Termination is pragma Preelaborate (Task_Termination); type Cause_Of_Termination is (Normal, Abnormal, Unhandled_Exception); type Termination_Handler is access protected procedure (Cause : Cause_Of_Termination; T : Ada.Task_Identification.Task_Id; X : Ada.Exceptions.Exception_Occurrence); procedure Set_Dependents_Fallback_Handler (Handler : Termination_Handler); function Current_Task_Fallback_Handler return Termination_Handler; procedure Set_Specific_Handler (T : Ada.Task_Identification.Task_Id; Handler : Termination_Handler); function Specific_Handler (T : Ada.Task_Identification.Task_Id) return Termination_Handler; end Ada.Task_Termination;
--------------------------------------------------------------------------------- -- Copyright 2004-2005 © Luke A. Guest -- -- This code is to be used for tutorial purposes only. -- You may not redistribute this code in any form without my express permission. --------------------------------------------------------------------------------- package body Line_Segment is function Create(StartPoint, EndPoint : Vector3.Object) return Object is begin return Object'(StartPoint, EndPoint); end Create; end Line_Segment;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- I N L I N E -- -- -- -- S p e c -- -- -- -- 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, 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. -- -- -- ------------------------------------------------------------------------------ -- This module handles two kinds of inlining activity: -- a) Instantiation of generic bodies. This is done unconditionally, after -- analysis and expansion of the main unit. -- b) Compilation of unit bodies that contain the bodies of inlined sub- -- programs. This is done only if inlining is enabled (-gnatn). Full inlining -- requires that a) an b) be mutually recursive, because each step may -- generate another generic expansion and further inlined calls. For now each -- of them uses a workpile algorithm, but they are called independently from -- Frontend, and thus are not mutually recursive. with Alloc; with Table; with Types; use Types; package Inline is -------------------------------- -- Generic Body Instantiation -- -------------------------------- -- The bodies of generic instantiations are built after semantic analysis -- of the main unit is complete. Generic instantiations are saved in a -- global data structure, and the bodies constructed by means of a separate -- analysis and expansion step. -- See full description in body of Sem_Ch12 for details type Pending_Body_Info is record Inst_Node : Node_Id; -- Node for instantiation that requires the body Act_Decl : Node_Id; -- Declaration for package or subprogram spec for instantiation Expander_Status : Boolean; -- If the body is instantiated only for semantic checking, expansion -- must be inhibited. Current_Sem_Unit : Unit_Number_Type; -- The semantic unit within which the instantiation is found. Must -- be restored when compiling the body, to insure that internal enti- -- ties use the same counter and are unique over spec and body. end record; package Pending_Instantiations is new Table.Table ( Table_Component_Type => Pending_Body_Info, Table_Index_Type => Int, Table_Low_Bound => 0, Table_Initial => Alloc.Pending_Instantiations_Initial, Table_Increment => Alloc.Pending_Instantiations_Increment, Table_Name => "Pending_Instantiations"); -- The following table records subprograms and packages for which -- generation of subprogram descriptors must be delayed. package Pending_Descriptor is new Table.Table ( Table_Component_Type => Entity_Id, Table_Index_Type => Int, Table_Low_Bound => 0, Table_Initial => Alloc.Pending_Instantiations_Initial, Table_Increment => Alloc.Pending_Instantiations_Increment, Table_Name => "Pending_Descriptor"); Analyzing_Inlined_Bodies : Boolean; -- This flag is set False by the call to Initialize, and then is set -- True by the call to Analyze_Inlined_Bodies. It is used to suppress -- generation of subprogram descriptors for inlined bodies. ----------------- -- Subprograms -- ----------------- procedure Initialize; -- Initialize internal tables procedure Lock; -- Lock internal tables before calling backend procedure Instantiate_Bodies; -- This procedure is called after semantic analysis is complete, to -- instantiate the bodies of generic instantiations that appear in the -- compilation unit. procedure Add_Inlined_Body (E : Entity_Id); -- E is an inlined subprogram appearing in a call, either explicitly, or -- a discriminant check for which gigi builds a call. Add E's enclosing -- unit to Inlined_Bodies so that body of E can be subsequently retrieved -- and analyzed. procedure Analyze_Inlined_Bodies; -- At end of compilation, analyze the bodies of all units that contain -- inlined subprograms that are actually called. procedure Check_Body_For_Inlining (N : Node_Id; P : Entity_Id); -- If front-end inlining is enabled and a package declaration contains -- inlined subprograms, load and compile the package body to collect the -- bodies of these subprograms, so they are available to inline calls. -- N is the compilation unit for the package. procedure Remove_Dead_Instance (N : Node_Id); -- If an instantiation appears in unreachable code, delete the pending -- body instance. end Inline;
with Ada.Strings, Ada.Strings.UTF_Encoding, Ada.Strings.UTF_Encoding.Wide_Strings, Ada.Wide_Text_IO; use Ada.Strings.UTF_Encoding; package body Password_Encode is -- -- package body Base64 is -- procedure Decode(Source : in String; Target : out Bytes; Last : out Natural) is -- Six-bit value representing a Base64 character's numerical value. D : Six_Bits; -- Slot := which chunk of bits in a 24-bit segment is being represented -- by the current character or value of D. range: 0 .. 3 type Slots is mod 4; Slot : Slots := 0; -- Current operation's string index of input string. begin Last := Target'first - 1; for Si in Source'range loop D := To_ModSix(Source(Si)); if D /= 0 or else Source(Si) = 'A' then -- source is valid Base64 case Slot is when 0 => Last := Last + 1; Target(Last) := 4 * D; -- dddddd00 ........ ........ when 1 => Target(Last) := Target(Last) + D / 16; exit when Last = Target'last and then (Si = Source'last or else Source(Si + 1) = '=') and then (D mod 16) = 0; Last := Last + 1; Target(Last) := (D mod 16) * 16; -- dddddddd dddd0000 ........ when 2 => Target(Last) := Target(Last) + D / 4; exit when Last = Target'last and then (Si = Source'last or else Source(Si + 1) = '=') and then (D mod 4) = 0; Last := Last + 1; Target(Last) := (D mod 4) * 64; -- dddddddd dddddddd dd000000 when 3 => Target(Last) := Target(Last) + D; -- dddddddd dddddddd dddddddd end case; Slot := Slot + 1; elsif Source(Si) = '=' then exit; -- terminator encountered end if; -- silently ignore whitespace, lf, garbage, ... end loop; end Decode; function Decode(Source : in String) return Bytes is Out_Bytes : Bytes(1 .. Source'Length) := (others => 0); Out_Length : Natural := 0; begin Decode(Source, Out_Bytes, Out_Length); return Out_Bytes(1 .. Out_Length); end Decode; -- Encode Bytes into Base64 String. procedure Encode(Source : in Bytes; Target : out String; Last : out Natural) is -- Target is filled in four character increments, except that -- a CR-LF pair is inserted after every 76 characters. -- Target'length must be at least: -- Output_Quad_Count: constant := (Source'length + 2) / 3; -- Output_Byte_Count: constant := 4 * Output_Quad_Count; -- Target'length = Output_Byte_Count + 2 * (Output_Byte_Count / 76) -- Constraint_Error will be raised if Target isn't long enough. -- use type Ada.Streams.Stream_Element; -- use type Ada.Streams.Stream_Element_Offset; D : Six_Bits; type Slots is mod 3; Slot : Slots := 0; Output_Line_Length: Natural := 0; begin Last := Target'first - 1; for Si in Source'range loop case Slot is when 0 => Output_Line_Length := Output_Line_Length + 4; Last := Last + 4; Target(Last - 3) := To_Char64(Source(Si) / 4); D := (Source(Si) mod 4) * 16; Target(Last - 2) := To_Char64(D); Target(Last - 1) := '='; Target(Last) := '='; -- dddddd dd0000 = = when 1 => D := D + Source(Si) / 16; Target(Last - 2) := To_Char64(D); D := (Source(Si) mod 16) * 4; Target(Last - 1) := To_Char64(D); -- dddddd dddddd dddd00 = when 2 => D := D + Source(Si) / 64; Target(Last - 1) := To_Char64(D); Target(Last) := To_Char64(Source(Si) mod 64); -- dddddd dddddd dddddd dddddd end case; Slot := Slot + 1; end loop; end Encode; function Encode(Source : in Bytes) return String is Out_String : String(1 .. (((Source'Length * 4) / 3) + 4)); Out_Length : Natural := 0; begin Encode(Source, Out_String, Out_Length); return Out_String(1 .. Out_Length); end Encode; end Base64; -- -- -- -- function Standard_Input return IO.File_Type is begin return IO.Standard_Input; end Standard_Input; function Standard_Output return IO.File_Type is begin return IO.Standard_Output; end Standard_Output; -- -- function Get_Codec return Password_Codec is New_Codec : Password_Codec := Codec; begin if Codec = Password_Codec'Last then Codec := Password_Codec'First; else Codec := Password_Codec'Succ(Codec); end if; return New_Codec; end Get_Codec; -- -- procedure Report_Wide(Message: Wide_String) is begin Ada.Wide_Text_IO.Put_Line(File => Ada.Wide_Text_IO.Current_Error, Item => Message); end Report_Wide; procedure Report(Message : UTF_8_String) is Converted_String : Wide_String := Wide_Strings.Decode(Item => Message); begin Report_Wide(Message => Converted_String); end Report; -- -- protected body Encoder_Module is procedure Get_Next(Target : out Natural) is begin Target := Natural(Data(Position)); Position := (Position mod Finish) + 1; end Get_Next; procedure Get_Next(Target : out Natural; Increment : Boolean) is begin Target := Natural(Data(Position) + Inc); Inc := (Inc + 1) mod 65536; Position := (Position mod Finish) + 1; end Get_Next; function Codec return Password_Codec is begin return Module_Codec; end Codec; procedure Set(S : in Wide_String := " ") is C : Wide_Character; function Validate(Character_Pos : Natural) return Offset is Valid_Offset: Offset := 0; begin if Character_Pos > 31 then Valid_Offset := Offset(Character_Pos - 31); else Valid_Offset := 0; end if; return Valid_Offset; end Validate; begin if S'Length < Size then Finish := S'Length; else Finish := Size; Report("Warning: password is as large or larger than allowed by this program."); Report(" To decrypt later you must use the exact same program or one with exact same"); Report(" internal configuration -- must clip the length of password to the same length"); Report(" as is being done now."); end if; Is_Set := True; for Position in 1 .. Finish loop C := S(Position); Data(Position) := Validate(Wide_Character'Pos(C)); end loop; Module_Codec := Get_Codec; Position := 1; end Set; function Status return Boolean is begin return Is_Set; end Status; procedure Reset is begin Position := 1; Inc := 0; end Reset; end Encoder_Module; -- -- Make a new encoder for every File Input/Output to be performed within -- any given time -- only one for One file at a time using the same -- password set. protected body Encoder is function Status return Integer is Number : Integer := 0; begin if Data(Status_Count).Status = True then Number := Status_Count; else for Module in Data'Range loop if Data(Module).Status then Number := Number + 1; end if; end loop; end if; return Number; end Status; procedure Reset is begin for Module in Data'Range loop Data(Module).Reset; end loop; Is_Clean := True; end Reset; procedure Set_Wide(S : in Wide_String) is begin if Status < Data'Length then Data(Status + 1).Set(S); end if; end Set_Wide; -- procedure Set(S : in UTF_8_String) is NewData : Wide_String := Wide_Strings.Decode(Item=> S); begin Set_Wide(S => NewData); end Set; -- procedure Set is NewData : Wide_String(1 .. 1) := (others => Ada.Strings.Wide_Space); begin Set_Wide(S => NewData); end Set; procedure Encode(Input : in Bytes; Output : out Bytes) is Input_Data : String := Base64.Encode(Input); Input_Length : Integer := Input_Mod'Length; Modules : constant Integer := Status; Bytes_Length : Integer := Input'Length; Break_Point : Integer := 1; Output_Data : String(1 .. Input_Length) := Input_Data; begin for Module in Data'Range loop case Data(Module).Codec is when Modular => if Bytes_Length mod 3 = 0 then for N in 1 .. Input_Length loop Output_Mod(N) := Base64.To_Char64((Base64.To_ModSix(Input_Data(N)) + Data(Module).Get_Next) mod 64); end loop; else for N in 1 .. (Input_Length - 4) loop Output_Mod(N) := Base64.To_Char64((Base64.To_ModSix(Input_Mod(N)) + GetNext) mod 64); end loop; for N in (Input_Length - 4) .. (Input_Length - 1) loop if Input_Mod(N + 1) = '=' then Output_Mod(N) := Input_Mod(N); else Output_Mod(N) := Base64.To_Char64((Base64.To_ModSix(Input_Mod(N)) + GetNext) mod 64); end if; end loop; end if; when Low_Swap => null; when Incrementing => null; when High_Swap => null; end case; end loop; if Is_Set2 then Input_Mod2 := Output_Mod; if Bytes_Length mod 3 = 0 then Break_Point := Input_Length / 2; else Break_Point := (Input_Length - 4) / 2; end if; for N in GetNext2 loop N := (Data(Module).Get_Next mod Break_Point) + 1; for M in 1 .. N loop Output_Mod(M) := Input_Mod2(M + N); Output_Mod(M + N) := Input_Mod2(M); end loop; end loop; end if; if Is_Set3 then null; end if; if Bytes_Length < 57 then Is_Clean := False; end if; end Encode; end Encoder; end Password_Encode;
pragma License (Unrestricted); -- implementation unit required by compiler with System.Exponentiations; package System.Exp_Int is pragma Pure; -- required for "**" with checking by compiler (s-expint.ads) function Exp_Integer is new Exponentiations.Generic_Exp_Integer (Integer); end System.Exp_Int;
with Ada.Text_IO; use Ada.Text_IO; package body Clases is function Dame_Alumno (Num : in Num_Alumno; La_Clase : in Clase) return Alumnos.Alumno is begin return La_Clase.Alumnos(Num); end Dame_Alumno; procedure Inserta_Alumno (Alu : in Alumnos.Alumno; La_Clase : in out Clase) is begin La_Clase.Num:=La_Clase.Num+1; La_Clase.Alumnos(La_Clase.Num):=Alu; end Inserta_Alumno; function Llena (La_Clase : in Clase) return Boolean is begin return La_Clase.Num=Max_Alumnos; end Llena; function Numero_Alumnos (La_Clase : in Clase) return Natural is begin return La_Clase.Num; end Numero_Alumnos; end Clases;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ U T I L -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2016, 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 Aspects; use Aspects; with Atree; use Atree; with Casing; use Casing; with Checks; use Checks; with Debug; use Debug; with Einfo; use Einfo; with Elists; use Elists; with Errout; use Errout; with Exp_Aggr; use Exp_Aggr; with Exp_Ch6; use Exp_Ch6; with Exp_Ch7; use Exp_Ch7; with Exp_Ch11; use Exp_Ch11; with Ghost; use Ghost; with Inline; use Inline; with Itypes; use Itypes; with Lib; use Lib; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Restrict; use Restrict; with Rident; use Rident; with Sem; use Sem; with Sem_Aux; use Sem_Aux; with Sem_Ch3; use Sem_Ch3; with Sem_Ch6; use Sem_Ch6; with Sem_Ch8; use Sem_Ch8; with Sem_Ch12; use Sem_Ch12; with Sem_Ch13; use Sem_Ch13; with Sem_Disp; use Sem_Disp; with Sem_Eval; use Sem_Eval; with Sem_Res; use Sem_Res; with Sem_Type; use Sem_Type; with Sem_Util; use Sem_Util; with Snames; use Snames; with Stand; use Stand; with Stringt; use Stringt; with Targparm; use Targparm; with Tbuild; use Tbuild; with Ttypes; use Ttypes; with Urealp; use Urealp; with Validsw; use Validsw; with GNAT.HTable; use GNAT.HTable; package body Exp_Util is --------------------------------------------------------- -- Handling of inherited class-wide pre/postconditions -- --------------------------------------------------------- -- Following AI12-0113, the expression for a class-wide condition is -- transformed for a subprogram that inherits it, by replacing calls -- to primitive operations of the original controlling type into the -- corresponding overriding operations of the derived type. The following -- hash table manages this mapping, and is expanded on demand whenever -- such inherited expression needs to be constructed. -- The mapping is also used to check whether an inherited operation has -- a condition that depends on overridden operations. For such an -- operation we must create a wrapper that is then treated as a normal -- overriding. In SPARK mode such operations are illegal. -- For a given root type there may be several type extensions with their -- own overriding operations, so at various times a given operation of -- the root will be mapped into different overridings. The root type is -- also mapped into the current type extension to indicate that its -- operations are mapped into the overriding operations of that current -- type extension. Primitives_Mapping_Size : constant := 511; subtype Num_Primitives is Integer range 0 .. Primitives_Mapping_Size - 1; function Entity_Hash (E : Entity_Id) return Num_Primitives; package Primitives_Mapping is new GNAT.HTable.Simple_HTable (Header_Num => Num_Primitives, Key => Entity_Id, Element => Entity_Id, No_element => Empty, Hash => Entity_Hash, Equal => "="); ----------------------- -- Local Subprograms -- ----------------------- function Build_Task_Array_Image (Loc : Source_Ptr; Id_Ref : Node_Id; A_Type : Entity_Id; Dyn : Boolean := False) return Node_Id; -- Build function to generate the image string for a task that is an array -- component, concatenating the images of each index. To avoid storage -- leaks, the string is built with successive slice assignments. The flag -- Dyn indicates whether this is called for the initialization procedure of -- an array of tasks, or for the name of a dynamically created task that is -- assigned to an indexed component. function Build_Task_Image_Function (Loc : Source_Ptr; Decls : List_Id; Stats : List_Id; Res : Entity_Id) return Node_Id; -- Common processing for Task_Array_Image and Task_Record_Image. Build -- function body that computes image. procedure Build_Task_Image_Prefix (Loc : Source_Ptr; Len : out Entity_Id; Res : out Entity_Id; Pos : out Entity_Id; Prefix : Entity_Id; Sum : Node_Id; Decls : List_Id; Stats : List_Id); -- Common processing for Task_Array_Image and Task_Record_Image. Create -- local variables and assign prefix of name to result string. function Build_Task_Record_Image (Loc : Source_Ptr; Id_Ref : Node_Id; Dyn : Boolean := False) return Node_Id; -- Build function to generate the image string for a task that is a record -- component. Concatenate name of variable with that of selector. The flag -- Dyn indicates whether this is called for the initialization procedure of -- record with task components, or for a dynamically created task that is -- assigned to a selected component. procedure Evaluate_Slice_Bounds (Slice : Node_Id); -- Force evaluation of bounds of a slice, which may be given by a range -- or by a subtype indication with or without a constraint. function Find_DIC_Type (Typ : Entity_Id) return Entity_Id; -- Subsidiary to all Build_DIC_Procedure_xxx routines. Find the type which -- defines the Default_Initial_Condition pragma of type Typ. This is either -- Typ itself or a parent type when the pragma is inherited. function Make_CW_Equivalent_Type (T : Entity_Id; E : Node_Id) return Entity_Id; -- T is a class-wide type entity, E is the initial expression node that -- constrains T in case such as: " X: T := E" or "new T'(E)". This function -- returns the entity of the Equivalent type and inserts on the fly the -- necessary declaration such as: -- -- type anon is record -- _parent : Root_Type (T); constrained with E discriminants (if any) -- Extension : String (1 .. expr to match size of E); -- end record; -- -- This record is compatible with any object of the class of T thanks to -- the first field and has the same size as E thanks to the second. function Make_Literal_Range (Loc : Source_Ptr; Literal_Typ : Entity_Id) return Node_Id; -- Produce a Range node whose bounds are: -- Low_Bound (Literal_Type) .. -- Low_Bound (Literal_Type) + (Length (Literal_Typ) - 1) -- this is used for expanding declarations like X : String := "sdfgdfg"; -- -- If the index type of the target array is not integer, we generate: -- Low_Bound (Literal_Type) .. -- Literal_Type'Val -- (Literal_Type'Pos (Low_Bound (Literal_Type)) -- + (Length (Literal_Typ) -1)) function Make_Non_Empty_Check (Loc : Source_Ptr; N : Node_Id) return Node_Id; -- Produce a boolean expression checking that the unidimensional array -- node N is not empty. function New_Class_Wide_Subtype (CW_Typ : Entity_Id; N : Node_Id) return Entity_Id; -- Create an implicit subtype of CW_Typ attached to node N function Requires_Cleanup_Actions (L : List_Id; Lib_Level : Boolean; Nested_Constructs : Boolean) return Boolean; -- Given a list L, determine whether it contains one of the following: -- -- 1) controlled objects -- 2) library-level tagged types -- -- Lib_Level is True when the list comes from a construct at the library -- level, and False otherwise. Nested_Constructs is True when any nested -- packages declared in L must be processed, and False otherwise. ------------------------------------- -- Activate_Atomic_Synchronization -- ------------------------------------- procedure Activate_Atomic_Synchronization (N : Node_Id) is Msg_Node : Node_Id; begin case Nkind (Parent (N)) is -- Check for cases of appearing in the prefix of a construct where we -- don't need atomic synchronization for this kind of usage. when -- Nothing to do if we are the prefix of an attribute, since we -- do not want an atomic sync operation for things like 'Size. N_Attribute_Reference -- The N_Reference node is like an attribute | N_Reference -- Nothing to do for a reference to a component (or components) -- of a composite object. Only reads and updates of the object -- as a whole require atomic synchronization (RM C.6 (15)). | N_Indexed_Component | N_Selected_Component | N_Slice => -- For all the above cases, nothing to do if we are the prefix if Prefix (Parent (N)) = N then return; end if; when others => null; end case; -- Nothing to do for the identifier in an object renaming declaration, -- the renaming itself does not need atomic synchronization. if Nkind (Parent (N)) = N_Object_Renaming_Declaration then return; end if; -- Go ahead and set the flag Set_Atomic_Sync_Required (N); -- Generate info message if requested if Warn_On_Atomic_Synchronization then case Nkind (N) is when N_Identifier => Msg_Node := N; when N_Expanded_Name | N_Selected_Component => Msg_Node := Selector_Name (N); when N_Explicit_Dereference | N_Indexed_Component => Msg_Node := Empty; when others => pragma Assert (False); return; end case; if Present (Msg_Node) then Error_Msg_N ("info: atomic synchronization set for &?N?", Msg_Node); else Error_Msg_N ("info: atomic synchronization set?N?", N); end if; end if; end Activate_Atomic_Synchronization; ---------------------- -- Adjust_Condition -- ---------------------- procedure Adjust_Condition (N : Node_Id) is begin if No (N) then return; end if; declare Loc : constant Source_Ptr := Sloc (N); T : constant Entity_Id := Etype (N); Ti : Entity_Id; begin -- Defend against a call where the argument has no type, or has a -- type that is not Boolean. This can occur because of prior errors. if No (T) or else not Is_Boolean_Type (T) then return; end if; -- Apply validity checking if needed if Validity_Checks_On and Validity_Check_Tests then Ensure_Valid (N); end if; -- Immediate return if standard boolean, the most common case, -- where nothing needs to be done. if Base_Type (T) = Standard_Boolean then return; end if; -- Case of zero/non-zero semantics or non-standard enumeration -- representation. In each case, we rewrite the node as: -- ityp!(N) /= False'Enum_Rep -- where ityp is an integer type with large enough size to hold any -- value of type T. if Nonzero_Is_True (T) or else Has_Non_Standard_Rep (T) then if Esize (T) <= Esize (Standard_Integer) then Ti := Standard_Integer; else Ti := Standard_Long_Long_Integer; end if; Rewrite (N, Make_Op_Ne (Loc, Left_Opnd => Unchecked_Convert_To (Ti, N), Right_Opnd => Make_Attribute_Reference (Loc, Attribute_Name => Name_Enum_Rep, Prefix => New_Occurrence_Of (First_Literal (T), Loc)))); Analyze_And_Resolve (N, Standard_Boolean); else Rewrite (N, Convert_To (Standard_Boolean, N)); Analyze_And_Resolve (N, Standard_Boolean); end if; end; end Adjust_Condition; ------------------------ -- Adjust_Result_Type -- ------------------------ procedure Adjust_Result_Type (N : Node_Id; T : Entity_Id) is begin -- Ignore call if current type is not Standard.Boolean if Etype (N) /= Standard_Boolean then return; end if; -- If result is already of correct type, nothing to do. Note that -- this will get the most common case where everything has a type -- of Standard.Boolean. if Base_Type (T) = Standard_Boolean then return; else declare KP : constant Node_Kind := Nkind (Parent (N)); begin -- If result is to be used as a Condition in the syntax, no need -- to convert it back, since if it was changed to Standard.Boolean -- using Adjust_Condition, that is just fine for this usage. if KP in N_Raise_xxx_Error or else KP in N_Has_Condition then return; -- If result is an operand of another logical operation, no need -- to reset its type, since Standard.Boolean is just fine, and -- such operations always do Adjust_Condition on their operands. elsif KP in N_Op_Boolean or else KP in N_Short_Circuit or else KP = N_Op_Not then return; -- Otherwise we perform a conversion from the current type, which -- must be Standard.Boolean, to the desired type. Use the base -- type to prevent spurious constraint checks that are extraneous -- to the transformation. The type and its base have the same -- representation, standard or otherwise. else Set_Analyzed (N); Rewrite (N, Convert_To (Base_Type (T), N)); Analyze_And_Resolve (N, Base_Type (T)); end if; end; end if; end Adjust_Result_Type; -------------------------- -- Append_Freeze_Action -- -------------------------- procedure Append_Freeze_Action (T : Entity_Id; N : Node_Id) is Fnode : Node_Id; begin Ensure_Freeze_Node (T); Fnode := Freeze_Node (T); if No (Actions (Fnode)) then Set_Actions (Fnode, New_List (N)); else Append (N, Actions (Fnode)); end if; end Append_Freeze_Action; --------------------------- -- Append_Freeze_Actions -- --------------------------- procedure Append_Freeze_Actions (T : Entity_Id; L : List_Id) is Fnode : Node_Id; begin if No (L) then return; end if; Ensure_Freeze_Node (T); Fnode := Freeze_Node (T); if No (Actions (Fnode)) then Set_Actions (Fnode, L); else Append_List (L, Actions (Fnode)); end if; end Append_Freeze_Actions; ------------------------------------ -- Build_Allocate_Deallocate_Proc -- ------------------------------------ procedure Build_Allocate_Deallocate_Proc (N : Node_Id; Is_Allocate : Boolean) is Desig_Typ : Entity_Id; Expr : Node_Id; Pool_Id : Entity_Id; Proc_To_Call : Node_Id := Empty; Ptr_Typ : Entity_Id; function Find_Object (E : Node_Id) return Node_Id; -- Given an arbitrary expression of an allocator, try to find an object -- reference in it, otherwise return the original expression. function Is_Allocate_Deallocate_Proc (Subp : Entity_Id) return Boolean; -- Determine whether subprogram Subp denotes a custom allocate or -- deallocate. ----------------- -- Find_Object -- ----------------- function Find_Object (E : Node_Id) return Node_Id is Expr : Node_Id; begin pragma Assert (Is_Allocate); Expr := E; loop if Nkind (Expr) = N_Explicit_Dereference then Expr := Prefix (Expr); elsif Nkind (Expr) = N_Qualified_Expression then Expr := Expression (Expr); elsif Nkind (Expr) = N_Unchecked_Type_Conversion then -- When interface class-wide types are involved in allocation, -- the expander introduces several levels of address arithmetic -- to perform dispatch table displacement. In this scenario the -- object appears as: -- Tag_Ptr (Base_Address (<object>'Address)) -- Detect this case and utilize the whole expression as the -- "object" since it now points to the proper dispatch table. if Is_RTE (Etype (Expr), RE_Tag_Ptr) then exit; -- Continue to strip the object else Expr := Expression (Expr); end if; else exit; end if; end loop; return Expr; end Find_Object; --------------------------------- -- Is_Allocate_Deallocate_Proc -- --------------------------------- function Is_Allocate_Deallocate_Proc (Subp : Entity_Id) return Boolean is begin -- Look for a subprogram body with only one statement which is a -- call to Allocate_Any_Controlled / Deallocate_Any_Controlled. if Ekind (Subp) = E_Procedure and then Nkind (Parent (Parent (Subp))) = N_Subprogram_Body then declare HSS : constant Node_Id := Handled_Statement_Sequence (Parent (Parent (Subp))); Proc : Entity_Id; begin if Present (Statements (HSS)) and then Nkind (First (Statements (HSS))) = N_Procedure_Call_Statement then Proc := Entity (Name (First (Statements (HSS)))); return Is_RTE (Proc, RE_Allocate_Any_Controlled) or else Is_RTE (Proc, RE_Deallocate_Any_Controlled); end if; end; end if; return False; end Is_Allocate_Deallocate_Proc; -- Start of processing for Build_Allocate_Deallocate_Proc begin -- Obtain the attributes of the allocation / deallocation if Nkind (N) = N_Free_Statement then Expr := Expression (N); Ptr_Typ := Base_Type (Etype (Expr)); Proc_To_Call := Procedure_To_Call (N); else if Nkind (N) = N_Object_Declaration then Expr := Expression (N); else Expr := N; end if; -- In certain cases an allocator with a qualified expression may -- be relocated and used as the initialization expression of a -- temporary: -- before: -- Obj : Ptr_Typ := new Desig_Typ'(...); -- after: -- Tmp : Ptr_Typ := new Desig_Typ'(...); -- Obj : Ptr_Typ := Tmp; -- Since the allocator is always marked as analyzed to avoid infinite -- expansion, it will never be processed by this routine given that -- the designated type needs finalization actions. Detect this case -- and complete the expansion of the allocator. if Nkind (Expr) = N_Identifier and then Nkind (Parent (Entity (Expr))) = N_Object_Declaration and then Nkind (Expression (Parent (Entity (Expr)))) = N_Allocator then Build_Allocate_Deallocate_Proc (Parent (Entity (Expr)), True); return; end if; -- The allocator may have been rewritten into something else in which -- case the expansion performed by this routine does not apply. if Nkind (Expr) /= N_Allocator then return; end if; Ptr_Typ := Base_Type (Etype (Expr)); Proc_To_Call := Procedure_To_Call (Expr); end if; Pool_Id := Associated_Storage_Pool (Ptr_Typ); Desig_Typ := Available_View (Designated_Type (Ptr_Typ)); -- Handle concurrent types if Is_Concurrent_Type (Desig_Typ) and then Present (Corresponding_Record_Type (Desig_Typ)) then Desig_Typ := Corresponding_Record_Type (Desig_Typ); end if; -- Do not process allocations / deallocations without a pool if No (Pool_Id) then return; -- Do not process allocations on / deallocations from the secondary -- stack. elsif Is_RTE (Pool_Id, RE_SS_Pool) then return; -- Optimize the case where we are using the default Global_Pool_Object, -- and we don't need the heavy finalization machinery. elsif Pool_Id = RTE (RE_Global_Pool_Object) and then not Needs_Finalization (Desig_Typ) then return; -- Do not replicate the machinery if the allocator / free has already -- been expanded and has a custom Allocate / Deallocate. elsif Present (Proc_To_Call) and then Is_Allocate_Deallocate_Proc (Proc_To_Call) then return; end if; if Needs_Finalization (Desig_Typ) then -- Certain run-time configurations and targets do not provide support -- for controlled types. if Restriction_Active (No_Finalization) then return; -- Do nothing if the access type may never allocate / deallocate -- objects. elsif No_Pool_Assigned (Ptr_Typ) then return; end if; -- The allocation / deallocation of a controlled object must be -- chained on / detached from a finalization master. pragma Assert (Present (Finalization_Master (Ptr_Typ))); -- The only other kind of allocation / deallocation supported by this -- routine is on / from a subpool. elsif Nkind (Expr) = N_Allocator and then No (Subpool_Handle_Name (Expr)) then return; end if; declare Loc : constant Source_Ptr := Sloc (N); Addr_Id : constant Entity_Id := Make_Temporary (Loc, 'A'); Alig_Id : constant Entity_Id := Make_Temporary (Loc, 'L'); Proc_Id : constant Entity_Id := Make_Temporary (Loc, 'P'); Size_Id : constant Entity_Id := Make_Temporary (Loc, 'S'); Actuals : List_Id; Fin_Addr_Id : Entity_Id; Fin_Mas_Act : Node_Id; Fin_Mas_Id : Entity_Id; Proc_To_Call : Entity_Id; Subpool : Node_Id := Empty; begin -- Step 1: Construct all the actuals for the call to library routine -- Allocate_Any_Controlled / Deallocate_Any_Controlled. -- a) Storage pool Actuals := New_List (New_Occurrence_Of (Pool_Id, Loc)); if Is_Allocate then -- b) Subpool if Nkind (Expr) = N_Allocator then Subpool := Subpool_Handle_Name (Expr); end if; -- If a subpool is present it can be an arbitrary name, so make -- the actual by copying the tree. if Present (Subpool) then Append_To (Actuals, New_Copy_Tree (Subpool, New_Sloc => Loc)); else Append_To (Actuals, Make_Null (Loc)); end if; -- c) Finalization master if Needs_Finalization (Desig_Typ) then Fin_Mas_Id := Finalization_Master (Ptr_Typ); Fin_Mas_Act := New_Occurrence_Of (Fin_Mas_Id, Loc); -- Handle the case where the master is actually a pointer to a -- master. This case arises in build-in-place functions. if Is_Access_Type (Etype (Fin_Mas_Id)) then Append_To (Actuals, Fin_Mas_Act); else Append_To (Actuals, Make_Attribute_Reference (Loc, Prefix => Fin_Mas_Act, Attribute_Name => Name_Unrestricted_Access)); end if; else Append_To (Actuals, Make_Null (Loc)); end if; -- d) Finalize_Address -- Primitive Finalize_Address is never generated in CodePeer mode -- since it contains an Unchecked_Conversion. if Needs_Finalization (Desig_Typ) and then not CodePeer_Mode then Fin_Addr_Id := Finalize_Address (Desig_Typ); pragma Assert (Present (Fin_Addr_Id)); Append_To (Actuals, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Fin_Addr_Id, Loc), Attribute_Name => Name_Unrestricted_Access)); else Append_To (Actuals, Make_Null (Loc)); end if; end if; -- e) Address -- f) Storage_Size -- g) Alignment Append_To (Actuals, New_Occurrence_Of (Addr_Id, Loc)); Append_To (Actuals, New_Occurrence_Of (Size_Id, Loc)); if Is_Allocate or else not Is_Class_Wide_Type (Desig_Typ) then Append_To (Actuals, New_Occurrence_Of (Alig_Id, Loc)); -- For deallocation of class-wide types we obtain the value of -- alignment from the Type Specific Record of the deallocated object. -- This is needed because the frontend expansion of class-wide types -- into equivalent types confuses the back end. else -- Generate: -- Obj.all'Alignment -- ... because 'Alignment applied to class-wide types is expanded -- into the code that reads the value of alignment from the TSD -- (see Expand_N_Attribute_Reference) Append_To (Actuals, Unchecked_Convert_To (RTE (RE_Storage_Offset), Make_Attribute_Reference (Loc, Prefix => Make_Explicit_Dereference (Loc, Relocate_Node (Expr)), Attribute_Name => Name_Alignment))); end if; -- h) Is_Controlled if Needs_Finalization (Desig_Typ) then declare Flag_Id : constant Entity_Id := Make_Temporary (Loc, 'F'); Flag_Expr : Node_Id; Param : Node_Id; Temp : Node_Id; begin if Is_Allocate then Temp := Find_Object (Expression (Expr)); else Temp := Expr; end if; -- Processing for allocations where the expression is a subtype -- indication. if Is_Allocate and then Is_Entity_Name (Temp) and then Is_Type (Entity (Temp)) then Flag_Expr := New_Occurrence_Of (Boolean_Literals (Needs_Finalization (Entity (Temp))), Loc); -- The allocation / deallocation of a class-wide object relies -- on a runtime check to determine whether the object is truly -- controlled or not. Depending on this check, the finalization -- machinery will request or reclaim extra storage reserved for -- a list header. elsif Is_Class_Wide_Type (Desig_Typ) then -- Detect a special case where interface class-wide types -- are involved as the object appears as: -- Tag_Ptr (Base_Address (<object>'Address)) -- The expression already yields the proper tag, generate: -- Temp.all if Is_RTE (Etype (Temp), RE_Tag_Ptr) then Param := Make_Explicit_Dereference (Loc, Prefix => Relocate_Node (Temp)); -- In the default case, obtain the tag of the object about -- to be allocated / deallocated. Generate: -- Temp'Tag else Param := Make_Attribute_Reference (Loc, Prefix => Relocate_Node (Temp), Attribute_Name => Name_Tag); end if; -- Generate: -- Needs_Finalization (<Param>) Flag_Expr := Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Needs_Finalization), Loc), Parameter_Associations => New_List (Param)); -- Processing for generic actuals elsif Is_Generic_Actual_Type (Desig_Typ) then Flag_Expr := New_Occurrence_Of (Boolean_Literals (Needs_Finalization (Base_Type (Desig_Typ))), Loc); -- The object does not require any specialized checks, it is -- known to be controlled. else Flag_Expr := New_Occurrence_Of (Standard_True, Loc); end if; -- Create the temporary which represents the finalization state -- of the expression. Generate: -- -- F : constant Boolean := <Flag_Expr>; Insert_Action (N, Make_Object_Declaration (Loc, Defining_Identifier => Flag_Id, Constant_Present => True, Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc), Expression => Flag_Expr)); Append_To (Actuals, New_Occurrence_Of (Flag_Id, Loc)); end; -- The object is not controlled else Append_To (Actuals, New_Occurrence_Of (Standard_False, Loc)); end if; -- i) On_Subpool if Is_Allocate then Append_To (Actuals, New_Occurrence_Of (Boolean_Literals (Present (Subpool)), Loc)); end if; -- Step 2: Build a wrapper Allocate / Deallocate which internally -- calls Allocate_Any_Controlled / Deallocate_Any_Controlled. -- Select the proper routine to call if Is_Allocate then Proc_To_Call := RTE (RE_Allocate_Any_Controlled); else Proc_To_Call := RTE (RE_Deallocate_Any_Controlled); end if; -- Create a custom Allocate / Deallocate routine which has identical -- profile to that of System.Storage_Pools. Insert_Action (N, Make_Subprogram_Body (Loc, Specification => -- procedure Pnn Make_Procedure_Specification (Loc, Defining_Unit_Name => Proc_Id, Parameter_Specifications => New_List ( -- P : Root_Storage_Pool Make_Parameter_Specification (Loc, Defining_Identifier => Make_Temporary (Loc, 'P'), Parameter_Type => New_Occurrence_Of (RTE (RE_Root_Storage_Pool), Loc)), -- A : [out] Address Make_Parameter_Specification (Loc, Defining_Identifier => Addr_Id, Out_Present => Is_Allocate, Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc)), -- S : Storage_Count Make_Parameter_Specification (Loc, Defining_Identifier => Size_Id, Parameter_Type => New_Occurrence_Of (RTE (RE_Storage_Count), Loc)), -- L : Storage_Count Make_Parameter_Specification (Loc, Defining_Identifier => Alig_Id, Parameter_Type => New_Occurrence_Of (RTE (RE_Storage_Count), Loc)))), Declarations => No_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Proc_To_Call, Loc), Parameter_Associations => Actuals))))); -- The newly generated Allocate / Deallocate becomes the default -- procedure to call when the back end processes the allocation / -- deallocation. if Is_Allocate then Set_Procedure_To_Call (Expr, Proc_Id); else Set_Procedure_To_Call (N, Proc_Id); end if; end; end Build_Allocate_Deallocate_Proc; ------------------------------- -- Build_Abort_Undefer_Block -- ------------------------------- function Build_Abort_Undefer_Block (Loc : Source_Ptr; Stmts : List_Id; Context : Node_Id) return Node_Id is Exceptions_OK : constant Boolean := not Restriction_Active (No_Exception_Propagation); AUD : Entity_Id; Blk : Node_Id; Blk_Id : Entity_Id; HSS : Node_Id; begin -- The block should be generated only when undeferring abort in the -- context of a potential exception. pragma Assert (Abort_Allowed and Exceptions_OK); -- Generate: -- begin -- <Stmts> -- at end -- Abort_Undefer_Direct; -- end; AUD := RTE (RE_Abort_Undefer_Direct); HSS := Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts, At_End_Proc => New_Occurrence_Of (AUD, Loc)); Blk := Make_Block_Statement (Loc, Handled_Statement_Sequence => HSS); Set_Is_Abort_Block (Blk); Add_Block_Identifier (Blk, Blk_Id); Expand_At_End_Handler (HSS, Blk_Id); -- Present the Abort_Undefer_Direct function to the back end to inline -- the call to the routine. Add_Inlined_Body (AUD, Context); return Blk; end Build_Abort_Undefer_Block; --------------------------------- -- Build_Class_Wide_Expression -- --------------------------------- procedure Build_Class_Wide_Expression (Prag : Node_Id; Subp : Entity_Id; Par_Subp : Entity_Id; Adjust_Sloc : Boolean) is function Replace_Entity (N : Node_Id) return Traverse_Result; -- Replace reference to formal of inherited operation or to primitive -- operation of root type, with corresponding entity for derived type, -- when constructing the class-wide condition of an overriding -- subprogram. -------------------- -- Replace_Entity -- -------------------- function Replace_Entity (N : Node_Id) return Traverse_Result is New_E : Entity_Id; begin if Adjust_Sloc then Adjust_Inherited_Pragma_Sloc (N); end if; if Nkind (N) = N_Identifier and then Present (Entity (N)) and then (Is_Formal (Entity (N)) or else Is_Subprogram (Entity (N))) and then (Nkind (Parent (N)) /= N_Attribute_Reference or else Attribute_Name (Parent (N)) /= Name_Class) then -- The replacement does not apply to dispatching calls within the -- condition, but only to calls whose static tag is that of the -- parent type. if Is_Subprogram (Entity (N)) and then Nkind (Parent (N)) = N_Function_Call and then Present (Controlling_Argument (Parent (N))) then return OK; end if; -- Determine whether entity has a renaming New_E := Primitives_Mapping.Get (Entity (N)); if Present (New_E) then Rewrite (N, New_Occurrence_Of (New_E, Sloc (N))); end if; -- Check that there are no calls left to abstract operations if -- the current subprogram is not abstract. if Nkind (Parent (N)) = N_Function_Call and then N = Name (Parent (N)) then if not Is_Abstract_Subprogram (Subp) and then Is_Abstract_Subprogram (Entity (N)) then Error_Msg_Sloc := Sloc (Current_Scope); Error_Msg_NE ("cannot call abstract subprogram in inherited condition " & "for&#", N, Current_Scope); -- In SPARK mode, reject an inherited condition for an -- inherited operation if it contains a call to an overriding -- operation, because this implies that the pre/postconditions -- of the inherited operation have changed silently. elsif SPARK_Mode = On and then Warn_On_Suspicious_Contract and then Present (Alias (Subp)) and then Present (New_E) and then Comes_From_Source (New_E) then Error_Msg_N ("cannot modify inherited condition (SPARK RM 6.1.1(1))", Parent (Subp)); Error_Msg_Sloc := Sloc (New_E); Error_Msg_Node_2 := Subp; Error_Msg_NE ("\overriding of&# forces overriding of&", Parent (Subp), New_E); end if; end if; -- Update type of function call node, which should be the same as -- the function's return type. if Is_Subprogram (Entity (N)) and then Nkind (Parent (N)) = N_Function_Call then Set_Etype (Parent (N), Etype (Entity (N))); end if; -- The whole expression will be reanalyzed elsif Nkind (N) in N_Has_Etype then Set_Analyzed (N, False); end if; return OK; end Replace_Entity; procedure Replace_Condition_Entities is new Traverse_Proc (Replace_Entity); -- Local variables Par_Formal : Entity_Id; Subp_Formal : Entity_Id; -- Start of processing for Build_Class_Wide_Expression begin -- Add mapping from old formals to new formals Par_Formal := First_Formal (Par_Subp); Subp_Formal := First_Formal (Subp); while Present (Par_Formal) and then Present (Subp_Formal) loop Primitives_Mapping.Set (Par_Formal, Subp_Formal); Next_Formal (Par_Formal); Next_Formal (Subp_Formal); end loop; Replace_Condition_Entities (Prag); end Build_Class_Wide_Expression; -------------------- -- Build_DIC_Call -- -------------------- function Build_DIC_Call (Loc : Source_Ptr; Obj_Id : Entity_Id; Typ : Entity_Id) return Node_Id is Proc_Id : constant Entity_Id := DIC_Procedure (Typ); Formal_Typ : constant Entity_Id := Etype (First_Formal (Proc_Id)); begin return Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Proc_Id, Loc), Parameter_Associations => New_List ( Make_Unchecked_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (Formal_Typ, Loc), Expression => New_Occurrence_Of (Obj_Id, Loc)))); end Build_DIC_Call; ------------------------------ -- Build_DIC_Procedure_Body -- ------------------------------ -- WARNING: This routine manages Ghost regions. Return statements must be -- replaced by gotos which jump to the end of the routine and restore the -- Ghost mode. procedure Build_DIC_Procedure_Body (Typ : Entity_Id) is procedure Add_DIC_Check (DIC_Prag : Node_Id; DIC_Expr : Node_Id; Stmts : in out List_Id); -- Subsidiary to all Add_xxx_DIC routines. Add a runtime check to verify -- assertion expression DIC_Expr of pragma DIC_Prag. All generated code -- is added to list Stmts. procedure Add_Inherited_DIC (DIC_Prag : Node_Id; Par_Typ : Entity_Id; Deriv_Typ : Entity_Id; Stmts : in out List_Id); -- Add a runtime check to verify the assertion expression of inherited -- pragma DIC_Prag. Par_Typ is parent type, which is also the owner of -- the DIC pragma. Deriv_Typ is the derived type inheriting the DIC -- pragma. All generated code is added to list Stmts. procedure Add_Inherited_Tagged_DIC (DIC_Prag : Node_Id; Par_Typ : Entity_Id; Deriv_Typ : Entity_Id; Stmts : in out List_Id); -- Add a runtime check to verify assertion expression DIC_Expr of -- inherited pragma DIC_Prag. This routine applies class-wide pre- and -- postcondition-like runtime semantics to the check. Par_Typ is the -- parent type whose DIC pragma is being inherited. Deriv_Typ is the -- derived type inheriting the DIC pragma. All generated code is added -- to list Stmts. procedure Add_Own_DIC (DIC_Prag : Node_Id; DIC_Typ : Entity_Id; Stmts : in out List_Id); -- Add a runtime check to verify the assertion expression of pragma -- DIC_Prag. DIC_Typ is the owner of the DIC pragma. All generated code -- is added to list Stmts. procedure Replace_Object_And_Primitive_References (Expr : Node_Id; Par_Typ : Entity_Id; Deriv_Typ : Entity_Id; Par_Obj : Entity_Id := Empty; Deriv_Obj : Entity_Id := Empty); -- Expr denotes an arbitrary expression. Par_Typ is a parent type in a -- type hierarchy. Deriv_Typ is a type derived from Par_Typ. Par_Obj is -- the formal parameter which emulates the current instance of Par_Typ. -- Deriv_Obj is the formal parameter which emulates the current instance -- of Deriv_Typ. Perform the following substitutions: -- -- * Replace a reference to Par_Obj with a reference to Deriv_Obj if -- applicable. -- -- * Replace a call to an overridden parent primitive with a call to -- the overriding derived type primitive. -- -- * Replace a call to an inherited parent primitive with a call to -- the internally-generated inherited derived type primitive. procedure Replace_Type_References (Expr : Node_Id; Typ : Entity_Id; Obj_Id : Entity_Id); -- Substitute all references of the current instance of type Typ with -- references to formal parameter Obj_Id within expression Expr. ------------------- -- Add_DIC_Check -- ------------------- procedure Add_DIC_Check (DIC_Prag : Node_Id; DIC_Expr : Node_Id; Stmts : in out List_Id) is Loc : constant Source_Ptr := Sloc (DIC_Prag); Nam : constant Name_Id := Original_Aspect_Pragma_Name (DIC_Prag); begin -- The DIC pragma is ignored, nothing left to do if Is_Ignored (DIC_Prag) then null; -- Otherwise the DIC expression must be checked at runtime. Generate: -- pragma Check (<Nam>, <DIC_Expr>); else Append_New_To (Stmts, Make_Pragma (Loc, Pragma_Identifier => Make_Identifier (Loc, Name_Check), Pragma_Argument_Associations => New_List ( Make_Pragma_Argument_Association (Loc, Expression => Make_Identifier (Loc, Nam)), Make_Pragma_Argument_Association (Loc, Expression => DIC_Expr)))); end if; end Add_DIC_Check; ----------------------- -- Add_Inherited_DIC -- ----------------------- procedure Add_Inherited_DIC (DIC_Prag : Node_Id; Par_Typ : Entity_Id; Deriv_Typ : Entity_Id; Stmts : in out List_Id) is Deriv_Proc : constant Entity_Id := DIC_Procedure (Deriv_Typ); Deriv_Obj : constant Entity_Id := First_Entity (Deriv_Proc); Par_Proc : constant Entity_Id := DIC_Procedure (Par_Typ); Par_Obj : constant Entity_Id := First_Entity (Par_Proc); Loc : constant Source_Ptr := Sloc (DIC_Prag); begin pragma Assert (Present (Deriv_Proc) and then Present (Par_Proc)); -- Verify the inherited DIC assertion expression by calling the DIC -- procedure of the parent type. -- Generate: -- <Par_Typ>DIC (Par_Typ (_object)); Append_New_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Par_Proc, Loc), Parameter_Associations => New_List ( Convert_To (Typ => Etype (Par_Obj), Expr => New_Occurrence_Of (Deriv_Obj, Loc))))); end Add_Inherited_DIC; ------------------------------ -- Add_Inherited_Tagged_DIC -- ------------------------------ procedure Add_Inherited_Tagged_DIC (DIC_Prag : Node_Id; Par_Typ : Entity_Id; Deriv_Typ : Entity_Id; Stmts : in out List_Id) is Deriv_Decl : constant Node_Id := Declaration_Node (Deriv_Typ); Deriv_Proc : constant Entity_Id := DIC_Procedure (Deriv_Typ); DIC_Args : constant List_Id := Pragma_Argument_Associations (DIC_Prag); DIC_Arg : constant Node_Id := First (DIC_Args); DIC_Expr : constant Node_Id := Expression_Copy (DIC_Arg); Par_Proc : constant Entity_Id := DIC_Procedure (Par_Typ); Expr : Node_Id; begin -- The processing of an inherited DIC assertion expression starts off -- with a copy of the original parent expression where all references -- to the parent type have already been replaced with references to -- the _object formal parameter of the parent type's DIC procedure. pragma Assert (Present (DIC_Expr)); Expr := New_Copy_Tree (DIC_Expr); -- Perform the following substitutions: -- * Replace a reference to the _object parameter of the parent -- type's DIC procedure with a reference to the _object parameter -- of the derived types' DIC procedure. -- * Replace a call to an overridden parent primitive with a call -- to the overriding derived type primitive. -- * Replace a call to an inherited parent primitive with a call to -- the internally-generated inherited derived type primitive. -- Note that primitives defined in the private part are automatically -- handled by the overriding/inheritance mechanism and do not require -- an extra replacement pass. pragma Assert (Present (Deriv_Proc) and then Present (Par_Proc)); Replace_Object_And_Primitive_References (Expr => Expr, Par_Typ => Par_Typ, Deriv_Typ => Deriv_Typ, Par_Obj => First_Formal (Par_Proc), Deriv_Obj => First_Formal (Deriv_Proc)); -- Preanalyze the DIC expression to detect errors and at the same -- time capture the visibility of the proper package part. Set_Parent (Expr, Deriv_Decl); Preanalyze_Assert_Expression (Expr, Any_Boolean); -- Once the DIC assertion expression is fully processed, add a check -- to the statements of the DIC procedure. Add_DIC_Check (DIC_Prag => DIC_Prag, DIC_Expr => Expr, Stmts => Stmts); end Add_Inherited_Tagged_DIC; ----------------- -- Add_Own_DIC -- ----------------- procedure Add_Own_DIC (DIC_Prag : Node_Id; DIC_Typ : Entity_Id; Stmts : in out List_Id) is DIC_Args : constant List_Id := Pragma_Argument_Associations (DIC_Prag); DIC_Arg : constant Node_Id := First (DIC_Args); DIC_Asp : constant Node_Id := Corresponding_Aspect (DIC_Prag); DIC_Expr : constant Node_Id := Get_Pragma_Arg (DIC_Arg); DIC_Proc : constant Entity_Id := DIC_Procedure (DIC_Typ); Obj_Id : constant Entity_Id := First_Formal (DIC_Proc); procedure Preanalyze_Own_DIC_For_ASIS; -- Preanalyze the original DIC expression of an aspect or a source -- pragma for ASIS. --------------------------------- -- Preanalyze_Own_DIC_For_ASIS -- --------------------------------- procedure Preanalyze_Own_DIC_For_ASIS is Expr : Node_Id := Empty; begin -- The DIC pragma is a source construct, preanalyze the original -- expression of the pragma. if Comes_From_Source (DIC_Prag) then Expr := DIC_Expr; -- Otherwise preanalyze the expression of the corresponding aspect elsif Present (DIC_Asp) then Expr := Expression (DIC_Asp); end if; -- The expression must be subjected to the same substitutions as -- the copy used in the generation of the runtime check. if Present (Expr) then Replace_Type_References (Expr => Expr, Typ => DIC_Typ, Obj_Id => Obj_Id); Preanalyze_Assert_Expression (Expr, Any_Boolean); end if; end Preanalyze_Own_DIC_For_ASIS; -- Local variables Typ_Decl : constant Node_Id := Declaration_Node (DIC_Typ); Expr : Node_Id; -- Start of processing for Add_Own_DIC begin Expr := New_Copy_Tree (DIC_Expr); -- Perform the following substitution: -- * Replace the current instance of DIC_Typ with a reference to -- the _object formal parameter of the DIC procedure. Replace_Type_References (Expr => Expr, Typ => DIC_Typ, Obj_Id => Obj_Id); -- Preanalyze the DIC expression to detect errors and at the same -- time capture the visibility of the proper package part. Set_Parent (Expr, Typ_Decl); Preanalyze_Assert_Expression (Expr, Any_Boolean); -- Save a copy of the expression with all replacements and analysis -- already taken place in case a derived type inherits the pragma. -- The copy will be used as the foundation of the derived type's own -- version of the DIC assertion expression. if Is_Tagged_Type (DIC_Typ) then Set_Expression_Copy (DIC_Arg, New_Copy_Tree (Expr)); end if; -- If the pragma comes from an aspect specification, replace the -- saved expression because all type references must be substituted -- for the call to Preanalyze_Spec_Expression in Check_Aspect_At_xxx -- routines. if Present (DIC_Asp) then Set_Entity (Identifier (DIC_Asp), New_Copy_Tree (Expr)); end if; -- Preanalyze the original DIC expression for ASIS if ASIS_Mode then Preanalyze_Own_DIC_For_ASIS; end if; -- Once the DIC assertion expression is fully processed, add a check -- to the statements of the DIC procedure. Add_DIC_Check (DIC_Prag => DIC_Prag, DIC_Expr => Expr, Stmts => Stmts); end Add_Own_DIC; --------------------------------------------- -- Replace_Object_And_Primitive_References -- --------------------------------------------- procedure Replace_Object_And_Primitive_References (Expr : Node_Id; Par_Typ : Entity_Id; Deriv_Typ : Entity_Id; Par_Obj : Entity_Id := Empty; Deriv_Obj : Entity_Id := Empty) is function Replace_Ref (Ref : Node_Id) return Traverse_Result; -- Substitute a reference to an entity with a reference to the -- corresponding entity stored in in table Primitives_Mapping. ----------------- -- Replace_Ref -- ----------------- function Replace_Ref (Ref : Node_Id) return Traverse_Result is Context : constant Node_Id := Parent (Ref); Loc : constant Source_Ptr := Sloc (Ref); New_Id : Entity_Id; New_Ref : Node_Id; Ref_Id : Entity_Id; Result : Traverse_Result; begin Result := OK; -- The current node denotes a reference if Nkind (Ref) in N_Has_Entity and then Present (Entity (Ref)) then Ref_Id := Entity (Ref); New_Id := Primitives_Mapping.Get (Ref_Id); -- The reference mentions a parent type primitive which has a -- corresponding derived type primitive. if Present (New_Id) then New_Ref := New_Occurrence_Of (New_Id, Loc); -- The reference mentions the _object parameter of the parent -- type's DIC procedure. elsif Present (Par_Obj) and then Present (Deriv_Obj) and then Ref_Id = Par_Obj then New_Ref := New_Occurrence_Of (Deriv_Obj, Loc); -- The reference to _object acts as an actual parameter in a -- subprogram call which may be invoking a primitive of the -- parent type: -- Primitive (... _object ...); -- The parent type primitive may not be overridden nor -- inherited when it is declared after the derived type -- definition: -- type Parent is tagged private; -- type Child is new Parent with private; -- procedure Primitive (Obj : Parent); -- In this scenario the _object parameter is converted to -- the parent type. if Nkind_In (Context, N_Function_Call, N_Procedure_Call_Statement) and then No (Primitives_Mapping.Get (Entity (Name (Context)))) then New_Ref := Convert_To (Par_Typ, New_Ref); -- Do not process the generated type conversion because -- both the parent type and the derived type are in the -- Primitives_Mapping table. This will clobber the type -- conversion by resetting its subtype mark. Result := Skip; end if; -- Otherwise there is nothing to replace else New_Ref := Empty; end if; if Present (New_Ref) then Rewrite (Ref, New_Ref); -- Update the return type when the context of the reference -- acts as the name of a function call. Note that the update -- should not be performed when the reference appears as an -- actual in the call. if Nkind (Context) = N_Function_Call and then Name (Context) = Ref then Set_Etype (Context, Etype (New_Id)); end if; end if; end if; -- Reanalyze the reference due to potential replacements if Nkind (Ref) in N_Has_Etype then Set_Analyzed (Ref, False); end if; return Result; end Replace_Ref; procedure Replace_Refs is new Traverse_Proc (Replace_Ref); -- Start of processing for Replace_Object_And_Primitive_References begin -- Map each primitive operation of the parent type to the proper -- primitive of the derived type. Update_Primitives_Mapping_Of_Types (Par_Typ => Par_Typ, Deriv_Typ => Deriv_Typ); -- Inspect the input expression and perform substitutions where -- necessary. Replace_Refs (Expr); end Replace_Object_And_Primitive_References; ----------------------------- -- Replace_Type_References -- ----------------------------- procedure Replace_Type_References (Expr : Node_Id; Typ : Entity_Id; Obj_Id : Entity_Id) is procedure Replace_Type_Ref (N : Node_Id); -- Substitute a single reference of the current instance of type Typ -- with a reference to Obj_Id. ---------------------- -- Replace_Type_Ref -- ---------------------- procedure Replace_Type_Ref (N : Node_Id) is Ref : Node_Id; begin -- Decorate the reference to Typ even though it may be rewritten -- further down. This is done for two reasons: -- 1) ASIS has all necessary semantic information in the -- original tree. -- 2) Routines which examine properties of the Original_Node -- have some semantic information. if Nkind (N) = N_Identifier then Set_Entity (N, Typ); Set_Etype (N, Typ); elsif Nkind (N) = N_Selected_Component then Analyze (Prefix (N)); Set_Entity (Selector_Name (N), Typ); Set_Etype (Selector_Name (N), Typ); end if; -- Perform the following substitution: -- Typ --> _object Ref := Make_Identifier (Sloc (N), Chars (Obj_Id)); Set_Entity (Ref, Obj_Id); Set_Etype (Ref, Typ); Rewrite (N, Ref); Set_Comes_From_Source (N, True); end Replace_Type_Ref; procedure Replace_Type_Refs is new Replace_Type_References_Generic (Replace_Type_Ref); -- Start of processing for Replace_Type_References begin Replace_Type_Refs (Expr, Typ); end Replace_Type_References; -- Local variables Loc : constant Source_Ptr := Sloc (Typ); DIC_Prag : Node_Id; DIC_Typ : Entity_Id; Dummy_1 : Entity_Id; Dummy_2 : Entity_Id; Mode : Ghost_Mode_Type; Proc_Body : Node_Id; Proc_Body_Id : Entity_Id; Proc_Decl : Node_Id; Proc_Id : Entity_Id; Stmts : List_Id := No_List; Work_Typ : Entity_Id; -- The working type -- Start of processing for Build_DIC_Procedure_Body begin Work_Typ := Base_Type (Typ); -- Do not process class-wide types as these are Itypes, but lack a first -- subtype (see below). if Is_Class_Wide_Type (Work_Typ) then return; -- Do not process the underlying full view of a private type. There is -- no way to get back to the partial view, plus the body will be built -- by the full view or the base type. elsif Is_Underlying_Full_View (Work_Typ) then return; -- Use the first subtype when dealing with various base types elsif Is_Itype (Work_Typ) then Work_Typ := First_Subtype (Work_Typ); -- The input denotes the corresponding record type of a protected or a -- task type. Work with the concurrent type because the corresponding -- record type may not be visible to clients of the type. elsif Ekind (Work_Typ) = E_Record_Type and then Is_Concurrent_Record_Type (Work_Typ) then Work_Typ := Corresponding_Concurrent_Type (Work_Typ); end if; -- The working type may be subject to pragma Ghost. Set the mode now to -- ensure that the DIC procedure is properly marked as Ghost. Set_Ghost_Mode (Work_Typ, Mode); -- The working type must be either define a DIC pragma of its own or -- inherit one from a parent type. pragma Assert (Has_DIC (Work_Typ)); -- Recover the type which defines the DIC pragma. This is either the -- working type itself or a parent type when the pragma is inherited. DIC_Typ := Find_DIC_Type (Work_Typ); pragma Assert (Present (DIC_Typ)); DIC_Prag := Get_Pragma (DIC_Typ, Pragma_Default_Initial_Condition); pragma Assert (Present (DIC_Prag)); -- Nothing to do if pragma DIC appears without an argument or its sole -- argument is "null". if not Is_Verifiable_DIC_Pragma (DIC_Prag) then goto Leave; end if; -- The working type may lack a DIC procedure declaration. This may be -- due to several reasons: -- * The working type's own DIC pragma does not contain a verifiable -- assertion expression. In this case there is no need to build a -- DIC procedure because there is nothing to check. -- * The working type derives from a parent type. In this case a DIC -- procedure should be built only when the inherited DIC pragma has -- a verifiable assertion expression. Proc_Id := DIC_Procedure (Work_Typ); -- Build a DIC procedure declaration when the working type derives from -- a parent type. if No (Proc_Id) then Build_DIC_Procedure_Declaration (Work_Typ); Proc_Id := DIC_Procedure (Work_Typ); end if; -- At this point there should be a DIC procedure declaration pragma Assert (Present (Proc_Id)); Proc_Decl := Unit_Declaration_Node (Proc_Id); -- Nothing to do if the DIC procedure already has a body if Present (Corresponding_Body (Proc_Decl)) then goto Leave; end if; -- Emulate the environment of the DIC procedure by installing its scope -- and formal parameters. Push_Scope (Proc_Id); Install_Formals (Proc_Id); -- The working type defines its own DIC pragma. Replace the current -- instance of the working type with the formal of the DIC procedure. -- Note that there is no need to consider inherited DIC pragmas from -- parent types because the working type's DIC pragma "hides" all -- inherited DIC pragmas. if Has_Own_DIC (Work_Typ) then pragma Assert (DIC_Typ = Work_Typ); Add_Own_DIC (DIC_Prag => DIC_Prag, DIC_Typ => DIC_Typ, Stmts => Stmts); -- Otherwise the working type inherits a DIC pragma from a parent type else pragma Assert (Has_Inherited_DIC (Work_Typ)); pragma Assert (DIC_Typ /= Work_Typ); -- The working type is tagged. The verification of the assertion -- expression is subject to the same semantics as class-wide pre- -- and postconditions. if Is_Tagged_Type (Work_Typ) then Add_Inherited_Tagged_DIC (DIC_Prag => DIC_Prag, Par_Typ => DIC_Typ, Deriv_Typ => Work_Typ, Stmts => Stmts); -- Otherwise the working type is not tagged. Verify the assertion -- expression of the inherited DIC pragma by directly calling the -- DIC procedure of the parent type. else Add_Inherited_DIC (DIC_Prag => DIC_Prag, Par_Typ => DIC_Typ, Deriv_Typ => Work_Typ, Stmts => Stmts); end if; end if; End_Scope; -- Produce an empty completing body in the following cases: -- * Assertions are disabled -- * The DIC Assertion_Policy is Ignore -- * Pragma DIC appears without an argument -- * Pragma DIC appears with argument "null" if No (Stmts) then Stmts := New_List (Make_Null_Statement (Loc)); end if; -- Generate: -- procedure <Work_Typ>DIC (_object : <Work_Typ>) is -- begin -- <Stmts> -- end <Work_Typ>DIC; Proc_Body := Make_Subprogram_Body (Loc, Specification => Copy_Subprogram_Spec (Parent (Proc_Id)), Declarations => Empty_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts)); Proc_Body_Id := Defining_Entity (Proc_Body); -- Perform minor decoration in case the body is not analyzed Set_Ekind (Proc_Body_Id, E_Subprogram_Body); Set_Etype (Proc_Body_Id, Standard_Void_Type); Set_Scope (Proc_Body_Id, Current_Scope); -- Link both spec and body to avoid generating duplicates Set_Corresponding_Body (Proc_Decl, Proc_Body_Id); Set_Corresponding_Spec (Proc_Body, Proc_Id); -- The body should not be inserted into the tree when the context is -- ASIS or a generic unit because it is not part of the template. Note -- that the body must still be generated in order to resolve the DIC -- assertion expression. if ASIS_Mode or Inside_A_Generic then null; -- Semi-insert the body into the tree for GNATprove by setting its -- Parent field. This allows for proper upstream tree traversals. elsif GNATprove_Mode then Set_Parent (Proc_Body, Parent (Declaration_Node (Work_Typ))); -- Otherwise the body is part of the freezing actions of the working -- type. else Append_Freeze_Action (Work_Typ, Proc_Body); end if; <<Leave>> Restore_Ghost_Mode (Mode); end Build_DIC_Procedure_Body; ------------------------------------- -- Build_DIC_Procedure_Declaration -- ------------------------------------- -- WARNING: This routine manages Ghost regions. Return statements must be -- replaced by gotos which jump to the end of the routine and restore the -- Ghost mode. procedure Build_DIC_Procedure_Declaration (Typ : Entity_Id) is Loc : constant Source_Ptr := Sloc (Typ); DIC_Prag : Node_Id; DIC_Typ : Entity_Id; Mode : Ghost_Mode_Type; Proc_Decl : Node_Id; Proc_Id : Entity_Id; Typ_Decl : Node_Id; CRec_Typ : Entity_Id; -- The corresponding record type of Full_Typ Full_Base : Entity_Id; -- The base type of Full_Typ Full_Typ : Entity_Id; -- The full view of working type Obj_Id : Entity_Id; -- The _object formal parameter of the DIC procedure Priv_Typ : Entity_Id; -- The partial view of working type Work_Typ : Entity_Id; -- The working type begin Work_Typ := Base_Type (Typ); -- Do not process class-wide types as these are Itypes, but lack a first -- subtype (see below). if Is_Class_Wide_Type (Work_Typ) then return; -- Do not process the underlying full view of a private type. There is -- no way to get back to the partial view, plus the body will be built -- by the full view or the base type. elsif Is_Underlying_Full_View (Work_Typ) then return; -- Use the first subtype when dealing with various base types elsif Is_Itype (Work_Typ) then Work_Typ := First_Subtype (Work_Typ); -- The input denotes the corresponding record type of a protected or a -- task type. Work with the concurrent type because the corresponding -- record type may not be visible to clients of the type. elsif Ekind (Work_Typ) = E_Record_Type and then Is_Concurrent_Record_Type (Work_Typ) then Work_Typ := Corresponding_Concurrent_Type (Work_Typ); end if; -- The working type may be subject to pragma Ghost. Set the mode now to -- ensure that the DIC procedure is properly marked as Ghost. Set_Ghost_Mode (Work_Typ, Mode); -- The type must be either subject to a DIC pragma or inherit one from a -- parent type. pragma Assert (Has_DIC (Work_Typ)); -- Recover the type which defines the DIC pragma. This is either the -- working type itself or a parent type when the pragma is inherited. DIC_Typ := Find_DIC_Type (Work_Typ); pragma Assert (Present (DIC_Typ)); DIC_Prag := Get_Pragma (DIC_Typ, Pragma_Default_Initial_Condition); pragma Assert (Present (DIC_Prag)); -- Nothing to do if pragma DIC appears without an argument or its sole -- argument is "null". if not Is_Verifiable_DIC_Pragma (DIC_Prag) then goto Leave; -- Nothing to do if the type already has a DIC procedure elsif Present (DIC_Procedure (Work_Typ)) then goto Leave; end if; Proc_Id := Make_Defining_Identifier (Loc, Chars => New_External_Name (Chars (Work_Typ), "Default_Initial_Condition")); -- Perform minor decoration in case the declaration is not analyzed Set_Ekind (Proc_Id, E_Procedure); Set_Etype (Proc_Id, Standard_Void_Type); Set_Scope (Proc_Id, Current_Scope); Set_Is_DIC_Procedure (Proc_Id); Set_DIC_Procedure (Work_Typ, Proc_Id); -- The DIC procedure requires debug info when the assertion expression -- is subject to Source Coverage Obligations. if Opt.Generate_SCO then Set_Needs_Debug_Info (Proc_Id); end if; -- Obtain all views of the input type Get_Views (Work_Typ, Priv_Typ, Full_Typ, Full_Base, CRec_Typ); -- Associate the DIC procedure and various relevant flags with all views Propagate_DIC_Attributes (Priv_Typ, From_Typ => Work_Typ); Propagate_DIC_Attributes (Full_Typ, From_Typ => Work_Typ); Propagate_DIC_Attributes (Full_Base, From_Typ => Work_Typ); Propagate_DIC_Attributes (CRec_Typ, From_Typ => Work_Typ); -- The declaration of the DIC procedure must be inserted after the -- declaration of the partial view as this allows for proper external -- visibility. if Present (Priv_Typ) then Typ_Decl := Declaration_Node (Priv_Typ); -- Derived types with the full view as parent do not have a partial -- view. Insert the DIC procedure after the derived type. else Typ_Decl := Declaration_Node (Full_Typ); end if; -- The type should have a declarative node pragma Assert (Present (Typ_Decl)); -- Create the formal parameter which emulates the variable-like behavior -- of the type's current instance. Obj_Id := Make_Defining_Identifier (Loc, Chars => Name_uObject); -- Perform minor decoration in case the declaration is not analyzed Set_Ekind (Obj_Id, E_In_Parameter); Set_Etype (Obj_Id, Work_Typ); Set_Scope (Obj_Id, Proc_Id); Set_First_Entity (Proc_Id, Obj_Id); -- Generate: -- procedure <Work_Typ>DIC (_object : <Work_Typ>); Proc_Decl := Make_Subprogram_Declaration (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Proc_Id, Parameter_Specifications => New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Obj_Id, Parameter_Type => New_Occurrence_Of (Work_Typ, Loc))))); -- The declaration should not be inserted into the tree when the context -- is ASIS or a generic unit because it is not part of the template. if ASIS_Mode or Inside_A_Generic then null; -- Semi-insert the declaration into the tree for GNATprove by setting -- its Parent field. This allows for proper upstream tree traversals. elsif GNATprove_Mode then Set_Parent (Proc_Decl, Parent (Typ_Decl)); -- Otherwise insert the declaration else Insert_After_And_Analyze (Typ_Decl, Proc_Decl); end if; <<Leave>> Restore_Ghost_Mode (Mode); end Build_DIC_Procedure_Declaration; -------------------------- -- Build_Procedure_Form -- -------------------------- procedure Build_Procedure_Form (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Subp : constant Entity_Id := Defining_Entity (N); Func_Formal : Entity_Id; Proc_Formals : List_Id; Proc_Decl : Node_Id; begin -- No action needed if this transformation was already done, or in case -- of subprogram renaming declarations. if Nkind (Specification (N)) = N_Procedure_Specification or else Nkind (N) = N_Subprogram_Renaming_Declaration then return; end if; -- Ditto when dealing with an expression function, where both the -- original expression and the generated declaration end up being -- expanded here. if Rewritten_For_C (Subp) then return; end if; Proc_Formals := New_List; -- Create a list of formal parameters with the same types as the -- function. Func_Formal := First_Formal (Subp); while Present (Func_Formal) loop Append_To (Proc_Formals, Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Chars (Func_Formal)), Parameter_Type => New_Occurrence_Of (Etype (Func_Formal), Loc))); Next_Formal (Func_Formal); end loop; -- Add an extra out parameter to carry the function result Name_Len := 6; Name_Buffer (1 .. Name_Len) := "RESULT"; Append_To (Proc_Formals, Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Chars => Name_Find), Out_Present => True, Parameter_Type => New_Occurrence_Of (Etype (Subp), Loc))); -- The new procedure declaration is inserted immediately after the -- function declaration. The processing in Build_Procedure_Body_Form -- relies on this order. Proc_Decl := Make_Subprogram_Declaration (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Make_Defining_Identifier (Loc, Chars (Subp)), Parameter_Specifications => Proc_Formals)); Insert_After_And_Analyze (Unit_Declaration_Node (Subp), Proc_Decl); -- Entity of procedure must remain invisible so that it does not -- overload subsequent references to the original function. Set_Is_Immediately_Visible (Defining_Entity (Proc_Decl), False); -- Mark the function as having a procedure form and link the function -- and its internally built procedure. Set_Rewritten_For_C (Subp); Set_Corresponding_Procedure (Subp, Defining_Entity (Proc_Decl)); Set_Corresponding_Function (Defining_Entity (Proc_Decl), Subp); end Build_Procedure_Form; ------------------------ -- Build_Runtime_Call -- ------------------------ function Build_Runtime_Call (Loc : Source_Ptr; RE : RE_Id) return Node_Id is begin -- If entity is not available, we can skip making the call (this avoids -- junk duplicated error messages in a number of cases). if not RTE_Available (RE) then return Make_Null_Statement (Loc); else return Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE), Loc)); end if; end Build_Runtime_Call; ------------------------ -- Build_SS_Mark_Call -- ------------------------ function Build_SS_Mark_Call (Loc : Source_Ptr; Mark : Entity_Id) return Node_Id is begin -- Generate: -- Mark : constant Mark_Id := SS_Mark; return Make_Object_Declaration (Loc, Defining_Identifier => Mark, Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Mark_Id), Loc), Expression => Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_SS_Mark), Loc))); end Build_SS_Mark_Call; --------------------------- -- Build_SS_Release_Call -- --------------------------- function Build_SS_Release_Call (Loc : Source_Ptr; Mark : Entity_Id) return Node_Id is begin -- Generate: -- SS_Release (Mark); return Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_SS_Release), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Mark, Loc))); end Build_SS_Release_Call; ---------------------------- -- Build_Task_Array_Image -- ---------------------------- -- This function generates the body for a function that constructs the -- image string for a task that is an array component. The function is -- local to the init proc for the array type, and is called for each one -- of the components. The constructed image has the form of an indexed -- component, whose prefix is the outer variable of the array type. -- The n-dimensional array type has known indexes Index, Index2... -- Id_Ref is an indexed component form created by the enclosing init proc. -- Its successive indexes are Val1, Val2, ... which are the loop variables -- in the loops that call the individual task init proc on each component. -- The generated function has the following structure: -- function F return String is -- Pref : string renames Task_Name; -- T1 : String := Index1'Image (Val1); -- ... -- Tn : String := indexn'image (Valn); -- Len : Integer := T1'Length + ... + Tn'Length + n + 1; -- -- Len includes commas and the end parentheses. -- Res : String (1..Len); -- Pos : Integer := Pref'Length; -- -- begin -- Res (1 .. Pos) := Pref; -- Pos := Pos + 1; -- Res (Pos) := '('; -- Pos := Pos + 1; -- Res (Pos .. Pos + T1'Length - 1) := T1; -- Pos := Pos + T1'Length; -- Res (Pos) := '.'; -- Pos := Pos + 1; -- ... -- Res (Pos .. Pos + Tn'Length - 1) := Tn; -- Res (Len) := ')'; -- -- return Res; -- end F; -- -- Needless to say, multidimensional arrays of tasks are rare enough that -- the bulkiness of this code is not really a concern. function Build_Task_Array_Image (Loc : Source_Ptr; Id_Ref : Node_Id; A_Type : Entity_Id; Dyn : Boolean := False) return Node_Id is Dims : constant Nat := Number_Dimensions (A_Type); -- Number of dimensions for array of tasks Temps : array (1 .. Dims) of Entity_Id; -- Array of temporaries to hold string for each index Indx : Node_Id; -- Index expression Len : Entity_Id; -- Total length of generated name Pos : Entity_Id; -- Running index for substring assignments Pref : constant Entity_Id := Make_Temporary (Loc, 'P'); -- Name of enclosing variable, prefix of resulting name Res : Entity_Id; -- String to hold result Val : Node_Id; -- Value of successive indexes Sum : Node_Id; -- Expression to compute total size of string T : Entity_Id; -- Entity for name at one index position Decls : constant List_Id := New_List; Stats : constant List_Id := New_List; begin -- For a dynamic task, the name comes from the target variable. For a -- static one it is a formal of the enclosing init proc. if Dyn then Get_Name_String (Chars (Entity (Prefix (Id_Ref)))); Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Pref, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_String_Literal (Loc, Strval => String_From_Name_Buffer))); else Append_To (Decls, Make_Object_Renaming_Declaration (Loc, Defining_Identifier => Pref, Subtype_Mark => New_Occurrence_Of (Standard_String, Loc), Name => Make_Identifier (Loc, Name_uTask_Name))); end if; Indx := First_Index (A_Type); Val := First (Expressions (Id_Ref)); for J in 1 .. Dims loop T := Make_Temporary (Loc, 'T'); Temps (J) := T; Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => T, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_Attribute_Reference (Loc, Attribute_Name => Name_Image, Prefix => New_Occurrence_Of (Etype (Indx), Loc), Expressions => New_List (New_Copy_Tree (Val))))); Next_Index (Indx); Next (Val); end loop; Sum := Make_Integer_Literal (Loc, Dims + 1); Sum := Make_Op_Add (Loc, Left_Opnd => Sum, Right_Opnd => Make_Attribute_Reference (Loc, Attribute_Name => Name_Length, Prefix => New_Occurrence_Of (Pref, Loc), Expressions => New_List (Make_Integer_Literal (Loc, 1)))); for J in 1 .. Dims loop Sum := Make_Op_Add (Loc, Left_Opnd => Sum, Right_Opnd => Make_Attribute_Reference (Loc, Attribute_Name => Name_Length, Prefix => New_Occurrence_Of (Temps (J), Loc), Expressions => New_List (Make_Integer_Literal (Loc, 1)))); end loop; Build_Task_Image_Prefix (Loc, Len, Res, Pos, Pref, Sum, Decls, Stats); Set_Character_Literal_Name (Char_Code (Character'Pos ('('))); Append_To (Stats, Make_Assignment_Statement (Loc, Name => Make_Indexed_Component (Loc, Prefix => New_Occurrence_Of (Res, Loc), Expressions => New_List (New_Occurrence_Of (Pos, Loc))), Expression => Make_Character_Literal (Loc, Chars => Name_Find, Char_Literal_Value => UI_From_Int (Character'Pos ('('))))); Append_To (Stats, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Pos, Loc), Expression => Make_Op_Add (Loc, Left_Opnd => New_Occurrence_Of (Pos, Loc), Right_Opnd => Make_Integer_Literal (Loc, 1)))); for J in 1 .. Dims loop Append_To (Stats, Make_Assignment_Statement (Loc, Name => Make_Slice (Loc, Prefix => New_Occurrence_Of (Res, Loc), Discrete_Range => Make_Range (Loc, Low_Bound => New_Occurrence_Of (Pos, Loc), High_Bound => Make_Op_Subtract (Loc, Left_Opnd => Make_Op_Add (Loc, Left_Opnd => New_Occurrence_Of (Pos, Loc), Right_Opnd => Make_Attribute_Reference (Loc, Attribute_Name => Name_Length, Prefix => New_Occurrence_Of (Temps (J), Loc), Expressions => New_List (Make_Integer_Literal (Loc, 1)))), Right_Opnd => Make_Integer_Literal (Loc, 1)))), Expression => New_Occurrence_Of (Temps (J), Loc))); if J < Dims then Append_To (Stats, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Pos, Loc), Expression => Make_Op_Add (Loc, Left_Opnd => New_Occurrence_Of (Pos, Loc), Right_Opnd => Make_Attribute_Reference (Loc, Attribute_Name => Name_Length, Prefix => New_Occurrence_Of (Temps (J), Loc), Expressions => New_List (Make_Integer_Literal (Loc, 1)))))); Set_Character_Literal_Name (Char_Code (Character'Pos (','))); Append_To (Stats, Make_Assignment_Statement (Loc, Name => Make_Indexed_Component (Loc, Prefix => New_Occurrence_Of (Res, Loc), Expressions => New_List (New_Occurrence_Of (Pos, Loc))), Expression => Make_Character_Literal (Loc, Chars => Name_Find, Char_Literal_Value => UI_From_Int (Character'Pos (','))))); Append_To (Stats, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Pos, Loc), Expression => Make_Op_Add (Loc, Left_Opnd => New_Occurrence_Of (Pos, Loc), Right_Opnd => Make_Integer_Literal (Loc, 1)))); end if; end loop; Set_Character_Literal_Name (Char_Code (Character'Pos (')'))); Append_To (Stats, Make_Assignment_Statement (Loc, Name => Make_Indexed_Component (Loc, Prefix => New_Occurrence_Of (Res, Loc), Expressions => New_List (New_Occurrence_Of (Len, Loc))), Expression => Make_Character_Literal (Loc, Chars => Name_Find, Char_Literal_Value => UI_From_Int (Character'Pos (')'))))); return Build_Task_Image_Function (Loc, Decls, Stats, Res); end Build_Task_Array_Image; ---------------------------- -- Build_Task_Image_Decls -- ---------------------------- function Build_Task_Image_Decls (Loc : Source_Ptr; Id_Ref : Node_Id; A_Type : Entity_Id; In_Init_Proc : Boolean := False) return List_Id is Decls : constant List_Id := New_List; T_Id : Entity_Id := Empty; Decl : Node_Id; Expr : Node_Id := Empty; Fun : Node_Id := Empty; Is_Dyn : constant Boolean := Nkind (Parent (Id_Ref)) = N_Assignment_Statement and then Nkind (Expression (Parent (Id_Ref))) = N_Allocator; begin -- If Discard_Names or No_Implicit_Heap_Allocations are in effect, -- generate a dummy declaration only. if Restriction_Active (No_Implicit_Heap_Allocations) or else Global_Discard_Names then T_Id := Make_Temporary (Loc, 'J'); Name_Len := 0; return New_List ( Make_Object_Declaration (Loc, Defining_Identifier => T_Id, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_String_Literal (Loc, Strval => String_From_Name_Buffer))); else if Nkind (Id_Ref) = N_Identifier or else Nkind (Id_Ref) = N_Defining_Identifier then -- For a simple variable, the image of the task is built from -- the name of the variable. To avoid possible conflict with the -- anonymous type created for a single protected object, add a -- numeric suffix. T_Id := Make_Defining_Identifier (Loc, New_External_Name (Chars (Id_Ref), 'T', 1)); Get_Name_String (Chars (Id_Ref)); Expr := Make_String_Literal (Loc, Strval => String_From_Name_Buffer); elsif Nkind (Id_Ref) = N_Selected_Component then T_Id := Make_Defining_Identifier (Loc, New_External_Name (Chars (Selector_Name (Id_Ref)), 'T')); Fun := Build_Task_Record_Image (Loc, Id_Ref, Is_Dyn); elsif Nkind (Id_Ref) = N_Indexed_Component then T_Id := Make_Defining_Identifier (Loc, New_External_Name (Chars (A_Type), 'N')); Fun := Build_Task_Array_Image (Loc, Id_Ref, A_Type, Is_Dyn); end if; end if; if Present (Fun) then Append (Fun, Decls); Expr := Make_Function_Call (Loc, Name => New_Occurrence_Of (Defining_Entity (Fun), Loc)); if not In_Init_Proc then Set_Uses_Sec_Stack (Defining_Entity (Fun)); end if; end if; Decl := Make_Object_Declaration (Loc, Defining_Identifier => T_Id, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Constant_Present => True, Expression => Expr); Append (Decl, Decls); return Decls; end Build_Task_Image_Decls; ------------------------------- -- Build_Task_Image_Function -- ------------------------------- function Build_Task_Image_Function (Loc : Source_Ptr; Decls : List_Id; Stats : List_Id; Res : Entity_Id) return Node_Id is Spec : Node_Id; begin Append_To (Stats, Make_Simple_Return_Statement (Loc, Expression => New_Occurrence_Of (Res, Loc))); Spec := Make_Function_Specification (Loc, Defining_Unit_Name => Make_Temporary (Loc, 'F'), Result_Definition => New_Occurrence_Of (Standard_String, Loc)); -- Calls to 'Image use the secondary stack, which must be cleaned up -- after the task name is built. return Make_Subprogram_Body (Loc, Specification => Spec, Declarations => Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Stats)); end Build_Task_Image_Function; ----------------------------- -- Build_Task_Image_Prefix -- ----------------------------- procedure Build_Task_Image_Prefix (Loc : Source_Ptr; Len : out Entity_Id; Res : out Entity_Id; Pos : out Entity_Id; Prefix : Entity_Id; Sum : Node_Id; Decls : List_Id; Stats : List_Id) is begin Len := Make_Temporary (Loc, 'L', Sum); Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Len, Object_Definition => New_Occurrence_Of (Standard_Integer, Loc), Expression => Sum)); Res := Make_Temporary (Loc, 'R'); Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Res, Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (Standard_String, Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( Make_Range (Loc, Low_Bound => Make_Integer_Literal (Loc, 1), High_Bound => New_Occurrence_Of (Len, Loc))))))); -- Indicate that the result is an internal temporary, so it does not -- receive a bogus initialization when declaration is expanded. This -- is both efficient, and prevents anomalies in the handling of -- dynamic objects on the secondary stack. Set_Is_Internal (Res); Pos := Make_Temporary (Loc, 'P'); Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Pos, Object_Definition => New_Occurrence_Of (Standard_Integer, Loc))); -- Pos := Prefix'Length; Append_To (Stats, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Pos, Loc), Expression => Make_Attribute_Reference (Loc, Attribute_Name => Name_Length, Prefix => New_Occurrence_Of (Prefix, Loc), Expressions => New_List (Make_Integer_Literal (Loc, 1))))); -- Res (1 .. Pos) := Prefix; Append_To (Stats, Make_Assignment_Statement (Loc, Name => Make_Slice (Loc, Prefix => New_Occurrence_Of (Res, Loc), Discrete_Range => Make_Range (Loc, Low_Bound => Make_Integer_Literal (Loc, 1), High_Bound => New_Occurrence_Of (Pos, Loc))), Expression => New_Occurrence_Of (Prefix, Loc))); Append_To (Stats, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Pos, Loc), Expression => Make_Op_Add (Loc, Left_Opnd => New_Occurrence_Of (Pos, Loc), Right_Opnd => Make_Integer_Literal (Loc, 1)))); end Build_Task_Image_Prefix; ----------------------------- -- Build_Task_Record_Image -- ----------------------------- function Build_Task_Record_Image (Loc : Source_Ptr; Id_Ref : Node_Id; Dyn : Boolean := False) return Node_Id is Len : Entity_Id; -- Total length of generated name Pos : Entity_Id; -- Index into result Res : Entity_Id; -- String to hold result Pref : constant Entity_Id := Make_Temporary (Loc, 'P'); -- Name of enclosing variable, prefix of resulting name Sum : Node_Id; -- Expression to compute total size of string Sel : Entity_Id; -- Entity for selector name Decls : constant List_Id := New_List; Stats : constant List_Id := New_List; begin -- For a dynamic task, the name comes from the target variable. For a -- static one it is a formal of the enclosing init proc. if Dyn then Get_Name_String (Chars (Entity (Prefix (Id_Ref)))); Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Pref, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_String_Literal (Loc, Strval => String_From_Name_Buffer))); else Append_To (Decls, Make_Object_Renaming_Declaration (Loc, Defining_Identifier => Pref, Subtype_Mark => New_Occurrence_Of (Standard_String, Loc), Name => Make_Identifier (Loc, Name_uTask_Name))); end if; Sel := Make_Temporary (Loc, 'S'); Get_Name_String (Chars (Selector_Name (Id_Ref))); Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Sel, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_String_Literal (Loc, Strval => String_From_Name_Buffer))); Sum := Make_Integer_Literal (Loc, Nat (Name_Len + 1)); Sum := Make_Op_Add (Loc, Left_Opnd => Sum, Right_Opnd => Make_Attribute_Reference (Loc, Attribute_Name => Name_Length, Prefix => New_Occurrence_Of (Pref, Loc), Expressions => New_List (Make_Integer_Literal (Loc, 1)))); Build_Task_Image_Prefix (Loc, Len, Res, Pos, Pref, Sum, Decls, Stats); Set_Character_Literal_Name (Char_Code (Character'Pos ('.'))); -- Res (Pos) := '.'; Append_To (Stats, Make_Assignment_Statement (Loc, Name => Make_Indexed_Component (Loc, Prefix => New_Occurrence_Of (Res, Loc), Expressions => New_List (New_Occurrence_Of (Pos, Loc))), Expression => Make_Character_Literal (Loc, Chars => Name_Find, Char_Literal_Value => UI_From_Int (Character'Pos ('.'))))); Append_To (Stats, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Pos, Loc), Expression => Make_Op_Add (Loc, Left_Opnd => New_Occurrence_Of (Pos, Loc), Right_Opnd => Make_Integer_Literal (Loc, 1)))); -- Res (Pos .. Len) := Selector; Append_To (Stats, Make_Assignment_Statement (Loc, Name => Make_Slice (Loc, Prefix => New_Occurrence_Of (Res, Loc), Discrete_Range => Make_Range (Loc, Low_Bound => New_Occurrence_Of (Pos, Loc), High_Bound => New_Occurrence_Of (Len, Loc))), Expression => New_Occurrence_Of (Sel, Loc))); return Build_Task_Image_Function (Loc, Decls, Stats, Res); end Build_Task_Record_Image; --------------------------------------- -- Build_Transient_Object_Statements -- --------------------------------------- procedure Build_Transient_Object_Statements (Obj_Decl : Node_Id; Fin_Call : out Node_Id; Hook_Assign : out Node_Id; Hook_Clear : out Node_Id; Hook_Decl : out Node_Id; Ptr_Decl : out Node_Id; Finalize_Obj : Boolean := True) is Loc : constant Source_Ptr := Sloc (Obj_Decl); Obj_Id : constant Entity_Id := Defining_Entity (Obj_Decl); Obj_Typ : constant Entity_Id := Base_Type (Etype (Obj_Id)); Desig_Typ : Entity_Id; Hook_Expr : Node_Id; Hook_Id : Entity_Id; Obj_Ref : Node_Id; Ptr_Typ : Entity_Id; begin -- Recover the type of the object Desig_Typ := Obj_Typ; if Is_Access_Type (Desig_Typ) then Desig_Typ := Available_View (Designated_Type (Desig_Typ)); end if; -- Create an access type which provides a reference to the transient -- object. Generate: -- type Ptr_Typ is access all Desig_Typ; Ptr_Typ := Make_Temporary (Loc, 'A'); Set_Ekind (Ptr_Typ, E_General_Access_Type); Set_Directly_Designated_Type (Ptr_Typ, Desig_Typ); Ptr_Decl := 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))); -- Create a temporary check which acts as a hook to the transient -- object. Generate: -- Hook : Ptr_Typ := null; Hook_Id := Make_Temporary (Loc, 'T'); Set_Ekind (Hook_Id, E_Variable); Set_Etype (Hook_Id, Ptr_Typ); Hook_Decl := Make_Object_Declaration (Loc, Defining_Identifier => Hook_Id, Object_Definition => New_Occurrence_Of (Ptr_Typ, Loc), Expression => Make_Null (Loc)); -- Mark the temporary as a hook. This signals the machinery in -- Build_Finalizer to recognize this special case. Set_Status_Flag_Or_Transient_Decl (Hook_Id, Obj_Decl); -- Hook the transient object to the temporary. Generate: -- Hook := Ptr_Typ (Obj_Id); -- <or> -- Hool := Obj_Id'Unrestricted_Access; if Is_Access_Type (Obj_Typ) then Hook_Expr := Unchecked_Convert_To (Ptr_Typ, New_Occurrence_Of (Obj_Id, Loc)); else Hook_Expr := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Obj_Id, Loc), Attribute_Name => Name_Unrestricted_Access); end if; Hook_Assign := Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Hook_Id, Loc), Expression => Hook_Expr); -- Crear the hook prior to finalizing the object. Generate: -- Hook := null; Hook_Clear := Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Hook_Id, Loc), Expression => Make_Null (Loc)); -- Finalize the object. Generate: -- [Deep_]Finalize (Obj_Ref[.all]); if Finalize_Obj then Obj_Ref := New_Occurrence_Of (Obj_Id, Loc); if Is_Access_Type (Obj_Typ) then Obj_Ref := Make_Explicit_Dereference (Loc, Obj_Ref); Set_Etype (Obj_Ref, Desig_Typ); end if; Fin_Call := Make_Final_Call (Obj_Ref => Obj_Ref, Typ => Desig_Typ); -- Otherwise finalize the hook. Generate: -- [Deep_]Finalize (Hook.all); else Fin_Call := Make_Final_Call ( Obj_Ref => Make_Explicit_Dereference (Loc, Prefix => New_Occurrence_Of (Hook_Id, Loc)), Typ => Desig_Typ); end if; end Build_Transient_Object_Statements; ----------------------------- -- Check_Float_Op_Overflow -- ----------------------------- procedure Check_Float_Op_Overflow (N : Node_Id) is begin -- Return if no check needed if not Is_Floating_Point_Type (Etype (N)) or else not (Do_Overflow_Check (N) and then Check_Float_Overflow) -- In CodePeer_Mode, rely on the overflow check flag being set instead -- and do not expand the code for float overflow checking. or else CodePeer_Mode then return; end if; -- Otherwise we replace the expression by -- do Tnn : constant ftype := expression; -- constraint_error when not Tnn'Valid; -- in Tnn; declare Loc : constant Source_Ptr := Sloc (N); Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N); Typ : constant Entity_Id := Etype (N); begin -- Turn off the Do_Overflow_Check flag, since we are doing that work -- right here. We also set the node as analyzed to prevent infinite -- recursion from repeating the operation in the expansion. Set_Do_Overflow_Check (N, False); Set_Analyzed (N, True); -- Do the rewrite to include the check Rewrite (N, Make_Expression_With_Actions (Loc, Actions => New_List ( Make_Object_Declaration (Loc, Defining_Identifier => Tnn, Object_Definition => New_Occurrence_Of (Typ, Loc), Constant_Present => True, Expression => Relocate_Node (N)), Make_Raise_Constraint_Error (Loc, Condition => Make_Op_Not (Loc, Right_Opnd => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Tnn, Loc), Attribute_Name => Name_Valid)), Reason => CE_Overflow_Check_Failed)), Expression => New_Occurrence_Of (Tnn, Loc))); Analyze_And_Resolve (N, Typ); end; end Check_Float_Op_Overflow; ---------------------------------- -- Component_May_Be_Bit_Aligned -- ---------------------------------- function Component_May_Be_Bit_Aligned (Comp : Entity_Id) return Boolean is UT : Entity_Id; begin -- If no component clause, then everything is fine, since the back end -- never bit-misaligns by default, even if there is a pragma Packed for -- the record. if No (Comp) or else No (Component_Clause (Comp)) then return False; end if; UT := Underlying_Type (Etype (Comp)); -- It is only array and record types that cause trouble if not Is_Record_Type (UT) and then not Is_Array_Type (UT) then return False; -- If we know that we have a small (64 bits or less) record or small -- bit-packed array, then everything is fine, since the back end can -- handle these cases correctly. elsif Esize (Comp) <= 64 and then (Is_Record_Type (UT) or else Is_Bit_Packed_Array (UT)) then return False; -- Otherwise if the component is not byte aligned, we know we have the -- nasty unaligned case. elsif Normalized_First_Bit (Comp) /= Uint_0 or else Esize (Comp) mod System_Storage_Unit /= Uint_0 then return True; -- If we are large and byte aligned, then OK at this level else return False; end if; end Component_May_Be_Bit_Aligned; ---------------------------------------- -- Containing_Package_With_Ext_Axioms -- ---------------------------------------- function Containing_Package_With_Ext_Axioms (E : Entity_Id) return Entity_Id is begin -- E is the package or generic package which is externally axiomatized if Ekind_In (E, E_Generic_Package, E_Package) and then Has_Annotate_Pragma_For_External_Axiomatization (E) then return E; end if; -- If E's scope is axiomatized, E is axiomatized if Present (Scope (E)) then declare First_Ax_Parent_Scope : constant Entity_Id := Containing_Package_With_Ext_Axioms (Scope (E)); begin if Present (First_Ax_Parent_Scope) then return First_Ax_Parent_Scope; end if; end; end if; -- Otherwise, if E is a package instance, it is axiomatized if the -- corresponding generic package is axiomatized. if Ekind (E) = E_Package then declare Par : constant Node_Id := Parent (E); Decl : Node_Id; begin if Nkind (Par) = N_Defining_Program_Unit_Name then Decl := Parent (Par); else Decl := Par; end if; if Present (Generic_Parent (Decl)) then return Containing_Package_With_Ext_Axioms (Generic_Parent (Decl)); end if; end; end if; return Empty; end Containing_Package_With_Ext_Axioms; ------------------------------- -- Convert_To_Actual_Subtype -- ------------------------------- procedure Convert_To_Actual_Subtype (Exp : Entity_Id) is Act_ST : Entity_Id; begin Act_ST := Get_Actual_Subtype (Exp); if Act_ST = Etype (Exp) then return; else Rewrite (Exp, Convert_To (Act_ST, Relocate_Node (Exp))); Analyze_And_Resolve (Exp, Act_ST); end if; end Convert_To_Actual_Subtype; ----------------------------------- -- Corresponding_Runtime_Package -- ----------------------------------- function Corresponding_Runtime_Package (Typ : Entity_Id) return RTU_Id is function Has_One_Entry_And_No_Queue (T : Entity_Id) return Boolean; -- Return True if protected type T has one entry and the maximum queue -- length is one. -------------------------------- -- Has_One_Entry_And_No_Queue -- -------------------------------- function Has_One_Entry_And_No_Queue (T : Entity_Id) return Boolean is Item : Entity_Id; Is_First : Boolean := True; begin Item := First_Entity (T); while Present (Item) loop if Is_Entry (Item) then -- The protected type has more than one entry if not Is_First then return False; end if; -- The queue length is not one if not Restriction_Active (No_Entry_Queue) and then Get_Max_Queue_Length (Item) /= Uint_1 then return False; end if; Is_First := False; end if; Next_Entity (Item); end loop; return True; end Has_One_Entry_And_No_Queue; -- Local variables Pkg_Id : RTU_Id := RTU_Null; -- Start of processing for Corresponding_Runtime_Package begin pragma Assert (Is_Concurrent_Type (Typ)); if Ekind (Typ) in Protected_Kind then if Has_Entries (Typ) -- A protected type without entries that covers an interface and -- overrides the abstract routines with protected procedures is -- considered equivalent to a protected type with entries in the -- context of dispatching select statements. It is sufficient to -- check for the presence of an interface list in the declaration -- node to recognize this case. or else Present (Interface_List (Parent (Typ))) -- Protected types with interrupt handlers (when not using a -- restricted profile) are also considered equivalent to -- protected types with entries. The types which are used -- (Static_Interrupt_Protection and Dynamic_Interrupt_Protection) -- are derived from Protection_Entries. or else (Has_Attach_Handler (Typ) and then not Restricted_Profile) or else Has_Interrupt_Handler (Typ) then if Abort_Allowed or else Restriction_Active (No_Select_Statements) = False or else not Has_One_Entry_And_No_Queue (Typ) or else (Has_Attach_Handler (Typ) and then not Restricted_Profile) then Pkg_Id := System_Tasking_Protected_Objects_Entries; else Pkg_Id := System_Tasking_Protected_Objects_Single_Entry; end if; else Pkg_Id := System_Tasking_Protected_Objects; end if; end if; return Pkg_Id; end Corresponding_Runtime_Package; ----------------------------------- -- Current_Sem_Unit_Declarations -- ----------------------------------- function Current_Sem_Unit_Declarations return List_Id is U : Node_Id := Unit (Cunit (Current_Sem_Unit)); Decls : List_Id; begin -- If the current unit is a package body, locate the visible -- declarations of the package spec. if Nkind (U) = N_Package_Body then U := Unit (Library_Unit (Cunit (Current_Sem_Unit))); end if; if Nkind (U) = N_Package_Declaration then U := Specification (U); Decls := Visible_Declarations (U); if No (Decls) then Decls := New_List; Set_Visible_Declarations (U, Decls); end if; else Decls := Declarations (U); if No (Decls) then Decls := New_List; Set_Declarations (U, Decls); end if; end if; return Decls; end Current_Sem_Unit_Declarations; ----------------------- -- Duplicate_Subexpr -- ----------------------- function Duplicate_Subexpr (Exp : Node_Id; Name_Req : Boolean := False; Renaming_Req : Boolean := False) return Node_Id is begin Remove_Side_Effects (Exp, Name_Req, Renaming_Req); return New_Copy_Tree (Exp); end Duplicate_Subexpr; --------------------------------- -- Duplicate_Subexpr_No_Checks -- --------------------------------- function Duplicate_Subexpr_No_Checks (Exp : Node_Id; Name_Req : Boolean := False; Renaming_Req : Boolean := False; Related_Id : Entity_Id := Empty; Is_Low_Bound : Boolean := False; Is_High_Bound : Boolean := False) return Node_Id is New_Exp : Node_Id; begin Remove_Side_Effects (Exp => Exp, Name_Req => Name_Req, Renaming_Req => Renaming_Req, Related_Id => Related_Id, Is_Low_Bound => Is_Low_Bound, Is_High_Bound => Is_High_Bound); New_Exp := New_Copy_Tree (Exp); Remove_Checks (New_Exp); return New_Exp; end Duplicate_Subexpr_No_Checks; ----------------------------------- -- Duplicate_Subexpr_Move_Checks -- ----------------------------------- function Duplicate_Subexpr_Move_Checks (Exp : Node_Id; Name_Req : Boolean := False; Renaming_Req : Boolean := False) return Node_Id is New_Exp : Node_Id; begin Remove_Side_Effects (Exp, Name_Req, Renaming_Req); New_Exp := New_Copy_Tree (Exp); Remove_Checks (Exp); return New_Exp; end Duplicate_Subexpr_Move_Checks; -------------------- -- Ensure_Defined -- -------------------- procedure Ensure_Defined (Typ : Entity_Id; N : Node_Id) is IR : Node_Id; begin -- An itype reference must only be created if this is a local itype, so -- that gigi can elaborate it on the proper objstack. if Is_Itype (Typ) and then Scope (Typ) = Current_Scope then IR := Make_Itype_Reference (Sloc (N)); Set_Itype (IR, Typ); Insert_Action (N, IR); end if; end Ensure_Defined; ----------------- -- Entity_Hash -- ----------------- function Entity_Hash (E : Entity_Id) return Num_Primitives is begin return Num_Primitives (E mod Primitives_Mapping_Size); end Entity_Hash; -------------------- -- Entry_Names_OK -- -------------------- function Entry_Names_OK return Boolean is begin return not Restricted_Profile and then not Global_Discard_Names and then not Restriction_Active (No_Implicit_Heap_Allocations) and then not Restriction_Active (No_Local_Allocators); end Entry_Names_OK; ------------------- -- Evaluate_Name -- ------------------- procedure Evaluate_Name (Nam : Node_Id) is K : constant Node_Kind := Nkind (Nam); begin -- For an explicit dereference, we simply force the evaluation of the -- name expression. The dereference provides a value that is the address -- for the renamed object, and it is precisely this value that we want -- to preserve. if K = N_Explicit_Dereference then Force_Evaluation (Prefix (Nam)); -- For a selected component, we simply evaluate the prefix elsif K = N_Selected_Component then Evaluate_Name (Prefix (Nam)); -- For an indexed component, or an attribute reference, we evaluate the -- prefix, which is itself a name, recursively, and then force the -- evaluation of all the subscripts (or attribute expressions). elsif Nkind_In (K, N_Indexed_Component, N_Attribute_Reference) then Evaluate_Name (Prefix (Nam)); declare E : Node_Id; begin E := First (Expressions (Nam)); while Present (E) loop Force_Evaluation (E); if Original_Node (E) /= E then Set_Do_Range_Check (E, Do_Range_Check (Original_Node (E))); end if; Next (E); end loop; end; -- For a slice, we evaluate the prefix, as for the indexed component -- case and then, if there is a range present, either directly or as the -- constraint of a discrete subtype indication, we evaluate the two -- bounds of this range. elsif K = N_Slice then Evaluate_Name (Prefix (Nam)); Evaluate_Slice_Bounds (Nam); -- For a type conversion, the expression of the conversion must be the -- name of an object, and we simply need to evaluate this name. elsif K = N_Type_Conversion then Evaluate_Name (Expression (Nam)); -- For a function call, we evaluate the call elsif K = N_Function_Call then Force_Evaluation (Nam); -- The remaining cases are direct name, operator symbol and character -- literal. In all these cases, we do nothing, since we want to -- reevaluate each time the renamed object is used. else return; end if; end Evaluate_Name; --------------------------- -- Evaluate_Slice_Bounds -- --------------------------- procedure Evaluate_Slice_Bounds (Slice : Node_Id) is DR : constant Node_Id := Discrete_Range (Slice); Constr : Node_Id; Rexpr : Node_Id; begin if Nkind (DR) = N_Range then Force_Evaluation (Low_Bound (DR)); Force_Evaluation (High_Bound (DR)); elsif Nkind (DR) = N_Subtype_Indication then Constr := Constraint (DR); if Nkind (Constr) = N_Range_Constraint then Rexpr := Range_Expression (Constr); Force_Evaluation (Low_Bound (Rexpr)); Force_Evaluation (High_Bound (Rexpr)); end if; end if; end Evaluate_Slice_Bounds; --------------------- -- Evolve_And_Then -- --------------------- procedure Evolve_And_Then (Cond : in out Node_Id; Cond1 : Node_Id) is begin if No (Cond) then Cond := Cond1; else Cond := Make_And_Then (Sloc (Cond1), Left_Opnd => Cond, Right_Opnd => Cond1); end if; end Evolve_And_Then; -------------------- -- Evolve_Or_Else -- -------------------- procedure Evolve_Or_Else (Cond : in out Node_Id; Cond1 : Node_Id) is begin if No (Cond) then Cond := Cond1; else Cond := Make_Or_Else (Sloc (Cond1), Left_Opnd => Cond, Right_Opnd => Cond1); end if; end Evolve_Or_Else; ----------------------------------------- -- Expand_Static_Predicates_In_Choices -- ----------------------------------------- procedure Expand_Static_Predicates_In_Choices (N : Node_Id) is pragma Assert (Nkind_In (N, N_Case_Statement_Alternative, N_Variant)); Choices : constant List_Id := Discrete_Choices (N); Choice : Node_Id; Next_C : Node_Id; P : Node_Id; C : Node_Id; begin Choice := First (Choices); while Present (Choice) loop Next_C := Next (Choice); -- Check for name of subtype with static predicate if Is_Entity_Name (Choice) and then Is_Type (Entity (Choice)) and then Has_Predicates (Entity (Choice)) then -- Loop through entries in predicate list, converting to choices -- and inserting in the list before the current choice. Note that -- if the list is empty, corresponding to a False predicate, then -- no choices are inserted. P := First (Static_Discrete_Predicate (Entity (Choice))); while Present (P) loop -- If low bound and high bounds are equal, copy simple choice if Expr_Value (Low_Bound (P)) = Expr_Value (High_Bound (P)) then C := New_Copy (Low_Bound (P)); -- Otherwise copy a range else C := New_Copy (P); end if; -- Change Sloc to referencing choice (rather than the Sloc of -- the predicate declaration element itself). Set_Sloc (C, Sloc (Choice)); Insert_Before (Choice, C); Next (P); end loop; -- Delete the predicated entry Remove (Choice); end if; -- Move to next choice to check Choice := Next_C; end loop; end Expand_Static_Predicates_In_Choices; ------------------------------ -- Expand_Subtype_From_Expr -- ------------------------------ -- This function is applicable for both static and dynamic allocation of -- objects which are constrained by an initial expression. Basically it -- transforms an unconstrained subtype indication into a constrained one. -- The expression may also be transformed in certain cases in order to -- avoid multiple evaluation. In the static allocation case, the general -- scheme is: -- Val : T := Expr; -- is transformed into -- Val : Constrained_Subtype_of_T := Maybe_Modified_Expr; -- -- Here are the main cases : -- -- <if Expr is a Slice> -- Val : T ([Index_Subtype (Expr)]) := Expr; -- -- <elsif Expr is a String Literal> -- Val : T (T'First .. T'First + Length (string literal) - 1) := Expr; -- -- <elsif Expr is Constrained> -- subtype T is Type_Of_Expr -- Val : T := Expr; -- -- <elsif Expr is an entity_name> -- Val : T (constraints taken from Expr) := Expr; -- -- <else> -- type Axxx is access all T; -- Rval : Axxx := Expr'ref; -- Val : T (constraints taken from Rval) := Rval.all; -- ??? note: when the Expression is allocated in the secondary stack -- we could use it directly instead of copying it by declaring -- Val : T (...) renames Rval.all procedure Expand_Subtype_From_Expr (N : Node_Id; Unc_Type : Entity_Id; Subtype_Indic : Node_Id; Exp : Node_Id; Related_Id : Entity_Id := Empty) is Loc : constant Source_Ptr := Sloc (N); Exp_Typ : constant Entity_Id := Etype (Exp); T : Entity_Id; begin -- In general we cannot build the subtype if expansion is disabled, -- because internal entities may not have been defined. However, to -- avoid some cascaded errors, we try to continue when the expression is -- an array (or string), because it is safe to compute the bounds. It is -- in fact required to do so even in a generic context, because there -- may be constants that depend on the bounds of a string literal, both -- standard string types and more generally arrays of characters. -- In GNATprove mode, these extra subtypes are not needed if GNATprove_Mode then return; end if; if not Expander_Active and then (No (Etype (Exp)) or else not Is_String_Type (Etype (Exp))) then return; end if; if Nkind (Exp) = N_Slice then declare Slice_Type : constant Entity_Id := Etype (First_Index (Exp_Typ)); begin Rewrite (Subtype_Indic, Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (Unc_Type, Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List (New_Occurrence_Of (Slice_Type, Loc))))); -- This subtype indication may be used later for constraint checks -- we better make sure that if a variable was used as a bound of -- of the original slice, its value is frozen. Evaluate_Slice_Bounds (Exp); end; elsif Ekind (Exp_Typ) = E_String_Literal_Subtype then Rewrite (Subtype_Indic, Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (Unc_Type, Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( Make_Literal_Range (Loc, Literal_Typ => Exp_Typ))))); -- If the type of the expression is an internally generated type it -- may not be necessary to create a new subtype. However there are two -- exceptions: references to the current instances, and aliased array -- object declarations for which the back end has to create a template. elsif Is_Constrained (Exp_Typ) and then not Is_Class_Wide_Type (Unc_Type) and then (Nkind (N) /= N_Object_Declaration or else not Is_Entity_Name (Expression (N)) or else not Comes_From_Source (Entity (Expression (N))) or else not Is_Array_Type (Exp_Typ) or else not Aliased_Present (N)) then if Is_Itype (Exp_Typ) then -- Within an initialization procedure, a selected component -- denotes a component of the enclosing record, and it appears as -- an actual in a call to its own initialization procedure. If -- this component depends on the outer discriminant, we must -- generate the proper actual subtype for it. if Nkind (Exp) = N_Selected_Component and then Within_Init_Proc then declare Decl : constant Node_Id := Build_Actual_Subtype_Of_Component (Exp_Typ, Exp); begin if Present (Decl) then Insert_Action (N, Decl); T := Defining_Identifier (Decl); else T := Exp_Typ; end if; end; -- No need to generate a new subtype else T := Exp_Typ; end if; else T := Make_Temporary (Loc, 'T'); Insert_Action (N, Make_Subtype_Declaration (Loc, Defining_Identifier => T, Subtype_Indication => New_Occurrence_Of (Exp_Typ, Loc))); -- This type is marked as an itype even though it has an explicit -- declaration since otherwise Is_Generic_Actual_Type can get -- set, resulting in the generation of spurious errors. (See -- sem_ch8.Analyze_Package_Renaming and sem_type.covers) Set_Is_Itype (T); Set_Associated_Node_For_Itype (T, Exp); end if; Rewrite (Subtype_Indic, New_Occurrence_Of (T, Loc)); -- Nothing needs to be done for private types with unknown discriminants -- if the underlying type is not an unconstrained composite type or it -- is an unchecked union. elsif Is_Private_Type (Unc_Type) and then Has_Unknown_Discriminants (Unc_Type) and then (not Is_Composite_Type (Underlying_Type (Unc_Type)) or else Is_Constrained (Underlying_Type (Unc_Type)) or else Is_Unchecked_Union (Underlying_Type (Unc_Type))) then null; -- Case of derived type with unknown discriminants where the parent type -- also has unknown discriminants. elsif Is_Record_Type (Unc_Type) and then not Is_Class_Wide_Type (Unc_Type) and then Has_Unknown_Discriminants (Unc_Type) and then Has_Unknown_Discriminants (Underlying_Type (Unc_Type)) then -- Nothing to be done if no underlying record view available -- If this is a limited type derived from a type with unknown -- discriminants, do not expand either, so that subsequent expansion -- of the call can add build-in-place parameters to call. if No (Underlying_Record_View (Unc_Type)) or else Is_Limited_Type (Unc_Type) then null; -- Otherwise use the Underlying_Record_View to create the proper -- constrained subtype for an object of a derived type with unknown -- discriminants. else Remove_Side_Effects (Exp); Rewrite (Subtype_Indic, Make_Subtype_From_Expr (Exp, Underlying_Record_View (Unc_Type))); end if; -- Renamings of class-wide interface types require no equivalent -- constrained type declarations because we only need to reference -- the tag component associated with the interface. The same is -- presumably true for class-wide types in general, so this test -- is broadened to include all class-wide renamings, which also -- avoids cases of unbounded recursion in Remove_Side_Effects. -- (Is this really correct, or are there some cases of class-wide -- renamings that require action in this procedure???) elsif Present (N) and then Nkind (N) = N_Object_Renaming_Declaration and then Is_Class_Wide_Type (Unc_Type) then null; -- In Ada 95 nothing to be done if the type of the expression is limited -- because in this case the expression cannot be copied, and its use can -- only be by reference. -- In Ada 2005 the context can be an object declaration whose expression -- is a function that returns in place. If the nominal subtype has -- unknown discriminants, the call still provides constraints on the -- object, and we have to create an actual subtype from it. -- If the type is class-wide, the expression is dynamically tagged and -- we do not create an actual subtype either. Ditto for an interface. -- For now this applies only if the type is immutably limited, and the -- function being called is build-in-place. This will have to be revised -- when build-in-place functions are generalized to other types. elsif Is_Limited_View (Exp_Typ) and then (Is_Class_Wide_Type (Exp_Typ) or else Is_Interface (Exp_Typ) or else not Has_Unknown_Discriminants (Exp_Typ) or else not Is_Composite_Type (Unc_Type)) then null; -- For limited objects initialized with build in place function calls, -- nothing to be done; otherwise we prematurely introduce an N_Reference -- node in the expression initializing the object, which breaks the -- circuitry that detects and adds the additional arguments to the -- called function. elsif Is_Build_In_Place_Function_Call (Exp) then null; else Remove_Side_Effects (Exp); Rewrite (Subtype_Indic, Make_Subtype_From_Expr (Exp, Unc_Type, Related_Id)); end if; end Expand_Subtype_From_Expr; ---------------------- -- Finalize_Address -- ---------------------- function Finalize_Address (Typ : Entity_Id) return Entity_Id is Utyp : Entity_Id := Typ; begin -- Handle protected class-wide or task class-wide types if Is_Class_Wide_Type (Utyp) then if Is_Concurrent_Type (Root_Type (Utyp)) then Utyp := Root_Type (Utyp); elsif Is_Private_Type (Root_Type (Utyp)) and then Present (Full_View (Root_Type (Utyp))) and then Is_Concurrent_Type (Full_View (Root_Type (Utyp))) then Utyp := Full_View (Root_Type (Utyp)); end if; end if; -- Handle private types if Is_Private_Type (Utyp) and then Present (Full_View (Utyp)) then Utyp := Full_View (Utyp); end if; -- Handle protected and task types if Is_Concurrent_Type (Utyp) and then Present (Corresponding_Record_Type (Utyp)) then Utyp := Corresponding_Record_Type (Utyp); end if; Utyp := Underlying_Type (Base_Type (Utyp)); -- Deal with untagged derivation of private views. If the parent is -- now known to be protected, the finalization routine is the one -- defined on the corresponding record of the ancestor (corresponding -- records do not automatically inherit operations, but maybe they -- should???) 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; end if; -- If the underlying_type is a subtype, we are dealing with the -- completion of a private type. We need to access the base type and -- generate a conversion to it. if Utyp /= Base_Type (Utyp) then pragma Assert (Is_Private_Type (Typ)); Utyp := Base_Type (Utyp); end if; -- When dealing with an internally built full view for a type with -- unknown discriminants, use the original record type. if Is_Underlying_Record_View (Utyp) then Utyp := Etype (Utyp); end if; return TSS (Utyp, TSS_Finalize_Address); end Finalize_Address; ------------------- -- Find_DIC_Type -- ------------------- function Find_DIC_Type (Typ : Entity_Id) return Entity_Id is Curr_Typ : Entity_Id; -- The current type being examined in the parent hierarchy traversal DIC_Typ : Entity_Id; -- The type which carries the DIC pragma. This variable denotes the -- partial view when private types are involved. Par_Typ : Entity_Id; -- The parent type of the current type. This variable denotes the full -- view when private types are involved. begin -- The input type defines its own DIC pragma, therefore it is the owner if Has_Own_DIC (Typ) then DIC_Typ := Typ; -- Otherwise the DIC pragma is inherited from a parent type else pragma Assert (Has_Inherited_DIC (Typ)); -- Climb the parent chain Curr_Typ := Typ; loop -- Inspect the parent type. Do not consider subtypes as they -- inherit the DIC attributes from their base types. DIC_Typ := Base_Type (Etype (Curr_Typ)); -- Look at the full view of a private type because the type may -- have a hidden parent introduced in the full view. Par_Typ := DIC_Typ; if Is_Private_Type (Par_Typ) and then Present (Full_View (Par_Typ)) then Par_Typ := Full_View (Par_Typ); end if; -- Stop the climb once the nearest parent type which defines a DIC -- pragma of its own is encountered or when the root of the parent -- chain is reached. exit when Has_Own_DIC (DIC_Typ) or else Curr_Typ = Par_Typ; Curr_Typ := Par_Typ; end loop; end if; return DIC_Typ; end Find_DIC_Type; ------------------------ -- Find_Interface_ADT -- ------------------------ function Find_Interface_ADT (T : Entity_Id; Iface : Entity_Id) return Elmt_Id is ADT : Elmt_Id; Typ : Entity_Id := T; begin pragma Assert (Is_Interface (Iface)); -- Handle private types if Has_Private_Declaration (Typ) and then Present (Full_View (Typ)) then Typ := Full_View (Typ); end if; -- Handle access types if Is_Access_Type (Typ) then Typ := Designated_Type (Typ); end if; -- Handle task and protected types implementing interfaces if Is_Concurrent_Type (Typ) then Typ := Corresponding_Record_Type (Typ); end if; pragma Assert (not Is_Class_Wide_Type (Typ) and then Ekind (Typ) /= E_Incomplete_Type); if Is_Ancestor (Iface, Typ, Use_Full_View => True) then return First_Elmt (Access_Disp_Table (Typ)); else ADT := Next_Elmt (Next_Elmt (First_Elmt (Access_Disp_Table (Typ)))); while Present (ADT) and then Present (Related_Type (Node (ADT))) and then Related_Type (Node (ADT)) /= Iface and then not Is_Ancestor (Iface, Related_Type (Node (ADT)), Use_Full_View => True) loop Next_Elmt (ADT); end loop; pragma Assert (Present (Related_Type (Node (ADT)))); return ADT; end if; end Find_Interface_ADT; ------------------------ -- Find_Interface_Tag -- ------------------------ function Find_Interface_Tag (T : Entity_Id; Iface : Entity_Id) return Entity_Id is AI_Tag : Entity_Id; Found : Boolean := False; Typ : Entity_Id := T; procedure Find_Tag (Typ : Entity_Id); -- Internal subprogram used to recursively climb to the ancestors -------------- -- Find_Tag -- -------------- procedure Find_Tag (Typ : Entity_Id) is AI_Elmt : Elmt_Id; AI : Node_Id; begin -- This routine does not handle the case in which the interface is an -- ancestor of Typ. That case is handled by the enclosing subprogram. pragma Assert (Typ /= Iface); -- Climb to the root type handling private types if Present (Full_View (Etype (Typ))) then if Full_View (Etype (Typ)) /= Typ then Find_Tag (Full_View (Etype (Typ))); end if; elsif Etype (Typ) /= Typ then Find_Tag (Etype (Typ)); end if; -- Traverse the list of interfaces implemented by the type if not Found and then Present (Interfaces (Typ)) and then not (Is_Empty_Elmt_List (Interfaces (Typ))) then -- Skip the tag associated with the primary table pragma Assert (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag)); AI_Tag := Next_Tag_Component (First_Tag_Component (Typ)); pragma Assert (Present (AI_Tag)); AI_Elmt := First_Elmt (Interfaces (Typ)); while Present (AI_Elmt) loop AI := Node (AI_Elmt); if AI = Iface or else Is_Ancestor (Iface, AI, Use_Full_View => True) then Found := True; return; end if; AI_Tag := Next_Tag_Component (AI_Tag); Next_Elmt (AI_Elmt); end loop; end if; end Find_Tag; -- Start of processing for Find_Interface_Tag begin pragma Assert (Is_Interface (Iface)); -- Handle access types if Is_Access_Type (Typ) then Typ := Designated_Type (Typ); end if; -- Handle class-wide types if Is_Class_Wide_Type (Typ) then Typ := Root_Type (Typ); end if; -- Handle private types if Has_Private_Declaration (Typ) and then Present (Full_View (Typ)) then Typ := Full_View (Typ); end if; -- Handle entities from the limited view if Ekind (Typ) = E_Incomplete_Type then pragma Assert (Present (Non_Limited_View (Typ))); Typ := Non_Limited_View (Typ); end if; -- Handle task and protected types implementing interfaces if Is_Concurrent_Type (Typ) then Typ := Corresponding_Record_Type (Typ); end if; -- If the interface is an ancestor of the type, then it shared the -- primary dispatch table. if Is_Ancestor (Iface, Typ, Use_Full_View => True) then pragma Assert (Etype (First_Tag_Component (Typ)) = RTE (RE_Tag)); return First_Tag_Component (Typ); -- Otherwise we need to search for its associated tag component else Find_Tag (Typ); pragma Assert (Found); return AI_Tag; end if; end Find_Interface_Tag; --------------------------- -- Find_Optional_Prim_Op -- --------------------------- function Find_Optional_Prim_Op (T : Entity_Id; Name : Name_Id) return Entity_Id is Prim : Elmt_Id; Typ : Entity_Id := T; Op : Entity_Id; begin if Is_Class_Wide_Type (Typ) then Typ := Root_Type (Typ); end if; Typ := Underlying_Type (Typ); -- Loop through primitive operations Prim := First_Elmt (Primitive_Operations (Typ)); while Present (Prim) loop Op := Node (Prim); -- We can retrieve primitive operations by name if it is an internal -- name. For equality we must check that both of its operands have -- the same type, to avoid confusion with user-defined equalities -- than may have a non-symmetric signature. exit when Chars (Op) = Name and then (Name /= Name_Op_Eq or else Etype (First_Formal (Op)) = Etype (Last_Formal (Op))); Next_Elmt (Prim); end loop; return Node (Prim); -- Empty if not found end Find_Optional_Prim_Op; --------------------------- -- Find_Optional_Prim_Op -- --------------------------- function Find_Optional_Prim_Op (T : Entity_Id; Name : TSS_Name_Type) return Entity_Id is Inher_Op : Entity_Id := Empty; Own_Op : Entity_Id := Empty; Prim_Elmt : Elmt_Id; Prim_Id : Entity_Id; Typ : Entity_Id := T; begin if Is_Class_Wide_Type (Typ) then Typ := Root_Type (Typ); end if; Typ := Underlying_Type (Typ); -- This search is based on the assertion that the dispatching version -- of the TSS routine always precedes the real primitive. Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim_Id := Node (Prim_Elmt); if Is_TSS (Prim_Id, Name) then if Present (Alias (Prim_Id)) then Inher_Op := Prim_Id; else Own_Op := Prim_Id; end if; end if; Next_Elmt (Prim_Elmt); end loop; if Present (Own_Op) then return Own_Op; elsif Present (Inher_Op) then return Inher_Op; else return Empty; end if; end Find_Optional_Prim_Op; ------------------ -- Find_Prim_Op -- ------------------ function Find_Prim_Op (T : Entity_Id; Name : Name_Id) return Entity_Id is Result : constant Entity_Id := Find_Optional_Prim_Op (T, Name); begin if No (Result) then raise Program_Error; end if; return Result; end Find_Prim_Op; ------------------ -- Find_Prim_Op -- ------------------ function Find_Prim_Op (T : Entity_Id; Name : TSS_Name_Type) return Entity_Id is Result : constant Entity_Id := Find_Optional_Prim_Op (T, Name); begin if No (Result) then raise Program_Error; end if; return Result; end Find_Prim_Op; ---------------------------- -- Find_Protection_Object -- ---------------------------- function Find_Protection_Object (Scop : Entity_Id) return Entity_Id is S : Entity_Id; begin S := Scop; while Present (S) loop if Ekind_In (S, E_Entry, E_Entry_Family, E_Function, E_Procedure) and then Present (Protection_Object (S)) then return Protection_Object (S); end if; S := Scope (S); end loop; -- If we do not find a Protection object in the scope chain, then -- something has gone wrong, most likely the object was never created. raise Program_Error; end Find_Protection_Object; -------------------------- -- Find_Protection_Type -- -------------------------- function Find_Protection_Type (Conc_Typ : Entity_Id) return Entity_Id is Comp : Entity_Id; Typ : Entity_Id := Conc_Typ; begin if Is_Concurrent_Type (Typ) then Typ := Corresponding_Record_Type (Typ); end if; -- Since restriction violations are not considered serious errors, the -- expander remains active, but may leave the corresponding record type -- malformed. In such cases, component _object is not available so do -- not look for it. if not Analyzed (Typ) then return Empty; end if; Comp := First_Component (Typ); while Present (Comp) loop if Chars (Comp) = Name_uObject then return Base_Type (Etype (Comp)); end if; Next_Component (Comp); end loop; -- The corresponding record of a protected type should always have an -- _object field. raise Program_Error; end Find_Protection_Type; ----------------------- -- Find_Hook_Context -- ----------------------- function Find_Hook_Context (N : Node_Id) return Node_Id is Par : Node_Id; Top : Node_Id; Wrapped_Node : Node_Id; -- Note: if we are in a transient scope, we want to reuse it as -- the context for actions insertion, if possible. But if N is itself -- part of the stored actions for the current transient scope, -- then we need to insert at the appropriate (inner) location in -- the not as an action on Node_To_Be_Wrapped. In_Cond_Expr : constant Boolean := Within_Case_Or_If_Expression (N); begin -- When the node is inside a case/if expression, the lifetime of any -- temporary controlled object is extended. Find a suitable insertion -- node by locating the topmost case or if expressions. if In_Cond_Expr then Par := N; Top := N; while Present (Par) loop if Nkind_In (Original_Node (Par), N_Case_Expression, N_If_Expression) then Top := Par; -- Prevent the search from going too far elsif Is_Body_Or_Package_Declaration (Par) then exit; end if; Par := Parent (Par); end loop; -- The topmost case or if expression is now recovered, but it may -- still not be the correct place to add generated code. Climb to -- find a parent that is part of a declarative or statement list, -- and is not a list of actuals in a call. Par := Top; while Present (Par) loop if Is_List_Member (Par) and then not Nkind_In (Par, N_Component_Association, N_Discriminant_Association, N_Parameter_Association, N_Pragma_Argument_Association) and then not Nkind_In (Parent (Par), N_Function_Call, N_Procedure_Call_Statement, N_Entry_Call_Statement) then return Par; -- Prevent the search from going too far elsif Is_Body_Or_Package_Declaration (Par) then exit; end if; Par := Parent (Par); end loop; return Par; else Par := N; while Present (Par) loop -- Keep climbing past various operators if Nkind (Parent (Par)) in N_Op or else Nkind_In (Parent (Par), N_And_Then, N_Or_Else) then Par := Parent (Par); else exit; end if; end loop; Top := Par; -- The node may be located in a pragma in which case return the -- pragma itself: -- pragma Precondition (... and then Ctrl_Func_Call ...); -- Similar case occurs when the node is related to an object -- declaration or assignment: -- Obj [: Some_Typ] := ... and then Ctrl_Func_Call ...; -- Another case to consider is when the node is part of a return -- statement: -- return ... and then Ctrl_Func_Call ...; -- Another case is when the node acts as a formal in a procedure -- call statement: -- Proc (... and then Ctrl_Func_Call ...); if Scope_Is_Transient then Wrapped_Node := Node_To_Be_Wrapped; else Wrapped_Node := Empty; end if; while Present (Par) loop if Par = Wrapped_Node or else Nkind_In (Par, N_Assignment_Statement, N_Object_Declaration, N_Pragma, N_Procedure_Call_Statement, N_Simple_Return_Statement) then return Par; -- Prevent the search from going too far elsif Is_Body_Or_Package_Declaration (Par) then exit; end if; Par := Parent (Par); end loop; -- Return the topmost short circuit operator return Top; end if; end Find_Hook_Context; ------------------------------ -- Following_Address_Clause -- ------------------------------ function Following_Address_Clause (D : Node_Id) return Node_Id is Id : constant Entity_Id := Defining_Identifier (D); Result : Node_Id; Par : Node_Id; function Check_Decls (D : Node_Id) return Node_Id; -- This internal function differs from the main function in that it -- gets called to deal with a following package private part, and -- it checks declarations starting with D (the main function checks -- declarations following D). If D is Empty, then Empty is returned. ----------------- -- Check_Decls -- ----------------- function Check_Decls (D : Node_Id) return Node_Id is Decl : Node_Id; begin Decl := D; while Present (Decl) loop if Nkind (Decl) = N_At_Clause and then Chars (Identifier (Decl)) = Chars (Id) then return Decl; elsif Nkind (Decl) = N_Attribute_Definition_Clause and then Chars (Decl) = Name_Address and then Chars (Name (Decl)) = Chars (Id) then return Decl; end if; Next (Decl); end loop; -- Otherwise not found, return Empty return Empty; end Check_Decls; -- Start of processing for Following_Address_Clause begin -- If parser detected no address clause for the identifier in question, -- then the answer is a quick NO, without the need for a search. if not Get_Name_Table_Boolean1 (Chars (Id)) then return Empty; end if; -- Otherwise search current declarative unit Result := Check_Decls (Next (D)); if Present (Result) then return Result; end if; -- Check for possible package private part following Par := Parent (D); if Nkind (Par) = N_Package_Specification and then Visible_Declarations (Par) = List_Containing (D) and then Present (Private_Declarations (Par)) then -- Private part present, check declarations there return Check_Decls (First (Private_Declarations (Par))); else -- No private part, clause not found, return Empty return Empty; end if; end Following_Address_Clause; ---------------------- -- Force_Evaluation -- ---------------------- procedure Force_Evaluation (Exp : Node_Id; Name_Req : Boolean := False; Related_Id : Entity_Id := Empty; Is_Low_Bound : Boolean := False; Is_High_Bound : Boolean := False; Mode : Force_Evaluation_Mode := Relaxed) is begin Remove_Side_Effects (Exp => Exp, Name_Req => Name_Req, Variable_Ref => True, Renaming_Req => False, Related_Id => Related_Id, Is_Low_Bound => Is_Low_Bound, Is_High_Bound => Is_High_Bound, Check_Side_Effects => Is_Static_Expression (Exp) or else Mode = Relaxed); end Force_Evaluation; --------------------------------- -- Fully_Qualified_Name_String -- --------------------------------- function Fully_Qualified_Name_String (E : Entity_Id; Append_NUL : Boolean := True) return String_Id is procedure Internal_Full_Qualified_Name (E : Entity_Id); -- Compute recursively the qualified name without NUL at the end, adding -- it to the currently started string being generated ---------------------------------- -- Internal_Full_Qualified_Name -- ---------------------------------- procedure Internal_Full_Qualified_Name (E : Entity_Id) is Ent : Entity_Id; begin -- Deal properly with child units if Nkind (E) = N_Defining_Program_Unit_Name then Ent := Defining_Identifier (E); else Ent := E; end if; -- Compute qualification recursively (only "Standard" has no scope) if Present (Scope (Scope (Ent))) then Internal_Full_Qualified_Name (Scope (Ent)); Store_String_Char (Get_Char_Code ('.')); end if; -- Every entity should have a name except some expanded blocks -- don't bother about those. if Chars (Ent) = No_Name then return; end if; -- Generates the entity name in upper case Get_Decoded_Name_String (Chars (Ent)); Set_All_Upper_Case; Store_String_Chars (Name_Buffer (1 .. Name_Len)); return; end Internal_Full_Qualified_Name; -- Start of processing for Full_Qualified_Name begin Start_String; Internal_Full_Qualified_Name (E); if Append_NUL then Store_String_Char (Get_Char_Code (ASCII.NUL)); end if; return End_String; end Fully_Qualified_Name_String; ------------------------ -- Generate_Poll_Call -- ------------------------ procedure Generate_Poll_Call (N : Node_Id) is begin -- No poll call if polling not active if not Polling_Required then return; -- Otherwise generate require poll call else Insert_Before_And_Analyze (N, Make_Procedure_Call_Statement (Sloc (N), Name => New_Occurrence_Of (RTE (RE_Poll), Sloc (N)))); end if; end Generate_Poll_Call; --------------------------------- -- Get_Current_Value_Condition -- --------------------------------- -- Note: the implementation of this procedure is very closely tied to the -- implementation of Set_Current_Value_Condition. In the Get procedure, we -- interpret Current_Value fields set by the Set procedure, so the two -- procedures need to be closely coordinated. procedure Get_Current_Value_Condition (Var : Node_Id; Op : out Node_Kind; Val : out Node_Id) is Loc : constant Source_Ptr := Sloc (Var); Ent : constant Entity_Id := Entity (Var); procedure Process_Current_Value_Condition (N : Node_Id; S : Boolean); -- N is an expression which holds either True (S = True) or False (S = -- False) in the condition. This procedure digs out the expression and -- if it refers to Ent, sets Op and Val appropriately. ------------------------------------- -- Process_Current_Value_Condition -- ------------------------------------- procedure Process_Current_Value_Condition (N : Node_Id; S : Boolean) is Cond : Node_Id; Prev_Cond : Node_Id; Sens : Boolean; begin Cond := N; Sens := S; loop Prev_Cond := Cond; -- Deal with NOT operators, inverting sense while Nkind (Cond) = N_Op_Not loop Cond := Right_Opnd (Cond); Sens := not Sens; end loop; -- Deal with conversions, qualifications, and expressions with -- actions. while Nkind_In (Cond, N_Type_Conversion, N_Qualified_Expression, N_Expression_With_Actions) loop Cond := Expression (Cond); end loop; exit when Cond = Prev_Cond; end loop; -- Deal with AND THEN and AND cases if Nkind_In (Cond, N_And_Then, N_Op_And) then -- Don't ever try to invert a condition that is of the form of an -- AND or AND THEN (since we are not doing sufficiently general -- processing to allow this). if Sens = False then Op := N_Empty; Val := Empty; return; end if; -- Recursively process AND and AND THEN branches Process_Current_Value_Condition (Left_Opnd (Cond), True); if Op /= N_Empty then return; end if; Process_Current_Value_Condition (Right_Opnd (Cond), True); return; -- Case of relational operator elsif Nkind (Cond) in N_Op_Compare then Op := Nkind (Cond); -- Invert sense of test if inverted test if Sens = False then case Op is when N_Op_Eq => Op := N_Op_Ne; when N_Op_Ne => Op := N_Op_Eq; when N_Op_Lt => Op := N_Op_Ge; when N_Op_Gt => Op := N_Op_Le; when N_Op_Le => Op := N_Op_Gt; when N_Op_Ge => Op := N_Op_Lt; when others => raise Program_Error; end case; end if; -- Case of entity op value if Is_Entity_Name (Left_Opnd (Cond)) and then Ent = Entity (Left_Opnd (Cond)) and then Compile_Time_Known_Value (Right_Opnd (Cond)) then Val := Right_Opnd (Cond); -- Case of value op entity elsif Is_Entity_Name (Right_Opnd (Cond)) and then Ent = Entity (Right_Opnd (Cond)) and then Compile_Time_Known_Value (Left_Opnd (Cond)) then Val := Left_Opnd (Cond); -- We are effectively swapping operands case Op is when N_Op_Eq => null; when N_Op_Ne => null; when N_Op_Lt => Op := N_Op_Gt; when N_Op_Gt => Op := N_Op_Lt; when N_Op_Le => Op := N_Op_Ge; when N_Op_Ge => Op := N_Op_Le; when others => raise Program_Error; end case; else Op := N_Empty; end if; return; elsif Nkind_In (Cond, N_Type_Conversion, N_Qualified_Expression, N_Expression_With_Actions) then Cond := Expression (Cond); -- Case of Boolean variable reference, return as though the -- reference had said var = True. else if Is_Entity_Name (Cond) and then Ent = Entity (Cond) then Val := New_Occurrence_Of (Standard_True, Sloc (Cond)); if Sens = False then Op := N_Op_Ne; else Op := N_Op_Eq; end if; end if; end if; end Process_Current_Value_Condition; -- Start of processing for Get_Current_Value_Condition begin Op := N_Empty; Val := Empty; -- Immediate return, nothing doing, if this is not an object if Ekind (Ent) not in Object_Kind then return; end if; -- Otherwise examine current value declare CV : constant Node_Id := Current_Value (Ent); Sens : Boolean; Stm : Node_Id; begin -- If statement. Condition is known true in THEN section, known False -- in any ELSIF or ELSE part, and unknown outside the IF statement. if Nkind (CV) = N_If_Statement then -- Before start of IF statement if Loc < Sloc (CV) then return; -- After end of IF statement elsif Loc >= Sloc (CV) + Text_Ptr (UI_To_Int (End_Span (CV))) then return; end if; -- At this stage we know that we are within the IF statement, but -- unfortunately, the tree does not record the SLOC of the ELSE so -- we cannot use a simple SLOC comparison to distinguish between -- the then/else statements, so we have to climb the tree. declare N : Node_Id; begin N := Parent (Var); while Parent (N) /= CV loop N := Parent (N); -- If we fall off the top of the tree, then that's odd, but -- perhaps it could occur in some error situation, and the -- safest response is simply to assume that the outcome of -- the condition is unknown. No point in bombing during an -- attempt to optimize things. if No (N) then return; end if; end loop; -- Now we have N pointing to a node whose parent is the IF -- statement in question, so now we can tell if we are within -- the THEN statements. if Is_List_Member (N) and then List_Containing (N) = Then_Statements (CV) then Sens := True; -- If the variable reference does not come from source, we -- cannot reliably tell whether it appears in the else part. -- In particular, if it appears in generated code for a node -- that requires finalization, it may be attached to a list -- that has not been yet inserted into the code. For now, -- treat it as unknown. elsif not Comes_From_Source (N) then return; -- Otherwise we must be in ELSIF or ELSE part else Sens := False; end if; end; -- ELSIF part. Condition is known true within the referenced -- ELSIF, known False in any subsequent ELSIF or ELSE part, -- and unknown before the ELSE part or after the IF statement. elsif Nkind (CV) = N_Elsif_Part then -- if the Elsif_Part had condition_actions, the elsif has been -- rewritten as a nested if, and the original elsif_part is -- detached from the tree, so there is no way to obtain useful -- information on the current value of the variable. -- Can this be improved ??? if No (Parent (CV)) then return; end if; Stm := Parent (CV); -- If the tree has been otherwise rewritten there is nothing -- else to be done either. if Nkind (Stm) /= N_If_Statement then return; end if; -- Before start of ELSIF part if Loc < Sloc (CV) then return; -- After end of IF statement elsif Loc >= Sloc (Stm) + Text_Ptr (UI_To_Int (End_Span (Stm))) then return; end if; -- Again we lack the SLOC of the ELSE, so we need to climb the -- tree to see if we are within the ELSIF part in question. declare N : Node_Id; begin N := Parent (Var); while Parent (N) /= Stm loop N := Parent (N); -- If we fall off the top of the tree, then that's odd, but -- perhaps it could occur in some error situation, and the -- safest response is simply to assume that the outcome of -- the condition is unknown. No point in bombing during an -- attempt to optimize things. if No (N) then return; end if; end loop; -- Now we have N pointing to a node whose parent is the IF -- statement in question, so see if is the ELSIF part we want. -- the THEN statements. if N = CV then Sens := True; -- Otherwise we must be in subsequent ELSIF or ELSE part else Sens := False; end if; end; -- Iteration scheme of while loop. The condition is known to be -- true within the body of the loop. elsif Nkind (CV) = N_Iteration_Scheme then declare Loop_Stmt : constant Node_Id := Parent (CV); begin -- Before start of body of loop if Loc < Sloc (Loop_Stmt) then return; -- After end of LOOP statement elsif Loc >= Sloc (End_Label (Loop_Stmt)) then return; -- We are within the body of the loop else Sens := True; end if; end; -- All other cases of Current_Value settings else return; end if; -- If we fall through here, then we have a reportable condition, Sens -- is True if the condition is true and False if it needs inverting. Process_Current_Value_Condition (Condition (CV), Sens); end; end Get_Current_Value_Condition; --------------------- -- Get_Stream_Size -- --------------------- function Get_Stream_Size (E : Entity_Id) return Uint is begin -- If we have a Stream_Size clause for this type use it if Has_Stream_Size_Clause (E) then return Static_Integer (Expression (Stream_Size_Clause (E))); -- Otherwise the Stream_Size if the size of the type else return Esize (E); end if; end Get_Stream_Size; --------------------------- -- Has_Access_Constraint -- --------------------------- function Has_Access_Constraint (E : Entity_Id) return Boolean is Disc : Entity_Id; T : constant Entity_Id := Etype (E); begin if Has_Per_Object_Constraint (E) and then Has_Discriminants (T) then Disc := First_Discriminant (T); while Present (Disc) loop if Is_Access_Type (Etype (Disc)) then return True; end if; Next_Discriminant (Disc); end loop; return False; else return False; end if; end Has_Access_Constraint; ----------------------------------------------------- -- Has_Annotate_Pragma_For_External_Axiomatization -- ----------------------------------------------------- function Has_Annotate_Pragma_For_External_Axiomatization (E : Entity_Id) return Boolean is function Is_Annotate_Pragma_For_External_Axiomatization (N : Node_Id) return Boolean; -- Returns whether N is -- pragma Annotate (GNATprove, External_Axiomatization); ---------------------------------------------------- -- Is_Annotate_Pragma_For_External_Axiomatization -- ---------------------------------------------------- -- The general form of pragma Annotate is -- pragma Annotate (IDENTIFIER [, IDENTIFIER {, ARG}]); -- ARG ::= NAME | EXPRESSION -- The first two arguments are by convention intended to refer to an -- external tool and a tool-specific function. These arguments are -- not analyzed. -- The following is used to annotate a package specification which -- GNATprove should treat specially, because the axiomatization of -- this unit is given by the user instead of being automatically -- generated. -- pragma Annotate (GNATprove, External_Axiomatization); function Is_Annotate_Pragma_For_External_Axiomatization (N : Node_Id) return Boolean is Name_GNATprove : constant String := "gnatprove"; Name_External_Axiomatization : constant String := "external_axiomatization"; -- Special names begin if Nkind (N) = N_Pragma and then Get_Pragma_Id (N) = Pragma_Annotate and then List_Length (Pragma_Argument_Associations (N)) = 2 then declare Arg1 : constant Node_Id := First (Pragma_Argument_Associations (N)); Arg2 : constant Node_Id := Next (Arg1); Nam1 : Name_Id; Nam2 : Name_Id; begin -- Fill in Name_Buffer with Name_GNATprove first, and then with -- Name_External_Axiomatization so that Name_Find returns the -- corresponding name. This takes care of all possible casings. Name_Len := 0; Add_Str_To_Name_Buffer (Name_GNATprove); Nam1 := Name_Find; Name_Len := 0; Add_Str_To_Name_Buffer (Name_External_Axiomatization); Nam2 := Name_Find; return Chars (Get_Pragma_Arg (Arg1)) = Nam1 and then Chars (Get_Pragma_Arg (Arg2)) = Nam2; end; else return False; end if; end Is_Annotate_Pragma_For_External_Axiomatization; -- Local variables Decl : Node_Id; Vis_Decls : List_Id; N : Node_Id; -- Start of processing for Has_Annotate_Pragma_For_External_Axiomatization begin if Nkind (Parent (E)) = N_Defining_Program_Unit_Name then Decl := Parent (Parent (E)); else Decl := Parent (E); end if; Vis_Decls := Visible_Declarations (Decl); N := First (Vis_Decls); while Present (N) loop -- Skip declarations generated by the frontend. Skip all pragmas -- that are not the desired Annotate pragma. Stop the search on -- the first non-pragma source declaration. if Comes_From_Source (N) then if Nkind (N) = N_Pragma then if Is_Annotate_Pragma_For_External_Axiomatization (N) then return True; end if; else return False; end if; end if; Next (N); end loop; return False; end Has_Annotate_Pragma_For_External_Axiomatization; -------------------- -- Homonym_Number -- -------------------- function Homonym_Number (Subp : Entity_Id) return Nat is Count : Nat; Hom : Entity_Id; begin Count := 1; Hom := Homonym (Subp); while Present (Hom) loop if Scope (Hom) = Scope (Subp) then Count := Count + 1; end if; Hom := Homonym (Hom); end loop; return Count; end Homonym_Number; ----------------------------------- -- In_Library_Level_Package_Body -- ----------------------------------- function In_Library_Level_Package_Body (Id : Entity_Id) return Boolean is begin -- First determine whether the entity appears at the library level, then -- look at the containing unit. if Is_Library_Level_Entity (Id) then declare Container : constant Node_Id := Cunit (Get_Source_Unit (Id)); begin return Nkind (Unit (Container)) = N_Package_Body; end; end if; return False; end In_Library_Level_Package_Body; ------------------------------ -- In_Unconditional_Context -- ------------------------------ function In_Unconditional_Context (Node : Node_Id) return Boolean is P : Node_Id; begin P := Node; while Present (P) loop case Nkind (P) is when N_Subprogram_Body => return True; when N_If_Statement => return False; when N_Loop_Statement => return False; when N_Case_Statement => return False; when others => P := Parent (P); end case; end loop; return False; end In_Unconditional_Context; ------------------- -- Insert_Action -- ------------------- procedure Insert_Action (Assoc_Node : Node_Id; Ins_Action : Node_Id) is begin if Present (Ins_Action) then Insert_Actions (Assoc_Node, New_List (Ins_Action)); end if; end Insert_Action; -- Version with check(s) suppressed procedure Insert_Action (Assoc_Node : Node_Id; Ins_Action : Node_Id; Suppress : Check_Id) is begin Insert_Actions (Assoc_Node, New_List (Ins_Action), Suppress); end Insert_Action; ------------------------- -- Insert_Action_After -- ------------------------- procedure Insert_Action_After (Assoc_Node : Node_Id; Ins_Action : Node_Id) is begin Insert_Actions_After (Assoc_Node, New_List (Ins_Action)); end Insert_Action_After; -------------------- -- Insert_Actions -- -------------------- procedure Insert_Actions (Assoc_Node : Node_Id; Ins_Actions : List_Id) is N : Node_Id; P : Node_Id; Wrapped_Node : Node_Id := Empty; begin if No (Ins_Actions) or else Is_Empty_List (Ins_Actions) then return; end if; -- Ignore insert of actions from inside default expression (or other -- similar "spec expression") in the special spec-expression analyze -- mode. Any insertions at this point have no relevance, since we are -- only doing the analyze to freeze the types of any static expressions. -- See section "Handling of Default Expressions" in the spec of package -- Sem for further details. if In_Spec_Expression then return; end if; -- If the action derives from stuff inside a record, then the actions -- are attached to the current scope, to be inserted and analyzed on -- exit from the scope. The reason for this is that we may also be -- generating freeze actions at the same time, and they must eventually -- be elaborated in the correct order. if Is_Record_Type (Current_Scope) and then not Is_Frozen (Current_Scope) then if No (Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions) then Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions := Ins_Actions; else Append_List (Ins_Actions, Scope_Stack.Table (Scope_Stack.Last).Pending_Freeze_Actions); end if; return; end if; -- We now intend to climb up the tree to find the right point to -- insert the actions. We start at Assoc_Node, unless this node is a -- subexpression in which case we start with its parent. We do this for -- two reasons. First it speeds things up. Second, if Assoc_Node is -- itself one of the special nodes like N_And_Then, then we assume that -- an initial request to insert actions for such a node does not expect -- the actions to get deposited in the node for later handling when the -- node is expanded, since clearly the node is being dealt with by the -- caller. Note that in the subexpression case, N is always the child we -- came from. -- N_Raise_xxx_Error is an annoying special case, it is a statement -- if it has type Standard_Void_Type, and a subexpression otherwise. -- Procedure calls, and similarly procedure attribute references, are -- also statements. if Nkind (Assoc_Node) in N_Subexpr and then (Nkind (Assoc_Node) not in N_Raise_xxx_Error or else Etype (Assoc_Node) /= Standard_Void_Type) and then Nkind (Assoc_Node) /= N_Procedure_Call_Statement and then (Nkind (Assoc_Node) /= N_Attribute_Reference or else not Is_Procedure_Attribute_Name (Attribute_Name (Assoc_Node))) then N := Assoc_Node; P := Parent (Assoc_Node); -- Non-subexpression case. Note that N is initially Empty in this case -- (N is only guaranteed Non-Empty in the subexpr case). else N := Empty; P := Assoc_Node; end if; -- Capture root of the transient scope if Scope_Is_Transient then Wrapped_Node := Node_To_Be_Wrapped; end if; loop pragma Assert (Present (P)); -- Make sure that inserted actions stay in the transient scope if Present (Wrapped_Node) and then N = Wrapped_Node then Store_Before_Actions_In_Scope (Ins_Actions); return; end if; case Nkind (P) is -- Case of right operand of AND THEN or OR ELSE. Put the actions -- in the Actions field of the right operand. They will be moved -- out further when the AND THEN or OR ELSE operator is expanded. -- Nothing special needs to be done for the left operand since -- in that case the actions are executed unconditionally. when N_Short_Circuit => if N = Right_Opnd (P) then -- We are now going to either append the actions to the -- actions field of the short-circuit operation. We will -- also analyze the actions now. -- This analysis is really too early, the proper thing would -- be to just park them there now, and only analyze them if -- we find we really need them, and to it at the proper -- final insertion point. However attempting to this proved -- tricky, so for now we just kill current values before and -- after the analyze call to make sure we avoid peculiar -- optimizations from this out of order insertion. Kill_Current_Values; -- If P has already been expanded, we can't park new actions -- on it, so we need to expand them immediately, introducing -- an Expression_With_Actions. N can't be an expression -- with actions, or else then the actions would have been -- inserted at an inner level. if Analyzed (P) then pragma Assert (Nkind (N) /= N_Expression_With_Actions); Rewrite (N, Make_Expression_With_Actions (Sloc (N), Actions => Ins_Actions, Expression => Relocate_Node (N))); Analyze_And_Resolve (N); elsif Present (Actions (P)) then Insert_List_After_And_Analyze (Last (Actions (P)), Ins_Actions); else Set_Actions (P, Ins_Actions); Analyze_List (Actions (P)); end if; Kill_Current_Values; return; end if; -- Then or Else dependent expression of an if expression. Add -- actions to Then_Actions or Else_Actions field as appropriate. -- The actions will be moved further out when the if is expanded. when N_If_Expression => declare ThenX : constant Node_Id := Next (First (Expressions (P))); ElseX : constant Node_Id := Next (ThenX); begin -- If the enclosing expression is already analyzed, as -- is the case for nested elaboration checks, insert the -- conditional further out. if Analyzed (P) then null; -- Actions belong to the then expression, temporarily place -- them as Then_Actions of the if expression. They will be -- moved to the proper place later when the if expression -- is expanded. elsif N = ThenX then if Present (Then_Actions (P)) then Insert_List_After_And_Analyze (Last (Then_Actions (P)), Ins_Actions); else Set_Then_Actions (P, Ins_Actions); Analyze_List (Then_Actions (P)); end if; return; -- Actions belong to the else expression, temporarily place -- them as Else_Actions of the if expression. They will be -- moved to the proper place later when the if expression -- is expanded. elsif N = ElseX then if Present (Else_Actions (P)) then Insert_List_After_And_Analyze (Last (Else_Actions (P)), Ins_Actions); else Set_Else_Actions (P, Ins_Actions); Analyze_List (Else_Actions (P)); end if; return; -- Actions belong to the condition. In this case they are -- unconditionally executed, and so we can continue the -- search for the proper insert point. else null; end if; end; -- Alternative of case expression, we place the action in the -- Actions field of the case expression alternative, this will -- be handled when the case expression is expanded. when N_Case_Expression_Alternative => if Present (Actions (P)) then Insert_List_After_And_Analyze (Last (Actions (P)), Ins_Actions); else Set_Actions (P, Ins_Actions); Analyze_List (Actions (P)); end if; return; -- Case of appearing within an Expressions_With_Actions node. When -- the new actions come from the expression of the expression with -- actions, they must be added to the existing actions. The other -- alternative is when the new actions are related to one of the -- existing actions of the expression with actions, and should -- never reach here: if actions are inserted on a statement -- within the Actions of an expression with actions, or on some -- sub-expression of such a statement, then the outermost proper -- insertion point is right before the statement, and we should -- never climb up as far as the N_Expression_With_Actions itself. when N_Expression_With_Actions => if N = Expression (P) then if Is_Empty_List (Actions (P)) then Append_List_To (Actions (P), Ins_Actions); Analyze_List (Actions (P)); else Insert_List_After_And_Analyze (Last (Actions (P)), Ins_Actions); end if; return; else raise Program_Error; end if; -- Case of appearing in the condition of a while expression or -- elsif. We insert the actions into the Condition_Actions field. -- They will be moved further out when the while loop or elsif -- is analyzed. when N_Elsif_Part | N_Iteration_Scheme => if N = Condition (P) then if Present (Condition_Actions (P)) then Insert_List_After_And_Analyze (Last (Condition_Actions (P)), Ins_Actions); else Set_Condition_Actions (P, Ins_Actions); -- Set the parent of the insert actions explicitly. This -- is not a syntactic field, but we need the parent field -- set, in particular so that freeze can understand that -- it is dealing with condition actions, and properly -- insert the freezing actions. Set_Parent (Ins_Actions, P); Analyze_List (Condition_Actions (P)); end if; return; end if; -- Statements, declarations, pragmas, representation clauses when -- Statements N_Procedure_Call_Statement | N_Statement_Other_Than_Procedure_Call -- Pragmas | N_Pragma -- Representation_Clause | N_At_Clause | N_Attribute_Definition_Clause | N_Enumeration_Representation_Clause | N_Record_Representation_Clause -- Declarations | N_Abstract_Subprogram_Declaration | N_Entry_Body | N_Exception_Declaration | N_Exception_Renaming_Declaration | N_Expression_Function | N_Formal_Abstract_Subprogram_Declaration | N_Formal_Concrete_Subprogram_Declaration | N_Formal_Object_Declaration | N_Formal_Type_Declaration | N_Full_Type_Declaration | N_Function_Instantiation | N_Generic_Function_Renaming_Declaration | N_Generic_Package_Declaration | N_Generic_Package_Renaming_Declaration | N_Generic_Procedure_Renaming_Declaration | N_Generic_Subprogram_Declaration | N_Implicit_Label_Declaration | N_Incomplete_Type_Declaration | N_Number_Declaration | N_Object_Declaration | N_Object_Renaming_Declaration | N_Package_Body | N_Package_Body_Stub | N_Package_Declaration | N_Package_Instantiation | N_Package_Renaming_Declaration | N_Private_Extension_Declaration | N_Private_Type_Declaration | N_Procedure_Instantiation | N_Protected_Body | N_Protected_Body_Stub | N_Protected_Type_Declaration | N_Single_Task_Declaration | N_Subprogram_Body | N_Subprogram_Body_Stub | N_Subprogram_Declaration | N_Subprogram_Renaming_Declaration | N_Subtype_Declaration | N_Task_Body | N_Task_Body_Stub | N_Task_Type_Declaration -- Use clauses can appear in lists of declarations | N_Use_Package_Clause | N_Use_Type_Clause -- Freeze entity behaves like a declaration or statement | N_Freeze_Entity | N_Freeze_Generic_Entity => -- Do not insert here if the item is not a list member (this -- happens for example with a triggering statement, and the -- proper approach is to insert before the entire select). if not Is_List_Member (P) then null; -- Do not insert if parent of P is an N_Component_Association -- node (i.e. we are in the context of an N_Aggregate or -- N_Extension_Aggregate node. In this case we want to insert -- before the entire aggregate. elsif Nkind (Parent (P)) = N_Component_Association then null; -- Do not insert if the parent of P is either an N_Variant node -- or an N_Record_Definition node, meaning in either case that -- P is a member of a component list, and that therefore the -- actions should be inserted outside the complete record -- declaration. elsif Nkind_In (Parent (P), N_Variant, N_Record_Definition) then null; -- Do not insert freeze nodes within the loop generated for -- an aggregate, because they may be elaborated too late for -- subsequent use in the back end: within a package spec the -- loop is part of the elaboration procedure and is only -- elaborated during the second pass. -- If the loop comes from source, or the entity is local to the -- loop itself it must remain within. elsif Nkind (Parent (P)) = N_Loop_Statement and then not Comes_From_Source (Parent (P)) and then Nkind (First (Ins_Actions)) = N_Freeze_Entity and then Scope (Entity (First (Ins_Actions))) /= Current_Scope then null; -- Otherwise we can go ahead and do the insertion elsif P = Wrapped_Node then Store_Before_Actions_In_Scope (Ins_Actions); return; else Insert_List_Before_And_Analyze (P, Ins_Actions); return; end if; -- A special case, N_Raise_xxx_Error can act either as a statement -- or a subexpression. We tell the difference by looking at the -- Etype. It is set to Standard_Void_Type in the statement case. when N_Raise_xxx_Error => if Etype (P) = Standard_Void_Type then if P = Wrapped_Node then Store_Before_Actions_In_Scope (Ins_Actions); else Insert_List_Before_And_Analyze (P, Ins_Actions); end if; return; -- In the subexpression case, keep climbing else null; end if; -- If a component association appears within a loop created for -- an array aggregate, attach the actions to the association so -- they can be subsequently inserted within the loop. For other -- component associations insert outside of the aggregate. For -- an association that will generate a loop, its Loop_Actions -- attribute is already initialized (see exp_aggr.adb). -- The list of Loop_Actions can in turn generate additional ones, -- that are inserted before the associated node. If the associated -- node is outside the aggregate, the new actions are collected -- at the end of the Loop_Actions, to respect the order in which -- they are to be elaborated. when N_Component_Association | N_Iterated_Component_Association => if Nkind (Parent (P)) = N_Aggregate and then Present (Loop_Actions (P)) then if Is_Empty_List (Loop_Actions (P)) then Set_Loop_Actions (P, Ins_Actions); Analyze_List (Ins_Actions); else declare Decl : Node_Id; begin -- Check whether these actions were generated by a -- declaration that is part of the Loop_Actions for -- the component_association. Decl := Assoc_Node; while Present (Decl) loop exit when Parent (Decl) = P and then Is_List_Member (Decl) and then List_Containing (Decl) = Loop_Actions (P); Decl := Parent (Decl); end loop; if Present (Decl) then Insert_List_Before_And_Analyze (Decl, Ins_Actions); else Insert_List_After_And_Analyze (Last (Loop_Actions (P)), Ins_Actions); end if; end; end if; return; else null; end if; -- Another special case, an attribute denoting a procedure call when N_Attribute_Reference => if Is_Procedure_Attribute_Name (Attribute_Name (P)) then if P = Wrapped_Node then Store_Before_Actions_In_Scope (Ins_Actions); else Insert_List_Before_And_Analyze (P, Ins_Actions); end if; return; -- In the subexpression case, keep climbing else null; end if; -- A contract node should not belong to the tree when N_Contract => raise Program_Error; -- For all other node types, keep climbing tree when N_Abortable_Part | N_Accept_Alternative | N_Access_Definition | N_Access_Function_Definition | N_Access_Procedure_Definition | N_Access_To_Object_Definition | N_Aggregate | N_Allocator | N_Aspect_Specification | N_Case_Expression | N_Case_Statement_Alternative | N_Character_Literal | N_Compilation_Unit | N_Compilation_Unit_Aux | N_Component_Clause | N_Component_Declaration | N_Component_Definition | N_Component_List | N_Constrained_Array_Definition | N_Decimal_Fixed_Point_Definition | N_Defining_Character_Literal | N_Defining_Identifier | N_Defining_Operator_Symbol | N_Defining_Program_Unit_Name | N_Delay_Alternative | N_Delta_Aggregate | N_Delta_Constraint | N_Derived_Type_Definition | N_Designator | N_Digits_Constraint | N_Discriminant_Association | N_Discriminant_Specification | N_Empty | N_Entry_Body_Formal_Part | N_Entry_Call_Alternative | N_Entry_Declaration | N_Entry_Index_Specification | N_Enumeration_Type_Definition | N_Error | N_Exception_Handler | N_Expanded_Name | N_Explicit_Dereference | N_Extension_Aggregate | N_Floating_Point_Definition | N_Formal_Decimal_Fixed_Point_Definition | N_Formal_Derived_Type_Definition | N_Formal_Discrete_Type_Definition | N_Formal_Floating_Point_Definition | N_Formal_Modular_Type_Definition | N_Formal_Ordinary_Fixed_Point_Definition | N_Formal_Package_Declaration | N_Formal_Private_Type_Definition | N_Formal_Incomplete_Type_Definition | N_Formal_Signed_Integer_Type_Definition | N_Function_Call | N_Function_Specification | N_Generic_Association | N_Handled_Sequence_Of_Statements | N_Identifier | N_In | N_Index_Or_Discriminant_Constraint | N_Indexed_Component | N_Integer_Literal | N_Iterator_Specification | N_Itype_Reference | N_Label | N_Loop_Parameter_Specification | N_Mod_Clause | N_Modular_Type_Definition | N_Not_In | N_Null | N_Op_Abs | N_Op_Add | N_Op_And | N_Op_Concat | N_Op_Divide | N_Op_Eq | N_Op_Expon | N_Op_Ge | N_Op_Gt | N_Op_Le | N_Op_Lt | N_Op_Minus | N_Op_Mod | N_Op_Multiply | N_Op_Ne | N_Op_Not | N_Op_Or | N_Op_Plus | N_Op_Rem | N_Op_Rotate_Left | N_Op_Rotate_Right | N_Op_Shift_Left | N_Op_Shift_Right | N_Op_Shift_Right_Arithmetic | N_Op_Subtract | N_Op_Xor | N_Operator_Symbol | N_Ordinary_Fixed_Point_Definition | N_Others_Choice | N_Package_Specification | N_Parameter_Association | N_Parameter_Specification | N_Pop_Constraint_Error_Label | N_Pop_Program_Error_Label | N_Pop_Storage_Error_Label | N_Pragma_Argument_Association | N_Procedure_Specification | N_Protected_Definition | N_Push_Constraint_Error_Label | N_Push_Program_Error_Label | N_Push_Storage_Error_Label | N_Qualified_Expression | N_Quantified_Expression | N_Raise_Expression | N_Range | N_Range_Constraint | N_Real_Literal | N_Real_Range_Specification | N_Record_Definition | N_Reference | N_SCIL_Dispatch_Table_Tag_Init | N_SCIL_Dispatching_Call | N_SCIL_Membership_Test | N_Selected_Component | N_Signed_Integer_Type_Definition | N_Single_Protected_Declaration | N_Slice | N_String_Literal | N_Subtype_Indication | N_Subunit | N_Target_Name | N_Task_Definition | N_Terminate_Alternative | N_Triggering_Alternative | N_Type_Conversion | N_Unchecked_Expression | N_Unchecked_Type_Conversion | N_Unconstrained_Array_Definition | N_Unused_At_End | N_Unused_At_Start | N_Variant | N_Variant_Part | N_Validate_Unchecked_Conversion | N_With_Clause => null; end case; -- If we fall through above tests, keep climbing tree N := P; if Nkind (Parent (N)) = N_Subunit then -- This is the proper body corresponding to a stub. Insertion must -- be done at the point of the stub, which is in the declarative -- part of the parent unit. P := Corresponding_Stub (Parent (N)); else P := Parent (N); end if; end loop; end Insert_Actions; -- Version with check(s) suppressed procedure Insert_Actions (Assoc_Node : Node_Id; Ins_Actions : List_Id; Suppress : Check_Id) is begin if Suppress = All_Checks then declare Sva : constant Suppress_Array := Scope_Suppress.Suppress; begin Scope_Suppress.Suppress := (others => True); Insert_Actions (Assoc_Node, Ins_Actions); Scope_Suppress.Suppress := Sva; end; else declare Svg : constant Boolean := Scope_Suppress.Suppress (Suppress); begin Scope_Suppress.Suppress (Suppress) := True; Insert_Actions (Assoc_Node, Ins_Actions); Scope_Suppress.Suppress (Suppress) := Svg; end; end if; end Insert_Actions; -------------------------- -- Insert_Actions_After -- -------------------------- procedure Insert_Actions_After (Assoc_Node : Node_Id; Ins_Actions : List_Id) is begin if Scope_Is_Transient and then Assoc_Node = Node_To_Be_Wrapped then Store_After_Actions_In_Scope (Ins_Actions); else Insert_List_After_And_Analyze (Assoc_Node, Ins_Actions); end if; end Insert_Actions_After; ------------------------ -- Insert_Declaration -- ------------------------ procedure Insert_Declaration (N : Node_Id; Decl : Node_Id) is P : Node_Id; begin pragma Assert (Nkind (N) in N_Subexpr); -- Climb until we find a procedure or a package P := N; loop pragma Assert (Present (Parent (P))); P := Parent (P); if Is_List_Member (P) then exit when Nkind_In (Parent (P), N_Package_Specification, N_Subprogram_Body); -- Special handling for handled sequence of statements, we must -- insert in the statements not the exception handlers! if Nkind (Parent (P)) = N_Handled_Sequence_Of_Statements then P := First (Statements (Parent (P))); exit; end if; end if; end loop; -- Now do the insertion Insert_Before (P, Decl); Analyze (Decl); end Insert_Declaration; --------------------------------- -- Insert_Library_Level_Action -- --------------------------------- procedure Insert_Library_Level_Action (N : Node_Id) is Aux : constant Node_Id := Aux_Decls_Node (Cunit (Main_Unit)); begin Push_Scope (Cunit_Entity (Main_Unit)); -- ??? should this be Current_Sem_Unit instead of Main_Unit? if No (Actions (Aux)) then Set_Actions (Aux, New_List (N)); else Append (N, Actions (Aux)); end if; Analyze (N); Pop_Scope; end Insert_Library_Level_Action; ---------------------------------- -- Insert_Library_Level_Actions -- ---------------------------------- procedure Insert_Library_Level_Actions (L : List_Id) is Aux : constant Node_Id := Aux_Decls_Node (Cunit (Main_Unit)); begin if Is_Non_Empty_List (L) then Push_Scope (Cunit_Entity (Main_Unit)); -- ??? should this be Current_Sem_Unit instead of Main_Unit? if No (Actions (Aux)) then Set_Actions (Aux, L); Analyze_List (L); else Insert_List_After_And_Analyze (Last (Actions (Aux)), L); end if; Pop_Scope; end if; end Insert_Library_Level_Actions; ---------------------- -- Inside_Init_Proc -- ---------------------- function Inside_Init_Proc return Boolean is S : Entity_Id; begin S := Current_Scope; while Present (S) and then S /= Standard_Standard loop if Is_Init_Proc (S) then return True; else S := Scope (S); end if; end loop; return False; end Inside_Init_Proc; ---------------------------- -- Is_All_Null_Statements -- ---------------------------- function Is_All_Null_Statements (L : List_Id) return Boolean is Stm : Node_Id; begin Stm := First (L); while Present (Stm) loop if Nkind (Stm) /= N_Null_Statement then return False; end if; Next (Stm); end loop; return True; end Is_All_Null_Statements; -------------------------------------------------- -- Is_Displacement_Of_Object_Or_Function_Result -- -------------------------------------------------- function Is_Displacement_Of_Object_Or_Function_Result (Obj_Id : Entity_Id) return Boolean is function Is_Controlled_Function_Call (N : Node_Id) return Boolean; -- Determine if particular node denotes a controlled function call. The -- call may have been heavily expanded. function Is_Displace_Call (N : Node_Id) return Boolean; -- Determine whether a particular node is a call to Ada.Tags.Displace. -- The call might be nested within other actions such as conversions. function Is_Source_Object (N : Node_Id) return Boolean; -- Determine whether a particular node denotes a source object --------------------------------- -- Is_Controlled_Function_Call -- --------------------------------- function Is_Controlled_Function_Call (N : Node_Id) return Boolean is Expr : Node_Id := Original_Node (N); begin -- When a function call appears in Object.Operation format, the -- original representation has several possible forms depending on -- the availability and form of actual parameters: -- Obj.Func N_Selected_Component -- Obj.Func (Actual) N_Indexed_Component -- Obj.Func (Formal => Actual) N_Function_Call, whose Name is an -- N_Selected_Component loop if Nkind (Expr) = N_Function_Call then Expr := Name (Expr); -- "Obj.Func (Actual)" case elsif Nkind (Expr) = N_Indexed_Component then Expr := Prefix (Expr); -- "Obj.Func" or "Obj.Func (Formal => Actual) case elsif Nkind (Expr) = N_Selected_Component then Expr := Selector_Name (Expr); else exit; end if; end loop; return Nkind (Expr) in N_Has_Entity and then Present (Entity (Expr)) and then Ekind (Entity (Expr)) = E_Function and then Needs_Finalization (Etype (Entity (Expr))); end Is_Controlled_Function_Call; ---------------------- -- Is_Displace_Call -- ---------------------- function Is_Displace_Call (N : Node_Id) return Boolean is Call : Node_Id := N; begin -- Strip various actions which may precede a call to Displace loop if Nkind (Call) = N_Explicit_Dereference then Call := Prefix (Call); elsif Nkind_In (Call, N_Type_Conversion, N_Unchecked_Type_Conversion) then Call := Expression (Call); else exit; end if; end loop; return Present (Call) and then Nkind (Call) = N_Function_Call and then Is_RTE (Entity (Name (Call)), RE_Displace); end Is_Displace_Call; ---------------------- -- Is_Source_Object -- ---------------------- function Is_Source_Object (N : Node_Id) return Boolean is begin return Present (N) and then Nkind (N) in N_Has_Entity and then Is_Object (Entity (N)) and then Comes_From_Source (N); end Is_Source_Object; -- Local variables Decl : constant Node_Id := Parent (Obj_Id); Obj_Typ : constant Entity_Id := Base_Type (Etype (Obj_Id)); Orig_Decl : constant Node_Id := Original_Node (Decl); -- Start of processing for Is_Displacement_Of_Object_Or_Function_Result begin -- Case 1: -- Obj : CW_Type := Function_Call (...); -- rewritten into: -- Tmp : ... := Function_Call (...)'reference; -- Obj : CW_Type renames (... Ada.Tags.Displace (Tmp)); -- where the return type of the function and the class-wide type require -- dispatch table pointer displacement. -- Case 2: -- Obj : CW_Type := Src_Obj; -- rewritten into: -- Obj : CW_Type renames (... Ada.Tags.Displace (Src_Obj)); -- where the type of the source object and the class-wide type require -- dispatch table pointer displacement. return Nkind (Decl) = N_Object_Renaming_Declaration and then Nkind (Orig_Decl) = N_Object_Declaration and then Comes_From_Source (Orig_Decl) and then Is_Class_Wide_Type (Obj_Typ) and then Is_Displace_Call (Renamed_Object (Obj_Id)) and then (Is_Controlled_Function_Call (Expression (Orig_Decl)) or else Is_Source_Object (Expression (Orig_Decl))); end Is_Displacement_Of_Object_Or_Function_Result; ------------------------------ -- Is_Finalizable_Transient -- ------------------------------ function Is_Finalizable_Transient (Decl : Node_Id; Rel_Node : Node_Id) return Boolean is Obj_Id : constant Entity_Id := Defining_Identifier (Decl); Obj_Typ : constant Entity_Id := Base_Type (Etype (Obj_Id)); function Initialized_By_Access (Trans_Id : Entity_Id) return Boolean; -- Determine whether transient object Trans_Id is initialized either -- by a function call which returns an access type or simply renames -- another pointer. function Initialized_By_Aliased_BIP_Func_Call (Trans_Id : Entity_Id) return Boolean; -- Determine whether transient object Trans_Id is initialized by a -- build-in-place function call where the BIPalloc parameter is of -- value 1 and BIPaccess is not null. This case creates an aliasing -- between the returned value and the value denoted by BIPaccess. function Is_Aliased (Trans_Id : Entity_Id; First_Stmt : Node_Id) return Boolean; -- Determine whether transient object Trans_Id has been renamed or -- aliased through 'reference in the statement list starting from -- First_Stmt. function Is_Allocated (Trans_Id : Entity_Id) return Boolean; -- Determine whether transient object Trans_Id is allocated on the heap function Is_Iterated_Container (Trans_Id : Entity_Id; First_Stmt : Node_Id) return Boolean; -- Determine whether transient object Trans_Id denotes a container which -- is in the process of being iterated in the statement list starting -- from First_Stmt. --------------------------- -- Initialized_By_Access -- --------------------------- function Initialized_By_Access (Trans_Id : Entity_Id) return Boolean is Expr : constant Node_Id := Expression (Parent (Trans_Id)); begin return Present (Expr) and then Nkind (Expr) /= N_Reference and then Is_Access_Type (Etype (Expr)); end Initialized_By_Access; ------------------------------------------ -- Initialized_By_Aliased_BIP_Func_Call -- ------------------------------------------ function Initialized_By_Aliased_BIP_Func_Call (Trans_Id : Entity_Id) return Boolean is Call : Node_Id := Expression (Parent (Trans_Id)); begin -- Build-in-place calls usually appear in 'reference format if Nkind (Call) = N_Reference then Call := Prefix (Call); end if; if Is_Build_In_Place_Function_Call (Call) then declare Access_Nam : Name_Id := No_Name; Access_OK : Boolean := False; Actual : Node_Id; Alloc_Nam : Name_Id := No_Name; Alloc_OK : Boolean := False; Formal : Node_Id; Func_Id : Entity_Id; Param : Node_Id; begin -- Examine all parameter associations of the function call Param := First (Parameter_Associations (Call)); while Present (Param) loop if Nkind (Param) = N_Parameter_Association and then Nkind (Selector_Name (Param)) = N_Identifier then Actual := Explicit_Actual_Parameter (Param); Formal := Selector_Name (Param); -- Construct the names of formals BIPaccess and BIPalloc -- using the function name retrieved from an arbitrary -- formal. if Access_Nam = No_Name and then Alloc_Nam = No_Name and then Present (Entity (Formal)) then Func_Id := Scope (Entity (Formal)); Access_Nam := New_External_Name (Chars (Func_Id), BIP_Formal_Suffix (BIP_Object_Access)); Alloc_Nam := New_External_Name (Chars (Func_Id), BIP_Formal_Suffix (BIP_Alloc_Form)); end if; -- A match for BIPaccess => Temp has been found if Chars (Formal) = Access_Nam and then Nkind (Actual) /= N_Null then Access_OK := True; end if; -- A match for BIPalloc => 1 has been found if Chars (Formal) = Alloc_Nam and then Nkind (Actual) = N_Integer_Literal and then Intval (Actual) = Uint_1 then Alloc_OK := True; end if; end if; Next (Param); end loop; return Access_OK and Alloc_OK; end; end if; return False; end Initialized_By_Aliased_BIP_Func_Call; ---------------- -- Is_Aliased -- ---------------- function Is_Aliased (Trans_Id : Entity_Id; First_Stmt : Node_Id) return Boolean is function Find_Renamed_Object (Ren_Decl : Node_Id) return Entity_Id; -- Given an object renaming declaration, retrieve the entity of the -- renamed name. Return Empty if the renamed name is anything other -- than a variable or a constant. ------------------------- -- Find_Renamed_Object -- ------------------------- function Find_Renamed_Object (Ren_Decl : Node_Id) return Entity_Id is Ren_Obj : Node_Id := Empty; function Find_Object (N : Node_Id) return Traverse_Result; -- Try to detect an object which is either a constant or a -- variable. ----------------- -- Find_Object -- ----------------- function Find_Object (N : Node_Id) return Traverse_Result is begin -- Stop the search once a constant or a variable has been -- detected. if Nkind (N) = N_Identifier and then Present (Entity (N)) and then Ekind_In (Entity (N), E_Constant, E_Variable) then Ren_Obj := Entity (N); return Abandon; end if; return OK; end Find_Object; procedure Search is new Traverse_Proc (Find_Object); -- Local variables Typ : constant Entity_Id := Etype (Defining_Identifier (Ren_Decl)); -- Start of processing for Find_Renamed_Object begin -- Actions related to dispatching calls may appear as renamings of -- tags. Do not process this type of renaming because it does not -- use the actual value of the object. if not Is_RTE (Typ, RE_Tag_Ptr) then Search (Name (Ren_Decl)); end if; return Ren_Obj; end Find_Renamed_Object; -- Local variables Expr : Node_Id; Ren_Obj : Entity_Id; Stmt : Node_Id; -- Start of processing for Is_Aliased begin -- A controlled transient object is not considered aliased when it -- appears inside an expression_with_actions node even when there are -- explicit aliases of it: -- do -- Trans_Id : Ctrl_Typ ...; -- transient object -- Alias : ... := Trans_Id; -- object is aliased -- Val : constant Boolean := -- ... Alias ...; -- aliasing ends -- <finalize Trans_Id> -- object safe to finalize -- in Val end; -- Expansion ensures that all aliases are encapsulated in the actions -- list and do not leak to the expression by forcing the evaluation -- of the expression. if Nkind (Rel_Node) = N_Expression_With_Actions then return False; -- Otherwise examine the statements after the controlled transient -- object and look for various forms of aliasing. else Stmt := First_Stmt; while Present (Stmt) loop if Nkind (Stmt) = N_Object_Declaration then Expr := Expression (Stmt); -- Aliasing of the form: -- Obj : ... := Trans_Id'reference; if Present (Expr) and then Nkind (Expr) = N_Reference and then Nkind (Prefix (Expr)) = N_Identifier and then Entity (Prefix (Expr)) = Trans_Id then return True; end if; elsif Nkind (Stmt) = N_Object_Renaming_Declaration then Ren_Obj := Find_Renamed_Object (Stmt); -- Aliasing of the form: -- Obj : ... renames ... Trans_Id ...; if Present (Ren_Obj) and then Ren_Obj = Trans_Id then return True; end if; end if; Next (Stmt); end loop; return False; end if; end Is_Aliased; ------------------ -- Is_Allocated -- ------------------ function Is_Allocated (Trans_Id : Entity_Id) return Boolean is Expr : constant Node_Id := Expression (Parent (Trans_Id)); begin return Is_Access_Type (Etype (Trans_Id)) and then Present (Expr) and then Nkind (Expr) = N_Allocator; end Is_Allocated; --------------------------- -- Is_Iterated_Container -- --------------------------- function Is_Iterated_Container (Trans_Id : Entity_Id; First_Stmt : Node_Id) return Boolean is Aspect : Node_Id; Call : Node_Id; Iter : Entity_Id; Param : Node_Id; Stmt : Node_Id; Typ : Entity_Id; begin -- It is not possible to iterate over containers in non-Ada 2012 code if Ada_Version < Ada_2012 then return False; end if; Typ := Etype (Trans_Id); -- Handle access type created for secondary stack use if Is_Access_Type (Typ) then Typ := Designated_Type (Typ); end if; -- Look for aspect Default_Iterator. It may be part of a type -- declaration for a container, or inherited from a base type -- or parent type. Aspect := Find_Value_Of_Aspect (Typ, Aspect_Default_Iterator); if Present (Aspect) then Iter := Entity (Aspect); -- Examine the statements following the container object and -- look for a call to the default iterate routine where the -- first parameter is the transient. Such a call appears as: -- It : Access_To_CW_Iterator := -- Iterate (Tran_Id.all, ...)'reference; Stmt := First_Stmt; while Present (Stmt) loop -- Detect an object declaration which is initialized by a -- secondary stack function call. if Nkind (Stmt) = N_Object_Declaration and then Present (Expression (Stmt)) and then Nkind (Expression (Stmt)) = N_Reference and then Nkind (Prefix (Expression (Stmt))) = N_Function_Call then Call := Prefix (Expression (Stmt)); -- The call must invoke the default iterate routine of -- the container and the transient object must appear as -- the first actual parameter. Skip any calls whose names -- are not entities. if Is_Entity_Name (Name (Call)) and then Entity (Name (Call)) = Iter and then Present (Parameter_Associations (Call)) then Param := First (Parameter_Associations (Call)); if Nkind (Param) = N_Explicit_Dereference and then Entity (Prefix (Param)) = Trans_Id then return True; end if; end if; end if; Next (Stmt); end loop; end if; return False; end Is_Iterated_Container; -- Local variables Desig : Entity_Id := Obj_Typ; -- Start of processing for Is_Finalizable_Transient begin -- Handle access types if Is_Access_Type (Desig) then Desig := Available_View (Designated_Type (Desig)); end if; return Ekind_In (Obj_Id, E_Constant, E_Variable) and then Needs_Finalization (Desig) and then Requires_Transient_Scope (Desig) and then Nkind (Rel_Node) /= N_Simple_Return_Statement -- Do not consider a transient object that was already processed and then not Is_Finalized_Transient (Obj_Id) -- Do not consider renamed or 'reference-d transient objects because -- the act of renaming extends the object's lifetime. and then not Is_Aliased (Obj_Id, Decl) -- Do not consider transient objects allocated on the heap since -- they are attached to a finalization master. and then not Is_Allocated (Obj_Id) -- If the transient object is a pointer, check that it is not -- initialized by a function that returns a pointer or acts as a -- renaming of another pointer. and then (not Is_Access_Type (Obj_Typ) or else not Initialized_By_Access (Obj_Id)) -- Do not consider transient objects which act as indirect aliases -- of build-in-place function results. and then not Initialized_By_Aliased_BIP_Func_Call (Obj_Id) -- Do not consider conversions of tags to class-wide types and then not Is_Tag_To_Class_Wide_Conversion (Obj_Id) -- Do not consider iterators because those are treated as normal -- controlled objects and are processed by the usual finalization -- machinery. This avoids the double finalization of an iterator. and then not Is_Iterator (Desig) -- Do not consider containers in the context of iterator loops. Such -- transient objects must exist for as long as the loop is around, -- otherwise any operation carried out by the iterator will fail. and then not Is_Iterated_Container (Obj_Id, Decl); end Is_Finalizable_Transient; --------------------------------- -- Is_Fully_Repped_Tagged_Type -- --------------------------------- function Is_Fully_Repped_Tagged_Type (T : Entity_Id) return Boolean is U : constant Entity_Id := Underlying_Type (T); Comp : Entity_Id; begin if No (U) or else not Is_Tagged_Type (U) then return False; elsif Has_Discriminants (U) then return False; elsif not Has_Specified_Layout (U) then return False; end if; -- Here we have a tagged type, see if it has any unlayed out fields -- other than a possible tag and parent fields. If so, we return False. Comp := First_Component (U); while Present (Comp) loop if not Is_Tag (Comp) and then Chars (Comp) /= Name_uParent and then No (Component_Clause (Comp)) then return False; else Next_Component (Comp); end if; end loop; -- All components are layed out return True; end Is_Fully_Repped_Tagged_Type; ---------------------------------- -- Is_Library_Level_Tagged_Type -- ---------------------------------- function Is_Library_Level_Tagged_Type (Typ : Entity_Id) return Boolean is begin return Is_Tagged_Type (Typ) and then Is_Library_Level_Entity (Typ); end Is_Library_Level_Tagged_Type; -------------------------- -- Is_Non_BIP_Func_Call -- -------------------------- function Is_Non_BIP_Func_Call (Expr : Node_Id) return Boolean is begin -- The expected call is of the format -- -- Func_Call'reference return Nkind (Expr) = N_Reference and then Nkind (Prefix (Expr)) = N_Function_Call and then not Is_Build_In_Place_Function_Call (Prefix (Expr)); end Is_Non_BIP_Func_Call; ------------------------------------ -- Is_Object_Access_BIP_Func_Call -- ------------------------------------ function Is_Object_Access_BIP_Func_Call (Expr : Node_Id; Obj_Id : Entity_Id) return Boolean is Access_Nam : Name_Id := No_Name; Actual : Node_Id; Call : Node_Id; Formal : Node_Id; Param : Node_Id; begin -- Build-in-place calls usually appear in 'reference format. Note that -- the accessibility check machinery may add an extra 'reference due to -- side effect removal. Call := Expr; while Nkind (Call) = N_Reference loop Call := Prefix (Call); end loop; if Nkind_In (Call, N_Qualified_Expression, N_Unchecked_Type_Conversion) then Call := Expression (Call); end if; if Is_Build_In_Place_Function_Call (Call) then -- Examine all parameter associations of the function call Param := First (Parameter_Associations (Call)); while Present (Param) loop if Nkind (Param) = N_Parameter_Association and then Nkind (Selector_Name (Param)) = N_Identifier then Formal := Selector_Name (Param); Actual := Explicit_Actual_Parameter (Param); -- Construct the name of formal BIPaccess. It is much easier to -- extract the name of the function using an arbitrary formal's -- scope rather than the Name field of Call. if Access_Nam = No_Name and then Present (Entity (Formal)) then Access_Nam := New_External_Name (Chars (Scope (Entity (Formal))), BIP_Formal_Suffix (BIP_Object_Access)); end if; -- A match for BIPaccess => Obj_Id'Unrestricted_Access has been -- found. if Chars (Formal) = Access_Nam and then Nkind (Actual) = N_Attribute_Reference and then Attribute_Name (Actual) = Name_Unrestricted_Access and then Nkind (Prefix (Actual)) = N_Identifier and then Entity (Prefix (Actual)) = Obj_Id then return True; end if; end if; Next (Param); end loop; end if; return False; end Is_Object_Access_BIP_Func_Call; ---------------------------------- -- Is_Possibly_Unaligned_Object -- ---------------------------------- function Is_Possibly_Unaligned_Object (N : Node_Id) return Boolean is T : constant Entity_Id := Etype (N); begin -- If renamed object, apply test to underlying object if Is_Entity_Name (N) and then Is_Object (Entity (N)) and then Present (Renamed_Object (Entity (N))) then return Is_Possibly_Unaligned_Object (Renamed_Object (Entity (N))); end if; -- Tagged and controlled types and aliased types are always aligned, as -- are concurrent types. if Is_Aliased (T) or else Has_Controlled_Component (T) or else Is_Concurrent_Type (T) or else Is_Tagged_Type (T) or else Is_Controlled (T) then return False; end if; -- If this is an element of a packed array, may be unaligned if Is_Ref_To_Bit_Packed_Array (N) then return True; end if; -- Case of indexed component reference: test whether prefix is unaligned if Nkind (N) = N_Indexed_Component then return Is_Possibly_Unaligned_Object (Prefix (N)); -- Case of selected component reference elsif Nkind (N) = N_Selected_Component then declare P : constant Node_Id := Prefix (N); C : constant Entity_Id := Entity (Selector_Name (N)); M : Nat; S : Nat; begin -- If component reference is for an array with non-static bounds, -- then it is always aligned: we can only process unaligned arrays -- with static bounds (more precisely compile time known bounds). if Is_Array_Type (T) and then not Compile_Time_Known_Bounds (T) then return False; end if; -- If component is aliased, it is definitely properly aligned if Is_Aliased (C) then return False; end if; -- If component is for a type implemented as a scalar, and the -- record is packed, and the component is other than the first -- component of the record, then the component may be unaligned. if Is_Packed (Etype (P)) and then Represented_As_Scalar (Etype (C)) and then First_Entity (Scope (C)) /= C then return True; end if; -- Compute maximum possible alignment for T -- If alignment is known, then that settles things if Known_Alignment (T) then M := UI_To_Int (Alignment (T)); -- If alignment is not known, tentatively set max alignment else M := Ttypes.Maximum_Alignment; -- We can reduce this if the Esize is known since the default -- alignment will never be more than the smallest power of 2 -- that does not exceed this Esize value. if Known_Esize (T) then S := UI_To_Int (Esize (T)); while (M / 2) >= S loop M := M / 2; end loop; end if; end if; -- The following code is historical, it used to be present but it -- is too cautious, because the front-end does not know the proper -- default alignments for the target. Also, if the alignment is -- not known, the front end can't know in any case. If a copy is -- needed, the back-end will take care of it. This whole section -- including this comment can be removed later ??? -- If the component reference is for a record that has a specified -- alignment, and we either know it is too small, or cannot tell, -- then the component may be unaligned. -- What is the following commented out code ??? -- if Known_Alignment (Etype (P)) -- and then Alignment (Etype (P)) < Ttypes.Maximum_Alignment -- and then M > Alignment (Etype (P)) -- then -- return True; -- end if; -- Case of component clause present which may specify an -- unaligned position. if Present (Component_Clause (C)) then -- Otherwise we can do a test to make sure that the actual -- start position in the record, and the length, are both -- consistent with the required alignment. If not, we know -- that we are unaligned. declare Align_In_Bits : constant Nat := M * System_Storage_Unit; begin if Component_Bit_Offset (C) mod Align_In_Bits /= 0 or else Esize (C) mod Align_In_Bits /= 0 then return True; end if; end; end if; -- Otherwise, for a component reference, test prefix return Is_Possibly_Unaligned_Object (P); end; -- If not a component reference, must be aligned else return False; end if; end Is_Possibly_Unaligned_Object; --------------------------------- -- Is_Possibly_Unaligned_Slice -- --------------------------------- function Is_Possibly_Unaligned_Slice (N : Node_Id) return Boolean is begin -- Go to renamed object if Is_Entity_Name (N) and then Is_Object (Entity (N)) and then Present (Renamed_Object (Entity (N))) then return Is_Possibly_Unaligned_Slice (Renamed_Object (Entity (N))); end if; -- The reference must be a slice if Nkind (N) /= N_Slice then return False; end if; -- We only need to worry if the target has strict alignment if not Target_Strict_Alignment then return False; end if; -- If it is a slice, then look at the array type being sliced declare Sarr : constant Node_Id := Prefix (N); -- Prefix of the slice, i.e. the array being sliced Styp : constant Entity_Id := Etype (Prefix (N)); -- Type of the array being sliced Pref : Node_Id; Ptyp : Entity_Id; begin -- The problems arise if the array object that is being sliced -- is a component of a record or array, and we cannot guarantee -- the alignment of the array within its containing object. -- To investigate this, we look at successive prefixes to see -- if we have a worrisome indexed or selected component. Pref := Sarr; loop -- Case of array is part of an indexed component reference if Nkind (Pref) = N_Indexed_Component then Ptyp := Etype (Prefix (Pref)); -- The only problematic case is when the array is packed, in -- which case we really know nothing about the alignment of -- individual components. if Is_Bit_Packed_Array (Ptyp) then return True; end if; -- Case of array is part of a selected component reference elsif Nkind (Pref) = N_Selected_Component then Ptyp := Etype (Prefix (Pref)); -- We are definitely in trouble if the record in question -- has an alignment, and either we know this alignment is -- inconsistent with the alignment of the slice, or we don't -- know what the alignment of the slice should be. if Known_Alignment (Ptyp) and then (Unknown_Alignment (Styp) or else Alignment (Styp) > Alignment (Ptyp)) then return True; end if; -- We are in potential trouble if the record type is packed. -- We could special case when we know that the array is the -- first component, but that's not such a simple case ??? if Is_Packed (Ptyp) then return True; end if; -- We are in trouble if there is a component clause, and -- either we do not know the alignment of the slice, or -- the alignment of the slice is inconsistent with the -- bit position specified by the component clause. declare Field : constant Entity_Id := Entity (Selector_Name (Pref)); begin if Present (Component_Clause (Field)) and then (Unknown_Alignment (Styp) or else (Component_Bit_Offset (Field) mod (System_Storage_Unit * Alignment (Styp))) /= 0) then return True; end if; end; -- For cases other than selected or indexed components we know we -- are OK, since no issues arise over alignment. else return False; end if; -- We processed an indexed component or selected component -- reference that looked safe, so keep checking prefixes. Pref := Prefix (Pref); end loop; end; end Is_Possibly_Unaligned_Slice; ------------------------------- -- Is_Related_To_Func_Return -- ------------------------------- function Is_Related_To_Func_Return (Id : Entity_Id) return Boolean is Expr : constant Node_Id := Related_Expression (Id); begin return Present (Expr) and then Nkind (Expr) = N_Explicit_Dereference and then Nkind (Parent (Expr)) = N_Simple_Return_Statement; end Is_Related_To_Func_Return; -------------------------------- -- Is_Ref_To_Bit_Packed_Array -- -------------------------------- function Is_Ref_To_Bit_Packed_Array (N : Node_Id) return Boolean is Result : Boolean; Expr : Node_Id; begin if Is_Entity_Name (N) and then Is_Object (Entity (N)) and then Present (Renamed_Object (Entity (N))) then return Is_Ref_To_Bit_Packed_Array (Renamed_Object (Entity (N))); end if; if Nkind_In (N, N_Indexed_Component, N_Selected_Component) then if Is_Bit_Packed_Array (Etype (Prefix (N))) then Result := True; else Result := Is_Ref_To_Bit_Packed_Array (Prefix (N)); end if; if Result and then Nkind (N) = N_Indexed_Component then Expr := First (Expressions (N)); while Present (Expr) loop Force_Evaluation (Expr); Next (Expr); end loop; end if; return Result; else return False; end if; end Is_Ref_To_Bit_Packed_Array; -------------------------------- -- Is_Ref_To_Bit_Packed_Slice -- -------------------------------- function Is_Ref_To_Bit_Packed_Slice (N : Node_Id) return Boolean is begin if Nkind (N) = N_Type_Conversion then return Is_Ref_To_Bit_Packed_Slice (Expression (N)); elsif Is_Entity_Name (N) and then Is_Object (Entity (N)) and then Present (Renamed_Object (Entity (N))) then return Is_Ref_To_Bit_Packed_Slice (Renamed_Object (Entity (N))); elsif Nkind (N) = N_Slice and then Is_Bit_Packed_Array (Etype (Prefix (N))) then return True; elsif Nkind_In (N, N_Indexed_Component, N_Selected_Component) then return Is_Ref_To_Bit_Packed_Slice (Prefix (N)); else return False; end if; end Is_Ref_To_Bit_Packed_Slice; ----------------------- -- Is_Renamed_Object -- ----------------------- function Is_Renamed_Object (N : Node_Id) return Boolean is Pnod : constant Node_Id := Parent (N); Kind : constant Node_Kind := Nkind (Pnod); begin if Kind = N_Object_Renaming_Declaration then return True; elsif Nkind_In (Kind, N_Indexed_Component, N_Selected_Component) then return Is_Renamed_Object (Pnod); else return False; end if; end Is_Renamed_Object; -------------------------------------- -- Is_Secondary_Stack_BIP_Func_Call -- -------------------------------------- function Is_Secondary_Stack_BIP_Func_Call (Expr : Node_Id) return Boolean is Alloc_Nam : Name_Id := No_Name; Actual : Node_Id; Call : Node_Id := Expr; Formal : Node_Id; Param : Node_Id; begin -- Build-in-place calls usually appear in 'reference format. Note that -- the accessibility check machinery may add an extra 'reference due to -- side effect removal. while Nkind (Call) = N_Reference loop Call := Prefix (Call); end loop; if Nkind_In (Call, N_Qualified_Expression, N_Unchecked_Type_Conversion) then Call := Expression (Call); end if; if Is_Build_In_Place_Function_Call (Call) then -- Examine all parameter associations of the function call Param := First (Parameter_Associations (Call)); while Present (Param) loop if Nkind (Param) = N_Parameter_Association and then Nkind (Selector_Name (Param)) = N_Identifier then Formal := Selector_Name (Param); Actual := Explicit_Actual_Parameter (Param); -- Construct the name of formal BIPalloc. It is much easier to -- extract the name of the function using an arbitrary formal's -- scope rather than the Name field of Call. if Alloc_Nam = No_Name and then Present (Entity (Formal)) then Alloc_Nam := New_External_Name (Chars (Scope (Entity (Formal))), BIP_Formal_Suffix (BIP_Alloc_Form)); end if; -- A match for BIPalloc => 2 has been found if Chars (Formal) = Alloc_Nam and then Nkind (Actual) = N_Integer_Literal and then Intval (Actual) = Uint_2 then return True; end if; end if; Next (Param); end loop; end if; return False; end Is_Secondary_Stack_BIP_Func_Call; ------------------------------------- -- Is_Tag_To_Class_Wide_Conversion -- ------------------------------------- function Is_Tag_To_Class_Wide_Conversion (Obj_Id : Entity_Id) return Boolean is Expr : constant Node_Id := Expression (Parent (Obj_Id)); begin return Is_Class_Wide_Type (Etype (Obj_Id)) and then Present (Expr) and then Nkind (Expr) = N_Unchecked_Type_Conversion and then Etype (Expression (Expr)) = RTE (RE_Tag); end Is_Tag_To_Class_Wide_Conversion; ---------------------------- -- Is_Untagged_Derivation -- ---------------------------- function Is_Untagged_Derivation (T : Entity_Id) return Boolean is begin return (not Is_Tagged_Type (T) and then Is_Derived_Type (T)) or else (Is_Private_Type (T) and then Present (Full_View (T)) and then not Is_Tagged_Type (Full_View (T)) and then Is_Derived_Type (Full_View (T)) and then Etype (Full_View (T)) /= T); end Is_Untagged_Derivation; --------------------------- -- Is_Volatile_Reference -- --------------------------- function Is_Volatile_Reference (N : Node_Id) return Boolean is begin -- Only source references are to be treated as volatile, internally -- generated stuff cannot have volatile external effects. if not Comes_From_Source (N) then return False; -- Never true for reference to a type elsif Is_Entity_Name (N) and then Is_Type (Entity (N)) then return False; -- Never true for a compile time known constant elsif Compile_Time_Known_Value (N) then return False; -- True if object reference with volatile type elsif Is_Volatile_Object (N) then return True; -- True if reference to volatile entity elsif Is_Entity_Name (N) then return Treat_As_Volatile (Entity (N)); -- True for slice of volatile array elsif Nkind (N) = N_Slice then return Is_Volatile_Reference (Prefix (N)); -- True if volatile component elsif Nkind_In (N, N_Indexed_Component, N_Selected_Component) then if (Is_Entity_Name (Prefix (N)) and then Has_Volatile_Components (Entity (Prefix (N)))) or else (Present (Etype (Prefix (N))) and then Has_Volatile_Components (Etype (Prefix (N)))) then return True; else return Is_Volatile_Reference (Prefix (N)); end if; -- Otherwise false else return False; end if; end Is_Volatile_Reference; -------------------- -- Kill_Dead_Code -- -------------------- procedure Kill_Dead_Code (N : Node_Id; Warn : Boolean := False) is W : Boolean := Warn; -- Set False if warnings suppressed begin if Present (N) then Remove_Warning_Messages (N); -- Generate warning if appropriate if W then -- We suppress the warning if this code is under control of an -- if statement, whose condition is a simple identifier, and -- either we are in an instance, or warnings off is set for this -- identifier. The reason for killing it in the instance case is -- that it is common and reasonable for code to be deleted in -- instances for various reasons. -- Could we use Is_Statically_Unevaluated here??? if Nkind (Parent (N)) = N_If_Statement then declare C : constant Node_Id := Condition (Parent (N)); begin if Nkind (C) = N_Identifier and then (In_Instance or else (Present (Entity (C)) and then Has_Warnings_Off (Entity (C)))) then W := False; end if; end; end if; -- Generate warning if not suppressed if W then Error_Msg_F ("?t?this code can never be executed and has been deleted!", N); end if; end if; -- Recurse into block statements and bodies to process declarations -- and statements. if Nkind (N) = N_Block_Statement or else Nkind (N) = N_Subprogram_Body or else Nkind (N) = N_Package_Body then Kill_Dead_Code (Declarations (N), False); Kill_Dead_Code (Statements (Handled_Statement_Sequence (N))); if Nkind (N) = N_Subprogram_Body then Set_Is_Eliminated (Defining_Entity (N)); end if; elsif Nkind (N) = N_Package_Declaration then Kill_Dead_Code (Visible_Declarations (Specification (N))); Kill_Dead_Code (Private_Declarations (Specification (N))); -- ??? After this point, Delete_Tree has been called on all -- declarations in Specification (N), so references to entities -- therein look suspicious. declare E : Entity_Id := First_Entity (Defining_Entity (N)); begin while Present (E) loop if Ekind (E) = E_Operator then Set_Is_Eliminated (E); end if; Next_Entity (E); end loop; end; -- Recurse into composite statement to kill individual statements in -- particular instantiations. elsif Nkind (N) = N_If_Statement then Kill_Dead_Code (Then_Statements (N)); Kill_Dead_Code (Elsif_Parts (N)); Kill_Dead_Code (Else_Statements (N)); elsif Nkind (N) = N_Loop_Statement then Kill_Dead_Code (Statements (N)); elsif Nkind (N) = N_Case_Statement then declare Alt : Node_Id; begin Alt := First (Alternatives (N)); while Present (Alt) loop Kill_Dead_Code (Statements (Alt)); Next (Alt); end loop; end; elsif Nkind (N) = N_Case_Statement_Alternative then Kill_Dead_Code (Statements (N)); -- Deal with dead instances caused by deleting instantiations elsif Nkind (N) in N_Generic_Instantiation then Remove_Dead_Instance (N); end if; end if; end Kill_Dead_Code; -- Case where argument is a list of nodes to be killed procedure Kill_Dead_Code (L : List_Id; Warn : Boolean := False) is N : Node_Id; W : Boolean; begin W := Warn; if Is_Non_Empty_List (L) then N := First (L); while Present (N) loop Kill_Dead_Code (N, W); W := False; Next (N); end loop; end if; end Kill_Dead_Code; ------------------------ -- Known_Non_Negative -- ------------------------ function Known_Non_Negative (Opnd : Node_Id) return Boolean is begin if Is_OK_Static_Expression (Opnd) and then Expr_Value (Opnd) >= 0 then return True; else declare Lo : constant Node_Id := Type_Low_Bound (Etype (Opnd)); begin return Is_OK_Static_Expression (Lo) and then Expr_Value (Lo) >= 0; end; end if; end Known_Non_Negative; -------------------- -- Known_Non_Null -- -------------------- function Known_Non_Null (N : Node_Id) return Boolean is begin -- Checks for case where N is an entity reference if Is_Entity_Name (N) and then Present (Entity (N)) then declare E : constant Entity_Id := Entity (N); Op : Node_Kind; Val : Node_Id; begin -- First check if we are in decisive conditional Get_Current_Value_Condition (N, Op, Val); if Known_Null (Val) then if Op = N_Op_Eq then return False; elsif Op = N_Op_Ne then return True; end if; end if; -- If OK to do replacement, test Is_Known_Non_Null flag if OK_To_Do_Constant_Replacement (E) then return Is_Known_Non_Null (E); -- Otherwise if not safe to do replacement, then say so else return False; end if; end; -- True if access attribute elsif Nkind (N) = N_Attribute_Reference and then Nam_In (Attribute_Name (N), Name_Access, Name_Unchecked_Access, Name_Unrestricted_Access) then return True; -- True if allocator elsif Nkind (N) = N_Allocator then return True; -- For a conversion, true if expression is known non-null elsif Nkind (N) = N_Type_Conversion then return Known_Non_Null (Expression (N)); -- Above are all cases where the value could be determined to be -- non-null. In all other cases, we don't know, so return False. else return False; end if; end Known_Non_Null; ---------------- -- Known_Null -- ---------------- function Known_Null (N : Node_Id) return Boolean is begin -- Checks for case where N is an entity reference if Is_Entity_Name (N) and then Present (Entity (N)) then declare E : constant Entity_Id := Entity (N); Op : Node_Kind; Val : Node_Id; begin -- Constant null value is for sure null if Ekind (E) = E_Constant and then Known_Null (Constant_Value (E)) then return True; end if; -- First check if we are in decisive conditional Get_Current_Value_Condition (N, Op, Val); if Known_Null (Val) then if Op = N_Op_Eq then return True; elsif Op = N_Op_Ne then return False; end if; end if; -- If OK to do replacement, test Is_Known_Null flag if OK_To_Do_Constant_Replacement (E) then return Is_Known_Null (E); -- Otherwise if not safe to do replacement, then say so else return False; end if; end; -- True if explicit reference to null elsif Nkind (N) = N_Null then return True; -- For a conversion, true if expression is known null elsif Nkind (N) = N_Type_Conversion then return Known_Null (Expression (N)); -- Above are all cases where the value could be determined to be null. -- In all other cases, we don't know, so return False. else return False; end if; end Known_Null; ----------------------------- -- Make_CW_Equivalent_Type -- ----------------------------- -- Create a record type used as an equivalent of any member of the class -- which takes its size from exp. -- Generate the following code: -- type Equiv_T is record -- _parent : T (List of discriminant constraints taken from Exp); -- Ext__50 : Storage_Array (1 .. (Exp'size - Typ'object_size)/8); -- end Equiv_T; -- -- ??? Note that this type does not guarantee same alignment as all -- derived types function Make_CW_Equivalent_Type (T : Entity_Id; E : Node_Id) return Entity_Id is Loc : constant Source_Ptr := Sloc (E); Root_Typ : constant Entity_Id := Root_Type (T); List_Def : constant List_Id := Empty_List; Comp_List : constant List_Id := New_List; Equiv_Type : Entity_Id; Range_Type : Entity_Id; Str_Type : Entity_Id; Constr_Root : Entity_Id; Sizexpr : Node_Id; begin -- If the root type is already constrained, there are no discriminants -- in the expression. if not Has_Discriminants (Root_Typ) or else Is_Constrained (Root_Typ) then Constr_Root := Root_Typ; -- At this point in the expansion, non-limited view of the type -- must be available, otherwise the error will be reported later. if From_Limited_With (Constr_Root) and then Present (Non_Limited_View (Constr_Root)) then Constr_Root := Non_Limited_View (Constr_Root); end if; else Constr_Root := Make_Temporary (Loc, 'R'); -- subtype cstr__n is T (List of discr constraints taken from Exp) Append_To (List_Def, Make_Subtype_Declaration (Loc, Defining_Identifier => Constr_Root, Subtype_Indication => Make_Subtype_From_Expr (E, Root_Typ))); end if; -- Generate the range subtype declaration Range_Type := Make_Temporary (Loc, 'G'); if not Is_Interface (Root_Typ) then -- subtype rg__xx is -- Storage_Offset range 1 .. (Expr'size - typ'size) / Storage_Unit Sizexpr := Make_Op_Subtract (Loc, Left_Opnd => Make_Attribute_Reference (Loc, Prefix => OK_Convert_To (T, Duplicate_Subexpr_No_Checks (E)), Attribute_Name => Name_Size), Right_Opnd => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Constr_Root, Loc), Attribute_Name => Name_Object_Size)); else -- subtype rg__xx is -- Storage_Offset range 1 .. Expr'size / Storage_Unit Sizexpr := Make_Attribute_Reference (Loc, Prefix => OK_Convert_To (T, Duplicate_Subexpr_No_Checks (E)), Attribute_Name => Name_Size); end if; Set_Paren_Count (Sizexpr, 1); Append_To (List_Def, Make_Subtype_Declaration (Loc, Defining_Identifier => Range_Type, Subtype_Indication => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Storage_Offset), Loc), Constraint => Make_Range_Constraint (Loc, Range_Expression => Make_Range (Loc, Low_Bound => Make_Integer_Literal (Loc, 1), High_Bound => Make_Op_Divide (Loc, Left_Opnd => Sizexpr, Right_Opnd => Make_Integer_Literal (Loc, Intval => System_Storage_Unit))))))); -- subtype str__nn is Storage_Array (rg__x); Str_Type := Make_Temporary (Loc, 'S'); Append_To (List_Def, Make_Subtype_Declaration (Loc, Defining_Identifier => Str_Type, Subtype_Indication => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Storage_Array), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List (New_Occurrence_Of (Range_Type, Loc)))))); -- type Equiv_T is record -- [ _parent : Tnn; ] -- E : Str_Type; -- end Equiv_T; Equiv_Type := Make_Temporary (Loc, 'T'); Set_Ekind (Equiv_Type, E_Record_Type); Set_Parent_Subtype (Equiv_Type, Constr_Root); -- Set Is_Class_Wide_Equivalent_Type very early to trigger the special -- treatment for this type. In particular, even though _parent's type -- is a controlled type or contains controlled components, we do not -- want to set Has_Controlled_Component on it to avoid making it gain -- an unwanted _controller component. Set_Is_Class_Wide_Equivalent_Type (Equiv_Type); -- A class-wide equivalent type does not require initialization Set_Suppress_Initialization (Equiv_Type); if not Is_Interface (Root_Typ) then Append_To (Comp_List, Make_Component_Declaration (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uParent), Component_Definition => Make_Component_Definition (Loc, Aliased_Present => False, Subtype_Indication => New_Occurrence_Of (Constr_Root, Loc)))); end if; Append_To (Comp_List, Make_Component_Declaration (Loc, Defining_Identifier => Make_Temporary (Loc, 'C'), Component_Definition => Make_Component_Definition (Loc, Aliased_Present => False, Subtype_Indication => New_Occurrence_Of (Str_Type, Loc)))); Append_To (List_Def, Make_Full_Type_Declaration (Loc, Defining_Identifier => Equiv_Type, Type_Definition => Make_Record_Definition (Loc, Component_List => Make_Component_List (Loc, Component_Items => Comp_List, Variant_Part => Empty)))); -- Suppress all checks during the analysis of the expanded code to avoid -- the generation of spurious warnings under ZFP run-time. Insert_Actions (E, List_Def, Suppress => All_Checks); return Equiv_Type; end Make_CW_Equivalent_Type; ------------------------- -- Make_Invariant_Call -- ------------------------- function Make_Invariant_Call (Expr : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Expr); Typ : constant Entity_Id := Base_Type (Etype (Expr)); Proc_Id : Entity_Id; begin pragma Assert (Has_Invariants (Typ)); Proc_Id := Invariant_Procedure (Typ); pragma Assert (Present (Proc_Id)); return Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Proc_Id, Loc), Parameter_Associations => New_List (Relocate_Node (Expr))); end Make_Invariant_Call; ------------------------ -- Make_Literal_Range -- ------------------------ function Make_Literal_Range (Loc : Source_Ptr; Literal_Typ : Entity_Id) return Node_Id is Lo : constant Node_Id := New_Copy_Tree (String_Literal_Low_Bound (Literal_Typ)); Index : constant Entity_Id := Etype (Lo); Hi : Node_Id; Length_Expr : constant Node_Id := Make_Op_Subtract (Loc, Left_Opnd => Make_Integer_Literal (Loc, Intval => String_Literal_Length (Literal_Typ)), Right_Opnd => Make_Integer_Literal (Loc, 1)); begin Set_Analyzed (Lo, False); if Is_Integer_Type (Index) then Hi := Make_Op_Add (Loc, Left_Opnd => New_Copy_Tree (Lo), Right_Opnd => Length_Expr); else Hi := Make_Attribute_Reference (Loc, Attribute_Name => Name_Val, Prefix => New_Occurrence_Of (Index, Loc), Expressions => New_List ( Make_Op_Add (Loc, Left_Opnd => Make_Attribute_Reference (Loc, Attribute_Name => Name_Pos, Prefix => New_Occurrence_Of (Index, Loc), Expressions => New_List (New_Copy_Tree (Lo))), Right_Opnd => Length_Expr))); end if; return Make_Range (Loc, Low_Bound => Lo, High_Bound => Hi); end Make_Literal_Range; -------------------------- -- Make_Non_Empty_Check -- -------------------------- function Make_Non_Empty_Check (Loc : Source_Ptr; N : Node_Id) return Node_Id is begin return Make_Op_Ne (Loc, Left_Opnd => Make_Attribute_Reference (Loc, Attribute_Name => Name_Length, Prefix => Duplicate_Subexpr_No_Checks (N, Name_Req => True)), Right_Opnd => Make_Integer_Literal (Loc, 0)); end Make_Non_Empty_Check; ------------------------- -- Make_Predicate_Call -- ------------------------- -- WARNING: This routine manages Ghost regions. Return statements must be -- replaced by gotos which jump to the end of the routine and restore the -- Ghost mode. function Make_Predicate_Call (Typ : Entity_Id; Expr : Node_Id; Mem : Boolean := False) return Node_Id is Loc : constant Source_Ptr := Sloc (Expr); Call : Node_Id; Func_Id : Entity_Id; Mode : Ghost_Mode_Type; begin pragma Assert (Present (Predicate_Function (Typ))); -- The related type may be subject to pragma Ghost. Set the mode now to -- ensure that the call is properly marked as Ghost. Set_Ghost_Mode (Typ, Mode); -- Call special membership version if requested and available if Mem and then Present (Predicate_Function_M (Typ)) then Func_Id := Predicate_Function_M (Typ); else Func_Id := Predicate_Function (Typ); end if; -- Case of calling normal predicate function Call := Make_Function_Call (Loc, Name => New_Occurrence_Of (Func_Id, Loc), Parameter_Associations => New_List (Relocate_Node (Expr))); Restore_Ghost_Mode (Mode); return Call; end Make_Predicate_Call; -------------------------- -- Make_Predicate_Check -- -------------------------- function Make_Predicate_Check (Typ : Entity_Id; Expr : Node_Id) return Node_Id is procedure Replace_Subtype_Reference (N : Node_Id); -- Replace current occurrences of the subtype to which a dynamic -- predicate applies, by the expression that triggers a predicate -- check. This is needed for aspect Predicate_Failure, for which -- we do not generate a wrapper procedure, but simply modify the -- expression for the pragma of the predicate check. -------------------------------- -- Replace_Subtype_Reference -- -------------------------------- procedure Replace_Subtype_Reference (N : Node_Id) is begin Rewrite (N, New_Copy_Tree (Expr)); -- We want to treat the node as if it comes from source, so -- that ASIS will not ignore it. Set_Comes_From_Source (N, True); end Replace_Subtype_Reference; procedure Replace_Subtype_References is new Replace_Type_References_Generic (Replace_Subtype_Reference); -- Local variables Loc : constant Source_Ptr := Sloc (Expr); Arg_List : List_Id; Fail_Expr : Node_Id; Nam : Name_Id; -- Start of processing for Make_Predicate_Check begin -- If predicate checks are suppressed, then return a null statement. For -- this call, we check only the scope setting. If the caller wants to -- check a specific entity's setting, they must do it manually. if Predicate_Checks_Suppressed (Empty) then return Make_Null_Statement (Loc); end if; -- Do not generate a check within an internal subprogram (stream -- functions and the like, including including predicate functions). if Within_Internal_Subprogram then return Make_Null_Statement (Loc); end if; -- Compute proper name to use, we need to get this right so that the -- right set of check policies apply to the Check pragma we are making. if Has_Dynamic_Predicate_Aspect (Typ) then Nam := Name_Dynamic_Predicate; elsif Has_Static_Predicate_Aspect (Typ) then Nam := Name_Static_Predicate; else Nam := Name_Predicate; end if; Arg_List := New_List ( Make_Pragma_Argument_Association (Loc, Expression => Make_Identifier (Loc, Nam)), Make_Pragma_Argument_Association (Loc, Expression => Make_Predicate_Call (Typ, Expr))); -- If subtype has Predicate_Failure defined, add the correponding -- expression as an additional pragma parameter, after replacing -- current instances with the expression being checked. if Has_Aspect (Typ, Aspect_Predicate_Failure) then Fail_Expr := New_Copy_Tree (Expression (Find_Aspect (Typ, Aspect_Predicate_Failure))); Replace_Subtype_References (Fail_Expr, Typ); Append_To (Arg_List, Make_Pragma_Argument_Association (Loc, Expression => Fail_Expr)); end if; return Make_Pragma (Loc, Chars => Name_Check, Pragma_Argument_Associations => Arg_List); end Make_Predicate_Check; ---------------------------- -- Make_Subtype_From_Expr -- ---------------------------- -- 1. If Expr is an unconstrained array expression, creates -- Unc_Type(Expr'first(1)..Expr'last(1),..., Expr'first(n)..Expr'last(n)) -- 2. If Expr is a unconstrained discriminated type expression, creates -- Unc_Type(Expr.Discr1, ... , Expr.Discr_n) -- 3. If Expr is class-wide, creates an implicit class-wide subtype function Make_Subtype_From_Expr (E : Node_Id; Unc_Typ : Entity_Id; Related_Id : Entity_Id := Empty) return Node_Id is List_Constr : constant List_Id := New_List; Loc : constant Source_Ptr := Sloc (E); D : Entity_Id; Full_Exp : Node_Id; Full_Subtyp : Entity_Id; High_Bound : Entity_Id; Index_Typ : Entity_Id; Low_Bound : Entity_Id; Priv_Subtyp : Entity_Id; Utyp : Entity_Id; begin if Is_Private_Type (Unc_Typ) and then Has_Unknown_Discriminants (Unc_Typ) then -- The caller requests a unique external name for both the private -- and the full subtype. if Present (Related_Id) then Full_Subtyp := Make_Defining_Identifier (Loc, Chars => New_External_Name (Chars (Related_Id), 'C')); Priv_Subtyp := Make_Defining_Identifier (Loc, Chars => New_External_Name (Chars (Related_Id), 'P')); else Full_Subtyp := Make_Temporary (Loc, 'C'); Priv_Subtyp := Make_Temporary (Loc, 'P'); end if; -- Prepare the subtype completion. Use the base type to find the -- underlying type because the type may be a generic actual or an -- explicit subtype. Utyp := Underlying_Type (Base_Type (Unc_Typ)); Full_Exp := Unchecked_Convert_To (Utyp, Duplicate_Subexpr_No_Checks (E)); Set_Parent (Full_Exp, Parent (E)); Insert_Action (E, Make_Subtype_Declaration (Loc, Defining_Identifier => Full_Subtyp, Subtype_Indication => Make_Subtype_From_Expr (Full_Exp, Utyp))); -- Define the dummy private subtype Set_Ekind (Priv_Subtyp, Subtype_Kind (Ekind (Unc_Typ))); Set_Etype (Priv_Subtyp, Base_Type (Unc_Typ)); Set_Scope (Priv_Subtyp, Full_Subtyp); Set_Is_Constrained (Priv_Subtyp); Set_Is_Tagged_Type (Priv_Subtyp, Is_Tagged_Type (Unc_Typ)); Set_Is_Itype (Priv_Subtyp); Set_Associated_Node_For_Itype (Priv_Subtyp, E); if Is_Tagged_Type (Priv_Subtyp) then Set_Class_Wide_Type (Base_Type (Priv_Subtyp), Class_Wide_Type (Unc_Typ)); Set_Direct_Primitive_Operations (Priv_Subtyp, Direct_Primitive_Operations (Unc_Typ)); end if; Set_Full_View (Priv_Subtyp, Full_Subtyp); return New_Occurrence_Of (Priv_Subtyp, Loc); elsif Is_Array_Type (Unc_Typ) then Index_Typ := First_Index (Unc_Typ); for J in 1 .. Number_Dimensions (Unc_Typ) loop -- Capture the bounds of each index constraint in case the context -- is an object declaration of an unconstrained type initialized -- by a function call: -- Obj : Unconstr_Typ := Func_Call; -- This scenario requires secondary scope management and the index -- constraint cannot depend on the temporary used to capture the -- result of the function call. -- SS_Mark; -- Temp : Unconstr_Typ_Ptr := Func_Call'reference; -- subtype S is Unconstr_Typ (Temp.all'First .. Temp.all'Last); -- Obj : S := Temp.all; -- SS_Release; -- Temp is gone at this point, bounds of S are -- -- non existent. -- Generate: -- Low_Bound : constant Base_Type (Index_Typ) := E'First (J); Low_Bound := Make_Temporary (Loc, 'B'); Insert_Action (E, Make_Object_Declaration (Loc, Defining_Identifier => Low_Bound, Object_Definition => New_Occurrence_Of (Base_Type (Etype (Index_Typ)), Loc), Constant_Present => True, Expression => Make_Attribute_Reference (Loc, Prefix => Duplicate_Subexpr_No_Checks (E), Attribute_Name => Name_First, Expressions => New_List ( Make_Integer_Literal (Loc, J))))); -- Generate: -- High_Bound : constant Base_Type (Index_Typ) := E'Last (J); High_Bound := Make_Temporary (Loc, 'B'); Insert_Action (E, Make_Object_Declaration (Loc, Defining_Identifier => High_Bound, Object_Definition => New_Occurrence_Of (Base_Type (Etype (Index_Typ)), Loc), Constant_Present => True, Expression => Make_Attribute_Reference (Loc, Prefix => Duplicate_Subexpr_No_Checks (E), Attribute_Name => Name_Last, Expressions => New_List ( Make_Integer_Literal (Loc, J))))); Append_To (List_Constr, Make_Range (Loc, Low_Bound => New_Occurrence_Of (Low_Bound, Loc), High_Bound => New_Occurrence_Of (High_Bound, Loc))); Index_Typ := Next_Index (Index_Typ); end loop; elsif Is_Class_Wide_Type (Unc_Typ) then declare CW_Subtype : Entity_Id; EQ_Typ : Entity_Id := Empty; begin -- A class-wide equivalent type is not needed on VM targets -- because the VM back-ends handle the class-wide object -- initialization itself (and doesn't need or want the -- additional intermediate type to handle the assignment). if Expander_Active and then Tagged_Type_Expansion then -- If this is the class-wide type of a completion that is a -- record subtype, set the type of the class-wide type to be -- the full base type, for use in the expanded code for the -- equivalent type. Should this be done earlier when the -- completion is analyzed ??? if Is_Private_Type (Etype (Unc_Typ)) and then Ekind (Full_View (Etype (Unc_Typ))) = E_Record_Subtype then Set_Etype (Unc_Typ, Base_Type (Full_View (Etype (Unc_Typ)))); end if; EQ_Typ := Make_CW_Equivalent_Type (Unc_Typ, E); end if; CW_Subtype := New_Class_Wide_Subtype (Unc_Typ, E); Set_Equivalent_Type (CW_Subtype, EQ_Typ); Set_Cloned_Subtype (CW_Subtype, Base_Type (Unc_Typ)); return New_Occurrence_Of (CW_Subtype, Loc); end; -- Indefinite record type with discriminants else D := First_Discriminant (Unc_Typ); while Present (D) loop Append_To (List_Constr, Make_Selected_Component (Loc, Prefix => Duplicate_Subexpr_No_Checks (E), Selector_Name => New_Occurrence_Of (D, Loc))); Next_Discriminant (D); end loop; end if; return Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (Unc_Typ, Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => List_Constr)); end Make_Subtype_From_Expr; ---------------------------- -- Matching_Standard_Type -- ---------------------------- function Matching_Standard_Type (Typ : Entity_Id) return Entity_Id is pragma Assert (Is_Scalar_Type (Typ)); Siz : constant Uint := Esize (Typ); begin -- Floating-point cases if Is_Floating_Point_Type (Typ) then if Siz <= Esize (Standard_Short_Float) then return Standard_Short_Float; elsif Siz <= Esize (Standard_Float) then return Standard_Float; elsif Siz <= Esize (Standard_Long_Float) then return Standard_Long_Float; elsif Siz <= Esize (Standard_Long_Long_Float) then return Standard_Long_Long_Float; else raise Program_Error; end if; -- Integer cases (includes fixed-point types) -- Unsigned integer cases (includes normal enumeration types) elsif Is_Unsigned_Type (Typ) then if Siz <= Esize (Standard_Short_Short_Unsigned) then return Standard_Short_Short_Unsigned; elsif Siz <= Esize (Standard_Short_Unsigned) then return Standard_Short_Unsigned; elsif Siz <= Esize (Standard_Unsigned) then return Standard_Unsigned; elsif Siz <= Esize (Standard_Long_Unsigned) then return Standard_Long_Unsigned; elsif Siz <= Esize (Standard_Long_Long_Unsigned) then return Standard_Long_Long_Unsigned; else raise Program_Error; end if; -- Signed integer cases else if Siz <= Esize (Standard_Short_Short_Integer) then return Standard_Short_Short_Integer; elsif Siz <= Esize (Standard_Short_Integer) then return Standard_Short_Integer; elsif Siz <= Esize (Standard_Integer) then return Standard_Integer; elsif Siz <= Esize (Standard_Long_Integer) then return Standard_Long_Integer; elsif Siz <= Esize (Standard_Long_Long_Integer) then return Standard_Long_Long_Integer; else raise Program_Error; end if; end if; end Matching_Standard_Type; ----------------------------- -- May_Generate_Large_Temp -- ----------------------------- -- At the current time, the only types that we return False for (i.e. where -- we decide we know they cannot generate large temps) are ones where we -- know the size is 256 bits or less at compile time, and we are still not -- doing a thorough job on arrays and records ??? function May_Generate_Large_Temp (Typ : Entity_Id) return Boolean is begin if not Size_Known_At_Compile_Time (Typ) then return False; elsif Esize (Typ) /= 0 and then Esize (Typ) <= 256 then return False; elsif Is_Array_Type (Typ) and then Present (Packed_Array_Impl_Type (Typ)) then return May_Generate_Large_Temp (Packed_Array_Impl_Type (Typ)); -- We could do more here to find other small types ??? else return True; end if; end May_Generate_Large_Temp; ------------------------ -- Needs_Finalization -- ------------------------ function Needs_Finalization (T : Entity_Id) return Boolean is function Has_Some_Controlled_Component (Rec : Entity_Id) return Boolean; -- If type is not frozen yet, check explicitly among its components, -- because the Has_Controlled_Component flag is not necessarily set. ----------------------------------- -- Has_Some_Controlled_Component -- ----------------------------------- function Has_Some_Controlled_Component (Rec : Entity_Id) return Boolean is Comp : Entity_Id; begin if Has_Controlled_Component (Rec) then return True; elsif not Is_Frozen (Rec) then if Is_Record_Type (Rec) then Comp := First_Entity (Rec); while Present (Comp) loop if not Is_Type (Comp) and then Needs_Finalization (Etype (Comp)) then return True; end if; Next_Entity (Comp); end loop; return False; else return Is_Array_Type (Rec) and then Needs_Finalization (Component_Type (Rec)); end if; else return False; end if; end Has_Some_Controlled_Component; -- Start of processing for Needs_Finalization begin -- Certain run-time configurations and targets do not provide support -- for controlled types. if Restriction_Active (No_Finalization) then return False; -- C++ types are not considered controlled. It is assumed that the -- non-Ada side will handle their clean up. elsif Convention (T) = Convention_CPP then return False; -- Never needs finalization if Disable_Controlled set elsif Disable_Controlled (T) then return False; elsif Is_Class_Wide_Type (T) and then Disable_Controlled (Etype (T)) then return False; else -- Class-wide types are treated as controlled because derivations -- from the root type can introduce controlled components. return Is_Class_Wide_Type (T) or else Is_Controlled (T) or else Has_Some_Controlled_Component (T) or else (Is_Concurrent_Type (T) and then Present (Corresponding_Record_Type (T)) and then Needs_Finalization (Corresponding_Record_Type (T))); end if; end Needs_Finalization; ---------------------------- -- Needs_Constant_Address -- ---------------------------- function Needs_Constant_Address (Decl : Node_Id; Typ : Entity_Id) return Boolean is begin -- If we have no initialization of any kind, then we don't need to place -- any restrictions on the address clause, because the object will be -- elaborated after the address clause is evaluated. This happens if the -- declaration has no initial expression, or the type has no implicit -- initialization, or the object is imported. -- The same holds for all initialized scalar types and all access types. -- Packed bit arrays of size up to 64 are represented using a modular -- type with an initialization (to zero) and can be processed like other -- initialized scalar types. -- If the type is controlled, code to attach the object to a -- finalization chain is generated at the point of declaration, and -- therefore the elaboration of the object cannot be delayed: the -- address expression must be a constant. if No (Expression (Decl)) and then not Needs_Finalization (Typ) and then (not Has_Non_Null_Base_Init_Proc (Typ) or else Is_Imported (Defining_Identifier (Decl))) then return False; elsif (Present (Expression (Decl)) and then Is_Scalar_Type (Typ)) or else Is_Access_Type (Typ) or else (Is_Bit_Packed_Array (Typ) and then Is_Modular_Integer_Type (Packed_Array_Impl_Type (Typ))) then return False; else -- Otherwise, we require the address clause to be constant because -- the call to the initialization procedure (or the attach code) has -- to happen at the point of the declaration. -- Actually the IP call has been moved to the freeze actions anyway, -- so maybe we can relax this restriction??? return True; end if; end Needs_Constant_Address; ---------------------------- -- New_Class_Wide_Subtype -- ---------------------------- function New_Class_Wide_Subtype (CW_Typ : Entity_Id; N : Node_Id) return Entity_Id is Res : constant Entity_Id := Create_Itype (E_Void, N); Res_Name : constant Name_Id := Chars (Res); Res_Scope : constant Entity_Id := Scope (Res); begin Copy_Node (CW_Typ, Res); Set_Comes_From_Source (Res, False); Set_Sloc (Res, Sloc (N)); Set_Is_Itype (Res); Set_Associated_Node_For_Itype (Res, N); Set_Is_Public (Res, False); -- By default, may be changed below. Set_Public_Status (Res); Set_Chars (Res, Res_Name); Set_Scope (Res, Res_Scope); Set_Ekind (Res, E_Class_Wide_Subtype); Set_Next_Entity (Res, Empty); Set_Etype (Res, Base_Type (CW_Typ)); Set_Is_Frozen (Res, False); Set_Freeze_Node (Res, Empty); return (Res); end New_Class_Wide_Subtype; -------------------------------- -- Non_Limited_Designated_Type -- --------------------------------- function Non_Limited_Designated_Type (T : Entity_Id) return Entity_Id is Desig : constant Entity_Id := Designated_Type (T); begin if Has_Non_Limited_View (Desig) then return Non_Limited_View (Desig); else return Desig; end if; end Non_Limited_Designated_Type; ----------------------------------- -- OK_To_Do_Constant_Replacement -- ----------------------------------- function OK_To_Do_Constant_Replacement (E : Entity_Id) return Boolean is ES : constant Entity_Id := Scope (E); CS : Entity_Id; begin -- Do not replace statically allocated objects, because they may be -- modified outside the current scope. if Is_Statically_Allocated (E) then return False; -- Do not replace aliased or volatile objects, since we don't know what -- else might change the value. elsif Is_Aliased (E) or else Treat_As_Volatile (E) then return False; -- Debug flag -gnatdM disconnects this optimization elsif Debug_Flag_MM then return False; -- Otherwise check scopes else CS := Current_Scope; loop -- If we are in right scope, replacement is safe if CS = ES then return True; -- Packages do not affect the determination of safety elsif Ekind (CS) = E_Package then exit when CS = Standard_Standard; CS := Scope (CS); -- Blocks do not affect the determination of safety elsif Ekind (CS) = E_Block then CS := Scope (CS); -- Loops do not affect the determination of safety. Note that we -- kill all current values on entry to a loop, so we are just -- talking about processing within a loop here. elsif Ekind (CS) = E_Loop then CS := Scope (CS); -- Otherwise, the reference is dubious, and we cannot be sure that -- it is safe to do the replacement. else exit; end if; end loop; return False; end if; end OK_To_Do_Constant_Replacement; ------------------------------------ -- Possible_Bit_Aligned_Component -- ------------------------------------ function Possible_Bit_Aligned_Component (N : Node_Id) return Boolean is begin -- Do not process an unanalyzed node because it is not yet decorated and -- most checks performed below will fail. if not Analyzed (N) then return False; end if; case Nkind (N) is -- Case of indexed component when N_Indexed_Component => declare P : constant Node_Id := Prefix (N); Ptyp : constant Entity_Id := Etype (P); begin -- If we know the component size and it is less than 64, then -- we are definitely OK. The back end always does assignment of -- misaligned small objects correctly. if Known_Static_Component_Size (Ptyp) and then Component_Size (Ptyp) <= 64 then return False; -- Otherwise, we need to test the prefix, to see if we are -- indexing from a possibly unaligned component. else return Possible_Bit_Aligned_Component (P); end if; end; -- Case of selected component when N_Selected_Component => declare P : constant Node_Id := Prefix (N); Comp : constant Entity_Id := Entity (Selector_Name (N)); begin -- If there is no component clause, then we are in the clear -- since the back end will never misalign a large component -- unless it is forced to do so. In the clear means we need -- only the recursive test on the prefix. if Component_May_Be_Bit_Aligned (Comp) then return True; else return Possible_Bit_Aligned_Component (P); end if; end; -- For a slice, test the prefix, if that is possibly misaligned, -- then for sure the slice is. when N_Slice => return Possible_Bit_Aligned_Component (Prefix (N)); -- For an unchecked conversion, check whether the expression may -- be bit-aligned. when N_Unchecked_Type_Conversion => return Possible_Bit_Aligned_Component (Expression (N)); -- If we have none of the above, it means that we have fallen off the -- top testing prefixes recursively, and we now have a stand alone -- object, where we don't have a problem, unless this is a renaming, -- in which case we need to look into the renamed object. when others => if Is_Entity_Name (N) and then Present (Renamed_Object (Entity (N))) then return Possible_Bit_Aligned_Component (Renamed_Object (Entity (N))); else return False; end if; end case; end Possible_Bit_Aligned_Component; ----------------------------------------------- -- Process_Statements_For_Controlled_Objects -- ----------------------------------------------- procedure Process_Statements_For_Controlled_Objects (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); function Are_Wrapped (L : List_Id) return Boolean; -- Determine whether list L contains only one statement which is a block function Wrap_Statements_In_Block (L : List_Id; Scop : Entity_Id := Current_Scope) return Node_Id; -- Given a list of statements L, wrap it in a block statement and return -- the generated node. Scop is either the current scope or the scope of -- the context (if applicable). ----------------- -- Are_Wrapped -- ----------------- function Are_Wrapped (L : List_Id) return Boolean is Stmt : constant Node_Id := First (L); begin return Present (Stmt) and then No (Next (Stmt)) and then Nkind (Stmt) = N_Block_Statement; end Are_Wrapped; ------------------------------ -- Wrap_Statements_In_Block -- ------------------------------ function Wrap_Statements_In_Block (L : List_Id; Scop : Entity_Id := Current_Scope) return Node_Id is Block_Id : Entity_Id; Block_Nod : Node_Id; Iter_Loop : Entity_Id; begin Block_Nod := Make_Block_Statement (Loc, Declarations => No_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => L)); -- Create a label for the block in case the block needs to manage the -- secondary stack. A label allows for flag Uses_Sec_Stack to be set. Add_Block_Identifier (Block_Nod, Block_Id); -- When wrapping the statements of an iterator loop, check whether -- the loop requires secondary stack management and if so, propagate -- the appropriate flags to the block. This ensures that the cursor -- is properly cleaned up at each iteration of the loop. Iter_Loop := Find_Enclosing_Iterator_Loop (Scop); if Present (Iter_Loop) then Set_Uses_Sec_Stack (Block_Id, Uses_Sec_Stack (Iter_Loop)); -- Secondary stack reclamation is suppressed when the associated -- iterator loop contains a return statement which uses the stack. Set_Sec_Stack_Needed_For_Return (Block_Id, Sec_Stack_Needed_For_Return (Iter_Loop)); end if; return Block_Nod; end Wrap_Statements_In_Block; -- Local variables Block : Node_Id; -- Start of processing for Process_Statements_For_Controlled_Objects begin -- Whenever a non-handled statement list is wrapped in a block, the -- block must be explicitly analyzed to redecorate all entities in the -- list and ensure that a finalizer is properly built. case Nkind (N) is when N_Conditional_Entry_Call | N_Elsif_Part | N_If_Statement | N_Selective_Accept => -- Check the "then statements" for elsif parts and if statements if Nkind_In (N, N_Elsif_Part, N_If_Statement) and then not Is_Empty_List (Then_Statements (N)) and then not Are_Wrapped (Then_Statements (N)) and then Requires_Cleanup_Actions (Then_Statements (N), False, False) then Block := Wrap_Statements_In_Block (Then_Statements (N)); Set_Then_Statements (N, New_List (Block)); Analyze (Block); end if; -- Check the "else statements" for conditional entry calls, if -- statements and selective accepts. if Nkind_In (N, N_Conditional_Entry_Call, N_If_Statement, N_Selective_Accept) and then not Is_Empty_List (Else_Statements (N)) and then not Are_Wrapped (Else_Statements (N)) and then Requires_Cleanup_Actions (Else_Statements (N), False, False) then Block := Wrap_Statements_In_Block (Else_Statements (N)); Set_Else_Statements (N, New_List (Block)); Analyze (Block); end if; when N_Abortable_Part | N_Accept_Alternative | N_Case_Statement_Alternative | N_Delay_Alternative | N_Entry_Call_Alternative | N_Exception_Handler | N_Loop_Statement | N_Triggering_Alternative => if not Is_Empty_List (Statements (N)) and then not Are_Wrapped (Statements (N)) and then Requires_Cleanup_Actions (Statements (N), False, False) then if Nkind (N) = N_Loop_Statement and then Present (Identifier (N)) then Block := Wrap_Statements_In_Block (L => Statements (N), Scop => Entity (Identifier (N))); else Block := Wrap_Statements_In_Block (Statements (N)); end if; Set_Statements (N, New_List (Block)); Analyze (Block); end if; when others => null; end case; end Process_Statements_For_Controlled_Objects; ------------------ -- Power_Of_Two -- ------------------ function Power_Of_Two (N : Node_Id) return Nat is Typ : constant Entity_Id := Etype (N); pragma Assert (Is_Integer_Type (Typ)); Siz : constant Nat := UI_To_Int (Esize (Typ)); Val : Uint; begin if not Compile_Time_Known_Value (N) then return 0; else Val := Expr_Value (N); for J in 1 .. Siz - 1 loop if Val = Uint_2 ** J then return J; end if; end loop; return 0; end if; end Power_Of_Two; ---------------------- -- Remove_Init_Call -- ---------------------- function Remove_Init_Call (Var : Entity_Id; Rep_Clause : Node_Id) return Node_Id is Par : constant Node_Id := Parent (Var); Typ : constant Entity_Id := Etype (Var); Init_Proc : Entity_Id; -- Initialization procedure for Typ function Find_Init_Call_In_List (From : Node_Id) return Node_Id; -- Look for init call for Var starting at From and scanning the -- enclosing list until Rep_Clause or the end of the list is reached. ---------------------------- -- Find_Init_Call_In_List -- ---------------------------- function Find_Init_Call_In_List (From : Node_Id) return Node_Id is Init_Call : Node_Id; begin Init_Call := From; while Present (Init_Call) and then Init_Call /= Rep_Clause loop if Nkind (Init_Call) = N_Procedure_Call_Statement and then Is_Entity_Name (Name (Init_Call)) and then Entity (Name (Init_Call)) = Init_Proc then return Init_Call; end if; Next (Init_Call); end loop; return Empty; end Find_Init_Call_In_List; Init_Call : Node_Id; -- Start of processing for Find_Init_Call begin if Present (Initialization_Statements (Var)) then Init_Call := Initialization_Statements (Var); Set_Initialization_Statements (Var, Empty); elsif not Has_Non_Null_Base_Init_Proc (Typ) then -- No init proc for the type, so obviously no call to be found return Empty; else -- We might be able to handle other cases below by just properly -- setting Initialization_Statements at the point where the init proc -- call is generated??? Init_Proc := Base_Init_Proc (Typ); -- First scan the list containing the declaration of Var Init_Call := Find_Init_Call_In_List (From => Next (Par)); -- If not found, also look on Var's freeze actions list, if any, -- since the init call may have been moved there (case of an address -- clause applying to Var). if No (Init_Call) and then Present (Freeze_Node (Var)) then Init_Call := Find_Init_Call_In_List (First (Actions (Freeze_Node (Var)))); end if; -- If the initialization call has actuals that use the secondary -- stack, the call may have been wrapped into a temporary block, in -- which case the block itself has to be removed. if No (Init_Call) and then Nkind (Next (Par)) = N_Block_Statement then declare Blk : constant Node_Id := Next (Par); begin if Present (Find_Init_Call_In_List (First (Statements (Handled_Statement_Sequence (Blk))))) then Init_Call := Blk; end if; end; end if; end if; if Present (Init_Call) then Remove (Init_Call); end if; return Init_Call; end Remove_Init_Call; ------------------------- -- Remove_Side_Effects -- ------------------------- procedure Remove_Side_Effects (Exp : Node_Id; Name_Req : Boolean := False; Renaming_Req : Boolean := False; Variable_Ref : Boolean := False; Related_Id : Entity_Id := Empty; Is_Low_Bound : Boolean := False; Is_High_Bound : Boolean := False; Check_Side_Effects : Boolean := True) is function Build_Temporary (Loc : Source_Ptr; Id : Character; Related_Nod : Node_Id := Empty) return Entity_Id; -- Create an external symbol of the form xxx_FIRST/_LAST if Related_Nod -- is present (xxx is taken from the Chars field of Related_Nod), -- otherwise it generates an internal temporary. --------------------- -- Build_Temporary -- --------------------- function Build_Temporary (Loc : Source_Ptr; Id : Character; Related_Nod : Node_Id := Empty) return Entity_Id is Temp_Nam : Name_Id; begin -- The context requires an external symbol if Present (Related_Id) then if Is_Low_Bound then Temp_Nam := New_External_Name (Chars (Related_Id), "_FIRST"); else pragma Assert (Is_High_Bound); Temp_Nam := New_External_Name (Chars (Related_Id), "_LAST"); end if; return Make_Defining_Identifier (Loc, Temp_Nam); -- Otherwise generate an internal temporary else return Make_Temporary (Loc, Id, Related_Nod); end if; end Build_Temporary; -- Local variables Loc : constant Source_Ptr := Sloc (Exp); Exp_Type : constant Entity_Id := Etype (Exp); Svg_Suppress : constant Suppress_Record := Scope_Suppress; Def_Id : Entity_Id; E : Node_Id; New_Exp : Node_Id; Ptr_Typ_Decl : Node_Id; Ref_Type : Entity_Id; Res : Node_Id; -- Start of processing for Remove_Side_Effects begin -- Handle cases in which there is nothing to do. In GNATprove mode, -- removal of side effects is useful for the light expansion of -- renamings. This removal should only occur when not inside a -- generic and not doing a pre-analysis. if not Expander_Active and (Inside_A_Generic or not Full_Analysis or not GNATprove_Mode) then return; -- Cannot generate temporaries if the invocation to remove side effects -- was issued too early and the type of the expression is not resolved -- (this happens because routines Duplicate_Subexpr_XX implicitly invoke -- Remove_Side_Effects). elsif No (Exp_Type) or else Ekind (Exp_Type) = E_Access_Attribute_Type then return; -- Nothing to do if prior expansion determined that a function call does -- not require side effect removal. elsif Nkind (Exp) = N_Function_Call and then No_Side_Effect_Removal (Exp) then return; -- No action needed for side-effect free expressions elsif Check_Side_Effects and then Side_Effect_Free (Exp, Name_Req, Variable_Ref) then return; end if; -- The remaining processing is done with all checks suppressed -- Note: from now on, don't use return statements, instead do a goto -- Leave, to ensure that we properly restore Scope_Suppress.Suppress. Scope_Suppress.Suppress := (others => True); -- If this is an elementary or a small not by-reference record type, and -- we need to capture the value, just make a constant; this is cheap and -- objects of both kinds of types can be bit aligned, so it might not be -- possible to generate a reference to them. Likewise if this is not a -- name reference, except for a type conversion because we would enter -- an infinite recursion with Checks.Apply_Predicate_Check if the target -- type has predicates (and type conversions need a specific treatment -- anyway, see below). Also do it if we have a volatile reference and -- Name_Req is not set (see comments for Side_Effect_Free). if (Is_Elementary_Type (Exp_Type) or else (Is_Record_Type (Exp_Type) and then Known_Static_RM_Size (Exp_Type) and then RM_Size (Exp_Type) <= 64 and then not Has_Discriminants (Exp_Type) and then not Is_By_Reference_Type (Exp_Type))) and then (Variable_Ref or else (not Is_Name_Reference (Exp) and then Nkind (Exp) /= N_Type_Conversion) or else (not Name_Req and then Is_Volatile_Reference (Exp))) then Def_Id := Build_Temporary (Loc, 'R', Exp); Set_Etype (Def_Id, Exp_Type); Res := New_Occurrence_Of (Def_Id, Loc); -- If the expression is a packed reference, it must be reanalyzed and -- expanded, depending on context. This is the case for actuals where -- a constraint check may capture the actual before expansion of the -- call is complete. if Nkind (Exp) = N_Indexed_Component and then Is_Packed (Etype (Prefix (Exp))) then Set_Analyzed (Exp, False); Set_Analyzed (Prefix (Exp), False); end if; -- Generate: -- Rnn : Exp_Type renames Expr; if Renaming_Req then E := Make_Object_Renaming_Declaration (Loc, Defining_Identifier => Def_Id, Subtype_Mark => New_Occurrence_Of (Exp_Type, Loc), Name => Relocate_Node (Exp)); -- Generate: -- Rnn : constant Exp_Type := Expr; else E := Make_Object_Declaration (Loc, Defining_Identifier => Def_Id, Object_Definition => New_Occurrence_Of (Exp_Type, Loc), Constant_Present => True, Expression => Relocate_Node (Exp)); Set_Assignment_OK (E); end if; Insert_Action (Exp, E); -- If the expression has the form v.all then we can just capture the -- pointer, and then do an explicit dereference on the result, but -- this is not right if this is a volatile reference. elsif Nkind (Exp) = N_Explicit_Dereference and then not Is_Volatile_Reference (Exp) then Def_Id := Build_Temporary (Loc, 'R', Exp); Res := Make_Explicit_Dereference (Loc, New_Occurrence_Of (Def_Id, Loc)); Insert_Action (Exp, Make_Object_Declaration (Loc, Defining_Identifier => Def_Id, Object_Definition => New_Occurrence_Of (Etype (Prefix (Exp)), Loc), Constant_Present => True, Expression => Relocate_Node (Prefix (Exp)))); -- Similar processing for an unchecked conversion of an expression of -- the form v.all, where we want the same kind of treatment. elsif Nkind (Exp) = N_Unchecked_Type_Conversion and then Nkind (Expression (Exp)) = N_Explicit_Dereference then Remove_Side_Effects (Expression (Exp), Name_Req, Variable_Ref); goto Leave; -- If this is a type conversion, leave the type conversion and remove -- the side effects in the expression. This is important in several -- circumstances: for change of representations, and also when this is a -- view conversion to a smaller object, where gigi can end up creating -- its own temporary of the wrong size. elsif Nkind (Exp) = N_Type_Conversion then Remove_Side_Effects (Expression (Exp), Name_Req, Variable_Ref); -- Generating C code the type conversion of an access to constrained -- array type into an access to unconstrained array type involves -- initializing a fat pointer and the expression must be free of -- side effects to safely compute its bounds. if Modify_Tree_For_C and then Is_Access_Type (Etype (Exp)) and then Is_Array_Type (Designated_Type (Etype (Exp))) and then not Is_Constrained (Designated_Type (Etype (Exp))) then Def_Id := Build_Temporary (Loc, 'R', Exp); Set_Etype (Def_Id, Exp_Type); Res := New_Occurrence_Of (Def_Id, Loc); Insert_Action (Exp, Make_Object_Declaration (Loc, Defining_Identifier => Def_Id, Object_Definition => New_Occurrence_Of (Exp_Type, Loc), Constant_Present => True, Expression => Relocate_Node (Exp))); else goto Leave; end if; -- If this is an unchecked conversion that Gigi can't handle, make -- a copy or a use a renaming to capture the value. elsif Nkind (Exp) = N_Unchecked_Type_Conversion and then not Safe_Unchecked_Type_Conversion (Exp) then if CW_Or_Has_Controlled_Part (Exp_Type) then -- Use a renaming to capture the expression, rather than create -- a controlled temporary. Def_Id := Build_Temporary (Loc, 'R', Exp); Res := New_Occurrence_Of (Def_Id, Loc); Insert_Action (Exp, Make_Object_Renaming_Declaration (Loc, Defining_Identifier => Def_Id, Subtype_Mark => New_Occurrence_Of (Exp_Type, Loc), Name => Relocate_Node (Exp))); else Def_Id := Build_Temporary (Loc, 'R', Exp); Set_Etype (Def_Id, Exp_Type); Res := New_Occurrence_Of (Def_Id, Loc); E := Make_Object_Declaration (Loc, Defining_Identifier => Def_Id, Object_Definition => New_Occurrence_Of (Exp_Type, Loc), Constant_Present => not Is_Variable (Exp), Expression => Relocate_Node (Exp)); Set_Assignment_OK (E); Insert_Action (Exp, E); end if; -- For expressions that denote names, we can use a renaming scheme. -- This is needed for correctness in the case of a volatile object of -- a non-volatile type because the Make_Reference call of the "default" -- approach would generate an illegal access value (an access value -- cannot designate such an object - see Analyze_Reference). elsif Is_Name_Reference (Exp) -- We skip using this scheme if we have an object of a volatile -- type and we do not have Name_Req set true (see comments for -- Side_Effect_Free). and then (Name_Req or else not Treat_As_Volatile (Exp_Type)) then Def_Id := Build_Temporary (Loc, 'R', Exp); Res := New_Occurrence_Of (Def_Id, Loc); Insert_Action (Exp, Make_Object_Renaming_Declaration (Loc, Defining_Identifier => Def_Id, Subtype_Mark => New_Occurrence_Of (Exp_Type, Loc), Name => Relocate_Node (Exp))); -- If this is a packed reference, or a selected component with -- a non-standard representation, a reference to the temporary -- will be replaced by a copy of the original expression (see -- Exp_Ch2.Expand_Renaming). Otherwise the temporary must be -- elaborated by gigi, and is of course not to be replaced in-line -- by the expression it renames, which would defeat the purpose of -- removing the side-effect. if Nkind_In (Exp, N_Selected_Component, N_Indexed_Component) and then Has_Non_Standard_Rep (Etype (Prefix (Exp))) then null; else Set_Is_Renaming_Of_Object (Def_Id, False); end if; -- Avoid generating a variable-sized temporary, by generating the -- reference just for the function call. The transformation could be -- refined to apply only when the array component is constrained by a -- discriminant??? elsif Nkind (Exp) = N_Selected_Component and then Nkind (Prefix (Exp)) = N_Function_Call and then Is_Array_Type (Exp_Type) then Remove_Side_Effects (Prefix (Exp), Name_Req, Variable_Ref); goto Leave; -- Otherwise we generate a reference to the expression else -- An expression which is in SPARK mode is considered side effect -- free if the resulting value is captured by a variable or a -- constant. if GNATprove_Mode and then Nkind (Parent (Exp)) = N_Object_Declaration then goto Leave; -- When generating C code we cannot consider side effect free object -- declarations that have discriminants and are initialized by means -- of a function call since on this target there is no secondary -- stack to store the return value and the expander may generate an -- extra call to the function to compute the discriminant value. In -- addition, for targets that have secondary stack, the expansion of -- functions with side effects involves the generation of an access -- type to capture the return value stored in the secondary stack; -- by contrast when generating C code such expansion generates an -- internal object declaration (no access type involved) which must -- be identified here to avoid entering into a never-ending loop -- generating internal object declarations. elsif Modify_Tree_For_C and then Nkind (Parent (Exp)) = N_Object_Declaration and then (Nkind (Exp) /= N_Function_Call or else not Has_Discriminants (Exp_Type) or else Is_Internal_Name (Chars (Defining_Identifier (Parent (Exp))))) then goto Leave; end if; -- Special processing for function calls that return a limited type. -- We need to build a declaration that will enable build-in-place -- expansion of the call. This is not done if the context is already -- an object declaration, to prevent infinite recursion. -- This is relevant only in Ada 2005 mode. In Ada 95 programs we have -- to accommodate functions returning limited objects by reference. if Ada_Version >= Ada_2005 and then Nkind (Exp) = N_Function_Call and then Is_Limited_View (Etype (Exp)) and then Nkind (Parent (Exp)) /= N_Object_Declaration then declare Obj : constant Entity_Id := Make_Temporary (Loc, 'F', Exp); Decl : Node_Id; begin Decl := Make_Object_Declaration (Loc, Defining_Identifier => Obj, Object_Definition => New_Occurrence_Of (Exp_Type, Loc), Expression => Relocate_Node (Exp)); Insert_Action (Exp, Decl); Set_Etype (Obj, Exp_Type); Rewrite (Exp, New_Occurrence_Of (Obj, Loc)); goto Leave; end; end if; Def_Id := Build_Temporary (Loc, 'R', Exp); -- The regular expansion of functions with side effects involves the -- generation of an access type to capture the return value found on -- the secondary stack. Since SPARK (and why) cannot process access -- types, use a different approach which ignores the secondary stack -- and "copies" the returned object. -- When generating C code, no need for a 'reference since the -- secondary stack is not supported. if GNATprove_Mode or Modify_Tree_For_C then Res := New_Occurrence_Of (Def_Id, Loc); Ref_Type := Exp_Type; -- Regular expansion utilizing an access type and 'reference else Res := Make_Explicit_Dereference (Loc, Prefix => New_Occurrence_Of (Def_Id, Loc)); -- Generate: -- type Ann is access all <Exp_Type>; Ref_Type := Make_Temporary (Loc, 'A'); Ptr_Typ_Decl := Make_Full_Type_Declaration (Loc, Defining_Identifier => Ref_Type, Type_Definition => Make_Access_To_Object_Definition (Loc, All_Present => True, Subtype_Indication => New_Occurrence_Of (Exp_Type, Loc))); Insert_Action (Exp, Ptr_Typ_Decl); end if; E := Exp; if Nkind (E) = N_Explicit_Dereference then New_Exp := Relocate_Node (Prefix (E)); else E := Relocate_Node (E); -- Do not generate a 'reference in SPARK mode or C generation -- since the access type is not created in the first place. if GNATprove_Mode or Modify_Tree_For_C then New_Exp := E; -- Otherwise generate reference, marking the value as non-null -- since we know it cannot be null and we don't want a check. else New_Exp := Make_Reference (Loc, E); Set_Is_Known_Non_Null (Def_Id); end if; end if; if Is_Delayed_Aggregate (E) then -- The expansion of nested aggregates is delayed until the -- enclosing aggregate is expanded. As aggregates are often -- qualified, the predicate applies to qualified expressions as -- well, indicating that the enclosing aggregate has not been -- expanded yet. At this point the aggregate is part of a -- stand-alone declaration, and must be fully expanded. if Nkind (E) = N_Qualified_Expression then Set_Expansion_Delayed (Expression (E), False); Set_Analyzed (Expression (E), False); else Set_Expansion_Delayed (E, False); end if; Set_Analyzed (E, False); end if; -- Generating C code of object declarations that have discriminants -- and are initialized by means of a function call we propagate the -- discriminants of the parent type to the internally built object. -- This is needed to avoid generating an extra call to the called -- function. -- For example, if we generate here the following declaration, it -- will be expanded later adding an extra call to evaluate the value -- of the discriminant (needed to compute the size of the object). -- -- type Rec (D : Integer) is ... -- Obj : constant Rec := SomeFunc; if Modify_Tree_For_C and then Nkind (Parent (Exp)) = N_Object_Declaration and then Has_Discriminants (Exp_Type) and then Nkind (Exp) = N_Function_Call then Insert_Action (Exp, Make_Object_Declaration (Loc, Defining_Identifier => Def_Id, Object_Definition => New_Copy_Tree (Object_Definition (Parent (Exp))), Constant_Present => True, Expression => New_Exp)); else Insert_Action (Exp, Make_Object_Declaration (Loc, Defining_Identifier => Def_Id, Object_Definition => New_Occurrence_Of (Ref_Type, Loc), Constant_Present => True, Expression => New_Exp)); end if; end if; -- Preserve the Assignment_OK flag in all copies, since at least one -- copy may be used in a context where this flag must be set (otherwise -- why would the flag be set in the first place). Set_Assignment_OK (Res, Assignment_OK (Exp)); -- Finally rewrite the original expression and we are done Rewrite (Exp, Res); Analyze_And_Resolve (Exp, Exp_Type); <<Leave>> Scope_Suppress := Svg_Suppress; end Remove_Side_Effects; --------------------------- -- Represented_As_Scalar -- --------------------------- function Represented_As_Scalar (T : Entity_Id) return Boolean is UT : constant Entity_Id := Underlying_Type (T); begin return Is_Scalar_Type (UT) or else (Is_Bit_Packed_Array (UT) and then Is_Scalar_Type (Packed_Array_Impl_Type (UT))); end Represented_As_Scalar; ------------------------------ -- Requires_Cleanup_Actions -- ------------------------------ function Requires_Cleanup_Actions (N : Node_Id; Lib_Level : Boolean) return Boolean is At_Lib_Level : constant Boolean := Lib_Level and then Nkind_In (N, N_Package_Body, N_Package_Specification); -- N is at the library level if the top-most context is a package and -- the path taken to reach N does not inlcude non-package constructs. begin case Nkind (N) is when N_Accept_Statement | N_Block_Statement | N_Entry_Body | N_Package_Body | N_Protected_Body | N_Subprogram_Body | N_Task_Body => return Requires_Cleanup_Actions (Declarations (N), At_Lib_Level, True) or else (Present (Handled_Statement_Sequence (N)) and then Requires_Cleanup_Actions (Statements (Handled_Statement_Sequence (N)), At_Lib_Level, True)); when N_Package_Specification => return Requires_Cleanup_Actions (Visible_Declarations (N), At_Lib_Level, True) or else Requires_Cleanup_Actions (Private_Declarations (N), At_Lib_Level, True); when others => return False; end case; end Requires_Cleanup_Actions; ------------------------------ -- Requires_Cleanup_Actions -- ------------------------------ function Requires_Cleanup_Actions (L : List_Id; Lib_Level : Boolean; Nested_Constructs : Boolean) return Boolean is Decl : Node_Id; Expr : Node_Id; Obj_Id : Entity_Id; Obj_Typ : Entity_Id; Pack_Id : Entity_Id; Typ : Entity_Id; begin if No (L) or else Is_Empty_List (L) then return False; end if; Decl := First (L); 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_Unregister_Tag) and then not Is_Abstract_Type (Typ) and then not No_Run_Time_Mode then return True; 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 Lib_Level 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 expansion of iterator loops generates an object declaration -- where the Ekind is explicitly set to loop parameter. This is to -- ensure that the loop parameter behaves as a constant from user -- code point of view. Such object are never controlled and do not -- require cleanup actions. An iterator loop over a container of -- controlled objects does not produce such object declarations. elsif Ekind (Obj_Id) = E_Loop_Parameter then return False; -- 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 return True; -- 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 return 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 return True; -- Processing for intermediate results of if expressions where -- one of the alternatives uses 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 return 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. elsif Ekind (Obj_Id) = E_Variable and then (Is_Simple_Protected_Type (Obj_Typ) or else Has_Simple_Protected_Object (Obj_Typ)) then return 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 Lib_Level 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 return 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 return 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))) and then Requires_Cleanup_Actions (Actions (Decl), Lib_Level, Nested_Constructs) then return True; end if; -- Nested package declarations elsif Nested_Constructs and then Nkind (Decl) = N_Package_Declaration then Pack_Id := Defining_Entity (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 and then Requires_Cleanup_Actions (Specification (Decl), Lib_Level) then return True; end if; -- Nested package bodies elsif Nested_Constructs and then 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 and then Requires_Cleanup_Actions (Decl, Lib_Level) then return True; end if; elsif Nkind (Decl) = N_Block_Statement and then -- 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. (Inside_Init_Proc -- 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. or else Is_Finalization_Wrapper (Decl)) then if Requires_Cleanup_Actions (Decl, Lib_Level) then return True; end if; end if; Next (Decl); end loop; return False; end Requires_Cleanup_Actions; ------------------------------------ -- Safe_Unchecked_Type_Conversion -- ------------------------------------ -- Note: this function knows quite a bit about the exact requirements of -- Gigi with respect to unchecked type conversions, and its code must be -- coordinated with any changes in Gigi in this area. -- The above requirements should be documented in Sinfo ??? function Safe_Unchecked_Type_Conversion (Exp : Node_Id) return Boolean is Otyp : Entity_Id; Ityp : Entity_Id; Oalign : Uint; Ialign : Uint; Pexp : constant Node_Id := Parent (Exp); begin -- If the expression is the RHS of an assignment or object declaration -- we are always OK because there will always be a target. -- Object renaming declarations, (generated for view conversions of -- actuals in inlined calls), like object declarations, provide an -- explicit type, and are safe as well. if (Nkind (Pexp) = N_Assignment_Statement and then Expression (Pexp) = Exp) or else Nkind_In (Pexp, N_Object_Declaration, N_Object_Renaming_Declaration) then return True; -- If the expression is the prefix of an N_Selected_Component we should -- also be OK because GCC knows to look inside the conversion except if -- the type is discriminated. We assume that we are OK anyway if the -- type is not set yet or if it is controlled since we can't afford to -- introduce a temporary in this case. elsif Nkind (Pexp) = N_Selected_Component and then Prefix (Pexp) = Exp then if No (Etype (Pexp)) then return True; else return not Has_Discriminants (Etype (Pexp)) or else Is_Constrained (Etype (Pexp)); end if; end if; -- Set the output type, this comes from Etype if it is set, otherwise we -- take it from the subtype mark, which we assume was already fully -- analyzed. if Present (Etype (Exp)) then Otyp := Etype (Exp); else Otyp := Entity (Subtype_Mark (Exp)); end if; -- The input type always comes from the expression, and we assume this -- is indeed always analyzed, so we can simply get the Etype. Ityp := Etype (Expression (Exp)); -- Initialize alignments to unknown so far Oalign := No_Uint; Ialign := No_Uint; -- Replace a concurrent type by its corresponding record type and each -- type by its underlying type and do the tests on those. The original -- type may be a private type whose completion is a concurrent type, so -- find the underlying type first. if Present (Underlying_Type (Otyp)) then Otyp := Underlying_Type (Otyp); end if; if Present (Underlying_Type (Ityp)) then Ityp := Underlying_Type (Ityp); end if; if Is_Concurrent_Type (Otyp) then Otyp := Corresponding_Record_Type (Otyp); end if; if Is_Concurrent_Type (Ityp) then Ityp := Corresponding_Record_Type (Ityp); end if; -- If the base types are the same, we know there is no problem since -- this conversion will be a noop. if Implementation_Base_Type (Otyp) = Implementation_Base_Type (Ityp) then return True; -- Same if this is an upwards conversion of an untagged type, and there -- are no constraints involved (could be more general???) elsif Etype (Ityp) = Otyp and then not Is_Tagged_Type (Ityp) and then not Has_Discriminants (Ityp) and then No (First_Rep_Item (Base_Type (Ityp))) then return True; -- If the expression has an access type (object or subprogram) we assume -- that the conversion is safe, because the size of the target is safe, -- even if it is a record (which might be treated as having unknown size -- at this point). elsif Is_Access_Type (Ityp) then return True; -- If the size of output type is known at compile time, there is never -- a problem. Note that unconstrained records are considered to be of -- known size, but we can't consider them that way here, because we are -- talking about the actual size of the object. -- We also make sure that in addition to the size being known, we do not -- have a case which might generate an embarrassingly large temp in -- stack checking mode. elsif Size_Known_At_Compile_Time (Otyp) and then (not Stack_Checking_Enabled or else not May_Generate_Large_Temp (Otyp)) and then not (Is_Record_Type (Otyp) and then not Is_Constrained (Otyp)) then return True; -- If either type is tagged, then we know the alignment is OK so Gigi -- will be able to use pointer punning. elsif Is_Tagged_Type (Otyp) or else Is_Tagged_Type (Ityp) then return True; -- If either type is a limited record type, we cannot do a copy, so say -- safe since there's nothing else we can do. elsif Is_Limited_Record (Otyp) or else Is_Limited_Record (Ityp) then return True; -- Conversions to and from packed array types are always ignored and -- hence are safe. elsif Is_Packed_Array_Impl_Type (Otyp) or else Is_Packed_Array_Impl_Type (Ityp) then return True; end if; -- The only other cases known to be safe is if the input type's -- alignment is known to be at least the maximum alignment for the -- target or if both alignments are known and the output type's -- alignment is no stricter than the input's. We can use the component -- type alignment for an array if a type is an unpacked array type. if Present (Alignment_Clause (Otyp)) then Oalign := Expr_Value (Expression (Alignment_Clause (Otyp))); elsif Is_Array_Type (Otyp) and then Present (Alignment_Clause (Component_Type (Otyp))) then Oalign := Expr_Value (Expression (Alignment_Clause (Component_Type (Otyp)))); end if; if Present (Alignment_Clause (Ityp)) then Ialign := Expr_Value (Expression (Alignment_Clause (Ityp))); elsif Is_Array_Type (Ityp) and then Present (Alignment_Clause (Component_Type (Ityp))) then Ialign := Expr_Value (Expression (Alignment_Clause (Component_Type (Ityp)))); end if; if Ialign /= No_Uint and then Ialign > Maximum_Alignment then return True; elsif Ialign /= No_Uint and then Oalign /= No_Uint and then Ialign <= Oalign then return True; -- Otherwise, Gigi cannot handle this and we must make a temporary else return False; end if; end Safe_Unchecked_Type_Conversion; --------------------------------- -- Set_Current_Value_Condition -- --------------------------------- -- Note: the implementation of this procedure is very closely tied to the -- implementation of Get_Current_Value_Condition. Here we set required -- Current_Value fields, and in Get_Current_Value_Condition, we interpret -- them, so they must have a consistent view. procedure Set_Current_Value_Condition (Cnode : Node_Id) is procedure Set_Entity_Current_Value (N : Node_Id); -- If N is an entity reference, where the entity is of an appropriate -- kind, then set the current value of this entity to Cnode, unless -- there is already a definite value set there. procedure Set_Expression_Current_Value (N : Node_Id); -- If N is of an appropriate form, sets an appropriate entry in current -- value fields of relevant entities. Multiple entities can be affected -- in the case of an AND or AND THEN. ------------------------------ -- Set_Entity_Current_Value -- ------------------------------ procedure Set_Entity_Current_Value (N : Node_Id) is begin if Is_Entity_Name (N) then declare Ent : constant Entity_Id := Entity (N); begin -- Don't capture if not safe to do so if not Safe_To_Capture_Value (N, Ent, Cond => True) then return; end if; -- Here we have a case where the Current_Value field may need -- to be set. We set it if it is not already set to a compile -- time expression value. -- Note that this represents a decision that one condition -- blots out another previous one. That's certainly right if -- they occur at the same level. If the second one is nested, -- then the decision is neither right nor wrong (it would be -- equally OK to leave the outer one in place, or take the new -- inner one. Really we should record both, but our data -- structures are not that elaborate. if Nkind (Current_Value (Ent)) not in N_Subexpr then Set_Current_Value (Ent, Cnode); end if; end; end if; end Set_Entity_Current_Value; ---------------------------------- -- Set_Expression_Current_Value -- ---------------------------------- procedure Set_Expression_Current_Value (N : Node_Id) is Cond : Node_Id; begin Cond := N; -- Loop to deal with (ignore for now) any NOT operators present. The -- presence of NOT operators will be handled properly when we call -- Get_Current_Value_Condition. while Nkind (Cond) = N_Op_Not loop Cond := Right_Opnd (Cond); end loop; -- For an AND or AND THEN, recursively process operands if Nkind (Cond) = N_Op_And or else Nkind (Cond) = N_And_Then then Set_Expression_Current_Value (Left_Opnd (Cond)); Set_Expression_Current_Value (Right_Opnd (Cond)); return; end if; -- Check possible relational operator if Nkind (Cond) in N_Op_Compare then if Compile_Time_Known_Value (Right_Opnd (Cond)) then Set_Entity_Current_Value (Left_Opnd (Cond)); elsif Compile_Time_Known_Value (Left_Opnd (Cond)) then Set_Entity_Current_Value (Right_Opnd (Cond)); end if; elsif Nkind_In (Cond, N_Type_Conversion, N_Qualified_Expression, N_Expression_With_Actions) then Set_Expression_Current_Value (Expression (Cond)); -- Check possible boolean variable reference else Set_Entity_Current_Value (Cond); end if; end Set_Expression_Current_Value; -- Start of processing for Set_Current_Value_Condition begin Set_Expression_Current_Value (Condition (Cnode)); end Set_Current_Value_Condition; -------------------------- -- Set_Elaboration_Flag -- -------------------------- procedure Set_Elaboration_Flag (N : Node_Id; Spec_Id : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); Ent : constant Entity_Id := Elaboration_Entity (Spec_Id); Asn : Node_Id; begin if Present (Ent) then -- Nothing to do if at the compilation unit level, because in this -- case the flag is set by the binder generated elaboration routine. if Nkind (Parent (N)) = N_Compilation_Unit then null; -- Here we do need to generate an assignment statement else Check_Restriction (No_Elaboration_Code, N); Asn := Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Ent, Loc), Expression => Make_Integer_Literal (Loc, Uint_1)); if Nkind (Parent (N)) = N_Subunit then Insert_After (Corresponding_Stub (Parent (N)), Asn); else Insert_After (N, Asn); end if; Analyze (Asn); -- Kill current value indication. This is necessary because the -- tests of this flag are inserted out of sequence and must not -- pick up bogus indications of the wrong constant value. Set_Current_Value (Ent, Empty); -- If the subprogram is in the current declarative part and -- 'access has been applied to it, generate an elaboration -- check at the beginning of the declarations of the body. if Nkind (N) = N_Subprogram_Body and then Address_Taken (Spec_Id) and then Ekind_In (Scope (Spec_Id), E_Block, E_Procedure, E_Function) then declare Loc : constant Source_Ptr := Sloc (N); Decls : constant List_Id := Declarations (N); Chk : Node_Id; begin -- No need to generate this check if first entry in the -- declaration list is a raise of Program_Error now. if Present (Decls) and then Nkind (First (Decls)) = N_Raise_Program_Error then return; end if; -- Otherwise generate the check Chk := Make_Raise_Program_Error (Loc, Condition => Make_Op_Eq (Loc, Left_Opnd => New_Occurrence_Of (Ent, Loc), Right_Opnd => Make_Integer_Literal (Loc, Uint_0)), Reason => PE_Access_Before_Elaboration); if No (Decls) then Set_Declarations (N, New_List (Chk)); else Prepend (Chk, Decls); end if; Analyze (Chk); end; end if; end if; end if; end Set_Elaboration_Flag; ---------------------------- -- Set_Renamed_Subprogram -- ---------------------------- procedure Set_Renamed_Subprogram (N : Node_Id; E : Entity_Id) is begin -- If input node is an identifier, we can just reset it if Nkind (N) = N_Identifier then Set_Chars (N, Chars (E)); Set_Entity (N, E); -- Otherwise we have to do a rewrite, preserving Comes_From_Source else declare CS : constant Boolean := Comes_From_Source (N); begin Rewrite (N, Make_Identifier (Sloc (N), Chars (E))); Set_Entity (N, E); Set_Comes_From_Source (N, CS); Set_Analyzed (N, True); end; end if; end Set_Renamed_Subprogram; ---------------------- -- Side_Effect_Free -- ---------------------- function Side_Effect_Free (N : Node_Id; Name_Req : Boolean := False; Variable_Ref : Boolean := False) return Boolean is Typ : constant Entity_Id := Etype (N); -- Result type of the expression function Safe_Prefixed_Reference (N : Node_Id) return Boolean; -- The argument N is a construct where the Prefix is dereferenced if it -- is an access type and the result is a variable. The call returns True -- if the construct is side effect free (not considering side effects in -- other than the prefix which are to be tested by the caller). function Within_In_Parameter (N : Node_Id) return Boolean; -- Determines if N is a subcomponent of a composite in-parameter. If so, -- N is not side-effect free when the actual is global and modifiable -- indirectly from within a subprogram, because it may be passed by -- reference. The front-end must be conservative here and assume that -- this may happen with any array or record type. On the other hand, we -- cannot create temporaries for all expressions for which this -- condition is true, for various reasons that might require clearing up -- ??? For example, discriminant references that appear out of place, or -- spurious type errors with class-wide expressions. As a result, we -- limit the transformation to loop bounds, which is so far the only -- case that requires it. ----------------------------- -- Safe_Prefixed_Reference -- ----------------------------- function Safe_Prefixed_Reference (N : Node_Id) return Boolean is begin -- If prefix is not side effect free, definitely not safe if not Side_Effect_Free (Prefix (N), Name_Req, Variable_Ref) then return False; -- If the prefix is of an access type that is not access-to-constant, -- then this construct is a variable reference, which means it is to -- be considered to have side effects if Variable_Ref is set True. elsif Is_Access_Type (Etype (Prefix (N))) and then not Is_Access_Constant (Etype (Prefix (N))) and then Variable_Ref then -- Exception is a prefix that is the result of a previous removal -- of side-effects. return Is_Entity_Name (Prefix (N)) and then not Comes_From_Source (Prefix (N)) and then Ekind (Entity (Prefix (N))) = E_Constant and then Is_Internal_Name (Chars (Entity (Prefix (N)))); -- If the prefix is an explicit dereference then this construct is a -- variable reference, which means it is to be considered to have -- side effects if Variable_Ref is True. -- We do NOT exclude dereferences of access-to-constant types because -- we handle them as constant view of variables. elsif Nkind (Prefix (N)) = N_Explicit_Dereference and then Variable_Ref then return False; -- Note: The following test is the simplest way of solving a complex -- problem uncovered by the following test (Side effect on loop bound -- that is a subcomponent of a global variable: -- with Text_Io; use Text_Io; -- procedure Tloop is -- type X is -- record -- V : Natural := 4; -- S : String (1..5) := (others => 'a'); -- end record; -- X1 : X; -- procedure Modi; -- generic -- with procedure Action; -- procedure Loop_G (Arg : X; Msg : String) -- procedure Loop_G (Arg : X; Msg : String) is -- begin -- Put_Line ("begin loop_g " & Msg & " will loop till: " -- & Natural'Image (Arg.V)); -- for Index in 1 .. Arg.V loop -- Text_Io.Put_Line -- (Natural'Image (Index) & " " & Arg.S (Index)); -- if Index > 2 then -- Modi; -- end if; -- end loop; -- Put_Line ("end loop_g " & Msg); -- end; -- procedure Loop1 is new Loop_G (Modi); -- procedure Modi is -- begin -- X1.V := 1; -- Loop1 (X1, "from modi"); -- end; -- -- begin -- Loop1 (X1, "initial"); -- end; -- The output of the above program should be: -- begin loop_g initial will loop till: 4 -- 1 a -- 2 a -- 3 a -- begin loop_g from modi will loop till: 1 -- 1 a -- end loop_g from modi -- 4 a -- begin loop_g from modi will loop till: 1 -- 1 a -- end loop_g from modi -- end loop_g initial -- If a loop bound is a subcomponent of a global variable, a -- modification of that variable within the loop may incorrectly -- affect the execution of the loop. elsif Nkind (Parent (Parent (N))) = N_Loop_Parameter_Specification and then Within_In_Parameter (Prefix (N)) and then Variable_Ref then return False; -- All other cases are side effect free else return True; end if; end Safe_Prefixed_Reference; ------------------------- -- Within_In_Parameter -- ------------------------- function Within_In_Parameter (N : Node_Id) return Boolean is begin if not Comes_From_Source (N) then return False; elsif Is_Entity_Name (N) then return Ekind (Entity (N)) = E_In_Parameter; elsif Nkind_In (N, N_Indexed_Component, N_Selected_Component) then return Within_In_Parameter (Prefix (N)); else return False; end if; end Within_In_Parameter; -- Start of processing for Side_Effect_Free begin -- If volatile reference, always consider it to have side effects if Is_Volatile_Reference (N) then return False; end if; -- Note on checks that could raise Constraint_Error. Strictly, if we -- take advantage of 11.6, these checks do not count as side effects. -- However, we would prefer to consider that they are side effects, -- since the back end CSE does not work very well on expressions which -- can raise Constraint_Error. On the other hand if we don't consider -- them to be side effect free, then we get some awkward expansions -- in -gnato mode, resulting in code insertions at a point where we -- do not have a clear model for performing the insertions. -- Special handling for entity names if Is_Entity_Name (N) then -- A type reference is always side effect free if Is_Type (Entity (N)) then return True; -- Variables are considered to be a side effect if Variable_Ref -- is set or if we have a volatile reference and Name_Req is off. -- If Name_Req is True then we can't help returning a name which -- effectively allows multiple references in any case. elsif Is_Variable (N, Use_Original_Node => False) then return not Variable_Ref and then (not Is_Volatile_Reference (N) or else Name_Req); -- Any other entity (e.g. a subtype name) is definitely side -- effect free. else return True; end if; -- A value known at compile time is always side effect free elsif Compile_Time_Known_Value (N) then return True; -- A variable renaming is not side-effect free, because the renaming -- will function like a macro in the front-end in some cases, and an -- assignment can modify the component designated by N, so we need to -- create a temporary for it. -- The guard testing for Entity being present is needed at least in -- the case of rewritten predicate expressions, and may well also be -- appropriate elsewhere. Obviously we can't go testing the entity -- field if it does not exist, so it's reasonable to say that this is -- not the renaming case if it does not exist. elsif Is_Entity_Name (Original_Node (N)) and then Present (Entity (Original_Node (N))) and then Is_Renaming_Of_Object (Entity (Original_Node (N))) and then Ekind (Entity (Original_Node (N))) /= E_Constant then declare RO : constant Node_Id := Renamed_Object (Entity (Original_Node (N))); begin -- If the renamed object is an indexed component, or an -- explicit dereference, then the designated object could -- be modified by an assignment. if Nkind_In (RO, N_Indexed_Component, N_Explicit_Dereference) then return False; -- A selected component must have a safe prefix elsif Nkind (RO) = N_Selected_Component then return Safe_Prefixed_Reference (RO); -- In all other cases, designated object cannot be changed so -- we are side effect free. else return True; end if; end; -- Remove_Side_Effects generates an object renaming declaration to -- capture the expression of a class-wide expression. In VM targets -- the frontend performs no expansion for dispatching calls to -- class- wide types since they are handled by the VM. Hence, we must -- locate here if this node corresponds to a previous invocation of -- Remove_Side_Effects to avoid a never ending loop in the frontend. elsif not Tagged_Type_Expansion and then not Comes_From_Source (N) and then Nkind (Parent (N)) = N_Object_Renaming_Declaration and then Is_Class_Wide_Type (Typ) then return True; -- Generating C the type conversion of an access to constrained array -- type into an access to unconstrained array type involves initializing -- a fat pointer and the expression cannot be assumed to be free of side -- effects since it must referenced several times to compute its bounds. elsif Modify_Tree_For_C and then Nkind (N) = N_Type_Conversion and then Is_Access_Type (Typ) and then Is_Array_Type (Designated_Type (Typ)) and then not Is_Constrained (Designated_Type (Typ)) then return False; end if; -- For other than entity names and compile time known values, -- check the node kind for special processing. case Nkind (N) is -- An attribute reference is side effect free if its expressions -- are side effect free and its prefix is side effect free or -- is an entity reference. -- Is this right? what about x'first where x is a variable??? when N_Attribute_Reference => return Side_Effect_Free (Expressions (N), Name_Req, Variable_Ref) and then Attribute_Name (N) /= Name_Input and then (Is_Entity_Name (Prefix (N)) or else Side_Effect_Free (Prefix (N), Name_Req, Variable_Ref)); -- A binary operator is side effect free if and both operands are -- side effect free. For this purpose binary operators include -- membership tests and short circuit forms. when N_Binary_Op | N_Membership_Test | N_Short_Circuit => return Side_Effect_Free (Left_Opnd (N), Name_Req, Variable_Ref) and then Side_Effect_Free (Right_Opnd (N), Name_Req, Variable_Ref); -- An explicit dereference is side effect free only if it is -- a side effect free prefixed reference. when N_Explicit_Dereference => return Safe_Prefixed_Reference (N); -- An expression with action is side effect free if its expression -- is side effect free and it has no actions. when N_Expression_With_Actions => return Is_Empty_List (Actions (N)) and then Side_Effect_Free (Expression (N), Name_Req, Variable_Ref); -- A call to _rep_to_pos is side effect free, since we generate -- this pure function call ourselves. Moreover it is critically -- important to make this exception, since otherwise we can have -- discriminants in array components which don't look side effect -- free in the case of an array whose index type is an enumeration -- type with an enumeration rep clause. -- All other function calls are not side effect free when N_Function_Call => return Nkind (Name (N)) = N_Identifier and then Is_TSS (Name (N), TSS_Rep_To_Pos) and then Side_Effect_Free (First (Parameter_Associations (N)), Name_Req, Variable_Ref); -- An IF expression is side effect free if it's of a scalar type, and -- all its components are all side effect free (conditions and then -- actions and else actions). We restrict to scalar types, since it -- is annoying to deal with things like (if A then B else C)'First -- where the type involved is a string type. when N_If_Expression => return Is_Scalar_Type (Typ) and then Side_Effect_Free (Expressions (N), Name_Req, Variable_Ref); -- An indexed component is side effect free if it is a side -- effect free prefixed reference and all the indexing -- expressions are side effect free. when N_Indexed_Component => return Side_Effect_Free (Expressions (N), Name_Req, Variable_Ref) and then Safe_Prefixed_Reference (N); -- A type qualification is side effect free if the expression -- is side effect free. when N_Qualified_Expression => return Side_Effect_Free (Expression (N), Name_Req, Variable_Ref); -- A selected component is side effect free only if it is a side -- effect free prefixed reference. when N_Selected_Component => return Safe_Prefixed_Reference (N); -- A range is side effect free if the bounds are side effect free when N_Range => return Side_Effect_Free (Low_Bound (N), Name_Req, Variable_Ref) and then Side_Effect_Free (High_Bound (N), Name_Req, Variable_Ref); -- A slice is side effect free if it is a side effect free -- prefixed reference and the bounds are side effect free. when N_Slice => return Side_Effect_Free (Discrete_Range (N), Name_Req, Variable_Ref) and then Safe_Prefixed_Reference (N); -- A type conversion is side effect free if the expression to be -- converted is side effect free. when N_Type_Conversion => return Side_Effect_Free (Expression (N), Name_Req, Variable_Ref); -- A unary operator is side effect free if the operand -- is side effect free. when N_Unary_Op => return Side_Effect_Free (Right_Opnd (N), Name_Req, Variable_Ref); -- An unchecked type conversion is side effect free only if it -- is safe and its argument is side effect free. when N_Unchecked_Type_Conversion => return Safe_Unchecked_Type_Conversion (N) and then Side_Effect_Free (Expression (N), Name_Req, Variable_Ref); -- An unchecked expression is side effect free if its expression -- is side effect free. when N_Unchecked_Expression => return Side_Effect_Free (Expression (N), Name_Req, Variable_Ref); -- A literal is side effect free when N_Character_Literal | N_Integer_Literal | N_Real_Literal | N_String_Literal => return True; -- We consider that anything else has side effects. This is a bit -- crude, but we are pretty close for most common cases, and we -- are certainly correct (i.e. we never return True when the -- answer should be False). when others => return False; end case; end Side_Effect_Free; -- A list is side effect free if all elements of the list are side -- effect free. function Side_Effect_Free (L : List_Id; Name_Req : Boolean := False; Variable_Ref : Boolean := False) return Boolean is N : Node_Id; begin if L = No_List or else L = Error_List then return True; else N := First (L); while Present (N) loop if not Side_Effect_Free (N, Name_Req, Variable_Ref) then return False; else Next (N); end if; end loop; return True; end if; end Side_Effect_Free; ---------------------------------- -- Silly_Boolean_Array_Not_Test -- ---------------------------------- -- This procedure implements an odd and silly test. We explicitly check -- for the case where the 'First of the component type is equal to the -- 'Last of this component type, and if this is the case, we make sure -- that constraint error is raised. The reason is that the NOT is bound -- to cause CE in this case, and we will not otherwise catch it. -- No such check is required for AND and OR, since for both these cases -- False op False = False, and True op True = True. For the XOR case, -- see Silly_Boolean_Array_Xor_Test. -- Believe it or not, this was reported as a bug. Note that nearly always, -- the test will evaluate statically to False, so the code will be -- statically removed, and no extra overhead caused. procedure Silly_Boolean_Array_Not_Test (N : Node_Id; T : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); CT : constant Entity_Id := Component_Type (T); begin -- The check we install is -- constraint_error when -- component_type'first = component_type'last -- and then array_type'Length /= 0) -- We need the last guard because we don't want to raise CE for empty -- arrays since no out of range values result. (Empty arrays with a -- component type of True .. True -- very useful -- even the ACATS -- does not test that marginal case). Insert_Action (N, Make_Raise_Constraint_Error (Loc, Condition => Make_And_Then (Loc, Left_Opnd => Make_Op_Eq (Loc, Left_Opnd => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (CT, Loc), Attribute_Name => Name_First), Right_Opnd => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (CT, Loc), Attribute_Name => Name_Last)), Right_Opnd => Make_Non_Empty_Check (Loc, Right_Opnd (N))), Reason => CE_Range_Check_Failed)); end Silly_Boolean_Array_Not_Test; ---------------------------------- -- Silly_Boolean_Array_Xor_Test -- ---------------------------------- -- This procedure implements an odd and silly test. We explicitly check -- for the XOR case where the component type is True .. True, since this -- will raise constraint error. A special check is required since CE -- will not be generated otherwise (cf Expand_Packed_Not). -- No such check is required for AND and OR, since for both these cases -- False op False = False, and True op True = True, and no check is -- required for the case of False .. False, since False xor False = False. -- See also Silly_Boolean_Array_Not_Test procedure Silly_Boolean_Array_Xor_Test (N : Node_Id; T : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); CT : constant Entity_Id := Component_Type (T); begin -- The check we install is -- constraint_error when -- Boolean (component_type'First) -- and then Boolean (component_type'Last) -- and then array_type'Length /= 0) -- We need the last guard because we don't want to raise CE for empty -- arrays since no out of range values result (Empty arrays with a -- component type of True .. True -- very useful -- even the ACATS -- does not test that marginal case). Insert_Action (N, Make_Raise_Constraint_Error (Loc, Condition => Make_And_Then (Loc, Left_Opnd => Make_And_Then (Loc, Left_Opnd => Convert_To (Standard_Boolean, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (CT, Loc), Attribute_Name => Name_First)), Right_Opnd => Convert_To (Standard_Boolean, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (CT, Loc), Attribute_Name => Name_Last))), Right_Opnd => Make_Non_Empty_Check (Loc, Right_Opnd (N))), Reason => CE_Range_Check_Failed)); end Silly_Boolean_Array_Xor_Test; -------------------------- -- Target_Has_Fixed_Ops -- -------------------------- Integer_Sized_Small : Ureal; -- Set to 2.0 ** -(Integer'Size - 1) the first time that this function is -- called (we don't want to compute it more than once). Long_Integer_Sized_Small : Ureal; -- Set to 2.0 ** -(Long_Integer'Size - 1) the first time that this function -- is called (we don't want to compute it more than once) First_Time_For_THFO : Boolean := True; -- Set to False after first call (if Fractional_Fixed_Ops_On_Target) function Target_Has_Fixed_Ops (Left_Typ : Entity_Id; Right_Typ : Entity_Id; Result_Typ : Entity_Id) return Boolean is function Is_Fractional_Type (Typ : Entity_Id) return Boolean; -- Return True if the given type is a fixed-point type with a small -- value equal to 2 ** (-(T'Object_Size - 1)) and whose values have -- an absolute value less than 1.0. This is currently limited to -- fixed-point types that map to Integer or Long_Integer. ------------------------ -- Is_Fractional_Type -- ------------------------ function Is_Fractional_Type (Typ : Entity_Id) return Boolean is begin if Esize (Typ) = Standard_Integer_Size then return Small_Value (Typ) = Integer_Sized_Small; elsif Esize (Typ) = Standard_Long_Integer_Size then return Small_Value (Typ) = Long_Integer_Sized_Small; else return False; end if; end Is_Fractional_Type; -- Start of processing for Target_Has_Fixed_Ops begin -- Return False if Fractional_Fixed_Ops_On_Target is false if not Fractional_Fixed_Ops_On_Target then return False; end if; -- Here the target has Fractional_Fixed_Ops, if first time, compute -- standard constants used by Is_Fractional_Type. if First_Time_For_THFO then First_Time_For_THFO := False; Integer_Sized_Small := UR_From_Components (Num => Uint_1, Den => UI_From_Int (Standard_Integer_Size - 1), Rbase => 2); Long_Integer_Sized_Small := UR_From_Components (Num => Uint_1, Den => UI_From_Int (Standard_Long_Integer_Size - 1), Rbase => 2); end if; -- Return True if target supports fixed-by-fixed multiply/divide for -- fractional fixed-point types (see Is_Fractional_Type) and the operand -- and result types are equivalent fractional types. return Is_Fractional_Type (Base_Type (Left_Typ)) and then Is_Fractional_Type (Base_Type (Right_Typ)) and then Is_Fractional_Type (Base_Type (Result_Typ)) and then Esize (Left_Typ) = Esize (Right_Typ) and then Esize (Left_Typ) = Esize (Result_Typ); end Target_Has_Fixed_Ops; ------------------------------------------ -- Type_May_Have_Bit_Aligned_Components -- ------------------------------------------ function Type_May_Have_Bit_Aligned_Components (Typ : Entity_Id) return Boolean is begin -- Array type, check component type if Is_Array_Type (Typ) then return Type_May_Have_Bit_Aligned_Components (Component_Type (Typ)); -- Record type, check components elsif Is_Record_Type (Typ) then declare E : Entity_Id; begin E := First_Component_Or_Discriminant (Typ); while Present (E) loop if Component_May_Be_Bit_Aligned (E) or else Type_May_Have_Bit_Aligned_Components (Etype (E)) then return True; end if; Next_Component_Or_Discriminant (E); end loop; return False; end; -- Type other than array or record is always OK else return False; end if; end Type_May_Have_Bit_Aligned_Components; ------------------------------- -- Update_Primitives_Mapping -- ------------------------------- procedure Update_Primitives_Mapping (Inher_Id : Entity_Id; Subp_Id : Entity_Id) is begin Update_Primitives_Mapping_Of_Types (Par_Typ => Find_Dispatching_Type (Inher_Id), Deriv_Typ => Find_Dispatching_Type (Subp_Id)); end Update_Primitives_Mapping; ---------------------------------------- -- Update_Primitives_Mapping_Of_Types -- ---------------------------------------- procedure Update_Primitives_Mapping_Of_Types (Par_Typ : Entity_Id; Deriv_Typ : Entity_Id) is procedure Add_Primitive (Prim : Entity_Id); -- Find a primitive in the inheritance/overriding chain starting from -- Prim whose dispatching type is parent type Par_Typ and add a mapping -- between the result and primitive Prim. ------------------- -- Add_Primitive -- ------------------- procedure Add_Primitive (Prim : Entity_Id) is function Ancestor_Primitive (Subp : Entity_Id) return Entity_Id; -- Return the next ancestor primitive in the inheritance/overriding -- chain of subprogram Subp. Return Empty if no such primitive is -- available. ------------------------ -- Ancestor_Primitive -- ------------------------ function Ancestor_Primitive (Subp : Entity_Id) return Entity_Id is Inher_Prim : constant Entity_Id := Alias (Subp); Over_Prim : constant Entity_Id := Overridden_Operation (Subp); begin -- The current subprogram overrides an ancestor primitive if Present (Over_Prim) then return Over_Prim; -- The current subprogram is an internally generated alias of an -- inherited ancestor primitive. elsif Present (Inher_Prim) then return Inher_Prim; -- Otherwise the current subprogram is the root of the inheritance -- or overriding chain. else return Empty; end if; end Ancestor_Primitive; -- Local variables Par_Prim : Entity_Id; -- Start of processing for Add_Primitive begin -- Inspect both the inheritance chain through the Alias attribute and -- the overriding chain through the Overridden_Operation looking for -- an ancestor primitive with the appropriate dispatching type. Par_Prim := Prim; while Present (Par_Prim) loop exit when Find_Dispatching_Type (Par_Prim) = Par_Typ; Par_Prim := Ancestor_Primitive (Par_Prim); end loop; -- Create a mapping of the form: -- Parent type primitive -> derived type primitive if Present (Par_Prim) then Primitives_Mapping.Set (Par_Prim, Prim); end if; end Add_Primitive; -- Local variables Deriv_Prim : Entity_Id; Par_Prim : Entity_Id; Par_Prims : Elist_Id; Prim_Elmt : Elmt_Id; -- Start of processing for Update_Primitives_Mapping_Of_Types begin -- Nothing to do if there are no types to work with if No (Par_Typ) or else No (Deriv_Typ) then return; -- Nothing to do if the mapping already exists elsif Primitives_Mapping.Get (Par_Typ) = Deriv_Typ then return; end if; -- Create a mapping of the form: -- Parent type -> Derived type -- to prevent any subsequent attempts to produce the same relations. Primitives_Mapping.Set (Par_Typ, Deriv_Typ); -- Inspect the primitives of the derived type and determine whether they -- relate to the primitives of the parent type. If there is a meaningful -- relation, create a mapping of the form: -- Parent type primitive -> Derived type primitive if Present (Direct_Primitive_Operations (Deriv_Typ)) then Prim_Elmt := First_Elmt (Direct_Primitive_Operations (Deriv_Typ)); while Present (Prim_Elmt) loop Deriv_Prim := Node (Prim_Elmt); if Is_Subprogram (Deriv_Prim) and then Find_Dispatching_Type (Deriv_Prim) = Deriv_Typ then Add_Primitive (Deriv_Prim); end if; Next_Elmt (Prim_Elmt); end loop; end if; -- If the parent operation is an interface operation, the overriding -- indicator is not present. Instead, we get from the interface -- operation the primitive of the current type that implements it. if Is_Interface (Par_Typ) then Par_Prims := Collect_Primitive_Operations (Par_Typ); if Present (Par_Prims) then Prim_Elmt := First_Elmt (Par_Prims); while Present (Prim_Elmt) loop Par_Prim := Node (Prim_Elmt); Deriv_Prim := Find_Primitive_Covering_Interface (Deriv_Typ, Par_Prim); if Present (Deriv_Prim) then Primitives_Mapping.Set (Par_Prim, Deriv_Prim); end if; Next_Elmt (Prim_Elmt); end loop; end if; end if; end Update_Primitives_Mapping_Of_Types; ---------------------------------- -- Within_Case_Or_If_Expression -- ---------------------------------- function Within_Case_Or_If_Expression (N : Node_Id) return Boolean is Par : Node_Id; begin -- Locate an enclosing case or if expression. Note that these constructs -- can be expanded into Expression_With_Actions, hence the test of the -- original node. Par := Parent (N); while Present (Par) loop if Nkind_In (Original_Node (Par), N_Case_Expression, N_If_Expression) then return True; -- Prevent the search from going too far elsif Is_Body_Or_Package_Declaration (Par) then return False; end if; Par := Parent (Par); end loop; return False; end Within_Case_Or_If_Expression; -------------------------------- -- Within_Internal_Subprogram -- -------------------------------- function Within_Internal_Subprogram return Boolean is S : Entity_Id; begin S := Current_Scope; while Present (S) and then not Is_Subprogram (S) loop S := Scope (S); end loop; return Present (S) and then Get_TSS_Name (S) /= TSS_Null and then not Is_Predicate_Function (S) and then not Is_Predicate_Function_M (S); end Within_Internal_Subprogram; end Exp_Util;
with Ada.Text_IO, Ada.Integer_Text_IO; use Ada.Text_IO, Ada.Integer_Text_IO; package body display is function "=" (L, R : pixelType) return Boolean is begin null; --do compare return (L.char = R.char); end "="; procedure setPixel(X,Y : Integer; char : character; color : colorType := colorDefault) is begin begin Screen(X,Y).char := char; Screen(X,Y).color := color; exception when others => null; end; end setPixel; procedure setPixel(X,Y : Integer; pixel : pixelType) is begin Screen(X,Y) := pixel; end setPixel; function getPixel(X,Y : Integer) return pixelType is temp : pixelType := pixelType'('~', colorDefault); begin if(X >= 0 and X <= Screen_Width and Y >= 0 and Y <= Screen_Height) then temp := screen(X,Y); end if; return temp; end getPixel; function LoadSprite(FileName : String) return SpriteType is File : File_Type; width : Integer; height : Integer; sprite : SpriteType; line: String(1..2500); color : colorType := colorDefault; offset : Positive := 1; begin --clear garbage data width := 127; height := 63; For Y in Integer range 0..height loop For X in Integer range 0..width loop sprite.Image(X,Y).char := ' '; sprite.color := colorDefault; end loop; end loop; --load sprite Open(File, In_File, FileName); Get(File => File, Item => width); Get(File => File, Item => height); Skip_Line(File); sprite.Width := width; sprite.Height := height; For Y in Integer range 0..sprite.height loop Get_Line(File => File, Item => line, Last => width); --Put(line(1..width-1)); width := width; --Skip_Line(File); offset := 1; color := colorDefault; For X in Integer range 0..sprite.width-1 loop color := Line(X+offset..X+offset+colorType'length-1); offset := offset+colorType'length; sprite.Image(X,Y).char := line(X+offset); sprite.Image(X,Y).color := color; end loop; exit when End_of_File(File); --Put(" <EOL> "); new_line; end loop; Close(File); Return sprite; end LoadSprite; procedure SetSprite(posX, posY : Integer; sprite : SpriteType) is chr : Character; col : colorType; begin For Y in Integer range 0..sprite.Height-1 loop For X in Integer range 0..sprite.Width-1 loop if (posX + X <= Screen_Width AND posX + X >= 0 AND posY + Y <= Screen_Height AND posY + Y >= 0) then chr := sprite.Image(X,Y).char; col := sprite.Image(X,Y).color; if (Character'Pos(chr) >= 32) then setPixel(posX + X, posY + Y, chr, col); end if; end if; end loop; end loop; end SetSprite; --text functions procedure setText(posX,posY : Integer; Item : String; color : colorType := colorDefault) is begin for I in Integer Range 1..Item'length loop if(posX + I >= 0 and posX + I <= Screen_Width) then setPixel(posX + I, posY, Item(I), color); end if; end loop; end setText; procedure setText(posX,posY : Integer; Item : Character; color : colorType := colorDefault) is begin if(posX >= 0 and posX <= Screen_Width) then setPixel(posX, posY, Item, color); end if; end setText; procedure Initialize(width, height : Integer) is begin Screen_Width := width; Screen_Height := height; --Initialize Screen to blank For Y in Integer Range 0..Screen_Height loop For X in Integer Range 0..Screen_Width loop setPixel(X,Y,' ',colorDefault); end loop; end loop; end Initialize; --Refresh Screen procedure Refresh is begin --clear screen --New_Line(100); Put(ASCII.ESC & "[;H"); --fill screen For Y in Integer Range 0..Screen_Height loop For X in Integer Range 0..Screen_Width loop begin Put(Screen(X,Y).color); if(Character'Pos(Screen(X,Y).char) >= 32) then Put(Screen(X,Y).char); else Put(' '); end if; exception when others => null; end; Flush; end loop; New_Line; end loop; end Refresh; procedure ClearDisplay is begin For Y in Integer Range 0..Screen_Height loop For X in Integer Range 0..Screen_Width loop setPixel(X,Y,' ', colorDefault); end loop; end loop; end ClearDisplay; procedure WipeScreen is begin put(ASCII.ESC & "[2J"); end WipeScreen; end display;
with Ada.Text_IO; use Ada.Text_IO; procedure practice is begin null; end practice;
with Ada.Text_IO, tools; use Ada.Text_IO; package body Garden_Pkg is package Position_Generator is new tools.Random_Generator(Position); function GetRandPos return Position is begin return Position_Generator.GetRandom; end GetRandPos; function GetField(pos : Position) return Boolean is begin return Garden(pos); end GetField; procedure SprayField(pos : Position) is begin Garden(pos) := true; end SprayField; procedure SprayAbsorbed is begin Garden := (1..10 => false); end SprayAbsorbed; end Garden_Pkg;
-- C83027C.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 DECLARATION WITHIN THE DISCRIMINANT PART OF A -- PRIVATE TYPE DECLARATION, AN INCOMPLETE TYPE DECLARATION, AND A -- GENERIC FORMAL TYPE DECLARATION HIDES AN OUTER DECLARATION OF A -- HOMOGRAPH. ALSO, CHECK THAT THE OUTER DECLARATION IS DIRECTLY -- VISIBLE IN BOTH DECLARATIVE REGIONS BEFORE THE DECLARATION OF THE -- INNER HOMOGRAPH AND THE OUTER DECLARATION IS VISIBLE BY SELECTION -- AFTER THE INNER HOMOGRAPH DECLARATION. -- HISTORY: -- BCB 09/06/88 CREATED ORIGINAL TEST. WITH REPORT; USE REPORT; PROCEDURE C83027C IS GENERIC TYPE T IS PRIVATE; X : T; FUNCTION GEN_FUN RETURN T; FUNCTION GEN_FUN RETURN T IS BEGIN RETURN X; END GEN_FUN; BEGIN TEST ("C83027C", "CHECK THAT A DECLARATION IN THE DISCRIMINANT " & "PART OF A PRIVATE TYPE DECLARATION, AN " & "INCOMPLETE TYPE DECLARATION, AND A GENERIC " & "FORMAL TYPE DECLARATION HIDES AN OUTER " & "DECLARATION OF A HOMOGRAPH"); ONE: DECLARE A : INTEGER := IDENT_INT(2); D : INTEGER := IDENT_INT(2); G : INTEGER := IDENT_INT(2); H : INTEGER := G; TYPE REC (Z : INTEGER) IS RECORD NULL; END RECORD; GENERIC TYPE INNER3 (G : INTEGER) IS PRIVATE; PACKAGE P_ONE IS TYPE INNER (X : INTEGER := A; A : INTEGER := IDENT_INT(3); C : INTEGER := ONE.A) IS PRIVATE; TYPE INNER2 (Y : INTEGER := D; D : INTEGER := IDENT_INT(3); F : INTEGER := ONE.D); TYPE INNER2 (Y : INTEGER := D; D : INTEGER := IDENT_INT(3); F : INTEGER := ONE.D) IS RECORD E : INTEGER := D; END RECORD; PRIVATE TYPE INNER (X : INTEGER := A; A : INTEGER := IDENT_INT(3); C : INTEGER := ONE.A) IS RECORD B : INTEGER := A; END RECORD; END P_ONE; PACKAGE BODY P_ONE IS RECVAR : INNER; RECVAR2 : INNER2; RECVAR3 : INNER3(3); BEGIN IF RECVAR.A /= IDENT_INT(3) THEN FAILED ("INCORRECT VALUE FOR INNER HOMOGRAPH - 1"); END IF; IF A /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE FOR OUTER HOMOGRAPH - 2"); END IF; IF RECVAR.B /= IDENT_INT(3) THEN FAILED ("INCORRECT VALUE FOR INNER VARIABLE - 3"); END IF; IF RECVAR.C /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE FOR INNER VARIABLE - 4"); END IF; IF RECVAR.X /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE FOR INNER VARIABLE - 5"); END IF; IF RECVAR2.D /= IDENT_INT(3) THEN FAILED ("INCORRECT VALUE FOR INNER HOMOGRAPH - 6"); END IF; IF D /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE FOR OUTER HOMOGRAPH - 7"); END IF; IF RECVAR2.E /= IDENT_INT(3) THEN FAILED ("INCORRECT VALUE FOR INNER VARIABLE - 8"); END IF; IF RECVAR2.F /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE FOR INNER VARIABLE - 9"); END IF; IF RECVAR2.Y /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE FOR INNER VARIABLE - 10"); END IF; IF RECVAR3.G /= IDENT_INT(3) THEN FAILED ("INCORRECT VALUE FOR INNER HOMOGRAPH - 11"); END IF; IF G /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE FOR OUTER HOMOGRAPH - 12"); END IF; IF H /= IDENT_INT(2) THEN FAILED ("INCORRECT VALUE FOR OUTER VARIABLE - 13"); END IF; END P_ONE; PACKAGE NEW_P_ONE IS NEW P_ONE (REC); BEGIN -- ONE NULL; END ONE; RESULT; END C83027C;
----------------------------------------------------------------------- -- awa-counters -- -- Copyright (C) 2015, 2018, 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 ADO.Objects; with ADO.Schemas; with Util.Strings; with AWA.Index_Arrays; -- = Counters Module = -- The `counters` module defines a general purpose counter service that -- allows to associate counters to database entities. For example it -- can be used to track the number of times a blog post or a wiki page -- is accessed. The `counters` module maintains the counters in a table -- on a per-day and per-entity basis. It allows to update the full counter -- in the target database entity table. -- -- @include awa-counters-modules.ads -- -- == Counter Declaration == -- Each counter must be declared by instantiating the `Definition` package. -- This instantiation serves as identification of the counter and it defines -- the database table as well as the column in that table that will hold -- the total counter. The following definition is used for the read counter -- of a wiki page. The wiki page table contains a `read_count` column -- and it will be incremented each time the counter is incremented. -- -- with AWA.Counters.Definition; -- ... -- package Read_Counter is -- new AWA.Counters.Definition -- (AWA.Wikis.Models.WIKI_PAGE_TABLE, "read_count"); -- -- When the database table does not contain any counter column, the column -- field name is not given and the counter definition is defined as follows: -- -- with AWA.Counters.Definition; -- ... -- package Login_Counter is -- new AWA.Counters.Definition (AWA.Users.Models.USER_PAGE_TABLE); -- -- Sometimes a counter is not associated with any database entity. -- Such counters are global and they are assigned a unique name. -- -- with AWA.Counters.Definition; -- ... -- package Start_Counter is -- new AWA.Counters.Definition (null, "startup_counter"); -- -- == Incrementing the counter == -- Incrementing the counter is done by calling the `Increment` operation. -- When the counter is associated with a database entity, the entity -- primary key must be given. The counter is not immediately incremented -- in the database so that several calls to the `Increment` operation will -- not trigger a database update. -- -- with AWA.Counters; -- ... -- AWA.Counters.Increment (Counter => Read_Counter.Counter, Key => Id); -- -- A global counter is also incremented by using the `Increment` operation. -- -- with AWA.Counters; -- ... -- AWA.Counters.Increment (Counter => Start_Counter.Counter); -- -- @include awa-counters-beans.ads -- @include awa-counters-components.ads -- -- == Data model == -- The `counters` module has a simple database model which needs two tables. -- The `Counter_Definition` table is used to keep track of the different -- counters used by the application. A row in that table is created for -- each counter declared by instantiating the `Definition` package. -- The `Counter` table holds the counters for each database entity -- and for each day. By looking at that table, it becomes possible -- to look at the daily access or usage of the counter. -- -- [images/awa_counters_model.png] -- package AWA.Counters is type Counter_Index_Type is new Natural; -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object <tt>Object</tt>. procedure Increment (Counter : in Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class); -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object key <tt>Key</tt>. procedure Increment (Counter : in Counter_Index_Type; Key : in ADO.Objects.Object_Key); -- Increment the global counter identified by <tt>Counter</tt>. procedure Increment (Counter : in Counter_Index_Type); private type Counter_Def is record Table : ADO.Schemas.Class_Mapping_Access; Field : Util.Strings.Name_Access; end record; function "=" (Left, Right : in Counter_Def) return Boolean; function "<" (Left, Right : in Counter_Def) return Boolean; function "&" (Left : in String; Right : in Counter_Def) return String; package Counter_Arrays is new AWA.Index_Arrays (Counter_Index_Type, Counter_Def); end AWA.Counters;
-- Take advantage of the DMA2D to accelerate some graphical operations on -- bitmap surfaces with System; with HAL.Bitmap; package STM32.DMA2D_Bitmap is type DMA2D_Bitmap_Buffer is new HAL.Bitmap.Bitmap_Buffer with null record; overriding procedure Set_Pixel (Buffer : DMA2D_Bitmap_Buffer; X : Natural; Y : Natural; Value : Word); overriding procedure Set_Pixel_Blend (Buffer : DMA2D_Bitmap_Buffer; X : Natural; Y : Natural; Value : HAL.Bitmap.Bitmap_Color); overriding function Get_Pixel (Buffer : DMA2D_Bitmap_Buffer; X : Natural; Y : Natural) return Word; overriding procedure Fill (Buffer : DMA2D_Bitmap_Buffer; Color : Word); overriding procedure Fill_Rect (Buffer : DMA2D_Bitmap_Buffer; Color : Word; X : Integer; Y : Integer; Width : Integer; Height : Integer); overriding procedure Copy_Rect (Src_Buffer : HAL.Bitmap.Bitmap_Buffer'Class; X_Src : Natural; Y_Src : Natural; Dst_Buffer : DMA2D_Bitmap_Buffer; X_Dst : Natural; Y_Dst : Natural; Bg_Buffer : HAL.Bitmap.Bitmap_Buffer'Class; X_Bg : Natural; Y_Bg : Natural; Width : Natural; Height : Natural) with Pre => Dst_Buffer.Color_Mode in HAL.Bitmap.ARGB_8888 .. HAL.Bitmap.ARGB_4444; overriding procedure Wait_Transfer (Buffer : DMA2D_Bitmap_Buffer); Null_Buffer : constant DMA2D_Bitmap_Buffer := (Addr => System.Null_Address, Width => 0, Height => 0, Color_Mode => HAL.Bitmap.L_8, Swapped => False); end STM32.DMA2D_Bitmap;
------------------------------------------------------------------------------ -- -- -- Command Line Interface Toolkit -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2019-2021, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Ensi Martini (ANNEXI-STRAYLINE) -- -- -- -- 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 copyright holder 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 Ada.Text_IO; use Ada; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Interfaces.C; use Interfaces.C; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; pragma External_With ("tty_ifo.c"); package body CLI is -- -- Helper functions, state, and constants -- Column_Actual: Positive; -- This is initialized by the package elaboration, which actually ensures -- the cursor is at this position by calling Clear_Line Control_Preamble: constant Character := Character'Val (8#33#); -- '\033' -- Needs to be output at the beginning of all ANSI terminal control codes CSI: constant String := Control_Preamble & '['; function Trim_Num (Num : Integer) return String is (Ada.Strings.Fixed.Trim(Integer'Image(Num), Ada.Strings.Left)); -- Helper function to ensure our codes with ordinals don't have extra spaces -------------------- -- Terminal_Width -- -------------------- function Terminal_Width return Positive is function term_width return Interfaces.C.unsigned_short with Import => True, Convention => C, External_Name => "tty_ifo__term_width"; begin if Output_Is_Terminal then return Positive (term_width); else return 80; end if; end Terminal_Width; ----------------------- -- Ouput_Is_Terminal -- ----------------------- use type Interfaces.C.int; function isatty return Interfaces.C.int with Import => True, Convention => C, External_Name => "tty_ifo__isatty"; Is_TTY: constant Boolean := (isatty > 0); function Output_Is_Terminal return Boolean is (Is_TTY); ---------------- -- Set_Column -- ---------------- procedure Set_Column (Col: in Positive) is begin if Is_TTY then Text_IO.Put (CSI & Trim_Num (Col) & 'G'); end if; Column_Actual := Col; end Set_Column; -------------------- -- Current_Column -- -------------------- function Current_Column return Positive is (Column_Actual); ------------------ -- Clear_Screen -- ------------------ procedure Clear_Screen is Clear_Screen_Sequence : constant String := CSI & "2J" & -- Clear entire screen CSI & ";H"; -- Home cursor to top-left begin if Is_TTY then Text_IO.Put (Clear_Screen_Sequence); end if; Column_Actual := 1; end Clear_Screen; ---------------- -- Clear_Line -- ---------------- procedure Clear_Line is begin -- Move cursor to column 1 and clear line Set_Column (1); Clear_To_End; end Clear_Line; ------------------ -- Clear_To_End -- ------------------ procedure Clear_To_End is begin if Is_TTY then Text_IO.Put (CSI & 'K'); -- Clear to end end if; end Clear_To_End; --------- -- Put -- --------- procedure Put (Char : Character; Style : Text_Style := Neutral) is begin Put (Message => String'(1 .. 1 => Char), Style => Style); end Put; -------------------------------------------------- procedure Put (Message: String; Style : Text_Style := Neutral) is begin Clear_Style; Apply_Style(Style); Text_IO.Put(Message); Clear_Style; Column_Actual := Column_Actual + Message'Length; end Put; ------------------- -- Wide_Wide_Put -- ------------------- procedure Wide_Wide_Put (Char : in Wide_Wide_Character; Style: in Text_Style := Neutral) is begin Wide_Wide_Put (Message => Wide_Wide_String'(1 .. 1 => Char), Style => Style); end Wide_Wide_Put; -------------------------------------------------- procedure Wide_Wide_Put (Message: in Wide_Wide_String; Style : in Text_Style := Neutral) is use Ada.Strings.UTF_Encoding; use Ada.Strings.UTF_Encoding.Wide_Wide_Strings; Encoded_Message: constant UTF_8_String := Encode (Message); begin Clear_Style; Apply_Style(Style); Text_IO.Put(Encoded_Message); Clear_Style; Column_Actual := Column_Actual + Message'Length; end Wide_Wide_Put; ------------ -- Put_At -- ------------ procedure Put_At (Char : in Character; Column : in Positive; Style : in Text_Style := Neutral) is begin Put_At (Message => String'(1 .. 1 => Char), Column => Column, Style => Style); end Put_At; -------------------------------------------------- procedure Put_At (Message: in String; Column : in Positive; Style : in Text_Style := Neutral) is Save_Col: constant Positive := Current_Column; begin Set_Column (Column); Put (Message => Message, Style => Style); Set_Column (Save_Col); end Put_At; ---------------------- -- Wide_Wide_Put_At -- ---------------------- procedure Wide_Wide_Put_At (Char : in Wide_Wide_Character; Column: in Positive; Style : in Text_Style := Neutral) is begin Wide_Wide_Put_At (Message => Wide_Wide_String'(1 .. 1 => Char), Column => Column, Style => Style); end Wide_Wide_Put_At; -------------------------------------------------- procedure Wide_Wide_Put_At (Message: in Wide_Wide_String; Column : in Positive; Style : in Text_Style := Neutral) is Save_Col: constant Positive := Current_Column; begin Set_Column (Column); Wide_Wide_Put (Message => Message, Style => Style); Set_Column (Save_Col); end Wide_Wide_Put_At; -------------- -- Put_Line -- -------------- procedure Put_Line (Message: String; Style : Text_Style := Neutral) is begin Put (Message, Style); New_Line; end Put_Line; ------------------------ -- Wide_Wide_Put_Line -- ------------------------ procedure Wide_Wide_Put_Line (Message: Wide_Wide_String; Style : Text_Style := Neutral) is begin Wide_Wide_Put (Message, Style); New_Line; end Wide_Wide_Put_Line; -------------- -- New_Line -- -------------- procedure New_Line is begin Text_IO.New_Line; Set_Column (1); end New_Line; ----------------------- -- Get/Get_Immediate -- ----------------------- procedure Get (Item: out String) renames Text_IO.Get; procedure Get (Item: out Character) renames Text_IO.Get; procedure Get_Line (Item: out String; Last: out Natural) renames Text_IO.Get_Line; procedure Get_Immediate (Item: out Character; Available: out Boolean) renames Text_IO.Get_Immediate; -------------------------- -- Text_Style Operators -- -------------------------- -- "+" -- function "+" (Left, Right : Text_Style) return Text_Style is -- This function will always take the color of the right Cursor, because -- addition works like an overwrite for all the attributes that are not -- currently turned on for Left cursor FG : Color := (if (Right.Foreground /= Default) then Right.Foreground else Left.Foreground); BG : Color := (if (Right.Background /= Default) then Right.Background else Left.Background); begin return (Text_Style'(Foreground => FG, Background => BG, Bold => Left.Bold or Right.Bold, Underscore => Left.Underscore or Right.Underscore, Blink => Left.Blink or Right.Blink, Reverse_Vid => Left.Reverse_Vid or Right.Reverse_Vid, Concealed => Left.Concealed or Right.Concealed)); end "+"; -- "-" -- function "-" (Left, Right : Text_Style) return Text_Style is -- This function will always take the color of the left Cursor, unless -- they are the same -- This is because subtracting the right Cursor means we cannot have that -- property of it FG : Color := (if (Left.Foreground = Right.Foreground) then Default else Left.Foreground); BG : Color := (if (Left.Background = Right.Background) then Default else Left.Background); begin return (Text_Style'(Foreground => FG, Background => BG, Bold => Left.Bold and (Left.Bold xor Right.Bold), Underscore => Left.Underscore and (Left.Underscore xor Right.Underscore), Blink => Left.Blink and (Left.Blink xor Right.Blink), Reverse_Vid => Left.Reverse_Vid and (Left.Reverse_Vid xor Right.Reverse_Vid), Concealed => Left.Concealed and (Left.Concealed xor Right.Concealed))); end "-"; ----------------- -- Apply_Style -- ----------------- procedure Apply_Style (Style : Text_Style) is Attribute_Sequence : String := CSI & "0m"; Change_Foreground_Sequence : String := CSI & Trim_Num(Color'Pos(Style.Foreground) + 30) & 'm'; Change_Background_Sequence : String := CSI & Trim_Num(Color'Pos(Style.Background) + 40) & 'm'; begin if not Is_TTY then return; end if; if Style.Foreground /= Default then Text_IO.Put(Change_Foreground_Sequence); end if; if Style.Background /= Default then Text_IO.Put(Change_Background_Sequence); end if; declare procedure Apply_Attribute (Attribute_Num : Integer) with Inline is begin -- Take first index of Trim_Num return because it is a string but -- we need a char Attribute_Sequence(3) := Trim_Num(Attribute_Num)(1); Text_IO.Put(Attribute_Sequence); end Apply_Attribute; begin if Style.Bold then Apply_Attribute(1); end if; if Style.Underscore then Apply_Attribute(4); end if; if Style.Blink then Apply_Attribute(5); end if; if Style.Reverse_Vid then Apply_Attribute(7); end if; if Style.Concealed then Apply_Attribute(8); end if; end; end Apply_Style; ----------------- -- Clear_Style -- ----------------- procedure Clear_Style is begin if not Is_TTY then return; end if; Text_IO.Put (CSI & "0m"); -- "Reset attributes"; end Clear_Style; begin Clear_Line; end CLI;
with System.Interrupt_Handlers; with System.Interrupt_Numbers; with System.Native_Interrupts.Vector; package body Ada.Interrupts is function Is_Reserved (Interrupt : Interrupt_Id) return Boolean is begin return System.Interrupt_Numbers.Is_Reserved ( System.Native_Interrupts.Interrupt_Id (Interrupt)); end Is_Reserved; function Is_Blocked (Interrupt : Interrupt_Id) return Boolean is begin return System.Native_Interrupts.Is_Blocked ( System.Native_Interrupts.Interrupt_Id (Interrupt)); end Is_Blocked; procedure Block (Interrupt : Interrupt_Id) is begin System.Native_Interrupts.Block ( System.Native_Interrupts.Interrupt_Id (Interrupt)); end Block; procedure Unblock (Interrupt : Interrupt_Id) is begin System.Native_Interrupts.Unblock ( System.Native_Interrupts.Interrupt_Id (Interrupt)); end Unblock; function Is_Attached (Interrupt : Interrupt_Id) return Boolean is begin return Current_Handler (Interrupt) /= null; end Is_Attached; function Current_Handler (Interrupt : Interrupt_Id) return Parameterless_Handler is begin if Is_Reserved (Interrupt) then raise Program_Error; end if; return System.Native_Interrupts.Vector.Current_Handler ( System.Native_Interrupts.Interrupt_Id (Interrupt)); end Current_Handler; procedure Attach_Handler ( New_Handler : Parameterless_Handler; Interrupt : Interrupt_Id) is Dummy_Old_Handler : Parameterless_Handler; begin Exchange_Handler (Dummy_Old_Handler, New_Handler, Interrupt); end Attach_Handler; procedure Exchange_Handler ( Old_Handler : out Parameterless_Handler; New_Handler : Parameterless_Handler; Interrupt : Interrupt_Id) is begin Old_Handler := Current_Handler (Interrupt); if (Old_Handler /= null and then System.Interrupt_Handlers.Is_Static_Handler (Old_Handler)) or else ( New_Handler /= null and then System.Interrupt_Handlers.Is_Static_Handler (New_Handler)) then raise Program_Error; end if; Unchecked_Exchange_Handler (Old_Handler, New_Handler, Interrupt); end Exchange_Handler; procedure Detach_Handler (Interrupt : Interrupt_Id) is Dummy_Old_Handler : Parameterless_Handler; begin Exchange_Handler (Dummy_Old_Handler, null, Interrupt); end Detach_Handler; procedure Unchecked_Attach_Handler ( New_Handler : Parameterless_Handler; Interrupt : Interrupt_Id) is Dummy_Old_Handler : Parameterless_Handler; begin Unchecked_Exchange_Handler (Dummy_Old_Handler, New_Handler, Interrupt); end Unchecked_Attach_Handler; procedure Unchecked_Exchange_Handler ( Old_Handler : out Parameterless_Handler; New_Handler : Parameterless_Handler; Interrupt : Interrupt_Id) is begin System.Native_Interrupts.Vector.Exchange_Handler ( Old_Handler, New_Handler, System.Native_Interrupts.Interrupt_Id (Interrupt)); end Unchecked_Exchange_Handler; procedure Unchecked_Detach_Handler (Interrupt : Interrupt_Id) is Dummy_Old_Handler : Parameterless_Handler; begin Unchecked_Exchange_Handler (Dummy_Old_Handler, null, Interrupt); end Unchecked_Detach_Handler; procedure Raise_Interrupt (Interrupt : Interrupt_Id) is begin System.Native_Interrupts.Raise_Interrupt ( System.Native_Interrupts.Interrupt_Id (Interrupt)); end Raise_Interrupt; end Ada.Interrupts;
with impact.d3.Scalar, impact.d3.Vector; package body impact.d3.Quaternions is function to_Quaternion (x, y, z, w : in Real) return Quaternion is begin return (x, (y, z, w)); end to_Quaternion; function to_Quaternion (Axis : in Vector_3; Angle : in Real) return Quaternion is Self : Quaternion; begin setRotation (Self, Axis, Angle); return Self; end to_Quaternion; function x (Self : in Quaternion) return Real is begin return Self.V (1); end x; function y (Self : in Quaternion) return Real is begin return Self.V (2); end y; function z (Self : in Quaternion) return Real is begin return Self.V (3); end z; function w (Self : in Quaternion) return Real is begin return Self.R; end w; procedure setRotation (Self : out Quaternion; Axis : in Vector_3; Angle : in Real) is use impact.d3.Vector, math.Functions; d : constant Real := length (axis); pragma Assert (d /= 0.0); s : constant Real := Sin (angle * 0.5) / d; begin Self := (V => (x (axis) * s, y (axis) * s, z (axis) * s), R => Cos (angle * 0.5)); end setRotation; function to_Quaternion (Yaw, Pitch, Roll : in Real ) return Quaternion is Self : Quaternion; begin if BT_EULER_DEFAULT_ZYX then setEulerZYX (Self, Yaw, Pitch, Roll); else setEuler (Self, Yaw, Pitch, Roll); end if; return Self; end to_Quaternion; procedure setEuler (Self : out Quaternion; Yaw, Pitch, Roll : in Real) is use math.Functions; halfYaw : constant Real := yaw * 0.5; halfPitch : constant Real := pitch * 0.5; halfRoll : constant Real := roll * 0.5; cosYaw : constant Real := Cos (halfYaw); sinYaw : constant Real := Sin (halfYaw); cosPitch : constant Real := Cos (halfPitch); sinPitch : constant Real := Sin (halfPitch); cosRoll : constant Real := Cos (halfRoll); sinRoll : constant Real := Sin (halfRoll); begin Self := (V => (cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw, cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw, sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw), R => cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw); end setEuler; procedure setEulerZYX (Self : out Quaternion; Yaw, Pitch, Roll : in Real) is use math.Functions; halfYaw : constant Real := yaw * 0.5; halfPitch : constant Real := pitch * 0.5; halfRoll : constant Real := roll * 0.5; cosYaw : constant Real := Cos (halfYaw); sinYaw : constant Real := Sin (halfYaw); cosPitch : constant Real := Cos (halfPitch); sinPitch : constant Real := Sin (halfPitch); cosRoll : constant Real := Cos (halfRoll); sinRoll : constant Real := Sin (halfRoll); begin Self := (V => (sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw, -- x cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw, -- y cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw), -- z R => cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw); -- formerly yzx end setEulerZYX; function multiply (Left, Right : in Quaternion) return Quaternion is use linear_Algebra_3d; begin return Left * Right; end multiply; function dot (Left, Right : in Quaternion) return Real is use linear_Algebra_3d; begin return Left * Right; end dot; function length2 (Self : in Quaternion) return Real is begin return dot (Self, Self); end length2; function length (Self : in Quaternion) return Real is use math.Functions; begin return sqRt (length2 (Self)); end length; function normalize (Self : access Quaternion) return Quaternion is use math.Vectors; begin Self.all := normalized (Self.all); return Self.all; end normalize; function normalized (Self : in Quaternion) return Quaternion is use linear_Algebra_3d; begin return Self / length (Self); end normalized; procedure normalize (Self : in out Quaternion) is begin Self := normalized (Self); end normalize; -- function "*" (Left : in Quaternion; Right : in Real) return Quaternion -- is -- use math.real_Arrays; -- begin -- return Quaternion (math.Vector_4 (Left) * Right); -- end; -- function "/" (Left : in Quaternion; Right : in Real) return Quaternion -- is -- use math.real_Arrays; -- begin -- pragma assert (Right /= 0.0); -- return Left * (1.0 / Right); -- end; function Angle (Left, Right : in Quaternion) return Real is use math.Functions; s : constant Real := sqRt (length2 (Left) * length2 (Right)); pragma Assert (s /= 0.0); begin return arcCos (dot (Left, Right) / s); end Angle; function getAngle (Self : in Quaternion) return Real is use math.Functions; begin return 2.0 * arcCos (Self.R); end getAngle; function getAxis (Self : in Quaternion) return Vector_3 is use impact.d3.Scalar, math.Functions; s_squared : constant Real := 1.0 - Self.R * Self.R; s : Real; begin if s_squared < 10.0 * SIMD_EPSILON then -- Check for divide by zero return (1.0, 0.0, 0.0); -- Arbitrary end if; s := 1.0 / sqRt (s_squared); return (Self.V (1) * s, Self.V (2) * s, Self.V (3) * s); end getAxis; function inverse (Self : in Quaternion) return Quaternion is begin return (Self.R, -Self.V); end inverse; -- function "+" (Left, Right : in Quaternion) return Quaternion -- is -- use math.real_Arrays; -- begin -- return Quaternion (Vector_4 (Left) + Vector_4 (Right)); -- end; -- -- -- -- function "-" (Left, Right : in Quaternion) return Quaternion -- is -- use math.real_Arrays; -- begin -- return Quaternion (Vector_4 (Left) - Vector_4 (Right)); -- end; function "-" (Self : in Quaternion) return Quaternion is begin return (R => -Self.R, V => -Self.V); end "-"; function farthest (Self : in Quaternion; qd : in Quaternion) return Quaternion is diff : constant Quaternion := Self - qd; sum : constant Quaternion := Self + qd; begin if dot (diff, diff) > dot (sum, sum) then return qd; end if; return -qd; end farthest; function nearest (Self : in Quaternion; qd : in Quaternion) return Quaternion is diff : constant Quaternion := Self - qd; sum : constant Quaternion := Self + qd; begin if dot (diff, diff) < dot (sum, sum) then return qd; end if; return -qd; end nearest; function slerp (Self : in Quaternion; q : in Quaternion; t : in Real ) return Quaternion is use math.Functions; theta : constant Real := angle (Self, q); d, s0, s1 : Real; begin if theta /= 0.0 then d := 1.0 / Sin (theta); s0 := Sin ((1.0 - t) * theta); s1 := Sin (t * theta); if dot (Self, q) < 0.0 then -- Take care of long angle case see http://en.wikipedia.org/wiki/Slerp return (V => ((Self.V (1) * s0 + (-x (q) * s1)) * d, (Self.V (2) * s0 + (-y (q) * s1)) * d, (Self.V (3) * s0 + (-z (q) * s1)) * d), R => ( Self.R * s0 + (-q.R * s1)) * d ); else return (V => ((Self.V (1) * s0 + x (q) * s1) * d, (Self.V (2) * s0 + y (q) * s1) * d, (Self.V (3) * s0 + z (q) * s1) * d), R => ( Self.R * s0 + q.R * s1) * d ); end if; else return Self; end if; end slerp; function getIdentity return Quaternion is begin return (V => (0.0, 0.0, 0.0), R => 1.0); end getIdentity; function "*" (Left : in Quaternion; Right : in Vector_3) return Quaternion is use linear_Algebra_3d; begin return linear_Algebra_3d."*" (Left, Right); -- return (w (Left) * x (Right) + y (Left) * z (Right) - z (Left) * y (Right), -- w (Left) * y (Right) + z (Left) * x (Right) - x (Left) * z (Right), -- w (Left) * z (Right) + x (Left) * y (Right) - y (Left) * x (Right), -- -x (Left) * x (Right) - y (Left) * y (Right) - z (Left) * z (Right)); end "*"; function "*" (Left : in Vector_3; Right : in Quaternion) return Quaternion is use impact.d3.Vector; begin return linear_Algebra_3d."*" (Left, Right); -- return (x (Left) * w (Right) + y (Left) * z (Right) - z (Left) * y (Right), -- y (Left) * w (Right) + z (Left) * x (Right) - x (Left) * z (Right), -- z (Left) * w (Right) + x (Left) * y (Right) - y (Left) * x (Right), -- -x (Left) * x (Right) - y (Left) * y (Right) - z (Left) * z (Right)); end; function quatRotate (rotation : in Quaternion; v : in Vector_3) return Vector_3 is q : Quaternion := rotation * v; begin q := multiply (q, inverse (rotation)); return (X (q), Y (q), Z (q)); end quatRotate; function shortestArcQuat (v1, v2 : in Vector_3) return Quaternion is use impact.d3.Scalar, impact.d3.Vector, math.Functions; c : constant Vector_3 := cross (v1, v2); d : constant Real := dot (v1, v2); n, unused : Vector_3; s, rs : Real; begin if d < -1.0 + SIMD_EPSILON then btPlaneSpace1 (v1, n, unused); return (V => (x (n), y (n), z (n)), R => 0.0); -- just pick any vector that is orthogonal to v1 end if; s := sqRt ((1.0 + d) * 2.0); rs := 1.0 / s; return (V => (X (c) * rs, Y (c) * rs, Z (c) * rs), R => s * 0.5); end shortestArcQuat; function shortestArcQuatNormalize2 (v1, v2 : access Vector_3) return Quaternion is use impact.d3.Scalar, impact.d3.Vector, math.Functions; begin normalize (v1.all); normalize (v2.all); return shortestArcQuat (v1.all, v2.all); end shortestArcQuatNormalize2; end impact.d3.Quaternions;
package GESTE_Fonts.FreeMonoBold5pt7b is Font : constant Bitmap_Font_Ref; private FreeMonoBold5pt7bBitmaps : aliased constant Font_Bitmap := ( 16#00#, 16#00#, 16#0C#, 16#30#, 16#C3#, 16#00#, 16#30#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#51#, 16#40#, 16#00#, 16#00#, 16#00#, 16#00#, 16#02#, 16#8A#, 16#78#, 16#C3#, 16#1E#, 16#51#, 16#40#, 16#00#, 16#00#, 16#04#, 16#69#, 16#C0#, 16#82#, 16#78#, 16#40#, 16#00#, 16#06#, 16#14#, 16#51#, 16#E7#, 16#8A#, 16#18#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#40#, 16#86#, 16#16#, 16#78#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#20#, 16#80#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#02#, 16#10#, 16#41#, 16#04#, 16#10#, 16#60#, 16#00#, 16#00#, 16#18#, 16#20#, 16#82#, 16#08#, 16#21#, 16#80#, 16#00#, 16#00#, 16#08#, 16#78#, 16#C7#, 16#80#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#20#, 16#8F#, 16#C8#, 16#20#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#20#, 16#80#, 16#00#, 16#00#, 16#00#, 16#00#, 16#0F#, 16#C0#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#30#, 16#00#, 16#00#, 16#00#, 16#82#, 16#10#, 16#42#, 16#08#, 16#41#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#49#, 16#24#, 16#92#, 16#30#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#60#, 16#82#, 16#08#, 16#78#, 16#00#, 16#00#, 16#00#, 16#1C#, 16#48#, 16#21#, 16#08#, 16#78#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#08#, 16#C0#, 16#82#, 16#78#, 16#00#, 16#00#, 16#00#, 16#00#, 16#10#, 16#C5#, 16#1E#, 16#38#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#41#, 16#E0#, 16#82#, 16#78#, 16#00#, 16#00#, 16#00#, 16#06#, 16#61#, 16#E4#, 16#92#, 16#38#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#08#, 16#61#, 16#04#, 16#20#, 16#00#, 16#00#, 16#00#, 16#0E#, 16#48#, 16#C4#, 16#92#, 16#78#, 16#00#, 16#00#, 16#00#, 16#0E#, 16#49#, 16#23#, 16#82#, 16#70#, 16#00#, 16#00#, 16#00#, 16#00#, 16#30#, 16#00#, 16#00#, 16#30#, 16#00#, 16#00#, 16#00#, 16#00#, 16#30#, 16#00#, 16#00#, 16#20#, 16#80#, 16#00#, 16#00#, 16#00#, 16#08#, 16#C6#, 16#06#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#03#, 16#F0#, 16#3F#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#40#, 16#C1#, 16#98#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#48#, 16#61#, 16#00#, 16#30#, 16#00#, 16#00#, 16#00#, 16#0C#, 16#49#, 16#66#, 16#96#, 16#41#, 16#20#, 16#00#, 16#00#, 16#1C#, 16#31#, 16#27#, 16#92#, 16#DC#, 16#00#, 16#00#, 16#00#, 16#3E#, 16#49#, 16#27#, 16#91#, 16#F8#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#4A#, 16#08#, 16#10#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#3C#, 16#49#, 16#24#, 16#92#, 16#F8#, 16#00#, 16#00#, 16#00#, 16#3E#, 16#49#, 16#C5#, 16#12#, 16#FC#, 16#00#, 16#00#, 16#00#, 16#3F#, 16#59#, 16#C4#, 16#10#, 16#F0#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#4A#, 16#09#, 16#D2#, 16#78#, 16#00#, 16#00#, 16#00#, 16#3F#, 16#49#, 16#E4#, 16#92#, 16#FC#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#20#, 16#82#, 16#08#, 16#78#, 16#00#, 16#00#, 16#00#, 16#0F#, 16#08#, 16#20#, 16#92#, 16#70#, 16#00#, 16#00#, 16#00#, 16#3F#, 16#59#, 16#85#, 16#12#, 16#EC#, 16#00#, 16#00#, 16#00#, 16#3C#, 16#20#, 16#82#, 16#49#, 16#FC#, 16#00#, 16#00#, 16#00#, 16#33#, 16#CE#, 16#DB#, 16#65#, 16#CC#, 16#00#, 16#00#, 16#00#, 16#37#, 16#69#, 16#A5#, 16#96#, 16#E8#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#4A#, 16#18#, 16#52#, 16#78#, 16#00#, 16#00#, 16#00#, 16#3E#, 16#49#, 16#27#, 16#90#, 16#F0#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#4A#, 16#18#, 16#52#, 16#79#, 16#F0#, 16#00#, 16#00#, 16#3C#, 16#49#, 16#27#, 16#16#, 16#EC#, 16#00#, 16#00#, 16#00#, 16#0E#, 16#49#, 16#81#, 16#82#, 16#78#, 16#00#, 16#00#, 16#00#, 16#3F#, 16#A6#, 16#92#, 16#08#, 16#78#, 16#00#, 16#00#, 16#00#, 16#3F#, 16#49#, 16#24#, 16#92#, 16#30#, 16#00#, 16#00#, 16#00#, 16#33#, 16#49#, 16#27#, 16#8C#, 16#30#, 16#00#, 16#00#, 16#00#, 16#3F#, 16#B5#, 16#E7#, 16#9E#, 16#48#, 16#00#, 16#00#, 16#00#, 16#33#, 16#48#, 16#C3#, 16#12#, 16#FC#, 16#00#, 16#00#, 16#00#, 16#33#, 16#48#, 16#C2#, 16#08#, 16#78#, 16#00#, 16#00#, 16#00#, 16#1E#, 16#58#, 16#42#, 16#12#, 16#78#, 16#00#, 16#00#, 16#00#, 16#06#, 16#00#, 16#00#, 16#00#, 16#00#, 16#60#, 16#00#, 16#04#, 16#10#, 16#20#, 16#81#, 16#04#, 16#08#, 16#20#, 16#00#, 16#00#, 16#1C#, 16#20#, 16#82#, 16#08#, 16#21#, 16#C0#, 16#00#, 16#00#, 16#08#, 16#31#, 16#20#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#08#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#70#, 16#27#, 16#B2#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#30#, 16#79#, 16#34#, 16#53#, 16#F8#, 16#00#, 16#00#, 16#00#, 16#00#, 16#79#, 16#24#, 16#11#, 16#78#, 16#00#, 16#00#, 16#00#, 16#06#, 16#79#, 16#28#, 16#B2#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#71#, 16#2F#, 16#90#, 16#78#, 16#00#, 16#00#, 16#00#, 16#0F#, 16#78#, 16#82#, 16#08#, 16#78#, 16#00#, 16#00#, 16#00#, 16#00#, 16#7F#, 16#28#, 16#92#, 16#78#, 16#20#, 16#00#, 16#00#, 16#30#, 16#79#, 16#24#, 16#92#, 16#FC#, 16#00#, 16#00#, 16#00#, 16#08#, 16#70#, 16#82#, 16#08#, 16#78#, 16#00#, 16#00#, 16#00#, 16#04#, 16#78#, 16#20#, 16#82#, 16#08#, 16#20#, 16#00#, 16#00#, 16#30#, 16#59#, 16#C6#, 16#14#, 16#DC#, 16#00#, 16#00#, 16#00#, 16#1C#, 16#20#, 16#82#, 16#08#, 16#78#, 16#00#, 16#00#, 16#00#, 16#00#, 16#FA#, 16#59#, 16#65#, 16#D4#, 16#00#, 16#00#, 16#00#, 16#00#, 16#F9#, 16#24#, 16#92#, 16#FC#, 16#00#, 16#00#, 16#00#, 16#00#, 16#79#, 16#28#, 16#52#, 16#78#, 16#00#, 16#00#, 16#00#, 16#00#, 16#F9#, 16#14#, 16#53#, 16#79#, 16#00#, 16#00#, 16#00#, 16#00#, 16#7F#, 16#28#, 16#B2#, 16#78#, 16#20#, 16#00#, 16#00#, 16#00#, 16#7C#, 16#C2#, 16#08#, 16#78#, 16#00#, 16#00#, 16#00#, 16#00#, 16#79#, 16#C7#, 16#8E#, 16#78#, 16#00#, 16#00#, 16#00#, 16#10#, 16#F9#, 16#04#, 16#10#, 16#38#, 16#00#, 16#00#, 16#00#, 16#00#, 16#D9#, 16#24#, 16#92#, 16#7C#, 16#00#, 16#00#, 16#00#, 16#00#, 16#FD#, 16#27#, 16#8C#, 16#30#, 16#00#, 16#00#, 16#00#, 16#00#, 16#CD#, 16#E7#, 16#9E#, 16#48#, 16#00#, 16#00#, 16#00#, 16#00#, 16#FD#, 16#E3#, 16#1E#, 16#FC#, 16#00#, 16#00#, 16#00#, 16#00#, 16#CD#, 16#27#, 16#8C#, 16#30#, 16#80#, 16#00#, 16#00#, 16#00#, 16#78#, 16#43#, 16#18#, 16#78#, 16#00#, 16#00#, 16#00#, 16#06#, 16#20#, 16#86#, 16#08#, 16#20#, 16#C0#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#18#, 16#10#, 16#41#, 16#84#, 16#10#, 16#C0#, 16#00#, 16#00#, 16#00#, 16#01#, 16#81#, 16#80#, 16#00#, 16#00#); Font_D : aliased constant Bitmap_Font := ( Bytes_Per_Glyph => 8, Glyph_Width => 6, Glyph_Height => 10, Data => FreeMonoBold5pt7bBitmaps'Access); Font : constant Bitmap_Font_Ref := Font_D'Access; end GESTE_Fonts.FreeMonoBold5pt7b;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt with Ada.Strings.Fixed; package body AdaBase.Driver.Base.Firebird is package ASF renames Ada.Strings.Fixed; --------------- -- execute -- --------------- overriding function execute (driver : Firebird_Driver; sql : String) return AD.AffectedRows is result : AD.AffectedRows := 0; begin return result; -- TODO end execute; ------------------------- -- query_clear_table -- ------------------------- overriding procedure query_clear_table (driver : Firebird_Driver; table : String) is -- Firebird has no "truncate" commands sql : constant String := "DELETE FROM " & table; AR : ACB.AD.AffectedRows; begin AR := driver.execute (sql => sql); end query_clear_table; ------------------------ -- query_drop_table -- ------------------------ overriding procedure query_drop_table (driver : Firebird_Driver; tables : String; when_exists : Boolean := False; cascade : Boolean := False) is sql : AD.textual; AR : AD.AffectedRows; begin if ASF.Index (Source => tables, Pattern => ",", From => 1) /= 0 then driver.log_problem (category => AD.execution, message => SUS ("Multiple tables detected -- Firebird can only drop " & "one table at a time : " & tables)); return; end if; if cascade then driver.log_nominal (category => AD.execution, message => SUS ("Note that requested CASCADE has no effect on Firebird")); end if; case when_exists is when False => sql := SUS ("DROP TABLE " & tables); when True => sql := SUS ("EXECUTE BLOCK AS BEGIN " & "if (exists(select 1 from rdb$relations where " & "rdb$relation_name = '" & tables & "')) then " & "execute statement 'drop table " & tables & ";'; END"); end case; AR := driver.execute (sql => USS (sql)); end query_drop_table; ---------------------- -- last_insert_id -- ---------------------- overriding function last_insert_id (driver : Firebird_Driver) return AD.TraxID is begin return 0; -- TODO end last_insert_id; ---------------------- -- last_sql_state -- ---------------------- overriding function last_sql_state (driver : Firebird_Driver) return AD.TSqlState is begin return AD.stateless; -- TODO end last_sql_state; ----------------------- -- last_error_info -- ----------------------- overriding function last_error_info (driver : Firebird_Driver) return AD.Error_Info is result : AD.Error_Info; begin return result; -- TODO end last_error_info; ------------- -- query -- ------------- overriding function query (driver : Firebird_Driver; sql : String) return AS.Base'Class is result : AS.Base; begin return result; -- TODO end query; ------------------------------------------------------------------------ -- PRIVATE ROUTINES NOT COVERED BY INTERFACES -- ------------------------------------------------------------------------ end AdaBase.Driver.Base.Firebird;
-- { dg-do run } with Init12; use Init12; with Text_IO; use Text_IO; with Dump; procedure P12 is Local_A1 : Arr1; Local_A11 : Arr11; Local_A2 : Arr2; Local_A22 : Arr22; begin Put ("My_A1 :"); Dump (My_A1'Address, Arr1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "My_A1 : 12 00 ab 00 34 00 cd 00 56 00 ef 00.*\n" } Put ("My_A11 :"); Dump (My_A11'Address, Arr11'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "My_A11 : 12 00 ab 00 34 00 cd 00 12 00 ab 00 34 00 cd 00.*\n" } Put ("My_A2 :"); Dump (My_A2'Address, Arr2'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "My_A2 : 00 ab 00 12 00 cd 00 34 00 ef 00 56.*\n" } Put ("My_A22 :"); Dump (My_A22'Address, Arr22'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "My_A22 : 00 ab 00 12 00 cd 00 34 00 ab 00 12 00 cd 00 34.*\n" } Local_A1 := My_A1; Put ("Local_A1 :"); Dump (Local_A1'Address, Arr1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A1 : 12 00 ab 00 34 00 cd 00 56 00 ef 00.*\n" } Local_A11 := My_A11; Put ("Local_A11 :"); Dump (Local_A11'Address, Arr11'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A11 : 12 00 ab 00 34 00 cd 00 12 00 ab 00 34 00 cd 00.*\n" } Local_A2 := My_A2; Put ("Local_A2 :"); Dump (Local_A2'Address, Arr2'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A2 : 00 ab 00 12 00 cd 00 34 00 ef 00 56.*\n" } Local_A22 := My_A22; Put ("Local_A22 :"); Dump (Local_A22'Address, Arr22'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A22 : 00 ab 00 12 00 cd 00 34 00 ab 00 12 00 cd 00 34.*\n" } Local_A1 := (16#AB0012#, 16#CD0034#, 16#EF0056#); Put ("Local_A1 :"); Dump (Local_A1'Address, Arr1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A1 : 12 00 ab 00 34 00 cd 00 56 00 ef 00.*\n" } Local_A11 := (1 => (16#AB0012#, 16#CD0034#), 2 => (16#AB0012#, 16#CD0034#)); Put ("Local_A11 :"); Dump (Local_A11'Address, Arr11'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A11 : 12 00 ab 00 34 00 cd 00 12 00 ab 00 34 00 cd 00.*\n" } Local_A2 := (16#AB0012#, 16#CD0034#, 16#EF0056#); Put ("Local_A2 :"); Dump (Local_A2'Address, Arr2'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A2 : 00 ab 00 12 00 cd 00 34 00 ef 00 56.*\n" } Local_A22 := (1 => (16#AB0012#, 16#CD0034#), 2 => (16#AB0012#, 16#CD0034#)); Put ("Local_A22 :"); Dump (Local_A22'Address, Arr22'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A22 : 00 ab 00 12 00 cd 00 34 00 ab 00 12 00 cd 00 34.*\n" } Local_A1(1) := Local_A2(1); Local_A1(2) := Local_A2(2); Local_A1(3) := Local_A2(3); Put ("Local_A1 :"); Dump (Local_A1'Address, Arr1'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A1 : 12 00 ab 00 34 00 cd 00 56 00 ef 00.*\n" } Local_A11(1,1) := Local_A22(1,1); Local_A11(1,2) := Local_A22(1,2); Local_A11(2,1) := Local_A22(2,1); Local_A11(2,2) := Local_A22(2,2); Put ("Local_A11 :"); Dump (Local_A11'Address, Arr11'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A11 : 12 00 ab 00 34 00 cd 00 12 00 ab 00 34 00 cd 00.*\n" } Local_A2(1) := Local_A1(1); Local_A2(2) := Local_A1(2); Local_A2(3) := Local_A1(3); Put ("Local_A2 :"); Dump (Local_A2'Address, Arr2'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A2 : 00 ab 00 12 00 cd 00 34 00 ef 00 56.*\n" } Local_A22(1,1) := Local_A11(1,1); Local_A22(1,2) := Local_A11(1,2); Local_A22(2,1) := Local_A11(2,1); Local_A22(2,2) := Local_A11(2,2); Put ("Local_A22 :"); Dump (Local_A22'Address, Arr22'Max_Size_In_Storage_Elements); New_Line; -- { dg-output "Local_A22 : 00 ab 00 12 00 cd 00 34 00 ab 00 12 00 cd 00 34.*\n" } end;
-------------------------------------------------------------------------------- -- Copyright (c) 2013, Felix Krause <contact@flyx.org> -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -------------------------------------------------------------------------------- with CL; with CL.Memory.Images.CL_GL; with CL.Platforms; with CL.Contexts.CL_GL; with CL.Command_Queues.CL_GL; with CL.Programs; with CL.Kernels; with CL.Events; with CL.Queueing.CL_GL; with GL.Buffers; with GL.Fixed.Textures; with GL.Fixed.Matrix; with GL.Immediate; with GL.Objects.Textures.Targets; with GL.Pixel_Data; with GL.Toggles; with GL.Types; with Glfw.Display; with Glfw.Events.Keys; with CL_Test.Helpers; with Ada.Text_IO; procedure CL_Test.CL_GL is use GL.Types; package IO renames Ada.Text_IO; GPU_Devices : constant CL.Platforms.Device_Kind := CL.Platforms.Device_Kind'(GPU => True, others => False); My_Platform_Props : constant CL.Platforms.CQ_Property_Vector := CL.Platforms.CQ_Property_Vector'(others => False); Platform : CL.Platforms.Platform; Device : CL.Platforms.Device; Device_List : CL.Platforms.Device_List (1 .. 1); Context : CL.Contexts.CL_GL.Context; Queue : CL.Command_Queues.CL_GL.Queue; Program : CL.Programs.Program; Kernel : CL.Kernels.Kernel; CL_Event : CL.Events.Event; Kernel_File : IO.File_Type; Global_Work_Size : aliased constant CL.Size_List := (1 => 512, 2 => 512); Local_Work_Size : aliased constant CL.Size_List := (1 => 16, 2 => 16); My_Texture : GL.Objects.Textures.Texture; CL_Texture : aliased CL.Memory.Images.CL_GL.Image2D; begin IO.Put_Line ("Initializing GLFW"); Glfw.Init; Glfw.Display.Open (Mode => Glfw.Display.Window); My_Texture.Initialize_Id; GL.Objects.Textures.Targets.Texture_2D.Bind (My_Texture); GL.Fixed.Matrix.Projection.Load_Identity; GL.Fixed.Matrix.Projection.Apply_Orthogonal (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); GL.Toggles.Set (GL.Toggles.Texture_2D, GL.Toggles.Enabled); IO.Put_Line ("Initializing OpenCL"); Platform := CL.Platforms.List (1); Device := Platform.Devices (GPU_Devices) (1); Device_List := (1 => Device); IO.Put_Line ("Using device " & Device.Name & " with maximum work group size" & Device.Max_Work_Group_Size'Img); Context := CL.Contexts.CL_GL.Constructors.Create (Platform, Device_List); Queue := CL.Command_Queues.CL_GL.Constructors.Create (Context, Device, My_Platform_Props); IO.Put_Line ("Loading kernel"); IO.Open (Kernel_File, IO.In_File, "../tests/cl_gl_testkernel.cl"); declare Kernel_Source : aliased constant String := Helpers.Read_File (Kernel_File); begin IO.Close (Kernel_File); Program := CL.Programs.Constructors.Create_From_Source (Context, Kernel_Source); end; IO.Put_Line ("Building Program"); Program.Build (Device_List, "", null); Kernel := CL.Kernels.Constructors.Create (Program, "cl_gl_testkernel"); IO.Put_Line ("Configuring Texture"); GL.Objects.Textures.Targets.Texture_2D.Set_X_Wrapping (GL.Objects.Textures.Repeat); GL.Objects.Textures.Targets.Texture_2D.Set_Y_Wrapping (GL.Objects.Textures.Mirrored_Repeat); GL.Objects.Textures.Targets.Texture_2D.Set_Magnifying_Filter (GL.Objects.Textures.Linear); GL.Objects.Textures.Targets.Texture_2D.Set_Minifying_Filter (GL.Objects.Textures.Linear); GL.Fixed.Textures.Set_Tex_Function (GL.Fixed.Textures.Replace); GL.Objects.Textures.Targets.Texture_2D.Load_Empty_Texture ( Level => 0, Internal_Format => GL.Pixel_Data.RGBA, Width => 512, Height => 512); IO.Put_Line ("Loading Texture to OpenCL"); CL_Texture := CL.Memory.Images.CL_GL.Constructors.Create_Image2D ( Context => Context, Mode => CL.Memory.Read_Write, Texture_Target => GL.Objects.Textures.Targets.Texture_2D, Mipmap_Level => 0, Texture => My_Texture ); Kernel.Set_Kernel_Argument_Object (0, CL_Texture); IO.Put_Line ("Entering main loop"); while not Glfw.Events.Keys.Pressed (Glfw.Events.Keys.Esc) and Glfw.Display.Opened loop GL.Buffers.Clear (GL.Buffers.Buffer_Bits'(Color => True, others => False)); GL.Finish; IO.Put_Line ("Acquire Texture"); CL_Event := CL.Queueing.CL_GL.Acquire_GL_Objects (Queue, (1 => CL_Texture'Unchecked_Access), null); Queue.Finish; IO.Put_Line ("Executing kernel"); CL_Event := CL.Queueing.Execute_Kernel (Queue, Kernel, 2, Global_Work_Size'Access, Local_Work_Size'Access, null); Queue.Finish; IO.Put_Line ("Release Texture"); CL_Event := CL.Queueing.CL_GL.Release_GL_Objects (Queue, (1 => CL_Texture'Unchecked_Access), null); Queue.Finish; IO.Put_Line ("Rendering Texture"); declare use GL.Immediate; use GL.Types.Doubles; Token : Input_Token := Start (Quads); begin Set_Texture_Coordinates (Vector4'( 0.0, 1.0, 0.0, 1.0)); Token.Add_Vertex (Vector4'(-1.0, -1.0, 0.0, 1.0)); Set_Texture_Coordinates (Vector4'( 0.0, 0.0, 0.0, 1.0)); Token.Add_Vertex (Vector4'(-1.0, 1.0, 0.0, 1.0)); Set_Texture_Coordinates (Vector4'( 1.0, 0.0, 0.0, 1.0)); Token.Add_Vertex (Vector4'( 1.0, 1.0, 0.0, 1.0)); Set_Texture_Coordinates (Vector4'( 1.0, 1.0, 0.0, 1.0)); Token.Add_Vertex (Vector4'( 1.0, -1.0, 0.0, 1.0)); end; GL.Finish; Glfw.Display.Swap_Buffers; delay 0.5; Glfw.Events.Poll_Events; end loop; Glfw.Terminate_Glfw; end CL_Test.CL_GL;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Unchecked_Deallocation; package body ABR is procedure Free is new Ada.Unchecked_Deallocation (Object => T_Noeud, Name => T_ABR); procedure Initialiser(Abr: out T_ABR) is begin Abr := Null; end Initialiser; function Est_Vide (Abr : T_Abr) return Boolean is begin return Abr = Null; end; function Taille (Abr : in T_ABR) return Integer is begin if Est_Vide (Abr) then return 0; else return 1 + Taille (Abr.all.Sous_Arbre_Gauche) + Taille (Abr.all.Sous_Arbre_Droit); end if; end Taille; procedure Inserer (Abr : in out T_ABR ; Cle : in Character ; Donnee : in Integer) is begin if (Est_Vide(Abr)) then Abr := New T_Noeud'(Cle, Donnee, Null, Null); elsif (ABR.all.Cle = Cle) then raise Cle_Presente_Exception; elsif (Cle < Abr.all.Cle) then Inserer(Abr.all.Sous_Arbre_Gauche, Cle, Donnee); elsif (Cle > Abr.all.Cle) then Inserer(Abr.all.Sous_Arbre_Droit, Cle, Donnee); end if; end Inserer; procedure Modifier (ABR : in out T_ABR ; Cle : in Character ; Donnee : in Integer) is begin if Est_Vide (ABR) then raise Cle_Absente_Exception; else if ABR.all.Cle = Cle then ABR.all.Donnee := Donnee; elsif ABR.all.Cle < Cle then Modifier (ABR.all.Sous_Arbre_Droit, Cle, Donnee); else Modifier (ABR.all.Sous_Arbre_Gauche, Cle, Donnee); end if; end if; end Modifier; function La_Donnee (Abr : in T_ABR ; Cle : in Character) return Integer is begin if Est_Vide (ABR) then raise Cle_Absente_Exception; else if ABR.all.Cle = Cle then return ABR.all.Donnee; elsif ABR.all.Cle < Cle then return La_Donnee (ABR.all.Sous_Arbre_Droit, Cle); else return La_Donnee (ABR.all.Sous_Arbre_Gauche, Cle); end if; end if; end La_Donnee; procedure Supprimer (Abr : in out T_ABR ; Cle : in Character) is tmp1 ,tmp2 : T_ABR; begin if (Abr = Null) then Null; else if (Cle < Abr.all.Cle) then Supprimer (Abr.all.Sous_Arbre_Gauche, Cle); elsif (Cle > Abr.all.Cle) then Supprimer (Abr.all.Sous_Arbre_Droit, Cle); else if (Abr.all.Sous_Arbre_Gauche = Null) then tmp1 := Abr.all.Sous_Arbre_Droit; Free (Abr); Abr := tmp1; elsif (Abr.all.Sous_Arbre_Droit = Null) then tmp1 := Abr.all.Sous_Arbre_Gauche; Free (Abr); Abr := tmp1; else tmp2 := Abr.all.Sous_Arbre_Droit; while (not Est_Vide (tmp2) and tmp2.all.Sous_Arbre_Gauche /= Null) loop tmp2 := tmp2.all.Sous_Arbre_Gauche; end loop; tmp1 := tmp2; Abr.all.Cle := tmp1.all.Cle; Supprimer (Abr.all.Sous_Arbre_Droit, tmp1.all.Cle); end if; end if; end if; end Supprimer; procedure Vider (Abr : in out T_ABR) is begin if not Est_Vide (ABR) then Vider (ABR.all.Sous_Arbre_Gauche); Vider (ABR.all.Sous_Arbre_Droit); free (ABR); end if; end Vider; procedure Afficher (ABR : in T_Abr) is begin if Est_Vide (ABR) then Afficher( Abr.all.Sous_Arbre_Gauche); Put_Line(Character'Image(ABR.all.Cle) & " : " & Integer'Image(ABR.all.Donnee)); Afficher( ABR.all.Sous_Arbre_Droit); end if; end Afficher; procedure Afficher_Debug (Abr : in T_Abr) is begin if not Est_Vide (ABR) then Put_Line (Character'Image(ABR.all.Cle) & " : " & Integer'Image(ABR.all.Donnee)); Afficher_Debug ( ABR.all.Sous_Arbre_Gauche); Afficher_Debug ( ABR.all.Sous_Arbre_Droit); end if; end Afficher_Debug; end ABR;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. 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. -- -- 3. Neither the name of STMicroelectronics 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. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f7xx_hal_sai.c -- -- @author MCD Application Team -- -- @version V1.0.2 -- -- @date 21-September-2015 -- -- @brief This file provides firmware functions to manage the following -- -- functionalities of the Serial Audio Interface (SAI) -- -- peripheral: -- -- + Initialization/de-initialization functions -- -- + I/O operation functions -- -- + Peripheral Control functions -- -- + Peripheral State functions -- -- -- -- COPYRIGHT(c) 2015 STMicroelectronics -- ------------------------------------------------------------------------------ with Ada.Real_Time; use Ada.Real_Time; with STM32_SVD; use STM32_SVD; with STM32_SVD.RCC; use STM32_SVD.RCC; package body STM32.SAI is function Get_Block (Periph : SAI_Controller; Block : SAI_Block) return Block_Registers_Access; --------------- -- Get_Block -- --------------- function Get_Block (Periph : SAI_Controller; Block : SAI_Block) return Block_Registers_Access is BlockA : aliased Block_Registers with Volatile, Import, Address => Periph.ACR1'Address; BlockB : aliased Block_Registers with Volatile, Import, Address => Periph.BCR1'Address; begin case Block is when Block_A => return BlockA'Unchecked_Access; when Block_B => return BlockB'Unchecked_Access; end case; end Get_Block; ------------------ -- Deinitialize -- ------------------ procedure Deinitialize (This : SAI_Controller; Block : SAI_Block) is Block_Regs : constant Block_Registers_Access := Get_Block (This, Block); Start : Time; begin -- Disable SAI Block_Regs.CR1.SAIAEN := False; Start := Clock; while Block_Regs.CR1.SAIAEN loop if Start + Seconds (1) < Clock then raise Constraint_Error with "Cannot reset the SAI peripheral"; end if; end loop; -- Reset the SAI block interrupts Block_Regs.IM := (others => <>); Block_Regs.CLRFR := (Reserved_3_3 => 0, Reserved_7_31 => 0, others => True); -- Flush the FIFO Block_Regs.CR2.FFLUS := True; end Deinitialize; ------------- -- Enabled -- ------------- function Enabled (This : SAI_Controller; Block : SAI_Block) return Boolean is Block_Regs : constant Block_Registers_Access := Get_Block (This, Block); begin return Block_Regs.CR1.SAIAEN; end Enabled; ------------ -- Enable -- ------------ procedure Enable (This : SAI_Controller; Block : SAI_Block) is Block_Regs : constant Block_Registers_Access := Get_Block (This, Block); begin Block_Regs.CR1.SAIAEN := True; end Enable; ------------- -- Disable -- ------------- procedure Disable (This : SAI_Controller; Block : SAI_Block) is Block_Regs : constant Block_Registers_Access := Get_Block (This, Block); begin Block_Regs.CR1.SAIAEN := False; end Disable; ---------------- -- Enable_DMA -- ---------------- procedure Enable_DMA (This : SAI_Controller; Block : SAI_Block) is Block_Regs : constant Block_Registers_Access := Get_Block (This, Block); begin Block_Regs.CR1.DMAEN := True; end Enable_DMA; --------------- -- DMA_Pause -- --------------- procedure DMA_Pause (This : SAI_Controller; Block : SAI_Block) is Block_Regs : constant Block_Registers_Access := Get_Block (This, Block); begin Block_Regs.CR1.DMAEN := False; end DMA_Pause; ---------------- -- DMA_Resume -- ---------------- procedure DMA_Resume (This : SAI_Controller; Block : SAI_Block) is Block_Regs : constant Block_Registers_Access := Get_Block (This, Block); begin Block_Regs.CR1.DMAEN := True; if not Block_Regs.CR1.SAIAEN then Enable (This, Block); end if; end DMA_Resume; -------------- -- DMA_Stop -- -------------- procedure DMA_Stop (This : SAI_Controller; Block : SAI_Block) is Block_Regs : constant Block_Registers_Access := Get_Block (This, Block); begin Block_Regs.CR1.DMAEN := False; Disable (This, Block); end DMA_Stop; --------------------------- -- Configure_Audio_Block -- --------------------------- procedure Configure_Audio_Block (This : SAI_Controller; Block : SAI_Block; Frequency : SAI_Audio_Frequency; Stereo_Mode : SAI_Mono_Stereo_Mode; Mode : SAI_Audio_Mode; MCD_Enabled : Boolean; Protocol : SAI_Protocol_Configuration; Data_Size : SAI_Data_Size; Endianness : SAI_Endianness; Clock_Strobing : SAI_Clock_Strobing_Edge; Synchronization : SAI_Synchronization; Output_Drive : SAI_Output_Drive; FIFO_Threshold : SAI_FIFO_Threshold; Tristate_Mgt : SAI_Tristate_Management := SD_Line_Driven; Companding_Mode : SAI_Companding_Mode := No_Companding) is Block_Reg : constant Block_Registers_Access := Get_Block (This, Block); Freq : UInt32; Tmp_Clock : UInt32; Mckdiv : UInt32; begin Deinitialize (This, Block); -- Configure Master Clock using the following formula : -- MCLK_x = SAI_CK_x / (MCKDIV[3:0] * 2) with MCLK_x = 256 * FS -- FS = SAI_CK_x / (MCKDIV[3:0] * 2) * 256 -- MCKDIV[3:0] = SAI_CK_x / FS * 512 Freq := STM32.Device.Get_Clock_Frequency (This); -- Calculate *10 to keep some precision Tmp_Clock := Freq * 10 / (Frequency * 512); Mckdiv := Tmp_Clock / 10; -- Round the result if needed if (Tmp_Clock mod 10) > 8 then Mckdiv := Mckdiv + 1; end if; Block_Reg.CR1 := (MODE => SAI_Audio_Mode'Enum_Rep (Mode), PRTCFG => SAI_Protocol_Configuration'Enum_Rep (Protocol), DS => SAI_Data_Size'Enum_Rep (Data_Size), LSBFIRST => Endianness = Data_LSB_First, CKSTR => Clock_Strobing = Clock_Strobing_Rising_Edge, SYNCEN => SAI_Synchronization'Enum_Rep (Synchronization), MONO => Stereo_Mode = Mono, OutDri => Output_Drive = Drive_Immediate, SAIAEN => False, DMAEN => False, NODIV => not MCD_Enabled, MCKDIV => UInt6 (Mckdiv), others => <>); Block_Reg.CR2.FTH := SAI_FIFO_Threshold'Enum_Rep (FIFO_Threshold); Block_Reg.CR2.FFLUS := False; Block_Reg.CR2.TRIS := Tristate_Mgt = SD_Line_Released; Block_Reg.CR2.COMP := SAI_Companding_Mode'Enum_Rep (Companding_Mode); end Configure_Audio_Block; --------------------------- -- Configure_Block_Frame -- --------------------------- procedure Configure_Block_Frame (This : SAI_Controller; Block : SAI_Block; Frame_Length : UInt8; Frame_Active : UInt7; Frame_Sync : SAI_Frame_Synchronization; FS_Polarity : SAI_Frame_Sync_Polarity; FS_Offset : SAI_Frame_Sync_Offset) is Block_Reg : constant Block_Registers_Access := Get_Block (This, Block); begin Block_Reg.FRCR := (FRL => Frame_Length - 1, FSALL => Frame_Active - 1, FSDEF => Frame_Sync = FS_Frame_And_Channel_Identification, FSPOL => FS_Polarity = FS_Active_High, FSOFF => FS_Offset = Before_First_Bit, others => <>); end Configure_Block_Frame; -------------------------- -- Configure_Block_Slot -- -------------------------- procedure Configure_Block_Slot (This : SAI_Controller; Block : SAI_Block; First_Bit_Offset : UInt5; Slot_Size : SAI_Slot_Size; Number_Of_Slots : Slots_Number; Enabled_Slots : SAI_Slots) is Block_Reg : constant Block_Registers_Access := Get_Block (This, Block); begin Block_Reg.SLOTR := (FBOFF => First_Bit_Offset, SLOTSZ => SAI_Slot_Size'Enum_Rep (Slot_Size), NBSLOT => UInt4 (Number_Of_Slots - 1), SLOTEN => UInt16 (Enabled_Slots), others => <>); end Configure_Block_Slot; end STM32.SAI;
-- Implantation du module Piles. with Ada.Unchecked_Deallocation; with Ada.Text_IO; use Ada.Text_IO; --// Ce module est nécessaire parce qu'on a ajouté le SP Afficher. package body Piles is procedure Free is new Ada.Unchecked_Deallocation (T_Cellule, T_Pile); procedure Initialiser (Pile : out T_Pile) is begin Pile := Null; end Initialiser; function Est_Vide (Pile : in T_Pile) return Boolean is begin return Pile = Null; end Est_Vide; function Sommet (Pile : in T_Pile) return T_Element is begin return Pile.all.Element; end Sommet; procedure Empiler (Pile : in out T_Pile; Element : in T_Element) is Nouvelle_Cellule: T_Pile; begin -- Créer une nouvelle cellule (allcoation puis initialisation) Nouvelle_Cellule := new T_Cellule; Nouvelle_Cellule.all.Element := Element; Nouvelle_Cellule.all.Suivant := Pile; -- Changer Pile (elle pointe sur la nouvelle cellule) Pile := Nouvelle_Cellule; end Empiler; procedure Depiler (Pile : in out T_Pile) is A_Detruire : T_Pile; begin A_Detruire := Pile; Pile := Pile.all.Suivant; Free (A_Detruire); end Depiler; procedure Detruire (P: in out T_Pile) is begin if P /= Null then Detruire (P.all.Suivant); Free (P); else Null; end if; end Detruire; procedure Afficher (Pile : in T_Pile) is -- Afficher les éléments de la pile. Le premier affiché est le fond de -- pile, le dernier le sommet, ils sont séparés par des virgules. procedure Afficher_Elements (Pile : in T_Pile) is begin if Pile = Null then Null; elsif Pile.all.Suivant = Null then Put (" "); Afficher_Element (Pile.all.Element); else Afficher_Elements (Pile.all.Suivant); Put (", "); Afficher_Element (Pile.all.Element); end if; end Afficher_Elements; begin Put ('['); Afficher_Elements (Pile); Put (" >"); end Afficher; end Piles;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ C H 1 0 -- -- -- -- 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. -- -- -- -- 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 Debug; use Debug; with Einfo; use Einfo; with Errout; use Errout; with Exp_Util; use Exp_Util; with Fname; use Fname; with Fname.UF; use Fname.UF; with Freeze; use Freeze; with Impunit; use Impunit; with Inline; use Inline; with Lib; use Lib; with Lib.Load; use Lib.Load; with Lib.Xref; use Lib.Xref; with Namet; use Namet; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Output; use Output; with Restrict; use Restrict; with Sem; use Sem; with Sem_Ch6; use Sem_Ch6; with Sem_Ch7; use Sem_Ch7; with Sem_Ch8; use Sem_Ch8; with Sem_Dist; use Sem_Dist; with Sem_Prag; use Sem_Prag; with Sem_Util; use Sem_Util; with Sem_Warn; use Sem_Warn; with Stand; use Stand; with Sinfo; use Sinfo; with Sinfo.CN; use Sinfo.CN; with Sinput; use Sinput; with Snames; use Snames; with Style; use Style; with Tbuild; use Tbuild; with Ttypes; use Ttypes; with Uname; use Uname; package body Sem_Ch10 is ----------------------- -- Local Subprograms -- ----------------------- procedure Analyze_Context (N : Node_Id); -- Analyzes items in the context clause of compilation unit procedure Check_With_Type_Clauses (N : Node_Id); -- If N is a body, verify that any with_type clauses on the spec, or -- on the spec of any parent, have a matching with_clause. procedure Check_Private_Child_Unit (N : Node_Id); -- If a with_clause mentions a private child unit, the compilation -- unit must be a member of the same family, as described in 10.1.2 (8). procedure Check_Stub_Level (N : Node_Id); -- Verify that a stub is declared immediately within a compilation unit, -- and not in an inner frame. procedure Expand_With_Clause (Nam : Node_Id; N : Node_Id); -- When a child unit appears in a context clause, the implicit withs on -- parents are made explicit, and with clauses are inserted in the context -- clause before the one for the child. If a parent in the with_clause -- is a renaming, the implicit with_clause is on the renaming whose name -- is mentioned in the with_clause, and not on the package it renames. -- N is the compilation unit whose list of context items receives the -- implicit with_clauses. procedure Implicit_With_On_Parent (Child_Unit : Node_Id; N : Node_Id); -- If the main unit is a child unit, implicit withs are also added for -- all its ancestors. procedure Install_Context_Clauses (N : Node_Id); -- Subsidiary to previous one. Process only with_ and use_clauses for -- current unit and its library unit if any. procedure Install_Withed_Unit (With_Clause : Node_Id); -- If the unit is not a child unit, make unit immediately visible. -- The caller ensures that the unit is not already currently installed. procedure Install_Parents (Lib_Unit : Node_Id; Is_Private : Boolean); -- This procedure establishes the context for the compilation of a child -- unit. If Lib_Unit is a child library spec then the context of the parent -- is installed, and the parent itself made immediately visible, so that -- the child unit is processed in the declarative region of the parent. -- Install_Parents makes a recursive call to itself to ensure that all -- parents are loaded in the nested case. If Lib_Unit is a library body, -- the only effect of Install_Parents is to install the private decls of -- the parents, because the visible parent declarations will have been -- installed as part of the context of the corresponding spec. procedure Install_Siblings (U_Name : Entity_Id; N : Node_Id); -- In the compilation of a child unit, a child of any of the ancestor -- units is directly visible if it is visible, because the parent is in -- an enclosing scope. Iterate over context to find child units of U_Name -- or of some ancestor of it. function Is_Child_Spec (Lib_Unit : Node_Id) return Boolean; -- Lib_Unit is a library unit which may be a spec or a body. Is_Child_Spec -- returns True if Lib_Unit is a library spec which is a child spec, i.e. -- a library spec that has a parent. If the call to Is_Child_Spec returns -- True, then Parent_Spec (Lib_Unit) is non-Empty and points to the -- compilation unit for the parent spec. -- -- Lib_Unit can also be a subprogram body that acts as its own spec. If -- the Parent_Spec is non-empty, this is also a child unit. procedure Remove_With_Type_Clause (Name : Node_Id); -- Remove imported type and its enclosing package from visibility, and -- remove attributes of imported type so they don't interfere with its -- analysis (should it appear otherwise in the context). procedure Remove_Context_Clauses (N : Node_Id); -- Subsidiary of previous one. Remove use_ and with_clauses. procedure Remove_Parents (Lib_Unit : Node_Id); -- Remove_Parents checks if Lib_Unit is a child spec. If so then the parent -- contexts established by the corresponding call to Install_Parents are -- removed. Remove_Parents contains a recursive call to itself to ensure -- that all parents are removed in the nested case. procedure Remove_Unit_From_Visibility (Unit_Name : Entity_Id); -- Reset all visibility flags on unit after compiling it, either as a -- main unit or as a unit in the context. procedure Analyze_Proper_Body (N : Node_Id; Nam : Entity_Id); -- Common processing for all stubs (subprograms, tasks, packages, and -- protected cases). N is the stub to be analyzed. Once the subunit -- name is established, load and analyze. Nam is the non-overloadable -- entity for which the proper body provides a completion. Subprogram -- stubs are handled differently because they can be declarations. ------------------------------ -- Analyze_Compilation_Unit -- ------------------------------ procedure Analyze_Compilation_Unit (N : Node_Id) is Unit_Node : constant Node_Id := Unit (N); Lib_Unit : Node_Id := Library_Unit (N); Spec_Id : Node_Id; Main_Cunit : constant Node_Id := Cunit (Main_Unit); Par_Spec_Name : Unit_Name_Type; Unum : Unit_Number_Type; procedure Generate_Parent_References (N : Node_Id; P_Id : Entity_Id); -- Generate cross-reference information for the parents of child units. -- N is a defining_program_unit_name, and P_Id is the immediate parent. -------------------------------- -- Generate_Parent_References -- -------------------------------- procedure Generate_Parent_References (N : Node_Id; P_Id : Entity_Id) is Pref : Node_Id; P_Name : Entity_Id := P_Id; begin Pref := Name (Parent (Defining_Entity (N))); if Nkind (Pref) = N_Expanded_Name then -- Done already, if the unit has been compiled indirectly as -- part of the closure of its context because of inlining. return; end if; while Nkind (Pref) = N_Selected_Component loop Change_Selected_Component_To_Expanded_Name (Pref); Set_Entity (Pref, P_Name); Set_Etype (Pref, Etype (P_Name)); Generate_Reference (P_Name, Pref, 'r'); Pref := Prefix (Pref); P_Name := Scope (P_Name); end loop; -- The guard here on P_Name is to handle the error condition where -- the parent unit is missing because the file was not found. if Present (P_Name) then Set_Entity (Pref, P_Name); Set_Etype (Pref, Etype (P_Name)); Generate_Reference (P_Name, Pref, 'r'); Style.Check_Identifier (Pref, P_Name); end if; end Generate_Parent_References; -- Start of processing for Analyze_Compilation_Unit begin Process_Compilation_Unit_Pragmas (N); -- If the unit is a subunit whose parent has not been analyzed (which -- indicates that the main unit is a subunit, either the current one or -- one of its descendents) then the subunit is compiled as part of the -- analysis of the parent, which we proceed to do. Basically this gets -- handled from the top down and we don't want to do anything at this -- level (i.e. this subunit will be handled on the way down from the -- parent), so at this level we immediately return. If the subunit -- ends up not analyzed, it means that the parent did not contain a -- stub for it, or that there errors were dectected in some ancestor. if Nkind (Unit_Node) = N_Subunit and then not Analyzed (Lib_Unit) then Semantics (Lib_Unit); if not Analyzed (Proper_Body (Unit_Node)) then if Errors_Detected > 0 then Error_Msg_N ("subunit not analyzed (errors in parent unit)", N); else Error_Msg_N ("missing stub for subunit", N); end if; end if; return; end if; -- Analyze context (this will call Sem recursively for with'ed units) Analyze_Context (N); -- If the unit is a package body, the spec is already loaded and must -- be analyzed first, before we analyze the body. if Nkind (Unit_Node) = N_Package_Body then -- If no Lib_Unit, then there was a serious previous error, so -- just ignore the entire analysis effort if No (Lib_Unit) then return; else Semantics (Lib_Unit); Check_Unused_Withs (Get_Cunit_Unit_Number (Lib_Unit)); -- Verify that the library unit is a package declaration. if Nkind (Unit (Lib_Unit)) /= N_Package_Declaration and then Nkind (Unit (Lib_Unit)) /= N_Generic_Package_Declaration then Error_Msg_N ("no legal package declaration for package body", N); return; -- Otherwise, the entity in the declaration is visible. Update -- the version to reflect dependence of this body on the spec. else Spec_Id := Defining_Entity (Unit (Lib_Unit)); Set_Is_Immediately_Visible (Spec_Id, True); Version_Update (N, Lib_Unit); if Nkind (Defining_Unit_Name (Unit_Node)) = N_Defining_Program_Unit_Name then Generate_Parent_References (Unit_Node, Scope (Spec_Id)); end if; end if; end if; -- If the unit is a subprogram body, then we similarly need to analyze -- its spec. However, things are a little simpler in this case, because -- here, this analysis is done only for error checking and consistency -- purposes, so there's nothing else to be done. elsif Nkind (Unit_Node) = N_Subprogram_Body then if Acts_As_Spec (N) then -- If the subprogram body is a child unit, we must create a -- declaration for it, in order to properly load the parent(s). -- After this, the original unit does not acts as a spec, because -- there is an explicit one. If this unit appears in a context -- clause, then an implicit with on the parent will be added when -- installing the context. If this is the main unit, there is no -- Unit_Table entry for the declaration, (It has the unit number -- of the main unit) and code generation is unaffected. Unum := Get_Cunit_Unit_Number (N); Par_Spec_Name := Get_Parent_Spec_Name (Unit_Name (Unum)); if Par_Spec_Name /= No_Name then Unum := Load_Unit (Load_Name => Par_Spec_Name, Required => True, Subunit => False, Error_Node => N); if Unum /= No_Unit then -- Build subprogram declaration and attach parent unit to it -- This subprogram declaration does not come from source! declare Loc : constant Source_Ptr := Sloc (N); SCS : constant Boolean := Get_Comes_From_Source_Default; begin Set_Comes_From_Source_Default (False); Lib_Unit := Make_Compilation_Unit (Loc, Context_Items => New_Copy_List (Context_Items (N)), Unit => Make_Subprogram_Declaration (Sloc (N), Specification => Copy_Separate_Tree (Specification (Unit_Node))), Aux_Decls_Node => Make_Compilation_Unit_Aux (Loc)); Set_Library_Unit (N, Lib_Unit); Set_Parent_Spec (Unit (Lib_Unit), Cunit (Unum)); Semantics (Lib_Unit); Set_Acts_As_Spec (N, False); Set_Comes_From_Source_Default (SCS); end; end if; end if; -- Here for subprogram with separate declaration else Semantics (Lib_Unit); Check_Unused_Withs (Get_Cunit_Unit_Number (Lib_Unit)); Version_Update (N, Lib_Unit); end if; if Nkind (Defining_Unit_Name (Specification (Unit_Node))) = N_Defining_Program_Unit_Name then Generate_Parent_References ( Specification (Unit_Node), Scope (Defining_Entity (Unit (Lib_Unit)))); end if; end if; -- If it is a child unit, the parent must be elaborated first -- and we update version, since we are dependent on our parent. if Is_Child_Spec (Unit_Node) then -- The analysis of the parent is done with style checks off declare Save_Style_Check : constant Boolean := Opt.Style_Check; Save_C_Restrict : constant Save_Compilation_Unit_Restrictions := Compilation_Unit_Restrictions_Save; begin if not GNAT_Mode then Style_Check := False; end if; Semantics (Parent_Spec (Unit_Node)); Version_Update (N, Parent_Spec (Unit_Node)); Style_Check := Save_Style_Check; Compilation_Unit_Restrictions_Restore (Save_C_Restrict); end; end if; -- With the analysis done, install the context. Note that we can't -- install the context from the with clauses as we analyze them, -- because each with clause must be analyzed in a clean visibility -- context, so we have to wait and install them all at once. Install_Context (N); if Is_Child_Spec (Unit_Node) then -- Set the entities of all parents in the program_unit_name. Generate_Parent_References ( Unit_Node, Defining_Entity (Unit (Parent_Spec (Unit_Node)))); end if; -- All components of the context: with-clauses, library unit, ancestors -- if any, (and their context) are analyzed and installed. Now analyze -- the unit itself, which is either a package, subprogram spec or body. Analyze (Unit_Node); -- The above call might have made Unit_Node an N_Subprogram_Body -- from something else, so propagate any Acts_As_Spec flag. if Nkind (Unit_Node) = N_Subprogram_Body and then Acts_As_Spec (Unit_Node) then Set_Acts_As_Spec (N); end if; -- Treat compilation unit pragmas that appear after the library unit if Present (Pragmas_After (Aux_Decls_Node (N))) then declare Prag_Node : Node_Id := First (Pragmas_After (Aux_Decls_Node (N))); begin while Present (Prag_Node) loop Analyze (Prag_Node); Next (Prag_Node); end loop; end; end if; -- Generate distribution stub files if requested and no error if N = Main_Cunit and then (Distribution_Stub_Mode = Generate_Receiver_Stub_Body or else Distribution_Stub_Mode = Generate_Caller_Stub_Body) and then not Fatal_Error (Main_Unit) then if Is_RCI_Pkg_Spec_Or_Body (N) then -- Regular RCI package Add_Stub_Constructs (N); elsif (Nkind (Unit_Node) = N_Package_Declaration and then Is_Shared_Passive (Defining_Entity (Specification (Unit_Node)))) or else (Nkind (Unit_Node) = N_Package_Body and then Is_Shared_Passive (Corresponding_Spec (Unit_Node))) then -- Shared passive package Add_Stub_Constructs (N); elsif Nkind (Unit_Node) = N_Package_Instantiation and then Is_Remote_Call_Interface (Defining_Entity (Specification (Instance_Spec (Unit_Node)))) then -- Instantiation of a RCI generic package Add_Stub_Constructs (N); end if; -- Reanalyze the unit with the new constructs Analyze (Unit_Node); end if; if Nkind (Unit_Node) = N_Package_Declaration or else Nkind (Unit_Node) in N_Generic_Declaration or else Nkind (Unit_Node) = N_Package_Renaming_Declaration or else Nkind (Unit_Node) = N_Subprogram_Declaration then Remove_Unit_From_Visibility (Defining_Entity (Unit_Node)); elsif Nkind (Unit_Node) = N_Package_Body or else (Nkind (Unit_Node) = N_Subprogram_Body and then not Acts_As_Spec (Unit_Node)) then -- Bodies that are not the main unit are compiled if they -- are generic or contain generic or inlined units. Their -- analysis brings in the context of the corresponding spec -- (unit declaration) which must be removed as well, to -- return the compilation environment to its proper state. Remove_Context (Lib_Unit); Set_Is_Immediately_Visible (Defining_Entity (Unit (Lib_Unit)), False); end if; -- Last step is to deinstall the context we just installed -- as well as the unit just compiled. Remove_Context (N); -- If this is the main unit and we are generating code, we must -- check that all generic units in the context have a body if they -- need it, even if they have not been instantiated. In the absence -- of .ali files for generic units, we must force the load of the body, -- just to produce the proper error if the body is absent. We skip this -- verification if the main unit itself is generic. if Get_Cunit_Unit_Number (N) = Main_Unit and then Operating_Mode = Generate_Code and then Expander_Active then -- Indicate that the main unit is now analyzed, to catch possible -- circularities between it and generic bodies. Remove main unit -- from visibility. This might seem superfluous, but the main unit -- must not be visible in the generic body expansions that follow. Set_Analyzed (N, True); Set_Is_Immediately_Visible (Cunit_Entity (Main_Unit), False); declare Item : Node_Id; Nam : Entity_Id; Un : Unit_Number_Type; Save_Style_Check : constant Boolean := Opt.Style_Check; Save_C_Restrict : constant Save_Compilation_Unit_Restrictions := Compilation_Unit_Restrictions_Save; begin Item := First (Context_Items (N)); while Present (Item) loop if Nkind (Item) = N_With_Clause and then not Implicit_With (Item) then Nam := Entity (Name (Item)); if (Ekind (Nam) = E_Generic_Procedure and then not Is_Intrinsic_Subprogram (Nam)) or else (Ekind (Nam) = E_Generic_Function and then not Is_Intrinsic_Subprogram (Nam)) or else (Ekind (Nam) = E_Generic_Package and then Unit_Requires_Body (Nam)) then Opt.Style_Check := False; if Present (Renamed_Object (Nam)) then Un := Load_Unit (Load_Name => Get_Body_Name (Get_Unit_Name (Unit_Declaration_Node (Renamed_Object (Nam)))), Required => False, Subunit => False, Error_Node => N, Renamings => True); else Un := Load_Unit (Load_Name => Get_Body_Name (Get_Unit_Name (Item)), Required => False, Subunit => False, Error_Node => N, Renamings => True); end if; if Un = No_Unit then Error_Msg_NE ("body of generic unit& not found", Item, Nam); exit; elsif not Analyzed (Cunit (Un)) and then Un /= Main_Unit then Opt.Style_Check := False; Semantics (Cunit (Un)); end if; end if; end if; Next (Item); end loop; Style_Check := Save_Style_Check; Compilation_Unit_Restrictions_Restore (Save_C_Restrict); end; end if; -- Deal with creating elaboration Boolean if needed. We create an -- elaboration boolean only for units that come from source since -- units manufactured by the compiler never need elab checks. if Comes_From_Source (N) and then (Nkind (Unit (N)) = N_Package_Declaration or else Nkind (Unit (N)) = N_Generic_Package_Declaration or else Nkind (Unit (N)) = N_Subprogram_Declaration or else Nkind (Unit (N)) = N_Generic_Subprogram_Declaration) then declare Loc : constant Source_Ptr := Sloc (N); Unum : constant Unit_Number_Type := Get_Source_Unit (Loc); begin Spec_Id := Defining_Entity (Unit (N)); Generate_Definition (Spec_Id); -- See if an elaboration entity is required for possible -- access before elaboration checking. Note that we must -- allow for this even if -gnatE is not set, since a client -- may be compiled in -gnatE mode and reference the entity. -- Case of units which do not require elaboration checks if -- Pure units do not need checks Is_Pure (Spec_Id) -- Preelaborated units do not need checks or else Is_Preelaborated (Spec_Id) -- No checks needed if pagma Elaborate_Body present or else Has_Pragma_Elaborate_Body (Spec_Id) -- No checks needed if unit does not require a body or else not Unit_Requires_Body (Spec_Id) -- No checks needed for predefined files or else Is_Predefined_File_Name (Unit_File_Name (Unum)) -- No checks required if no separate spec or else Acts_As_Spec (N) then -- This is a case where we only need the entity for -- checking to prevent multiple elaboration checks. Set_Elaboration_Entity_Required (Spec_Id, False); -- Case of elaboration entity is required for access before -- elaboration checking (so certainly we must build it!) else Set_Elaboration_Entity_Required (Spec_Id, True); end if; Build_Elaboration_Entity (N, Spec_Id); end; end if; -- Finally, freeze the compilation unit entity. This for sure is needed -- because of some warnings that can be output (see Freeze_Subprogram), -- but may in general be required. If freezing actions result, place -- them in the compilation unit actions list, and analyze them. declare Loc : constant Source_Ptr := Sloc (N); L : constant List_Id := Freeze_Entity (Cunit_Entity (Current_Sem_Unit), Loc); begin while Is_Non_Empty_List (L) loop Insert_Library_Level_Action (Remove_Head (L)); end loop; end; Set_Analyzed (N); if Nkind (Unit_Node) = N_Package_Declaration and then Get_Cunit_Unit_Number (N) /= Main_Unit and then Front_End_Inlining and then Expander_Active then Check_Body_For_Inlining (N, Defining_Entity (Unit_Node)); end if; end Analyze_Compilation_Unit; --------------------- -- Analyze_Context -- --------------------- procedure Analyze_Context (N : Node_Id) is Item : Node_Id; begin -- Loop through context items Item := First (Context_Items (N)); while Present (Item) loop -- For with clause, analyze the with clause, and then update -- the version, since we are dependent on a unit that we with. if Nkind (Item) = N_With_Clause then -- Skip analyzing with clause if no unit, nothing to do (this -- happens for a with that references a non-existent unit) if Present (Library_Unit (Item)) then Analyze (Item); end if; if not Implicit_With (Item) then Version_Update (N, Library_Unit (Item)); end if; -- But skip use clauses at this stage, since we don't want to do -- any installing of potentially use visible entities until we -- we actually install the complete context (in Install_Context). -- Otherwise things can get installed in the wrong context. -- Similarly, pragmas are analyzed in Install_Context, after all -- the implicit with's on parent units are generated. else null; end if; Next (Item); end loop; end Analyze_Context; ------------------------------- -- Analyze_Package_Body_Stub -- ------------------------------- procedure Analyze_Package_Body_Stub (N : Node_Id) is Id : constant Entity_Id := Defining_Identifier (N); Nam : Entity_Id; begin -- The package declaration must be in the current declarative part. Check_Stub_Level (N); Nam := Current_Entity_In_Scope (Id); if No (Nam) or else not Is_Package (Nam) then Error_Msg_N ("missing specification for package stub", N); elsif Has_Completion (Nam) and then Present (Corresponding_Body (Unit_Declaration_Node (Nam))) then Error_Msg_N ("duplicate or redundant stub for package", N); else -- Indicate that the body of the package exists. If we are doing -- only semantic analysis, the stub stands for the body. If we are -- generating code, the existence of the body will be confirmed -- when we load the proper body. Set_Has_Completion (Nam); Set_Scope (Defining_Entity (N), Current_Scope); Analyze_Proper_Body (N, Nam); end if; end Analyze_Package_Body_Stub; ------------------------- -- Analyze_Proper_Body -- ------------------------- procedure Analyze_Proper_Body (N : Node_Id; Nam : Entity_Id) is Subunit_Name : constant Unit_Name_Type := Get_Unit_Name (N); Unum : Unit_Number_Type; Subunit_Not_Found : Boolean := False; procedure Optional_Subunit; -- This procedure is called when the main unit is a stub, or when we -- are not generating code. In such a case, we analyze the subunit if -- present, which is user-friendly and in fact required for ASIS, but -- we don't complain if the subunit is missing. ---------------------- -- Optional_Subunit -- ---------------------- procedure Optional_Subunit is Comp_Unit : Node_Id; begin -- Try to load subunit, but ignore any errors that occur during -- the loading of the subunit, by using the special feature in -- Errout to ignore all errors. Note that Fatal_Error will still -- be set, so we will be able to check for this case below. Ignore_Errors_Enable := Ignore_Errors_Enable + 1; Unum := Load_Unit (Load_Name => Subunit_Name, Required => False, Subunit => True, Error_Node => N); Ignore_Errors_Enable := Ignore_Errors_Enable - 1; -- All done if we successfully loaded the subunit if Unum /= No_Unit and then not Fatal_Error (Unum) then Comp_Unit := Cunit (Unum); Set_Corresponding_Stub (Unit (Comp_Unit), N); Analyze_Subunit (Comp_Unit); Set_Library_Unit (N, Comp_Unit); elsif Unum = No_Unit and then Present (Nam) then if Is_Protected_Type (Nam) then Set_Corresponding_Body (Parent (Nam), Defining_Identifier (N)); else Set_Corresponding_Body ( Unit_Declaration_Node (Nam), Defining_Identifier (N)); end if; end if; end Optional_Subunit; -- Start of processing for Analyze_Proper_Body begin -- If the subunit is already loaded, it means that the main unit -- is a subunit, and that the current unit is one of its parents -- which was being analyzed to provide the needed context for the -- analysis of the subunit. In this case we analyze the subunit and -- continue with the parent, without looking a subsequent subunits. if Is_Loaded (Subunit_Name) then -- If the proper body is already linked to the stub node, -- the stub is in a generic unit and just needs analyzing. if Present (Library_Unit (N)) then Set_Corresponding_Stub (Unit (Library_Unit (N)), N); Analyze_Subunit (Library_Unit (N)); -- Otherwise we must load the subunit and link to it else -- Load the subunit, this must work, since we originally -- loaded the subunit earlier on. So this will not really -- load it, just give access to it. Unum := Load_Unit (Load_Name => Subunit_Name, Required => True, Subunit => False, Error_Node => N); -- And analyze the subunit in the parent context (note that we -- do not call Semantics, since that would remove the parent -- context). Because of this, we have to manually reset the -- compiler state to Analyzing since it got destroyed by Load. if Unum /= No_Unit then Compiler_State := Analyzing; Set_Corresponding_Stub (Unit (Cunit (Unum)), N); Analyze_Subunit (Cunit (Unum)); Set_Library_Unit (N, Cunit (Unum)); end if; end if; -- If the main unit is a subunit, then we are just performing semantic -- analysis on that subunit, and any other subunits of any parent unit -- should be ignored, except that if we are building trees for ASIS -- usage we want to annotate the stub properly. elsif Nkind (Unit (Cunit (Main_Unit))) = N_Subunit and then Subunit_Name /= Unit_Name (Main_Unit) then if Tree_Output then Optional_Subunit; end if; -- But before we return, set the flag for unloaded subunits. This -- will suppress junk warnings of variables in the same declarative -- part (or a higher level one) that are in danger of looking unused -- when in fact there might be a declaration in the subunit that we -- do not intend to load. Unloaded_Subunits := True; return; -- If the subunit is not already loaded, and we are generating code, -- then this is the case where compilation started from the parent, -- and we are generating code for an entire subunit tree. In that -- case we definitely need to load the subunit. -- In order to continue the analysis with the rest of the parent, -- and other subunits, we load the unit without requiring its -- presence, and emit a warning if not found, rather than terminating -- the compilation abruptly, as for other missing file problems. elsif Operating_Mode = Generate_Code then -- If the proper body is already linked to the stub node, -- the stub is in a generic unit and just needs analyzing. -- We update the version. Although we are not technically -- semantically dependent on the subunit, given our approach -- of macro substitution of subunits, it makes sense to -- include it in the version identification. if Present (Library_Unit (N)) then Set_Corresponding_Stub (Unit (Library_Unit (N)), N); Analyze_Subunit (Library_Unit (N)); Version_Update (Cunit (Main_Unit), Library_Unit (N)); -- Otherwise we must load the subunit and link to it else Unum := Load_Unit (Load_Name => Subunit_Name, Required => False, Subunit => True, Error_Node => N); if Operating_Mode = Generate_Code and then Unum = No_Unit then Error_Msg_Name_1 := Subunit_Name; Error_Msg_Name_2 := Get_File_Name (Subunit_Name, Subunit => True); Error_Msg_N ("subunit% in file{ not found!?", N); Subunits_Missing := True; Subunit_Not_Found := True; end if; -- Load_Unit may reset Compiler_State, since it may have been -- necessary to parse an additional units, so we make sure -- that we reset it to the Analyzing state. Compiler_State := Analyzing; if Unum /= No_Unit and then not Fatal_Error (Unum) then if Debug_Flag_L then Write_Str ("*** Loaded subunit from stub. Analyze"); Write_Eol; end if; declare Comp_Unit : constant Node_Id := Cunit (Unum); begin -- Check for child unit instead of subunit if Nkind (Unit (Comp_Unit)) /= N_Subunit then Error_Msg_N ("expected SEPARATE subunit, found child unit", Cunit_Entity (Unum)); -- OK, we have a subunit, so go ahead and analyze it, -- and set Scope of entity in stub, for ASIS use. else Set_Corresponding_Stub (Unit (Comp_Unit), N); Analyze_Subunit (Comp_Unit); Set_Library_Unit (N, Comp_Unit); -- We update the version. Although we are not technically -- semantically dependent on the subunit, given our -- approach of macro substitution of subunits, it makes -- sense to include it in the version identification. Version_Update (Cunit (Main_Unit), Comp_Unit); end if; end; end if; end if; -- The remaining case is when the subunit is not already loaded and -- we are not generating code. In this case we are just performing -- semantic analysis on the parent, and we are not interested in -- the subunit. For subprograms, analyze the stub as a body. For -- other entities the stub has already been marked as completed. else Optional_Subunit; end if; end Analyze_Proper_Body; ---------------------------------- -- Analyze_Protected_Body_Stub -- ---------------------------------- procedure Analyze_Protected_Body_Stub (N : Node_Id) is Nam : Entity_Id := Current_Entity_In_Scope (Defining_Identifier (N)); begin Check_Stub_Level (N); -- First occurrence of name may have been as an incomplete type. if Present (Nam) and then Ekind (Nam) = E_Incomplete_Type then Nam := Full_View (Nam); end if; if No (Nam) or else not Is_Protected_Type (Etype (Nam)) then Error_Msg_N ("missing specification for Protected body", N); else Set_Scope (Defining_Entity (N), Current_Scope); Set_Has_Completion (Etype (Nam)); Analyze_Proper_Body (N, Etype (Nam)); end if; end Analyze_Protected_Body_Stub; ---------------------------------- -- Analyze_Subprogram_Body_Stub -- ---------------------------------- -- A subprogram body stub can appear with or without a previous -- specification. If there is one, the analysis of the body will -- find it and verify conformance. The formals appearing in the -- specification of the stub play no role, except for requiring an -- additional conformance check. If there is no previous subprogram -- declaration, the stub acts as a spec, and provides the defining -- entity for the subprogram. procedure Analyze_Subprogram_Body_Stub (N : Node_Id) is Decl : Node_Id; begin Check_Stub_Level (N); -- Verify that the identifier for the stub is unique within this -- declarative part. if Nkind (Parent (N)) = N_Block_Statement or else Nkind (Parent (N)) = N_Package_Body or else Nkind (Parent (N)) = N_Subprogram_Body then Decl := First (Declarations (Parent (N))); while Present (Decl) and then Decl /= N loop if Nkind (Decl) = N_Subprogram_Body_Stub and then (Chars (Defining_Unit_Name (Specification (Decl))) = Chars (Defining_Unit_Name (Specification (N)))) then Error_Msg_N ("identifier for stub is not unique", N); end if; Next (Decl); end loop; end if; -- Treat stub as a body, which checks conformance if there is a previous -- declaration, or else introduces entity and its signature. Analyze_Subprogram_Body (N); if Errors_Detected = 0 then Analyze_Proper_Body (N, Empty); end if; end Analyze_Subprogram_Body_Stub; --------------------- -- Analyze_Subunit -- --------------------- -- A subunit is compiled either by itself (for semantic checking) -- or as part of compiling the parent (for code generation). In -- either case, by the time we actually process the subunit, the -- parent has already been installed and analyzed. The node N is -- a compilation unit, whose context needs to be treated here, -- because we come directly here from the parent without calling -- Analyze_Compilation_Unit. -- The compilation context includes the explicit context of the -- subunit, and the context of the parent, together with the parent -- itself. In order to compile the current context, we remove the -- one inherited from the parent, in order to have a clean visibility -- table. We restore the parent context before analyzing the proper -- body itself. On exit, we remove only the explicit context of the -- subunit. procedure Analyze_Subunit (N : Node_Id) is Lib_Unit : constant Node_Id := Library_Unit (N); Par_Unit : constant Entity_Id := Current_Scope; Lib_Spec : Node_Id := Library_Unit (Lib_Unit); Num_Scopes : Int := 0; Use_Clauses : array (1 .. Scope_Stack.Last) of Node_Id; Enclosing_Child : Entity_Id := Empty; procedure Analyze_Subunit_Context; -- Capture names in use clauses of the subunit. This must be done -- before re-installing parent declarations, because items in the -- context must not be hidden by declarations local to the parent. procedure Re_Install_Parents (L : Node_Id; Scop : Entity_Id); -- Recursive procedure to restore scope of all ancestors of subunit, -- from outermost in. If parent is not a subunit, the call to install -- context installs context of spec and (if parent is a child unit) -- the context of its parents as well. It is confusing that parents -- should be treated differently in both cases, but the semantics are -- just not identical. procedure Re_Install_Use_Clauses; -- As part of the removal of the parent scope, the use clauses are -- removed, to be reinstalled when the context of the subunit has -- been analyzed. Use clauses may also have been affected by the -- analysis of the context of the subunit, so they have to be applied -- again, to insure that the compilation environment of the rest of -- the parent unit is identical. procedure Remove_Scope; -- Remove current scope from scope stack, and preserve the list -- of use clauses in it, to be reinstalled after context is analyzed. ------------------------------ -- Analyze_Subunit_Context -- ------------------------------ procedure Analyze_Subunit_Context is Item : Node_Id; Nam : Node_Id; Unit_Name : Entity_Id; begin Analyze_Context (N); Item := First (Context_Items (N)); -- make withed units immediately visible. If child unit, make the -- ultimate parent immediately visible. while Present (Item) loop if Nkind (Item) = N_With_Clause then Unit_Name := Entity (Name (Item)); while Is_Child_Unit (Unit_Name) loop Set_Is_Visible_Child_Unit (Unit_Name); Unit_Name := Scope (Unit_Name); end loop; if not Is_Immediately_Visible (Unit_Name) then Set_Is_Immediately_Visible (Unit_Name); Set_Context_Installed (Item); end if; elsif Nkind (Item) = N_Use_Package_Clause then Nam := First (Names (Item)); while Present (Nam) loop Analyze (Nam); Next (Nam); end loop; elsif Nkind (Item) = N_Use_Type_Clause then Nam := First (Subtype_Marks (Item)); while Present (Nam) loop Analyze (Nam); Next (Nam); end loop; end if; Next (Item); end loop; Item := First (Context_Items (N)); -- reset visibility of withed units. They will be made visible -- again when we install the subunit context. while Present (Item) loop if Nkind (Item) = N_With_Clause then Unit_Name := Entity (Name (Item)); while Is_Child_Unit (Unit_Name) loop Set_Is_Visible_Child_Unit (Unit_Name, False); Unit_Name := Scope (Unit_Name); end loop; if Context_Installed (Item) then Set_Is_Immediately_Visible (Unit_Name, False); Set_Context_Installed (Item, False); end if; end if; Next (Item); end loop; end Analyze_Subunit_Context; ------------------------ -- Re_Install_Parents -- ------------------------ procedure Re_Install_Parents (L : Node_Id; Scop : Entity_Id) is E : Entity_Id; begin if Nkind (Unit (L)) = N_Subunit then Re_Install_Parents (Library_Unit (L), Scope (Scop)); end if; Install_Context (L); -- If the subunit occurs within a child unit, we must restore the -- immediate visibility of any siblings that may occur in context. if Present (Enclosing_Child) then Install_Siblings (Enclosing_Child, L); end if; New_Scope (Scop); if Scop /= Par_Unit then Set_Is_Immediately_Visible (Scop); end if; E := First_Entity (Current_Scope); while Present (E) loop Set_Is_Immediately_Visible (E); Next_Entity (E); end loop; -- A subunit appears within a body, and for a nested subunits -- all the parents are bodies. Restore full visibility of their -- private entities. if Ekind (Scop) = E_Package then Set_In_Package_Body (Scop); Install_Private_Declarations (Scop); end if; end Re_Install_Parents; ---------------------------- -- Re_Install_Use_Clauses -- ---------------------------- procedure Re_Install_Use_Clauses is U : Node_Id; begin for J in reverse 1 .. Num_Scopes loop U := Use_Clauses (J); Scope_Stack.Table (Scope_Stack.Last - J + 1).First_Use_Clause := U; Install_Use_Clauses (U); end loop; end Re_Install_Use_Clauses; ------------------ -- Remove_Scope -- ------------------ procedure Remove_Scope is E : Entity_Id; begin Num_Scopes := Num_Scopes + 1; Use_Clauses (Num_Scopes) := Scope_Stack.Table (Scope_Stack.Last).First_Use_Clause; E := First_Entity (Current_Scope); while Present (E) loop Set_Is_Immediately_Visible (E, False); Next_Entity (E); end loop; if Is_Child_Unit (Current_Scope) then Enclosing_Child := Current_Scope; end if; Pop_Scope; end Remove_Scope; -- Start of processing for Analyze_Subunit begin if not Is_Empty_List (Context_Items (N)) then -- Save current use clauses. Remove_Scope; Remove_Context (Lib_Unit); -- Now remove parents and their context, including enclosing -- subunits and the outer parent body which is not a subunit. if Present (Lib_Spec) then Remove_Context (Lib_Spec); while Nkind (Unit (Lib_Spec)) = N_Subunit loop Lib_Spec := Library_Unit (Lib_Spec); Remove_Scope; Remove_Context (Lib_Spec); end loop; if Nkind (Unit (Lib_Unit)) = N_Subunit then Remove_Scope; end if; if Nkind (Unit (Lib_Spec)) = N_Package_Body then Remove_Context (Library_Unit (Lib_Spec)); end if; end if; Analyze_Subunit_Context; Re_Install_Parents (Lib_Unit, Par_Unit); -- If the context includes a child unit of the parent of the -- subunit, the parent will have been removed from visibility, -- after compiling that cousin in the context. The visibility -- of the parent must be restored now. This also applies if the -- context includes another subunit of the same parent which in -- turn includes a child unit in its context. if Ekind (Par_Unit) = E_Package then if not Is_Immediately_Visible (Par_Unit) or else (Present (First_Entity (Par_Unit)) and then not Is_Immediately_Visible (First_Entity (Par_Unit))) then Set_Is_Immediately_Visible (Par_Unit); Install_Visible_Declarations (Par_Unit); Install_Private_Declarations (Par_Unit); end if; end if; Re_Install_Use_Clauses; Install_Context (N); -- If the subunit is within a child unit, then siblings of any -- parent unit that appear in the context clause of the subunit -- must also be made immediately visible. if Present (Enclosing_Child) then Install_Siblings (Enclosing_Child, N); end if; end if; Analyze (Proper_Body (Unit (N))); Remove_Context (N); end Analyze_Subunit; ---------------------------- -- Analyze_Task_Body_Stub -- ---------------------------- procedure Analyze_Task_Body_Stub (N : Node_Id) is Nam : Entity_Id := Current_Entity_In_Scope (Defining_Identifier (N)); Loc : constant Source_Ptr := Sloc (N); begin Check_Stub_Level (N); -- First occurrence of name may have been as an incomplete type. if Present (Nam) and then Ekind (Nam) = E_Incomplete_Type then Nam := Full_View (Nam); end if; if No (Nam) or else not Is_Task_Type (Etype (Nam)) then Error_Msg_N ("missing specification for task body", N); else Set_Scope (Defining_Entity (N), Current_Scope); Set_Has_Completion (Etype (Nam)); Analyze_Proper_Body (N, Etype (Nam)); -- Set elaboration flag to indicate that entity is callable. -- This cannot be done in the expansion of the body itself, -- because the proper body is not in a declarative part. This -- is only done if expansion is active, because the context -- may be generic and the flag not defined yet. if Expander_Active then Insert_After (N, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, New_External_Name (Chars (Etype (Nam)), 'E')), Expression => New_Reference_To (Standard_True, Loc))); end if; end if; end Analyze_Task_Body_Stub; ------------------------- -- Analyze_With_Clause -- ------------------------- -- Analyze the declaration of a unit in a with clause. At end, -- label the with clause with the defining entity for the unit. procedure Analyze_With_Clause (N : Node_Id) is Unit_Kind : constant Node_Kind := Nkind (Unit (Library_Unit (N))); E_Name : Entity_Id; Par_Name : Entity_Id; Pref : Node_Id; U : Node_Id; Intunit : Boolean; -- Set True if the unit currently being compiled is an internal unit Save_Style_Check : constant Boolean := Opt.Style_Check; Save_C_Restrict : constant Save_Compilation_Unit_Restrictions := Compilation_Unit_Restrictions_Save; begin -- We reset ordinary style checking during the analysis of a with'ed -- unit, but we do NOT reset GNAT special analysis mode (the latter -- definitely *does* apply to with'ed units). if not GNAT_Mode then Style_Check := False; end if; -- If the library unit is a predefined unit, and we are in no -- run time mode, then temporarily reset No_Run_Time mode for the -- analysis of the with'ed unit. The No_Run_Time pragma does not -- prevent explicit with'ing of run-time units. if No_Run_Time and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (Unit (Library_Unit (N))))) then No_Run_Time := False; Semantics (Library_Unit (N)); No_Run_Time := True; else Semantics (Library_Unit (N)); end if; U := Unit (Library_Unit (N)); Intunit := Is_Internal_File_Name (Unit_File_Name (Current_Sem_Unit)); -- Following checks are skipped for dummy packages (those supplied -- for with's where no matching file could be found). Such packages -- are identified by the Sloc value being set to No_Location if Sloc (U) /= No_Location then -- Check restrictions, except that we skip the check if this -- is an internal unit unless we are compiling the internal -- unit as the main unit. We also skip this for dummy packages. if not Intunit or else Current_Sem_Unit = Main_Unit then Check_Restricted_Unit (Unit_Name (Get_Source_Unit (U)), N); end if; -- Check for inappropriate with of internal implementation unit -- if we are currently compiling the main unit and the main unit -- is itself not an internal unit. if Implementation_Unit_Warnings and then Current_Sem_Unit = Main_Unit and then Implementation_Unit (Get_Source_Unit (U)) and then not Intunit then Error_Msg_N ("& is an internal 'G'N'A'T unit?", Name (N)); Error_Msg_N ("\use of this unit is non-portable and version-dependent?", Name (N)); end if; end if; -- Semantic analysis of a generic unit is performed on a copy of -- the original tree. Retrieve the entity on which semantic info -- actually appears. if Unit_Kind in N_Generic_Declaration then E_Name := Defining_Entity (U); -- Note: in the following test, Unit_Kind is the original Nkind, but -- in the case of an instantiation, semantic analysis above will -- have replaced the unit by its instantiated version. If the instance -- body has been generated, the instance now denotes the body entity. -- For visibility purposes we need the entity of its spec. elsif (Unit_Kind = N_Package_Instantiation or else Nkind (Original_Node (Unit (Library_Unit (N)))) = N_Package_Instantiation) and then Nkind (U) = N_Package_Body then E_Name := Corresponding_Spec (U); elsif Unit_Kind = N_Package_Instantiation and then Nkind (U) = N_Package_Instantiation then -- If the instance has not been rewritten as a package declaration, -- then it appeared already in a previous with clause. Retrieve -- the entity from the previous instance. E_Name := Defining_Entity (Specification (Instance_Spec (U))); elsif Unit_Kind = N_Procedure_Instantiation or else Unit_Kind = N_Function_Instantiation then -- Instantiation node is replaced with a package that contains -- renaming declarations and instance itself. The subprogram -- Instance is declared in the visible part of the wrapper package. E_Name := First_Entity (Defining_Entity (U)); while Present (E_Name) loop exit when Is_Subprogram (E_Name) and then Is_Generic_Instance (E_Name); E_Name := Next_Entity (E_Name); end loop; elsif Unit_Kind = N_Package_Renaming_Declaration or else Unit_Kind in N_Generic_Renaming_Declaration then E_Name := Defining_Entity (U); elsif Unit_Kind = N_Subprogram_Body and then Nkind (Name (N)) = N_Selected_Component and then not Acts_As_Spec (Library_Unit (N)) then -- For a child unit that has no spec, one has been created and -- analyzed. The entity required is that of the spec. E_Name := Corresponding_Spec (U); else E_Name := Defining_Entity (U); end if; if Nkind (Name (N)) = N_Selected_Component then -- Child unit in a with clause Change_Selected_Component_To_Expanded_Name (Name (N)); end if; -- Restore style checks and restrictions Style_Check := Save_Style_Check; Compilation_Unit_Restrictions_Restore (Save_C_Restrict); -- Record the reference, but do NOT set the unit as referenced, we -- want to consider the unit as unreferenced if this is the only -- reference that occurs. Set_Entity_With_Style_Check (Name (N), E_Name); Generate_Reference (E_Name, Name (N), Set_Ref => False); if Is_Child_Unit (E_Name) then Pref := Prefix (Name (N)); Par_Name := Scope (E_Name); while Nkind (Pref) = N_Selected_Component loop Change_Selected_Component_To_Expanded_Name (Pref); Set_Entity_With_Style_Check (Pref, Par_Name); Generate_Reference (Par_Name, Pref); Pref := Prefix (Pref); Par_Name := Scope (Par_Name); end loop; if Present (Entity (Pref)) and then not Analyzed (Parent (Parent (Entity (Pref)))) then -- If the entity is set without its unit being compiled, -- the original parent is a renaming, and Par_Name is the -- renamed entity. For visibility purposes, we need the -- original entity, which must be analyzed now, because -- Load_Unit retrieves directly the renamed unit, and the -- renaming declaration itself has not been analyzed. Analyze (Parent (Parent (Entity (Pref)))); pragma Assert (Renamed_Object (Entity (Pref)) = Par_Name); Par_Name := Entity (Pref); end if; Set_Entity_With_Style_Check (Pref, Par_Name); Generate_Reference (Par_Name, Pref); end if; -- If the withed unit is System, and a system extension pragma is -- present, compile the extension now, rather than waiting for -- a visibility check on a specific entity. if Chars (E_Name) = Name_System and then Scope (E_Name) = Standard_Standard and then Present (System_Extend_Pragma_Arg) and then Present_System_Aux (N) then -- If the extension is not present, an error will have been emitted. null; end if; end Analyze_With_Clause; ------------------------------ -- Analyze_With_Type_Clause -- ------------------------------ procedure Analyze_With_Type_Clause (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Nam : Node_Id := Name (N); Pack : Node_Id; Decl : Node_Id; P : Entity_Id; Unum : Unit_Number_Type; Sel : Node_Id; procedure Decorate_Tagged_Type (T : Entity_Id; Kind : Entity_Kind); -- Set basic attributes of type, including its class_wide type. function In_Chain (E : Entity_Id) return Boolean; -- Check that the imported type is not already in the homonym chain, -- for example through a with_type clause in a parent unit. -------------------------- -- Decorate_Tagged_Type -- -------------------------- procedure Decorate_Tagged_Type (T : Entity_Id; Kind : Entity_Kind) is CW : Entity_Id; begin Set_Ekind (T, E_Record_Type); Set_Is_Tagged_Type (T); Set_Etype (T, T); Set_From_With_Type (T); Set_Scope (T, P); if not In_Chain (T) then Set_Homonym (T, Current_Entity (T)); Set_Current_Entity (T); end if; -- Build bogus class_wide type, if not previously done. if No (Class_Wide_Type (T)) then CW := Make_Defining_Identifier (Loc, New_Internal_Name ('S')); Set_Ekind (CW, E_Class_Wide_Type); Set_Etype (CW, T); Set_Scope (CW, P); Set_Is_Tagged_Type (CW); Set_Is_First_Subtype (CW, True); Init_Size_Align (CW); Set_Has_Unknown_Discriminants (CW, True); Set_Class_Wide_Type (CW, CW); Set_Equivalent_Type (CW, Empty); Set_From_With_Type (CW); Set_Class_Wide_Type (T, CW); end if; end Decorate_Tagged_Type; -------------- -- In_Chain -- -------------- function In_Chain (E : Entity_Id) return Boolean is H : Entity_Id := Current_Entity (E); begin while Present (H) loop if H = E then return True; else H := Homonym (H); end if; end loop; return False; end In_Chain; -- Start of processing for Analyze_With_Type_Clause begin if Nkind (Nam) = N_Selected_Component then Pack := New_Copy_Tree (Prefix (Nam)); Sel := Selector_Name (Nam); else Error_Msg_N ("illegal name for imported type", Nam); return; end if; Decl := Make_Package_Declaration (Loc, Specification => (Make_Package_Specification (Loc, Defining_Unit_Name => Pack, Visible_Declarations => New_List, End_Label => Empty))); Unum := Load_Unit (Load_Name => Get_Unit_Name (Decl), Required => True, Subunit => False, Error_Node => Nam); if Unum = No_Unit or else Nkind (Unit (Cunit (Unum))) /= N_Package_Declaration then Error_Msg_N ("imported type must be declared in package", Nam); return; elsif Unum = Current_Sem_Unit then -- If type is defined in unit being analyzed, then the clause -- is redundant. return; else P := Cunit_Entity (Unum); end if; -- Find declaration for imported type, and set its basic attributes -- if it has not been analyzed (which will be the case if there is -- circular dependence). declare Decl : Node_Id; Typ : Entity_Id; begin if not Analyzed (Cunit (Unum)) and then not From_With_Type (P) then Set_Ekind (P, E_Package); Set_Etype (P, Standard_Void_Type); Set_From_With_Type (P); Set_Scope (P, Standard_Standard); Set_Homonym (P, Current_Entity (P)); Set_Current_Entity (P); elsif Analyzed (Cunit (Unum)) and then Is_Child_Unit (P) then -- If the child unit is already in scope, indicate that it is -- visible, and remains so after intervening calls to rtsfind. Set_Is_Visible_Child_Unit (P); end if; if Nkind (Parent (P)) = N_Defining_Program_Unit_Name then -- Make parent packages visible. declare Parent_Comp : Node_Id; Parent_Id : Entity_Id; Child : Entity_Id; begin Child := P; Parent_Comp := Parent_Spec (Unit (Cunit (Unum))); loop Parent_Id := Defining_Entity (Unit (Parent_Comp)); Set_Scope (Child, Parent_Id); -- The type may be imported from a child unit, in which -- case the current compilation appears in the name. Do -- not change its visibility here because it will conflict -- with the subsequent normal processing. if not Analyzed (Unit_Declaration_Node (Parent_Id)) and then Parent_Id /= Cunit_Entity (Current_Sem_Unit) then Set_Ekind (Parent_Id, E_Package); Set_Etype (Parent_Id, Standard_Void_Type); -- The same package may appear is several with_type -- clauses. if not From_With_Type (Parent_Id) then Set_Homonym (Parent_Id, Current_Entity (Parent_Id)); Set_Current_Entity (Parent_Id); Set_From_With_Type (Parent_Id); end if; end if; Set_Is_Immediately_Visible (Parent_Id); Child := Parent_Id; Parent_Comp := Parent_Spec (Unit (Parent_Comp)); exit when No (Parent_Comp); end loop; Set_Scope (Parent_Id, Standard_Standard); end; end if; -- Even if analyzed, the package may not be currently visible. It -- must be while the with_type clause is active. Set_Is_Immediately_Visible (P); Decl := First (Visible_Declarations (Specification (Unit (Cunit (Unum))))); while Present (Decl) loop if Nkind (Decl) = N_Full_Type_Declaration and then Chars (Defining_Identifier (Decl)) = Chars (Sel) then Typ := Defining_Identifier (Decl); if Tagged_Present (N) then -- The declaration must indicate that this is a tagged -- type or a type extension. if (Nkind (Type_Definition (Decl)) = N_Record_Definition and then Tagged_Present (Type_Definition (Decl))) or else (Nkind (Type_Definition (Decl)) = N_Derived_Type_Definition and then Present (Record_Extension_Part (Type_Definition (Decl)))) then null; else Error_Msg_N ("imported type is not a tagged type", Nam); return; end if; if not Analyzed (Decl) then -- Unit is not currently visible. Add basic attributes -- to type and build its class-wide type. Init_Size_Align (Typ); Decorate_Tagged_Type (Typ, E_Record_Type); end if; else if Nkind (Type_Definition (Decl)) /= N_Access_To_Object_Definition then Error_Msg_N ("imported type is not an access type", Nam); elsif not Analyzed (Decl) then Set_Ekind (Typ, E_Access_Type); Set_Etype (Typ, Typ); Set_Scope (Typ, P); Init_Size (Typ, System_Address_Size); Init_Alignment (Typ); Set_Directly_Designated_Type (Typ, Standard_Integer); Set_From_With_Type (Typ); if not In_Chain (Typ) then Set_Homonym (Typ, Current_Entity (Typ)); Set_Current_Entity (Typ); end if; end if; end if; Set_Entity (Sel, Typ); return; elsif ((Nkind (Decl) = N_Private_Type_Declaration and then Tagged_Present (Decl)) or else (Nkind (Decl) = N_Private_Extension_Declaration)) and then Chars (Defining_Identifier (Decl)) = Chars (Sel) then Typ := Defining_Identifier (Decl); if not Tagged_Present (N) then Error_Msg_N ("type must be declared tagged", N); elsif not Analyzed (Decl) then Decorate_Tagged_Type (Typ, E_Private_Type); end if; Set_Entity (Sel, Typ); Set_From_With_Type (Typ); return; end if; Decl := Next (Decl); end loop; Error_Msg_NE ("not a visible access or tagged type in&", Nam, P); end; end Analyze_With_Type_Clause; ----------------------------- -- Check_With_Type_Clauses -- ----------------------------- procedure Check_With_Type_Clauses (N : Node_Id) is Lib_Unit : constant Node_Id := Unit (N); procedure Check_Parent_Context (U : Node_Id); -- Examine context items of parent unit to locate with_type clauses. -------------------------- -- Check_Parent_Context -- -------------------------- procedure Check_Parent_Context (U : Node_Id) is Item : Node_Id; begin Item := First (Context_Items (U)); while Present (Item) loop if Nkind (Item) = N_With_Type_Clause and then not Error_Posted (Item) and then From_With_Type (Scope (Entity (Selector_Name (Name (Item))))) then Error_Msg_Sloc := Sloc (Item); Error_Msg_N ("Missing With_Clause for With_Type_Clause#", N); end if; Next (Item); end loop; end Check_Parent_Context; -- Start of processing for Check_With_Type_Clauses begin if Extensions_Allowed and then (Nkind (Lib_Unit) = N_Package_Body or else Nkind (Lib_Unit) = N_Subprogram_Body) then Check_Parent_Context (Library_Unit (N)); if Is_Child_Spec (Unit (Library_Unit (N))) then Check_Parent_Context (Parent_Spec (Unit (Library_Unit (N)))); end if; end if; end Check_With_Type_Clauses; ------------------------------ -- Check_Private_Child_Unit -- ------------------------------ procedure Check_Private_Child_Unit (N : Node_Id) is Lib_Unit : constant Node_Id := Unit (N); Item : Node_Id; Curr_Unit : Entity_Id; Sub_Parent : Node_Id; Priv_Child : Entity_Id; Par_Lib : Entity_Id; Par_Spec : Node_Id; function Is_Private_Library_Unit (Unit : Entity_Id) return Boolean; -- Returns true if and only if the library unit is declared with -- an explicit designation of private. function Is_Private_Library_Unit (Unit : Entity_Id) return Boolean is begin return Private_Present (Parent (Unit_Declaration_Node (Unit))); end Is_Private_Library_Unit; -- Start of processing for Check_Private_Child_Unit begin if Nkind (Lib_Unit) = N_Package_Body or else Nkind (Lib_Unit) = N_Subprogram_Body then Curr_Unit := Defining_Entity (Unit (Library_Unit (N))); Par_Lib := Curr_Unit; elsif Nkind (Lib_Unit) = N_Subunit then -- The parent is itself a body. The parent entity is to be found -- in the corresponding spec. Sub_Parent := Library_Unit (N); Curr_Unit := Defining_Entity (Unit (Library_Unit (Sub_Parent))); -- If the parent itself is a subunit, Curr_Unit is the entity -- of the enclosing body, retrieve the spec entity which is -- the proper ancestor we need for the following tests. if Ekind (Curr_Unit) = E_Package_Body then Curr_Unit := Spec_Entity (Curr_Unit); end if; Par_Lib := Curr_Unit; else Curr_Unit := Defining_Entity (Lib_Unit); Par_Lib := Curr_Unit; Par_Spec := Parent_Spec (Lib_Unit); if No (Par_Spec) then Par_Lib := Empty; else Par_Lib := Defining_Entity (Unit (Par_Spec)); end if; end if; -- Loop through context items Item := First (Context_Items (N)); while Present (Item) loop if Nkind (Item) = N_With_Clause and then not Implicit_With (Item) and then Is_Private_Descendant (Entity (Name (Item))) then Priv_Child := Entity (Name (Item)); declare Curr_Parent : Entity_Id := Par_Lib; Child_Parent : Entity_Id := Scope (Priv_Child); Prv_Ancestor : Entity_Id := Child_Parent; Curr_Private : Boolean := Is_Private_Library_Unit (Curr_Unit); begin -- If the child unit is a public child then locate -- the nearest private ancestor; Child_Parent will -- then be set to the parent of that ancestor. if not Is_Private_Library_Unit (Priv_Child) then while Present (Prv_Ancestor) and then not Is_Private_Library_Unit (Prv_Ancestor) loop Prv_Ancestor := Scope (Prv_Ancestor); end loop; if Present (Prv_Ancestor) then Child_Parent := Scope (Prv_Ancestor); end if; end if; while Present (Curr_Parent) and then Curr_Parent /= Standard_Standard and then Curr_Parent /= Child_Parent loop Curr_Private := Curr_Private or else Is_Private_Library_Unit (Curr_Parent); Curr_Parent := Scope (Curr_Parent); end loop; if not Present (Curr_Parent) then Curr_Parent := Standard_Standard; end if; if Curr_Parent /= Child_Parent then if Ekind (Priv_Child) = E_Generic_Package and then Chars (Priv_Child) in Text_IO_Package_Name and then Chars (Scope (Scope (Priv_Child))) = Name_Ada then Error_Msg_NE ("& is a nested package, not a compilation unit", Name (Item), Priv_Child); else Error_Msg_N ("unit in with clause is private child unit!", Item); Error_Msg_NE ("current unit must also have parent&!", Item, Child_Parent); end if; elsif not Curr_Private and then Nkind (Lib_Unit) /= N_Package_Body and then Nkind (Lib_Unit) /= N_Subprogram_Body and then Nkind (Lib_Unit) /= N_Subunit then Error_Msg_NE ("current unit must also be private descendant of&", Item, Child_Parent); end if; end; end if; Next (Item); end loop; end Check_Private_Child_Unit; ---------------------- -- Check_Stub_Level -- ---------------------- procedure Check_Stub_Level (N : Node_Id) is Par : constant Node_Id := Parent (N); Kind : constant Node_Kind := Nkind (Par); begin if (Kind = N_Package_Body or else Kind = N_Subprogram_Body or else Kind = N_Task_Body or else Kind = N_Protected_Body) and then (Nkind (Parent (Par)) = N_Compilation_Unit or else Nkind (Parent (Par)) = N_Subunit) then null; -- In an instance, a missing stub appears at any level. A warning -- message will have been emitted already for the missing file. elsif not In_Instance then Error_Msg_N ("stub cannot appear in an inner scope", N); elsif Expander_Active then Error_Msg_N ("missing proper body", N); end if; end Check_Stub_Level; ------------------------ -- Expand_With_Clause -- ------------------------ procedure Expand_With_Clause (Nam : Node_Id; N : Node_Id) is Loc : constant Source_Ptr := Sloc (Nam); Ent : constant Entity_Id := Entity (Nam); Withn : Node_Id; P : Node_Id; function Build_Unit_Name (Nam : Node_Id) return Node_Id; function Build_Unit_Name (Nam : Node_Id) return Node_Id is Result : Node_Id; begin if Nkind (Nam) = N_Identifier then return New_Occurrence_Of (Entity (Nam), Loc); else Result := Make_Expanded_Name (Loc, Chars => Chars (Entity (Nam)), Prefix => Build_Unit_Name (Prefix (Nam)), Selector_Name => New_Occurrence_Of (Entity (Nam), Loc)); Set_Entity (Result, Entity (Nam)); return Result; end if; end Build_Unit_Name; begin New_Nodes_OK := New_Nodes_OK + 1; Withn := Make_With_Clause (Loc, Name => Build_Unit_Name (Nam)); P := Parent (Unit_Declaration_Node (Ent)); Set_Library_Unit (Withn, P); Set_Corresponding_Spec (Withn, Ent); Set_First_Name (Withn, True); Set_Implicit_With (Withn, True); Prepend (Withn, Context_Items (N)); Mark_Rewrite_Insertion (Withn); Install_Withed_Unit (Withn); if Nkind (Nam) = N_Expanded_Name then Expand_With_Clause (Prefix (Nam), N); end if; New_Nodes_OK := New_Nodes_OK - 1; end Expand_With_Clause; ----------------------------- -- Implicit_With_On_Parent -- ----------------------------- procedure Implicit_With_On_Parent (Child_Unit : Node_Id; N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); P : constant Node_Id := Parent_Spec (Child_Unit); P_Unit : constant Node_Id := Unit (P); P_Name : Entity_Id := Defining_Entity (P_Unit); Withn : Node_Id; function Build_Ancestor_Name (P : Node_Id) return Node_Id; -- Build prefix of child unit name. Recurse if needed. function Build_Unit_Name return Node_Id; -- If the unit is a child unit, build qualified name with all -- ancestors. ------------------------- -- Build_Ancestor_Name -- ------------------------- function Build_Ancestor_Name (P : Node_Id) return Node_Id is P_Ref : Node_Id := New_Reference_To (Defining_Entity (P), Loc); begin if No (Parent_Spec (P)) then return P_Ref; else return Make_Selected_Component (Loc, Prefix => Build_Ancestor_Name (Unit (Parent_Spec (P))), Selector_Name => P_Ref); end if; end Build_Ancestor_Name; --------------------- -- Build_Unit_Name -- --------------------- function Build_Unit_Name return Node_Id is Result : Node_Id; begin if No (Parent_Spec (P_Unit)) then return New_Reference_To (P_Name, Loc); else Result := Make_Expanded_Name (Loc, Chars => Chars (P_Name), Prefix => Build_Ancestor_Name (Unit (Parent_Spec (P_Unit))), Selector_Name => New_Reference_To (P_Name, Loc)); Set_Entity (Result, P_Name); return Result; end if; end Build_Unit_Name; -- Start of processing for Implicit_With_On_Parent begin New_Nodes_OK := New_Nodes_OK + 1; Withn := Make_With_Clause (Loc, Name => Build_Unit_Name); Set_Library_Unit (Withn, P); Set_Corresponding_Spec (Withn, P_Name); Set_First_Name (Withn, True); Set_Implicit_With (Withn, True); -- Node is placed at the beginning of the context items, so that -- subsequent use clauses on the parent can be validated. Prepend (Withn, Context_Items (N)); Mark_Rewrite_Insertion (Withn); Install_Withed_Unit (Withn); if Is_Child_Spec (P_Unit) then Implicit_With_On_Parent (P_Unit, N); end if; New_Nodes_OK := New_Nodes_OK - 1; end Implicit_With_On_Parent; --------------------- -- Install_Context -- --------------------- procedure Install_Context (N : Node_Id) is Lib_Unit : Node_Id := Unit (N); begin Install_Context_Clauses (N); if Is_Child_Spec (Lib_Unit) then Install_Parents (Lib_Unit, Private_Present (Parent (Lib_Unit))); end if; Check_With_Type_Clauses (N); end Install_Context; ----------------------------- -- Install_Context_Clauses -- ----------------------------- procedure Install_Context_Clauses (N : Node_Id) is Lib_Unit : Node_Id := Unit (N); Item : Node_Id; Uname_Node : Entity_Id; Check_Private : Boolean := False; Decl_Node : Node_Id; Lib_Parent : Entity_Id; begin -- Loop through context clauses to find the with/use clauses Item := First (Context_Items (N)); while Present (Item) loop -- Case of explicit WITH clause if Nkind (Item) = N_With_Clause and then not Implicit_With (Item) then -- If Name (Item) is not an entity name, something is wrong, and -- this will be detected in due course, for now ignore the item if not Is_Entity_Name (Name (Item)) then goto Continue; end if; Uname_Node := Entity (Name (Item)); if Is_Private_Descendant (Uname_Node) then Check_Private := True; end if; Install_Withed_Unit (Item); Decl_Node := Unit_Declaration_Node (Uname_Node); -- If the unit is a subprogram instance, it appears nested -- within a package that carries the parent information. if Is_Generic_Instance (Uname_Node) and then Ekind (Uname_Node) /= E_Package then Decl_Node := Parent (Parent (Decl_Node)); end if; if Is_Child_Spec (Decl_Node) then if Nkind (Name (Item)) = N_Expanded_Name then Expand_With_Clause (Prefix (Name (Item)), N); else -- if not an expanded name, the child unit must be a -- renaming, nothing to do. null; end if; elsif Nkind (Decl_Node) = N_Subprogram_Body and then not Acts_As_Spec (Parent (Decl_Node)) and then Is_Child_Spec (Unit (Library_Unit (Parent (Decl_Node)))) then Implicit_With_On_Parent (Unit (Library_Unit (Parent (Decl_Node))), N); end if; -- Check license conditions unless this is a dummy unit if Sloc (Library_Unit (Item)) /= No_Location then License_Check : declare Withl : constant License_Type := License (Source_Index (Get_Source_Unit (Library_Unit (Item)))); Unitl : constant License_Type := License (Source_Index (Current_Sem_Unit)); procedure License_Error; -- Signal error of bad license ------------------- -- License_Error -- ------------------- procedure License_Error is begin Error_Msg_N ("?license of with'ed unit & is incompatible", Name (Item)); end License_Error; -- Start of processing for License_Check begin case Unitl is when Unknown => null; when Restricted => if Withl = GPL then License_Error; end if; when GPL => if Withl = Restricted then License_Error; end if; when Modified_GPL => if Withl = Restricted or else Withl = GPL then License_Error; end if; when Unrestricted => null; end case; end License_Check; end if; -- Case of USE PACKAGE clause elsif Nkind (Item) = N_Use_Package_Clause then Analyze_Use_Package (Item); -- Case of USE TYPE clause elsif Nkind (Item) = N_Use_Type_Clause then Analyze_Use_Type (Item); -- Case of WITH TYPE clause -- A With_Type_Clause is processed when installing the context, -- because it is a visibility mechanism and does not create a -- semantic dependence on other units, as a With_Clause does. elsif Nkind (Item) = N_With_Type_Clause then Analyze_With_Type_Clause (Item); -- case of PRAGMA elsif Nkind (Item) = N_Pragma then Analyze (Item); end if; <<Continue>> Next (Item); end loop; if Is_Child_Spec (Lib_Unit) then -- The unit also has implicit withs on its own parents. if No (Context_Items (N)) then Set_Context_Items (N, New_List); end if; Implicit_With_On_Parent (Lib_Unit, N); end if; -- If the unit is a body, the context of the specification must also -- be installed. if Nkind (Lib_Unit) = N_Package_Body or else (Nkind (Lib_Unit) = N_Subprogram_Body and then not Acts_As_Spec (N)) then Install_Context (Library_Unit (N)); if Is_Child_Spec (Unit (Library_Unit (N))) then -- If the unit is the body of a public child unit, the private -- declarations of the parent must be made visible. If the child -- unit is private, the private declarations have been installed -- already in the call to Install_Parents for the spec. Installing -- private declarations must be done for all ancestors of public -- child units. In addition, sibling units mentioned in the -- context clause of the body are directly visible. declare Lib_Spec : Node_Id := Unit (Library_Unit (N)); P : Node_Id; P_Name : Entity_Id; begin while Is_Child_Spec (Lib_Spec) loop P := Unit (Parent_Spec (Lib_Spec)); if not (Private_Present (Parent (Lib_Spec))) then P_Name := Defining_Entity (P); Install_Private_Declarations (P_Name); Set_Use (Private_Declarations (Specification (P))); end if; Lib_Spec := P; end loop; end; end if; -- For a package body, children in context are immediately visible Install_Siblings (Defining_Entity (Unit (Library_Unit (N))), N); end if; if Nkind (Lib_Unit) = N_Generic_Package_Declaration or else Nkind (Lib_Unit) = N_Generic_Subprogram_Declaration or else Nkind (Lib_Unit) = N_Package_Declaration or else Nkind (Lib_Unit) = N_Subprogram_Declaration then if Is_Child_Spec (Lib_Unit) then Lib_Parent := Defining_Entity (Unit (Parent_Spec (Lib_Unit))); Set_Is_Private_Descendant (Defining_Entity (Lib_Unit), Is_Private_Descendant (Lib_Parent) or else Private_Present (Parent (Lib_Unit))); else Set_Is_Private_Descendant (Defining_Entity (Lib_Unit), Private_Present (Parent (Lib_Unit))); end if; end if; if Check_Private then Check_Private_Child_Unit (N); end if; end Install_Context_Clauses; --------------------- -- Install_Parents -- --------------------- procedure Install_Parents (Lib_Unit : Node_Id; Is_Private : Boolean) is P : Node_Id; E_Name : Entity_Id; P_Name : Entity_Id; P_Spec : Node_Id; begin P := Unit (Parent_Spec (Lib_Unit)); P_Name := Defining_Entity (P); if Etype (P_Name) = Any_Type then return; end if; if Ekind (P_Name) = E_Generic_Package and then Nkind (Lib_Unit) /= N_Generic_Subprogram_Declaration and then Nkind (Lib_Unit) /= N_Generic_Package_Declaration and then Nkind (Lib_Unit) not in N_Generic_Renaming_Declaration then Error_Msg_N ("child of a generic package must be a generic unit", Lib_Unit); elsif not Is_Package (P_Name) then Error_Msg_N ("parent unit must be package or generic package", Lib_Unit); raise Unrecoverable_Error; elsif Present (Renamed_Object (P_Name)) then Error_Msg_N ("parent unit cannot be a renaming", Lib_Unit); raise Unrecoverable_Error; -- Verify that a child of an instance is itself an instance, or -- the renaming of one. Given that an instance that is a unit is -- replaced with a package declaration, check against the original -- node. elsif Nkind (Original_Node (P)) = N_Package_Instantiation and then Nkind (Lib_Unit) not in N_Renaming_Declaration and then Nkind (Original_Node (Lib_Unit)) not in N_Generic_Instantiation then Error_Msg_N ("child of an instance must be an instance or renaming", Lib_Unit); end if; -- This is the recursive call that ensures all parents are loaded if Is_Child_Spec (P) then Install_Parents (P, Is_Private or else Private_Present (Parent (Lib_Unit))); end if; -- Now we can install the context for this parent Install_Context_Clauses (Parent_Spec (Lib_Unit)); Install_Siblings (P_Name, Parent (Lib_Unit)); -- The child unit is in the declarative region of the parent. The -- parent must therefore appear in the scope stack and be visible, -- as when compiling the corresponding body. If the child unit is -- private or it is a package body, private declarations must be -- accessible as well. Use declarations in the parent must also -- be installed. Finally, other child units of the same parent that -- are in the context are immediately visible. -- Find entity for compilation unit, and set its private descendant -- status as needed. E_Name := Defining_Entity (Lib_Unit); Set_Is_Child_Unit (E_Name); Set_Is_Private_Descendant (E_Name, Is_Private_Descendant (P_Name) or else Private_Present (Parent (Lib_Unit))); P_Spec := Specification (Unit_Declaration_Node (P_Name)); New_Scope (P_Name); -- Save current visibility of unit Scope_Stack.Table (Scope_Stack.Last).Previous_Visibility := Is_Immediately_Visible (P_Name); Set_Is_Immediately_Visible (P_Name); Install_Visible_Declarations (P_Name); Set_Use (Visible_Declarations (P_Spec)); if Is_Private or else Private_Present (Parent (Lib_Unit)) then Install_Private_Declarations (P_Name); Set_Use (Private_Declarations (P_Spec)); end if; end Install_Parents; ---------------------- -- Install_Siblings -- ---------------------- procedure Install_Siblings (U_Name : Entity_Id; N : Node_Id) is Item : Node_Id; Id : Entity_Id; Prev : Entity_Id; function Is_Ancestor (E : Entity_Id) return Boolean; -- Determine whether the scope of a child unit is an ancestor of -- the current unit. -- Shouldn't this be somewhere more general ??? function Is_Ancestor (E : Entity_Id) return Boolean is Par : Entity_Id; begin Par := U_Name; while Present (Par) and then Par /= Standard_Standard loop if Par = E then return True; end if; Par := Scope (Par); end loop; return False; end Is_Ancestor; -- Start of processing for Install_Siblings begin -- Iterate over explicit with clauses, and check whether the -- scope of each entity is an ancestor of the current unit. Item := First (Context_Items (N)); while Present (Item) loop if Nkind (Item) = N_With_Clause and then not Implicit_With (Item) then Id := Entity (Name (Item)); if Is_Child_Unit (Id) and then Is_Ancestor (Scope (Id)) then Set_Is_Immediately_Visible (Id); Prev := Current_Entity (Id); -- Check for the presence of another unit in the context, -- that may be inadvertently hidden by the child. if Present (Prev) and then Is_Immediately_Visible (Prev) and then not Is_Child_Unit (Prev) then declare Clause : Node_Id; begin Clause := First (Context_Items (N)); while Present (Clause) loop if Nkind (Clause) = N_With_Clause and then Entity (Name (Clause)) = Prev then Error_Msg_NE ("child unit& hides compilation unit " & "with the same name?", Name (Item), Id); exit; end if; Next (Clause); end loop; end; end if; -- the With_Clause may be on a grand-child, which makes -- the child immediately visible. elsif Is_Child_Unit (Scope (Id)) and then Is_Ancestor (Scope (Scope (Id))) then Set_Is_Immediately_Visible (Scope (Id)); end if; end if; Next (Item); end loop; end Install_Siblings; ------------------------- -- Install_Withed_Unit -- ------------------------- procedure Install_Withed_Unit (With_Clause : Node_Id) is Uname : Entity_Id := Entity (Name (With_Clause)); P : constant Entity_Id := Scope (Uname); begin -- We do not apply the restrictions to an internal unit unless -- we are compiling the internal unit as a main unit. This check -- is also skipped for dummy units (for missing packages). if Sloc (Uname) /= No_Location and then (not Is_Internal_File_Name (Unit_File_Name (Current_Sem_Unit)) or else Current_Sem_Unit = Main_Unit) then Check_Restricted_Unit (Unit_Name (Get_Source_Unit (Uname)), With_Clause); end if; if P /= Standard_Standard then -- If the unit is not analyzed after analysis of the with clause, -- and it is an instantiation, then it awaits a body and is the main -- unit. Its appearance in the context of some other unit indicates -- a circular dependency (DEC suite perversity). if not Analyzed (Uname) and then Nkind (Parent (Uname)) = N_Package_Instantiation then Error_Msg_N ("instantiation depends on itself", Name (With_Clause)); elsif not Is_Visible_Child_Unit (Uname) then Set_Is_Visible_Child_Unit (Uname); if Is_Generic_Instance (Uname) and then Ekind (Uname) in Subprogram_Kind then -- Set flag as well on the visible entity that denotes the -- instance, which renames the current one. Set_Is_Visible_Child_Unit (Related_Instance (Defining_Entity (Unit (Library_Unit (With_Clause))))); null; end if; -- The parent unit may have been installed already, and -- may have appeared in a use clause. if In_Use (Scope (Uname)) then Set_Is_Potentially_Use_Visible (Uname); end if; Set_Context_Installed (With_Clause); end if; elsif not Is_Immediately_Visible (Uname) then Set_Is_Immediately_Visible (Uname); Set_Context_Installed (With_Clause); end if; -- A with-clause overrides a with-type clause: there are no restric- -- tions on the use of package entities. if Ekind (Uname) = E_Package then Set_From_With_Type (Uname, False); end if; end Install_Withed_Unit; ------------------- -- Is_Child_Spec -- ------------------- function Is_Child_Spec (Lib_Unit : Node_Id) return Boolean is K : constant Node_Kind := Nkind (Lib_Unit); begin return (K in N_Generic_Declaration or else K in N_Generic_Instantiation or else K in N_Generic_Renaming_Declaration or else K = N_Package_Declaration or else K = N_Package_Renaming_Declaration or else K = N_Subprogram_Declaration or else K = N_Subprogram_Renaming_Declaration) and then Present (Parent_Spec (Lib_Unit)); end Is_Child_Spec; ----------------------- -- Load_Needed_Body -- ----------------------- -- N is a generic unit named in a with clause, or else it is -- a unit that contains a generic unit or an inlined function. -- In order to perform an instantiation, the body of the unit -- must be present. If the unit itself is generic, we assume -- that an instantiation follows, and load and analyze the body -- unconditionally. This forces analysis of the spec as well. -- If the unit is not generic, but contains a generic unit, it -- is loaded on demand, at the point of instantiation (see ch12). procedure Load_Needed_Body (N : Node_Id; OK : out Boolean) is Body_Name : Unit_Name_Type; Unum : Unit_Number_Type; Save_Style_Check : constant Boolean := Opt.Style_Check; -- The loading and analysis is done with style checks off begin if not GNAT_Mode then Style_Check := False; end if; Body_Name := Get_Body_Name (Get_Unit_Name (Unit (N))); Unum := Load_Unit (Load_Name => Body_Name, Required => False, Subunit => False, Error_Node => N, Renamings => True); if Unum = No_Unit then OK := False; else Compiler_State := Analyzing; -- reset after load if not Fatal_Error (Unum) then if Debug_Flag_L then Write_Str ("*** Loaded generic body"); Write_Eol; end if; Semantics (Cunit (Unum)); end if; OK := True; end if; Style_Check := Save_Style_Check; end Load_Needed_Body; -------------------- -- Remove_Context -- -------------------- procedure Remove_Context (N : Node_Id) is Lib_Unit : constant Node_Id := Unit (N); begin -- If this is a child unit, first remove the parent units. if Is_Child_Spec (Lib_Unit) then Remove_Parents (Lib_Unit); end if; Remove_Context_Clauses (N); end Remove_Context; ---------------------------- -- Remove_Context_Clauses -- ---------------------------- procedure Remove_Context_Clauses (N : Node_Id) is Item : Node_Id; Unit_Name : Entity_Id; begin -- Loop through context items and undo with_clauses and use_clauses. Item := First (Context_Items (N)); while Present (Item) loop -- We are interested only in with clauses which got installed -- on entry, as indicated by their Context_Installed flag set if Nkind (Item) = N_With_Clause and then Context_Installed (Item) then -- Remove items from one with'ed unit Unit_Name := Entity (Name (Item)); Remove_Unit_From_Visibility (Unit_Name); Set_Context_Installed (Item, False); elsif Nkind (Item) = N_Use_Package_Clause then End_Use_Package (Item); elsif Nkind (Item) = N_Use_Type_Clause then End_Use_Type (Item); elsif Nkind (Item) = N_With_Type_Clause then Remove_With_Type_Clause (Name (Item)); end if; Next (Item); end loop; end Remove_Context_Clauses; -------------------- -- Remove_Parents -- -------------------- procedure Remove_Parents (Lib_Unit : Node_Id) is P : Node_Id; P_Name : Entity_Id; E : Entity_Id; Vis : constant Boolean := Scope_Stack.Table (Scope_Stack.Last).Previous_Visibility; begin if Is_Child_Spec (Lib_Unit) then P := Unit (Parent_Spec (Lib_Unit)); P_Name := Defining_Entity (P); Remove_Context_Clauses (Parent_Spec (Lib_Unit)); End_Package_Scope (P_Name); Set_Is_Immediately_Visible (P_Name, Vis); -- Remove from visibility the siblings as well, which are directly -- visible while the parent is in scope. E := First_Entity (P_Name); while Present (E) loop if Is_Child_Unit (E) then Set_Is_Immediately_Visible (E, False); end if; Next_Entity (E); end loop; Set_In_Package_Body (P_Name, False); -- This is the recursive call to remove the context of any -- higher level parent. This recursion ensures that all parents -- are removed in the reverse order of their installation. Remove_Parents (P); end if; end Remove_Parents; ----------------------------- -- Remove_With_Type_Clause -- ----------------------------- procedure Remove_With_Type_Clause (Name : Node_Id) is Typ : Entity_Id; P : Entity_Id; procedure Unchain (E : Entity_Id); -- Remove entity from visibility list. procedure Unchain (E : Entity_Id) is Prev : Entity_Id; begin Prev := Current_Entity (E); -- Package entity may appear is several with_type_clauses, and -- may have been removed already. if No (Prev) then return; elsif Prev = E then Set_Name_Entity_Id (Chars (E), Homonym (E)); else while Present (Prev) and then Homonym (Prev) /= E loop Prev := Homonym (Prev); end loop; if (Present (Prev)) then Set_Homonym (Prev, Homonym (E)); end if; end if; end Unchain; begin if Nkind (Name) = N_Selected_Component then Typ := Entity (Selector_Name (Name)); if No (Typ) then -- error in declaration. return; end if; else return; end if; P := Scope (Typ); -- If the exporting package has been analyzed, it has appeared in the -- context already and should be left alone. Otherwise, remove from -- visibility. if not Analyzed (Unit_Declaration_Node (P)) then Unchain (P); Unchain (Typ); Set_Is_Frozen (Typ, False); end if; if Ekind (Typ) = E_Record_Type then Set_From_With_Type (Class_Wide_Type (Typ), False); Set_From_With_Type (Typ, False); end if; Set_From_With_Type (P, False); -- If P is a child unit, remove parents as well. P := Scope (P); while Present (P) and then P /= Standard_Standard loop Set_From_With_Type (P, False); if not Analyzed (Unit_Declaration_Node (P)) then Unchain (P); end if; P := Scope (P); end loop; -- The back-end needs to know that an access type is imported, so it -- does not need elaboration and can appear in a mutually recursive -- record definition, so the imported flag on an access type is -- preserved. end Remove_With_Type_Clause; --------------------------------- -- Remove_Unit_From_Visibility -- --------------------------------- procedure Remove_Unit_From_Visibility (Unit_Name : Entity_Id) is P : Entity_Id := Scope (Unit_Name); begin if Debug_Flag_I then Write_Str ("remove withed unit "); Write_Name (Chars (Unit_Name)); Write_Eol; end if; if P /= Standard_Standard then Set_Is_Visible_Child_Unit (Unit_Name, False); end if; Set_Is_Potentially_Use_Visible (Unit_Name, False); Set_Is_Immediately_Visible (Unit_Name, False); end Remove_Unit_From_Visibility; end Sem_Ch10;
with Ada.Containers.Functional_Vectors; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Common; use Common; package LMCP_Messages with SPARK_Mode is type Message_Root is abstract tagged null record; -- Messages only contain functional containers and SPARK compatible data type AltitudeTypeEnum is (AGL, MSL); type SpeedTypeEnum is (Airspeed, Groundspeed); type TurnTypeEnum is (TurnShort, FlyOver); type Location3D is tagged record -- Latitude Latitude : Real64 := 0.0; -- Longitude Longitude : Real64 := 0.0; -- Altitude for this waypoint Altitude : Real32 := 0.0; -- Altitude type for specified altitude AltitudeType : AltitudeTypeEnum := MSL; end record; type EntityState is new Message_Root with record Id : Int64 := 0; Location : Location3D; Heading : Real32 := 0.0; end record; type PlanningState is record -- Identifier of the entitiy EntityID : Int64 := 0; -- Position of this entity for the plan. A valid PlanningState must define PlanningPosition (null not allowed). PlanningPosition : Location3D; -- Heading of this entity for the plan PlanningHeading : Real32 := 0.0; end record; package PS_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => PlanningState); type PlanningState_Seq is new PS_Sequences.Sequence; type AutomationRequest is new Message_Root with record EntityList : Int64_Seq; OperatingRegion : Int64 := 0; TaskList : Int64_Seq; TaskRelationships : Unbounded_String; RedoAllTasks : Boolean := False; end record; type TaskAutomationRequest is new AutomationRequest with record RequestID : Int64 := 0; PlanningStates : PlanningState_Seq; SandboxRequest : Boolean := False; end record; type ImpactAutomationRequest is new AutomationRequest with record RequestID : Int64 := 0; PlayID : Int64 := 0; SolutionID : Int64 := 0; end record; type UniqueAutomationRequest is new AutomationRequest with record RequestID : Int64 := 0; PlanningStates : PlanningState_Seq; SandboxRequest : Boolean := False; end record; type VehicleAction is record -- A list of tasks that are associated with this action. A length of zero denotes no associated tasks. This field is for analysis purposes. The automation service should associate a list of tasks with each action to enable analysis of the allocation of tasks to vehicles. -- AssociatedTaskList : Int64_Seq; end record; package VA_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => VehicleAction); type VA_Seq is new VA_Sequences.Sequence; type CommandStatusTypeEnum is (Pending, Approved, InProcess, Executed, Cancelled); type VehicleActionCommand is new Message_Root with record CommandId : Int64 := 0; VehicleId : Int64 := 0; VehicleActionList : VA_Seq; Status : CommandStatusTypeEnum := Pending; end record; package VAC_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => VehicleActionCommand); type VehicleActionCommand_Seq is new VAC_Sequences.Sequence; type Waypoint is new Location3D with record -- A unique waypoint number Number : Int64 := 0; -- The index of the next waypoint in the list. Consecutively numbered waypoints are <b>not</b> considered linked, the link must be explicitly stated in this field. NextWaypoint : Int64 := 0; -- Commanded speed for this waypoint. See SpeedType for defintion of this field. Speed : Real32 := 0.0; -- Type of commanded speed SpeedType : SpeedTypeEnum := Airspeed; -- The commanded climb rate. Positive values upwards. For surface (ground and sea) entities, this value is ignored. ClimbRate : Real32 := 0.0; -- The type of turn to execute TurnType : TurnTypeEnum := TurnShort; -- A list of actions to perform at this waypoint VehicleActionList : VA_Seq; -- A waypoint for contingency (e.g. lost-comm, alternate mission) operations. A value of zero denotes that no contingency point is specified. ContingencyWaypointA : Int64 := 0; -- A waypoint for contingency (e.g. lost-comm, alternate mission) operations. A value of zero denotes that no contingency point is specified. ContingencyWaypointB : Int64 := 0; -- A list of tasks that are associated with this waypoint. A length of zero denotes no associated tasks. This field is for analysis purposes. The automation service should associate a list of tasks with each waypoint to enable analysis of the allocation of tasks to vehicles. AssociatedTasks : Int64_Seq; end record; package WP_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => Waypoint); type WP_Seq is new WP_Sequences.Sequence; type MissionCommand is new VehicleActionCommand with record WaypointList : WP_Seq; FirstWaypoint : Int64 := 0; end record; package MC_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => MissionCommand); type MissionCommand_Seq is new MC_Sequences.Sequence; type KeyValuePair is record -- A key (name) for the property Key : Unbounded_String := To_Unbounded_String (""); -- A value for the property Value : Unbounded_String := To_Unbounded_String (""); end record; package KVP_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => KeyValuePair); type KVP_Seq is new KVP_Sequences.Sequence; type AutomationResponse is new Message_Root with record MissionCommandList : MissionCommand_Seq; VehicleCommandList : VehicleActionCommand_Seq; Info : KVP_Seq; end record; type TaskAutomationResponse is new AutomationResponse with record ResponseID : Int64 := 0; FinalStates : PlanningState_Seq; end record; type ImpactAutomationResponse is new AutomationResponse with record ResponseID : Int64 := 0; PlayId : Int64 := 0; SolutionId : Int64 := 0; Sandbox : Boolean := False; end record; type UniqueAutomationResponse is new AutomationResponse with record ResponseID : Int64 := 0; FinalStates : PlanningState_Seq; end record; type ServiceStatusTypeEnum is (Information, Warning, Error); type ServiceStatus is new Message_Root with record PercentComplete : Real32 := 0.0; Info : KVP_Seq; StatusType : ServiceStatusTypeEnum := Information; end record; type RouteConstraints is record -- ID denoting this set of route constraints RouteID : Int64 := 0; -- Location from which the planned route will start. A valid RouteConstraints message must define StartLocation (null not allowed). StartLocation : Location3D; -- Heading of entity at the start of the route StartHeading : Real32 := 0.0; -- If "true" the heading value in StartHeading must be used to start the route. If not, any starting heading can be used. UseStartHeading : Boolean := True; -- Location to which the planned route will end. A valid RouteConstraints message must define EndLocation (null not allowed). EndLocation : Location3D; -- Heading of entity at the end of the route EndHeading : Real32 := 0.0; -- If "true" the heading value in EndHeading must be used to end the route. If not, any ending heading can be used. UseEndHeading : Boolean := True; end record; package RC_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => RouteConstraints); type RC_Seq is new RC_Sequences.Sequence; type RoutePlan is record -- ID denoting this plan corresponding with requested route constraint pair RouteID : Int64 := 0; -- Waypoints that connect the start location with the end location. Empty if only costs were requested Waypoints : WP_Seq; -- Time cost of route. If less than zero, a planning error has occurred RouteCost : Int64 := -1; -- Error messages, if applicable RouteError : KVP_Seq; end record; package RP_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => RoutePlan); type RP_Seq is new RP_Sequences.Sequence with Predicate => (for all I in 1 .. RP_Sequences.Last (RP_Sequences.Sequence (RP_Seq)) => (for all J in 1 .. RP_Sequences.Last (RP_Sequences.Sequence (RP_Seq)) => I = J or else RP_Sequences.Get (RP_Sequences.Sequence (RP_Seq), I).RouteID /= RP_Sequences.Get (RP_Sequences.Sequence (RP_Seq), J).RouteID)); -- Sequence of route plans have no duplicates function Contains (S : RP_Seq; Id : Int64) return Boolean is (for some RP of S => RP.RouteID = Id); type RouteRequest is new Message_Root with record RequestID : Int64; AssociatedTaskID : Int64; VehicleID : Int64_Seq; OperatingRegion : Int64; IsCostOnlyRequest : Boolean; RouteRequests : RC_Seq; end record; type RoutePlanRequest is new Message_Root with record RequestID : Int64 := 0; AssociatedTaskID : Int64 := 0; VehicleID : Int64 := 0; OperatingRegion : Int64 := 0; IsCostOnlyRequest : Boolean := False; RouteRequests : RC_Seq; end record; type RoutePlanResponse is new Message_Root with record ResponseID : Int64 := 0; -- Associated Task ID (0 if no associated task) that this set of responses corresponds to AssociatedTaskID : Int64 := 0; -- Vehicle that was considered during planning VehicleID : Int64 := 0; -- Operating region that was considered during planning OperatingRegion : Int64 := 0; -- List of all responses for this vehicle + operating region situation RouteResponses : RP_Seq; end record; package RPR_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => RoutePlanResponse); type RPR_Seq is new RPR_Sequences.Sequence; type RouteResponse is new Message_Root with record -- Response ID matching ID from request ({@link RouteRequest}) ResponseID : Int64 := 0; -- Corresponding route responses for all requested vehicles Routes : RPR_Seq; end record; type TaskOptionCost is new Message_Root with record -- Corresponding Vehicle ID VehicleID : Int64 := 0; -- Initial task ID (if zero, corresponds to current vehicle location) InitialTaskID : Int64 := 0; -- Initial task option InitialTaskOption : Int64 := 0; -- Destination task ID DestinationTaskID : Int64 := 0; -- Destination task option DestinationTaskOption : Int64 := 0; -- Timing corresponding to travel between ('InitialTask' using 'InitialTaskOption') and ('DestinationTask' using 'DestinationTaskOption'). If time is less than zero, no feasible path exists between tasks. TimeToGo : Int64 := 0; end record; package TOC_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => TaskOptionCost); type TOC_Seq is new TOC_Sequences.Sequence; type AssignmentCostMatrix is new Message_Root with record -- ID that matches this cost matrix with the appropriate unique automation request CorrespondingAutomationRequestID : Int64 := 0; -- Over-arching task relationship description (directly from automation request). A process algebra string with only task IDs. -- TaskLevelRelationship : Unbounded_String := To_Unbounded_String(""); -- List of all tasks that this cost matrix includes TaskList : Int64_Seq; -- Operating region that was used during matrix calculation OperatingRegion : Int64 := 0; -- Set of task-to-task timings for each requested vehicle. Assume 'T' max tasks [16], 'O' max options per task [8], 'V' max vehicles [16]: then max number of elements in matrix is 'V*T*O + (T*O)^2' [18432] CostMatrix : TOC_Seq; end record; type TaskOption is record -- Task ID TaskID : Int64 := 0; -- ID for this option OptionID : Int64 := 0; -- Eligible entities for completing this option with identical cost to complete. If list is empty, then all vehicles are assumed to be eligible. EligibleEntities : Int64_Seq; -- Cost to complete option in terms of time (given in milliseconds) Cost : Int64 := 0; -- Start location entering the option. A valid TaskOption must define StartLocation (null not allowed). StartLocation : Location3D; -- Start heading entering the option StartHeading : Real32 := 0.0; -- Ending location for this option. A valid TaskOption must define EndLocation (null not allowed). EndLocation : Location3D; -- Ending heading for this option EndHeading : Real32 := 0.0; end record; package TO_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => TaskOption); type TaskOption_Seq is new TO_Sequences.Sequence; type TaskPlanOptions is new Message_Root with record -- ID that matches this message with the appropriate unique automation request CorrespondingAutomationRequestID : Int64 := 0; -- Task ID TaskID : Int64 := 0; -- Process algebra string encoding all of the different options Composition : Unbounded_String := To_Unbounded_String (""); -- List of options. Options : TaskOption_Seq; end record; type TaskAssignment is record -- Task ID TaskID : Int64 := 0; -- Option ID that was selected for this task OptionID : Int64 := 0; -- Vehicle that is assigned to this task AssignedVehicle : Int64 := 0; -- Time before which this task cannot begin TimeThreshold : Int64 := 0; -- Time that this task is assigned to be completed. TimeTaskCompleted : Int64 := 0; end record; package TaskAssignment_Sequences is new Ada.Containers.Functional_Vectors (Index_Type => Positive, Element_Type => TaskAssignment); type TaskAssignment_Sequence is new TaskAssignment_Sequences.Sequence; type TaskAssignmentSummary is new Message_Root with record -- ID that matches this summary with the appropriate unique automation request CorrespondingAutomationRequestID : Int64 := 0; -- Operating region which was considered during this assignment OperatingRegion : Int64 := 0; -- Ordered list of tasks to be completed TaskList : TaskAssignment_Sequence; end record; end LMCP_Messages;
package Shell.Commands.Safe -- -- Allows commands to be safely run in different tasks. -- -- Requires the 'ashell_spawn_server' binary to be installed -- in a folder on the users PATH (such as /usr/bin). -- is --- Run - Block until process completes. -- procedure Run (The_Command : in out Command; Input : in Data := No_Data; Raise_Error : in Boolean := False); function Run (The_Command : in out Command; Input : in Data := No_Data; Raise_Error : in Boolean := False) return Command_Results; procedure Stop_Spawn_Client; -- -- Called at program completion to halt the spawn client task and spawn server process. end Shell.Commands.Safe;
pragma License (Unrestricted); -- implementation unit required by compiler package System.Img_WChar is pragma Pure; -- required for Wide_Character'Image by compiler (s-imgwch.ads) procedure Image_Wide_Character ( V : Wide_Character; S : in out String; P : out Natural; Ada_2005 : Boolean); -- required for Wide_Wide_Character'Image by compiler (s-imgwch.ads) procedure Image_Wide_Wide_Character ( V : Wide_Wide_Character; S : in out String; P : out Natural); -- helper Image_ad : constant String := "SOFT_HYPHEN"; end System.Img_WChar;
with Ada.Text_IO; use Ada.Text_IO; with Datastore; use Datastore; procedure Main is function Get (Prompt : String) return String is begin Put (" " & Prompt & "> "); return Get_Line; end Get; Index : Integer; begin loop Index := Integer'value (Get ("Enter index")); exit when Index not in Datastore.Index_T'range; -- Add a user-supplied string to the array at the specified index end loop; for I in Index_T'range loop -- If the object pointed to by index is not empty, -- Print each item in the list null; end loop; end Main; --Main
package body Servo_Controller is ------------ -- Engine -- ------------ task body Engine is begin loop case Engine_Servo.Current_Direction is when Forward => Servo.Write(1600, Engine_Servo.Pin); when Backward => Servo.Write(1000, Engine_Servo.Pin); when Stop => Servo.Write(1500, Engine_Servo.Pin); end case; end loop; end Engine; end Servo_Controller;
-- Generated at 2017-03-27 17:51:44 +0000 by Natools.Static_Hash_Maps -- from src/natools-web-acl-maps.sx package Natools.Static_Maps.Web.ACL is pragma Pure; type Command is (Unknown_Command, Is_In_All_Groups, Is_In_Any_Group, Is_User); function To_Command (Key : String) return Command; private Map_1_Key_0 : aliased constant String := "is-in-groups"; Map_1_Key_1 : aliased constant String := "is-in-all-groups"; Map_1_Key_2 : aliased constant String := "is-in-group"; Map_1_Key_3 : aliased constant String := "is-in-any-group"; Map_1_Key_4 : aliased constant String := "is"; Map_1_Key_5 : aliased constant String := "is-user"; Map_1_Key_6 : aliased constant String := "is-any-of"; Map_1_Keys : constant array (0 .. 6) of access constant String := (Map_1_Key_0'Access, Map_1_Key_1'Access, Map_1_Key_2'Access, Map_1_Key_3'Access, Map_1_Key_4'Access, Map_1_Key_5'Access, Map_1_Key_6'Access); Map_1_Elements : constant array (0 .. 6) of Command := (Is_In_All_Groups, Is_In_All_Groups, Is_In_Any_Group, Is_In_Any_Group, Is_User, Is_User, Is_User); end Natools.Static_Maps.Web.ACL;
-- { dg-do run } procedure Pack10 is type U16 is mod 2**16; type U8 is mod 2**8; type R is record A : U16; B : U8; end record; type M is array (1..2) of R; pragma Pack (M); -- This size clause can actually be omitted for M'Size use 48; type R2 is record C : M; D : U8; end record; for R2 use record C at 0 range 0 .. 24*2-1; end record; My_R2 : R2; begin My_R2.D := 1; My_R2.C(2).B := 0; if My_R2.D /=1 then raise Program_Error; end if; end;
------------------------------------------------------------------------------ -- -- -- GNAT EXAMPLE -- -- -- -- Copyright (C) 2013, AdaCore -- -- -- -- 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. -- -- -- -- 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 System.Machine_Code; use System.Machine_Code; with Interfaces; use Interfaces; with Ada.Text_IO; use Ada.Text_IO; with Ppc; use Ppc; with Ppc6xx; use Ppc6xx; with Commands; use Commands; pragma Warnings (Off); with System.BB.Board_Parameters; use System.BB.Board_Parameters; with System.Machine_Reset; pragma Warnings (On); package body Mpc83xx is -- Memory map: -- 0000_0000 - 00ff_ffff ( 16 MB): Ram (RWX) -- IMMRBAR ( 1 MB): IO (RW,UC) -- 0010_0000 - 001f_ffff (128 KB): SIL0 (RWX) SIL0_Addr : constant := 16#0100_0000#; -- At 16MB -- Memory map Ram_Base : constant := 16#0000_0000#; procedure Enable_MMU is begin Put_Line ("configure mmu"); -- Initialize I and D bats -- Ram Base: RWX Asm ("mtspr %0,%1", Inputs => (Unsigned_32'Asm_Input ("i", Ibat0u), Unsigned_32'Asm_Input ("r", Ram_Base or BL_16MB or Vs_Mask)), Volatile => True); Asm ("mtspr %0,%1", Inputs => (Unsigned_32'Asm_Input ("i", Ibat0l), Unsigned_32'Asm_Input ("r", Ram_Base or WIMG_CE or Pp_RO)), Volatile => True); Asm ("mtspr %0,%1", Inputs => (Unsigned_32'Asm_Input ("i", Dbat0u), Unsigned_32'Asm_Input ("r", Ram_Base or BL_32MB or Vs_Mask)), Volatile => True); Asm ("mtspr %0,%1", Inputs => (Unsigned_32'Asm_Input ("i", Dbat0l), Unsigned_32'Asm_Input ("r", Ram_Base or WIMG_WB or Pp_RW)), Volatile => True); -- IMMRBAR: RW Asm ("mtspr %0,%1", Inputs => (Unsigned_32'Asm_Input ("i", Dbat2u), Unsigned_32'Asm_Input ("r", IMMRBAR or BL_1MB or Vs_Mask)), Volatile => True); Asm ("mtspr %0,%1", Inputs => (Unsigned_32'Asm_Input ("i", Dbat2l), Unsigned_32'Asm_Input ("r", IMMRBAR or WIMG_UC or Pp_RW)), Volatile => True); -- SIL4 Asm ("mtspr %0,%1", Inputs => (Unsigned_32'Asm_Input ("i", Ibat3u), Unsigned_32'Asm_Input ("r", 0 or BL_128KB or Vp_Mask)), Volatile => True); Asm ("mtspr %0,%1", Inputs => (Unsigned_32'Asm_Input ("i", Ibat3l), Unsigned_32'Asm_Input ("r", SIL0_Addr or WIMG_CE or Pp_RO)), Volatile => True); Asm ("mtspr %0,%1", Inputs => (Unsigned_32'Asm_Input ("i", Dbat3u), Unsigned_32'Asm_Input ("r", 0 or BL_128KB or Vp_Mask)), Volatile => True); Asm ("mtspr %0,%1", Inputs => (Unsigned_32'Asm_Input ("i", Dbat3l), Unsigned_32'Asm_Input ("r", SIL0_Addr or WIMG_WB or Pp_RW)), Volatile => True); Put_Line ("Clear SR"); -- Clear SR Asm ("mtsr 0,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 1,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 2,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 3,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 4,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 5,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 6,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 7,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 8,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 9,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 10,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 11,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 12,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 13,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 14,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Asm ("mtsr 15,%0", Inputs => (Unsigned_32'Asm_Input ("r", 0)), Volatile => True); Put_Line ("Enable MMU"); -- Enable MMU declare Msr : Unsigned_32; begin Msr := Get_Msr; Msr := Msr or MSR_IR or MSR_DR; Asm ("mtmsr %0", Inputs => Unsigned_32'Asm_Input ("r", Msr), Volatile => True); Asm ("isync", Volatile => True); end; end Enable_MMU; Commands : aliased Command_List := (1, (1 => (new String'("mmu - Switch MMU on"), Enable_MMU'Access)), null); begin Register_Commands (Commands'Access); end Mpc83xx;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2018 - 2019 Joakim Strandberg <joakim@mequinox.se> -- -- 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 Wayland_XML is procedure Set_Summary (This : in out Arg_Tag; Value : String) is begin This.My_Summary := (Exists => True, Value => new String'(Value)); end Set_Summary; procedure Set_Interface_Attribute (This : in out Arg_Tag; Value : String) is begin This.My_Interface_Attribute := (Exists => True, Value => new String'(Value)); end Set_Interface_Attribute; procedure Set_Type_Attribute (This : in out Arg_Tag; Value : String) is begin if Value = "int" then This.My_Type_Attribute := (Exists => True, Value => Type_Integer); elsif Value = "uint" then This.My_Type_Attribute := (Exists => True, Value => Type_Unsigned_Integer); elsif Value = "string" then This.My_Type_Attribute := (Exists => True, Value => Type_String); elsif Value = "fd" then This.My_Type_Attribute := (Exists => True, Value => Type_FD); elsif Value = "new_id" then This.My_Type_Attribute := (Exists => True, Value => Type_New_Id); elsif Value = "object" then This.My_Type_Attribute := (Exists => True, Value => Type_Object); elsif Value = "fixed" then This.My_Type_Attribute := (Exists => True, Value => Type_Fixed); elsif Value = "array" then This.My_Type_Attribute := (Exists => True, Value => Type_Array); else raise TYPE_ATTRIBUTE_EXCEPTION with Value; end if; end Set_Type_Attribute; procedure Set_Name (This : in out Arg_Tag; Value : String) is begin This.My_Name := (Exists => True, Value => new String'(Value)); end Set_Name; procedure Set_Allow_Null (This : in out Arg_Tag; Value : Boolean) is begin This.My_Allow_Null := (Exists => True, Value => Value); end Set_Allow_Null; procedure Set_Enum (This : in out Arg_Tag; Value : String) is begin This.My_Enum := (Exists => True, Value => new String'(Value)); end Set_Enum; procedure Set_Text (This : in out Copyright_Tag; Value : String) is begin This.My_Text := (Exists => True, Value => new String'(Value)); end Set_Text; procedure Set_Text (This : in out Description_Tag; Value : String) is begin This.My_Text := (Exists => True, Value => new String'(Value)); end Set_Text; procedure Set_Summary (This : in out Description_Tag; Value : String) is begin This.My_Summary := (Exists => True, Value => new String'(Value)); end Set_Summary; procedure Set_Value (This : in out Entry_Tag; V : Entry_Value) is begin This.My_Value := (Exists => True, Value => V); end Set_Value; procedure Set_Summary (This : in out Entry_Tag; Value : String) is begin This.My_Summary := (Exists => True, Value => new String'(Value)); end Set_Summary; procedure Set_Name (This : in out Entry_Tag; Value : String) is begin This.My_Name := (Exists => True, Value => new String'(Value)); end Set_Name; procedure Set_Since (This : in out Entry_Tag; Value : Version_Number) is begin This.My_Since := (Exists => True, Value => Value); end Set_Since; procedure Set_Name (This : in out Enum_Tag; Value : String) is begin This.My_Name := (Exists => True, Value => new String'(Value)); end Set_Name; procedure Set_Bitfield (This : in out Enum_Tag; Value : Boolean) is begin This.My_Bitfield := (Exists => True, Value => Value); end Set_Bitfield; procedure Set_Since (This : in out Enum_Tag; Value : Version_Number) is begin This.My_Since := (Exists => True, Value => Value); end Set_Since; procedure Append_Child (This : in out Enum_Tag; Item : not null Wayland_XML.Description_Tag_Ptr) is Child : constant Enum_Child := (Child_Description, Item); begin This.My_Children.Append (Child); end Append_Child; procedure Append_Child (This : in out Enum_Tag; Item : not null Entry_Tag_Ptr) is Child : constant Enum_Child := (Child_Entry, Item); begin This.My_Children.Append (Child); This.My_Entries.Append (Child); end Append_Child; procedure Sort_Entries (This : in out Enum_Tag) is begin Enum_Child_Sorting.Sort (This.My_Entries); end Sort_Entries; procedure Set_Name (This : in out Event_Tag; Value : String) is begin This.My_Name := (Exists => True, Value => new String'(Value)); end Set_Name; procedure Set_Since (This : in out Event_Tag; Value : Version_Number) is begin This.My_Since_Attribute := (Exists => True, Value => Value); end Set_Since; procedure Append_Child (This : in out Event_Tag; Item : not null Wayland_XML.Description_Tag_Ptr) is C : constant Event_Child := (Child_Description, Item); begin This.My_Children.Append (C); end Append_Child; procedure Append_Child (This : in out Event_Tag; Item : not null Wayland_XML.Arg_Tag_Ptr) is C : constant Event_Child := (Child_Arg, Item); begin This.My_Children.Append (C); end Append_Child; procedure Set_Name (This : in out Request_Tag; Value : String) is begin This.My_Name := (Exists => True, Value => new String'(Value)); end Set_Name; procedure Append_Child (This : in out Request_Tag; Item : not null Description_Tag_Ptr) is C : constant Request_Child := (Child_Description, Item); begin This.My_Children.Append (C); end Append_Child; procedure Append_Child (This : in out Request_Tag; Item : not null Wayland_XML.Arg_Tag_Ptr) is C : constant Request_Child := (Child_Arg, Item); begin This.My_Children.Append (C); end Append_Child; procedure Set_Type_Attribute (This : in out Request_Tag; Value : String) is begin This.My_Type_Attribute := (Exists => True, Value => new String'(Value)); end Set_Type_Attribute; procedure Set_Since (This : in out Request_Tag; Value : Version_Number) is begin This.My_Since := (Exists => True, Value => Value); end Set_Since; function Exists_Description (This : aliased Request_Tag) return Boolean is N : Natural := 0; begin for Child of Children (This) loop if Child.Kind_Id = Child_Description and then Exists_Text (Child.Description_Tag.all) then N := N + 1; end if; end loop; return N = 1; end Exists_Description; function Description (This : aliased Request_Tag) return String is begin for Child of Children (This) loop if Child.Kind_Id = Child_Description then return Text (Child.Description_Tag.all); end if; end loop; raise Program_Error; end Description; function Exists_Events (This : aliased Interface_Tag) return Boolean is (for some Child of Children (This) => Child.Kind_Id = Child_Event); procedure Set_Name (This : in out Interface_Tag; Value : String) is begin This.My_Name := (Exists => True, Value => new String'(Value)); end Set_Name; procedure Set_Version (This : in out Interface_Tag; Value : Version_Number) is begin This.My_Version := (Exists => True, Value => Value); end Set_Version; procedure Append_Child (This : in out Interface_Tag; Item : not null Description_Tag_Ptr) is C : constant Interface_Child := (Child_Description, Item); begin This.My_Children.Append (C); end Append_Child; procedure Append_Child (This : in out Interface_Tag; Item : not null Request_Tag_Ptr) is C : constant Interface_Child := (Child_Request, Item); begin This.My_Children.Append (C); end Append_Child; procedure Append_Child (This : in out Interface_Tag; Item : not null Event_Tag_Ptr) is C : constant Interface_Child := (Child_Event, Item); begin This.My_Children.Append (C); end Append_Child; procedure Append_Child (This : in out Interface_Tag; Item : not null Enum_Tag_Ptr) is C : constant Interface_Child := (Child_Enum, Item); begin This.My_Children.Append (C); end Append_Child; procedure Set_Name (This : in out Protocol_Tag; Value : String) is begin This.My_Name := (Exists => True, Value => new String'(Value)); end Set_Name; procedure Append_Child (This : in out Protocol_Tag; Item : not null Wayland_XML.Copyright_Ptr) is C : constant Protocol_Child := (Kind_Id => Child_Copyright, Copyright_Tag => Item); begin This.My_Children.Append (C); end Append_Child; procedure Append_Child (This : in out Protocol_Tag; Item : not null Interface_Tag_Ptr) is C : constant Protocol_Child := (Kind_Id => Child_Interface, Interface_Tag => Item); begin This.My_Children.Append (C); end Append_Child; procedure Append_Child (This : in out Protocol_Tag; Item : not null Description_Tag_Ptr) is C : constant Protocol_Child := (Kind_Id => Child_Description, Description_Tag => Item); begin This.My_Children.Append (C); end Append_Child; end Wayland_XML;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . B B . E X E C U T I O N _ T I M E -- -- -- -- B o d y -- -- -- -- Copyright (C) 2011-2014, 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 3, 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. -- -- -- -- -- -- -- -- -- -- -- -- 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/>. -- -- -- ------------------------------------------------------------------------------ with System.BB.Parameters; with System.BB.Board_Support; with System.BB.Threads.Queues; with System.BB.Protection; with System.Multiprocessors; with System.Multiprocessors.Fair_Locks; with System.Multiprocessors.Spin_Locks; with System.OS_Interface; ------------------------------ -- System.BB.Execution_Time -- ------------------------------ package body System.BB.Execution_Time is use type System.BB.Time.Time; use System.BB.Interrupts; use System.BB.Threads; use System.Multiprocessors; use System.Multiprocessors.Fair_Locks; use System.Multiprocessors.Spin_Locks; Interrupts_Execution_Time : array (Interrupt_ID) of System.BB.Time.Time := (others => System.BB.Time.Time'First); -- Time counter for each interrupt Interrupt_Exec_Time_Lock : Fair_Lock := (Spinning => (others => False), Lock => (Flag => Unlocked)); -- Protect access to interrupt time counters on multiprocessor systems CPU_Clock : array (CPU) of System.BB.Time.Time; -- Date of the last Interrupt Disabled : array (CPU) of Boolean := (1 => False, others => True); -- If the CPU clock is disabled the next elapsed time will be discarded (to -- handle CPU idle time). At the start, only the first CPU is enabled. procedure Disable_Execution_Time; -- Disable the CPU clock of the current processor. The clock remains -- disabled until the next call to Scheduling_Event. procedure Scheduling_Event; -- Assign elapsed time to the executing Task/Interrupt and reset CPU clock. -- If the clock is disabled, the elapsed time is discarded and the clock -- re-enabled. This must be called at the end of an execution period: -- -- When the run-time switches from a task to another task -- a task to an interrupt -- an interrupt to a task -- an interrupt to another interrupt -- and before an idle loop. function Elapsed_Time return System.BB.Time.Time; -- Function returning the time elapsed since the last scheduling event, -- i.e. the execution time of the currently executing entity (thread or -- interrupt) that has not yet been added to the global counters. function Read_Execution_Time_Atomic (Th : System.BB.Threads.Thread_Id) return System.BB.Time.Time; -- Read the execution time of thread Th. The result is a coherent value: -- if the execution time has changed from A to B (while being read by this -- function), the result will be between A and B. The error is less -- than 2**32 and less than the increment. function To_Time (High, Low : Time.Word) return Time.Time; -- Low level routine to convert a composite execution time to type Time function To_Composite_Execution_Time (T : Time.Time) return Time.Composite_Execution_Time; -- Low level routine to convert a time to a composite execution time ---------------------------- -- Disable_Execution_Time -- ---------------------------- procedure Disable_Execution_Time is CPU_Id : constant CPU := System.OS_Interface.Current_CPU; begin Disabled (CPU_Id) := True; end Disable_Execution_Time; ------------------ -- Elapsed_Time -- ------------------ function Elapsed_Time return System.BB.Time.Time is CPU_Id : constant CPU := System.OS_Interface.Current_CPU; pragma Assert (not Disabled (CPU_Id)); -- As the thread or interrupt handler is executing, the execution time -- accounting must not be disabled (it is disabled only while in the -- idle loop when neither threads nor interrupts execute). Now : constant BB.Time.Time := System.BB.Time.Clock; pragma Assert (Now >= CPU_Clock (CPU_Id)); begin return Now - CPU_Clock (CPU_Id); end Elapsed_Time; ---------------------------- -- Global_Interrupt_Clock -- ---------------------------- function Global_Interrupt_Clock return System.BB.Time.Time is Sum : System.BB.Time.Time := System.BB.Time.Time'First; begin -- Protect shared access on multiprocessor systems if System.BB.Parameters.Multiprocessor then Lock (Interrupt_Exec_Time_Lock); end if; for Interrupt in Interrupt_ID loop Sum := Sum + Interrupts_Execution_Time (Interrupt); end loop; -- If any interrupt is executing, we need to add the elapsed time -- between the last scheduling and now. if System.BB.Interrupts.Current_Interrupt /= No_Interrupt then Sum := Sum + Elapsed_Time; end if; if System.BB.Parameters.Multiprocessor then Unlock (Interrupt_Exec_Time_Lock); end if; return Sum; end Global_Interrupt_Clock; --------------------- -- Interrupt_Clock -- --------------------- function Interrupt_Clock (Interrupt : Interrupt_ID) return System.BB.Time.Time is Value : System.BB.Time.Time; begin -- Protect against interruption the addition between Execution_Time -- and Elapsed_Time. System.BB.Protection.Enter_Kernel; -- Protect shared access on multiprocessor systems if System.BB.Parameters.Multiprocessor then Lock (Interrupt_Exec_Time_Lock); end if; Value := Interrupts_Execution_Time (Interrupt); -- If the interrupt is executing (i.e., if we are requesting the -- interrupt clock from the interrupt handler), we need to add the -- elapsed time between the last scheduling and now. if System.BB.Interrupts.Current_Interrupt = Interrupt then Value := Value + Elapsed_Time; end if; if System.BB.Parameters.Multiprocessor then Unlock (Interrupt_Exec_Time_Lock); end if; System.BB.Protection.Leave_Kernel; return Value; end Interrupt_Clock; -------------------------------- -- Read_Execution_Time_Atomic -- -------------------------------- function Read_Execution_Time_Atomic (Th : System.BB.Threads.Thread_Id) return System.BB.Time.Time is use Time; H1 : Word; L : Word; H2 : Word; begin -- Read parts in that order H1 := Th.Execution_Time.High; L := Th.Execution_Time.Low; H2 := Th.Execution_Time.High; -- If value has changed while being read, keep the latest high part, -- but use 0 for the low part. So the result will be greater than -- the old value and less than the new value. if H1 /= H2 then L := 0; end if; return Time.Time (H2) * 2 ** 32 + Time.Time (L); end Read_Execution_Time_Atomic; ---------------------- -- Scheduling_Event -- ---------------------- procedure Scheduling_Event is Now : constant System.BB.Time.Time := System.BB.Time.Clock; CPU_Id : constant CPU := System.OS_Interface.Current_CPU; Last_CPU_Clock : constant System.BB.Time.Time := CPU_Clock (CPU_Id); Elapsed_Time : System.BB.Time.Time; begin pragma Assert (Now >= Last_CPU_Clock); Elapsed_Time := Now - Last_CPU_Clock; -- Reset the clock CPU_Clock (CPU_Id) := Now; if Disabled (CPU_Id) then -- Discard the elapsed time and re-enable the clock Disabled (CPU_Id) := False; return; end if; -- Case of CPU currently executing an interrupt if Current_Interrupt /= No_Interrupt then -- Protect shared access on multiprocessor systems if System.BB.Parameters.Multiprocessor then Lock (Interrupt_Exec_Time_Lock); end if; Interrupts_Execution_Time (Current_Interrupt) := Interrupts_Execution_Time (Current_Interrupt) + Elapsed_Time; if System.BB.Parameters.Multiprocessor then Unlock (Interrupt_Exec_Time_Lock); end if; -- This CPU is currently executing a task else declare T : Time.Time; begin T := To_Time (Thread_Self.Execution_Time.High, Thread_Self.Execution_Time.Low); T := T + Elapsed_Time; Thread_Self.Execution_Time := To_Composite_Execution_Time (T); end; end if; end Scheduling_Event; ------------------ -- Thread_Clock -- ------------------ function Thread_Clock (Th : System.BB.Threads.Thread_Id) return System.BB.Time.Time is Res : System.BB.Time.Time; Sec : System.BB.Time.Time; -- Second read of execution time ET : System.BB.Time.Time; -- Elapsed time begin pragma Assert (Th /= Null_Thread_Id); Res := Read_Execution_Time_Atomic (Th); -- If the thread Th is running, we need to add the elapsed time between -- the last scheduling and now. The thread Th is running if it is the -- current one and no interrupt is executed if Th = Thread_Self and then System.BB.Interrupts.Current_Interrupt = No_Interrupt then ET := Elapsed_Time; Sec := Read_Execution_Time_Atomic (Th); if Res /= Sec then -- The whole set of values (Res, ET and Sec) isn't coherent, as -- the execution time has been updated (might happen in case of -- interrupt). Unfortunately, the error in Sec might be as large -- as ET. So lets read again. The error will be small, as the time -- spent between this third read and the second one is small. Res := Read_Execution_Time_Atomic (Th); else Res := Res + ET; end if; end if; return Res; end Thread_Clock; --------------------------------- -- To_Composite_Execution_Time -- --------------------------------- function To_Composite_Execution_Time (T : Time.Time) return Time.Composite_Execution_Time is begin return (High => Time.Word (T / 2 ** 32), Low => Time.Word (T mod 2 ** 32)); end To_Composite_Execution_Time; ------------- -- To_Time -- ------------- function To_Time (High, Low : Time.Word) return Time.Time is begin return Time.Time (High) * 2 ** 32 + Time.Time (Low); end To_Time; begin -- Set the hooks to enable computation System.BB.Time.Scheduling_Event_Hook := Scheduling_Event'Access; System.BB.Time.Disable_Execution_Time_Hook := Disable_Execution_Time'Access; -- Initialize CPU_Clock declare Now : constant BB.Time.Time := System.BB.Time.Clock; -- ??? Clock is called before timer initialization begin CPU_Clock := (others => Now); end; end System.BB.Execution_Time;
with interfaces.c.strings; package body agar.gui.surface is package cs renames interfaces.c.strings; package cbinds is function allocate (width : c.int; height : c.int; format : agar.gui.pixelformat.pixel_format_access_t; flags : flags_t) return surface_access_t; pragma import (c, allocate, "AG_SurfaceNew"); function std_rgb (width : c.unsigned; height : c.unsigned) return surface_access_t; pragma import (c, std_rgb, "agar_surface_std_rgb"); function std_rgba (width : c.unsigned; height : c.unsigned) return surface_access_t; pragma import (c, std_rgba, "agar_surface_std_rgba"); function indexed (width : c.unsigned; height : c.unsigned; bits_per_pixel : c.int; flags : flags_t) return surface_access_t; pragma import (c, indexed, "AG_SurfaceIndexed"); function rgb (width : c.unsigned; height : c.unsigned; bits_per_pixel : c.int; flags : flags_t; rmask : agar.core.types.uint32_t; gmask : agar.core.types.uint32_t; bmask : agar.core.types.uint32_t) return surface_access_t; pragma import (c, rgb, "AG_SurfaceRGB"); function rgba (width : c.unsigned; height : c.unsigned; bits_per_pixel : c.int; flags : flags_t; rmask : agar.core.types.uint32_t; gmask : agar.core.types.uint32_t; bmask : agar.core.types.uint32_t; amask : agar.core.types.uint32_t) return surface_access_t; pragma import (c, rgba, "AG_SurfaceRGBA"); function from_pixels_rgb (pixels : agar.core.types.void_ptr_t; width : c.unsigned; height : c.unsigned; bits_per_pixel : c.int; flags : flags_t; rmask : agar.core.types.uint32_t; gmask : agar.core.types.uint32_t; bmask : agar.core.types.uint32_t) return surface_access_t; pragma import (c, from_pixels_rgb, "AG_SurfaceFromPixelsRGB"); function from_pixels_rgba (pixels : agar.core.types.void_ptr_t; width : c.unsigned; height : c.unsigned; bits_per_pixel : c.int; flags : flags_t; rmask : agar.core.types.uint32_t; gmask : agar.core.types.uint32_t; bmask : agar.core.types.uint32_t; amask : agar.core.types.uint32_t) return surface_access_t; pragma import (c, from_pixels_rgba, "AG_SurfaceFromPixelsRGBA"); function from_bmp (file : cs.chars_ptr) return surface_access_t; pragma import (c, from_bmp, "AG_SurfaceFromBMP"); end cbinds; function allocate (width : positive; height : positive; format : agar.gui.pixelformat.pixel_format_access_t; flags : flags_t) return surface_access_t is begin return cbinds.allocate (width => c.int (width), height => c.int (height), format => format, flags => flags); end allocate; function std_rgb (width : positive; height : positive) return surface_access_t is begin return cbinds.std_rgb (width => c.unsigned (width), height => c.unsigned (height)); end std_rgb; function std_rgba (width : positive; height : positive) return surface_access_t is begin return cbinds.std_rgba (width => c.unsigned (width), height => c.unsigned (height)); end std_rgba; function indexed (width : positive; height : positive; bits_per_pixel : positive; flags : flags_t) return surface_access_t is begin return cbinds.indexed (width => c.unsigned (width), height => c.unsigned (height), bits_per_pixel => c.int (bits_per_pixel), flags => flags); end indexed; function rgb (width : positive; height : positive; bits_per_pixel : positive; flags : flags_t; rmask : agar.core.types.uint32_t; gmask : agar.core.types.uint32_t; bmask : agar.core.types.uint32_t) return surface_access_t is begin return cbinds.rgb (width => c.unsigned (width), height => c.unsigned (height), bits_per_pixel => c.int (bits_per_pixel), flags => flags, rmask => rmask, gmask => gmask, bmask => bmask); end rgb; function rgba (width : positive; height : positive; bits_per_pixel : positive; flags : flags_t; rmask : agar.core.types.uint32_t; gmask : agar.core.types.uint32_t; bmask : agar.core.types.uint32_t; amask : agar.core.types.uint32_t) return surface_access_t is begin return cbinds.rgba (width => c.unsigned (width), height => c.unsigned (height), bits_per_pixel => c.int (bits_per_pixel), flags => flags, rmask => rmask, gmask => gmask, bmask => bmask, amask => amask); end rgba; function from_pixels_rgb (pixels : agar.core.types.void_ptr_t; width : positive; height : positive; bits_per_pixel : positive; flags : flags_t; rmask : agar.core.types.uint32_t; gmask : agar.core.types.uint32_t; bmask : agar.core.types.uint32_t) return surface_access_t is begin return cbinds.from_pixels_rgb (pixels => pixels, width => c.unsigned (width), height => c.unsigned (height), bits_per_pixel => c.int (bits_per_pixel), flags => flags, rmask => rmask, gmask => gmask, bmask => bmask); end from_pixels_rgb; function from_pixels_rgba (pixels : agar.core.types.void_ptr_t; width : positive; height : positive; bits_per_pixel : positive; flags : flags_t; rmask : agar.core.types.uint32_t; gmask : agar.core.types.uint32_t; bmask : agar.core.types.uint32_t; amask : agar.core.types.uint32_t) return surface_access_t is begin return cbinds.from_pixels_rgba (pixels => pixels, width => c.unsigned (width), height => c.unsigned (height), bits_per_pixel => c.int (bits_per_pixel), flags => flags, rmask => rmask, gmask => gmask, bmask => bmask, amask => amask); end from_pixels_rgba; function from_bmp (file : string) return surface_access_t is ca_file : aliased c.char_array := c.to_c (file); begin return cbinds.from_bmp (cs.to_chars_ptr (ca_file'unchecked_access)); end from_bmp; end agar.gui.surface;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- M A K E U T L -- -- -- -- S p e c -- -- -- -- Copyright (C) 2004-2015, 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 various subprograms used by the builders, in -- particular those subprograms related to project management and build -- queue management. with ALI; with Namet; use Namet; with Opt; with Osint; with Prj; use Prj; with Prj.Tree; with Snames; use Snames; with Table; with Types; use Types; with GNAT.OS_Lib; use GNAT.OS_Lib; package Makeutl is type Fail_Proc is access procedure (S : String); -- Pointer to procedure which outputs a failure message Root_Environment : Prj.Tree.Environment; -- The environment coming from environment variables and command line -- switches. When we do not have an aggregate project, this is used for -- parsing the project tree. When we have an aggregate project, this is -- used to parse the aggregate project; the latter then generates another -- environment (with additional external values and project path) to parse -- the aggregated projects. Default_Config_Name : constant String := "default.cgpr"; -- Name of the configuration file used by gprbuild and generated by -- gprconfig by default. On_Windows : constant Boolean := Directory_Separator = '\'; -- True when on Windows Source_Info_Option : constant String := "--source-info="; -- Switch to indicate the source info file Subdirs_Option : constant String := "--subdirs="; -- Switch used to indicate that the real directories (object, exec, -- library, ...) are subdirectories of those in the project file. Relocate_Build_Tree_Option : constant String := "--relocate-build-tree"; -- Switch to build out-of-tree. In this context the object, exec and -- library directories are relocated to the current working directory -- or the directory specified as parameter to this option. Root_Dir_Option : constant String := "--root-dir"; -- The root directory under which all artifacts (objects, library, ali) -- directory are to be found for the current compilation. This directory -- will be used to relocate artifacts based on this directory. If this -- option is not specificed the default value is the directory of the -- main project. Unchecked_Shared_Lib_Imports : constant String := "--unchecked-shared-lib-imports"; -- Command line switch to allow shared library projects to import projects -- that are not shared library projects. Single_Compile_Per_Obj_Dir_Switch : constant String := "--single-compile-per-obj-dir"; -- Switch to forbid simultaneous compilations for the same object directory -- when project files are used. Create_Map_File_Switch : constant String := "--create-map-file"; -- Switch to create a map file when an executable is linked No_Exit_Message_Option : constant String := "--no-exit-message"; -- Switch to suppress exit error message when there are compilation -- failures. This is useful when a tool, such as gnatprove, silently calls -- the builder and does not want to pollute its output with error messages -- coming from the builder. This is an internal switch. Keep_Temp_Files_Option : constant String := "--keep-temp-files"; -- Switch to suppress deletion of temp files created by the builder. -- Note that debug switch -gnatdn also has this effect. Load_Standard_Base : Boolean := True; -- False when gprbuild is called with --db- package Db_Switch_Args is new Table.Table (Table_Component_Type => Name_Id, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 200, Table_Increment => 100, Table_Name => "Makegpr.Db_Switch_Args"); -- Table of all the arguments of --db switches of gprbuild package Directories is new Table.Table (Table_Component_Type => Path_Name_Type, Table_Index_Type => Integer, Table_Low_Bound => 1, Table_Initial => 200, Table_Increment => 100, Table_Name => "Makegpr.Directories"); -- Table of all the source or object directories, filled up by -- Get_Directories. procedure Add (Option : String_Access; To : in out String_List_Access; Last : in out Natural); procedure Add (Option : String; To : in out String_List_Access; Last : in out Natural); -- Add a string to a list of strings function Absolute_Path (Path : Path_Name_Type; Project : Project_Id) return String; -- Returns an absolute path for a configuration pragmas file function Create_Binder_Mapping_File (Project_Tree : Project_Tree_Ref) return Path_Name_Type; -- Create a binder mapping file and returns its path name function Create_Name (Name : String) return File_Name_Type; function Create_Name (Name : String) return Name_Id; function Create_Name (Name : String) return Path_Name_Type; -- Get an id for a name function Base_Name_Index_For (Main : String; Main_Index : Int; Index_Separator : Character) return File_Name_Type; -- Returns the base name of Main, without the extension, followed by the -- Index_Separator followed by the Main_Index if it is non-zero. function Executable_Prefix_Path return String; -- Return the absolute path parent directory of the directory where the -- current executable resides, if its directory is named "bin", otherwise -- return an empty string. When a directory is returned, it is guaranteed -- to end with a directory separator. procedure Inform (N : Name_Id := No_Name; Msg : String); procedure Inform (N : File_Name_Type; Msg : String); -- Prints out the program name followed by a colon, N and S function File_Not_A_Source_Of (Project_Tree : Project_Tree_Ref; Uname : Name_Id; Sfile : File_Name_Type) return Boolean; -- Check that file name Sfile is one of the source of unit Uname. Returns -- True if the unit is in one of the project file, but the file name is not -- one of its source. Returns False otherwise. function Check_Source_Info_In_ALI (The_ALI : ALI.ALI_Id; Tree : Project_Tree_Ref) return Name_Id; -- Check whether all file references in ALI are still valid (i.e. the -- source files are still associated with the same units). Return the name -- of the unit if everything is still valid. Return No_Name otherwise. procedure Ensure_Absolute_Path (Switch : in out String_Access; Parent : String; Do_Fail : Fail_Proc; For_Gnatbind : Boolean := False; Including_Non_Switch : Boolean := True; Including_RTS : Boolean := False); -- Do nothing if Switch is an absolute path switch. If relative, fail if -- Parent is the empty string, otherwise prepend the path with Parent. This -- subprogram is only used when using project files. If For_Gnatbind is -- True, consider gnatbind specific syntax for -L (not a path, left -- unchanged) and -A (path is optional, preceded with "=" if present). -- If Including_RTS is True, process also switches --RTS=. Do_Fail is -- called in case of error. Using Osint.Fail might be appropriate. function Is_Subunit (Source : Source_Id) return Boolean; -- Return True if source is a subunit procedure Initialize_Source_Record (Source : Source_Id); -- Get information either about the source file, or the object and -- dependency file, as well as their timestamps. function Is_External_Assignment (Env : Prj.Tree.Environment; Argv : String) return Boolean; -- Verify that an external assignment switch is syntactically correct -- -- Correct forms are: -- -- -Xname=value -- -X"name=other value" -- -- Assumptions: 'First = 1, Argv (1 .. 2) = "-X" -- -- When this function returns True, the external assignment has been -- entered by a call to Prj.Ext.Add, so that in a project file, External -- ("name") will return "value". type Name_Ids is array (Positive range <>) of Name_Id; No_Names : constant Name_Ids := (1 .. 0 => No_Name); -- Name_Ids is used for list of language names in procedure Get_Directories -- below. Ada_Only : constant Name_Ids := (1 => Name_Ada); -- Used to invoke Get_Directories in gnatmake type Activity_Type is (Compilation, Executable_Binding, SAL_Binding); procedure Get_Directories (Project_Tree : Project_Tree_Ref; For_Project : Project_Id; Activity : Activity_Type; Languages : Name_Ids); -- Put in table Directories the source (when Sources is True) or -- object/library (when Sources is False) directories of project -- For_Project and of all the project it imports directly or indirectly. -- The source directories of imported projects are only included if one -- of the declared languages is in the list Languages. function Aggregate_Libraries_In (Tree : Project_Tree_Ref) return Boolean; -- Return True iff there is one or more aggregate library projects in -- the project tree Tree. procedure Write_Path_File (FD : File_Descriptor); -- Write in the specified open path file the directories in table -- Directories, then closed the path file. procedure Get_Switches (Source : Source_Id; Pkg_Name : Name_Id; Project_Tree : Project_Tree_Ref; Value : out Variable_Value; Is_Default : out Boolean); procedure Get_Switches (Source_File : File_Name_Type; Source_Lang : Name_Id; Source_Prj : Project_Id; Pkg_Name : Name_Id; Project_Tree : Project_Tree_Ref; Value : out Variable_Value; Is_Default : out Boolean; Test_Without_Suffix : Boolean := False; Check_ALI_Suffix : Boolean := False); -- Compute the switches (Compilation switches for instance) for the given -- file. This checks various attributes to see if there are file specific -- switches, or else defaults on the switches for the corresponding -- language. Is_Default is set to False if there were file-specific -- switches. Source_File can be set to No_File to force retrieval of the -- default switches. If Test_Without_Suffix is True, and there is no "for -- Switches(Source_File) use", then this procedure also tests without the -- extension of the filename. If Test_Without_Suffix is True and -- Check_ALI_Suffix is True, then we also replace the file extension with -- ".ali" when testing. function Linker_Options_Switches (Project : Project_Id; Do_Fail : Fail_Proc; In_Tree : Project_Tree_Ref) return String_List; -- Collect the options specified in the Linker'Linker_Options attributes -- of project Project, in project tree In_Tree, and in the projects that -- it imports directly or indirectly, and returns the result. function Path_Or_File_Name (Path : Path_Name_Type) return String; -- Returns a file name if -df is used, otherwise return a path name function Unit_Index_Of (ALI_File : File_Name_Type) return Int; -- Find the index of a unit in a source file. Return zero if the file is -- not a multi-unit source file. procedure Verbose_Msg (N1 : Name_Id; S1 : String; N2 : Name_Id := No_Name; S2 : String := ""; Prefix : String := " -> "; Minimum_Verbosity : Opt.Verbosity_Level_Type := Opt.Low); procedure Verbose_Msg (N1 : File_Name_Type; S1 : String; N2 : File_Name_Type := No_File; S2 : String := ""; Prefix : String := " -> "; Minimum_Verbosity : Opt.Verbosity_Level_Type := Opt.Low); -- If the verbose flag (Verbose_Mode) is set and the verbosity level is at -- least equal to Minimum_Verbosity, then print Prefix to standard output -- followed by N1 and S1. If N2 /= No_Name then N2 is printed after S1. S2 -- is printed last. Both N1 and N2 are printed in quotation marks. The two -- forms differ only in taking Name_Id or File_Name_Type arguments. ------------------------- -- Program termination -- ------------------------- procedure Fail_Program (Project_Tree : Project_Tree_Ref; S : String; Flush_Messages : Boolean := True); -- Terminate program with a message and a fatal status code procedure Finish_Program (Project_Tree : Project_Tree_Ref; Exit_Code : Osint.Exit_Code_Type := Osint.E_Success; S : String := ""); -- Terminate program, with or without a message, setting the status code -- according to Fatal. This properly removes all temporary files. -------------- -- Switches -- -------------- generic with function Add_Switch (Switch : String; For_Lang : Name_Id; For_Builder : Boolean; Has_Global_Compilation_Switches : Boolean) return Boolean; -- For_Builder is true if we have a builder switch. This function -- should return True in case of success (the switch is valid), -- False otherwise. The error message will be displayed by -- Compute_Builder_Switches itself. -- -- Has_Global_Compilation_Switches is True if the attribute -- Global_Compilation_Switches is defined in the project. procedure Compute_Builder_Switches (Project_Tree : Project_Tree_Ref; Env : in out Prj.Tree.Environment; Main_Project : Project_Id; Only_For_Lang : Name_Id := No_Name); -- Compute the builder switches and global compilation switches. Every time -- a switch is found in the project, it is passed to Add_Switch. You can -- provide a value for Only_For_Lang so that we only look for this language -- when parsing the global compilation switches. ----------------------- -- Project_Tree data -- ----------------------- -- The following types are specific to builders, and associated with each -- of the loaded project trees. type Binding_Data_Record; type Binding_Data is access Binding_Data_Record; type Binding_Data_Record is record Language : Language_Ptr; Language_Name : Name_Id; Binder_Driver_Name : File_Name_Type; Binder_Driver_Path : String_Access; Binder_Prefix : Name_Id; Next : Binding_Data; end record; -- Data for a language that have a binder driver type Builder_Project_Tree_Data is new Project_Tree_Appdata with record Binding : Binding_Data; There_Are_Binder_Drivers : Boolean := False; -- True when there is a binder driver. Set by Get_Configuration when -- an attribute Language_Processing'Binder_Driver is declared. -- Reset to False if there are no sources of the languages with binder -- drivers. Number_Of_Mains : Natural := 0; -- Number of main units in this project tree Closure_Needed : Boolean := False; -- If True, we need to add the closure of the file we just compiled to -- the queue. If False, it is assumed that all files are already on the -- queue so we do not waste time computing the closure. Need_Compilation : Boolean := True; Need_Binding : Boolean := True; Need_Linking : Boolean := True; -- Which of the compilation phases are needed for this project tree end record; type Builder_Data_Access is access all Builder_Project_Tree_Data; procedure Free (Data : in out Builder_Project_Tree_Data); -- Free all memory allocated for Data function Builder_Data (Tree : Project_Tree_Ref) return Builder_Data_Access; -- Return (allocate if needed) tree-specific data procedure Compute_Compilation_Phases (Tree : Project_Tree_Ref; Root_Project : Project_Id; Option_Unique_Compile : Boolean := False; -- Was "-u" specified ? Option_Compile_Only : Boolean := False; -- Was "-c" specified ? Option_Bind_Only : Boolean := False; Option_Link_Only : Boolean := False); -- Compute which compilation phases will be needed for Tree. This also does -- the computation for aggregated trees. This also check whether we'll need -- to check the closure of the files we have just compiled to add them to -- the queue. ----------- -- Mains -- ----------- -- Package Mains is used to store the mains specified on the command line -- and to retrieve them when a project file is used, to verify that the -- files exist and that they belong to a project file. -- Mains are stored in a table. An index is used to retrieve the mains -- from the table. type Main_Info is record File : File_Name_Type; -- Always canonical casing Index : Int := 0; Location : Source_Ptr := No_Location; Source : Prj.Source_Id := No_Source; Project : Project_Id; Tree : Project_Tree_Ref; end record; No_Main_Info : constant Main_Info := (No_File, 0, No_Location, No_Source, No_Project, null); package Mains is procedure Add_Main (Name : String; Index : Int := 0; Location : Source_Ptr := No_Location; Project : Project_Id := No_Project; Tree : Project_Tree_Ref := null); -- Add one main to the table. This is in general used to add the main -- files specified on the command line. Index is used for multi-unit -- source files, and indicates which unit in the source is concerned. -- Location is the location within the project file (if a project file -- is used). Project and Tree indicate to which project the main should -- belong. In particular, for aggregate projects, this isn't necessarily -- the main project tree. These can be set to No_Project and null when -- not using projects. procedure Delete; -- Empty the table procedure Reset; -- Reset the cursor to the beginning of the table procedure Set_Multi_Unit_Index (Project_Tree : Project_Tree_Ref := null; Index : Int := 0); -- If a single main file was defined, this subprogram indicates which -- unit inside it is the main (case of a multi-unit source files). -- Errors are raised if zero or more than one main file was defined, -- and Index is non-zaero. This subprogram is used for the handling -- of the command line switch. function Next_Main return String; function Next_Main return Main_Info; -- Moves the cursor forward and returns the new current entry. Returns -- No_Main_Info there are no more mains in the table. function Number_Of_Mains (Tree : Project_Tree_Ref) return Natural; -- Returns the number of mains in this project tree (if Tree is null, it -- returns the total number of project trees). procedure Fill_From_Project (Root_Project : Project_Id; Project_Tree : Project_Tree_Ref); -- If no main was already added (presumably from the command line), add -- the main units from root_project (or in the case of an aggregate -- project from all the aggregated projects). procedure Complete_Mains (Flags : Processing_Flags; Root_Project : Project_Id; Project_Tree : Project_Tree_Ref); -- If some main units were already added from the command line, check -- that they all belong to the root project, and that they are full -- paths rather than (partial) base names (e.g. no body suffix was -- specified). end Mains; ----------- -- Queue -- ----------- type Source_Info_Format is (Format_Gprbuild, Format_Gnatmake); package Queue is -- The queue of sources to be checked for compilation. There can be a -- single such queue per application. type Source_Info (Format : Source_Info_Format := Format_Gprbuild) is record case Format is when Format_Gprbuild => Tree : Project_Tree_Ref := No_Project_Tree; Id : Source_Id := No_Source; Closure : Boolean := False; when Format_Gnatmake => File : File_Name_Type := No_File; Unit : Unit_Name_Type := No_Unit_Name; Index : Int := 0; Project : Project_Id := No_Project; Sid : Source_Id := No_Source; end case; end record; -- Information about files stored in the queue. The exact information -- depends on the builder, and in particular whether it only supports -- project-based files (in which case we have a full Source_Id record). No_Source_Info : constant Source_Info := (Format_Gprbuild, null, null, False); procedure Initialize (Queue_Per_Obj_Dir : Boolean; Force : Boolean := False); -- Initialize the queue -- -- Queue_Per_Obj_Dir matches the --single-compile-per-obj-dir switch: -- when True, there cannot be simultaneous compilations with the object -- files in the same object directory when project files are used. -- -- Nothing is done if Force is False and the queue was already -- initialized. procedure Remove_Marks; -- Remove all marks set for the files. This means that the files will be -- handed to the compiler if they are added to the queue, and is mostly -- useful when recompiling several executables in non-project mode, as -- the switches may be different and -s may be in use. function Is_Empty return Boolean; -- Returns True if the queue is empty function Is_Virtually_Empty return Boolean; -- Returns True if queue is empty or if all object directories are busy procedure Insert (Source : Source_Info; With_Roots : Boolean := False); function Insert (Source : Source_Info; With_Roots : Boolean := False) return Boolean; -- Insert source in the queue. The second version returns False if the -- Source was already marked in the queue. If With_Roots is True and the -- source is in Format_Gprbuild mode (ie with a project), this procedure -- also includes the "Roots" for this main, ie all the other files that -- must be included in the library or binary (in particular to combine -- Ada and C files connected through pragma Export/Import). When the -- roots are computed, they are also stored in the corresponding -- Source_Id for later reuse by the binder. procedure Insert_Project_Sources (Project : Project_Id; Project_Tree : Project_Tree_Ref; All_Projects : Boolean; Unique_Compile : Boolean); -- Insert all the compilable sources of the project in the queue. If -- All_Project is true, then all sources from imported projects are also -- inserted. Unique_Compile should be true if "-u" was specified on the -- command line: if True and some files were given on the command line), -- only those files will be compiled (so Insert_Project_Sources will do -- nothing). If True and no file was specified on the command line, all -- files of the project(s) will be compiled. This procedure also -- processed aggregated projects. procedure Insert_Withed_Sources_For (The_ALI : ALI.ALI_Id; Project_Tree : Project_Tree_Ref; Excluding_Shared_SALs : Boolean := False); -- Insert in the queue those sources withed by The_ALI, if there are not -- already in the queue and Only_Interfaces is False or they are part of -- the interfaces of their project. procedure Extract (Found : out Boolean; Source : out Source_Info); -- Get the first source that can be compiled from the queue. If no -- source may be compiled, sets Found to False. In this case, the value -- for Source is undefined. function Size return Natural; -- Return the total size of the queue, including the sources already -- extracted. function Processed return Natural; -- Return the number of source in the queue that have aready been -- processed. procedure Set_Obj_Dir_Busy (Obj_Dir : Path_Name_Type); procedure Set_Obj_Dir_Free (Obj_Dir : Path_Name_Type); -- Mark Obj_Dir as busy or free (see the parameter to Initialize) function Element (Rank : Positive) return File_Name_Type; -- Get the file name for element of index Rank in the queue end Queue; end Makeutl;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- ADA.NUMERICS.GENERIC_COMPLEX_ELEMENTARY_FUNCTIONS -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2019, 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 Ada.Numerics.Generic_Elementary_Functions; package body Ada.Numerics.Generic_Complex_Elementary_Functions is package Elementary_Functions is new Ada.Numerics.Generic_Elementary_Functions (Real'Base); use Elementary_Functions; PI : constant := 3.14159_26535_89793_23846_26433_83279_50288_41971; PI_2 : constant := PI / 2.0; Sqrt_Two : constant := 1.41421_35623_73095_04880_16887_24209_69807_85696; Log_Two : constant := 0.69314_71805_59945_30941_72321_21458_17656_80755; subtype T is Real'Base; Epsilon : constant T := 2.0 ** (1 - T'Model_Mantissa); Square_Root_Epsilon : constant T := Sqrt_Two ** (1 - T'Model_Mantissa); Inv_Square_Root_Epsilon : constant T := Sqrt_Two ** (T'Model_Mantissa - 1); Root_Root_Epsilon : constant T := Sqrt_Two ** ((1 - T'Model_Mantissa) / 2); Log_Inverse_Epsilon_2 : constant T := T (T'Model_Mantissa - 1) / 2.0; Complex_Zero : constant Complex := (0.0, 0.0); Complex_One : constant Complex := (1.0, 0.0); Complex_I : constant Complex := (0.0, 1.0); Half_Pi : constant Complex := (PI_2, 0.0); -------- -- ** -- -------- function "**" (Left : Complex; Right : Complex) return Complex is begin if Re (Right) = 0.0 and then Im (Right) = 0.0 and then Re (Left) = 0.0 and then Im (Left) = 0.0 then raise Argument_Error; elsif Re (Left) = 0.0 and then Im (Left) = 0.0 and then Re (Right) < 0.0 then raise Constraint_Error; elsif Re (Left) = 0.0 and then Im (Left) = 0.0 then return Left; elsif Right = (0.0, 0.0) then return Complex_One; elsif Re (Right) = 0.0 and then Im (Right) = 0.0 then return 1.0 + Right; elsif Re (Right) = 1.0 and then Im (Right) = 0.0 then return Left; else return Exp (Right * Log (Left)); end if; end "**"; function "**" (Left : Real'Base; Right : Complex) return Complex is begin if Re (Right) = 0.0 and then Im (Right) = 0.0 and then Left = 0.0 then raise Argument_Error; elsif Left = 0.0 and then Re (Right) < 0.0 then raise Constraint_Error; elsif Left = 0.0 then return Compose_From_Cartesian (Left, 0.0); elsif Re (Right) = 0.0 and then Im (Right) = 0.0 then return Complex_One; elsif Re (Right) = 1.0 and then Im (Right) = 0.0 then return Compose_From_Cartesian (Left, 0.0); else return Exp (Log (Left) * Right); end if; end "**"; function "**" (Left : Complex; Right : Real'Base) return Complex is begin if Right = 0.0 and then Re (Left) = 0.0 and then Im (Left) = 0.0 then raise Argument_Error; elsif Re (Left) = 0.0 and then Im (Left) = 0.0 and then Right < 0.0 then raise Constraint_Error; elsif Re (Left) = 0.0 and then Im (Left) = 0.0 then return Left; elsif Right = 0.0 then return Complex_One; elsif Right = 1.0 then return Left; else return Exp (Right * Log (Left)); end if; end "**"; ------------ -- Arccos -- ------------ function Arccos (X : Complex) return Complex is Result : Complex; begin if X = Complex_One then return Complex_Zero; elsif abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return Half_Pi - X; elsif abs Re (X) > Inv_Square_Root_Epsilon or else abs Im (X) > Inv_Square_Root_Epsilon then return -2.0 * Complex_I * Log (Sqrt ((1.0 + X) / 2.0) + Complex_I * Sqrt ((1.0 - X) / 2.0)); end if; Result := -Complex_I * Log (X + Complex_I * Sqrt (1.0 - X * X)); if Im (X) = 0.0 and then abs Re (X) <= 1.00 then Set_Im (Result, Im (X)); end if; return Result; end Arccos; ------------- -- Arccosh -- ------------- function Arccosh (X : Complex) return Complex is Result : Complex; begin if X = Complex_One then return Complex_Zero; elsif abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then Result := Compose_From_Cartesian (-Im (X), -PI_2 + Re (X)); elsif abs Re (X) > Inv_Square_Root_Epsilon or else abs Im (X) > Inv_Square_Root_Epsilon then Result := Log_Two + Log (X); else Result := 2.0 * Log (Sqrt ((1.0 + X) / 2.0) + Sqrt ((X - 1.0) / 2.0)); end if; if Re (Result) <= 0.0 then Result := -Result; end if; return Result; end Arccosh; ------------ -- Arccot -- ------------ function Arccot (X : Complex) return Complex is Xt : Complex; begin if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return Half_Pi - X; elsif abs Re (X) > 1.0 / Epsilon or else abs Im (X) > 1.0 / Epsilon then Xt := Complex_One / X; if Re (X) < 0.0 then Set_Re (Xt, PI - Re (Xt)); return Xt; else return Xt; end if; end if; Xt := Complex_I * Log ((X - Complex_I) / (X + Complex_I)) / 2.0; if Re (Xt) < 0.0 then Xt := PI + Xt; end if; return Xt; end Arccot; -------------- -- Arccoth -- -------------- function Arccoth (X : Complex) return Complex is R : Complex; begin if X = (0.0, 0.0) then return Compose_From_Cartesian (0.0, PI_2); elsif abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return PI_2 * Complex_I + X; elsif abs Re (X) > 1.0 / Epsilon or else abs Im (X) > 1.0 / Epsilon then if Im (X) > 0.0 then return (0.0, 0.0); else return PI * Complex_I; end if; elsif Im (X) = 0.0 and then Re (X) = 1.0 then raise Constraint_Error; elsif Im (X) = 0.0 and then Re (X) = -1.0 then raise Constraint_Error; end if; begin R := Log ((1.0 + X) / (X - 1.0)) / 2.0; exception when Constraint_Error => R := (Log (1.0 + X) - Log (X - 1.0)) / 2.0; end; if Im (R) < 0.0 then Set_Im (R, PI + Im (R)); end if; if Re (X) = 0.0 then Set_Re (R, Re (X)); end if; return R; end Arccoth; ------------ -- Arcsin -- ------------ function Arcsin (X : Complex) return Complex is Result : Complex; begin -- For very small argument, sin (x) = x if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return X; elsif abs Re (X) > Inv_Square_Root_Epsilon or else abs Im (X) > Inv_Square_Root_Epsilon then Result := -Complex_I * (Log (Complex_I * X) + Log (2.0 * Complex_I)); if Im (Result) > PI_2 then Set_Im (Result, PI - Im (X)); elsif Im (Result) < -PI_2 then Set_Im (Result, -(PI + Im (X))); end if; return Result; end if; Result := -Complex_I * Log (Complex_I * X + Sqrt (1.0 - X * X)); if Re (X) = 0.0 then Set_Re (Result, Re (X)); elsif Im (X) = 0.0 and then abs Re (X) <= 1.00 then Set_Im (Result, Im (X)); end if; return Result; end Arcsin; ------------- -- Arcsinh -- ------------- function Arcsinh (X : Complex) return Complex is Result : Complex; begin if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return X; elsif abs Re (X) > Inv_Square_Root_Epsilon or else abs Im (X) > Inv_Square_Root_Epsilon then Result := Log_Two + Log (X); -- may have wrong sign if (Re (X) < 0.0 and then Re (Result) > 0.0) or else (Re (X) > 0.0 and then Re (Result) < 0.0) then Set_Re (Result, -Re (Result)); end if; return Result; end if; Result := Log (X + Sqrt (1.0 + X * X)); if Re (X) = 0.0 then Set_Re (Result, Re (X)); elsif Im (X) = 0.0 then Set_Im (Result, Im (X)); end if; return Result; end Arcsinh; ------------ -- Arctan -- ------------ function Arctan (X : Complex) return Complex is begin if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return X; else return -Complex_I * (Log (1.0 + Complex_I * X) - Log (1.0 - Complex_I * X)) / 2.0; end if; end Arctan; ------------- -- Arctanh -- ------------- function Arctanh (X : Complex) return Complex is begin if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return X; else return (Log (1.0 + X) - Log (1.0 - X)) / 2.0; end if; end Arctanh; --------- -- Cos -- --------- function Cos (X : Complex) return Complex is begin return Compose_From_Cartesian (Cos (Re (X)) * Cosh (Im (X)), -(Sin (Re (X)) * Sinh (Im (X)))); end Cos; ---------- -- Cosh -- ---------- function Cosh (X : Complex) return Complex is begin return Compose_From_Cartesian (Cosh (Re (X)) * Cos (Im (X)), Sinh (Re (X)) * Sin (Im (X))); end Cosh; --------- -- Cot -- --------- function Cot (X : Complex) return Complex is begin if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return Complex_One / X; elsif Im (X) > Log_Inverse_Epsilon_2 then return -Complex_I; elsif Im (X) < -Log_Inverse_Epsilon_2 then return Complex_I; end if; return Cos (X) / Sin (X); end Cot; ---------- -- Coth -- ---------- function Coth (X : Complex) return Complex is begin if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return Complex_One / X; elsif Re (X) > Log_Inverse_Epsilon_2 then return Complex_One; elsif Re (X) < -Log_Inverse_Epsilon_2 then return -Complex_One; else return Cosh (X) / Sinh (X); end if; end Coth; --------- -- Exp -- --------- function Exp (X : Complex) return Complex is EXP_RE_X : constant Real'Base := Exp (Re (X)); begin return Compose_From_Cartesian (EXP_RE_X * Cos (Im (X)), EXP_RE_X * Sin (Im (X))); end Exp; function Exp (X : Imaginary) return Complex is ImX : constant Real'Base := Im (X); begin return Compose_From_Cartesian (Cos (ImX), Sin (ImX)); end Exp; --------- -- Log -- --------- function Log (X : Complex) return Complex is ReX : Real'Base; ImX : Real'Base; Z : Complex; begin if Re (X) = 0.0 and then Im (X) = 0.0 then raise Constraint_Error; elsif abs (1.0 - Re (X)) < Root_Root_Epsilon and then abs Im (X) < Root_Root_Epsilon then Z := X; Set_Re (Z, Re (Z) - 1.0); return (1.0 - (1.0 / 2.0 - (1.0 / 3.0 - (1.0 / 4.0) * Z) * Z) * Z) * Z; end if; begin ReX := Log (Modulus (X)); exception when Constraint_Error => ReX := Log (Modulus (X / 2.0)) - Log_Two; end; ImX := Arctan (Im (X), Re (X)); if ImX > PI then ImX := ImX - 2.0 * PI; end if; return Compose_From_Cartesian (ReX, ImX); end Log; --------- -- Sin -- --------- function Sin (X : Complex) return Complex is begin if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return X; end if; return Compose_From_Cartesian (Sin (Re (X)) * Cosh (Im (X)), Cos (Re (X)) * Sinh (Im (X))); end Sin; ---------- -- Sinh -- ---------- function Sinh (X : Complex) return Complex is begin if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return X; else return Compose_From_Cartesian (Sinh (Re (X)) * Cos (Im (X)), Cosh (Re (X)) * Sin (Im (X))); end if; end Sinh; ---------- -- Sqrt -- ---------- function Sqrt (X : Complex) return Complex is ReX : constant Real'Base := Re (X); ImX : constant Real'Base := Im (X); XR : constant Real'Base := abs Re (X); YR : constant Real'Base := abs Im (X); R : Real'Base; R_X : Real'Base; R_Y : Real'Base; begin -- Deal with pure real case, see (RM G.1.2(39)) if ImX = 0.0 then if ReX > 0.0 then return Compose_From_Cartesian (Sqrt (ReX), 0.0); elsif ReX = 0.0 then return X; else return Compose_From_Cartesian (0.0, Real'Copy_Sign (Sqrt (-ReX), ImX)); end if; elsif ReX = 0.0 then R_X := Sqrt (YR / 2.0); if ImX > 0.0 then return Compose_From_Cartesian (R_X, R_X); else return Compose_From_Cartesian (R_X, -R_X); end if; else R := Sqrt (XR ** 2 + YR ** 2); -- If the square of the modulus overflows, try rescaling the -- real and imaginary parts. We cannot depend on an exception -- being raised on all targets. if R > Real'Base'Last then raise Constraint_Error; end if; -- We are solving the system -- XR = R_X ** 2 - Y_R ** 2 (1) -- YR = 2.0 * R_X * R_Y (2) -- -- The symmetric solution involves square roots for both R_X and -- R_Y, but it is more accurate to use the square root with the -- larger argument for either R_X or R_Y, and equation (2) for the -- other. if ReX < 0.0 then R_Y := Sqrt (0.5 * (R - ReX)); R_X := YR / (2.0 * R_Y); else R_X := Sqrt (0.5 * (R + ReX)); R_Y := YR / (2.0 * R_X); end if; end if; if Im (X) < 0.0 then -- halve angle, Sqrt of magnitude R_Y := -R_Y; end if; return Compose_From_Cartesian (R_X, R_Y); exception when Constraint_Error => -- Rescale and try again R := Modulus (Compose_From_Cartesian (Re (X / 4.0), Im (X / 4.0))); R_X := 2.0 * Sqrt (0.5 * R + 0.5 * Re (X / 4.0)); R_Y := 2.0 * Sqrt (0.5 * R - 0.5 * Re (X / 4.0)); if Im (X) < 0.0 then -- halve angle, Sqrt of magnitude R_Y := -R_Y; end if; return Compose_From_Cartesian (R_X, R_Y); end Sqrt; --------- -- Tan -- --------- function Tan (X : Complex) return Complex is begin if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return X; elsif Im (X) > Log_Inverse_Epsilon_2 then return Complex_I; elsif Im (X) < -Log_Inverse_Epsilon_2 then return -Complex_I; else return Sin (X) / Cos (X); end if; end Tan; ---------- -- Tanh -- ---------- function Tanh (X : Complex) return Complex is begin if abs Re (X) < Square_Root_Epsilon and then abs Im (X) < Square_Root_Epsilon then return X; elsif Re (X) > Log_Inverse_Epsilon_2 then return Complex_One; elsif Re (X) < -Log_Inverse_Epsilon_2 then return -Complex_One; else return Sinh (X) / Cosh (X); end if; end Tanh; end Ada.Numerics.Generic_Complex_Elementary_Functions;
-- -- Jan & Uwe R. Zimmer, Australia, July 2011 -- with Real_Type; use Real_Type; generic Dimension : Positive; package Matrices is type Matrix is array (1 .. Dimension, 1 .. Dimension) of Real; -- function Image (Matrix : Matrix_3D) return String; function "*" (A, B : Matrix) return Matrix; function Transpose (M : Matrix) return Matrix; end Matrices;
with cLib.Binding; with cLib.lconv; with interfaces.C.Strings; with ada.Strings.unbounded; with ada.Text_IO; procedure Simple is use ada.text_IO, ada.Strings.Unbounded, Interfaces.C.Strings; the_set_Locale : Interfaces.C.Strings.chars_ptr := clib.Binding.setlocale (cLib.binding.LC_ALL, new_String ("")); the_Locale : clib.lconv.Pointer := clib.Binding.localeconv.all'access; function grouping_Image return String is the_Grouping : String := Value (the_Locale.grouping); the_Image : unbounded_String; begin for Each in the_Grouping'range loop append (the_Image, Integer'Image (Character'Pos (the_Grouping (Each)))); end loop; return to_String (the_Image); end grouping_Image; begin put_Line ("Locale is: '" & Value (the_set_Locale) & "'"); put_Line (" decimal_point: " & Value (the_Locale.decimal_Point )); put_Line (" thousands_sep: " & Value (the_Locale.thousands_sep )); put_Line (" grouping: " & grouping_Image ); put_Line (" int_curr_symbol: " & Value (the_Locale.int_curr_symbol)); end Simple;
-- Laboratory work on the topic: "Ada. Semaphores" -- Variant: A = ( B + C ) * ( MO + d * ( MK * MR ) ) -- Created: 8.02.2018 8:52 PM -- Author: Obozniy Dmitriy IO-51 with Data, Ada.Text_IO, Ada.Integer_Text_IO, Ada.Synchronous_Task_Control; use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Synchronous_Task_Control; procedure Lab1 is N: integer := 500; -- vector size P: integer := 2; -- processors count H: integer := N/P; -- subvector size d: integer; -- shared resource (global variable) package datax is new Data (n,p); use datax; C, A, B: Vector; -- shared resource and global variables MO, MK, MR: Matrix; -- shared resource and global variables -- semaphores Sem1, Sem2, Sem3, Skd: Suspension_Object; procedure Task_Begin is task T1 is pragma Task_Name("Task1"); pragma Priority(5); pragma Storage_Size(30000000); end T1; task body T1 is --local variables d1: integer; C1: Vector; MO1: Matrix; begin put_line("Process T1 started "); -- input B, C and MR if n<=1 then Vector_Input(B,"B"); Vector_Input(C,"C"); Matrix_Input(MR,"MR"); else Vector_Fill(B,1); Vector_Fill(C,1); Matrix_Fill(MR,1); end if; -- signal for task T2 about end of input B, C and MR Set_True(Sem1); -- waiting for end of input in task T2 Suspend_Until_True(Sem2); -- copy d in d1, C in C1, MO in MO1 Suspend_Until_True(Skd); -- critical zone d1:= d; C1:= C; MO1:= MO; Set_True(Skd); -- Calculating AH Func(A,B,C1,MO1,MK,MR,d1,0); -- waiting for end of calculating in T2 Suspend_Until_True(Sem3); -- output the result if N<=10 then Put_Line("A: "); Vector_Output(A); put_line(""); end if; put_line("Process T1 finished"); end T1; task T2 is pragma Task_Name("Task2"); pragma Priority(5); pragma Storage_Size(30000000); end T2; task body T2 is -- local variables d2: integer; C2: Vector; MO2: Matrix; begin put_line("Process T2 started "); -- input MO, MK and d if n<=1 then Matrix_Input(MO,"MO"); Matrix_Input(MK,"MK"); else Matrix_Fill(MO,1); Matrix_Fill(MK,1); end if; d:= 1; -- signal for task T1 about end of input MO, MK and d Set_True(Sem2); -- waiting for end of input in task T1 Suspend_Until_True(Sem1); -- copy d in d2, C in C2, MO in MO2 Suspend_Until_True(Skd); d2:= d; C2:= C; MO2:= MO; Set_True(Skd); -- Calculating AH Func(A,B,C2,MO2,MK,MR,d2,1); -- signal for T1 about end of calculating Set_True(Sem3); put_line("Process T2 finished"); end T2; begin null; end Task_Begin; -- body of main program begin put_line("Main procedure started "); -- setting start value of semaphore Skd Set_True(Skd); Task_Begin; end Lab1;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 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 Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.Mappers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers.URLs; package body Security.Policies.URLs is -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in URL_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URL); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URL); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; begin if P /= null then for I in P.Permissions'Range loop if Context.Has_Permission (P.Permissions (I)) then return True; end if; end loop; end if; end; return False; end Has_Permission; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- ------------------------------ -- Policy Configuration -- ------------------------------ -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out URL_Policy) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out URL_Policy) is procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); begin Free (Manager.Cache); -- for I in Manager.Names'Range loop -- exit when Manager.Names (I) = null; -- Ada.Strings.Unbounded.Free (Manager.Names (I)); -- end loop; end Finalize; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in out URL_Policy'Class); procedure Set_Member (P : in out URL_Policy'Class; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in out URL_Policy'Class) is Pol : Security.Policies.URLs.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class, Element_Type_Access => URL_Policy_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Perm : constant Security.Controllers.URLs.URL_Controller_Access := new Security.Controllers.URLs.URL_Controller; begin Perm.Manager := Policy'Unchecked_Access; Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Policy_Mapper.Set_Context (Reader, Perm.Manager); if not Policy.Manager.Has_Controller (P_URL.Permission) then Policy.Manager.Add_Permission (Name => "url", Permission => Perm.all'Access); end if; end Prepare_Config; -- ------------------------------ -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in URL_Policy'Class) then return null; else return URL_Policy'Class (Policy.all)'Access; end if; end Get_URL_Policy; begin Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.URLs;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with Glfw.Monitors; with Ada.Text_IO; procedure Glfw_Test.Monitors is procedure Print_Gamma_Value_Array (Values : Glfw.Monitors.Gamma_Value_Array) is use Ada.Text_IO; First : Boolean := True; begin Put ("["); for I in Values'Range loop if First then First := False; else Put (","); end if; Put (Values (I)'Img); end loop; Put_Line ("]"); end Print_Gamma_Value_Array; procedure Print_Monitor_Info (M : Glfw.Monitors.Monitor) is use Ada.Text_IO; use type Glfw.Monitors.Video_Mode; Param1, Param2 : Integer; VM_List : constant Glfw.Monitors.Video_Mode_List := M.Video_Modes; Gamma_Ramp : constant Glfw.Monitors.Gamma_Ramp := M.Current_Gamma_Ramp; begin Put_Line ("Monitor """ & M.Name & """"); M.Get_Position (Param1, Param2); Put_Line ("Position: (" & Param1'Img & "," & Param2'Img & ")"); M.Get_Physical_Size (Param1, Param2); Put_Line ("Dimensions: " & Param1'Img & " x " & Param2'Img); Put_Line ("Video modes: "); for I in VM_List'Range loop Put (" ["); if VM_List (I) = M.Current_Video_Mode then Put ("x"); else Put (" "); end if; Put ("] dim(" & VM_List (I).Width'Img & " x" & VM_List (I).Height'Img); Put ("), rgb(" & VM_List (I).Red_Bits'Img & "," & VM_List (I).Green_Bits'Img & "," & VM_List (I).Blue_Bits'Img); Put_Line ("), refresh(" & VM_List (I).Refresh_Rate'Img & ")"); end loop; Put_Line ("Gamma ramp:"); Put (" red: "); Print_Gamma_Value_Array (Gamma_Ramp.Red); Put (" green: "); Print_Gamma_Value_Array (Gamma_Ramp.Green); Put (" blue: "); Print_Gamma_Value_Array (Gamma_Ramp.Blue); end Print_Monitor_Info; begin Glfw.Init; Enable_Print_Errors; declare My_Monitors : constant Glfw.Monitors.Monitor_List := Glfw.Monitors.Monitors; begin for I in My_Monitors'Range loop Print_Monitor_Info (My_Monitors (I)); Ada.Text_IO.Put_Line ("--------------------------------------------"); end loop; end; Glfw.Shutdown; end Glfw_Test.Monitors;
------------------------------------------------------------------------------ -- -- -- GNAT SYSTEM UTILITIES -- -- -- -- C E I N F O -- -- -- -- B o d y -- -- -- -- Copyright (C) 1998-2014, 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. -- -- -- ------------------------------------------------------------------------------ -- Check consistency of einfo.ads and einfo.adb. Checks that field name usage -- is consistent, including comments mentioning fields. -- Note that this is used both as a standalone program, and as a procedure -- called by XEinfo. This raises an unhandled exception if it finds any -- errors; we don't attempt any sophisticated error recovery. with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Text_IO; use Ada.Strings.Unbounded.Text_IO; with Ada.Text_IO; use Ada.Text_IO; with GNAT.Spitbol; use GNAT.Spitbol; with GNAT.Spitbol.Patterns; use GNAT.Spitbol.Patterns; with GNAT.Spitbol.Table_VString; procedure CEinfo is package TV renames GNAT.Spitbol.Table_VString; use TV; Infil : File_Type; Lineno : Natural := 0; Err : exception; -- Raised on error Fieldnm : VString; Accessfunc : VString; Line : VString; Fields : GNAT.Spitbol.Table_VString.Table (500); -- Maps field names to underlying field access name UC : constant Pattern := Any ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); Fnam : constant Pattern := (UC & Break (' ')) * Fieldnm; Field_Def : constant Pattern := "-- " & Fnam & " (" & Break (')') * Accessfunc; Field_Ref : constant Pattern := " -- " & Fnam & Break ('(') & Len (1) & Break (')') * Accessfunc; Field_Com : constant Pattern := " -- " & Fnam & Span (' ') & (Break (' ') or Rest) * Accessfunc; Func_Hedr : constant Pattern := " function " & Fnam; Func_Retn : constant Pattern := " return " & Break (' ') * Accessfunc; Proc_Hedr : constant Pattern := " procedure " & Fnam; Proc_Setf : constant Pattern := " Set_" & Break (' ') * Accessfunc; procedure Next_Line; -- Read next line trimmed from Infil into Line and bump Lineno procedure Next_Line is begin Line := Get_Line (Infil); Trim (Line); Lineno := Lineno + 1; end Next_Line; -- Start of processing for CEinfo begin Anchored_Mode := True; New_Line; Open (Infil, In_File, "einfo.ads"); Put_Line ("Acquiring field names from spec"); loop Next_Line; -- Old format of einfo.ads exit when Match (Line, " -- Access Kinds --"); -- New format of einfo.ads exit when Match (Line, "-- Access Kinds --"); if Match (Line, Field_Def) then Set (Fields, Fieldnm, Accessfunc); end if; end loop; Put_Line ("Checking consistent references in spec"); loop Next_Line; exit when Match (Line, " -- Description of Defined"); end loop; loop Next_Line; exit when Match (Line, " -- Component_Alignment Control"); if Match (Line, Field_Ref) then if Accessfunc /= "synth" and then Accessfunc /= "special" and then Accessfunc /= Get (Fields, Fieldnm) then if Present (Fields, Fieldnm) then Put_Line ("*** field name incorrect at line " & Lineno); Put_Line (" found field " & Accessfunc); Put_Line (" expecting field " & Get (Fields, Fieldnm)); else Put_Line ("*** unknown field name " & Fieldnm & " at line " & Lineno); end if; raise Err; end if; end if; end loop; Close (Infil); Open (Infil, In_File, "einfo.adb"); Lineno := 0; Put_Line ("Check listing of fields in body"); loop Next_Line; exit when Match (Line, " -- Attribute Access Functions --"); if Match (Line, Field_Com) and then Fieldnm /= "(unused)" and then Accessfunc /= Get (Fields, Fieldnm) then if Present (Fields, Fieldnm) then Put_Line ("*** field name incorrect at line " & Lineno); Put_Line (" found field " & Accessfunc); Put_Line (" expecting field " & Get (Fields, Fieldnm)); else Put_Line ("*** unknown field name " & Fieldnm & " at line " & Lineno); end if; raise Err; end if; end loop; Put_Line ("Check references in access routines in body"); loop Next_Line; exit when Match (Line, " -- Classification Functions --"); if Match (Line, Func_Hedr) then null; elsif Match (Line, Func_Retn) and then Accessfunc /= Get (Fields, Fieldnm) and then Fieldnm /= "Mechanism" then Put_Line ("*** incorrect field at line " & Lineno); Put_Line (" found field " & Accessfunc); Put_Line (" expecting field " & Get (Fields, Fieldnm)); raise Err; end if; end loop; Put_Line ("Check references in set routines in body"); loop Next_Line; exit when Match (Line, " -- Attribute Set Procedures"); end loop; loop Next_Line; exit when Match (Line, " ------------"); if Match (Line, Proc_Hedr) then null; elsif Match (Line, Proc_Setf) and then Accessfunc /= Get (Fields, Fieldnm) and then Fieldnm /= "Mechanism" then Put_Line ("*** incorrect field at line " & Lineno); Put_Line (" found field " & Accessfunc); Put_Line (" expecting field " & Get (Fields, Fieldnm)); raise Err; end if; end loop; Close (Infil); Put_Line ("All tests completed successfully, no errors detected"); end CEinfo;
----------------------------------------------------------------------- -- AWA.Comments.Models -- AWA.Comments.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-body.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 2017 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 Ada.Unchecked_Deallocation; with Util.Beans.Objects.Time; with ASF.Events.Faces.Actions; package body AWA.Comments.Models is use type ADO.Objects.Object_Record_Access; use type ADO.Objects.Object_Ref; use type ADO.Objects.Object_Record; pragma Warnings (Off, "formal parameter * is not referenced"); function Comment_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => COMMENT_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Comment_Key; function Comment_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => COMMENT_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Comment_Key; function "=" (Left, Right : Comment_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end "="; procedure Set_Field (Object : in out Comment_Ref'Class; Impl : out Comment_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Comment_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Comment_Ref) is Impl : Comment_Access; begin Impl := new Comment_Impl; Impl.Create_Date := ADO.DEFAULT_TIME; Impl.Entity_Id := ADO.NO_IDENTIFIER; Impl.Version := 0; Impl.Entity_Type := 0; Impl.Status := AWA.Comments.Models.Status_Type'First; Impl.Format := AWA.Comments.Models.Format_Type'First; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Comment -- ---------------------------------------- procedure Set_Create_Date (Object : in out Comment_Ref; Value : in Ada.Calendar.Time) is Impl : Comment_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Time (Impl.all, 1, Impl.Create_Date, Value); end Set_Create_Date; function Get_Create_Date (Object : in Comment_Ref) return Ada.Calendar.Time is Impl : constant Comment_Access := Comment_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Create_Date; end Get_Create_Date; procedure Set_Message (Object : in out Comment_Ref; Value : in String) is Impl : Comment_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 2, Impl.Message, Value); end Set_Message; procedure Set_Message (Object : in out Comment_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Comment_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 2, Impl.Message, Value); end Set_Message; function Get_Message (Object : in Comment_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Message); end Get_Message; function Get_Message (Object : in Comment_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Comment_Access := Comment_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Message; end Get_Message; procedure Set_Entity_Id (Object : in out Comment_Ref; Value : in ADO.Identifier) is Impl : Comment_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Identifier (Impl.all, 3, Impl.Entity_Id, Value); end Set_Entity_Id; function Get_Entity_Id (Object : in Comment_Ref) return ADO.Identifier is Impl : constant Comment_Access := Comment_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Entity_Id; end Get_Entity_Id; procedure Set_Id (Object : in out Comment_Ref; Value : in ADO.Identifier) is Impl : Comment_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 4, Value); end Set_Id; function Get_Id (Object : in Comment_Ref) return ADO.Identifier is Impl : constant Comment_Access := Comment_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; function Get_Version (Object : in Comment_Ref) return Integer is Impl : constant Comment_Access := Comment_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Entity_Type (Object : in out Comment_Ref; Value : in ADO.Entity_Type) is Impl : Comment_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Entity_Type (Impl.all, 6, Impl.Entity_Type, Value); end Set_Entity_Type; function Get_Entity_Type (Object : in Comment_Ref) return ADO.Entity_Type is Impl : constant Comment_Access := Comment_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Entity_Type; end Get_Entity_Type; procedure Set_Status (Object : in out Comment_Ref; Value : in AWA.Comments.Models.Status_Type) is procedure Set_Field_Enum is new ADO.Objects.Set_Field_Operation (Status_Type); Impl : Comment_Access; begin Set_Field (Object, Impl); Set_Field_Enum (Impl.all, 7, Impl.Status, Value); end Set_Status; function Get_Status (Object : in Comment_Ref) return AWA.Comments.Models.Status_Type is Impl : constant Comment_Access := Comment_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Status; end Get_Status; procedure Set_Format (Object : in out Comment_Ref; Value : in AWA.Comments.Models.Format_Type) is procedure Set_Field_Enum is new ADO.Objects.Set_Field_Operation (Format_Type); Impl : Comment_Access; begin Set_Field (Object, Impl); Set_Field_Enum (Impl.all, 8, Impl.Format, Value); end Set_Format; function Get_Format (Object : in Comment_Ref) return AWA.Comments.Models.Format_Type is Impl : constant Comment_Access := Comment_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Format; end Get_Format; procedure Set_Author (Object : in out Comment_Ref; Value : in AWA.Users.Models.User_Ref'Class) is Impl : Comment_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 9, Impl.Author, Value); end Set_Author; function Get_Author (Object : in Comment_Ref) return AWA.Users.Models.User_Ref'Class is Impl : constant Comment_Access := Comment_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Author; end Get_Author; -- Copy of the object. procedure Copy (Object : in Comment_Ref; Into : in out Comment_Ref) is Result : Comment_Ref; begin if not Object.Is_Null then declare Impl : constant Comment_Access := Comment_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Comment_Access := new Comment_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Create_Date := Impl.Create_Date; Copy.Message := Impl.Message; Copy.Entity_Id := Impl.Entity_Id; Copy.Version := Impl.Version; Copy.Entity_Type := Impl.Entity_Type; Copy.Status := Impl.Status; Copy.Format := Impl.Format; Copy.Author := Impl.Author; end; end if; Into := Result; end Copy; procedure Find (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Comment_Access := new Comment_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Comment_Access := new Comment_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Comment_Access := new Comment_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Comment_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Comment_Impl) is type Comment_Impl_Ptr is access all Comment_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Comment_Impl, Comment_Impl_Ptr); pragma Warnings (Off, "*redundant conversion*"); Ptr : Comment_Impl_Ptr := Comment_Impl (Object.all)'Access; pragma Warnings (On, "*redundant conversion*"); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, COMMENT_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (COMMENT_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_1_NAME, -- create_date Value => Object.Create_Date); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_1_NAME, -- message Value => Object.Message); Object.Clear_Modified (2); end if; if Object.Is_Modified (3) then Stmt.Save_Field (Name => COL_2_1_NAME, -- entity_id Value => Object.Entity_Id); Object.Clear_Modified (3); end if; if Object.Is_Modified (4) then Stmt.Save_Field (Name => COL_3_1_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (4); end if; if Object.Is_Modified (6) then Stmt.Save_Field (Name => COL_5_1_NAME, -- entity_type Value => Object.Entity_Type); Object.Clear_Modified (6); end if; if Object.Is_Modified (7) then Stmt.Save_Field (Name => COL_6_1_NAME, -- status Value => Integer (Status_Type'Pos (Object.Status))); Object.Clear_Modified (7); end if; if Object.Is_Modified (8) then Stmt.Save_Field (Name => COL_7_1_NAME, -- format Value => Integer (Format_Type'Pos (Object.Format))); Object.Clear_Modified (8); end if; if Object.Is_Modified (9) then Stmt.Save_Field (Name => COL_8_1_NAME, -- author_id Value => Object.Author); Object.Clear_Modified (9); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => "version", Value => Object.Version); Stmt.Set_Filter (Filter => "id = ? and version = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (COMMENT_DEF'Access); Result : Integer; begin Object.Version := 1; Query.Save_Field (Name => COL_0_1_NAME, -- create_date Value => Object.Create_Date); Query.Save_Field (Name => COL_1_1_NAME, -- message Value => Object.Message); Query.Save_Field (Name => COL_2_1_NAME, -- entity_id Value => Object.Entity_Id); Session.Allocate (Id => Object); Query.Save_Field (Name => COL_3_1_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_4_1_NAME, -- version Value => Object.Version); Query.Save_Field (Name => COL_5_1_NAME, -- entity_type Value => Object.Entity_Type); Query.Save_Field (Name => COL_6_1_NAME, -- status Value => Integer (Status_Type'Pos (Object.Status))); Query.Save_Field (Name => COL_7_1_NAME, -- format Value => Integer (Format_Type'Pos (Object.Format))); Query.Save_Field (Name => COL_8_1_NAME, -- author_id Value => Object.Author); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (COMMENT_DEF'Access); begin Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Comment_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Comment_Impl (Obj.all)'Access; if Name = "create_date" then return Util.Beans.Objects.Time.To_Object (Impl.Create_Date); elsif Name = "message" then return Util.Beans.Objects.To_Object (Impl.Message); elsif Name = "entity_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Entity_Id)); elsif Name = "id" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = "entity_type" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Entity_Type)); elsif Name = "status" then return AWA.Comments.Models.Status_Type_Objects.To_Object (Impl.Status); elsif Name = "format" then return AWA.Comments.Models.Format_Type_Objects.To_Object (Impl.Format); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Comment_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Create_Date := Stmt.Get_Time (0); Object.Message := Stmt.Get_Unbounded_String (1); Object.Entity_Id := Stmt.Get_Identifier (2); Object.Set_Key_Value (Stmt.Get_Identifier (3)); Object.Entity_Type := ADO.Entity_Type (Stmt.Get_Integer (5)); Object.Status := Status_Type'Val (Stmt.Get_Integer (6)); Object.Format := Format_Type'Val (Stmt.Get_Integer (7)); if not Stmt.Is_Null (8) then Object.Author.Set_Key_Value (Stmt.Get_Identifier (8), Session); end if; Object.Version := Stmt.Get_Integer (4); ADO.Objects.Set_Created (Object); end Load; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Info; Name : in String) return Util.Beans.Objects.Object is begin if Name = "id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Id)); elsif Name = "author" then return Util.Beans.Objects.To_Object (From.Author); elsif Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "date" then return Util.Beans.Objects.Time.To_Object (From.Date); elsif Name = "format" then return AWA.Comments.Models.Format_Type_Objects.To_Object (From.Format); elsif Name = "comment" then return Util.Beans.Objects.To_Object (From.Comment); elsif Name = "status" then return AWA.Comments.Models.Status_Type_Objects.To_Object (From.Status); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Set the value identified by the name -- ------------------------------ overriding procedure Set_Value (Item : in out Comment_Info; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" then Item.Id := ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value)); elsif Name = "author" then Item.Author := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "email" then Item.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "date" then Item.Date := Util.Beans.Objects.Time.To_Time (Value); elsif Name = "format" then Item.Format := AWA.Comments.Models.Format_Type_Objects.To_Value (Value); elsif Name = "comment" then Item.Comment := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "status" then Item.Status := AWA.Comments.Models.Status_Type_Objects.To_Value (Value); end if; end Set_Value; -- -------------------- -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. -- -------------------- procedure List (Object : in out Comment_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class) is begin List (Object.List, Session, Context); end List; -- -------------------- -- The comment information. -- -------------------- procedure List (Object : in out Comment_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class) is procedure Read (Into : in out Comment_Info); Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Context); Pos : Natural := 0; procedure Read (Into : in out Comment_Info) is begin Into.Id := Stmt.Get_Identifier (0); Into.Author := Stmt.Get_Unbounded_String (1); Into.Email := Stmt.Get_Unbounded_String (2); Into.Date := Stmt.Get_Time (3); Into.Format := AWA.Comments.Models.Format_Type'Val (Stmt.Get_Integer (4)); Into.Comment := Stmt.Get_Unbounded_String (5); Into.Status := AWA.Comments.Models.Status_Type'Val (Stmt.Get_Integer (6)); end Read; begin Stmt.Execute; Comment_Info_Vectors.Clear (Object); while Stmt.Has_Elements loop Object.Insert_Space (Before => Pos); Object.Update_Element (Index => Pos, Process => Read'Access); Pos := Pos + 1; Stmt.Next; end loop; end List; procedure Op_Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); procedure Op_Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Comment_Bean'Class (Bean).Create (Outcome); end Op_Create; package Binding_Comment_Bean_1 is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Comment_Bean, Method => Op_Create, Name => "create"); procedure Op_Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); procedure Op_Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Comment_Bean'Class (Bean).Delete (Outcome); end Op_Delete; package Binding_Comment_Bean_2 is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Comment_Bean, Method => Op_Delete, Name => "delete"); procedure Op_Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); procedure Op_Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Comment_Bean'Class (Bean).Save (Outcome); end Op_Save; package Binding_Comment_Bean_3 is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Comment_Bean, Method => Op_Save, Name => "save"); procedure Op_Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); procedure Op_Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Comment_Bean'Class (Bean).Publish (Outcome); end Op_Publish; package Binding_Comment_Bean_4 is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Comment_Bean, Method => Op_Publish, Name => "publish"); Binding_Comment_Bean_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Binding_Comment_Bean_1.Proxy'Access, 2 => Binding_Comment_Bean_2.Proxy'Access, 3 => Binding_Comment_Bean_3.Proxy'Access, 4 => Binding_Comment_Bean_4.Proxy'Access ); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression. -- ------------------------------ overriding function Get_Method_Bindings (From : in Comment_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Comment_Bean_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Set the value identified by the name -- ------------------------------ overriding procedure Set_Value (Item : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "create_date" then Item.Set_Create_Date (Util.Beans.Objects.Time.To_Time (Value)); elsif Name = "message" then Item.Set_Message (Util.Beans.Objects.To_String (Value)); elsif Name = "entity_id" then Item.Set_Entity_Id (ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value))); elsif Name = "entity_type" then Item.Set_Entity_Type (ADO.Entity_Type (Util.Beans.Objects.To_Integer (Value))); elsif Name = "status" then Item.Set_Status (Status_Type_Objects.To_Value (Value)); elsif Name = "format" then Item.Set_Format (Format_Type_Objects.To_Value (Value)); end if; end Set_Value; end AWA.Comments.Models;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2013, 2016, 2017, 2018, 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 Ada.Strings.Unbounded; -- == OAuth Client == -- The `Security.OAuth.Clients` package implements the client OAuth 2.0 authorization. -- -- === Application setup === -- For an OAuth2 client application to authenticate, it must be registered on the server -- and the server provides the following information: -- -- * **client_id**: the client identifier is a unique string that identifies the application. -- * **client_secret** the client secret is a secret shared between the server and the -- client application. The client secret is optional. -- -- The `Security.OAuth.Clients.Application` tagged record is the primary type that -- allows to perform one of the OAuth 2.0 authorization flows. It is necessary to -- declare an `Application` instance and register the **client_id**, the **client_secret** -- and the authorisation URLs to connect to the server. -- -- App : Security.OAuth.Clients.Application; -- ... -- App.Set_Application_Identifier ("app-identifier"); -- App.Set_Application_Secret ("app-secret"); -- App.Set_Provider_URL ("https://graph.facebook.com/oauth/access_token"); -- -- -- === Resource Owner Password Credentials Grant === -- The RFC 6749: 4.3. Resource Owner Password Credentials Grant allows to authorize an -- application by using the user's name and password. This is the simplest OAuth flow -- but because it requires to know the user's name and password, it is not recommended and -- not supported by several servers. To use this authorization, the application will use -- the `Request_Token` procedure and will give the user's name, password and the scope -- of permissions. When the authorization succeeds, a `Grant_Type` token object is returned. -- -- Token : Security.OAuth.Clients.Grant_Type; -- ... -- App.Request_Token ("admin", "admin", "scope", Token); -- -- === Refreshing an access token === -- An access token has an expiration date and a new access token must be asked by using the -- refresh token. When the access token has expired, the grant token object can be refreshed -- to retrieve a new access token by using the `Refresh_Token` procedure. The scope of -- permissions can also be passsed. -- -- App.Refresh_Token ("scope", Token); -- package Security.OAuth.Clients is -- Note: OAuth 1.0 could be implemented but since it's being deprecated -- it's not worth doing it. -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private; type OpenID_Token_Access is access all OpenID_Token'Class; -- Get the id_token that was returned by the authentication process. function Get_Id_Token (From : in OpenID_Token) return String; -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. function Create_Nonce (Bits : in Positive := 256) return String; type Grant_Type is new Security.Principal with private; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Grant_Type) return String; -- Get the Authorization header to be used for accessing a protected resource. -- (See RFC 6749 7. Accessing Protected Resources) function Get_Authorization (From : in Grant_Type) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is new Security.OAuth.Application with private; -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. procedure Set_Provider_URI (App : in out Application; URI : in String); -- OAuth 2.0 Section 4.1.1 Authorization Request -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. function Get_State (App : in Application; Nonce : in String) return String; -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String; -- OAuth 2.0 Section 4.1.2 Authorization Response -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Get a request token with username and password. -- RFC 6749: 4.3. Resource Owner Password Credentials Grant procedure Request_Token (App : in Application; Username : in String; Password : in String; Scope : in String; Token : in out Grant_Type'Class); -- Refresh the access token. -- RFC 6749: 6. Refreshing an Access Token procedure Refresh_Token (App : in Application; Scope : in String; Token : in out Grant_Type'Class); -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Principal with record Access_Id : String (1 .. Len); end record; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record Id_Token : String (1 .. Id_Len); Refresh_Token : String (1 .. Refresh_Len); end record; type Application is new Security.OAuth.Application with record Request_URI : Ada.Strings.Unbounded.Unbounded_String; end record; type Grant_Type is new Security.Principal with record Access_Token : Ada.Strings.Unbounded.Unbounded_String; Refresh_Token : Ada.Strings.Unbounded.Unbounded_String; Id_Token : Ada.Strings.Unbounded.Unbounded_String; Expires : Natural; end record; end Security.OAuth.Clients;
with Interfaces.C, System; use type System.Address; package body FLTK.Images.Bitmaps is procedure free_fl_bitmap (I : in System.Address); pragma Import (C, free_fl_bitmap, "free_fl_bitmap"); pragma Inline (free_fl_bitmap); function fl_bitmap_copy (I : in System.Address; W, H : in Interfaces.C.int) return System.Address; pragma Import (C, fl_bitmap_copy, "fl_bitmap_copy"); pragma Inline (fl_bitmap_copy); function fl_bitmap_copy2 (I : in System.Address) return System.Address; pragma Import (C, fl_bitmap_copy2, "fl_bitmap_copy2"); pragma Inline (fl_bitmap_copy2); procedure fl_bitmap_draw2 (I : in System.Address; X, Y : in Interfaces.C.int); pragma Import (C, fl_bitmap_draw2, "fl_bitmap_draw2"); pragma Inline (fl_bitmap_draw2); procedure fl_bitmap_draw (I : in System.Address; X, Y, W, H, CX, CY : in Interfaces.C.int); pragma Import (C, fl_bitmap_draw, "fl_bitmap_draw"); pragma Inline (fl_bitmap_draw); overriding procedure Finalize (This : in out Bitmap) is begin if This.Void_Ptr /= System.Null_Address and then This in Bitmap'Class then free_fl_bitmap (This.Void_Ptr); This.Void_Ptr := System.Null_Address; end if; Finalize (Image (This)); end Finalize; function Copy (This : in Bitmap; Width, Height : in Natural) return Bitmap'Class is begin return Copied : Bitmap do Copied.Void_Ptr := fl_bitmap_copy (This.Void_Ptr, Interfaces.C.int (Width), Interfaces.C.int (Height)); end return; end Copy; function Copy (This : in Bitmap) return Bitmap'Class is begin return Copied : Bitmap do Copied.Void_Ptr := fl_bitmap_copy2 (This.Void_Ptr); end return; end Copy; procedure Draw (This : in Bitmap; X, Y : in Integer) is begin fl_bitmap_draw2 (This.Void_Ptr, Interfaces.C.int (X), Interfaces.C.int (Y)); end Draw; procedure Draw (This : in Bitmap; X, Y, W, H : in Integer; CX, CY : in Integer := 0) is begin fl_bitmap_draw (This.Void_Ptr, Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H), Interfaces.C.int (CX), Interfaces.C.int (CY)); end Draw; end FLTK.Images.Bitmaps;
with Project_Processor.Parsers.Abstract_Parsers; with EU_Projects.Projects; package Project_Processor.Parsers.Simple_Format is type Parser_Type is new Abstract_Parsers.Abstract_Parser with private; overriding function Create (Params : not null access Plugins.Parameter_Maps.Map) return Parser_Type; overriding procedure Parse (Parser : in out Parser_Type; Project : out EU_Projects.Projects.Project_Descriptor; Input : String); private type Parser_Type is new Abstract_Parsers.Abstract_Parser with null record; end Project_Processor.Parsers.Simple_Format;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2019, Fabien Chouteau -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. 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. -- -- 3. Neither the name of the copyright holder 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. -- -- -- ------------------------------------------------------------------------------ with LibRISCV.CSR; with ESF; package body LibRISCV.Instructions with SPARK_Mode => On is function Shift_Right (Value : Word; Amount : Natural) return Word; pragma Import (Intrinsic, Shift_Right); ------------ -- Decode -- ------------ function Decode (Raw : Word) return Instruction is function Opcode return Raw_Opcode is (Raw_Opcode (Raw and 2#111_1111#)); function RD return GPR_Id is (GPR_Id (Shift_Right (Raw, 7) and 2#11111#)); function RS1 return GPR_Id is (GPR_Id (Shift_Right (Raw, 15) and 2#11111#)); function RS2 return GPR_Id is (GPR_Id (Shift_Right (Raw, 20) and 2#11111#)); function Funct3 return Raw_Funct3 is (Raw_Funct3 (Shift_Right (Raw, 12) and 2#111#)); function Imm12 return Raw_Imm12 is (Raw_Imm12 (Shift_Right (Raw, 20) and 2#1111_1111_1111#)); function Imm12_S return Raw_Imm12 is I_11_5, I_4_0 : Word; begin I_11_5 := Shift_Right (Raw, 25) and 2#111_1111#; I_4_0 := Shift_Right (Raw, 7) and 2#1_1111#; return Raw_Imm12 (Shift_Left (I_11_5, 5) or I_4_0); end Imm12_S; function Imm13_B return Raw_Imm13 is I_12, I_10_5, I_4_1, I_11 : Word; begin I_12 := Shift_Right (Raw, 31) and 2#1#; I_10_5 := Shift_Right (Raw, 25) and 2#11_1111#; I_4_1 := Shift_Right (Raw, 8) and 2#1111#; I_11 := Shift_Right (Raw, 7) and 2#1#; return Raw_Imm13 (Shift_Left (I_12, 12) or Shift_Left (I_10_5, 5) or Shift_Left (I_4_1, 1) or Shift_Left (I_11, 11)); end Imm13_B; function Funct7 return Raw_Funct7 is (Raw_Funct7 (Shift_Right (Raw, 25) and 2#111_1111#)); function Imm32_U return Word is (Raw and 16#FF_FF_F0_00#); function Imm21_J return Raw_Imm21 is I_20, I_10_1, I_11, I_19_12 : Word; Res : Raw_Imm21; begin I_20 := Shift_Right (Raw, 31) and 2#1#; I_10_1 := Shift_Right (Raw, 21) and 2#11_1111_1111#; I_11 := Shift_Right (Raw, 20) and 2#1#; I_19_12 := Shift_Right (Raw, 12) and 2#1111_1111#; Res := Raw_Imm21 (Shift_Left (I_20, 20) or Shift_Left (I_19_12, 12) or Shift_Left (I_11, 11) or Shift_Left (I_10_1, 1)); return Res; end Imm21_J; Invalid_Insn : constant Instruction := (Kind => Invalid, Raw => Raw); begin case Opcode is when OP_LUI => return (Insn_LUI, RD, Imm32_U); when OP_AUIPC => return (Insn_AUIPC, RD, Imm32_U); when OP_JAL => return (Insn_JAL, RD, Imm21_J); when OP_JALR => if Funct3 /= Funct3_JALR then return Invalid_Insn; else return (Insn_JALR, RD, RS1, Imm12); end if; when OP_Branch => return (case Funct3 is when Funct3_BEQ => (Insn_BEQ, RS1, RS2, Imm13_B), when Funct3_BNE => (Insn_BNE, RS1, RS2, Imm13_B), when Funct3_BLT => (Insn_BLT, RS1, RS2, Imm13_B), when Funct3_BGE => (Insn_BGE, RS1, RS2, Imm13_B), when Funct3_BLTU => (Insn_BLTU, RS1, RS2, Imm13_B), when Funct3_BGEU => (Insn_BGEU, RS1, RS2, Imm13_B), when others => Invalid_Insn); when OP_Load => return (case Funct3 is when Funct3_LB => (Insn_LB, RD, RS1, Imm12), when Funct3_LH => (Insn_LH, RD, RS1, Imm12), when Funct3_LW => (Insn_LW, RD, RS1, Imm12), when Funct3_LBU => (Insn_LBU, RD, RS1, Imm12), when Funct3_LHU => (Insn_LHU, RD, RS1, Imm12), when others => Invalid_Insn); when OP_Store => return (case Funct3 is when Funct3_SB => (Insn_SB, RS1, RS2, Imm12_S), when Funct3_SH => (Insn_SH, RS1, RS2, Imm12_S), when Funct3_SW => (Insn_SW, RS1, RS2, Imm12_S), when others => Invalid_Insn); when OP_OP_IMM => return (case Funct3 is when Funct3_ADDI => (Insn_ADDI, RD, RS1, Imm12), when Funct3_SLTI => (Insn_SLTI, RD, RS1, Imm12), when Funct3_SLTIU => (Insn_SLTIU, RD, RS1, Imm12), when Funct3_XORI => (Insn_XORI, RD, RS1, Imm12), when Funct3_ORI => (Insn_ORI, RD, RS1, Imm12), when Funct3_ANDI => (Insn_ANDI, RD, RS1, Imm12), when Funct3_SLLI => (case Funct7 is when Funct7_SLLI => (Insn_SLLI, RD, RS1, Imm12), when others => Invalid_Insn), when Funct3_SRLI => (case Funct7 is when Funct7_SRLI => (Insn_SRLI, RD, RS1, Imm12), when Funct7_SRAI => (Insn_SRAI, RD, RS1, Imm12), when others => Invalid_Insn)); when OP_OP => return (case Funct3 is when Funct3_ADD_SUB => (case Funct7 is when Funct7_ADD => (Insn_ADD, RD, RS1, RS2), when Funct7_SUB => (Insn_SUB, RD, RS1, RS2), when others => Invalid_Insn), when Funct3_SLL => (case Funct7 is when Funct7_SLL => (Insn_SLL, RD, RS1, RS2), when others => Invalid_Insn), when Funct3_SLT => (case Funct7 is when Funct7_SLT => (Insn_SLT, RD, RS1, RS2), when others => Invalid_Insn), when Funct3_SLTU => (case Funct7 is when Funct7_SLTU => (Insn_SLTU, RD, RS1, RS2), when others => Invalid_Insn), when Funct3_XOR => (case Funct7 is when Funct7_XOR => (Insn_XOR, RD, RS1, RS2), when others => Invalid_Insn), when Funct3_OR => (case Funct7 is when Funct7_OR => (Insn_OR, RD, RS1, RS2), when others => Invalid_Insn), when Funct3_AND => (case Funct7 is when Funct7_AND => (Insn_AND, RD, RS1, RS2), when others => Invalid_Insn), when Funct3_SR => (case Funct7 is when Funct7_SRL => (Insn_SRL, RD, RS1, RS2), when Funct7_SRA => (Insn_SRA, RD, RS1, RS2), when others => Invalid_Insn)); when OP_Misc_Mem => if RD = 0 and then RS1 = 0 then return (case Funct3 is when Funct3_FENCE => (Insn_FENCE, RD, RS1, Imm12), when Funct3_FENCE_I => (Insn_FENCE_I, RD, RS1, Imm12), when others => Invalid_Insn); else return Invalid_Insn; end if; when OP_System => if Funct3 = Funct3_PRIV then if RD = 0 and then RS1 = 0 then return (case Imm12 is when 2#0000000_00000# => (Insn_ECALL, RD, RS1, Imm12), when 2#0000000_00001# => (Insn_EBREAK, RD, RS1, Imm12), when 2#0000000_00010# => (Insn_URET, RD, RS1, Imm12), when 2#0001000_00010# => (Insn_SRET, RD, RS1, Imm12), when 2#0011000_00010# => (Insn_MRET, RD, RS1, Imm12), when others => Invalid_Insn); else return Invalid_Insn; end if; else return (case Funct3 is when Funct3_CSRRW => (Insn_CSRRW, RD, RS1, Imm12), when Funct3_CSRRS => (Insn_CSRRS, RD, RS1, Imm12), when Funct3_CSRRC => (Insn_CSRRC, RD, RS1, Imm12), when Funct3_CSRRWI => (Insn_CSRRWI, RD, RS1, Imm12), when Funct3_CSRRSI => (Insn_CSRRSI, RD, RS1, Imm12), when Funct3_CSRRCI => (Insn_CSRRCI, RD, RS1, Imm12), when others => Invalid_Insn); end if; when others => return Invalid_Insn; end case; end Decode; ------------ -- Encode -- ------------ function Encode (Insn : Instruction) return Word is begin case Insn.Kind is when Invalid => return Insn.Raw; when R_Insn_Kind => return Encode_R (Insn); when I_Insn_Kind => return Encode_I (Insn); when S_Insn_Kind => return Encode_S (Insn); when B_Insn_Kind => return Encode_B (Insn); when U_Insn_Kind => return Encode_U (Insn); when J_Insn_Kind => return Encode_J (Insn); end case; end Encode; ---------------- -- Add_Opcode -- ---------------- procedure Add_Opcode (Raw : in out Word; Op : Raw_Opcode) is begin -- Clear Raw := Raw and not (2#111_1111#); -- Set Raw := Raw or Word (Op); end Add_Opcode; ---------------- -- Add_Funct3 -- ---------------- procedure Add_Funct3 (Raw : in out Word; Funct : Raw_Funct3) is begin -- Clear Raw := Raw and not (2#111_0000_0000_0000#); -- Set Raw := Raw or Shift_Left (Word (Funct), 12); end Add_Funct3; ---------------- -- Add_Funct7 -- ---------------- procedure Add_Funct7 (Raw : in out Word; Funct : Raw_Funct7) is begin -- Clear Raw := Raw and not (2#1111_1110_0000_0000_0000_0000_0000_0000#); -- Set Raw := Raw or Shift_Left (Word (Funct), 25); end Add_Funct7; ------------ -- Add_RD -- ------------ procedure Add_RD (Raw : in out Word; Id : GPR_Id) is begin -- Clear Raw := Raw and not (2#1111_1000_0000#); -- Set Raw := Raw or Shift_Left (Word (Id), 7); end Add_RD; ------------- -- Add_RS1 -- ------------- procedure Add_RS1 (Raw : in out Word; Id : GPR_Id) is begin -- Clear Raw := Raw and not (2#1111_1000_0000_0000_0000#); -- Set Raw := Raw or Shift_Left (Word (Id), 15); end Add_RS1; ------------- -- Add_RS2 -- ------------- procedure Add_RS2 (Raw : in out Word; Id : GPR_Id) is begin -- Clear Raw := Raw and not (2#1_1111_0000_0000_0000_0000_0000#); -- Set Raw := Raw or Shift_Left (Word (Id), 20); end Add_RS2; ----------------- -- Add_Imm13_B -- ----------------- procedure Add_Imm13_B (Raw : in out Word; Imm : Raw_Imm13) is I_12, I_10_5, I_4_1, I_11 : Word; begin -- Clear Raw := Raw and not (2#1111_1110_0000_0000_0001_1111_1000_0000#); I_12 := Shift_Right (Word (Imm), 12) and 2#1#; I_10_5 := Shift_Right (Word (Imm), 5) and 2#11_1111#; I_4_1 := Shift_Right (Word (Imm), 1) and 2#1111#; I_11 := Shift_Right (Word (Imm), 11) and 2#1#; -- Set Raw := Raw or ((Shift_Left (I_12, 31) or Shift_Left (I_10_5, 25) or Shift_Left (I_4_1, 8) or Shift_Left (I_11, 7))); end Add_Imm13_B; ----------------- -- Add_Imm12_I -- ----------------- procedure Add_Imm12_I (Raw : in out Word; Imm : Raw_Imm12) is begin -- Clear Raw := Raw and not (2#1111_1111_1111_0000_0000_0000_0000_0000#); -- Set Raw := Raw or (Shift_Left (Word (Imm), 20)); end Add_Imm12_I; ----------------- -- Add_Imm12_S -- ----------------- procedure Add_Imm12_S (Raw : in out Word; Imm : Raw_Imm12) is I_4_0, I_11_5 : Word; begin -- Clear Raw := Raw and not (2#1111_1110_0000_0000_0000_1111_1000_0000#); I_4_0 := Word (Imm) and 2#1_1111#; I_11_5 := Shift_Right (Word (Imm), 5) and 2#11_1111#; -- Set Raw := Raw or ((Shift_Left (I_11_5, 25) or Shift_Left (I_4_0, 7))); end Add_Imm12_S; ----------------- -- Add_Imm21_J -- ----------------- procedure Add_Imm21_J (Raw : in out Word; Imm : Raw_Imm21) is I_20, I_10_1, I_19_12, I_11 : Word; begin -- Clear Raw := Raw and not (2#1111_1110_0000_0000_0001_1111_1000_0000#); I_20 := Shift_Right (Word (Imm), 20) and 2#1#; I_10_1 := Shift_Right (Word (Imm), 1) and 2#11_1111_1111#; I_19_12 := Shift_Right (Word (Imm), 12) and 2#1111_1111#; I_11 := Shift_Right (Word (Imm), 11) and 2#1#; -- Set Raw := Raw or ((Shift_Left (I_20, 31) or Shift_Left (I_10_1, 21) or Shift_Left (I_19_12, 12) or Shift_Left (I_11, 20))); end Add_Imm21_J; -------------- -- Encode_R -- -------------- function Encode_R (Insn : Instruction) return Word is Raw : Word := 0; begin Add_RD (Raw, Insn.R_RD); Add_RS1 (Raw, Insn.R_RS1); Add_RS2 (Raw, Insn.R_RS2); Add_Opcode (Raw, OP_OP); Add_Funct3 (Raw, (case Insn.Kind is when Insn_ADD | Insn_SUB => Funct3_ADD_SUB, when Insn_SLL => Funct3_SLL, when Insn_SLT => Funct3_SLT, when Insn_SLTU => Funct3_SLTU, when Insn_XOR => Funct3_XOR, when Insn_SRL | Insn_SRA => Funct3_SR, when Insn_OR => Funct3_OR, when Insn_AND => Funct3_AND, when others => raise Program_Error)); Add_Funct7 (Raw, (case Insn.Kind is when Insn_ADD => Funct7_ADD, when Insn_SUB => Funct7_SUB, when Insn_SLL => Funct7_SLL, when Insn_SLT => Funct7_SLT, when Insn_SLTU => Funct7_SLTU, when Insn_XOR => Funct7_XOR, when Insn_SRL => Funct7_SRL, when Insn_SRA => Funct7_SRA, when Insn_OR => Funct7_OR, when Insn_AND => Funct7_AND, when others => raise Program_Error)); return Raw; end Encode_R; -------------- -- Encode_I -- -------------- function Encode_I (Insn : Instruction) return Word is Raw : Word := 0; begin Add_RD (Raw, Insn.I_RD); Add_RS1 (Raw, Insn.I_RS1); -- Ensure correct Imm some special instructions case Insn.Kind is when Insn_FENCE_I | Insn_ECALL => Add_Imm12_I (Raw, 0); when Insn_EBREAK => Add_Imm12_I (Raw, 1); when others => Add_Imm12_I (Raw, Insn.I_Imm); end case; Add_Opcode (Raw, (case Insn.Kind is when Insn_SLLI => OP_OP_IMM, when Insn_SRLI => OP_OP_IMM, when Insn_SRAI => OP_OP_IMM, when Insn_ADDI => OP_OP_IMM, when Insn_SLTI => OP_OP_IMM, when Insn_SLTIU => OP_OP_IMM, when Insn_XORI => OP_OP_IMM, when Insn_ORI => OP_OP_IMM, when Insn_ANDI => OP_OP_IMM, when Insn_JALR => OP_JALR, when Insn_LB => OP_Load, when Insn_LH => OP_Load, when Insn_LW => OP_Load, when Insn_LBU => OP_Load, when Insn_LHU => OP_Load, when Insn_FENCE => OP_Misc_Mem, when Insn_FENCE_I => OP_Misc_Mem, when Insn_ECALL => OP_System, when Insn_EBREAK => OP_System, when Insn_CSRRW => OP_System, when Insn_CSRRS => OP_System, when Insn_CSRRC => OP_System, when Insn_CSRRWI => OP_System, when Insn_CSRRSI => OP_System, when Insn_CSRRCI => OP_System, when Insn_URET => OP_System, when Insn_SRET => OP_System, when Insn_MRET => OP_System, when others => raise Program_Error)); Add_Funct3 (Raw, (case Insn.Kind is when Insn_SLLI => Funct3_SLLI, when Insn_SRLI => Funct3_SRLI, when Insn_SRAI => Funct3_SR, when Insn_ADDI => Funct3_ADDI, when Insn_SLTI => Funct3_SLTI, when Insn_SLTIU => Funct3_SLTIU, when Insn_XORI => Funct3_XORI, when Insn_ORI => Funct3_ORI, when Insn_ANDI => Funct3_ANDI, when Insn_JALR => Funct3_JALR, when Insn_LB => Funct3_LB, when Insn_LH => Funct3_LH, when Insn_LW => Funct3_LW, when Insn_LBU => Funct3_LBU, when Insn_LHU => Funct3_LHU, when Insn_FENCE => Funct3_FENCE, when Insn_FENCE_I => Funct3_FENCE_I, when Insn_ECALL => Funct3_ECALL, when Insn_EBREAK => Funct3_EBREAK, when Insn_CSRRW => Funct3_CSRRW, when Insn_CSRRS => Funct3_CSRRS, when Insn_CSRRC => Funct3_CSRRC, when Insn_CSRRWI => Funct3_CSRRWI, when Insn_CSRRSI => Funct3_CSRRSI, when Insn_CSRRCI => Funct3_CSRRCI, when Insn_URET => Funct3_PRIV, when Insn_SRET => Funct3_PRIV, when Insn_MRET => Funct3_PRIV, when others => raise Program_Error)); return Raw; end Encode_I; -------------- -- Encode_S -- -------------- function Encode_S (Insn : Instruction) return Word is Raw : Word := 0; begin Add_RS1 (Raw, Insn.S_RS1); Add_RS2 (Raw, Insn.S_RS2); Add_Imm12_S (Raw, Insn.S_Imm); Add_Opcode (Raw, OP_Store); Add_Funct3 (Raw, (case Insn.Kind is when Insn_SB => Funct3_SB, when Insn_SH => Funct3_SH, when Insn_SW => Funct3_SW, when others => raise Program_Error)); return Raw; end Encode_S; -------------- -- Encode_B -- -------------- function Encode_B (Insn : Instruction) return Word is Raw : Word := 0; begin Add_RS1 (Raw, Insn.B_RS1); Add_RS2 (Raw, Insn.B_RS2); Add_Opcode (Raw, OP_Branch); Add_Imm13_B (Raw, Insn.B_Imm); Add_Funct3 (Raw, (case Insn.Kind is when Insn_BEQ => Funct3_BEQ, when Insn_BNE => Funct3_BNE, when Insn_BLT => Funct3_BLT, when Insn_BGE => Funct3_BGE, when Insn_BLTU => Funct3_BLTU, when Insn_BGEU => Funct3_BGEU, when others => raise Program_Error)); return Raw; end Encode_B; -------------- -- Encode_U -- -------------- function Encode_U (Insn : Instruction) return Word is Raw : Word := Insn.U_Imm; begin Add_RD (Raw, Insn.U_RD); Add_Opcode (Raw, (case Insn.Kind is when Insn_LUI => OP_LUI, when Insn_AUIPC => OP_AUIPC, when others => raise Program_Error)); return Raw; end Encode_U; -------------- -- Encode_J -- -------------- function Encode_J (Insn : Instruction) return Word is Raw : Word := 0; begin Add_RD (Raw, Insn.J_RD); Add_Imm21_J (Raw, Insn.J_Imm); Add_Opcode (Raw, (case Insn.Kind is when Insn_JAL => OP_JAL, when others => raise Program_Error)); return Raw; end Encode_J; --------- -- Img -- --------- function Img (Insn : Instruction; Addr : Address) return String is use ESF; begin if Insn.Kind in Insn_CSRRW .. Insn_CSRRC then return Fmt ("0x\s\t\s\t\s, \s, \s", Hex (Addr), Img (Insn.Kind), Img (Insn.I_RD), CSR.Img (CSR.Id (Insn.I_Imm)), Img (Insn.I_RS1)); elsif Insn.Kind in Insn_CSRRWI .. Insn_CSRRCI then return Fmt ("0x\s\t\s\t\s, \s, \s", Hex (Addr), Img (Insn.Kind), Img (Insn.I_RD), CSR.Img (CSR.Id (Insn.I_Imm)), Insn.I_RS1'Img); else case Insn.Kind is when Invalid => return Fmt ("0x\s\tinvalid 0x\s", Hex (Addr), Hex (Insn.Raw)); when R_Insn_Kind => return Fmt ("0x\s\t\s\t\s, \s, \s", Hex (Addr), Img (Insn.Kind), Img (Insn.R_RD), Img (Insn.R_RS1), Img (Insn.R_RS2)); when I_Insn_Kind => if Insn.Kind in Insn_FENCE | Insn_FENCE_I | Insn_ECALL | Insn_EBREAK | Insn_URET | Insn_MRET | Insn_SRET then return Fmt ("0x\s\t\s", Hex (Addr), Img (Insn.Kind)); else return Fmt ("0x\s\t\s\t\s, \s, \s", Hex (Addr), Img (Insn.Kind), Img (Insn.I_RD), Img (Insn.I_RS1), Insn.I_Imm'Img); end if; when S_Insn_Kind => return Fmt ("0x\s\t\s\t\s, \s(\s)", Hex (Addr), Img (Insn.Kind), Img (Insn.S_RS2), Sign_Extend (Insn.S_Imm).S'Img, Img (Insn.S_RS1)); when B_Insn_Kind => return Fmt ("0x\s\t\s\t\s, \s, \s", Hex (Addr), Img (Insn.Kind), Img (Insn.B_RS1), Img (Insn.B_RS2), Sign_Extend (Insn.B_Imm).S'Img); when U_Insn_Kind => return Fmt ("0x\s\t\s\t\s, \s", Hex (Addr), Img (Insn.Kind), Img (Insn.U_RD), Insn.U_Imm'Img); when J_Insn_Kind => return Fmt ("0x\s\t\s\t\s, \s", Hex (Addr), Img (Insn.Kind), Img (Insn.J_RD), Sign_Extend (Insn.J_Imm).S'Img); end case; end if; end Img; --------- -- Img -- --------- function Img (Kind : Insn_Kind) return String is (case Kind is when Invalid => "invalid", when Insn_ADD => "add", when Insn_SUB => "sub", when Insn_SLL => "sll", when Insn_SLT => "slt", when Insn_SLTU => "sltu", when Insn_XOR => "xor", when Insn_SRL => "srl", when Insn_SRA => "sra", when Insn_OR => "or", when Insn_AND => "and", when Insn_BEQ => "beq", when Insn_BNE => "bne", when Insn_BLT => "blt", when Insn_BGE => "bge", when Insn_BLTU => "bltu", when Insn_BGEU => "bgeu", when Insn_SB => "sb", when Insn_SH => "sh", when Insn_SW => "sw", when Insn_SLLI => "slli", when Insn_SRLI => "srli", when Insn_SRAI => "srai", when Insn_JALR => "jalr", when Insn_LB => "lb", when Insn_LH => "lh", when Insn_LW => "lw", when Insn_LBU => "lbu", when Insn_LHU => "lhu", when Insn_ADDI => "addi", when Insn_SLTI => "slti", when Insn_SLTIU => "sltiu", when Insn_XORI => "xori", when Insn_ORI => "ori", when Insn_ANDI => "andi", when Insn_FENCE => "fence", when Insn_FENCE_I => "fence.i", when Insn_ECALL => "ecall", when Insn_EBREAK => "ebreak", when Insn_CSRRW => "csrrw", when Insn_CSRRS => "csrrs", when Insn_CSRRC => "csrrc", when Insn_CSRRWI => "csrrwi", when Insn_CSRRSI => "csrrsi", when Insn_CSRRCI => "csrrci", when Insn_URET => "uret", when Insn_SRET => "sret", when Insn_MRET => "mret", when Insn_LUI => "lui", when Insn_AUIPC => "auipc", when Insn_JAL => "jal" ); ----------------- -- Sign_Extend -- ----------------- function Sign_Extend (Imm : Raw_Imm12) return Register is U : U_Register; begin if (Imm and 2#1000_0000_0000#) /= 0 then U := 16#FF_FF_F8_00# or U_Register (Imm); else U := U_Register (Imm); end if; return (Signed => False, U => U); end Sign_Extend; ----------------- -- Sign_Extend -- ----------------- function Sign_Extend (Imm : Raw_Imm13) return Register is U : U_Register; begin if (Imm and 2#1_0000_0000_0000#) /= 0 then U := 16#FF_FF_E0_00# or U_Register (Imm); else U := U_Register (Imm); end if; return (Signed => False, U => U); end Sign_Extend; ----------------- -- Sign_Extend -- ----------------- function Sign_Extend (Imm : Raw_Imm21) return Register is U : U_Register; begin if (Imm and 2#1_0000_0000_0000_0000_0000#) /= 0 then U := 16#FF_E0_00_00# or U_Register (Imm); else U := U_Register (Imm); end if; return (Signed => False, U => U); end Sign_Extend; end LibRISCV.Instructions;
-- part of AdaYaml, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" with Yaml.Dom.Sequence_Data; with Yaml.Dom.Mapping_Data; package Yaml.Dom.Node is type Instance (Kind : Node_Kind) is record Tag : Text.Reference; case Kind is when Scalar => Scalar_Style : Scalar_Style_Type; Content : Text.Reference; when Sequence => Sequence_Style : Collection_Style_Type; Items : Sequence_Data.Instance; when Mapping => Mapping_Style : Collection_Style_Type; Pairs : Mapping_Data.Instance; end case; end record; function "=" (Left, Right : Instance) return Boolean; function Hash (Object : Instance) return Ada.Containers.Hash_Type; end Yaml.Dom.Node;
-- with -- Glx; package openGL.Surface.privvy is -- function to_glx (Self : in Surface.item'Class) return glx.GLXDrawable; procedure dummy; end openGL.Surface.privvy;
----------------------------------------------------------------------- -- Util-texts -- Various Text Transformation Utilities -- Copyright (C) 2001, 2002, 2003, 2009, 2010 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. ----------------------------------------------------------------------- generic type Stream is limited private; type Char is (<>); type Input is array (Positive range <>) of Char; with procedure Put (Buffer : in out Stream; C : in Character); with function To_Upper (C : Char) return Char; with function To_Lower (C : Char) return Char; with function To_Input (S : Stream) return Input; package Util.Texts.Transforms is pragma Preelaborate; -- Capitalize the string into the result stream. procedure Capitalize (Content : in Input; Into : in out Stream); -- Capitalize the string function Capitalize (Content : Input) return Input; -- Translate the input string into an upper case string in the result stream. procedure To_Upper_Case (Content : in Input; Into : in out Stream); -- Translate the input string into an upper case string. function To_Upper_Case (Content : Input) return Input; -- Translate the input string into a lower case string in the result stream. procedure To_Lower_Case (Content : in Input; Into : in out Stream); function To_Lower_Case (Content : Input) return Input; -- Write in the output stream the value as a \uNNNN encoding form. procedure To_Hex (Into : in out Stream; Value : in Char); pragma Inline_Always (To_Hex); -- Escape the content into the result stream using the JavaScript -- escape rules. procedure Escape_Java_Script (Content : in Input; Into : in out Stream); function Escape_Java_Script (Content : Input) return Input; -- Escape the content into the result stream using the Java -- escape rules. procedure Escape_Java (Content : in Input; Into : in out Stream); function Escape_Java (Content : Input) return Input; -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 procedure Escape_Xml (Content : in Input; Into : in out Stream); function Escape_Xml (Content : Input) return Input; -- Translate the XML entity represented by <tt>Entity</tt> into an UTF-8 sequence -- in the output stream. procedure Translate_Xml_Entity (Entity : in Input; Into : in out Stream); -- Unescape the XML entities from the content into the result stream. -- For each XML entity found, call the <tt>Translator</tt> procedure who is responsible -- for writing the result in the stream. The XML entity starts with '&' and ends with ';'. -- The '&' and ';' are part of the entity when given to the translator. If the trailing -- ';' is not part of the entity, it means the entity was truncated or the end of input -- stream is reached. procedure Unescape_Xml (Content : in Input; Translator : not null access procedure (Entity : in Input; Into : in out Stream) := Translate_Xml_Entity'Access; Into : in out Stream); private procedure Put (Into : in out Stream; Value : in String); procedure Escape_Java (Content : in Input; Escape_Single_Quote : in Boolean; Into : in out Stream); end Util.Texts.Transforms;
with Ada.Text_IO; with Ada.Integer_Text_IO; package body Problem_36 is package IO renames Ada.Text_IO; package I_IO renames Ada.Integer_Text_IO; function Is_Palindrome(s : String) return Boolean is left : Integer := s'First; right : Integer := s'Last; begin while left <= right loop if s(left) /= s(right) then return False; end if; left := Integer'Succ(left); right := Integer'Pred(right); end loop; return True; end Is_Palindrome; function Decimal(num : Integer) return String is function Dec_Mag(num : Integer) return Integer is begin if num >= 1_000_000 then return 7; elsif num >= 100_000 then return 6; elsif num >= 10_000 then return 5; elsif num >= 1_000 then return 4; elsif num >= 100 then return 3; elsif num >= 10 then return 2; else return 1; end if; end Dec_Mag; s : String (1 .. Dec_Mag(num)); n : Integer := Num; begin for index in reverse s'Range loop s(index) := Character'Val(Character'Pos('0') + (n mod 10)); n := n / 10; end loop; return s; end Decimal; function Binary(num: Integer) return String is function Bin_Mag(num : Integer) return Integer is begin if num >= 2**17 then return 17; elsif num >= 2**16 then return 16; elsif num >= 2**15 then return 15; elsif num >= 2**14 then return 14; elsif num >= 2**13 then return 13; elsif num >= 2**12 then return 12; elsif num >= 2**11 then return 11; elsif num >= 2**10 then return 10; elsif num >= 2**9 then return 9; elsif num >= 2**8 then return 8; elsif num >= 2**7 then return 7; elsif num >= 2**6 then return 6; elsif num >= 2**5 then return 5; elsif num >= 2**4 then return 4; elsif num >= 2**3 then return 3; elsif num >= 2**2 then return 2; elsif num >= 2**1 then return 1; else return 0; end if; end Bin_Mag; s : String(1 .. Bin_Mag(num) + 1); n : Integer := num; begin for index in reverse s'Range loop s(index) := Character'Val(Character'Pos('0') + (n mod 2)); n := n / 2; end loop; return s; end Binary; procedure Solve is num : Integer := 1; sum : Integer := 0; begin while num < 1_000_000 loop if Is_Palindrome(Decimal(num)) and Is_Palindrome(Binary(num)) then sum := sum + num; end if; num := num + 2; end loop; I_IO.Put(sum); IO.New_Line; end Solve; end Problem_36;