content
stringlengths
23
1.05M
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Range_Expansion is type Sequence is array (Positive range <>) of Integer; function Expand (Text : String) return Sequence is To : Integer := Text'First; Count : Natural := 0; Low : Integer; function Get return Integer is From : Integer := To; begin if Text (To) = '-' then To := To + 1; end if; while To <= Text'Last loop case Text (To) is when ',' | '-' => exit; when others => To := To + 1; end case; end loop; return Integer'Value (Text (From..To - 1)); end Get; begin while To <= Text'Last loop -- Counting items of the list Low := Get; if To > Text'Last or else Text (To) = ',' then Count := Count + 1; else To := To + 1; Count := Count + Get - Low + 1; end if; To := To + 1; end loop; return Result : Sequence (1..Count) do Count := 0; To := Text'First; while To <= Text'Last loop -- Filling the list Low := Get; if To > Text'Last or else Text (To) = ',' then Count := Count + 1; Result (Count) := Low; else To := To + 1; for Item in Low..Get loop Count := Count + 1; Result (Count) := Item; end loop; end if; To := To + 1; end loop; end return; end Expand; procedure Put (S : Sequence) is First : Boolean := True; begin for I in S'Range loop if First then First := False; else Put (','); end if; Put (Integer'Image (S (I))); end loop; end Put; begin Put (Expand ("-6,-3--1,3-5,7-11,14,15,17-20")); end Test_Range_Expansion;
package Compiler.Parser is use Node_List; function Parse(AST_In: List) return List; private end Compiler.Parser;
with Ada.Naked_Text_IO; package body Ada.Text_IO.Terminal is use type IO_Modes.File_Mode; use type IO_Modes.File_External; -- implementation function Is_Terminal ( File : File_Type) return Boolean is pragma Check (Dynamic_Predicate, Check => Is_Open (File) or else raise Status_Error); NC_File : Naked_Text_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin return Naked_Text_IO.External (NC_File) = IO_Modes.Terminal; end Is_Terminal; procedure Set_Size ( File : File_Type; Size : Size_Type) is begin Set_Size ( File, -- checking the predicate Size.Line_Length, Size.Page_Length); end Set_Size; procedure Set_Size ( File : File_Type; Line_Length, Page_Length : Count) is pragma Check (Dynamic_Predicate, Check => Is_Open (File) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Mode (File) /= In_File or else raise Mode_Error); NC_File : Naked_Text_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin System.Native_Text_IO.Set_Terminal_Size ( Naked_Text_IO.Terminal_Handle (NC_File), Integer (Line_Length), Integer (Page_Length)); end Set_Size; function Size ( File : File_Type) return Size_Type is begin return Result : Size_Type do Size ( File, -- checking the predicate Result.Line_Length, Result.Page_Length); end return; end Size; procedure Size ( File : File_Type; Line_Length, Page_Length : out Count) is pragma Check (Dynamic_Predicate, Check => Is_Open (File) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Mode (File) /= In_File or else raise Mode_Error); NC_File : Naked_Text_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin System.Native_Text_IO.Terminal_Size ( Naked_Text_IO.Terminal_Handle (NC_File), Natural'Base (Line_Length), Natural'Base (Page_Length)); end Size; function View ( File : File_Type) return View_Type is begin return Result : View_Type do View ( File, -- checking the predicate Result.Left, Result.Top, Result.Right, Result.Bottom); end return; end View; procedure View ( File : File_Type; Left, Top : out Positive_Count; Right, Bottom : out Count) is pragma Check (Dynamic_Predicate, Check => Is_Open (File) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Mode (File) /= In_File or else raise Mode_Error); NC_File : Naked_Text_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin System.Native_Text_IO.Terminal_View ( Naked_Text_IO.Terminal_Handle (NC_File), Positive'Base (Left), Positive'Base (Top), Natural'Base (Right), Natural'Base (Bottom)); end View; procedure Set_Position ( File : File_Type; Position : Position_Type) is begin Set_Position ( File, -- checking the predicate Position.Col, Position.Line); end Set_Position; procedure Set_Position ( File : File_Type; Col, Line : Positive_Count) is pragma Check (Dynamic_Predicate, Check => Is_Open (File) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Mode (File) /= In_File or else raise Mode_Error); NC_File : Naked_Text_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin System.Native_Text_IO.Set_Terminal_Position ( Naked_Text_IO.Terminal_Handle (NC_File), Integer (Col), Integer (Line)); end Set_Position; procedure Set_Col ( File : File_Type; To : Positive_Count) is pragma Check (Dynamic_Predicate, Check => Is_Open (File) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Mode (File) /= In_File or else raise Mode_Error); NC_File : Naked_Text_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin System.Native_Text_IO.Set_Terminal_Col ( Naked_Text_IO.Terminal_Handle (NC_File), Integer (To)); end Set_Col; function Position ( File : File_Type) return Position_Type is begin return Result : Position_Type do Position ( File, -- checking the predicate Result.Col, Result.Line); end return; end Position; procedure Position ( File : File_Type; Col, Line : out Positive_Count) is pragma Check (Dynamic_Predicate, Check => Is_Open (File) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Mode (File) /= In_File or else raise Mode_Error); NC_File : Naked_Text_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin System.Native_Text_IO.Terminal_Position ( Naked_Text_IO.Terminal_Handle (NC_File), Positive'Base (Col), Positive'Base (Line)); end Position; procedure Save_State ( File : File_Type; To_State : out Output_State) is pragma Check (Dynamic_Predicate, Check => Is_Open (File) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Mode (File) /= In_File or else raise Mode_Error); NC_File : Naked_Text_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin System.Native_Text_IO.Save_State ( Naked_Text_IO.Terminal_Handle (NC_File), System.Native_Text_IO.Output_State (To_State)); end Save_State; procedure Reset_State ( File : File_Type; From_State : Output_State) is pragma Check (Dynamic_Predicate, Check => Is_Open (File) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Mode (File) /= In_File or else raise Mode_Error); NC_File : Naked_Text_IO.Non_Controlled_File_Type renames Controlled.Reference (File).all; begin System.Native_Text_IO.Reset_State ( Naked_Text_IO.Terminal_Handle (NC_File), System.Native_Text_IO.Output_State (From_State)); end Reset_State; end Ada.Text_IO.Terminal;
pragma License (Unrestricted); -- AARM A.16(124.b/2), specialized for Windows private with C.windef; package Ada.Directories.Information is -- System-specific directory information. -- Version for the Microsoft(R) Windows(R) operating system. function Creation_Time (Name : String) return Calendar.Time; function Last_Access_Time (Name : String) return Calendar.Time; function Is_Read_Only (Name : String) return Boolean; function Needs_Archiving (Name : String) return Boolean; -- This generally means that the file needs to be backed up. -- The flag is only cleared by backup programs. function Is_Compressed (Name : String) return Boolean; function Is_Encrypted (Name : String) return Boolean; function Is_Hidden (Name : String) return Boolean; function Is_System (Name : String) return Boolean; function Is_Offline (Name : String) return Boolean; function Is_Temporary (Name : String) return Boolean; function Is_Sparse (Name : String) return Boolean; function Is_Not_Indexed (Name : String) return Boolean; function Creation_Time ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Calendar.Time; function Last_Access_Time ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Calendar.Time; function Is_Read_Only ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; function Needs_Archiving ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; -- This generally means that the file needs to be backed up. -- The flag is only cleared by backup programs. function Is_Compressed ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; function Is_Encrypted ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; function Is_Hidden ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; function Is_System ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; function Is_Offline ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; function Is_Temporary ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; function Is_Sparse ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; function Is_Not_Indexed ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; -- Additional implementation-defined subprograms allowed here. -- extended function Is_Symbolic_Link (Name : String) return Boolean; function Is_Symbolic_Link ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return Boolean; -- extended from here -- The permissions of the current user. type User_Permission is (User_Execute, User_Write, User_Read); type User_Permission_Set_Type is array (User_Permission) of Boolean; pragma Pack (User_Permission_Set_Type); function User_Permission_Set (Name : String) return User_Permission_Set_Type; function User_Permission_Set ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return User_Permission_Set_Type; -- to here -- extended -- Unique file identifier. type File_Id is private; function Identity (Name : String) return File_Id; function Identity ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return File_Id; -- unimplemented, source-level compatibility with POSIX function Owner (Name : String) return String with Import, Convention => Ada, External_Name => "__drake_program_error"; function Owner ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return String with Import, Convention => Ada, External_Name => "__drake_program_error"; function Group (Name : String) return String with Import, Convention => Ada, External_Name => "__drake_program_error"; function Group ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return String with Import, Convention => Ada, External_Name => "__drake_program_error"; function Read_Symbolic_Link (Name : String) return String with Import, Convention => Ada, External_Name => "__drake_program_error"; function Read_Symbolic_Link ( Directory_Entry : Directory_Entry_Type) -- Assigned_Directory_Entry_Type return String with Import, Convention => Ada, External_Name => "__drake_program_error"; private type File_Id is record -- These should be extend to 128bit for ReFS. FileIndexLow : C.windef.DWORD; FileIndexHigh : C.windef.DWORD; VolumeSerialNumber : C.windef.DWORD; end record; end Ada.Directories.Information;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $ package body Gela.Embeded_Links.Double_Lists is package S renames Simple_Lists; subtype L is Simple_Lists.List; ------------ -- Append -- ------------ procedure Append (Container : in out List; New_Item : in Element_Access) is begin Set_Prev (New_Item, Last (Container)); S.Append (L (Container), New_Item); end Append; ----------- -- Clear -- ----------- procedure Clear (Container : in out List) is Next : aliased Element_Access; begin while Iterate (Container, Next'Access) loop Set_Prev (Next, null); end loop; S.Clear (L (Container)); end Clear; ------------ -- Delete -- ------------ procedure Delete (Container : in out List; Item : in Element_Access) is Ignore : Element_Access; begin if Item = First (Container) then Delete_First (Container, Ignore); else Delete_Next (Container, Get_Prev (Item), Ignore); end if; Set_Prev (Item, null); end Delete; ------------------ -- Delete_First -- ------------------ procedure Delete_First (Container : in out List; Removed : out Element_Access) is begin S.Delete_First (L (Container), Removed); if Removed /= null then Set_Prev (Removed, null); end if; if First (Container) /= null then Set_Prev (First (Container), null); end if; end Delete_First; ----------------- -- Delete_Last -- ----------------- procedure Delete_Last (Container : in out List; Removed : out Element_Access) is begin if Is_Empty (Container) then Removed := null; elsif Last (Container) = First (Container) then Delete_First (Container, Removed); else Delete_Next (Container, Get_Prev (Last (Container)), Removed); end if; end Delete_Last; ----------------- -- Delete_Next -- ----------------- procedure Delete_Next (Container : in out List; After : in Element_Access; Removed : out Element_Access) is begin S.Delete_Next (L (Container), After, Removed); if Removed /= null then if After /= Last (Container) then Set_Prev (Get_Next (After), Get_Prev (Removed)); end if; Set_Prev (Removed, null); end if; end Delete_Next; ------------ -- Insert -- ------------ procedure Insert (Container : in out List; Before : in Element_Access; New_Item : in Element_Access) is begin if Before = First (Container) then Prepend (Container, New_Item); else S.Insert_After (L (Container), Get_Prev (Before), New_Item); end if; end Insert; ------------------ -- Insert_After -- ------------------ procedure Insert_After (Container : in out List; After : in Element_Access; New_Item : in Element_Access) is begin S.Insert_After (L (Container), After, New_Item); Set_Prev (New_Item, After); end Insert_After; ------------- -- Prepend -- ------------- procedure Prepend (Container : in out List; New_Item : in Element_Access) is Head : constant Element_Access := First (Container); begin if Head /= null then Set_Prev (Head, New_Item); end if; S.Prepend (L (Container), New_Item); end Prepend; ------------------ -- Splice_After -- ------------------ procedure Splice_After (Target : in out List; Source : in out List; After : in Element_Access := null) is Head : constant Element_Access := First (Source); begin if Head /= null then Set_Prev (Head, Last (Target)); end if; S.Splice_After (L (Target), L (Source), After); end Splice_After; end Gela.Embeded_Links.Double_Lists; ------------------------------------------------------------------------------ -- Copyright (c) 2006, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
-- Copyright 2019 Michael Casadevall <michael@casadevall.pro> -- -- 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.Containers.Vectors; use Ada.Containers; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Streams; use Ada.Streams; with Interfaces.C.Extensions; use Interfaces.C.Extensions; with DNSCatcher.DNS; use DNSCatcher.DNS; with DNSCatcher.Types; use DNSCatcher.Types; with DNSCatcher.Utils.Logger; use DNSCatcher.Utils.Logger; with DNSCatcher.DNS.Processor.RData; use DNSCatcher.DNS.Processor.RData; -- @summary -- -- Handles processing of raw DNS packets and their representation from wire -- form to useful data structures. -- -- @description -- -- The Packet Processor is the top level interface for parsing a packet, and -- getting useful information out of it. It also parses RData throught the -- RData processor to create a single set of record(s) that describe a given -- DNS packet -- package DNSCatcher.DNS.Processor.Packet is -- Logicial representation of a DNS Question packet type Parsed_DNS_Question is record QName : Unbounded_String; -- Domain the question is asked for QType : RR_Types; -- QType RRType desired by client QClass : Classes; -- DNS Class queried end record; -- Logicial representation of a parsed DNS Resource Record type Parsed_DNS_Resource_Record is record RName : Unbounded_String; -- Resource Name RType : RR_Types; -- Resource Record Type RClass : Unsigned_16; -- DNS Class RCode : Unsigned_4; -- Response code TTL : Unsigned_32; -- Time to Live RData : Unbounded_String; -- Raw RData response Raw_Packet : Stream_Element_Array_Ptr; -- Raw packet data, used by RData parser RData_Offset : Stream_Element_Offset; -- Offset within raw packet to start of RData end record; -- Vector class for questions package Question_Vector is new Vectors (Positive, Parsed_DNS_Question); -- Vector class for Resource Records package Resource_Record_Vector is new Vectors (Positive, Parsed_RData_Access); -- Parsed DNS Packet type Parsed_DNS_Packet is record Header : DNS_Packet_Header; -- DNS Packet Header Questions : Question_Vector.Vector; -- Questions section Answer : Resource_Record_Vector.Vector; -- Answers section Authority : Resource_Record_Vector.Vector; -- Authoritive section Additional : Resource_Record_Vector.Vector; -- Additional Section end record; type Parsed_DNS_Packet_Ptr is access Parsed_DNS_Packet; -- Converts raw DNS packets into parsed DNS packets -- -- @value Logger -- Pointer to the a logger message packet from the caller -- -- @value Packet -- Raw DNS data gathered from DNSCatcher.Network.* -- -- @returns -- Pointer to parsed DNS data; must be freed by caller -- function Packet_Parser (Logger : Logger_Message_Packet_Ptr; Packet : Raw_Packet_Record_Ptr) return Parsed_DNS_Packet_Ptr; pragma Test_Case (Name => "Packet_Parser", Mode => Robustness); Unknown_RCode : exception; Unknown_RR_Type : exception; Unknown_Class : exception; Unknown_Compression_Method : exception; -- Converts DNS names in packets to string -- -- The full packet is required due to DNS compression -- -- @value Raw_Data -- Pointer to the full packet -- -- @value Offset -- Offet to the string to decode -- -- @returns -- Unbounded_String with the DNS name decoded or exception -- function Parse_DNS_Packet_Name_Records (Raw_Data : Raw_DNS_Packet_Data_Ptr; Offset : in out Stream_Element_Offset) return Unbounded_String; -- Converts DNS RR Types in packets to RRTypes Enum -- -- @value Raw_Data -- Pointer to the full packet -- -- @value Offset -- Offet to the string to decode -- -- @returns -- DNS RR_Type -- function Parse_DNS_RR_Type (Raw_Data : Raw_DNS_Packet_Data_Ptr; Offset : in out Stream_Element_Offset) return RR_Types; -- Converts DNS Class in packets to DNS Class Enum -- -- @value Raw_Data -- Pointer to the full packet -- -- @value Offset -- Offet to the string to decode -- -- @returns -- DNS Class -- function Parse_DNS_Class (Raw_Data : Raw_DNS_Packet_Data_Ptr; Offset : in out Stream_Element_Offset) return Classes; -- Converts DNS Questions in packets to logicial representation -- -- @value Logger -- Pointer to logger message packet -- -- @value Raw_Data -- The full packet data section to decode -- -- @value Offset -- Offet to the string to decode -- -- @returns -- Parsed DNS Question -- function Parse_Question_Record (Logger : Logger_Message_Packet_Ptr; Raw_Data : Raw_DNS_Packet_Data_Ptr; Offset : in out Stream_Element_Offset) return Parsed_DNS_Question; -- Converts DNS resource record to logicial representation -- -- @value Logger -- Pointer to logger message packet -- -- @value Packet -- The full packet to decode -- -- @value Offset -- Offet to the resource record to decode -- -- @returns -- Parsed Resource Record -- function Parse_Resource_Record_Response (Logger : Logger_Message_Packet_Ptr; Packet : Raw_DNS_Packet; Offset : in out Stream_Element_Offset) return Parsed_RData_Access; -- Deallocators -- Deallocation helper for Parsed_DNS_Packet_Ptrs -- -- @value Packet -- The packet to be deallocated -- procedure Free_Parsed_DNS_Packet (Packet : in out Parsed_DNS_Packet_Ptr); end DNSCatcher.DNS.Processor.Packet;
with Entities; use Entities; with Vectors2D; use Vectors2D; with Ada.Containers.Doubly_Linked_Lists; with Links; use Links; with Collisions; use Collisions; package Worlds is package EntsList is new Ada.Containers.Doubly_Linked_Lists(EntityClassAcc); type EntsListAcc is access EntsList.List; package LinksList is new Ada.Containers.Doubly_Linked_Lists(LinkAcc); type LinksListAcc is access LinksList.List; type SearchModes is (SM_Entity, SM_Environment, SM_All); type StepModes is (Step_Normal, Step_LowRAM); type EntCheckerAcc is access function(E : EntityClassAcc) return Boolean; type World is tagged record -- Access to accesses to the entities Entities : EntsListAcc; -- Access to accesses to the environments entities Environments : EntsListAcc; -- Access to accesses to the links Links : LinksListAcc; -- Access to collisions (note this is different from the 3 above) Cols : ColsListAcc; -- Entities.len + Environments.len + Links.len < MaxEntities MaxEntities : Natural; -- Timestep dt : Float; -- Inverse timestep Invdt : Float; -- Function called when World checks the validity of its entities InvalidChecker : EntCheckerAcc; -- Max speed of entities, 0.0 to disable on an axis MaxSpeed : Vec2D := (0.0, 0.0); -- Default static entity, useful for faking collisions -- Its restitution is LinkTypesFactors(LTRope) StaticEnt : EntityClassAcc := null; end record; pragma Pack (World); -- init world procedure Init(This : in out World; dt : in Float; MaxEnts : Natural := 32); procedure Step(This : in out World; Mode : StepModes := Step_Normal); -- clear the world (deep free) procedure Free(This : in out World); -- Add entity to the world procedure AddEntity(This : in out World; Ent : not null EntityClassAcc); -- Add env to the world procedure AddEnvironment(This : in out World; Ent : not null EntityClassAcc); -- Add a link between two entities (rope, spring...) procedure LinkEntities(This : in out World; A, B : EntityClassAcc; LinkType : LinkTypes; Factor : Float := 0.0); -- Remove all links tied to the passed entity procedure UnlinkEntity(This : in out World; E : EntityClassAcc); -- Increases the number of max entities by Count procedure IncreaseMaxEntities(This : in out World; Count : Positive); -- Gives the world a function to check if entities are valid or not procedure SetInvalidChecker(This : in out World; Invalider : EntCheckerAcc); -- Remove entity from the world -- Entity is detroyed if Destroy is true procedure RemoveEntity(This : in out World; Ent : EntityClassAcc; Destroy : Boolean); -- Remove env from the world -- Entity is detroyed if Destroy is true procedure RemoveEnvironment(This : in out World; Ent : not null EntityClassAcc; Destroy : Boolean); -- Returns the entity in which Pos is -- If SearchMode = SM_All, searches first entities, then envs (ents are "on top") function GetClosest(This : in out World; Pos : Vec2D; SearchMode : SearchModes := SM_All) return EntityClassAcc; -- Get the list of entities function GetEntities(This : in World) return EntsListAcc; -- Get the list of envs function GetEnvironments(This : in World) return EntsListAcc; -- Get the list of links function GetLinks(This : in World) return LinksListAcc; -- Lets you set a maximum speed >= 0 -- If max speed = 0 -> no max speed on that axis procedure SetMaxSpeed(This : in out World; Speed : Vec2D); -- Remove invalid entities according to InvalidChecker, if not null procedure CheckEntities(This : in out World); end Worlds;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $: with Asis.Iterator; with Asis.Elements; with Asis.Declarations; with Asis.Gela.Lists; with Asis.Gela.Utils; with Asis.Gela.Unit_Utils; with Asis.Gela.Elements.Decl; with Asis.Gela.Elements.Defs; with Asis.Gela.Element_Utils; with XASIS.Utils; package body Asis.Gela.Implicit.Limited_View is type State_Information is record Unit : Asis.Compilation_Unit; Pkg : Asis.Element; end record; procedure Pre_Operation (Element : in Asis.Element; Control : in out Traverse_Control; State : in out State_Information); procedure Post_Operation (Element : in Asis.Element; Control : in out Traverse_Control; State : in out State_Information); type Cloner is new Asis.Cloner with null record; function Clone (Object : Cloner; Item : Element; Parent : Element) return Element; ----------- -- Clone -- ----------- function Clone (Object : Cloner; Item : Element; Parent : Element) return Element is use Asis.Gela.Elements; Result : constant Asis.Element := Clone (Item.all, Parent); Node : Base_Element_Node renames Base_Element_Node (Result.all); begin Set_Is_Part_Of_Implicit (Node, True); return Result; end Clone; -------------------- -- Post_Operation -- -------------------- procedure Post_Operation (Element : in Asis.Element; Control : in out Traverse_Control; State : in out State_Information) is use Asis.Gela.Elements.Decl; Parent : Asis.Element; begin if Asis.Elements.Declaration_Kind (Element) = A_Package_Declaration then Parent := Enclosing_Element (State.Pkg.all); if Assigned (Parent) then State.Pkg := Parent; end if; end if; end Post_Operation; ------------------- -- Pre_Operation -- ------------------- procedure Pre_Operation (Element : in Asis.Element; Control : in out Traverse_Control; State : in out State_Information) is use Asis.Declarations; use Asis.Gela.Elements; use Asis.Gela.Elements.Decl; use Asis.Gela.Lists; -------------------------- -- Implicit_Declaration -- -------------------------- procedure Implicit_Declaration (Node : in out Declaration_Node'Class; Self : Asis.Element) is Copy : Cloner; Name : constant Asis.Element_List := Names (Element); List : Asis.Element; begin Set_Declaration_Origin (Node, An_Implicit_Predefined_Declaration); Set_Enclosing_Compilation_Unit (Node, State.Unit); Set_Start_Position (Node, (1, 1)); Set_End_Position (Node, (0, 0)); Set_Is_Part_Of_Implicit (Node, True); Set_Enclosing_Element (Node, State.Pkg); List := Primary_Defining_Name_Lists.Deep_Copy (Name, Copy, Self); Set_Names (Node, List); if Assigned (State.Pkg) then Element_Utils.Add_To_Visible (State.Pkg, Self); end if; end Implicit_Declaration; --------------- -- Is_Tagged -- --------------- function Is_Tagged (Element : Asis.Declaration) return Boolean is View : constant Asis.Definition := Asis.Declarations.Type_Declaration_View (Element); begin case Asis.Elements.Definition_Kind (View) is when A_Type_Definition | An_Incomplete_Type_Definition | A_Private_Type_Definition | A_Task_Definition | A_Protected_Definition => return False; when A_Tagged_Incomplete_Type_Definition | A_Tagged_Private_Type_Definition | A_Private_Extension_Definition => return True; when others => raise Internal_Error; end case; end Is_Tagged; ---------------------- -- Is_Redeclaration -- ---------------------- function Is_Redeclaration (Decl : Asis.Declaration) return Boolean is use XASIS.Utils; use Asis.Elements; Name : constant Program_Text := Declaration_Direct_Name (Decl); Parent : constant Asis.Declaration := Enclosing_Element (Decl); List : constant Asis.Declarative_Item_List := Visible_Part_Declarative_Items (Parent); begin for J in List'Range loop if Is_Equal (Decl, List (J)) then return False; elsif Element_Kind (List (J)) = A_Declaration and then Has_Defining_Name (List (J), Name) then return True; end if; end loop; return False; end Is_Redeclaration; begin if Asis.Elements.Element_Kind (Element) = A_Declaration and Assigned (State.Pkg) then if not Utils.In_Visible_Part (Element) then Control := Abandon_Siblings; return; end if; end if; case Asis.Elements.Declaration_Kind (Element) is when An_Ordinary_Type_Declaration | An_Incomplete_Type_Declaration | A_Task_Type_Declaration | A_Protected_Type_Declaration | A_Private_Type_Declaration | A_Private_Extension_Declaration => if Is_Redeclaration (Element) then Control := Abandon_Children; return; end if; declare Node : Incomplete_Type_Declaration_Ptr := new Incomplete_Type_Declaration_Node; begin Implicit_Declaration (Node.all, Asis.Element (Node)); if Is_Tagged (Element) then declare use Asis.Gela.Elements.Defs; Child : Tagged_Incomplete_Type_Definition_Ptr := new Tagged_Incomplete_Type_Definition_Node; begin Set_Enclosing_Compilation_Unit (Child.all, State.Unit); Set_Start_Position (Child.all, (1, 1)); Set_End_Position (Child.all, (0, 0)); Set_Is_Part_Of_Implicit (Child.all, True); Set_Enclosing_Element (Child.all, Asis.Element (Node)); Set_Type_Declaration_View (Node.all, Asis.Element (Child)); end; else declare use Asis.Gela.Elements.Defs; Child : Tagged_Incomplete_Type_Definition_Ptr := new Tagged_Incomplete_Type_Definition_Node; begin Set_Enclosing_Compilation_Unit (Child.all, State.Unit); Set_Start_Position (Child.all, (1, 1)); Set_End_Position (Child.all, (0, 0)); Set_Is_Part_Of_Implicit (Child.all, True); Set_Enclosing_Element (Child.all, Asis.Element (Node)); Set_Type_Declaration_View (Node.all, Asis.Element (Child)); end; end if; Control := Abandon_Children; end; when A_Package_Declaration => declare List : Primary_Declaration_Lists.List := new Primary_Declaration_Lists.List_Node; Node : Package_Declaration_Ptr := new Package_Declaration_Node; begin Set_Is_Private_Present (Node.all, Is_Private_Present (Element)); Set_Visible_Part_Declarative_Items (Node.all, Asis.Element (List)); Implicit_Declaration (Node.all, Asis.Element (Node)); State.Pkg := Asis.Element (Node); Control := Continue; end; when others => Control := Abandon_Children; end case; end Pre_Operation; procedure Walk is new Asis.Iterator.Traverse_Element (State_Information); -------------- -- Populate -- -------------- procedure Populate (View_Unit : Asis.Compilation_Unit; Declaration : Asis.Declaration) is Control : Traverse_Control := Continue; State : State_Information; begin State.Unit := View_Unit; Walk (Declaration, Control, State); Unit_Utils.Set_Unit_Declaration (View_Unit, State.Pkg); end Populate; end Asis.Gela.Implicit.Limited_View; ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
-- part of AdaYaml, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" with Ada.Containers; with Text.Builder; with Yaml.Tags; package body Yaml.Parser is use type Lexer.Token_Kind; use type Text.Reference; function New_Parser return Reference is Ptr : constant not null Instance_Access := new Instance; begin return Reference'(Ada.Finalization.Controlled with Data => Ptr); end New_Parser; function Value (Object : Reference) return Accessor is ((Data => Object.Data)); procedure Adjust (Object : in out Reference) is begin Increase_Refcount (Object.Data); end Adjust; procedure Finalize (Object : in out Reference) is begin Decrease_Refcount (Object.Data); end Finalize; procedure Init (P : in out Instance) with Inline is begin P.Levels := Level_Stacks.New_Stack (32); P.Levels.Push ((State => At_Stream_Start'Access, Indentation => -2)); P.Pool.Create (Text.Pool.Default_Size); Tag_Handle_Sets.Init (P.Tag_Handles, P.Pool, 16); P.Header_Props := Default_Properties; P.Inline_Props := Default_Properties; end Init; procedure Set_Input (P : in out Instance; Input : Source.Pointer) is begin Init (P); Lexer.Init (P.L, Input, P.Pool); end Set_Input; procedure Set_Input (P : in out Instance; Input : String) is begin Init (P); Lexer.Init (P.L, Input, P.Pool); end Set_Input; procedure Set_Warning_Handler (P : in out Instance; Handler : access Warning_Handler'Class) is begin P.Handler := Handler; end Set_Warning_Handler; function Next (P : in out Instance) return Event is begin return E : Event do while not P.Levels.Top.State (P, E) loop null; end loop; end return; end Next; function Pool (P : Instance) return Text.Pool.Reference is (P.Pool); procedure Finalize (P : in out Instance) is null; function Current_Lexer_Token_Start (P : Instance) return Mark is (Lexer.Recent_Start_Mark (P.L)); function Current_Input_Character (P : Instance) return Mark is (Lexer.Cur_Mark (P.L)); function Recent_Lexer_Token_Start (P : Instance) return Mark is (P.Current.Start_Pos); function Recent_Lexer_Token_End (P : Instance) return Mark is (P.Current.End_Pos); ----------------------------------------------------------------------------- -- internal utility subroutines ----------------------------------------------------------------------------- procedure Reset_Tag_Handles (P : in out Class) is begin Tag_Handle_Sets.Clear (P.Tag_Handles); pragma Warnings (Off); if P.Tag_Handles.Set ("!", P.Pool.From_String ("!")) and P.Tag_Handles.Set ("!!", P.Pool.From_String ("tag:yaml.org,2002:")) then null; end if; pragma Warnings (On); end Reset_Tag_Handles; function Parse_Tag (P : in out Class) return Text.Reference is use type Ada.Containers.Hash_Type; Tag_Handle : constant String := Lexer.Full_Lexeme (P.L); Holder : constant access constant Tag_Handle_Sets.Holder := P.Tag_Handles.Get (Tag_Handle, False); begin if Holder.Hash = 0 then raise Parser_Error with "Unknown tag handle: " & Tag_Handle; end if; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind /= Lexer.Suffix then raise Parser_Error with "Unexpected token (expected tag suffix): " & P.Current.Kind'Img; end if; return P.Pool.From_String (Holder.Value & Lexer.Current_Content (P.L)); end Parse_Tag; function To_Style (T : Lexer.Scalar_Token_Kind) return Scalar_Style_Type is (case T is when Lexer.Plain_Scalar => Plain, when Lexer.Single_Quoted_Scalar => Single_Quoted, when Lexer.Double_Quoted_Scalar => Double_Quoted, when Lexer.Literal_Scalar => Literal, when Lexer.Folded_Scalar => Folded) with Inline; ----------------------------------------------------------------------------- -- state implementations ----------------------------------------------------------------------------- function At_Stream_Start (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.all := (State => At_Stream_End'Access, Indentation => -2); P.Levels.Push ((State => Before_Doc'Access, Indentation => -1)); E := Event'(Kind => Stream_Start, Start_Position => (Line => 1, Column => 1, Index => 1), End_Position => (Line => 1, Column => 1, Index => 1)); P.Current := Lexer.Next_Token (P.L); Reset_Tag_Handles (P); return True; end At_Stream_Start; function At_Stream_End (P : in out Class; E : out Event) return Boolean is T : constant Lexer.Token := Lexer.Next_Token (P.L); begin E := Event'(Kind => Stream_End, Start_Position => T.Start_Pos, End_Position => T.End_Pos); return True; end At_Stream_End; function Before_Doc (P : in out Class; E : out Event) return Boolean is Version : Text.Reference := Text.Empty; Seen_Directives : Boolean := False; begin loop case P.Current.Kind is when Lexer.Document_End => if Seen_Directives then raise Parser_Error with "Directives must be followed by '---'"; end if; P.Current := Lexer.Next_Token (P.L); when Lexer.Directives_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Document_Start, Implicit_Start => False, Version => Version); P.Current := Lexer.Next_Token (P.L); P.Levels.Top.State := Before_Doc_End'Access; P.Levels.Push ((State => After_Directives_End'Access, Indentation => -1)); return True; when Lexer.Stream_End => P.Levels.Pop; return False; when Lexer.Indentation => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Document_Start, Implicit_Start => True, Version => Version); P.Levels.Top.State := Before_Doc_End'Access; P.Levels.Push ((State => Before_Implicit_Root'Access, Indentation => -1)); return True; when Lexer.Yaml_Directive => Seen_Directives := True; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind /= Lexer.Directive_Param then raise Parser_Error with "Invalid token (expected YAML version string): " & P.Current.Kind'Img; elsif Version /= Text.Empty then raise Parser_Error with "Duplicate YAML directive"; end if; Version := P.Pool.From_String (Lexer.Full_Lexeme (P.L)); if Version /= "1.3" and then P.Handler /= null then P.Handler.Wrong_Yaml_Version (Version.Value); end if; P.Current := Lexer.Next_Token (P.L); when Lexer.Tag_Directive => Seen_Directives := True; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind /= Lexer.Tag_Handle then raise Parser_Error with "Invalid token (expected tag handle): " & P.Current.Kind'Img; end if; declare Tag_Handle : constant String := Lexer.Full_Lexeme (P.L); Holder : access Tag_Handle_Sets.Holder; begin P.Current := Lexer.Next_Token (P.L); if P.Current.Kind /= Lexer.Suffix then raise Parser_Error with "Invalid token (expected tag URI): " & P.Current.Kind'Img; end if; if Tag_Handle = "!" or Tag_Handle = "!!" then Holder := Tag_Handle_Sets.Get (P.Tag_Handles, Tag_Handle, False); Holder.Value := Lexer.Current_Content (P.L); else if not Tag_Handle_Sets.Set (P.Tag_Handles, Tag_Handle, Lexer.Current_Content (P.L)) then raise Parser_Error with "Redefinition of tag handle " & Tag_Handle; end if; end if; end; P.Current := Lexer.Next_Token (P.L); when Lexer.Unknown_Directive => Seen_Directives := True; if P.Handler /= null then declare Name : constant String := Lexer.Short_Lexeme (P.L); Params : Text.Builder.Reference := Text.Builder.Create (P.Pool); First : Boolean := True; begin loop P.Current := Lexer.Next_Token (P.L); exit when P.Current.Kind /= Lexer.Directive_Param; if First then First := False; else Params.Append (' '); end if; Params.Append (Lexer.Full_Lexeme (P.L)); end loop; P.Handler.Unknown_Directive (Name, Params.Lock.Value.Data.all); end; else loop P.Current := Lexer.Next_Token (P.L); exit when P.Current.Kind /= Lexer.Directive_Param; end loop; end if; when others => raise Parser_Error with "Unexpected token (expected directive or document start): " & P.Current.Kind'Img; end case; end loop; end Before_Doc; function After_Directives_End (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Node_Property_Kind => P.Inline_Start := P.Current.Start_Pos; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Indentation => P.Header_Start := P.Inline_Start; P.Levels.Top.State := At_Block_Indentation'Access; P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); return False; when Lexer.Document_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Pop; return True; when Lexer.Folded_Scalar | Lexer.Literal_Scalar => E := Event'( Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => (if P.Current.Kind = Lexer.Folded_Scalar then Folded else Literal), Content => Lexer.Current_Content (P.L)); P.Levels.Pop; P.Current := Lexer.Next_Token (P.L); return True; when others => raise Parser_Error with "Illegal content at '---' line: " & P.Current.Kind'Img; end case; end After_Directives_End; function Before_Implicit_Root (P : in out Class; E : out Event) return Boolean is pragma Unreferenced (E); begin if P.Current.Kind /= Lexer.Indentation then raise Parser_Error with "Unexpected token (expected line start) :" & P.Current.Kind'Img; end if; P.Inline_Start := P.Current.End_Pos; P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); P.Current := Lexer.Next_Token (P.L); case P.Current.Kind is when Lexer.Seq_Item_Ind | Lexer.Map_Key_Ind | Lexer.Map_Value_Ind => P.Levels.Top.State := After_Compact_Parent'Access; return False; when Lexer.Scalar_Token_Kind => P.Levels.Top.State := Require_Implicit_Map_Start'Access; return False; when Lexer.Node_Property_Kind => P.Levels.Top.State := Require_Implicit_Map_Start'Access; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Flow_Map_Start | Lexer.Flow_Seq_Start => P.Levels.Top.State := After_Compact_Parent_Props'Access; return False; when others => raise Parser_Error with "Unexpected token (expected collection start): " & P.Current.Kind'Img; end case; end Before_Implicit_Root; function Require_Implicit_Map_Start (P : in out Class; E : out Event) return Boolean is Header_End : Mark; begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); Header_End := P.Current.Start_Pos; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then P.Cached := E; E := Event'(Start_Position => P.Header_Start, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; else if not Is_Empty (P.Header_Props) then raise Parser_Error with "Alias may not have properties2"; end if; -- alias is allowed on document root without '---' P.Levels.Pop; end if; return True; when Lexer.Flow_Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; Header_End := P.Current.Start_Pos; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then if Lexer.Last_Scalar_Was_Multiline (P.L) then raise Parser_Error with "Implicit mapping key may not be multiline"; end if; P.Cached := E; E := Event'(Start_Position => P.Header_Start, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; elsif P.Current.Kind in Lexer.Indentation | Lexer.Document_End | Lexer.Directives_End | Lexer.Stream_End then raise Parser_Error with "Scalar at root level requires '---'."; end if; return True; when Lexer.Flow_Map_Start | Lexer.Flow_Seq_Start => P.Levels.Top.State := Before_Flow_Item_Props'Access; return False; when Lexer.Indentation => raise Parser_Error with "Stand-alone node properties not allowed on non-header line"; when others => raise Parser_Error with "Unexpected token (expected implicit mapping key): " & P.Current.Kind'Img; end case; end Require_Implicit_Map_Start; function At_Block_Indentation (P : in out Class; E : out Event) return Boolean is Header_End : Mark; begin if P.Block_Indentation = P.Levels.Top.Indentation and then (P.Current.Kind /= Lexer.Seq_Item_Ind or else P.Levels.Element (P.Levels.Length - 2).State = In_Block_Seq'Access) then -- empty element is empty scalar E := Event'(Start_Position => P.Header_Start, End_Position => P.Header_Start, Kind => Scalar, Scalar_Properties => P.Header_Props, Scalar_Style => Plain, Content => Text.Empty); P.Header_Props := Default_Properties; P.Levels.Pop; P.Levels.Pop; return True; end if; P.Inline_Start := P.Current.Start_Pos; P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Node_Property_Kind => if Is_Empty (P.Header_Props) then P.Levels.Top.State := Require_Inline_Block_Item'Access; else P.Levels.Top.State := Require_Implicit_Map_Start'Access; end if; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Seq_Item_Ind => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Sequence_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.all := (In_Block_Seq'Access, Lexer.Recent_Indentation (P.L)); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => Lexer.Recent_Indentation (P.L))); P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Map_Key_Ind => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.all := (Before_Block_Map_Value'Access, Lexer.Recent_Indentation (P.L)); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => Lexer.Recent_Indentation (P.L))); P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Flow_Scalar_Token_Kind => P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Header_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Header_Props := Default_Properties; Header_End := P.Current.Start_Pos; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then if Lexer.Last_Scalar_Was_Multiline (P.L) then raise Parser_Error with "Implicit mapping key may not be multiline"; end if; P.Cached := E; E := Event'(Start_Position => P.Header_Start, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => P.Cached.Scalar_Properties, Collection_Style => Block); P.Cached.Scalar_Properties := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; else P.Levels.Pop; end if; return True; when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); P.Inline_Props := Default_Properties; Header_End := P.Current.Start_Pos; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then P.Cached := E; E := Event'(Start_Position => P.Header_Start, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; elsif not Is_Empty (P.Header_Props) then raise Parser_Error with "Alias may not have properties1"; else P.Levels.Pop; end if; return True; when others => P.Levels.Top.State := At_Block_Indentation_Props'Access; return False; end case; end At_Block_Indentation; function At_Block_Indentation_Props (P : in out Class; E : out Event) return Boolean is Header_End : Mark; begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Map_Value_Ind => P.Cached := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Inline_Props := Default_Properties; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; return True; when Lexer.Flow_Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; Header_End := P.Current.Start_Pos; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then if Lexer.Last_Scalar_Was_Multiline (P.L) then raise Parser_Error with "Implicit mapping key may not be multiline"; end if; P.Cached := E; E := Event'(Start_Position => P.Header_Start, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; else P.Levels.Pop; end if; return True; when Lexer.Flow_Map_Start => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Flow); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Flow_Map_Sep'Access; P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Flow_Seq_Start => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Sequence_Start, Collection_Properties => P.Header_Props, Collection_Style => Flow); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Flow_Seq_Sep'Access; P.Current := Lexer.Next_Token (P.L); return True; when others => raise Parser_Error with "Unexpected token (expected block content): " & P.Current.Kind'Img; end case; end At_Block_Indentation_Props; function Before_Node_Properties (P : in out Class; E : out Event) return Boolean is pragma Unreferenced (E); begin case P.Current.Kind is when Lexer.Tag_Handle => if P.Inline_Props.Tag /= Tags.Question_Mark then raise Parser_Error with "Only one tag allowed per element"; end if; P.Inline_Props.Tag := Parse_Tag (P); when Lexer.Verbatim_Tag => if P.Inline_Props.Tag /= Tags.Question_Mark then raise Parser_Error with "Only one tag allowed per element"; end if; P.Inline_Props.Tag := Lexer.Current_Content (P.L); when Lexer.Anchor => if P.Inline_Props.Anchor /= Text.Empty then raise Parser_Error with "Only one anchor allowed per element"; end if; P.Inline_Props.Anchor := P.Pool.From_String (Lexer.Short_Lexeme (P.L)); when Lexer.Annotation_Handle => declare NS : constant String := Lexer.Full_Lexeme (P.L); begin P.Current := Lexer.Next_Token (P.L); if P.Current.Kind /= Lexer.Suffix then raise Parser_Error with "Unexpected token (expected annotation suffix): " & P.Current.Kind'Img; end if; if NS = "@@" then E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.Start_Pos, Kind => Annotation_Start, Annotation_Properties => P.Inline_Props, Namespace => Standard_Annotation_Namespace, Name => Lexer.Current_Content (P.L)); else E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.Start_Pos, Kind => Annotation_Start, Annotation_Properties => P.Inline_Props, Namespace => P.Pool.From_String (NS), Name => Lexer.Current_Content (P.L)); end if; end; P.Inline_Props := Default_Properties; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Params_Start then P.Current := Lexer.Next_Token (P.L); P.Levels.Push ((State => After_Param_Sep'Access, Indentation => P.Block_Indentation)); else P.Levels.Top.State := After_Annotation'Access; end if; return True; when Lexer.Indentation => P.Header_Props := P.Inline_Props; P.Inline_Props := Default_Properties; P.Levels.Pop; return False; when Lexer.Alias => raise Parser_Error with "Alias may not have node properties"; when others => P.Levels.Pop; return False; end case; P.Current := Lexer.Next_Token (P.L); return False; end Before_Node_Properties; function After_Compact_Parent (P : in out Class; E : out Event) return Boolean is begin P.Inline_Start := P.Current.Start_Pos; case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Top.State := After_Compact_Parent_Props'Access; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); when Lexer.Seq_Item_Ind => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Sequence_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.all := (In_Block_Seq'Access, Lexer.Recent_Indentation (P.L)); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => <>)); P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Map_Key_Ind => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.all := (Before_Block_Map_Value'Access, Lexer.Recent_Indentation (P.L)); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => <>)); P.Current := Lexer.Next_Token (P.L); return True; when others => P.Levels.Top.State := After_Compact_Parent_Props'Access; return False; end case; return False; end After_Compact_Parent; function After_Compact_Parent_Props (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Indentation => P.Header_Start := P.Inline_Start; P.Levels.Top.all := (State => At_Block_Indentation'Access, Indentation => P.Levels.Element (P.Levels.Length - 2).Indentation); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); return False; when Lexer.Stream_End | Lexer.Document_End | Lexer.Directives_End => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.Start_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Inline_Props := Default_Properties; P.Levels.Pop; return True; when Lexer.Map_Value_Ind => P.Cached := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Inline_Props := Default_Properties; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.Start_Pos, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Block); P.Levels.Top.State := After_Implicit_Map_Start'Access; return True; when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); declare Header_End : constant Mark := P.Current.Start_Pos; begin P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then P.Cached := E; E := Event'(Start_Position => Header_End, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Block); P.Levels.Top.State := After_Implicit_Map_Start'Access; else P.Levels.Pop; end if; end; return True; when Lexer.Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; declare Header_End : constant Mark := P.Current.Start_Pos; begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then if Lexer.Last_Scalar_Was_Multiline (P.L) then raise Parser_Error with "Implicit mapping key may not be multiline"; end if; P.Cached := E; E := Event'(Start_Position => Header_End, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Block); P.Levels.Top.State := After_Implicit_Map_Start'Access; else P.Levels.Pop; end if; end; return True; when Lexer.Flow_Map_Start => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Inline_Props, Collection_Style => Flow); P.Inline_Props := Default_Properties; P.Levels.Top.State := After_Flow_Map_Sep'Access; P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Flow_Seq_Start => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Sequence_Start, Collection_Properties => P.Inline_Props, Collection_Style => Flow); P.Inline_Props := Default_Properties; P.Levels.Top.State := After_Flow_Seq_Sep'Access; P.Current := Lexer.Next_Token (P.L); return True; when others => raise Parser_Error with "Unexpected token (expected newline or flow item start): " & P.Current.Kind'Img; end case; end After_Compact_Parent_Props; function After_Block_Parent (P : in out Class; E : out Event) return Boolean is pragma Unreferenced (E); begin P.Inline_Start := P.Current.Start_Pos; case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Top.State := After_Block_Parent_Props'Access; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); when Lexer.Seq_Item_Ind | Lexer.Map_Key_Ind => raise Parser_Error with "Compact notation not allowed after implicit key"; when others => P.Levels.Top.State := After_Block_Parent_Props'Access; end case; return False; end After_Block_Parent; function After_Block_Parent_Props (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Map_Value_Ind => raise Parser_Error with "Compact notation not allowed after implicit key"; when Lexer.Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then raise Parser_Error with "Compact notation not allowed after implicit key"; end if; P.Levels.Pop; return True; when others => P.Levels.Top.State := After_Compact_Parent_Props'Access; return False; end case; end After_Block_Parent_Props; function Require_Inline_Block_Item (P : in out Class; E : out Event) return Boolean is pragma Unreferenced (E); begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Indentation => raise Parser_Error with "Node properties may not stand alone on a line"; when others => P.Levels.Top.State := After_Compact_Parent_Props'Access; return False; end case; end Require_Inline_Block_Item; function Before_Doc_End (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Document_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Document_End, Implicit_End => False); P.Levels.Top.State := Before_Doc'Access; Reset_Tag_Handles (P); P.Current := Lexer.Next_Token (P.L); when Lexer.Stream_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Document_End, Implicit_End => True); P.Levels.Pop; when Lexer.Directives_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Document_End, Implicit_End => True); Reset_Tag_Handles (P); P.Levels.Top.State := Before_Doc'Access; when others => raise Parser_Error with "Unexpected token (expected document end): " & P.Current.Kind'Img; end case; return True; end Before_Doc_End; function In_Block_Seq (P : in out Class; E : out Event) return Boolean is begin if P.Block_Indentation > P.Levels.Top.Indentation then raise Parser_Error with "Invalid indentation (bseq); got" & P.Block_Indentation'Img & ", expected" & P.Levels.Top.Indentation'Img; end if; case P.Current.Kind is when Lexer.Seq_Item_Ind => P.Current := Lexer.Next_Token (P.L); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => P.Block_Indentation)); return False; when others => if P.Levels.Element (P.Levels.Length - 2).Indentation = P.Levels.Top.Indentation then E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Sequence_End); P.Levels.Pop; P.Levels.Pop; return True; else raise Parser_Error with "Illegal token (expected block sequence indicator): " & P.Current.Kind'Img; end if; end case; end In_Block_Seq; function After_Implicit_Map_Start (P : in out Class; E : out Event) return Boolean is begin E := P.Cached; P.Levels.Top.State := After_Implicit_Key'Access; return True; end After_Implicit_Map_Start; function Before_Block_Map_Key (P : in out Class; E : out Event) return Boolean is begin if P.Block_Indentation > P.Levels.Top.Indentation then raise Parser_Error with "Invalid indentation (bmk); got" & P.Block_Indentation'Img & ", expected" & P.Levels.Top.Indentation'Img & ", token = " & P.Current.Kind'Img; end if; case P.Current.Kind is when Lexer.Map_Key_Ind => P.Levels.Top.State := Before_Block_Map_Value'Access; P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => P.Levels.Top.Indentation)); P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Node_Property_Kind => P.Levels.Top.State := At_Block_Map_Key_Props'Access; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Flow_Scalar_Token_Kind => P.Levels.Top.State := At_Block_Map_Key_Props'Access; return False; when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); P.Current := Lexer.Next_Token (P.L); P.Levels.Top.State := After_Implicit_Key'Access; return True; when Lexer.Map_Value_Ind => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Top.State := Before_Block_Map_Value'Access; return True; when others => raise Parser_Error with "Unexpected token (expected mapping key): " & P.Current.Kind'Img; end case; end Before_Block_Map_Key; function At_Block_Map_Key_Props (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); when Lexer.Flow_Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; if Lexer.Last_Scalar_Was_Multiline (P.L) then raise Parser_Error with "Implicit mapping key may not be multiline"; end if; when Lexer.Map_Value_Ind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.Start_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Inline_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Key'Access; return True; when others => raise Parser_Error with "Unexpected token (expected implicit mapping key): " & P.Current.Kind'Img; end case; P.Current := Lexer.Next_Token (P.L); P.Levels.Top.State := After_Implicit_Key'Access; return True; end At_Block_Map_Key_Props; function After_Implicit_Key (P : in out Class; E : out Event) return Boolean is pragma Unreferenced (E); begin if P.Current.Kind /= Lexer.Map_Value_Ind then raise Parser_Error with "Unexpected token (expected ':'): " & P.Current.Kind'Img; end if; P.Current := Lexer.Next_Token (P.L); P.Levels.Top.State := Before_Block_Map_Key'Access; P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Block_Parent'Access, Indentation => P.Levels.Top.Indentation)); return False; end After_Implicit_Key; function Before_Block_Map_Value (P : in out Class; E : out Event) return Boolean is begin if P.Block_Indentation > P.Levels.Top.Indentation then raise Parser_Error with "Invalid indentation (bmv)"; end if; case P.Current.Kind is when Lexer.Map_Value_Ind => P.Levels.Top.State := Before_Block_Map_Key'Access; P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => P.Levels.Top.Indentation)); P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Map_Key_Ind | Lexer.Flow_Scalar_Token_Kind | Lexer.Node_Property_Kind => -- the value is allowed to be missing after an explicit key E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Top.State := Before_Block_Map_Key'Access; return True; when others => raise Parser_Error with "Unexpected token (expected mapping value): " & P.Current.Kind'Img; end case; end Before_Block_Map_Value; function Before_Block_Indentation (P : in out Class; E : out Event) return Boolean is procedure End_Block_Node is begin if P.Levels.Top.State = Before_Block_Map_Key'Access then E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_End); elsif P.Levels.Top.State = Before_Block_Map_Value'Access then E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Top.State := Before_Block_Map_Key'Access; P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); return; elsif P.Levels.Top.State = In_Block_Seq'Access then E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Sequence_End); elsif P.Levels.Top.State = At_Block_Indentation'Access then E := Event'(Start_Position => P.Header_Start, End_Position => P.Header_Start, Kind => Scalar, Scalar_Properties => P.Header_Props, Scalar_Style => Plain, Content => Text.Empty); P.Header_Props := Default_Properties; elsif P.Levels.Top.State = Before_Block_Indentation'Access then raise Parser_Error with "Unexpected double Before_Block_Indentation"; else raise Parser_Error with "Internal error (please report this bug)"; end if; P.Levels.Pop; end End_Block_Node; begin P.Levels.Pop; case P.Current.Kind is when Lexer.Indentation => P.Block_Indentation := Lexer.Current_Indentation (P.L); if P.Block_Indentation < P.Levels.Top.Indentation then End_Block_Node; return True; else P.Current := Lexer.Next_Token (P.L); return False; end if; when Lexer.Stream_End | Lexer.Document_End | Lexer.Directives_End => P.Block_Indentation := 0; if P.Levels.Top.State /= Before_Doc_End'Access then End_Block_Node; return True; else return False; end if; when others => raise Parser_Error with "Unexpected content after node in block context (expected newline): " & P.Current.Kind'Img; end case; end Before_Block_Indentation; function Before_Flow_Item (P : in out Class; E : out Event) return Boolean is begin P.Inline_Start := P.Current.Start_Pos; case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Top.State := Before_Flow_Item_Props'Access; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; when others => P.Levels.Top.State := Before_Flow_Item_Props'Access; end case; return False; end Before_Flow_Item; function Before_Flow_Item_Props (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; when Lexer.Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; when Lexer.Flow_Map_Start => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Inline_Props, Collection_Style => Flow); P.Levels.Top.State := After_Flow_Map_Sep'Access; P.Current := Lexer.Next_Token (P.L); when Lexer.Flow_Seq_Start => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Sequence_Start, Collection_Properties => P.Inline_Props, Collection_Style => Flow); P.Levels.Top.State := After_Flow_Seq_Sep'Access; P.Current := Lexer.Next_Token (P.L); when Lexer.Flow_Map_End | Lexer.Flow_Seq_End | Lexer.Flow_Separator | Lexer.Map_Value_Ind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Pop; when others => raise Parser_Error with "Unexpected token (expected flow node): " & P.Current.Kind'Img; end case; P.Inline_Props := Default_Properties; return True; end Before_Flow_Item_Props; function After_Flow_Map_Key (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Map_Value_Ind => P.Levels.Top.State := After_Flow_Map_Value'Access; P.Levels.Push ((State => Before_Flow_Item'Access, others => <>)); P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Flow_Separator | Lexer.Flow_Map_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Top.State := After_Flow_Map_Value'Access; return True; when others => raise Parser_Error with "Unexpected token (expected ':'): " & P.Current.Kind'Img; end case; end After_Flow_Map_Key; function After_Flow_Map_Value (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Flow_Separator => P.Levels.Top.State := After_Flow_Map_Sep'Access; P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Flow_Map_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_End); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; when Lexer.Flow_Scalar_Token_Kind | Lexer.Map_Key_Ind | Lexer.Anchor | Lexer.Alias | Lexer.Annotation_Handle | Lexer.Flow_Map_Start | Lexer.Flow_Seq_Start => raise Parser_Error with "Missing ','"; when others => raise Parser_Error with "Unexpected token (expected ',' or '}'): " & P.Current.Kind'Img; end case; end After_Flow_Map_Value; function After_Flow_Seq_Item (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Flow_Separator => P.Levels.Top.State := After_Flow_Seq_Sep'Access; P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Flow_Seq_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Sequence_End); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; when Lexer.Flow_Scalar_Token_Kind | Lexer.Map_Key_Ind | Lexer.Anchor | Lexer.Alias | Lexer.Annotation_Handle | Lexer.Flow_Map_Start | Lexer.Flow_Seq_Start => raise Parser_Error with "Missing ','"; when others => raise Parser_Error with "Unexpected token (expected ',' or ']'): " & P.Current.Kind'Img; end case; end After_Flow_Seq_Item; function After_Flow_Map_Sep (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Map_Key_Ind => P.Current := Lexer.Next_Token (P.L); when Lexer.Flow_Map_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_End); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; when others => null; end case; P.Levels.Top.State := After_Flow_Map_Key'Access; P.Levels.Push ((State => Before_Flow_Item'Access, Indentation => <>)); return False; end After_Flow_Map_Sep; function Possible_Next_Sequence_Item (P : in out Class; E : out Event; End_Token : Lexer.Token_Kind; After_Props, After_Item : State_Type) return Boolean is begin P.Inline_Start := P.Current.Start_Pos; case P.Current.Kind is when Lexer.Flow_Separator => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.Start_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Node_Property_Kind => P.Levels.Top.State := After_Props; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Flow_Scalar_Token_Kind => P.Levels.Top.State := After_Props; return False; when Lexer.Map_Key_Ind => P.Levels.Top.State := After_Item; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Flow); P.Current := Lexer.Next_Token (P.L); P.Levels.Push ((State => Before_Pair_Value'Access, others => <>)); P.Levels.Push ((State => Before_Flow_Item'Access, others => <>)); return True; when Lexer.Map_Value_Ind => P.Levels.Top.State := After_Item; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Flow); P.Levels.Push ((State => At_Empty_Pair_Key'Access, others => <>)); return True; when others => if P.Current.Kind = End_Token then E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Sequence_End); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; else P.Levels.Top.State := After_Item; P.Levels.Push ((State => Before_Flow_Item'Access, others => <>)); return False; end if; end case; end Possible_Next_Sequence_Item; function After_Flow_Seq_Sep (P : in out Class; E : out Event) return Boolean is begin return Possible_Next_Sequence_Item (P, E, Lexer.Flow_Seq_End, After_Flow_Seq_Sep_Props'Access, After_Flow_Seq_Item'Access); end After_Flow_Seq_Sep; function Forced_Next_Sequence_Item (P : in out Class; E : out Event) return Boolean is begin if P.Current.Kind in Lexer.Flow_Scalar_Token_Kind then E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then P.Cached := E; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.Start_Pos, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Flow); P.Levels.Push ((State => After_Implicit_Pair_Start'Access, Indentation => <>)); end if; return True; else P.Levels.Push ((State => Before_Flow_Item_Props'Access, others => <>)); return False; end if; end Forced_Next_Sequence_Item; function After_Flow_Seq_Sep_Props (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.State := After_Flow_Seq_Item'Access; return Forced_Next_Sequence_Item (P, E); end After_Flow_Seq_Sep_Props; function At_Empty_Pair_Key (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.State := Before_Pair_Value'Access; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.Start_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); return True; end At_Empty_Pair_Key; function Before_Pair_Value (P : in out Class; E : out Event) return Boolean is begin if P.Current.Kind = Lexer.Map_Value_Ind then P.Levels.Top.State := After_Pair_Value'Access; P.Levels.Push ((State => Before_Flow_Item'Access, others => <>)); P.Current := Lexer.Next_Token (P.L); return False; else -- pair ends here without value. E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Pop; return True; end if; end Before_Pair_Value; function After_Implicit_Pair_Start (P : in out Class; E : out Event) return Boolean is begin E := P.Cached; P.Current := Lexer.Next_Token (P.L); P.Levels.Top.State := After_Pair_Value'Access; P.Levels.Push ((State => Before_Flow_Item'Access, others => <>)); return True; end After_Implicit_Pair_Start; function After_Pair_Value (P : in out Class; E : out Event) return Boolean is begin E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_End); P.Levels.Pop; return True; end After_Pair_Value; function After_Param_Sep (P : in out Class; E : out Event) return Boolean is begin return Possible_Next_Sequence_Item (P, E, Lexer.Params_End, After_Param_Sep_Props'Access, After_Param'Access); end After_Param_Sep; function After_Param_Sep_Props (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.State := After_Param'Access; return Forced_Next_Sequence_Item (P, E); end After_Param_Sep_Props; function After_Param (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Flow_Separator => P.Levels.Top.State := After_Param_Sep'Access; P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Params_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Annotation_End); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; when Lexer.Flow_Scalar_Token_Kind | Lexer.Map_Key_Ind | Lexer.Anchor | Lexer.Alias | Lexer.Annotation_Handle | Lexer.Flow_Map_Start | Lexer.Flow_Seq_Start => raise Parser_Error with "Missing ','"; when others => raise Parser_Error with "Unexpected token (expected ',' or ')'): " & P.Current.Kind'Img; end case; end After_Param; function After_Annotation (P : in out Class; E : out Event) return Boolean is begin E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.Start_Pos, Kind => Annotation_End); P.Levels.Pop; return True; end After_Annotation; end Yaml.Parser;
-- Copyright (c) 2010 - 2018, Nordic Semiconductor ASA -- -- All rights reserved. -- -- 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, except as embedded into a Nordic -- Semiconductor ASA integrated circuit in a product or a software update for -- such product, 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 Nordic Semiconductor ASA nor the names of its -- contributors may be used to endorse or promote products derived from this -- software without specific prior written permission. -- -- 4. This software, with or without modification, must only be used with a -- Nordic Semiconductor ASA integrated circuit. -- -- 5. Any software provided in binary form under this license must not be reverse -- engineered, decompiled, modified and/or disassembled. -- -- THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS -- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -- OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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 spec has been automatically generated from nrf52.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package NRF_SVD.GPIOTE is pragma Preelaborate; --------------- -- Registers -- --------------- -- Description collection[0]: Task for writing to pin specified in CONFIG[0].PSEL. Action on pin is configured in CONFIG[0].POLARITY. -- Description collection[0]: Task for writing to pin specified in -- CONFIG[0].PSEL. Action on pin is configured in CONFIG[0].POLARITY. type TASKS_OUT_Registers is array (0 .. 7) of HAL.UInt32; -- Description collection[0]: Task for writing to pin specified in CONFIG[0].PSEL. Action on pin is to set it high. -- Description collection[0]: Task for writing to pin specified in -- CONFIG[0].PSEL. Action on pin is to set it high. type TASKS_SET_Registers is array (0 .. 7) of HAL.UInt32; -- Description collection[0]: Task for writing to pin specified in CONFIG[0].PSEL. Action on pin is to set it low. -- Description collection[0]: Task for writing to pin specified in -- CONFIG[0].PSEL. Action on pin is to set it low. type TASKS_CLR_Registers is array (0 .. 7) of HAL.UInt32; -- Description collection[0]: Event generated from pin specified in CONFIG[0].PSEL -- Description collection[0]: Event generated from pin specified in -- CONFIG[0].PSEL type EVENTS_IN_Registers is array (0 .. 7) of HAL.UInt32; -- Write '1' to Enable interrupt for IN[0] event type INTENSET_IN0_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENSET_IN0_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Enable interrupt for IN[0] event type INTENSET_IN0_Field_1 is (-- Reset value for the field Intenset_In0_Field_Reset, -- Enable Set) with Size => 1; for INTENSET_IN0_Field_1 use (Intenset_In0_Field_Reset => 0, Set => 1); -- INTENSET_IN array type INTENSET_IN_Field_Array is array (0 .. 7) of INTENSET_IN0_Field_1 with Component_Size => 1, Size => 8; -- Type definition for INTENSET_IN type INTENSET_IN_Field (As_Array : Boolean := False) is record case As_Array is when False => -- IN as a value Val : HAL.UInt8; when True => -- IN as an array Arr : INTENSET_IN_Field_Array; end case; end record with Unchecked_Union, Size => 8; for INTENSET_IN_Field use record Val at 0 range 0 .. 7; Arr at 0 range 0 .. 7; end record; -- Write '1' to Enable interrupt for PORT event type INTENSET_PORT_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENSET_PORT_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Enable interrupt for PORT event type INTENSET_PORT_Field_1 is (-- Reset value for the field Intenset_Port_Field_Reset, -- Enable Set) with Size => 1; for INTENSET_PORT_Field_1 use (Intenset_Port_Field_Reset => 0, Set => 1); -- Enable interrupt type INTENSET_Register is record -- Write '1' to Enable interrupt for IN[0] event IN_k : INTENSET_IN_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_8_30 : HAL.UInt23 := 16#0#; -- Write '1' to Enable interrupt for PORT event PORT : INTENSET_PORT_Field_1 := Intenset_Port_Field_Reset; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTENSET_Register use record IN_k at 0 range 0 .. 7; Reserved_8_30 at 0 range 8 .. 30; PORT at 0 range 31 .. 31; end record; -- Write '1' to Disable interrupt for IN[0] event type INTENCLR_IN0_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENCLR_IN0_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Disable interrupt for IN[0] event type INTENCLR_IN0_Field_1 is (-- Reset value for the field Intenclr_In0_Field_Reset, -- Disable Clear) with Size => 1; for INTENCLR_IN0_Field_1 use (Intenclr_In0_Field_Reset => 0, Clear => 1); -- INTENCLR_IN array type INTENCLR_IN_Field_Array is array (0 .. 7) of INTENCLR_IN0_Field_1 with Component_Size => 1, Size => 8; -- Type definition for INTENCLR_IN type INTENCLR_IN_Field (As_Array : Boolean := False) is record case As_Array is when False => -- IN as a value Val : HAL.UInt8; when True => -- IN as an array Arr : INTENCLR_IN_Field_Array; end case; end record with Unchecked_Union, Size => 8; for INTENCLR_IN_Field use record Val at 0 range 0 .. 7; Arr at 0 range 0 .. 7; end record; -- Write '1' to Disable interrupt for PORT event type INTENCLR_PORT_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENCLR_PORT_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Disable interrupt for PORT event type INTENCLR_PORT_Field_1 is (-- Reset value for the field Intenclr_Port_Field_Reset, -- Disable Clear) with Size => 1; for INTENCLR_PORT_Field_1 use (Intenclr_Port_Field_Reset => 0, Clear => 1); -- Disable interrupt type INTENCLR_Register is record -- Write '1' to Disable interrupt for IN[0] event IN_k : INTENCLR_IN_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_8_30 : HAL.UInt23 := 16#0#; -- Write '1' to Disable interrupt for PORT event PORT : INTENCLR_PORT_Field_1 := Intenclr_Port_Field_Reset; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTENCLR_Register use record IN_k at 0 range 0 .. 7; Reserved_8_30 at 0 range 8 .. 30; PORT at 0 range 31 .. 31; end record; -- Mode type CONFIG_MODE_Field is (-- Disabled. Pin specified by PSEL will not be acquired by the GPIOTE module. Disabled, -- Event mode Event, -- Task mode Task_k) with Size => 2; for CONFIG_MODE_Field use (Disabled => 0, Event => 1, Task_k => 3); subtype CONFIG_PSEL_Field is HAL.UInt5; -- When In task mode: Operation to be performed on output when OUT[n] task -- is triggered. When In event mode: Operation on input that shall trigger -- IN[n] event. type CONFIG_POLARITY_Field is (-- Task mode: No effect on pin from OUT[n] task. Event mode: no IN[n] event -- generated on pin activity. None, -- Task mode: Set pin from OUT[n] task. Event mode: Generate IN[n] event when -- rising edge on pin. Lotohi, -- Task mode: Clear pin from OUT[n] task. Event mode: Generate IN[n] event -- when falling edge on pin. Hitolo, -- Task mode: Toggle pin from OUT[n]. Event mode: Generate IN[n] when any -- change on pin. Toggle) with Size => 2; for CONFIG_POLARITY_Field use (None => 0, Lotohi => 1, Hitolo => 2, Toggle => 3); -- When in task mode: Initial value of the output when the GPIOTE channel -- is configured. When in event mode: No effect. type CONFIG_OUTINIT_Field is (-- Task mode: Initial value of pin before task triggering is low Low, -- Task mode: Initial value of pin before task triggering is high High) with Size => 1; for CONFIG_OUTINIT_Field use (Low => 0, High => 1); -- Description collection[0]: Configuration for OUT[n], SET[n] and CLR[n] -- tasks and IN[n] event type CONFIG_Register is record -- Mode MODE : CONFIG_MODE_Field := NRF_SVD.GPIOTE.Disabled; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; -- GPIO number associated with SET[n], CLR[n] and OUT[n] tasks and IN[n] -- event PSEL : CONFIG_PSEL_Field := 16#0#; -- unspecified Reserved_13_15 : HAL.UInt3 := 16#0#; -- When In task mode: Operation to be performed on output when OUT[n] -- task is triggered. When In event mode: Operation on input that shall -- trigger IN[n] event. POLARITY : CONFIG_POLARITY_Field := NRF_SVD.GPIOTE.None; -- unspecified Reserved_18_19 : HAL.UInt2 := 16#0#; -- When in task mode: Initial value of the output when the GPIOTE -- channel is configured. When in event mode: No effect. OUTINIT : CONFIG_OUTINIT_Field := NRF_SVD.GPIOTE.Low; -- unspecified Reserved_21_31 : HAL.UInt11 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CONFIG_Register use record MODE at 0 range 0 .. 1; Reserved_2_7 at 0 range 2 .. 7; PSEL at 0 range 8 .. 12; Reserved_13_15 at 0 range 13 .. 15; POLARITY at 0 range 16 .. 17; Reserved_18_19 at 0 range 18 .. 19; OUTINIT at 0 range 20 .. 20; Reserved_21_31 at 0 range 21 .. 31; end record; -- Description collection[0]: Configuration for OUT[n], SET[n] and CLR[n] -- tasks and IN[n] event type CONFIG_Registers is array (0 .. 7) of CONFIG_Register; ----------------- -- Peripherals -- ----------------- -- GPIO Tasks and Events type GPIOTE_Peripheral is record -- Description collection[0]: Task for writing to pin specified in -- CONFIG[0].PSEL. Action on pin is configured in CONFIG[0].POLARITY. TASKS_OUT : aliased TASKS_OUT_Registers; -- Description collection[0]: Task for writing to pin specified in -- CONFIG[0].PSEL. Action on pin is to set it high. TASKS_SET : aliased TASKS_SET_Registers; -- Description collection[0]: Task for writing to pin specified in -- CONFIG[0].PSEL. Action on pin is to set it low. TASKS_CLR : aliased TASKS_CLR_Registers; -- Description collection[0]: Event generated from pin specified in -- CONFIG[0].PSEL EVENTS_IN : aliased EVENTS_IN_Registers; -- Event generated from multiple input GPIO pins with SENSE mechanism -- enabled EVENTS_PORT : aliased HAL.UInt32; -- Enable interrupt INTENSET : aliased INTENSET_Register; -- Disable interrupt INTENCLR : aliased INTENCLR_Register; -- Description collection[0]: Configuration for OUT[n], SET[n] and -- CLR[n] tasks and IN[n] event CONFIG : aliased CONFIG_Registers; end record with Volatile; for GPIOTE_Peripheral use record TASKS_OUT at 16#0# range 0 .. 255; TASKS_SET at 16#30# range 0 .. 255; TASKS_CLR at 16#60# range 0 .. 255; EVENTS_IN at 16#100# range 0 .. 255; EVENTS_PORT at 16#17C# range 0 .. 31; INTENSET at 16#304# range 0 .. 31; INTENCLR at 16#308# range 0 .. 31; CONFIG at 16#510# range 0 .. 255; end record; -- GPIO Tasks and Events GPIOTE_Periph : aliased GPIOTE_Peripheral with Import, Address => GPIOTE_Base; end NRF_SVD.GPIOTE;
generic type Element_Type is private; with function ">" ( Left, Right: Element_Type ) return Boolean; Min_Element : in Element_Type; package Binary_Heap is type Priority_Queue( Max_Size: Positive ) is limited private; procedure Delete_Min ( X: out Element_Type; H: in out Priority_Queue ); -- Delete and show minimum element in priority queue function Find_Min ( H: Priority_Queue ) return Element_Type; -- Return minimum element in priority queue procedure Insert ( X: Element_Type; H: in out Priority_Queue ); -- Add a new element to priority queue function Is_Empty ( H: Priority_Queue ) return Boolean; -- Returns true if priority queue is empty function Is_Full ( H: Priority_Queue ) return Boolean; -- Returns true if priority queue is full procedure Make_Empty( H: out Priority_Queue ); -- Make a priority queue empty Overflow : exception; -- Raised for Insert on a full priority queue Underflow: exception; -- Raised for Delete_Min or Find_Min private type Array_Of_Element_Type is array( Natural range <> ) of Element_Type; type Priority_Queue( Max_Size : Positive ) is record Size : Natural := 0; Element : Array_Of_Element_Type( 0..Max_Size ) := ( others => Min_Element ); end record; end Binary_Heap;
-- -- -- with Types; package body Action_Algorithms is function Compute_Action (Session : Session_Type; Action : Action_Record) return Integer is use Actions; use type Types.Symbol_Index; State_Num : constant Integer := Integer (Action.X.State.Number); Min_Reduce : constant Integer := Integer (Session.Min_Reduce); Min_SR : constant Integer := Integer (Session.Min_Shift_Reduce); Rule_Number : constant Integer := Integer (Action.X.Rule.Number); begin case Action.Kind is when Shift => return State_Num; when Shift_Reduce => -- Since a SHIFT is inherient after a prior REDUCE, convert any -- SHIFTREDUCE action with a nonterminal on the LHS into a simple -- REDUCE action: if Action.Symbol.Index >= Session.Num_Terminal then return Min_Reduce + Rule_Number; else return Min_SR + Rule_Number; end if; when Reduce => return Min_Reduce + Rule_Number; when Error => return Integer (Session.Err_Action); when C_Accept => return Integer (Session.Acc_Action); when others => return -1; end case; end Compute_Action; end Action_Algorithms;
-- Práctica 4: César Borao Moratinos (Hash_Maps_G_Chaining, Test Program) with Ada.Text_IO; With Ada.Strings.Unbounded; with Ada.Numerics.Discrete_Random; with Hash_Maps_G; procedure Hash_Maps_Test is package ASU renames Ada.Strings.Unbounded; package ATIO renames Ada.Text_IO; HASH_SIZE: constant := 10; type Hash_Range is mod HASH_SIZE; function Natural_Hash (N: Natural) return Hash_Range is begin return Hash_Range'Mod(N); end Natural_Hash; function Nick_to_Integer (Nick: ASU.Unbounded_String) return Integer is C: character; Result: Integer := 0; Counter: Integer := 1; begin loop C := ASU.Element(Nick, Counter); Result := Result + Character'Pos(C); exit when Counter = ASU.Length(Nick); Counter := Counter + 1; end loop; return Result; end Nick_to_Integer; function Nick_Hash (Nick: ASU.Unbounded_String) return Hash_Range is begin return Hash_Range'Mod(Nick_to_Integer(Nick)); end Nick_Hash; package Maps is new Hash_Maps_G (Key_Type => ASU.Unbounded_String, Value_Type => Natural, "=" => ASU."=", Hash_Range => Hash_Range, Hash => Nick_Hash, Max => 10); procedure Print_Map (M : Maps.Map) is C: Maps.Cursor := Maps.First(M); begin Ada.Text_IO.Put_Line ("Map"); Ada.Text_IO.Put_Line ("==="); while Maps.Has_Element(C) loop Ada.Text_IO.Put_Line (ASU.To_String(Maps.Element(C).Key) & " " & Natural'Image(Maps.Element(C).Value)); Maps.Next(C); end loop; end Print_Map; procedure Do_Put (M: in out Maps.Map; K: ASU.Unbounded_String; V: Natural) is begin Ada.Text_IO.New_Line; ATIO.Put_Line("Putting " & ASU.To_String(K)); Maps.Put (M, K, V); Print_Map(M); exception when Maps.Full_Map => Ada.Text_IO.Put_Line("Full_Map"); end Do_Put; procedure Do_Get (M: in out Maps.Map; K: ASU.Unbounded_String) is V: Natural; Success: Boolean; begin Ada.Text_IO.New_Line; ATIO.Put_Line("Getting " & ASU.To_String(K)); Maps.Get (M, K, V, Success); if Success then Ada.Text_IO.Put_Line("Value: " & Natural'Image(V)); Print_Map(M); else Ada.Text_IO.Put_Line("Element not found!"); end if; end Do_Get; procedure Do_Delete (M: in out Maps.Map; K: ASU.Unbounded_String) is Success: Boolean; begin Ada.Text_IO.New_Line; ATIO.Put_Line("Deleting " & ASU.To_String(K)); Maps.Delete (M, K, Success); if Success then Print_Map(M); else Ada.Text_IO.Put_Line("Element not found!"); end if; end Do_Delete; A_Map : Maps.Map; begin -- First puts Do_Put (A_Map, ASU.To_Unbounded_String("lechuga"), 10); Do_Put (A_Map, ASU.To_Unbounded_String("tomate"), 11); Do_Put (A_Map, ASU.To_Unbounded_String("cebolla"), 30); Do_Put (A_Map, ASU.To_Unbounded_String("pimiento"), 15); Do_Put (A_Map, ASU.To_Unbounded_String("atun"), 50); Do_Put (A_Map, ASU.To_Unbounded_String("aceituna"), 17); Do_Put (A_Map, ASU.To_Unbounded_String("maiz"), 16); Do_Put (A_Map, ASU.To_Unbounded_String("aceite"), 40); Do_Put (A_Map, ASU.To_Unbounded_String("esparrago"), 25); Do_Put (A_Map, ASU.To_Unbounded_String("vinagre"), 60); -- Now deletes Do_Delete (A_Map, ASU.To_Unbounded_String("cebolla")); Do_Delete (A_Map, ASU.To_Unbounded_String("carne")); Do_Delete (A_Map, ASU.To_Unbounded_String("pescado")); Do_Delete (A_Map, ASU.To_Unbounded_String("aceituna")); Do_Delete (A_Map, ASU.To_Unbounded_String("bacon")); Do_Delete (A_Map, ASU.To_Unbounded_String("macarron")); -- Now gets Do_Get (A_Map, ASU.To_Unbounded_String("arroz")); Do_Get (A_Map, ASU.To_Unbounded_String("cebolla")); Do_Get (A_Map, ASU.To_Unbounded_String("vinagre")); end Hash_Maps_Test;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with Ada.Unchecked_Conversion; with System.Address_To_Access_Conversions; with GL; with Glfw.API; with Glfw.Enums; with Glfw.Windows.Context; package body Glfw.Windows is package Conv is new System.Address_To_Access_Conversions (Window'Class); procedure Raw_Position_Callback (Raw : System.Address; X, Y : Interfaces.C.int); procedure Raw_Size_Callback (Raw : System.Address; Width, Height : Interfaces.C.int); procedure Raw_Close_Callback (Raw : System.Address); procedure Raw_Refresh_Callback (Raw : System.Address); procedure Raw_Focus_Callback (Raw : System.Address; Focused : Bool); procedure Raw_Iconify_Callback (Raw : System.Address; Iconified : Bool); procedure Raw_Framebuffer_Size_Callback (Raw : System.Address; Width, Height : Interfaces.C.int); procedure Raw_Mouse_Button_Callback (Raw : System.Address; Button : Input.Mouse.Button; State : Input.Button_State; Mods : Input.Keys.Modifiers); procedure Raw_Mouse_Position_Callback (Raw : System.Address; X, Y : Input.Mouse.Coordinate); procedure Raw_Mouse_Scroll_Callback (Raw : System.Address; X, Y : Input.Mouse.Scroll_Offset); procedure Raw_Mouse_Enter_Callback (Raw : System.Address; Action : Input.Mouse.Enter_Action); procedure Raw_Key_Callback (Raw : System.Address; Key : Input.Keys.Key; Scancode : Input.Keys.Scancode; Action : Input.Keys.Action; Mods : Input.Keys.Modifiers); procedure Raw_Character_Callback (Raw : System.Address; Char : Interfaces.C.unsigned); pragma Convention (C, Raw_Position_Callback); pragma Convention (C, Raw_Size_Callback); pragma Convention (C, Raw_Close_Callback); pragma Convention (C, Raw_Refresh_Callback); pragma Convention (C, Raw_Focus_Callback); pragma Convention (C, Raw_Iconify_Callback); pragma Convention (C, Raw_Framebuffer_Size_Callback); pragma Convention (C, Raw_Mouse_Button_Callback); pragma Convention (C, Raw_Mouse_Position_Callback); pragma Convention (C, Raw_Mouse_Scroll_Callback); pragma Convention (C, Raw_Mouse_Enter_Callback); pragma Convention (C, Raw_Key_Callback); pragma Convention (C, Raw_Character_Callback); function Window_Ptr (Raw : System.Address) return not null access Window'Class is begin return Conv.To_Pointer (API.Get_Window_User_Pointer (Raw)); end Window_Ptr; procedure Raw_Position_Callback (Raw : System.Address; X, Y : Interfaces.C.int) is begin Window_Ptr (Raw).Position_Changed (Integer (X), Integer (Y)); end Raw_Position_Callback; procedure Raw_Size_Callback (Raw : System.Address; Width, Height : Interfaces.C.int) is begin Window_Ptr (Raw).Size_Changed (Natural (Width), Natural (Height)); end Raw_Size_Callback; procedure Raw_Close_Callback (Raw : System.Address) is begin Window_Ptr (Raw).Close_Requested; end Raw_Close_Callback; procedure Raw_Refresh_Callback (Raw : System.Address) is begin Window_Ptr (Raw).Refresh; end Raw_Refresh_Callback; procedure Raw_Focus_Callback (Raw : System.Address; Focused : Bool) is begin Window_Ptr (Raw).Focus_Changed (Boolean (Focused)); end Raw_Focus_Callback; procedure Raw_Iconify_Callback (Raw : System.Address; Iconified : Bool) is begin Window_Ptr (Raw).Iconification_Changed (Boolean (Iconified)); end Raw_Iconify_Callback; procedure Raw_Framebuffer_Size_Callback (Raw : System.Address; Width, Height : Interfaces.C.int) is begin Window_Ptr (Raw).Framebuffer_Size_Changed (Natural (Width), Natural (Height)); end Raw_Framebuffer_Size_Callback; procedure Raw_Mouse_Button_Callback (Raw : System.Address; Button : Input.Mouse.Button; State : Input.Button_State; Mods : Input.Keys.Modifiers) is begin Window_Ptr (Raw).Mouse_Button_Changed (Button, State, Mods); end Raw_Mouse_Button_Callback; procedure Raw_Mouse_Position_Callback (Raw : System.Address; X, Y : Input.Mouse.Coordinate) is begin Window_Ptr (Raw).Mouse_Position_Changed (X, Y); end Raw_Mouse_Position_Callback; procedure Raw_Mouse_Scroll_Callback (Raw : System.Address; X, Y : Input.Mouse.Scroll_Offset) is begin Window_Ptr (Raw).Mouse_Scrolled (X, Y); end Raw_Mouse_Scroll_Callback; procedure Raw_Mouse_Enter_Callback (Raw : System.Address; Action : Input.Mouse.Enter_Action) is begin Window_Ptr (Raw).Mouse_Entered (Action); end Raw_Mouse_Enter_Callback; procedure Raw_Key_Callback (Raw : System.Address; Key : Input.Keys.Key; Scancode : Input.Keys.Scancode; Action : Input.Keys.Action; Mods : Input.Keys.Modifiers) is begin Window_Ptr (Raw).Key_Changed (Key, Scancode, Action, Mods); end Raw_Key_Callback; procedure Raw_Character_Callback (Raw : System.Address; Char : Interfaces.C.unsigned) is function Convert is new Ada.Unchecked_Conversion (Interfaces.C.unsigned, Wide_Wide_Character); begin Window_Ptr (Raw).Character_Entered (Convert (Char)); end Raw_Character_Callback; procedure Init (Object : not null access Window; Width, Height : Size; Title : String; Monitor : Monitors.Monitor := Monitors.No_Monitor; Share_Resources_With : access Window'Class := null) is use type System.Address; C_Title : constant Interfaces.C.char_array := Interfaces.C.To_C (Title); Share : System.Address; begin if Object.Handle /= System.Null_Address then raise Operation_Exception with "Window has already been initialized"; end if; if Share_Resources_With = null then Share := System.Null_Address; else Share := Share_Resources_With.Handle; end if; Object.Handle := API.Create_Window (Interfaces.C.int (Width), Interfaces.C.int (Height), C_Title, Monitor.Raw_Pointer, Share); if Object.Handle = System.Null_Address then raise Creation_Error; end if; API.Set_Window_User_Pointer (Object.Handle, Conv.To_Address (Conv.Object_Pointer'(Object.all'Unchecked_Access))); Context.Make_Current (Object); GL.Init; end Init; function Initialized (Object : not null access Window) return Boolean is use type System.Address; begin return Object.Handle /= System.Null_Address; end Initialized; procedure Destroy (Object : not null access Window) is begin API.Destroy_Window (Object.Handle); Object.Handle := System.Null_Address; end Destroy; procedure Show (Object : not null access Window) is begin API.Show_Window (Object.Handle); end Show; procedure Hide (Object : not null access Window) is begin API.Hide_Window (Object.Handle); end Hide; procedure Set_Title (Object : not null access Window; Value : String) is begin API.Set_Window_Title (Object.Handle, Interfaces.C.To_C (Value)); end Set_Title; function Key_State (Object : not null access Window; Key : Input.Keys.Key) return Input.Button_State is begin return API.Get_Key (Object.Handle, Key); end Key_State; function Mouse_Button_State (Object : not null access Window; Button : Input.Mouse.Button) return Input.Button_State is begin return API.Get_Mouse_Button (Object.Handle, Button); end Mouse_Button_State; procedure Set_Input_Toggle (Object : not null access Window; Kind : Input.Sticky_Toggle; Value : Boolean) is begin API.Set_Input_Mode (Object.Handle, Kind, Bool (Value)); end Set_Input_Toggle; function Get_Cursor_Mode (Object : not null access Window) return Input.Mouse.Cursor_Mode is begin return API.Get_Input_Mode (Object.Handle, Enums.Mouse_Cursor); end Get_Cursor_Mode; procedure Set_Cursor_Mode (Object : not null access Window; Mode : Input.Mouse.Cursor_Mode) is begin API.Set_Input_Mode (Object.Handle, Enums.Mouse_Cursor, Mode); end Set_Cursor_Mode; procedure Get_Cursor_Pos (Object : not null access Window; X, Y : out Input.Mouse.Coordinate) is begin API.Get_Cursor_Pos (Object.Handle, X, Y); end Get_Cursor_Pos; procedure Set_Cursor_Pos (Object : not null access Window; X, Y : Input.Mouse.Coordinate) is begin API.Set_Cursor_Pos (Object.Handle, X, Y); end Set_Cursor_Pos; procedure Get_Position (Object : not null access Window; X, Y : out Coordinate) is begin API.Get_Window_Pos (Object.Handle, X, Y); end Get_Position; procedure Set_Position (Object : not null access Window; X, Y : Coordinate) is begin API.Set_Window_Pos (Object.Handle, X, Y); end Set_Position; procedure Get_Size (Object : not null access Window; Width, Height : out Size) is begin API.Get_Window_Size (Object.Handle, Width, Height); end Get_Size; procedure Set_Size (Object : not null access Window; Width, Height : Size) is begin API.Set_Window_Size (Object.Handle, Width, Height); end Set_Size; procedure Get_Framebuffer_Size (Object : not null access Window; Width, Height : out Size) is begin API.Get_Framebuffer_Size (Object.Handle, Width, Height); end Get_Framebuffer_Size; function Visible (Object : not null access Window) return Boolean is begin return Boolean (Bool'(API.Get_Window_Attrib (Object.Handle, Enums.Visible))); end Visible; function Iconified (Object : not null access Window) return Boolean is begin return Boolean (Bool'(API.Get_Window_Attrib (Object.Handle, Enums.Iconified))); end Iconified; function Focused (Object : not null access Window) return Boolean is begin return Boolean (Bool'(API.Get_Window_Attrib (Object.Handle, Enums.Focused))); end Focused; function Should_Close (Object : not null access Window) return Boolean is begin return Boolean (API.Window_Should_Close (Object.Handle)); end Should_Close; procedure Set_Should_Close (Object : not null access Window; Value : Boolean) is begin API.Set_Window_Should_Close (Object.Handle, Bool (Value)); end Set_Should_Close; procedure Enable_Callback (Object : not null access Window; Subject : Callbacks.Kind) is begin case Subject is when Callbacks.Position => API.Set_Window_Pos_Callback (Object.Handle, Raw_Position_Callback'Access); when Callbacks.Size => API.Set_Window_Size_Callback (Object.Handle, Raw_Size_Callback'Access); when Callbacks.Close => API.Set_Window_Close_Callback (Object.Handle, Raw_Close_Callback'Access); when Callbacks.Refresh => API.Set_Window_Refresh_Callback (Object.Handle, Raw_Refresh_Callback'Access); when Callbacks.Focus => API.Set_Window_Focus_Callback (Object.Handle, Raw_Focus_Callback'Access); when Callbacks.Iconify => API.Set_Window_Iconify_Callback (Object.Handle, Raw_Iconify_Callback'Access); when Callbacks.Framebuffer_Size => API.Set_Framebuffer_Size_Callback (Object.Handle, Raw_Framebuffer_Size_Callback'Access); when Callbacks.Mouse_Button => API.Set_Mouse_Button_Callback (Object.Handle, Raw_Mouse_Button_Callback'Access); when Callbacks.Mouse_Position => API.Set_Cursor_Pos_Callback (Object.Handle, Raw_Mouse_Position_Callback'Access); when Callbacks.Mouse_Scroll => API.Set_Scroll_Callback (Object.Handle, Raw_Mouse_Scroll_Callback'Access); when Callbacks.Mouse_Enter => API.Set_Cursor_Enter_Callback (Object.Handle, Raw_Mouse_Enter_Callback'Access); when Callbacks.Key => API.Set_Key_Callback (Object.Handle, Raw_Key_Callback'Access); when Callbacks.Char => API.Set_Char_Callback (Object.Handle, Raw_Character_Callback'Access); end case; end Enable_Callback; procedure Disable_Callback (Object : not null access Window; Subject : Callbacks.Kind) is begin case Subject is when Callbacks.Position => API.Set_Window_Pos_Callback (Object.Handle, null); when Callbacks.Size => API.Set_Window_Size_Callback (Object.Handle, null); when Callbacks.Close => API.Set_Window_Close_Callback (Object.Handle, null); when Callbacks.Refresh => API.Set_Window_Refresh_Callback (Object.Handle, null); when Callbacks.Focus => API.Set_Window_Focus_Callback (Object.Handle, null); when Callbacks.Iconify => API.Set_Window_Iconify_Callback (Object.Handle, null); when Callbacks.Framebuffer_Size => API.Set_Framebuffer_Size_Callback (Object.Handle, null); when Callbacks.Mouse_Button => API.Set_Mouse_Button_Callback (Object.Handle, null); when Callbacks.Mouse_Position => API.Set_Cursor_Pos_Callback (Object.Handle, null); when Callbacks.Mouse_Scroll => API.Set_Scroll_Callback (Object.Handle, null); when Callbacks.Mouse_Enter => API.Set_Cursor_Enter_Callback (Object.Handle, null); when Callbacks.Key => API.Set_Key_Callback (Object.Handle, null); when Callbacks.Char => API.Set_Char_Callback (Object.Handle, null); end case; end Disable_Callback; procedure Get_OpenGL_Version (Object : not null access Window; Major, Minor, Revision : out Natural) is Value : Interfaces.C.int; begin Value := API.Get_Window_Attrib (Object.Handle, Enums.Context_Version_Major); Major := Natural (Value); Value := API.Get_Window_Attrib (Object.Handle, Enums.Context_Version_Minor); Minor := Natural (Value); Value := API.Get_Window_Attrib (Object.Handle, Enums.Context_Revision); Revision := Natural (Value); end Get_OpenGL_Version; end Glfw.Windows;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with Ada.Unchecked_Deallocation; package body GL.Objects is procedure Initialize_Id (Object : in out GL_Object) is New_Id : UInt; begin -- may raise exception; therefore we call it before actually making -- changes to the holder. GL_Object'Class (Object).Internal_Create_Id (New_Id); Object.Clear; Object.Reference := new GL_Object_Reference'(GL_Id => New_Id, Reference_Count => 1, Is_Owner => True); end Initialize_Id; overriding procedure Adjust (Object : in out GL_Object) is begin if Object.Reference /= null and then Object.Reference.Reference_Count > 0 then Object.Reference.Reference_Count := Object.Reference.Reference_Count + 1; end if; end Adjust; overriding procedure Finalize (Object : in out GL_Object) is procedure Free is new Ada.Unchecked_Deallocation (Object => GL_Object_Reference, Name => GL_Object_Reference_Access); Reference : GL_Object_Reference_Access := Object.Reference; begin Object.Reference := null; if Reference /= null and then Reference.Reference_Count > 0 then -- Reference_Count = 0 means that the holder recides in global memory Reference.Reference_Count := Reference.Reference_Count - 1; if Reference.Reference_Count = 0 then if Reference.Is_Owner then begin GL_Object'Class (Object).Internal_Release_Id (Reference.GL_Id); exception when others => -- cannot let this escape as we're in a Finalize call and -- thus that error cannot be properly catched. Chances are -- that if the destructor fails, the context already has -- vanished and thus we do not need to worry about -- anything. null; end; end if; Free (Reference); end if; end if; end Finalize; function Initialized (Object : GL_Object) return Boolean is begin return Object.Reference /= null; end Initialized; function Raw_Id (Object : GL_Object) return UInt is begin return Object.Reference.GL_Id; end Raw_Id; procedure Set_Raw_Id (Object : in out GL_Object; Id : UInt; Owned : Boolean := True) is begin Object.Finalize; -- must create a new holder object for this ID. therefore, we are -- dropping the reference to the old ID. Object.Reference := new GL_Object_Reference'(GL_Id => Id, Reference_Count => 1, Is_Owner => Owned); end Set_Raw_Id; function "=" (Left, Right : GL_Object) return Boolean is begin return Left.Reference = Right.Reference; end "="; procedure Clear (Object : in out GL_Object) renames Finalize; end GL.Objects;
-- Task 2 of RTPL WS17/18 -- Team members: Hannes B. and Gabriel Z. package convert with SPARK_Mode is -- Procedure for option 2 procedure opt2; -- Procedure for option 3 procedure opt3; private -- Float values for user input F1 : Float := 1.0; F2 : Float := 2.0; -- Convert Celsius to Fahrenheit function myCel2Fahr (cel : Float) return Float with Pre => cel >= -273.15, Post => myCel2Fahr'Result >= -459.67, Global => null, Depends => (myCel2Fahr'Result => cel); -- Convert Celsius to Fahrenheit function myFahr2Cel (fahr : Float) return Float with Pre => fahr >= -459.67, Post => myFahr2Cel'Result >= -273.15, Global => null, Depends => (myFahr2Cel'Result => fahr); end convert;
package body data_storage is overriding function Get_Data (ND : Naive_Data) return Integer is begin return ND.data; end; overriding procedure Set_Data (ND : in out Naive_Data; data : Integer) is begin ND.data := data; end; overriding function Do_Complex_Calculation(ND : Naive_Data; input : Integer) return Integer is begin return Do_Naive_Calculation(ND, input); end; overriding function Get_Extra_Data (OD : Optimized_Data) return Integer is begin return OD.extra_data; end; overriding procedure Set_Extra_Data (OD : in out Optimized_Data; data : Integer) is begin OD.extra_data := data; end; overriding function Do_Complex_Calculation(OD : Optimized_Data; input : Integer) return Integer is begin return Do_Optimized_Calculation(OD, input); end; end data_storage;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- -- -- This specification is derived from the Ada Semantic Interface -- -- Specification Standard (ISO/IEC 15291) and ASIS 1999 Issues. -- -- -- -- The copyright notice and the license provisions that follow apply to the -- -- part following the private keyword. -- -- -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $ ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- 15 package Asis.Declarations ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- package Asis.Declarations is pragma Preelaborate; ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- Asis.Declarations encapsulates a set of queries that operate on -- A_Defining_Name and A_Declaration elements. ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- |ER A_Declaration - 3.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- 15.1 function Names ------------------------------------------------------------------------------- function Names (Declaration : in Asis.Declaration) return Asis.Defining_Name_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the element to query -- -- Returns a list of names defined by the declaration, in their order of -- appearance. Declarations that define a single name will return a list of -- length one. -- -- Returns Nil_Element_List for A_Declaration Elements representing the -- (implicit) declarations of universal and root numeric type (that is, if -- Type_Kind (Type_Declaration_View (Declaration)) = A_Root_Type_Definition). -- -- Examples: -- -- type Foo is (Pooh, Baah); -- -- Returns a list containing one A_Defining_Name: Foo. -- -- One, Uno : constant Integer := 1; -- -- Returns a list of two A_Defining_Name elements: One and Uno. -- -- Function designators that define operators are A_Defining_Operator_Symbol. -- -- Results of this query may vary across ASIS implementations. Some -- implementations may normalize all multi-name declarations into an -- equivalent series of corresponding single name declarations. For those -- implementations, this query will always return a list containing a single -- name. See Reference Manual 3.3.1(7). -- -- Appropriate Element_Kinds: -- A_Declaration -- -- Returns Element_Kinds: -- A_Defining_Name -- -- |ER------------------------------------------------------------------------ -- |ER A_Defining_Name - 3.1 -- |ER------------------------------------------------------------------------ -- |ER A_Defining_Identifier - 3.1 - no child elements -- |ER A_Defining_Operator_Symbol - 6.1 - no child elements -- |ER -- |ER A string image returned by: -- |ER function Defining_Name_Image -- ------------------------------------------------------------------------------- -- 15.2 function Defining_Name_Image ------------------------------------------------------------------------------- function Defining_Name_Image (Defining_Name : in Asis.Defining_Name) return Program_Text; ------------------------------------------------------------------------------- -- Defining_Name - Specifies the element to query -- -- Returns the program text image of the name. Embedded quotes (for operator -- designator strings) are doubled. -- -- A_Defining_Identifier elements are simple identifier names "Abc" -- (name Abc). -- -- A_Defining_Operator_Symbol elements have names with embedded quotes -- """abs""" (function "abs"). -- -- A_Defining_Character_Literal elements have names with embedded apostrophes -- "'x'" (literal 'x'). -- -- A_Defining_Enumeration_Literal elements have simple identifier names -- "Blue" (literal Blue). If A_Defining_Enumeration_Literal element is of -- type Character or Wide_Character but does not have a graphical -- presentation, then the result is implementation-dependent. -- -- A_Defining_Expanded_Name elements are prefix.selector names "A.B.C" -- (name A.B.C). -- -- The case of names returned by this query may vary between implementors. -- Implementors are encouraged, but not required, to return names in the -- same case as was used in the original compilation text. -- -- The Defining_Name_Image of a label_statement_identifier does not include -- the enclosing "<<" and ">>" that form the label syntax. Similarly, the -- Defining_Name_Image of an identifier for a loop_statement or -- block_statement does not include the trailing colon that forms the loop -- name syntax. -- Use Asis.Text.Element_Image or Asis.Text.Lines queries to obtain these -- syntactic constructs and any comments associated with them. -- -- Appropriate Element_Kinds: -- A_Defining_Name -- |ER------------------------------------------------------------------------ -- |ER A_Defining_Character_Literal - 3.5.1 - no child elements -- |ER A_Defining_Enumeration_Literal - 3.5.1 - no child elements -- |ER -- |ER A program text image returned by: -- |ER function Defining_Name_Image -- |ER -- |ER A program text image of the enumeration literal value returned by: -- |ER function Position_Number_Image -- |ER function Representation_Value_Image -- ------------------------------------------------------------------------------- -- 15.3 function Position_Number_Image ------------------------------------------------------------------------------- function Position_Number_Image (Defining_Name : in Asis.Defining_Name) return Wide_String; ------------------------------------------------------------------------------- -- Expression - Specifies the literal expression to query -- -- Returns the program text image of the position number of the value of the -- enumeration literal. -- -- The program text returned is the image of the universal_integer value that -- is returned by the attribute 'Pos if it were applied to the value. -- For example: Integer'Image(Color'Pos(Blue)). -- -- Appropriate Defining_Name_Kinds: -- A_Defining_Character_Literal -- A_Defining_Enumeration_Literal -- ------------------------------------------------------------------------------- -- 15.4 function Representation_Value_Image ------------------------------------------------------------------------------- function Representation_Value_Image (Defining_Name : in Asis.Defining_Name) return Wide_String; ------------------------------------------------------------------------------- -- Expression - Specifies the literal expression to query -- -- Returns the string image of the internal code for the enumeration literal. -- -- If a representation_clause is defined for the enumeration type then the -- string returned is the Integer'Wide_Image of the corresponding value given -- in the enumeration_aggregate. Otherwise, the string returned is the same -- as the Position_Number_Image. -- -- Appropriate Defining_Name_Kinds: -- A_Defining_Character_Literal -- A_Defining_Enumeration_Literal -- -- |ER------------------------------------------------------------------------ -- |ER A_Defining_Expanded_Name - 6.1 -- |ER -- |ER A string image returned by: -- |ER function Defining_Name_Image -- |CR -- |CR Child elements returned by: -- |CR function Defining_Prefix -- |CR function Defining_Selector -- ------------------------------------------------------------------------------- -- 15.5 function Defining_Prefix ------------------------------------------------------------------------------- function Defining_Prefix (Defining_Name : in Asis.Defining_Name) return Asis.Name; ------------------------------------------------------------------------------- -- Defining_Name - Specifies the element to query -- -- Returns the element that forms the prefix of the name. The prefix is the -- name to the left of the rightmost 'dot' in the expanded name. -- The Defining_Prefix of A.B is A, and of A.B.C is A.B. -- -- Appropriate Defining_Name_Kinds: -- A_Defining_Expanded_Name -- -- Returns Expression_Kinds: -- An_Identifier -- A_Selected_Component -- ------------------------------------------------------------------------------- -- 15.6 function Defining_Selector ------------------------------------------------------------------------------- function Defining_Selector (Defining_Name : in Asis.Defining_Name) return Asis.Defining_Name; ------------------------------------------------------------------------------- -- Defining_Name - Specifies the element to query -- -- Returns the element that forms the selector of the name. The selector is -- the name to the right of the rightmost 'dot' in the expanded name. -- The Defining_Selector of A.B is B, and of A.B.C is C. -- -- Appropriate Defining_Name_Kinds: -- A_Defining_Expanded_Name -- -- Returns Defining_Name_Kinds: -- A_Defining_Identifier -- -- |ER------------------------------------------------------------------------ -- |ER An_Ordinary_Type_Declaration - 3.2.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Discriminant_Part -- |CR function Type_Declaration_View -- ------------------------------------------------------------------------------- -- 15.7 function Discriminant_Part ------------------------------------------------------------------------------- function Discriminant_Part (Declaration : in Asis.Declaration) return Asis.Definition; ------------------------------------------------------------------------------- -- Declaration - Specifies the type declaration to query -- -- Returns the discriminant_part, if any, from the type_declaration or -- formal_type_declaration. -- -- Returns a Nil_Element if the Declaration has no explicit discriminant_part. -- -- Appropriate Declaration_Kinds: -- An_Ordinary_Type_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- An_Incomplete_Type_Declaration -- A_Private_Type_Declaration -- A_Private_Extension_Declaration -- A_Formal_Type_Declaration -- -- Returns Definition_Kinds: -- Not_A_Definition -- An_Unknown_Discriminant_Part -- A_Known_Discriminant_Part -- ------------------------------------------------------------------------------- -- 15.8 function Type_Declaration_View ------------------------------------------------------------------------------- function Type_Declaration_View (Declaration : in Asis.Declaration) return Asis.Definition; ------------------------------------------------------------------------------- -- Declaration - Specifies the declaration element to query -- -- Returns the definition characteristics that form the view of the -- type_declaration. The view is the remainder of the declaration following -- the reserved word "is". -- -- For a full_type_declaration, returns the type_definition, task_definition, -- or protected_definition following the reserved word "is" in the -- declaration. -- -- Returns a Nil_Element for a task_type_declaration that has no explicit -- task_definition. -- -- For a private_type_declaration or private_extension_declaration, returns -- the definition element representing the private declaration view. -- -- For an incomplete_type_declaration, returns the definition element -- representing the incomplete declaration view. -- -- For a subtype_declaration, returns the subtype_indication. -- -- For a formal_type_declaration, returns the formal_type_definition. -- -- Appropriate Declaration_Kinds: -- An_Ordinary_Type_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Private_Type_Declaration -- A_Private_Extension_Declaration -- A_Subtype_Declaration -- A_Formal_Type_Declaration -- An_Incomplete_Type_Declaration -- -- Returns Definition_Kinds: -- Not_A_Definition -- A_Type_Definition -- A_Subtype_Indication -- An_Incomplete_Type_Definition -- A_Tagged_Incomplete_Type_Definition -- A_Private_Type_Definition -- A_Tagged_Private_Type_Definition -- A_Private_Extension_Definition -- A_Task_Definition -- A_Protected_Definition -- A_Formal_Type_Definition -- -- |ER------------------------------------------------------------------------ -- |ER A_Subtype_Declaration - 3.2.2 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Type_Declaration_View -- |ER------------------------------------------------------------------------ -- |ER A_Variable_Declaration - 3.3.1 -- |CR -- |CR Child elements: -- |CR function Names -- |CR function Object_Declaration_View -- |CR function Initialization_Expression -- ------------------------------------------------------------------------------- -- 15.9 function Object_Declaration_Subtype ------------------------------------------------------------------------------- function Object_Declaration_Subtype (Declaration : in Asis.Declaration) return Asis.Definition; ------------------------------------------------------------------------------- -- Declaration - Specifies the declaration element to query. -- -- Returns a definition that corresponds to the subtype -- of the object, as specified by a subtype_indication, subtype_mark, -- access_definition, or full type definition. -- -- For a single_task_declaration or single_protected_declaration, returns -- the task_definition or protected_definition. If no task_definition is -- given explicitly (the reserved word is is not written), an empty -- task_definition is returned for which Is_Task_Definition_Present returns -- False. -- -- If an empty task_definition E is returned, then -- Is_Part_of_Implicit(E) = False; Element_Span(E) returns a value where the -- First_Column_Number > Last_Column_Numbber and First_Line = Last_Line = -- the line of the semicolon; Element_Image(E) = ""; and Lines(E) returns -- a single line whose Line_Image = "". -- -- For a Component_Declaration, returns the Component_Definition following -- the colon. -- -- For all other object_declaration variables or constants, parameter or -- discriminant specifications, object renamings, or formal object, returns -- the subtype_indication, subtype_mark, access_definition, or -- array_type_definition following the colon. -- -- Appropriate Declaration_Kinds: -- A_Variable_Declaration -- A_Constant_Declaration -- A_Deferred_Constant_Declaration -- A_Single_Protected_Declaration -- A_Single_Task_Declaration -- A_Component_Declaration -- A_Discriminant_Specification -- A_Parameter_Specification -- A_Formal_Object_Declaration -- An_Object_Renaming_Declaration -- -- Returns Definition_Kinds: -- Not_A_Definition -- A_Type_Definition -- Returns Type_Kinds: -- A_Constrained_Array_Definition -- A_Subtype_Indication -- A_Task_Definition -- A_Protected_Definition -- A_Component_Definition -- An_Access_Definition -- -- NOTE: Asis.Declarations.Object_Declaration_View, -- Asis.Declarations.Declaration_Subtype_Mark and the value -- An_Access_Definition_Trait of Trait_Kinds type are obsolete in ASIS 2005 -- and should not be used in new applications that are supposed to analyze Ada -- 2005 code. -- ------------------------------------------------------------------------------- -- 15.9 function Object_Declaration_View (obsolete) ------------------------------------------------------------------------------- function Object_Declaration_View (Declaration : in Asis.Declaration) return Asis.Definition; ------------------------------------------------------------------------------- -- Declaration - Specifies the declaration element to query -- -- Returns the definition characteristics that form the view of the -- object_declaration. The view is the subtype_indication or full type -- definition of the object_declaration. An initial value, if any, is not -- part of this view. -- -- For a single_task_declaration or single_protected_declaration, returns -- the task_definition or protected_definition following the reserved word -- "is". -- -- Returns a Nil_Element for a single_task_declaration that has no explicit -- task_definition. -- -- For a Component_Declaration, returns the Component_Definition following -- the colon. -- -- For all other object_declaration variables or constants, returns the -- subtype_indication or array_type_definition following the colon. -- -- Appropriate Declaration_Kinds: -- A_Variable_Declaration -- A_Constant_Declaration -- A_Deferred_Constant_Declaration -- A_Single_Protected_Declaration -- A_Single_Task_Declaration -- A_Component_Declaration -- -- Returns Definition_Kinds: -- Not_A_Definition -- A_Type_Definition -- Returns Type_Kinds: -- A_Constrained_Array_Definition -- A_Subtype_Indication -- A_Task_Definition -- A_Protected_Definition -- A_Component_Definition -- ------------------------------------------------------------------------------- -- 15.10 function Initialization_Expression ------------------------------------------------------------------------------- function Initialization_Expression (Declaration : in Asis.Declaration) return Asis.Expression; ------------------------------------------------------------------------------- -- Declaration - Specifies the object declaration to query -- -- Returns the initialization expression [:= expression] of the declaration. -- -- Returns a Nil_Element if the declaration does not include an explicit -- initialization. -- -- Appropriate Declaration_Kinds: -- A_Variable_Declaration -- A_Constant_Declaration -- An_Integer_Number_Declaration -- A_Real_Number_Declaration -- A_Discriminant_Specification -- A_Component_Declaration -- A_Parameter_Specification -- A_Formal_Object_Declaration -- -- Returns Element_Kinds: -- Not_An_Element -- An_Expression -- -- |ER------------------------------------------------------------------------ -- |ER A_Constant_Declaration - 3.3.1 -- |CR -- |CR Child elements: -- |CR function Names -- |CR function Object_Declaration_View -- |CR function Initialization_Expression -- |CR -- |CR Element queries that provide semantically related elements: -- |CR function Corresponding_Constant_Declaration -- ------------------------------------------------------------------------------- -- 15.11 function Corresponding_Constant_Declaration ------------------------------------------------------------------------------- function Corresponding_Constant_Declaration (Name : in Asis.Defining_Name) return Asis.Declaration; ------------------------------------------------------------------------------- -- Name - Specifies the name of a constant declaration to query -- -- Returns the corresponding full constant declaration when given the name -- from a deferred constant declaration. -- -- Returns the corresponding deferred constant declaration when given the -- name from a full constant declaration. -- -- Returns A_Pragma if the deferred constant declaration is completed -- by pragma Import. -- -- Returns a Nil_Element if the full constant declaration has no -- corresponding deferred constant declaration. -- -- Raises ASIS_Inappropriate_Element with a Status of Value_Error if the -- argument is not the name of a constant or a deferred constant. -- -- The name of a constant declaration is available from both the Names and -- the Corresponding_Name_Definition queries. -- -- Appropriate Element_Kinds: -- A_Defining_Name -- -- Returns Declaration_Kinds: -- Not_A_Declaration -- A_Constant_Declaration -- A_Deferred_Constant_Declaration -- -- Returns Element_Kinds: -- Not_An_Element -- A_Declaration -- A_Pragma -- |ER------------------------------------------------------------------------ -- |ER A_Deferred_Constant_Declaration - 3.3.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Object_Declaration_View -- |ER------------------------------------------------------------------------ -- |ER An_Integer_Number_Declaration - 3.3.2 -- |ER A_Real_Number_Declaration - 3.3.2 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Initialization_Expression -- |ER------------------------------------------------------------------------ -- |ER An_Enumeration_Literal_Specification - 3.5.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |ER------------------------------------------------------------------------ -- |ER A_Discriminant_Specification - 3.7 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Declaration_Subtype_Mark (obsolete) -- |CR function Initialization_Expression -- ------------------------------------------------------------------------------- -- 15.12 function Declaration_Subtype_Mark (obsolete) ------------------------------------------------------------------------------- function Declaration_Subtype_Mark (Declaration : in Asis.Declaration) return Asis.Expression; ------------------------------------------------------------------------------- -- Declaration - Specifies the declaration element to query -- -- Returns the expression element that names the subtype_mark of the -- declaration. -- -- Appropriate Declaration_Kinds: -- A_Discriminant_Specification -- A_Parameter_Specification -- A_Formal_Object_Declaration -- An_Object_Renaming_Declaration -- -- Returns Expression_Kinds: -- An_Identifier -- A_Selected_Component -- An_Attribute_Reference -- -- |ER------------------------------------------------------------------------ -- |ER A_Component_Declaration - 3.8 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Object_Declaration_View -- |CR function Initialization_Expression -- |ER------------------------------------------------------------------------ -- |ER An_Incomplete_Type_Declaration - 3.10.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Discriminant_Part -- ------------------------------------------------------------------------------- -- 15.13 function Corresponding_Type_Declaration ------------------------------------------------------------------------------- function Corresponding_Type_Declaration (Declaration : in Asis.Declaration) return Asis.Declaration; function Corresponding_Type_Declaration (Declaration : in Asis.Declaration; The_Context : in Asis.Context) return Asis.Declaration; ------------------------------------------------------------------------------- -- Declaration - Specifies the type declaration to query -- The_Context - Specifies the program Context to use for obtaining package -- body information -- -- Returns the corresponding full type declaration when given a private or -- incomplete type declaration. Returns the corresponding private or -- incomplete type declaration when given a full type declaration. -- -- These two function calls will always produce identical results: -- -- Decl2 := Corresponding_Type_Declaration ( Decl1 ); -- Decl2 := Corresponding_Type_Declaration -- ( Decl1, -- Enclosing_Context ( Enclosing_Compilation_Unit ( Decl1 ))); -- -- Returns a Nil_Element when a full type declaration is given that has no -- corresponding private or incomplete type declaration, or when a -- corresponding type declaration does not exist within The_Context. -- -- The parameter The_Context is used whenever the corresponding full type of -- an incomplete type is in a corresponding package body. See Reference -- Manual 3.10.1(3). Any non-Nil result will always have the given Context -- as its Enclosing_Context. -- -- Appropriate Declaration_Kinds: -- An_Ordinary_Type_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- An_Incomplete_Type_Declaration -- A_Private_Type_Declaration -- A_Private_Extension_Declaration -- -- Returns Declaration_Kinds: -- Not_A_Declaration -- An_Ordinary_Type_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- An_Incomplete_Type_Declaration -- A_Private_Type_Declaration -- A_Private_Extension_Declaration -- ------------------------------------------------------------------------------- -- 15.14 function Corresponding_First_Subtype ------------------------------------------------------------------------------- function Corresponding_First_Subtype (Declaration : in Asis.Declaration) return Asis.Declaration; ------------------------------------------------------------------------------- -- Declaration - Specifies the subtype_declaration to query -- -- This function recursively unwinds subtyping to return at -- a type_declaration that defines the first subtype of the argument. -- -- Returns a declaration that Is_Identical to the argument if the argument is -- already the first subtype. -- -- Appropriate Declaration_Kinds: -- An_Ordinary_Type_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Private_Type_Declaration -- A_Private_Extension_Declaration -- A_Subtype_Declaration -- A_Formal_Type_Declaration -- -- Returns Declaration_Kinds: -- An_Ordinary_Type_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Private_Type_Declaration -- A_Private_Extension_Declaration -- A_Formal_Type_Declaration -- ------------------------------------------------------------------------------- -- 15.15 function Corresponding_Last_Constraint ------------------------------------------------------------------------------- function Corresponding_Last_Constraint (Declaration : in Asis.Declaration) return Asis.Declaration; ------------------------------------------------------------------------------- -- Declaration - Specifies the subtype_declaration or type_declaration to -- query. -- -- This function recursively unwinds subtyping to return at a declaration -- that is either a type_declaration or subtype_declaration that imposes -- an explicit constraint on the argument. -- -- Unwinds a minimum of one level of subtyping even if an argument -- declaration itself has a constraint. -- -- Returns a declaration that Is_Identical to the argument if the argument -- is a type_declaration, i.e. the first subtype. -- -- Appropriate Declaration_Kinds: -- An_Ordinary_Type_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Private_Type_Declaration -- A_Private_Extension_Declaration -- A_Subtype_Declaration -- A_Formal_Type_Declaration -- -- Returns Declaration_Kinds: -- An_Ordinary_Type_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Private_Type_Declaration -- A_Private_Extension_Declaration -- A_Subtype_Declaration -- A_Formal_Type_Declaration -- ------------------------------------------------------------------------------- -- 15.16 function Corresponding_Last_Subtype ------------------------------------------------------------------------------- function Corresponding_Last_Subtype (Declaration : in Asis.Declaration) return Asis.Declaration; ------------------------------------------------------------------------------- -- Declaration - Specifies the subtype_declaration or type_declaration to -- query. -- -- This function unwinds subtyping a single level to arrive at a declaration -- that is either a type_declaration or subtype_declaration. -- -- Returns a declaration that Is_Identical to the argument if the argument -- is a type_declaration (i.e., the first subtype). -- -- Appropriate Declaration_Kinds: -- An_Ordinary_Type_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Private_Type_Declaration -- A_Private_Extension_Declaration -- A_Subtype_Declaration -- A_Formal_Type_Declaration -- -- Returns Declaration_Kinds: -- An_Ordinary_Type_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Private_Type_Declaration -- A_Private_Extension_Declaration -- A_Subtype_Declaration -- A_Formal_Type_Declaration -- ------------------------------------------------------------------------------- -- 15.17 function Corresponding_Representation_Clauses ------------------------------------------------------------------------------- function Corresponding_Representation_Clauses (Declaration : in Asis.Declaration) return Asis.Representation_Clause_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the declaration to query -- -- Returns all representation_clause elements that apply to the declaration. -- -- Returns a Nil_Element_List if no clauses apply to the declaration. -- -- The clauses returned may be the clauses applying to a parent type if the -- type is a derived type with no explicit representation. These clauses -- are not Is_Part_Of_Implicit, they are the representation_clause elements -- specified in conjunction with the declaration of the parent type. -- -- All Declaration_Kinds are appropriate except Not_A_Declaration. -- -- Returns Clause_Kinds: -- A_Representation_Clause -- |ER------------------------------------------------------------------------ -- |ER A_Loop_Parameter_Specification - 5.5 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Specification_Subtype_Definition -- ------------------------------------------------------------------------------- -- 15.18 function Specification_Subtype_Definition ------------------------------------------------------------------------------- function Specification_Subtype_Definition (Specification : in Asis.Declaration) return Asis.Discrete_Subtype_Definition; ------------------------------------------------------------------------------- -- Specification - Specifies the loop_parameter_specification or -- Entry_Index_Specification to query -- -- Returns the Discrete_Subtype_Definition of the specification. -- -- Appropriate Declaration_Kinds: -- A_Loop_Parameter_Specification -- An_Entry_Index_Specification -- -- Returns Definition_Kinds: -- A_Discrete_Subtype_Definition -- -- |ER------------------------------------------------------------------------ -- |ER A_Procedure_Declaration - 6.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Parameter_Profile -- ------------------------------------------------------------------------------- -- 15.19 function Parameter_Profile ------------------------------------------------------------------------------- function Parameter_Profile (Declaration : in Asis.Declaration) return Asis.Parameter_Specification_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the subprogram or entry declaration to query -- -- Returns a list of parameter specifications in the formal part of the -- subprogram or entry declaration, in their order of appearance. -- -- Returns a Nil_Element_List if the subprogram or entry has no -- parameters. -- -- Results of this query may vary across ASIS implementations. Some -- implementations normalize all multiple name parameter specifications into -- an equivalent sequence of corresponding single name parameter -- specifications. See Reference Manual 3.3.1(7). -- -- Appropriate Declaration_Kinds: -- A_Procedure_Declaration -- A_Function_Declaration -- A_Procedure_Body_Declaration -- A_Function_Body_Declaration -- A_Procedure_Renaming_Declaration -- A_Function_Renaming_Declaration -- An_Entry_Declaration -- An_Entry_Body_Declaration -- A_Procedure_Body_Stub -- A_Function_Body_Stub -- A_Generic_Function_Declaration -- A_Generic_Procedure_Declaration -- A_Formal_Function_Declaration -- A_Formal_Procedure_Declaration -- -- Returns Declaration_Kinds: -- A_Parameter_Specification -- -- |ER------------------------------------------------------------------------ -- |ER A_Function_Declaration - 6.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Parameter_Profile -- |CR function Result_Profile (obsolete) -- ------------------------------------------------------------------------------- -- 15.20 function Result_Subtype ------------------------------------------------------------------------------- function Result_Subtype (Declaration : in Asis.Declaration) return Asis.Definition; ------------------------------------------------------------------------------- -- Declaration - Specifies the function declaration to query. -- -- Returns a definition that corresponds to the result subtype -- of the function, as specified by a subtype_indication (with -- no specified constraint) or an access_definition. -- -- Appropriate Declaration_Kinds: -- A_Function_Declaration -- A_Function_Body_Declaration -- A_Function_Body_Stub -- A_Function_Renaming_Declaration -- A_Generic_Function_Declaration -- A_Formal_Function_Declaration -- -- Returns Definition_Kinds: -- A_Subtype_Indication -- An_Access_Definition -- ------------------------------------------------------------------------------- -- 15.20 function Result_Profile (obsolete) ------------------------------------------------------------------------------- function Result_Profile (Declaration : in Asis.Declaration) return Asis.Expression; ------------------------------------------------------------------------------- -- Declaration - Specifies the function declaration to query -- -- Returns the subtype mark expression for the return type for any function -- declaration. -- -- Appropriate Declaration_Kinds: -- A_Function_Declaration -- A_Function_Body_Declaration -- A_Function_Body_Stub -- A_Function_Renaming_Declaration -- A_Generic_Function_Declaration -- A_Formal_Function_Declaration -- -- Returns Expression_Kinds: -- An_Identifier -- A_Selected_Component -- An_Attribute_Reference -- -- |ER------------------------------------------------------------------------ -- |ER A_Parameter_Specification - 6.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Declaration_Subtype_Mark (obsolete) -- |CR function Initialization_Expression -- |ER------------------------------------------------------------------------ -- |ER A_Procedure_Body_Declaration - 6.3 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Parameter_Profile -- |CR function Body_Declarative_Items -- |CR function Body_Statements -- |CR function Body_Exception_Handlers -- |CR function Body_Block_Statement - obsolescent, not recommended -- ------------------------------------------------------------------------------- -- 15.21 function Body_Declarative_Items ------------------------------------------------------------------------------- function Body_Declarative_Items (Declaration : in Asis.Declaration; Include_Pragmas : in Boolean := False) return Asis.Element_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the body declaration to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of all basic declarations, representation specifications, -- use clauses, and pragmas in the declarative part of the body, in their -- order of appearance. -- -- Returns a Nil_Element_List if there are no declarative_item or pragma -- elements. -- -- Results of this query may vary across ASIS implementations. Some -- implementations normalize all multi-name declarations into an -- equivalent sequence of corresponding single name object declarations. -- See Reference Manual 3.3.1(7). -- -- Appropriate Declaration_Kinds: -- A_Function_Body_Declaration -- A_Procedure_Body_Declaration -- A_Package_Body_Declaration -- A_Task_Body_Declaration -- An_Entry_Body_Declaration -- -- Returns Element_Kinds: -- A_Pragma -- A_Declaration -- A_Clause -- ------------------------------------------------------------------------------- -- 15.22 function Body_Statements ------------------------------------------------------------------------------- function Body_Statements (Declaration : in Asis.Declaration; Include_Pragmas : in Boolean := False) return Asis.Statement_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the body declaration to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of the statements and pragmas for the body, in -- their order of appearance. -- -- Returns a Nil_Element_List if there are no statements or pragmas. -- -- Appropriate Declaration_Kinds: -- A_Function_Body_Declaration -- A_Procedure_Body_Declaration -- A_Package_Body_Declaration -- A_Task_Body_Declaration -- An_Entry_Body_Declaration -- -- Returns Element_Kinds: -- A_Pragma -- A_Statement -- ------------------------------------------------------------------------------- -- 15.23 function Body_Exception_Handlers ------------------------------------------------------------------------------- function Body_Exception_Handlers (Declaration : in Asis.Declaration; Include_Pragmas : in Boolean := False) return Asis.Exception_Handler_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the body declaration to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of the exception_handler elements of the body, in their -- order of appearance. -- -- The only pragmas returned are those following the reserved word -- "exception" and preceding the reserved word "when" of first exception -- handler. -- -- Returns a Nil_Element_List if there are no exception_handler or pragma -- elements. -- -- Appropriate Declaration_Kinds: -- A_Function_Body_Declaration -- A_Procedure_Body_Declaration -- A_Package_Body_Declaration -- A_Task_Body_Declaration -- An_Entry_Body_Declaration -- -- Returns Element_Kinds: -- An_Exception_Handler -- A_Pragma -- -- |ER------------------------------------------------------------------------ -- |ER A_Function_Body_Declaration - 6.3 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Parameter_Profile -- |CR function Result_Profile (obsolete) -- |CR function Body_Declarative_Items -- |CR function Body_Statements -- |CR function Body_Exception_Handlers -- |CR function Body_Block_Statement - obsolescent, not recommended -- ------------------------------------------------------------------------------- -- 15.24 function Body_Block_Statement ------------------------------------------------------------------------------- -- Function Body_Block_Statement is a new query that supplies the -- equivalent combined functionality of the replaced queries: -- Subprogram_Body_Block, Package_Body_Block, and Task_Body_Block. -- Use of the query Body_Block_Statement is not recommended in new programs. -- This functionality is redundant with the queries Body_Declarative_Items, -- Body_Statements, and Body_Exception_Handlers. ------------------------------------------------------------------------------- function Body_Block_Statement (Declaration : in Asis.Declaration) return Asis.Statement; ------------------------------------------------------------------------------- -- Declaration - Specifies the program unit body to query -- -- Returns a block statement that is the structural equivalent of the body. -- The block statement is not Is_Part_Of_Implicit. The block includes -- the declarative part, the sequence of statements, and any exception -- handlers. -- -- Appropriate Declaration_Kinds: -- A_Function_Body_Declaration -- A_Procedure_Body_Declaration -- A_Package_Body_Declaration -- A_Task_Body_Declaration -- An_Entry_Body_Declaration -- -- Returns Statement_Kinds: -- A_Block_Statement -- -- |AN Application Note: -- |AN -- |AN This function is an obsolescent feature retained for compatibility -- |AN with ASIS 83. It is never called by Traverse_Element. Use of this -- |AN query is not recommended in new programs. -- ------------------------------------------------------------------------------- -- 15.25 function Is_Name_Repeated ------------------------------------------------------------------------------- function Is_Name_Repeated (Declaration : in Asis.Declaration) return Boolean; ------------------------------------------------------------------------------- -- Declaration - Specifies the declaration to query -- -- Returns True if the name of the declaration is repeated after the "end" -- which terminates the declaration. -- -- Returns False for any unexpected Element. -- -- Expected Declaration_Kinds: -- A_Package_Declaration -- A_Package_Body_Declaration -- A_Procedure_Body_Declaration -- A_Function_Body_Declaration -- A_Generic_Package_Declaration -- A_Task_Type_Declaration -- A_Single_Task_Declaration -- A_Task_Body_Declaration -- A_Protected_Type_Declaration -- A_Single_Protected_Declaration -- A_Protected_Body_Declaration -- An_Entry_Body_Declaration -- ------------------------------------------------------------------------------- -- 15.26 function Corresponding_Declaration ------------------------------------------------------------------------------- function Corresponding_Declaration (Declaration : in Asis.Declaration) return Asis.Declaration; function Corresponding_Declaration (Declaration : in Asis.Declaration; The_Context : in Asis.Context) return Asis.Declaration; ------------------------------------------------------------------------------- -- Declaration - Specifies the specification to query -- The_Context - Specifies a Context to use -- -- Returns the corresponding specification of a subprogram, package, or task -- body declaration. Returns the expanded generic specification template for -- generic instantiations. The argument can be a Unit_Declaration from a -- Compilation_Unit, or, it can be any appropriate body declaration from any -- declarative context. -- -- These two function calls will always produce identical results: -- -- Decl2 := Corresponding_Declaration (Decl1); -- Decl2 := Corresponding_Declaration -- (Decl1, Enclosing_Context ( Enclosing_Compilation_Unit ( Decl1 ))); -- -- If a specification declaration is given, the same element is returned, -- unless it is a generic instantiation or an inherited subprogram -- declaration (see below). -- -- If a subprogram renaming declaration is given: -- -- a) in case of renaming-as-declaration, the same element is returned; -- -- b) in case of renaming-as-body, the subprogram declaration completed -- by this subprogram renaming declaration is returned. -- (Reference Manual, 8.5.4(1)) -- -- Returns a Nil_Element if no explicit specification exists, or the -- declaration is the proper body of a subunit. -- -- The parameter The_Context is used to locate the corresponding specification -- within a particular Context. The_Context need not be the Enclosing_Context -- of the Declaration. Any non-Nil result will always have The_Context -- as its Enclosing_Context. This implies that while a non-Nil result may be -- Is_Equal with the argument, it will only be Is_Identical if the -- Enclosing_Context of the Declaration is the same as the parameter -- The_Context. -- -- If a generic instantiation is given, the expanded generic specification -- template representing the instance is returned and Is_Part_Of_Instance. -- For example, an argument that is A_Package_Instantiation, results in a -- value that is A_Package_Declaration that can be analyzed with all -- appropriate queries. -- -- Retuns the declaration of the generic child unit corresponding to an -- implicit generic child unit specification. Reference Manual 10.1.1(19). -- -- The Enclosing_Element of the expanded specification is the generic -- instantiation. The Enclosing_Compilation_Unit of the expanded template -- is that of the instantiation. -- -- If an inherited subprogram declaration is given, the specification -- returned is the one for the user-defined subprogram from which the -- argument was ultimately inherited. -- -- Appropriate Declaration_Kinds returning a specification: -- A_Function_Body_Declaration -- A_Function_Renaming_Declaration (renaming-as-body) -- A_Function_Body_Stub -- A_Function_Instantiation -- A_Package_Body_Declaration -- A_Package_Body_Stub -- A_Package_Instantiation -- A_Procedure_Body_Declaration -- A_Procedure_Renaming_Declaration (renaming-as-body) -- A_Procedure_Body_Stub -- A_Procedure_Instantiation -- A_Task_Body_Declaration -- A_Task_Body_Stub -- A_Protected_Body_Declaration -- A_Protected_Body_Stub -- A_Formal_Package_Declaration -- A_Formal_Package_Declaration_With_Box -- A_Generic_Package_Renaming_Declaration -- A_Generic_Procedure_Renaming_Declaration -- A_Generic_Function_Renaming_Declaration -- An_Entry_Body_Declaration -- A_Package_Declaration (added by Gela for limited_view) -- -- Appropriate Declaration_Kinds returning the argument Declaration: -- A_Function_Declaration -- A_Function_Renaming_Declaration (renaming-as-declaration) -- A_Generic_Function_Declaration -- A_Generic_Package_Declaration -- A_Generic_Procedure_Declaration -- A_Package_Declaration -- A_Package_Renaming_Declaration -- A_Procedure_Declaration -- A_Procedure_Renaming_Declaration (renaming-as-declaration) -- A_Single_Task_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Single_Protected_Declaration -- A_Generic_Package_Renaming_Declaration -- A_Generic_Procedure_Renaming_Declaration -- A_Generic_Function_Renaming_Declaration -- An_Entry_Declaration -- -- Returns Declaration_Kinds: -- Not_A_Declaration -- A_Function_Declaration -- A_Function_Renaming_Declaration -- A_Generic_Function_Declaration -- A_Generic_Package_Declaration -- A_Generic_Procedure_Declaration -- A_Package_Declaration -- A_Package_Renaming_Declaration -- A_Procedure_Declaration -- A_Procedure_Renaming_Declaration -- A_Single_Task_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Single_Protected_Declaration -- An_Entry_Declaration -- ------------------------------------------------------------------------------- -- 15.27 function Corresponding_Body ------------------------------------------------------------------------------- function Corresponding_Body (Declaration : in Asis.Declaration) return Asis.Declaration; function Corresponding_Body (Declaration : in Asis.Declaration; The_Context : in Asis.Context) return Asis.Declaration; ------------------------------------------------------------------------------- -- Declaration - Specifies the specification to query -- The_Context - Specifies a Context to use -- -- Returns the corresponding body for a given subprogram, package, or task -- specification declaration. Returns the expanded generic body template for -- generic instantiations. The argument can be a Unit_Declaration from a -- Compilation_Unit, or, it can be any appropriate specification declaration -- from any declarative context. -- -- These two function calls will always produce identical results: -- -- Decl2 := Corresponding_Body (Decl1); -- Decl2 := Corresponding_Body -- (Decl1, Enclosing_Context ( Enclosing_Compilation_Unit( Decl1 ))); -- -- If a body declaration is given, the same element is returned. -- -- Returns a Nil_Element if no body exists in The_Context. -- -- The parameter The_Context is used to locate the corresponding specification -- within a particular Context. The_Context need not be the Enclosing_Context -- of the Declaration. Any non-Nil result will always have The_Context -- as its Enclosing_Context. This implies that while a non-Nil result may be -- Is_Equal with the argument, it will only be Is_Identical if the -- Enclosing_Context of the Declaration is the same as the parameter -- The_Context. -- -- Implicit predefined operations (e.g., "+", "=", etc.) will not typically -- have unit bodies. (Corresponding_Body returns a Nil_Element.) -- User-defined overloads of the predefined operations will have -- Corresponding_Body values once the bodies have inserted into the -- environment. The Corresponding_Body of an inherited subprogram is that -- of the original user-defined subprogram. -- -- If a generic instantiation is given, the body representing the expanded -- generic body template is returned. (i.e., an argument that is -- A_Package_Instantiation, results in a value that is -- A_Package_Body_Declaration that can be analyzed with all appropriate ASIS -- queries). -- -- Returns a Nil_Element if the body of the generic has not yet been compiled -- or inserted into the Ada Environment Context. -- -- The Enclosing_Element of the expanded body is the generic instantiation. -- The Enclosing_Compilation_Unit of the expanded template is that of the -- instantiation. -- -- Returns Nil_Element for an implicit generic child unit specification. -- Reference Manual 10.1.1(19). -- -- Returns A_Nil_Element for a null procedure or an abstract procedure. -- -- Returns A_Pragma if the Declaration is completed by pragma Import. -- -- Appropriate Declaration_Kinds returning a body: -- A_Function_Declaration -- A_Function_Instantiation -- A_Generic_Package_Declaration -- A_Generic_Procedure_Declaration -- A_Generic_Function_Declaration -- A_Package_Declaration -- A_Package_Instantiation -- A_Procedure_Declaration -- A_Procedure_Instantiation -- A_Single_Task_Declaration -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Single_Protected_Declaration -- A_Formal_Package_Declaration -- A_Formal_Package_Declaration_With_Box -- An_Entry_Declaration (restricted to protected entry) -- -- Appropriate Declaration_Kinds returning the argument Declaration: -- A_Function_Body_Declaration -- A_Function_Body_Stub -- A_Function_Renaming_Declaration -- A_Package_Body_Declaration -- A_Package_Body_Stub -- A_Package_Renaming_Declaration -- A_Procedure_Body_Declaration -- A_Procedure_Renaming_Declaration -- A_Procedure_Body_Stub -- A_Task_Body_Declaration -- A_Task_Body_Stub -- A_Protected_Body_Declaration -- A_Protected_Body_Stub -- A_Generic_Package_Renaming_Declaration -- A_Generic_Procedure_Renaming_Declaration -- A_Generic_Function_Renaming_Declaration -- An_Entry_Body_Declaration -- -- Returns Declaration_Kinds: -- Not_A_Declaration -- A_Function_Body_Declaration -- A_Function_Body_Stub -- A_Function_Renaming_Declaration -- A_Package_Body_Declaration -- A_Package_Body_Stub -- A_Procedure_Body_Declaration -- A_Procedure_Renaming_Declaration -- A_Procedure_Body_Stub -- A_Task_Body_Declaration -- A_Task_Body_Stub -- A_Protected_Body_Declaration -- A_Protected_Body_Stub -- An_Entry_Body_Declaration -- -- Returns Element_Kinds: -- Not_An_Element -- A_Declaration -- A_Pragma -- ------------------------------------------------------------------------------- -- 15.28 function Corresponding_Subprogram_Derivation ------------------------------------------------------------------------------- function Corresponding_Subprogram_Derivation (Declaration : in Asis.Declaration) return Asis.Declaration; ------------------------------------------------------------------------------- -- Declaration - Specifies an implicit inherited subprogram declaration -- -- Returns the subprogram declaration from which the given implicit inherited -- subprogram argument was inherited. The result can itself be an implicitly -- inherited subprogram. -- -- Appropriate Element_Kinds: -- A_Declaration -- -- Appropriate Declaration_Kinds: -- A_Function_Declaration -- A_Procedure_Declaration -- -- Returns Element_Kinds: -- A_Declaration -- -- Returns Declaration_Kinds: -- A_Function_Body_Declaration -- A_Function_Declaration -- A_Function_Renaming_Declaration -- A_Procedure_Body_Declaration -- A_Procedure_Declaration -- A_Procedure_Renaming_Declaration -- -- Raises ASIS_Inappropriate_Element for a subprogram declaration that is not -- Is_Part_Of_Inherited. -- ------------------------------------------------------------------------------- -- 15.29 function Corresponding_Type ------------------------------------------------------------------------------- function Corresponding_Type (Declaration : in Asis.Declaration) return Asis.Type_Definition; ------------------------------------------------------------------------------- -- Declaration - Specifies the subprogram_declaration to query -- -- Returns the type definition for which this entity is an implicit -- declaration. The result will often be a derived type. However, this query -- also works for declarations of predefined operators such as "+" and "=". -- Raises ASIS_Inappropriate_Element if the argument is not an implicit -- declaration resulting from the declaration of a type. -- -- Appropriate Element_Kinds: -- A_Declaration -- -- Appropriate Declaration_Kinds: -- A_Function_Declaration -- A_Procedure_Declaration -- -- Returns Definition_Kinds: -- A_Type_Definition -- A_Formal_Type_Definition -- ------------------------------------------------------------------------------- -- 15.30 function Corresponding_Equality_Operator ------------------------------------------------------------------------------- function Corresponding_Equality_Operator (Declaration : in Asis.Declaration) return Asis.Declaration; ------------------------------------------------------------------------------- -- Declaration - Specifies an equality or an inequality operator declaration -- -- If given an explicit Declaration of "=" whose result type is Boolean: -- -- - Returns the complimentary implicit "/=" operator declaration. -- -- - Returns a Nil_Element if the Ada implementation has not defined an -- implicit "/=" for the "=". Implementations of this sort will transform -- a A/=B expression into a NOT(A=B) expression. The function call -- representing the NOT operation is Is_Part_Of_Implicit in this case. -- -- If given an implicit Declaration of "/=" whose result type is Boolean: -- -- - Returns the complimentary explicit "=" operator declaration. -- -- Returns a Nil_Element for any other function declaration. -- -- Appropriate Declaration_Kinds: -- A_Function_Declaration -- -- Returns Declaration_Kinds: -- A_Function_Declaration -- -- |ER------------------------------------------------------------------------ -- |ER A_Package_Declaration - 7.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Visible_Part_Declarative_Items -- |CR function Private_Part_Declarative_Items -- ------------------------------------------------------------------------------- -- 15.31 function Visible_Part_Declarative_Items ------------------------------------------------------------------------------- function Visible_Part_Declarative_Items (Declaration : in Asis.Declaration; Include_Pragmas : in Boolean := False) return Asis.Declarative_Item_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the package to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of all basic declarations, representation specifications, -- use clauses, and pragmas in the visible part of a package, in their order -- of appearance. -- -- Results of this query may vary across ASIS implementations. Some -- implementations normalize all multi-name object declarations into an -- equivalent sequence of corresponding single name object declarations. -- See Reference Manual 3.3.1(7). -- -- Appropriate Declaration_Kinds: -- A_Generic_Package_Declaration -- A_Package_Declaration -- -- Returns Element_Kinds: -- A_Declaration -- A_Pragma -- A_Clause -- ------------------------------------------------------------------------------- -- 15.32 function Is_Private_Present ------------------------------------------------------------------------------- function Is_Private_Present (Declaration : in Asis.Declaration) return Boolean; ------------------------------------------------------------------------------- -- Declaration - Specifies the declaration to query -- -- Returns True if the argument is a package specification which has a -- reserved word "private" which marks the beginning of a (possibly empty) -- private part. -- -- Returns False for any package specification without a private part. -- Returns False for any unexpected Element. -- -- Expected Element_Kinds: -- A_Declaration -- -- Expected Declaration_Kinds: -- A_Generic_Package_Declaration -- A_Package_Declaration -- ------------------------------------------------------------------------------- -- 15.33 function Private_Part_Declarative_Items ------------------------------------------------------------------------------- function Private_Part_Declarative_Items (Declaration : in Asis.Declaration; Include_Pragmas : in Boolean := False) return Asis.Declarative_Item_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the package to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of all basic declarations, representation specifications, -- use clauses, and pragmas in the private part of a package in their order -- of appearance. -- -- Results of this query may vary across ASIS implementations. Some -- implementations normalize all multi-name object declarations into an -- equivalent sequence of corresponding single name object declarations. -- See Reference Manual 3.3.1(7). -- -- Appropriate Declaration_Kinds: -- A_Generic_Package_Declaration -- A_Package_Declaration -- -- Returns Element_Kinds: -- A_Declaration -- A_Pragma -- A_Clause -- -- |ER------------------------------------------------------------------------ -- |ER A_Package_Body_Declaration - 7.2 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Body_Declarative_Items -- |CR function Body_Statements -- |CR function Body_Exception_Handlers -- |CR function Body_Block_Statement - obsolescent, not recommended -- |ER------------------------------------------------------------------------ -- |ER A_Private_Type_Declaration - 7.3 -- |ER A_Private_Extension_Declaration - 7.3 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Discriminant_Part -- |CR function Type_Declaration_View -- |ER------------------------------------------------------------------------ -- |ER An_Object_Renaming_Declaration - 8.5.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Declaration_Subtype_Mark (obsolete) -- |CR function Renamed_Entity -- ------------------------------------------------------------------------------- -- 15.34 function Renamed_Entity ------------------------------------------------------------------------------- function Renamed_Entity (Declaration : in Asis.Declaration) return Asis.Expression; ------------------------------------------------------------------------------- -- Declaration - Specifies the rename declaration to query -- -- Returns the name expression that follows the reserved word "renames" in -- the renaming declaration. -- -- Appropriate Declaration_Kinds: -- An_Exception_Renaming_Declaration -- A_Function_Renaming_Declaration -- An_Object_Renaming_Declaration -- A_Package_Renaming_Declaration -- A_Procedure_Renaming_Declaration -- A_Generic_Package_Renaming_Declaration -- A_Generic_Procedure_Renaming_Declaration -- A_Generic_Function_Renaming_Declaration -- -- Returns Element_Kinds: -- An_Expression -- -- |ER------------------------------------------------------------------------ -- |ER An_Exception_Renaming_Declaration - 8.5.2 -- |ER A_Package_Renaming_Declaration - 8.5.3 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Renamed_Entity -- |ER------------------------------------------------------------------------ -- |ER A_Procedure_Renaming_Declaration - 8.5.4 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Parameter_Profile -- |CR function Renamed_Entity -- |ER------------------------------------------------------------------------ -- |ER A_Function_Renaming_Declaration - 8.5.4 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Parameter_Profile -- |CR function Result_Profile (obsolete) -- |CR function Renamed_Entity -- |ER------------------------------------------------------------------------ -- |ER A_Generic_Package_Renaming_Declaration - 8.5.5 -- |ER A_Generic_Procedure_Renaming_Declaration - 8.5.5 -- |ER A_Generic_Function_Renaming_Declaration - 8.5.5 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Renamed_Entity -- ------------------------------------------------------------------------------- -- 15.35 function Corresponding_Base_Entity ------------------------------------------------------------------------------- function Corresponding_Base_Entity (Declaration : in Asis.Declaration) return Asis.Expression; ------------------------------------------------------------------------------- -- Declaration - Specifies the rename declaration to query -- -- The base entity is defined to be the renamed entity that is not itself -- defined by another renaming declaration. -- -- If the name following the reserved word "renames" is itself declared -- by a previous renaming_declaration, then this query unwinds the renamings -- by recursively operating on the previous renaming_declaration. -- -- Otherwise, the name following the reserved word "renames" is returned. -- -- Appropriate Declaration_Kinds: -- An_Object_Renaming_Declaration -- An_Exception_Renaming_Declaration -- A_Procedure_Renaming_Declaration -- A_Function_Renaming_Declaration -- A_Package_Renaming_Declaration -- A_Generic_Package_Renaming_Declaration -- A_Generic_Procedure_Renaming_Declaration -- A_Generic_Function_Renaming_Declaration -- -- Returns Element_Kinds: -- An_Expression -- -- |ER------------------------------------------------------------------------ -- |ER A_Task_Type_Declaration - 9.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Discriminant_Part -- |CR function Type_Declaration_View -- |ER------------------------------------------------------------------------ -- |ER A_Single_Task_Declaration - 9.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Object_Declaration_View -- |ER------------------------------------------------------------------------ -- |ER A_Task_Body_Declaration - 9.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Body_Declarative_Items -- |CR function Body_Statements -- |CR function Body_Exception_Handlers -- |CR function Body_Block_Statement - obsolescent, not recommended -- |ER------------------------------------------------------------------------ -- |ER A_Protected_Type_Declaration - 9.4 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Discriminant_Part -- |CR function Type_Declaration_View -- |ER------------------------------------------------------------------------ -- |ER A_Single_Protected_Declaration - 9.4 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Object_Declaration_View -- |ER------------------------------------------------------------------------ -- |ER A_Protected_Body_Declaration - 9.4 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Protected_Operation_Items -- ------------------------------------------------------------------------------- -- 15.36 function Protected_Operation_Items ------------------------------------------------------------------------------- function Protected_Operation_Items (Declaration : in Asis.Declaration; Include_Pragmas : in Boolean := False) return Asis.Declaration_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the protected_body declaration to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of protected_operation_item and pragma elements of the -- protected_body, in order of appearance. -- -- Returns a Nil_Element_List if there are no items or pragmas. -- -- Appropriate Declaration_Kinds: -- A_Protected_Body_Declaration -- -- Returns Element_Kinds: -- A_Pragma -- A_Declaration -- A_Clause -- -- Returns Declaration_Kinds: -- A_Procedure_Declaration -- A_Function_Declaration -- A_Procedure_Body_Declaration -- A_Function_Body_Declaration -- An_Entry_Body_Declaration -- -- Returns Clause_Kinds: -- A_Representation_Clause -- -- |ER------------------------------------------------------------------------ -- |ER An_Entry_Declaration - 9.5.2 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Entry_Family_Definition -- |CR function Parameter_Profile -- ------------------------------------------------------------------------------- -- 15.37 function Entry_Family_Definition ------------------------------------------------------------------------------- function Entry_Family_Definition (Declaration : in Asis.Declaration) return Asis.Discrete_Subtype_Definition; ------------------------------------------------------------------------------- -- Declaration - Specifies the entry declaration to query -- -- Returns the Discrete_Subtype_Definition element for the entry family of -- an entry_declaration. -- -- Returns a Nil_Element if the entry_declaration does not define a family -- of entries. -- -- Appropriate Declaration_Kinds: -- An_Entry_Declaration -- -- Returns Definition_Kinds: -- Not_A_Definition -- A_Discrete_Subtype_Definition -- -- |ER------------------------------------------------------------------------ -- |ER An_Entry_Body_Declaration - 9.5.2 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Entry_Index_Specification -- |CR function Parameter_Profile -- |CR function Entry_Barrier -- |CR function Body_Declarative_Items -- |CR function Body_Statements -- |CR function Body_Exception_Handlers -- |CR function Body_Block_Statement - obsolescent, not recommended -- ------------------------------------------------------------------------------- -- 15.38 function Entry_Index_Specification ------------------------------------------------------------------------------- function Entry_Index_Specification (Declaration : in Asis.Declaration) return Asis.Declaration; ------------------------------------------------------------------------------- -- Declaration - Specifies the entry body declaration to query -- -- Returns the An_Entry_Index_Specification element of an entry body -- declaration. -- -- Returns a Nil_Element if the entry does not declare any -- An_Entry_Index_Specification element. -- -- Appropriate Declaration_Kinds: -- An_Entry_Body_Declaration -- -- Returns Declaration_Kinds: -- Not_A_Declaration -- An_Entry_Index_Specification -- ------------------------------------------------------------------------------- -- 15.39 function Entry_Barrier ------------------------------------------------------------------------------- function Entry_Barrier (Declaration : in Asis.Declaration) return Asis.Expression; ------------------------------------------------------------------------------- -- Declaration - Specifies the entry body declaration to query -- -- Returns the expression following the reserved word "when" in an entry -- body declaration. -- -- Appropriate Declaration_Kinds: -- An_Entry_Body_Declaration -- -- Returns Element_Kinds: -- An_Expression -- -- |ER------------------------------------------------------------------------ -- |ER A_Procedure_Body_Stub - 10.1.3 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Parameter_Profile -- |ER------------------------------------------------------------------------ -- |ER A_Function_Body_Stub - 10.1.3 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Parameter_Profile -- |CR function Result_Profile (obsolete) -- |ER------------------------------------------------------------------------ -- |ER A_Package_Body_Stub - 10.1.3 -- |ER A_Task_Body_Stub - 10.1.3 -- |ER A_Protected_Body_Stub - 10.1.3 -- |CR -- |CR Child elements returned by: -- |CR function Names -- ------------------------------------------------------------------------------- -- 15.40 function Corresponding_Subunit ------------------------------------------------------------------------------- function Corresponding_Subunit (Body_Stub : in Asis.Declaration) return Asis.Declaration; function Corresponding_Subunit (Body_Stub : in Asis.Declaration; The_Context : in Asis.Context) return Asis.Declaration; ------------------------------------------------------------------------------- -- Body_Stub - Specifies the stub to query -- The_Context - Specifies a Context to use to locate the subunit -- -- Returns the Unit_Declaration of the subunit compilation unit corresponding -- to the body stub. -- -- Returns a Nil_Element if the subunit does not exist in The_Context. -- -- These two function calls will always produce identical results: -- -- Decl2 := Corresponding_Subunit (Decl1); -- Decl2 := Corresponding_Subunit -- (Decl1, Enclosing_Context ( Enclosing_Compilation_Unit( Decl1 ))); -- -- The parameter The_Context is used to locate the corresponding subunit body. -- Any non-Nil result will always have The_Context as its Enclosing_Context. -- -- Appropriate Declaration_Kinds: -- A_Function_Body_Stub -- A_Package_Body_Stub -- A_Procedure_Body_Stub -- A_Task_Body_Stub -- A_Protected_Body_Stub -- -- Returns Declaration_Kinds: -- Not_A_Declaration -- A_Function_Body_Declaration -- A_Package_Body_Declaration -- A_Procedure_Body_Declaration -- A_Task_Body_Declaration -- A_Protected_Body_Declaration -- ------------------------------------------------------------------------------- -- 15.41 function Is_Subunit ------------------------------------------------------------------------------- function Is_Subunit (Declaration : in Asis.Declaration) return Boolean; ------------------------------------------------------------------------------- -- Declaration - Specifies the declaration to query -- -- Returns True if the declaration is the proper_body of a subunit. -- -- Returns False for any unexpected Element. -- -- Equivalent to: -- -- Declaration = Unit_Declaration(Enclosing_Compilation_Unit (Declaration)) -- and Unit_Kind(Enclosing_Compilation_Unit (Declaration)) in A_Subunit. -- -- Expected Declaration_Kinds: -- A_Procedure_Body_Declaration -- A_Function_Body_Declaration -- A_Package_Body_Declaration -- A_Task_Body_Declaration -- A_Protected_Body_Declaration -- ------------------------------------------------------------------------------- -- 15.42 function Corresponding_Body_Stub ------------------------------------------------------------------------------- function Corresponding_Body_Stub (Subunit : in Asis.Declaration) return Asis.Declaration; function Corresponding_Body_Stub (Subunit : in Asis.Declaration; The_Context : in Asis.Context) return Asis.Declaration; ------------------------------------------------------------------------------- -- Subunit - Specifies the Is_Subunit declaration to query -- The_Context - Specifies a Context to use to locate the parent unit -- -- Returns the body stub declaration located in the subunit's parent unit. -- -- Returns a Nil_Element if the parent unit does not exist in The_Context. -- -- These two function calls will always produce identical results: -- -- Decl2 := Corresponding_Body_Stub (Decl1); -- Decl2 := Corresponding_Body_Stub -- (Decl1, Enclosing_Context ( Enclosing_Compilation_Unit( Decl1 ))); -- -- The parameter The_Context is used to locate the corresponding parent body. -- Any non-Nil result will always have The_Context as its Enclosing_Context. -- -- Appropriate Declaration Kinds: -- (Is_Subunit(Declaration) shall also be True) -- A_Function_Body_Declaration -- A_Package_Body_Declaration -- A_Procedure_Body_Declaration -- A_Task_Body_Declaration -- A_Protected_Body_Declaration -- -- Returns Declaration_Kinds: -- Not_A_Declaration -- A_Function_Body_Stub -- A_Package_Body_Stub -- A_Procedure_Body_Stub -- A_Task_Body_Stub -- A_Protected_Body_Stub -- -- |ER------------------------------------------------------------------------ -- |ER An_Exception_Declaration - 11.1 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |ER------------------------------------------------------------------------ -- |ER A_Choice_Parameter_Specification - 11.2 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |ER------------------------------------------------------------------------ -- |ER A_Generic_Procedure_Declaration - 12.1 -- |CR -- |CR Child elements returned by: -- |CR function Generic_Formal_Part -- |CR function Names -- |CR function Parameter_Profile -- ------------------------------------------------------------------------------- -- 15.43 function Generic_Formal_Part ------------------------------------------------------------------------------- function Generic_Formal_Part (Declaration : in Asis.Declaration; Include_Pragmas : in Boolean := False) return Asis.Element_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the generic declaration to query -- Include_Pragmas - Specifies whether pragmas are to be returned -- -- Returns a list of generic formal parameter declarations, use clauses, -- and pragmas, in their order of appearance. -- -- Results of this query may vary across ASIS implementations. Some -- implementations normalize all multi-name object declarations into an -- equivalent sequence of corresponding single name object declarations. -- See Reference Manual 3.3.1(7). -- -- Appropriate Declaration_Kinds: -- A_Generic_Package_Declaration -- A_Generic_Procedure_Declaration -- A_Generic_Function_Declaration -- -- Returns Element_Kinds: -- A_Pragma -- A_Declaration -- A_Clause -- -- Returns Declaration_Kinds: -- A_Formal_Object_Declaration -- A_Formal_Type_Declaration -- A_Formal_Procedure_Declaration -- A_Formal_Function_Declaration -- A_Formal_Package_Declaration -- A_Formal_Package_Declaration_With_Box -- -- Returns Clause_Kinds: -- A_Use_Package_Clause -- A_Use_Type_Clause -- -- |ER------------------------------------------------------------------------ -- |ER A_Generic_Function_Declaration - 12.1 -- |CR -- |CR Child elements returned by: -- |CR function Generic_Formal_Part -- |CR function Names -- |CR function Parameter_Profile -- |CR function Result_Profile (obsolete) -- |ER------------------------------------------------------------------------ -- |ER A_Generic_Package_Declaration - 12.1 -- |CR -- |CR Child elements returned by: -- |CR function Generic_Formal_Part -- |CR function Names -- |CR function Visible_Part_Declarative_Items -- |CR function Private_Part_Declarative_Items -- |ER------------------------------------------------------------------------ -- |ER A_Package_Instantiation - 12.3 -- |ER A_Procedure_Instantiation - 12.3 -- |ER A_Function_Instantiation - 12.3 -- |CR -- |CR Child elements returned by: -- |CR function Names -- |CR function Generic_Unit_Name -- |CR function Generic_Actual_Part ------------------------------------------------------------------------------- -- -- Instantiations can always be analyzed in terms of the generic actual -- parameters supplied with the instantiation. A generic instance is a copy -- of the generic unit, and while there is no explicit (textual) specification -- in the program text, an implicit specification and body, if there is one, -- with the generic actual parameters is implied. -- -- To analyze the implicit instance specification or body of a generic -- instantiation: -- -- - Use Corresponding_Declaration to return the implicit expanded -- specification of an instantiation. -- -- - Use Corresponding_Body to return the implicit body of an instantiation. -- -- - Then analyze the specification or body with any appropriate queries. -- -- To analyze the explicit generic specification or body referenced by a -- generic instantiation: -- -- - Use Generic_Unit_Name to obtain the name of the generic unit. -- -- - Then use Corresponding_Name_Declaration to get to the generic -- declaration. -- -- - Then use Corresponding_Body to get to the body of the generic -- declaration. -- ------------------------------------------------------------------------------- -- 15.44 function Generic_Unit_Name ------------------------------------------------------------------------------- function Generic_Unit_Name (Declaration : in Asis.Declaration) return Asis.Expression; ------------------------------------------------------------------------------- -- Declaration - Specifies the generic instantiation to query -- -- Returns the name following the reserved word "new" in the generic -- instantiation. The name denotes the generic package, generic procedure, -- or generic function that is the template for this generic instance. -- -- Appropriate Declaration_Kinds: -- A_Function_Instantiation -- A_Package_Instantiation -- A_Procedure_Instantiation -- A_Formal_Package_Declaration -- A_Formal_Package_Declaration_With_Box -- -- Returns Expression_Kinds: -- An_Identifier -- An_Operator_Symbol -- A_Selected_Component -- ------------------------------------------------------------------------------- -- 15.45 function Generic_Actual_Part ------------------------------------------------------------------------------- function Generic_Actual_Part (Declaration : in Asis.Declaration; Normalized : in Boolean := False) return Asis.Association_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the generic_instantiation to query -- Normalized - Specifies whether the normalized form is desired -- -- Returns a list of the generic_association elements of the instantiation. -- -- Returns a Nil_Element_List if there are no generic_association elements. -- -- An unnormalized list contains only explicit associations ordered as they -- appear in the program text. Each unnormalized association has an optional -- generic_formal_parameter_selector_name and an -- explicit_generic_actual_parameter component. -- -- A normalized list contains artificial associations representing all -- explicit and default associations. It has a length equal to the number of -- generic_formal_parameter_declaration elements of the generic_formal_part -- of the template. The order of normalized associations matches the order -- of the generic_formal_parameter_declaration elements. -- -- Each normalized association represents a one-on-one mapping of a -- generic_formal_parameter_declaration to the explicit or default expression -- or name. A normalized association has: -- -- - one A_Defining_Name component that denotes the -- generic_formal_parameter_declaration, and -- -- - one An_Expression component that is either: -- the explicit_generic_actual_parameter, -- a default_expression, or -- a default_name from the generic_formal_parameter_declaration or -- an implicit naming expression which denotes the actual subprogram -- selected at the place of instantiation for a formal subprogram -- having A_Box_Default. -- -- Appropriate Declaration_Kinds: -- A_Function_Instantiation -- A_Package_Instantiation -- A_Procedure_Instantiation -- A_Formal_Package_Declaration -- -- Returns Association_Kinds: -- A_Generic_Association -- -- |IR Implementation Requirements: -- |IR -- |IR Normalized associations are Is_Normalized and Is_Part_Of_Implicit. -- |IR Normalized associations provided by default are -- |IR Is_Defaulted_Association. Normalized associations are never Is_Equal -- |IR to unnormalized associations. -- -- |IP Implementation Permissions: -- |IP -- |IP An implementation may choose to always include default parameters -- |IP in itsinternal representation. -- |IP -- |IP An implementation may also choose to normalize its representation -- |IP to use the defining_identifier element rather than the -- |IP generic_formal_parameter_selector_name elements. -- |IP -- |IP In either case, this query will return Is_Normalized associations even -- |IP ifNormalized is False, and the query Generic_Actual_Part_Normalized -- |IP will return True. -- -- |ER------------------------------------------------------------------------ -- |ER A_Formal_Object_Declaration - 12.4 -- |CR -- |CR Child elements returned by: -- |CR functions Names, Declaration_Subtype_Mark, Initialization_Expression -- |ER------------------------------------------------------------------------ -- |ER A_Formal_Type_Declaration - 12.5 -- |CR -- |CR Child elements returned by: -- |CR functions Names, Discriminant_Part, Type_Declaration_View -- |ER------------------------------------------------------------------------ -- |ER A_Formal_Procedure_Declaration - 12.6 -- |CR -- |CR Child elements returned by: -- |CR functions Names, function Parameter_Profile, -- |CR function Formal_Subprogram_Default -- ------------------------------------------------------------------------------- -- 15.46 function Formal_Subprogram_Default ------------------------------------------------------------------------------- function Formal_Subprogram_Default (Declaration : in Asis.Generic_Formal_Parameter) return Asis.Expression; ------------------------------------------------------------------------------- -- Declaration - Specifies the generic formal subprogram declaration to query -- -- Returns the name appearing after the reserved word "is" in the given -- generic formal subprogram declaration. -- -- Appropriate Declaration_Kinds: -- A_Formal_Function_Declaration -- A_Formal_Procedure_Declaration -- -- Appropriate Subprogram_Default_Kinds: -- A_Name_Default -- -- Returns Element_Kinds: -- An_Expression -- -- |ER------------------------------------------------------------------------ -- |ER A_Formal_Function_Declaration - 12.6 -- |CR -- |CR Child elements returned by: -- |CR functions Names, function Parameter_Profile, -- |CR Result_Profile (obsolete), and Formal_Subprogram_Default -- |ER------------------------------------------------------------------------ -- |ER A_Formal_Package_Declaration - 12.7 -- |CR -- |CR Child elements returned by: -- |CR functions Names, Generic_Unit_Name, and Generic_Actual_Part -- |ER------------------------------------------------------------------------ -- |ER A_Formal_Package_Declaration_With_Box - 12.7 -- |CR -- |CR Child elements returned by: -- |CR functions Names and Generic_Unit_Name -- ------------------------------------------------------------------------------- -- 15.47 function Corresponding_Generic_Element ------------------------------------------------------------------------------- function Corresponding_Generic_Element (Reference : in Asis.Element) return Asis.Defining_Name; ------------------------------------------------------------------------------- -- Reference - Specifies an expression that references an entity declared -- within the implicit specification of a generic instantiation, -- or, specifies the defining name of such an entity. -- -- Given a reference to some implicit entity, whose declaration occurs within -- an implicit generic instance, returns the corresponding entity name -- definition from the generic template used to create the generic instance. -- (Reference Manual 12.3 (16)) -- -- Returns the first A_Defining_Name, from the generic template, that -- corresponds to the entity referenced. -- -- Returns a Nil_Element if the argument does not refer to an entity declared -- as a component of a generic package instantiation. The entity name can -- refer to an ordinary declaration, an inherited subprogram declaration, or -- a predefined operator declaration. -- -- Appropriate Element_Kinds: -- A_Defining_Name -- An_Expression -- -- Appropriate Expression_Kinds: -- An_Identifier -- An_Operator_Symbol -- A_Character_Literal -- An_Enumeration_Literal -- -- Returns Element_Kinds: -- Not_An_Element -- A_Defining_Name -- ------------------------------------------------------------------------------- -- 15.48 function Is_Dispatching_Operation ------------------------------------------------------------------------------- function Is_Dispatching_Operation (Declaration : in Asis.Element) return Boolean; ------------------------------------------------------------------------------- -- Declaration - Specifies the declaration to query. -- -- Returns True if the declaration is a primitive subprogram of a tagged type. -- -- Returns False for any unexpected argument. -- -- Expected Element_Kinds: -- A_Procedure_Declaration -- A_Function_Declaration -- A_Procedure_Renaming_Declaration -- A_Function_Renaming_Declaration -- ------------------------------------------------------------------------------- -- 15.xx function Progenitor_List ------------------------------------------------------------------------------- function Progenitor_List (Declaration : Asis.Declaration) return Asis.Name_List; ------------------------------------------------------------------------------- -- Declaration - Specifies the declaration to query. -- -- Returns a list of subtype marks making up the interface_list in the -- argument declaration, in their order of appearance. If Declaration has no -- progenitors, an empty list is returned. -- -- Appropriate Declaration_Kinds: -- A_Private_Extension_Declaration -- A_Private_Type_Declaration -- (Gela: ??? Mistake ???) -- A_Task_Type_Declaration -- A_Protected_Type_Declaration -- A_Single_Task_Declaration -- A_Single_Protected_Declaration -- -- Returns Expression_Kinds: -- An_Identifier -- A_Selected_Component -- ------------------------------------------------------------------------------- -- 15.xx function Overriding_Indicator_Kind ------------------------------------------------------------------------------- function Overriding_Indicator_Kind -- 8.3.1 (2) (Declaration : Asis.Declaration) return Asis.Overriding_Indicator_Kinds; ------------------------------------------------------------------------------- -- Declaration specifies the subprogram declaration to query. -- -- Returns the kind of Overriding_Indicator for the subprogram declaration. -- -- Returns Not_An_Overriding_Indicator for any unexpected Element. -- -- Expected Declaration_Kinds: -- A_Procedure_Declaration -- A_Function_Declaration -- A_Procedure_Body_Declaration -- A_Function_Body_Declaration -- A_Null_Procedure_Declaration TODO!!! -- A_Procedure_Renaming_Declaration -- A_Function_Renaming_Declaration -- An_Entry_Declaration -- A_Procedure_Body_Stub -- A_Function_Body_Stub -- A_Procedure_Instantiation -- A_Function_Instantiation -- ------------------------------------------------------------------------------- end Asis.Declarations; ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
-- -*- Mode: Ada -*- -- Filename : maths.ads -- Description : Sample shared library using an Ada and a C function as an example. -- Author : Luke A. Guest -- Created On : Sun Oct 27 17:50:33 2013 package Maths is function Add (A, B : in Integer) return Integer with Export => True, Convention => Ada, External_Name => "Add"; function Sub (A, B : in Integer) return Integer with Import => True, Convention => C, External_Name => "sub"; end Maths;
with Basic_Test_Window; use Basic_Test_Window; with Giza.Context; use Giza.Context; with Giza.Events; use Giza.Events; with Giza.Widget.Button; use Giza.Widget; package Test_Graphic_Bounds is type Graphic_Bounds_Window is new Test_Window with private; type Graphic_Boounds_Window_Ref is access all Graphic_Bounds_Window; overriding procedure On_Init (This : in out Graphic_Bounds_Window); overriding procedure On_Displayed (This : in out Graphic_Bounds_Window); overriding procedure On_Hidden (This : in out Graphic_Bounds_Window); overriding procedure Draw (This : in out Graphic_Bounds_Window; Ctx : in out Giza.Context.Class; Force : Boolean := True); private type Graphic_Bounds_Window is new Test_Window with record Evt : aliased Timer_Event; Bound_Btn : Button.Ref; end record; end Test_Graphic_Bounds;
procedure Nullptr is type PInt is access Integer; procedure SetZero(pi : PInt) is begin if pi = null then return; end if; pi.all := 0; end SetZero; x : PInt := null; begin x := new Integer'(1); SetZero(x); end Nullptr;
------------------------------------- -- Course Work -- Ada -- Ann Pidchasiuk, IV-71 ------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Calendar; use Ada.Calendar; with ada.float_text_io; use ada.float_text_io; procedure Main is N: integer := 900; P: integer := 6; H: Integer := N / P; type vector is array(integer range <>) of integer; Subtype Vector_N is Vector(1..N); Subtype Vector_5H is Vector(1..5*H); Subtype Vector_4H is Vector(1..4*H); Subtype Vector_3H is Vector(1..3*H); Subtype Vector_2H is Vector(1..2*H); Subtype Vector_H is Vector(1..H); type Matrix is array(integer range <>) of Vector_N; Subtype Matrix_N is Matrix(1..N); Subtype Matrix_5H is Matrix(1..5*H); Subtype Matrix_4H is Matrix(1..4*H); Subtype Matrix_3H is Matrix(1..3*H); Subtype Matrix_2H is Matrix(1..2*H); Subtype Matrix_H is Matrix(1..H); Time_all: duration; time1,time2: time; --------------------Specification Task 1--------------------- task T1 is pragma Storage_Size(3000000000); entry Send_MOME_T2(MOh: in Matrix_H; MEh: in Matrix_H); entry Send_R_T2(Rh: in Vector_H); entry Send_MZ_T6(MZ4h: in Matrix_4H); entry Send_m_T2(m_res: in Integer); entry Send_A_T2(A3h: in Vector_3H); entry Send_A_T6(A2h: in Vector_2H); end T1; --------------------Specification Task 2--------------------- task T2 is pragma Storage_Size(3000000000); entry Send_BZ_T1(Bh:in Vector_H; Zh: in Vector_H); entry Send_MOME_T3(MO2h: in Matrix_2H; ME2h: in Matrix_2H); entry Send_R_T3(R2h: in Vector_2H); entry Send_MZ_T1(MZ3h: in Matrix_3H); entry Send_m1_T1(m1_send: in Integer); entry Send_m_T3(m_res: in Integer); entry Send_A_T3(A2h: in Vector_2H); end T2; --------------------Specification Task 3--------------------- task T3 is pragma Storage_Size(3000000000); entry Send_BZ_T4(Bh: in Vector_H; Zh: in Vector_H); entry Send_R_T4(R3h: in Vector_3H); entry Send_MZ_T2(MZ2h: in Matrix_2H); entry Send_m2_T2(m2_send: in Integer); entry Send_m4_T4(m4_send: in Integer); entry Send_A_T4(Ah: in Vector_H); end T3; --------------------Specification Task 4--------------------- task T4 is pragma Storage_Size(3000000000); entry Send_BZ_T5(B2h: in Vector_2H; Z2h: in Vector_2H); entry Send_MOME_T3(MO3h: in Matrix_3H; ME3h: in Matrix_3H); entry Send_R_T5(R4h: in Vector_4H); entry Send_MZ_T3(MZh: in Matrix_H); entry Send_m5_T5(m5_send: in Integer); entry Send_m_T3(m_res: in Integer); end T4; --------------------Specification Task 5--------------------- task T5 is pragma Storage_Size(3000000000); entry Send_BZ_T6(B3h: in Vector_3H; Z3h: in Vector_3H); entry Send_MOME_T4(MO2h: in Matrix_2H; ME2h: in Matrix_2H); entry Send_MZ_T6(MZh: in Matrix_H); entry Send_m6_T6(m6_send: in Integer); entry Send_m_T4(m_res: in Integer); end T5; --------------------Specification Task 6--------------------- task T6 is pragma Storage_Size(3000000000); entry Send_BZ_T1(B4h: in Vector_4H; Z4h: in Vector_4H); entry Send_MOME_T5(MOh: in Matrix_H; MEh: in Matrix_H); entry Send_R_T5(Rh: in Vector_H); entry Send_m_T5(m_res: in Integer); entry Send_A_T5(Ah: in Vector_H); end T6; ------------------------- Task 1-------------------------- task body T1 is Sum1, Sum2: Integer := 0; MO, ME: Matrix_H; Z, B: Vector_N; MZ: Matrix_4H; m, m1: Integer; R: Vector_H; A: Vector_N; MTx: Matrix_H; begin put_Line("T1 started!"); for i in 1 .. N loop B(i):=1; Z(i):=1; end loop; T2.Send_BZ_T1(B(H+1 .. 2*H), Z(H+1 .. 2*H)); T6.Send_BZ_T1(B(2*H+1 .. N), Z(2*H+1 .. N)); accept Send_MOME_T2 (MOh : in Matrix_H; MEh : in Matrix_H) do MO := MOh; ME := MEh; end Send_MOME_T2; accept Send_R_T2 (Rh : in Vector_H) do R := Rh; end Send_R_T2; accept Send_MZ_T6 (MZ4h : in Matrix_4H) do MZ := MZ4h; end Send_MZ_T6; T2.Send_MZ_T1(MZ(H+1 .. 4*H)); m1 :=100000; for I in 1 .. H loop if m1 < Z(I) then m1 := Z(I); end if; end loop; T2.Send_m1_T1(m1); accept Send_m_T2 (m_res : in Integer) do m := m_res; end Send_m_T2; for i in 1.. H loop for j in 1 .. N loop Sum1 := 0; for z in 1 .. N loop Sum1 := Sum1 + MO(J)(Z) * MZ(Z)(I); end loop; MTx(J)(I) := Sum1; end loop; end loop; for i in 1.. H loop Sum1 := 0; Sum2 := 0; for j in 1 .. N loop Sum1 := Sum1 + B(i) * MTx(I)(J); Sum2 := Sum2 + m * R(i) * ME(I)(J); end loop; A(I) := Sum1 + Sum2; end loop; accept Send_A_T2 (A3h : in Vector_3H) do A(H+1 .. 4*H) := A3h; end Send_A_T2; accept Send_A_T6 (A2h : in Vector_2H) do A(4*H+1 .. N) := A2h; end Send_A_T6; if N < 36 then for i in 1 .. N loop Put(A(i), 4); end loop; end if; time2:=clock; time_all:=time2-time1; put_line("TIME"); put (Float(Time_all), 4, 3, 0); put_Line("T1 end!"); end T1; ------------------------- Task 2-------------------------- task body T2 is Sum1, Sum2: Integer := 0; B, Z: Vector_H; R: Vector_2H; A: Vector_3H; MO, ME: Matrix_2H; MZ: Matrix_3H; m, m1, m2: Integer; MTx: Matrix_H; begin put_Line("T2 started!"); accept Send_BZ_T1 (Bh : in Vector_H; Zh : in Vector_H) do B := Bh; Z := Zh; end Send_BZ_T1; accept Send_MOME_T3 (MO2h : in Matrix_2H; ME2h : in Matrix_2H) do MO := MO2h; ME := ME2h; end Send_MOME_T3; T1.Send_MOME_T2(MO(H+1 .. 2*H), ME(H+1 .. 2*H)); accept Send_R_T3 (R2h : in Vector_2H) do R := R2h; end Send_R_T3; T1.Send_R_T2(R(H+1 .. 2*H)); accept Send_MZ_T1 (MZ3h : in Matrix_3H) do MZ := MZ3h; end Send_MZ_T1; T3.Send_MZ_T2(MZ(H+1 .. 3*H)); m2 :=100000; for I in 1 .. H loop if m2 < Z(I) then m2 := Z(I); end if; end loop; accept Send_m1_T1 (m1_send : in Integer) do m1 := m1_send; end Send_m1_T1; if m2 < m1 then m2 := m1; end if; T3.Send_m2_T2(m2); accept Send_m_T3 (m_res : in Integer) do m := m_res; end Send_m_T3; T1.Send_m_T2(m); for i in 1.. H loop for j in 1 .. N loop Sum1 := 0; for z in 1 .. N loop Sum1 := Sum1 + MO(J)(Z) * MZ(Z)(I); end loop; MTx(J)(I) := Sum1; end loop; end loop; for i in 1.. H loop Sum1 := 0; Sum2 := 0; for j in 1 .. N loop Sum1 := Sum1 + B(i) * MTx(I)(J); Sum2 := Sum2 + m * R(i) * ME(I)(J); end loop; A(I) := Sum1 + Sum2; end loop; accept Send_A_T3 (A2h : in Vector_2H) do A(H+1 .. 3*H) := A2h; end Send_A_T3; T1.Send_A_T2(A); Put_Line("T2 ended"); end T2; ------------------------- Task 3-------------------------- task body T3 is Sum1, Sum2: Integer := 0; MO, ME: Matrix_N; B, Z: Vector_H; R: Vector_3H; MZ: Matrix_2H; m, m2, m3, m4: Integer; A: Vector_2H; MTx: Matrix_H; begin put_Line("T3 started!"); for i in 1 .. N loop for j in 1 .. N loop MO(i)(j) := 1; ME(i)(j) := 1; end loop; end loop; accept Send_BZ_T4 (Bh : in Vector_H; Zh : in Vector_H) do B := Bh; Z := Zh; end Send_BZ_T4; T2.Send_MOME_T3(MO(H+1 .. 3*H), ME(H+1 .. 3*H)); T4.Send_MOME_T3(MO(3*H+1 .. N), ME(3*H+1 .. N)); accept Send_R_T4 (R3h : in Vector_3H) do R := R3h; end Send_R_T4; T2.Send_R_T3(R(H+1 .. 3*H)); accept Send_MZ_T2 (MZ2h : in Matrix_2H) do MZ := MZ2h; end Send_MZ_T2; T4.Send_MZ_T3(MZ(H+1 .. 2*H)); m3 :=100000; for I in 1 .. H loop if m3 < Z(I) then m3 := Z(I); end if; end loop; accept Send_m2_T2 (m2_send : in Integer) do m2 := m2_send; end Send_m2_T2; if m3 < m2 then m3 := m2; end if; accept Send_m4_T4 (m4_send : in Integer) do m4 := m4_send; end Send_m4_T4; if m3 < m4 then m3 := m4; end if; m := m3; T2.Send_m_T3(m); T4.Send_m_T3(m); for i in 1.. H loop for j in 1 .. N loop Sum1 := 0; for z in 1 .. N loop Sum1 := Sum1 + MO(J)(Z) * MZ(Z)(I); end loop; MTx(J)(I) := Sum1; end loop; end loop; for i in 1.. H loop Sum1 := 0; Sum2 := 0; for j in 1 .. N loop Sum1 := Sum1 + B(i) * MTx(I)(J); Sum2 := Sum2 + m * R(i) * ME(I)(J); end loop; A(I) := Sum1 + Sum2; end loop; accept Send_A_T4 (Ah : in Vector_H) do A(H+1 .. 2*H) := Ah; end Send_A_T4; T2.Send_A_T3(A); Put_Line("T3 ended"); end T3; ------------------------- Task 4-------------------------- task body T4 is Sum1, Sum2: Integer := 0; B, Z: Vector_2H; A: Vector_H; R: Vector_4H; MO, ME: Matrix_3H; MZ: Matrix_H; m, m5, m4: Integer; MTx: Matrix_H; begin put_Line("T4 started!"); accept Send_BZ_T5 (B2h : in Vector_2H; Z2h : in Vector_2H) do B := B2h; Z := Z2h; end Send_BZ_T5; T3.Send_BZ_T4(B(H+1 .. 2*H), Z(H+1 .. 2*H)); accept Send_MOME_T3 (MO3h : in Matrix_3H; ME3h : in Matrix_3H) do MO := MO3h; ME := ME3h; end Send_MOME_T3; T5.Send_MOME_T4(MO(H+1 .. 3*H), ME(H+1 .. 3*H)); accept Send_R_T5 (R4h : in Vector_4H) do R := R4h; end Send_R_T5; T3.Send_R_T4(R(H+1 .. 4*H)); accept Send_MZ_T3 (MZh : in Matrix_H) do MZ := MZh; end Send_MZ_T3; -- dont go m4 :=100000; for I in 1 .. H loop if m4 < Z(I) then m4 := Z(I); end if; end loop; accept Send_m5_T5 (m5_send : in Integer) do m5 := m5_send; end Send_m5_T5; if m4 < m5 then m4 := m5; end if; T3.Send_m4_T4(m4); accept Send_m_T3 (m_res : in Integer) do m := m_res; end Send_m_T3; T5.Send_m_T4(m); for i in 1.. H loop for j in 1 .. N loop Sum1 := 0; for z in 1 .. N loop Sum1 := Sum1 + MO(J)(Z) * MZ(Z)(I); end loop; MTx(J)(I) := Sum1; end loop; end loop; for i in 1.. H loop Sum1 := 0; Sum2 := 0; for j in 1 .. N loop Sum1 := Sum1 + B(i) * MTx(I)(J); Sum2 := Sum2 + m * R(i) * ME(I)(J); end loop; A(I) := Sum1 + Sum2; end loop; T3.Send_A_T4(A); Put_Line("T4 ended"); end T4; ------------------------- Task 5-------------------------- task body T5 is Sum1, Sum2: Integer := 0; R: Vector_N; B, Z: Vector_3H; MO, ME: Matrix_2H; MZ: Matrix_H; m, m5, m6: Integer; A: Vector_H; MTx: Matrix_H; begin put_Line("T5 started!"); for i in 1 .. N loop R(i):=1; end loop; accept Send_BZ_T6 (B3h : in Vector_3H; Z3h : in Vector_3H) do B := B3h; Z := Z3h; end Send_BZ_T6; T4.Send_BZ_T5(B(H+1 .. 3*H), Z(H+1 .. 3*H)); accept Send_MOME_T4 (MO2h : in Matrix_2H; ME2h : in Matrix_2H) do MO := MO2h; ME := ME2h; end Send_MOME_T4; T6.Send_MOME_T5(MO(H+1 .. 2*H), ME(H+1 .. 2*H)); T6.Send_R_T5(R(H+1 .. 2*H)); T4.Send_R_T5(R(2*H+1 .. N)); accept Send_MZ_T6 (MZh : in Matrix_H) do MZ := MZh; end Send_MZ_T6; m5 :=100000; for I in 1 .. H loop if m5 < Z(I) then m5 := Z(I); end if; end loop; accept Send_m6_T6 (m6_send : in Integer) do m6 := m6_send; end Send_m6_T6; if m5 < m6 then m5 := m6; end if; T4.Send_m5_T5(m5); accept Send_m_T4 (m_res : in Integer) do m := m_res; end Send_m_T4; T6.Send_m_T5(m); for i in 1.. H loop for j in 1 .. N loop Sum1 := 0; for z in 1 .. N loop Sum1 := Sum1 + MO(J)(Z) * MZ(Z)(I); end loop; MTx(J)(I) := Sum1; end loop; end loop; for i in 1.. H loop Sum1 := 0; Sum2 := 0; for j in 1 .. N loop Sum1 := Sum1 + B(i) * MTx(I)(J); Sum2 := Sum2 + m * R(i) * ME(I)(J); end loop; A(I) := Sum1 + Sum2; end loop; T6.Send_A_T5(A); Put_Line("T5 ended"); end T5; ------------------------- Task 6-------------------------- task body T6 is Sum1, Sum2: Integer := 0; MZ: Matrix_N; A: Vector_2H; B, Z: Vector_4H; MO, ME: Matrix_H; R: Vector_H; m6, m: Integer; MTx: Matrix_H; begin put_Line("T6 started!"); for i in 1 .. N loop for j in 1..N loop MZ(i)(j):=1; end loop; end loop; accept Send_BZ_T1 (B4h : in Vector_4H; Z4h : in Vector_4H) do B := B4h; Z := Z4h; end Send_BZ_T1; T5.Send_BZ_T6(B(H+1 .. 4*H), Z(H+1 .. 4*H)); accept Send_MOME_T5 (MOh : in Matrix_H; MEh : in Matrix_H) do MO := MOh; ME := MEh; end Send_MOME_T5; accept Send_R_T5 (Rh : in Vector_H) do R := Rh; end Send_R_T5; T5.Send_MZ_T6(MZ(H+1 .. 2*H)); T1.Send_MZ_T6(MZ(2*H+1 .. N)); --dont go m6 :=100000; for I in 1 .. H loop if m6 < Z(I) then m6 := Z(I); end if; end loop; T5.Send_m6_T6(m6); accept Send_m_T5 (m_res : in Integer) do m := m_res; end Send_m_T5; for i in 1.. H loop for j in 1 .. N loop Sum1 := 0; for z in 1 .. N loop Sum1 := Sum1 + MO(J)(Z) * MZ(Z)(I); end loop; MTx(J)(I) := Sum1; end loop; end loop; for i in 1.. H loop Sum1 := 0; Sum2 := 0; for j in 1 .. N loop Sum1 := Sum1 + B(i) * MTx(I)(J); Sum2 := Sum2 + m * R(i) * ME(I)(J); end loop; A(I) := Sum1 + Sum2; end loop; accept Send_A_T5 (Ah : in Vector_H) do A(H+1 .. 2*H) := Ah; end Send_A_T5; T1.Send_A_T6(A); Put_Line("T6 ended"); end T6; begin time1:=clock; null; end main;
-- Derived from ga_ref_impl Multivector.java with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO; with Maths; -- with GA_Utilities; with SVD; package body Multivectors is type Basis_Blade_Array is array (integer range <>) of Blade.Basis_Blade; epsilon : constant Float := 10.0 ** (-6); Spatial_Dimension : Natural := 0; MV_Basis_Vector_Names : Blade_Types.Basis_Vector_Names; -- This array can be used to lookup the number of coordinates for -- the grade part of a general multivector procedure Compress (MV : in out Multivector); function Cosine_Series (MV : Multivector; Order : Integer) return Multivector; function Exp_Series (MV : Multivector; Met : Metric_Record; Order : Integer) return Multivector; function Random_Vector (Dim : Integer; Scale : Float) return Multivector; function Scalar_Product_Local (MV1, MV2 : Multivector) return float; function Sine_Series (MV : Multivector; Order : Integer) return Multivector; function To_Geometric_Matrix (MV : Multivector; BBs_L : Basis_Blade_Array; Met : Metric_Record) return GA_Maths.Float_Matrix; -- ------------------------------------------------------------------------- function "+" (MV : Multivector; S : Float) return Multivector is MV1 : Multivector := MV; begin MV1.Blades.Append (Blade.New_Scalar_Blade (S)); Simplify (MV1); return MV1; end "+"; -- ------------------------------------------------------------------------ function "+" (S : Float; MV : Multivector) return Multivector is begin return MV + S; end "+"; -- ------------------------------------------------------------------------ function "+" (MV1, MV2 : Multivector) return Multivector is use Blade; use Blade_List_Package; Blades_1 : constant Blade_List := MV1.Blades; Blades_2 : constant Blade_List := MV2.Blades; Blades_3 : Blade_List; Curs : Cursor := Blades_1.First; MV3 : Multivector := MV1; begin -- result.addAll(blades); while Has_Element (Curs) loop Blades_3.Append (Element (Curs)); Next (Curs); end loop; Curs := Blades_2.First; -- result.addAll(x.blades); while Has_Element (Curs) loop Blades_3.Append (Element (Curs)); Next (Curs); end loop; MV3.Blades := Blades_3; -- Simplify does the adding Simplify (MV3); return MV3; exception when others => Put_Line ("An exception occurred in Multivectors +."); raise; end "+"; -- ------------------------------------------------------------------------- function "-" (MV : Multivector; S : Float) return Multivector is MV1 : Multivector := MV; begin MV1.Blades.Append (Blade.New_Scalar_Blade (-S)); Simplify (MV1); return MV1; end "-"; -- ------------------------------------------------------------------------ function "-" (S : Float; MV : Multivector) return Multivector is begin return MV - S; end "-"; -- ------------------------------------------------------------------------ -- Return negative value of a multivector function "-" (MV : Multivector) return Multivector is use Blade; use Blade_List_Package; Neg_MV : Multivector := MV; Neg_Blades : Blade_List := Neg_MV.Blades; Neg_Curs : Cursor := Neg_Blades.First; Blade_Neg : Blade.Basis_Blade; begin while Has_Element (Neg_Curs) loop Blade_Neg := Element (Neg_Curs); Blade_Neg := New_Blade (Bitmap (Blade_Neg), - Weight (Blade_Neg)) ; Neg_Blades.Replace_Element (Neg_Curs, Blade_Neg); Next (Neg_Curs); end loop; Neg_MV.Blades := Neg_Blades; return Neg_MV; exception when others => Put_Line ("An exception occurred in Multivector - 1"); raise; end "-"; -- ------------------------------------------------------------------------- function "-" (MV1, MV2 : Multivector) return Multivector is Neg_MV2 : constant Multivector := -MV2; begin return MV1 + Neg_MV2; exception when others => Put_Line ("An exception occurred in Multivector - 2"); raise; end "-"; -- ------------------------------------------------------------------------- function "*" (Scale : float; MV : Multivector) return Multivector is use Blade; use Blade_List_Package; Blades : constant Blade_List := Get_Blade_List (MV); Curs : Cursor := Blades.First; aBlade : Basis_Blade; New_MV : Multivector := MV; N_Blades : Blade_List := Get_Blade_List (New_MV); N_Curs : Cursor := N_Blades.First; begin while Has_Element (Curs) loop aBlade := Element (Curs); Blade.Update_Blade (aBlade, Scale * Weight (aBlade)); N_Blades.Replace_Element (N_Curs, aBlade); Next (Curs); Next (N_Curs); end loop; New_MV.Blades := N_Blades; return New_MV; end "*"; -- ------------------------------------------------------------------------ function "*" (MV : Multivector; Scale : float) return Multivector is begin return Scale * MV; end "*"; -- ------------------------------------------------------------------------ function "/" (MV : Multivector; Scale : float) return Multivector is use Blade; use Blade_List_Package; Blades : constant Blade_List := Get_Blade_List (MV); Curs : Cursor := Blades.First; aBlade : Basis_Blade; New_MV : Multivector := MV; N_Blades : Blade_List := Get_Blade_List (New_MV); N_Curs : Cursor := N_Blades.First; begin while Has_Element (Curs) loop aBlade := Element (Curs); Blade.Update_Blade (aBlade, Weight (aBlade) / Scale); N_Blades.Replace_Element (N_Curs, aBlade); Next (Curs); Next (N_Curs); end loop; New_MV.Blades := N_Blades; return New_MV; end "/"; -- ------------------------------------------------------------------------ procedure Add_Blade (MV : in out Multivector; aBlade : Blade.Basis_Blade) is begin MV.Blades.Append (aBlade); end Add_Blade; -- ------------------------------------------------------------------------- procedure Add_Blade (MV : in out Multivector; Index : E2_Base; Value : Float) is begin MV.Blades.Append (Blade.New_Basis_Blade (Index, Value)); exception when others => Put_Line ("An exception occurred in Multivector.Add_Blade 1"); raise; end Add_Blade; -- ------------------------------------------------------------------------- procedure Add_Blade (MV : in out Multivector; Index : E3_Base; Value : Float) is begin MV.Blades.Append (Blade.New_Basis_Blade (Index, Value)); exception when others => Put_Line ("An exception occurred in Multivector.Add_Blade 2"); raise; end Add_Blade; -- ------------------------------------------------------------------------- procedure Add_Blade (MV : in out Multivector; Index : C3_Base; Value : Float) is begin MV.Blades.Append (Blade.New_Basis_Blade (Index, Value)); exception when others => Put_Line ("An exception occurred in Multivector.Add_Blade 2"); raise; end Add_Blade; -- ------------------------------------------------------------------------- -- procedure Add_Complex_Blade (MV : in out Multivector; Index : C3_Base; -- Value : GA_Maths.Complex_Types.Complex) is -- begin -- MV.Blades.Append (Blade.New_Complex_Basis_Blade (Index, Value)); -- -- exception -- when others => -- Put_Line ("An exception occurred in Multivector.Add_Blade 2"); -- raise; -- end Add_Complex_Blade; -- ------------------------------------------------------------------------- procedure Add_To_Matrix (M : in out GA_Maths.Float_Matrix; Beta, Gamma : Blade.Basis_Blade) is use Blade; -- Matrix indices are 1 greater than bitmap values Row : constant Integer := Integer (Bitmap (Gamma)) + 1; Col : constant Integer := Integer (Bitmap (Beta)) + 1; begin M (Row, Col) := M (Row, Col) + Weight (Gamma); exception when others => Put_Line ("An exception occurred in Multivector.Add_To_Matrix 1."); raise; end Add_To_Matrix; -- ------------------------------------------------------------------------- procedure Add_To_Matrix (M : in out GA_Maths.Float_Matrix; Beta : Blade.Basis_Blade; Gamma : Blade.Blade_List) is use Blade; use Blade_List_Package; Curs : Cursor := Gamma.First; begin while Has_Element (Curs) loop Add_To_Matrix (M, Beta, Element (Curs)); Next (Curs); end loop; exception when others => Put_Line ("An exception occurred in Multivector.Add_To_Matrix 2."); raise; end Add_To_Matrix; -- ------------------------------------------------------------------------- procedure Add_Multivector (MV_List : in out Multivector_List; MV : Multivector)is begin MV_List.Append (MV); end Add_Multivector; -- ------------------------------------------------------------------------- function Basis_Vector (Index : BV_Base) return M_Vector is MV : M_Vector; begin MV.Blades.Append (Blade.New_Basis_Blade (Index)); return MV; end Basis_Vector; -- ------------------------------------------------------------------------- function Basis_Vector (Index : E2_Base) return M_Vector is MV : M_Vector; begin MV.Blades.Append (Blade.New_Basis_Blade (Index)); return MV; end Basis_Vector; -- ------------------------------------------------------------------------- function Basis_Vector (Index : E3_Base) return M_Vector is MV : M_Vector; begin MV.Blades.Append (Blade.New_Basis_Blade (Index)); return MV; exception when others => Put_Line ("An exception occurred in Multivector.Basis_Vector."); raise; end Basis_Vector; -- ------------------------------------------------------------------------- function Basis_Vector (Index : C3_Base) return M_Vector is MV : M_Vector; begin MV.Blades.Append (Blade.New_Basis_Blade (Index)); return MV; end Basis_Vector; -- ------------------------------------------------------------------------- function Blades (MV : Multivector) return Blade.Blade_List is begin return MV.Blades; end Blades; -- ------------------------------------------------------------------------- function Component (MV : Multivector; BM : Interfaces.Unsigned_32) return Float is use Interfaces; use Blade; use Blade_List_Package; Blades : constant Blade_List := Get_Blade_List (MV); Curs : Cursor := Blades.First; Found : Boolean := False; Value : Float := 0.0; begin while Has_Element (Curs) and not Found loop Found := Blade.Bitmap (Element (Curs)) = BM; if Found then Value := Blade.Weight (Element (Curs)); else Next (Curs); end if; end loop; return Value; end Component; -- ------------------------------------------------------------------------- procedure Compress (MV : in out Multivector; Epsilon : Float) is use Blade; use Blade_List_Package; use GA_Maths; Blades : Blade_List := MV.Blades; thisBlade : Blade.Basis_Blade; Curs : Cursor := Blades.First; Max_Mag : Float := 0.0; begin Simplify (MV); while Has_Element (Curs) loop thisBlade := Element (Curs); Max_Mag := Maximum (Weight (thisBlade), Max_Mag); Next (Curs); end loop; if Max_Mag = 0.0 then MV.Blades.Clear; else -- remove basis blades with too low scale while Has_Element (Curs) loop thisBlade := Element (Curs); if Abs (Weight (thisBlade)) < Epsilon then Blades.Delete (Curs); end if ; Next (Curs); end loop; MV.Blades := Blades; end if; end Compress; -- ------------------------------------------------------------------------- procedure Compress (MV : in out Multivector) is begin Compress (MV, epsilon); -- Compress (MV, 10.0 ** (-13)); end Compress; -- ------------------------------------------------------------------------- function Cosine (MV : Multivector) return Multivector is begin return Cosine (MV, 12); end Cosine; -- ------------------------------------------------------------------------- function Cosine (MV : Multivector; Order : Integer) return Multivector is use GA_Maths.Float_Functions; A2 : Multivector := Geometric_Product (MV, MV); A2_Scalar : Float; Alpha : Float; Result : Multivector; begin Compress (A2); if Is_Null (A2, epsilon) then Result := New_Multivector (1.0); elsif Is_Scalar (A2) then A2_Scalar := Scalar_Part (A2); if A2_Scalar < 0.0 then Alpha := Sqrt (-A2_Scalar); Result := New_Multivector (Cosh (Alpha)); else Alpha := Sqrt (A2_Scalar); Result := New_Multivector (Cos (Alpha)); end if; else -- Not null and not scalar Result := Cosine_Series (MV, Order); end if; return Result; end Cosine; -- ------------------------------------------------------------------------- function Cosine_Series (MV : Multivector; Order : Integer) return Multivector is use Interfaces; Scaled : constant Multivector := MV; Scaled_GP : Multivector; Temp : Multivector := Scaled; Sign : Integer := -1; Result : Multivector := New_Multivector (1.0); begin -- Taylor approximation for Count in 2 .. Order loop Scaled_GP := Geometric_Product (Scaled, 1.0 / Float (Count)); Temp := Geometric_Product (Temp, Scaled_GP); if (Unsigned_32 (Count) and 1) = 0 then Result := Result + Geometric_Product (Temp, Float (Sign)); Sign := -Sign; end if; end loop; return Result; end Cosine_Series; -- ------------------------------------------------------------------------- function Dot (MV1, MV2 : Multivector) return Multivector is begin return Inner_Product (MV1, MV2, Blade.Hestenes_Inner_Product); end Dot; -- ------------------------------------------------------------------------- function Dual (MV : Multivector; Met : Metric_Record := C3_Metric) return Multivector is use Interfaces; Index : constant Unsigned_32 := Shift_Left (1, Eigen_Values (Met)'Length) - 1; MV_I : Multivector; begin -- case MV.Type_Of_MV is -- when MV_Line => MV_I.Type_Of_MV := MV_Dual_Line; -- when MV_Sphere => MV_I.Type_Of_MV := MV_Dual_Sphere; -- when others => raise MV_Exception with -- "Multivectors.DualMet called with invalid Type_Of_MV: " & -- MV_Type'Image (MV.Type_Of_MV); -- end case; MV_I.Blades.Append (Blade.New_Basis_Blade (Index)); MV_I := Versor_Inverse (MV_I); return Inner_Product (MV, MV_I, Met); end Dual; -- ------------------------------------------------------------------------- function Dual (MV : Multivector; Dim : Integer) return Multivector is use Interfaces; Index : constant Unsigned_32 := Shift_Left (1, Dim) - 1; MV_I : Multivector; begin MV_I.Blades.Append (Blade.New_Basis_Blade (Index)); MV_I := Versor_Inverse (MV_I); return Inner_Product (MV, MV_I, Blade.Left_Contraction); end Dual; -- ------------------------------------------------------------------------- function Exp (MV : Multivector; Met : Metric_Record := C3_Metric; Order : Integer := 12) return Multivector is use GA_Maths.Float_Functions; X2 : constant Multivector := Geometric_Product (MV, MV, Met); S_X2 : constant Float := Scalar_Part (X2); A : Float; Result : Multivector; begin if Norm_Esq (X2) - S_X2 * S_X2 < epsilon then -- x * x is scalar if S_X2 < 0.0 then A := Sqrt (-S_X2); Result := New_Multivector (Cos (A)) + Sin (A) / A * MV; elsif S_X2 > 0.0 then A := Sqrt (S_X2); Result := New_Multivector (Cosh (A)) + Sinh (A) / A * MV; else Result := 1.0 + MV; end if; else Result := Exp_Series (MV, Met, Order); end if; return Result; end Exp; -- ------------------------------------------------------------------------- -- function Exp_Dual_Line (DL : Dual_Line; Met : Metric.Metric_Record) -- return Dual_Line is -- -- use Blade; -- use Blade_List_Package; -- Blades : constant Blade_List := DL.Blades; -- Curs : Cursor := Blades.First; -- MV : Multivector; -- begin -- while Has_Element (Curs) loop -- Add_Blade (MV, Element (Curs)); -- Next (Curs); -- end loop; -- MV := Exp (MV, Met); -- return To_Dual_Line (MV); -- end Exp_Dual_Line; -- ------------------------------------------------------------------------- -- Possibly imprecise function Exp_Series (MV : Multivector; Met : Metric.Metric_Record; Order : Integer) return Multivector is Scaled : Multivector; Scaled_GP : Multivector; Temp : Multivector := New_Multivector (1.0); Scale : Integer := 1; Max : Float := Norm_E (MV); Result : Multivector := Temp; begin if Max > 1.0 then Scale := 2; end if; while Max > 1.0 loop Max := Max / 2.0; Scale := 2 * Scale; end loop; Scaled := Geometric_Product (MV, 1.0 / Float (Scale)); -- Taylor approximation for Count in 1 .. Order loop Scaled_GP := Geometric_Product (Scaled, 1.0 / Float (Count)); Temp := Geometric_Product (Temp, Scaled_GP); Result := Result + Temp; end loop; -- Undo scaling while Scale > 1 loop Result := Geometric_Product (Result, Result, Met); Scale := Scale / 2; end loop; return Result; end Exp_Series; -- ------------------------------------------------------------------------- function Extract_Grade (MV : Multivector; Index : integer) return Multivector is use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; thisBlade : Blade.Basis_Blade; Curs : Cursor := Blades.First; Max_Grade : Integer := 0; Gr : array (1 .. Index) of Integer; New_List : Blade_List; aGrade : Integer; MV_E : Multivector; begin for k in Gr'Range loop Gr (k) := k; if Gr (k) > Max_Grade then Max_Grade := Gr (k); end if; end loop; declare Keep : constant array (0 .. Max_Grade + 1) of Boolean := (others => True); begin while Has_Element (Curs) loop thisBlade := Element (Curs); aGrade := Blade.Grade (thisBlade); if aGrade <= Max_Grade and then Keep (aGrade) then New_List.Append (thisBlade); end if; Next (Curs); end loop; end; MV_E.Blades := New_List; Simplify (MV_E); return MV_E; end Extract_Grade; -- ------------------------------------------------------------------------- function From_Vector (V : M_Vector) return Multivector is use Blade; use Blade_List_Package; Blades : constant Blade_List := V.Blades; Curs : Cursor := Blades.First; MV : Multivector; begin while Has_Element (Curs) loop Add_Blade (MV, Element (Curs)); Next (Curs); end loop; return MV; end From_Vector; -- ------------------------------------------------------------------------- -- Implements metric == null case of Multivector.java generalInverse -- function General_Inverse (MV : Multivector) return Multivector is -- use Interfaces; -- use GA_Maths.Float_Array_Package; -- use Blade; -- use Blade_List_Package; -- use GA_Maths; -- -- Dim : constant Natural := Space_Dimension (MV); -- Max_Index : constant Natural := 2 ** Spatial_Dimension; -- Mat : Float_Matrix (1 .. Max_Index, 1 .. Max_Index) := -- (others => (others => 0.0)); -- Mat_Inv : Float_Matrix (1 .. Max_Index, 1 .. Max_Index) := -- (others => (others => 0.0)); -- BBs_L : Basis_Blade_Array (1 .. Max_Index); -- Curs : Cursor := MV.Blades.First; -- Cond : Float; -- aBlade : Basis_Blade; -- GP : Basis_Blade; -- Value : Float; -- Blades : Blade_List; -- Result : Multivector; -- begin -- if Is_Scalar (MV) or Is_Null (MV) then -- Result := MV; -- else -- for index in BBs_L'Range loop -- BBs_L (index) := New_Basis_Blade (Interfaces.Unsigned_32 (index - 1)); -- end loop; -- -- -- Construct a matrix 'Mat' such that matrix multiplication of 'Mat' with -- -- the coordinates of another multivector 'x' (stored in a M_Vector) -- -- would result in the geometric product of 'Mat' and 'x' -- while Has_Element (Curs) loop -- aBlade := Element (Curs); -- for index in BBs_L'Range loop -- GP := Geometric_Product (aBlade, BBs_L (index)); -- if Weight (GP) /= 0.0 then -- Add_To_Matrix (Mat, BBs_L (index), GP); -- end if; -- end loop; -- Next (Curs); -- end loop; -- -- Cond := SVD.Condition_Number (Mat); -- if Cond < 1.0 / Float'Model_Epsilon then -- Mat_Inv := Inverse (Mat); -- else -- raise MV_Exception with -- "Multivectors.Geometric_Product, Mat is not invertible"; -- end if; -- -- reconstruct multivector from first column of matrix -- -- for Row in BBs'Range loop -- for Row in Mat_Inv'Range (1) loop -- Value := Mat_Inv (Row, 1); -- if Value /= 0.0 then -- Update_Blade (BBs_L (Row), Value); -- Blades.Append (BBs_L (Row)); -- end if; -- end loop; -- Result := New_Multivector (Blades); -- end if; -- -- return Result; -- -- exception -- when others => -- Put_Line ("An exception occurred in Multivector.General_Inverse."); -- raise; -- end General_Inverse; -- ------------------------------------------------------------------------- function General_Inverse (MV : Multivector; Met : Metric_Record := C3_Metric) return Multivector is use Interfaces; use Blade; use GA_Maths; use Float_Array_Package; -- Dim : Natural; Cond : Float; Value : Float; Blades : Blade_List; Result : Multivector; begin if Is_Scalar (MV) or Is_Null (MV) then Result := MV; else -- Dim := Space_Dimension (MV) ; declare -- cern.colt.matrix.DoubleFactory2D.dense.make(1 << dim, 1 << dim); -- L_Max : constant integer := 2 ** (Dim - 1); -- 1 << dim L_Max : constant integer := 2 ** (Spatial_Dimension); Mat : Float_Matrix (1 .. L_Max, 1 .. L_Max) := (others => (others => 0.0)); Mat_Inv : Float_Matrix (1 .. L_Max, 1 .. L_Max) := (others => (others => 0.0)); BBs_L : Basis_Blade_Array (1 .. L_Max); -- Det : Float; begin -- Create all unit basis blades for Dim L -- Array of basis bitmaps (0 - 31) for index in BBs_L'Range loop BBs_L (index) := New_Basis_Blade (Interfaces.Unsigned_32 (index - 1)); end loop; Mat := To_Geometric_Matrix (MV, BBs_L, Met); Cond := SVD.Condition_Number (Mat); if Cond < 1.0 / Float'Model_Epsilon then Mat_Inv := Inverse (Mat); else raise MV_Exception with "Multivectors.General_Inverse metric cannot invert matrix as it is singular."; end if; for Row in BBs_L'Range loop Value := Mat_Inv (Row, 1); if Value /= 0.0 then Update_Blade (BBs_L (Row), Value); Blades.Append (BBs_L (Row)); end if; end loop; Result := New_Multivector (Blades); end; -- declare block end if; Simplify (Result); return Result; exception when others => Put_Line ("An exception occurred in Multivector.General_Inverse Metric"); raise; end General_Inverse; -- ------------------------------------------------------------------------- function Geometric_Product (MV : Multivector; Sc : Float) return Multivector is use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; Curs : Cursor := Blades.First; New_MV : Multivector; begin if Is_Empty (Blades) then New_MV := MV; elsif Sc /= 0.0 then while Has_Element (Curs) loop New_MV.Blades.Append (New_Blade (Bitmap (Element (Curs)), Sc * Weight (Element (Curs)))); Next (Curs); end loop; Simplify (New_MV); end if; return New_MV; end Geometric_Product; -- ------------------------------------------------------------------------- function Geometric_Product (Sc : Float; MV : Multivector) return Multivector is begin return Geometric_Product (MV, Sc); end Geometric_Product; -- ------------------------------------------------------------------------- -- function Geometric_Product (MV1, MV2 : Multivector) return Multivector is -- use Blade; -- use Blade_List_Package; -- Blades_1 : constant Blade_List := MV1.Blades; -- Blades_2 : constant Blade_List := MV2.Blades; -- Curs_1 : Cursor := Blades_1.First; -- Curs_2 : Cursor; -- Blade_1 : Blade.Basis_Blade; -- Blade_2 : Blade.Basis_Blade; -- GP : Multivector; -- begin -- if Is_Empty (List (Blades_1)) then -- raise MV_Exception with "Multivectors.Geometric_Product, MV1 is null."; -- end if; -- if Is_Empty (List (Blades_2)) then -- raise MV_Exception with "Multivectors.Geometric_Product, MV2 is null."; -- end if; -- -- while Has_Element (Curs_1) loop -- Blade_1 := Element (Curs_1); -- Curs_2 := Blades_2.First; -- while Has_Element (Curs_2) loop -- Blade_2 := Element (Curs_2); -- GP.Blades.Append (Blade.Geometric_Product (Blade_1, Blade_2)); -- Next (Curs_2); -- end loop; -- Next (Curs_1); -- end loop; -- Simplify (GP); -- -- return GP; -- -- end Geometric_Product; -- ------------------------------------------------------------------------- function Geometric_Product (MV1, MV2 : Multivector; Met : Metric_Record := C3_Metric) return Multivector is use Blade; use Blade_List_Package; MV1s : Multivector := MV1; MV2s : Multivector := MV2; Blades_1 : Blade_List; Blades_2 : Blade_List; Curs_1 : Cursor; Curs_2 : Cursor; Blade_1 : Blade.Basis_Blade; Blade_2 : Blade.Basis_Blade; Blades_GP : Blade_List; -- Result GP : Multivector; begin Simplify (MV1s); Simplify (MV2s); if not Is_Empty (List (MV1s.Blades)) and not Is_Empty (List (MV2s.Blades)) then Blades_1 := MV1s.Blades; Blades_2 := MV2s.Blades; Curs_1 := Blades_1.First; while Has_Element (Curs_1) loop Blade_1 := Element (Curs_1); Curs_2 := Blades_2.First; while Has_Element (Curs_2) loop Blade_2 := Element (Curs_2); Blades_GP := Blade.Geometric_Product (Blade_1, Blade_2, Met); if not Blades_GP.Is_Empty then Add_Blades (GP.Blades, Blades_GP); end if; Next (Curs_2); end loop; Next (Curs_1); end loop; Simplify (GP); end if; return GP; end Geometric_Product; -- ------------------------------------------------------------------------- function Get_Blade_List (MV : Multivector) return Blade.Blade_List is begin return MV.Blades; end Get_Blade_List; -- ------------------------------------------------------------------------- function Get_Blade (MV : Multivector; Index : Interfaces.Unsigned_32) return Blade.Basis_Blade is use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; thisBlade : Blade.Basis_Blade; Curs : Cursor := Blades.First; Found : Boolean := False; begin while Has_Element (Curs) and not Found loop thisBlade := Element (Curs); Found := Blade.Grade (thisBlade) = Integer (Index); Next (Curs); end loop; return thisBlade; end Get_Blade; -- ------------------------------------------------------------------------- function Get_Blade (MV : Multivector; theBlade : out Multivector; Index : Interfaces.Unsigned_32) return Boolean is use Interfaces; use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; Curs : Cursor := Blades.First; Found : Boolean := False; begin while Has_Element (Curs) and not Found loop Found := Bitmap (Element (Curs)) = Index; if Found then theBlade.Blades.Append (Element (Curs)); else Next (Curs); end if; end loop; return Found; end Get_Blade; -- ------------------------------------------------------------------------- function Get_Multivector (MV_List : Multivector_List; Index : Positive) return Multivector is MV : Multivector; begin if not MV_List.Is_Empty then MV := MV_List.Element (Index); else raise MV_Exception with "Multivectors.Get_Multivector, MV_List is empty."; end if; return MV; end Get_Multivector; -- ------------------------------------------------------------------------- function Get_Random_Blade (Dim, Grade : Integer; Scale : Float) return Multivector is Result : Multivector := New_Multivector (Scale * Float (Maths.Random_Float)); begin for index in 1 .. Grade loop Result := Outer_Product (Result, Get_Random_Vector (Dim, Scale)); end loop; return Result; end Get_Random_Blade; -- ------------------------------------------------------------------------- function Get_Random_Vector (Dim : Integer; Scale : Float) return Multivector is use Blade; Blades : Blade_List; Base_Index : C3_Base; begin for index in 1 .. Dim loop Base_Index := C3_Base'Enum_Val (2 * (index - 1)); Blades.Add_Blade (New_Basis_Blade (Base_Index, Scale * Float (Maths.Random_Float))); end loop; return New_Multivector (Blades); end Get_Random_Vector; -- ------------------------------------------------------------------------- -- Grade returns the grade (bit count) of an homogeneous Multivector. -- 0 is returned for null Multivectors. -- Is_Homogeneous False is returned if the Multivector is not homogeneous. function Grade (MV : Multivector; theGrade : out Integer) return Grade_Status is use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; Cursor_B : Cursor := Blades.First; thisBlade : Blade.Basis_Blade; OK : Boolean := not Blades.Is_Empty; Status : Grade_Status := Grade_OK; begin if OK then thisBlade := Element (Cursor_B); -- Blades.First theGrade := Blade.Grade (thisBlade); Next (Cursor_B); while OK and Has_Element (Cursor_B) loop thisBlade := Element (Cursor_B); OK := Blade.Grade (thisBlade) = theGrade; Next (Cursor_B); end loop; if not OK then Status := Grade_Inhomogeneous; end if; else Status := Grade_Null; end if; return Status; end Grade; -- ------------------------------------------------------------------------- function Grade_Inversion (MV : Multivector) return Multivector is use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; Inversion : Blade_List; thisBlade : Blade.Basis_Blade; Cursor_B : Cursor := Blades.First; Result : Multivector; begin while Has_Element (Cursor_B) loop thisBlade := Element (Cursor_B); Inversion.Append (Blade.Grade_Inversion (thisBlade)); Next (Cursor_B); end loop; Result := (MV.Type_Of_MV, Inversion, False); Simplify (Result); return Result; end Grade_Inversion; -- ------------------------------------------------------------------------- -- Grade_Use returns a bitmap of grades that are in use in MV -- Bit 1: Scalar, Bit 2 etc non-scalar grades function Grade_Use (MV : Multivector) return GA_Maths.Grade_Usage is use Interfaces; use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; BB : Blade.Basis_Blade; Cursor_B : Cursor := Blades.First; GU_Bitmap : Unsigned_32 := 0; begin while Has_Element (Cursor_B) loop BB := Element (Cursor_B); GU_Bitmap := GU_Bitmap or Shift_Left (1, Blade.Grade (BB)); Next (Cursor_B); end loop; return GU_Bitmap; end Grade_Use; -- ------------------------------------------------------------------------- function Highest_Grade (MV : Multivector) return Integer is use Blade; use Blade_List_Package; Blades : constant Blade_List := Multivectors.Get_Blade_List (MV); Curs : Cursor := Blades.First; aGrade : Integer; High_Grade : Integer := 0; begin while Has_Element (Curs) loop aGrade := Grade (Element (Curs)); if aGrade > High_Grade then High_Grade := aGrade; end if; Next (Curs); end loop; return High_Grade; end Highest_Grade; -- ------------------------------------------------------------------------- function Inner_Product (MV1, MV2 : Multivector; Cont : Blade.Contraction_Type) return Multivector is use Blade; use Blade_List_Package; MV1s : Multivector := MV1; MV2s : Multivector := MV2; B1 : Basis_Blade; B2 : Basis_Blade; List_1 : Blade_List; List_2 : Blade_List; Cursor_1 : Cursor; Cursor_2 : Cursor; IP : Blade.Basis_Blade; MV : Multivector; begin Simplify (MV1s); Simplify (MV2s); List_1 := MV1s.Blades; List_2 := MV2s.Blades; Cursor_1 := List_1.First; while Has_Element (Cursor_1) loop B1 := Element (Cursor_1); Cursor_2 := List_2.First; while Has_Element (Cursor_2) loop B2 := Element (Cursor_2); IP := Blade.Inner_Product (B1, B2, Cont); if Blade.Weight (IP) /= 0.0 then MV.Blades.Append (IP); end if; Next (Cursor_2); end loop; Next (Cursor_1); end loop; Simplify (MV); return MV; exception when others => Put_Line ("An exception occurred in Multivector.Inner_Product"); raise; end Inner_Product; -- ------------------------------------------------------------------------- function Inner_Product (MV1, MV2 : Multivector; Met : Metric_Record; Cont : Blade.Contraction_Type := Blade.Left_Contraction) return Multivector is use Blade; use Blade_List_Package; MV1s : Multivector := MV1; MV2s : Multivector := MV2; B1 : Blade.Basis_Blade; B2 : Blade.Basis_Blade; List_1 : Blade_List; List_2 : Blade_List; Cursor_1 : Cursor; Cursor_2 : Cursor; Blades_IP : Blade.Blade_List; MV : Multivector; begin Simplify (MV1s); Simplify (MV2s); List_1 := MV1s.Blades; List_2 := MV2s.Blades; Cursor_1 := List_1.First; -- New_Line; -- Put_Line ("Multivectors.Inner_Product metric, Contraction Type: " & -- Blade.Contraction_Type'Image (Cont)); while Has_Element (Cursor_1) loop B1 := Element (Cursor_1); -- GA_Utilities.Print_Blade_String ("Multivectors.Inner_Product B1", -- B1, Blade_Types.Basis_Names_C3GA); Cursor_2 := List_2.First; while Has_Element (Cursor_2) loop B2 := Element (Cursor_2); -- GA_Utilities.Print_Blade_String ("Multivectors.Inner_Product B2", -- B2, Blade_Types.Basis_Names_C3GA); Blades_IP := Blade.Inner_Product (B1, B2, Met, Cont); Add_Blades (MV.Blades, Blades_IP); Next (Cursor_2); end loop; Next (Cursor_1); end loop; Simplify (MV); -- GA_Utilities.Print_Multivector_String ("Multivectors.Inner_Product MV", -- MV, Blade_Types.Basis_Names_C3GA); return MV; exception when others => Put_Line ("An exception occurred in Multivectors.Inner_Product metric"); raise; end Inner_Product; -- ------------------------------------------------------------------------- function Inverse_Rotor (R : Rotor) return Rotor is begin return To_Rotor (General_Inverse (R)); end Inverse_Rotor; -- ------------------------------------------------------------------------- -- Inverse based on c3ga.h inline scalar inverse function Inverse_Scalar (theScalar : Scalar) return Scalar is use Blade; S_Weight : constant float := Weight (theScalar.Blades.First_Element); Inv_Weight : float; begin if S_Weight = 0.0 then raise MV_Exception with "Multivectors.Inverse_Scalar called with zero weight blade"; end if; Inv_Weight := 1.0 / S_Weight ** 2; return New_Scalar (S_Weight * Inv_Weight); end Inverse_Scalar; -- ------------------------------------------------------------------------- function Is_Null (MV : Multivector) return Boolean is M : Multivector := MV; begin Simplify (M); return M.Blades.Is_Empty; end Is_Null; -- ------------------------------------------------------------------------- function Is_Null (MV : Multivector; Epsilon : Float) return Boolean is S : constant Float := Norm_Esq (MV); begin return S < Epsilon * Epsilon; end Is_Null; -- ------------------------------------------------------------------------- function Is_Scalar (MV : Multivector) return Boolean is use Interfaces; use Ada.Containers; use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; Result : Boolean := Is_Null (MV); begin if not Result and then Blades.Length = 1 then Result := Bitmap (Element (Blades.First)) = 0; end if; return Result; end Is_Scalar; -- ------------------------------------------------------------------------- function Largest_Basis_Blade (MV : Multivector) return Blade.Basis_Blade is use Blade; use Blade_List_Package; theMV : Multivector := MV; Blades : constant Blade_List := theMV.Blades; Cursor_B : Cursor := Blades.First; Largest_Blade : Blade.Basis_Blade; Best_Scale : Float := 0.0; begin Simplify (theMV); while Has_Element (Cursor_B) loop if Abs (Blade.Weight (Element (Cursor_B))) > Best_Scale then Best_Scale := Abs (Blade.Weight (Element (Cursor_B))); Largest_Blade := Element (Cursor_B); end if; Next (Cursor_B); end loop; return Largest_Blade; end Largest_Basis_Blade; -- ------------------------------------------------------------------------- function Largest_Coordinate (MV : Multivector) return Float is use Blade; use Blade_List_Package; theMV : Multivector := MV; Blades : constant Blade_List := theMV.Blades; Cursor_B : Cursor := Blades.First; aBlade : Blade.Basis_Blade; Largest : Float := 0.0; begin Simplify (theMV); while Has_Element (Cursor_B) loop aBlade := Element (Cursor_B); Largest := GA_Maths.Maximum (Largest, Abs (Blade.Weight (aBlade))); Next (Cursor_B); end loop; return Largest; end Largest_Coordinate; -- ------------------------------------------------------------------------- function Left_Contraction (MV1, MV2 : Multivector) return Multivector is begin return Inner_Product (MV1, MV2, Blade.Left_Contraction); end Left_Contraction; -- ------------------------------------------------------------------------- function Left_Contraction (MV1, MV2 : Multivector; Met : Metric_Record) return Multivector is begin return Inner_Product (MV1, MV2, Met); end Left_Contraction; -- ------------------------------------------------------------------------- function List_Length (MV_List : Multivector_List) return Integer is begin return Integer (MV_List.Length); end List_Length; -- ------------------------------------------------------------------------- function Multivector_List_String (Blades : Blade.Blade_List; BV_Names : Blade_Types.Basis_Vector_Names) return Ada.Strings.Unbounded.Unbounded_String is use Ada.Strings.Unbounded; use Blade; use Blade_List_Package; Blade_Cursor : Cursor := Blades.First; thisBlade : Blade.Basis_Blade; Blade_UBS : Ada.Strings.Unbounded.Unbounded_String; theString : Ada.Strings.Unbounded.Unbounded_String := To_Unbounded_String ("0.0"); String_Length : Integer := 0; begin while Has_Element (Blade_Cursor) loop thisBlade := Element (Blade_Cursor); -- GA_Utilities.Print_Blade ("Multivectors.Multivector_String thisBlade", thisBlade); Blade_UBS := Blade.Blade_String (thisBlade, BV_Names); -- Put_Line ("Multivectors.Multivector_String, " & To_String (Blade_UBS)); if Length (Blade_UBS) > 0 then declare Blade_String : constant String := To_String (Blade_UBS); begin if Blade_Cursor = Blades.First then theString := To_Unbounded_String (Blade_String); else if Blade_String (1) = '-' then theString := theString & " - "; else theString := theString & " + "; end if; theString := theString & Blade_String (2 .. Blade_String'Length); end if; if Length (theString) - String_Length > 50 then theString := theString & ASCII.LF; String_Length := Length (theString); end if; end; end if; Next (Blade_Cursor); end loop; return theString; exception when anError : others => Put_Line ("An exception occurred in Multivectors.Multivector_List_String."); Put_Line (Exception_Information (anError)); raise; end Multivector_List_String; -- ------------------------------------------------------------------------- function Multivector_String (MV : Multivector; BV_Names : Blade_Types.Basis_Vector_Names) return Ada.Strings.Unbounded.Unbounded_String is use Ada.Strings.Unbounded; use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; Blade_Cursor : Cursor := Blades.First; thisBlade : Blade.Basis_Blade; Blade_UBS : Ada.Strings.Unbounded.Unbounded_String; theString : Ada.Strings.Unbounded.Unbounded_String := To_Unbounded_String ("0.0"); String_Length : Integer := 0; begin while Has_Element (Blade_Cursor) loop thisBlade := Element (Blade_Cursor); -- GA_Utilities.Print_Blade ("Multivectors.Multivector_String thisBlade", thisBlade); Blade_UBS := Blade.Blade_String (thisBlade, BV_Names); -- Put_Line ("Multivectors.Multivector_String, " & To_String (Blade_UBS)); if Length (Blade_UBS) > 0 then declare Blade_String : constant String := To_String (Blade_UBS); begin if Blade_Cursor = Blades.First then theString := To_Unbounded_String (Blade_String); else if Blade_String (1) = '-' then theString := theString & " - "; else theString := theString & " + "; end if; theString := theString & Blade_String (2 .. Blade_String'Length); end if; if Length (theString) - String_Length > 50 then theString := theString & ASCII.LF; String_Length := Length (theString); end if; end; end if; Next (Blade_Cursor); end loop; return theString; exception when anError : others => Put_Line ("An exception occurred in Multivectors.Multivector_String."); Put_Line (Exception_Information (anError)); raise; end Multivector_String; -- ------------------------------------------------------------------------- function MV_Kind (MV : Multivector) return MV_Type is begin return MV.Type_Of_MV; end MV_Kind; -- ------------------------------------------------------------------------- function MV_Size (MV : Multivector) return Natural is Blades : constant Blade.Blade_List := MV.Blades; begin return Natural (Blades.Length); end MV_Size; -- ------------------------------------------------------------------------- function Space_Dimension return Natural is begin return Spatial_Dimension; end Space_Dimension; -- ------------------------------------------------------------------------- function Negate (MV : Multivector) return Multivector is use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; Curs : Cursor := Blades.First; aBlade : Blade.Basis_Blade; Negated_MV : Multivector; begin while Has_Element (Curs) loop aBlade := Element (Curs); Blade.Update_Blade (aBlade, -Weight (aBlade)); Negated_MV.Blades.Append (aBlade); Next (Curs); end loop; return Negated_MV; end Negate; -- ------------------------------------------------------------------------ function New_Bivector (V1, V2 : M_Vector) return Bivector is begin return Bivector (Outer_Product (V1, V2)); end New_Bivector; -- ------------------------------------------------------------------------- function New_Bivector (e1e2, e2e3, e3e1 : Float) return Bivector is use Blade; BV : Bivector; begin -- BV.Type_Of_MV := MV_Bivector; BV.Blades.Append (New_Basis_Blade (BV_e1e2, e1e2)); BV.Blades.Append (New_Basis_Blade (BV_e2e3, e2e3)); BV.Blades.Append (New_Basis_Blade (BV_e3e1, e3e1)); Simplify (BV); return BV; end New_Bivector; -- ------------------------------------------------------------------------- function New_Multivector (Scalar_Weight : Float) return Multivector is MV : Multivector; begin MV.Blades.Append (Blade.New_Scalar_Blade (Scalar_Weight)); return MV; end New_Multivector; -- ------------------------------------------------------------------------- function New_Multivector (aBlade : Blade.Basis_Blade) return Multivector is MV : Multivector; begin MV.Blades.Append (aBlade); return MV; end New_Multivector; -- ------------------------------------------------------------------------- function New_Multivector (Blades : Blade.Blade_List) return Multivector is MV : Multivector; begin MV.Blades := Blades; return MV; end New_Multivector; -- ------------------------------------------------------------------------- -- function New_Normalized_Point return Normalized_Point is -- NP : Normalized_Point; -- begin -- NP.Type_Of_MV := MV_Normalized_Point; -- return NP; -- end New_Normalized_Point; -- ------------------------------------------------------------------------- function New_Normalized_Point (e1, e2, e3 : Float) return Normalized_Point is use Blade; NP : Normalized_Point; begin -- NP.Type_Of_MV := MV_Normalized_Point; NP.Blades.Append (New_Basis_Blade (C3_no, 1.0)); NP.Blades.Append (New_Basis_Blade (C3_e1, e1)); NP.Blades.Append (New_Basis_Blade (C3_e2, e2)); NP.Blades.Append (New_Basis_Blade (C3_e3, e3)); NP.Blades.Append (New_Basis_Blade (C3_ni, 0.5 * (e1 * e1 + e2 * e2 + e3 * e3))); return NP; end New_Normalized_Point; -- ------------------------------------------------------------------------- -- function New_Rotor return Rotor is -- begin -- return New_Rotor (1.0); -- end New_Rotor; -- ------------------------------------------------------------------------- function New_Rotor (Scalar_Weight : Float) return Rotor is use Blade; R : Rotor; begin -- R.Type_Of_MV := MV_Rotor; R.Blades.Append (Blade.New_Scalar_Blade (Scalar_Weight)); return R; end New_Rotor; -- ------------------------------------------------------------------------- function New_Rotor (Scalar_Weight : Float; BV : Bivector) return Rotor is use Blade; R : Rotor; begin -- R.Type_Of_MV := MV_Rotor; R.Blades.Append (New_Scalar_Blade (Scalar_Weight)); R.Blades.Append (Get_Blade (BV, BV_Base'Enum_Rep (BV_e1e2))); R.Blades.Append (Get_Blade (BV, BV_Base'Enum_Rep (BV_e2e3))); R.Blades.Append (Get_Blade (BV, BV_Base'Enum_Rep (BV_e3e1))); return R; end New_Rotor; -- ------------------------------------------------------------------------- function New_Rotor (Scalar_Weight, e1, e2, e3 : Float) return Rotor is use Blade; R : Rotor; begin -- R.Type_Of_MV := MV_Rotor; R.Blades.Append (New_Scalar_Blade (Scalar_Weight)); R.Blades.Append (New_Basis_Blade (E3_e1, e1)); R.Blades.Append (New_Basis_Blade (E3_e2, e2)); R.Blades.Append (New_Basis_Blade (E3_e3, e3)); return R; end New_Rotor; -- ------------------------------------------------------------------------- function New_Scalar (Scalar_Weight : Float := 0.0) return Scalar is S : Scalar; begin -- S.Type_Of_MV := MV_Scalar; S.Blades.Append (Blade.New_Scalar_Blade (Scalar_Weight)); return S; end New_Scalar; -- ------------------------------------------------------------------------ function New_TR_Versor (Scalar_Weight : Float := 0.0) return TR_Versor is V : TR_Versor; begin -- V.Type_Of_MV := MV_TR_Versor; if Scalar_Weight /= 0.0 then V.Blades.Append (Blade.New_Scalar_Blade (Scalar_Weight)); end if; return V; end New_TR_Versor; -- ------------------------------------------------------------------------ -- function New_Vector return M_Vector is -- V : M_Vector; -- begin -- V.Type_Of_MV := MV_Vector; -- return V; -- end New_Vector; -- ------------------------------------------------------------------------ function New_Vector (e1, e2 : Float) return M_Vector is use Blade; V : M_Vector; begin -- V.Type_Of_MV := MV_Vector; Add_Blade (V, New_Basis_Blade (E2_e1, e1)); Add_Blade (V, New_Basis_Blade (E2_e2, e2)); return V; end New_Vector; -- ------------------------------------------------------------------------ function New_Vector (e1, e2, e3 : Float) return M_Vector is use Blade; V : M_Vector; begin -- V.Type_Of_MV := MV_Vector; Add_Blade (V, New_Basis_Blade (E3_e1, e1)); Add_Blade (V, New_Basis_Blade (E3_e2, e2)); Add_Blade (V, New_Basis_Blade (E3_e3, e3)); Simplify (V); return V; end New_Vector; -- ------------------------------------------------------------------------ function Norm_E (MV : Multivector) return Float is use GA_Maths.Float_Functions; begin return Sqrt (Norm_Esq (MV)); end Norm_E; -- ------------------------------------------------------------------------- -- Based on Geometric Algebra for Computer Science section 3.1.3, eq (3.4) -- and ga_ref_impl.Multivector.java norm_e2() function Norm_Esq (MV : Multivector) return Float is S : Float := Scalar_Product_Local (MV, Reverse_MV (MV)); begin if S < 0.0 then S := 0.0; end if; return S; end Norm_Esq; -- ------------------------------------------------------------------------- function Outer_Product (MV1, MV2 : Multivector) return Multivector is use Blade; use Blade_List_Package; MV1s : Multivector := MV1; MV2s : Multivector := MV2; List_1 : Blade_List; List_2 : Blade_List; Cursor_1 : Cursor; Cursor_2 : Cursor; Blade_OP : Blade.Basis_Blade; B1 : Blade.Basis_Blade; B2 : Blade.Basis_Blade; OP : Multivector; begin Simplify (MV1s); Simplify (MV2s); List_1 := MV1s.Blades; List_2 := MV2s.Blades; Cursor_1 := List_1.First; -- For each element of List_1 -- For each element of List_1 -- Calculate the outer product of these two elements -- Append the resultant element to the Result list. while Has_Element (Cursor_1) loop B1 := Element (Cursor_1); Cursor_2 := List_2.First; while Has_Element (Cursor_2) loop B2 := Element (Cursor_2); Blade_OP := Outer_Product (B1, B2); if Weight (Blade_OP) /= 0.0 then OP.Blades.Append (Blade_OP); end if; Next (Cursor_2); end loop; Next (Cursor_1); end loop; Simplify (OP); return OP; end Outer_Product; -- ------------------------------------------------------------------------- function Random_Blade (Dim, Grade : Integer; Scale : Float) return Multivector is Result : Multivector := New_Multivector (2.0 * Scale * Float (Maths.Random_Float) - 0.5); begin For index in 1 .. Grade loop Result := Outer_Product (Result, Random_Vector (Dim, Scale)); end loop; return Result; end Random_Blade; -- ------------------------------------------------------------------------- function Random_Vector (Dim : Integer; Scale : Float) return Multivector is Result : Multivector := New_Multivector (2.0 * Scale * Float (Maths.Random_Float) - 0.5); use Interfaces; use Blade; Bases : Blade_List; aBlade : Basis_Blade; Bit : Unsigned_32; begin For index in Unsigned_32 range 0 .. Unsigned_32 (Dim - 1) loop Bit := Shift_Left (1, Natural (index)); aBlade := New_Basis_Blade (C3_Base'Enum_Val (Integer (Bit)), 2.0 * Scale * Float (Maths.Random_Float) - 0.5); Bases.Append (aBlade); end loop; Result.Blades := Bases; return Result; end Random_Vector; -- ------------------------------------------------------------------------- function Reverse_MV (MV : Multivector) return Multivector is use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; B_Cursor : Cursor := Blades.First; Rev_Blades : Blade_List; begin -- loop over all basis lades, reverse each one and add to result while Has_Element (B_Cursor) loop Rev_Blades.Append (Reverse_Blade (Element (B_Cursor))); Next (B_Cursor); end loop; return New_Multivector (Rev_Blades); end Reverse_MV; -- ------------------------------------------------------------------------- function Right_Contraction (MV1, MV2 : Multivector) return Multivector is begin return Inner_Product (MV1, MV2, Blade.Right_Contraction); end Right_Contraction; -- ------------------------------------------------------------------------- function Right_Contraction (MV1, MV2 : Multivector; Met : Metric_Record) return Multivector is begin return Inner_Product (MV1, MV2, Met); end Right_Contraction; -- ------------------------------------------------------------------------- -- function Rotor_Inverse (R : Rotor; IR : out Rotor) return Boolean is -- use Blade; -- use Blade_List_Package; -- MV : Multivector; -- Blades : constant Blade_List := MV.Blades; -- Curs : Cursor := Blades.First; -- Invertible : constant Boolean := General_Inverse (R, MV); -- begin -- if Invertible then -- while Has_Element (Curs) loop -- Add_Blade (IR, Element (Curs)); -- Next (Curs); -- end loop; -- end if; -- return Invertible; -- end Rotor_Inverse; -- ------------------------------------------------------------------------- function Scalar_Part (MV : Multivector) return Float is use Interfaces; use Blade; use Blade_List_Package; BB : Blade.Basis_Blade; Blades : constant Blade_List := MV.Blades; B_Cursor : Cursor := Blades.First; Sum : Float := 0.0; begin while Has_Element (B_Cursor) loop BB := Element (B_Cursor); if Bitmap (BB) = 0 then Sum := Sum + Weight (BB); end if; Next (B_Cursor); end loop; return Sum; end Scalar_Part; -- ------------------------------------------------------------------------- function Scalar_Product_Local (MV1, MV2 : Multivector) return float is begin return Scalar_Part (Inner_Product (MV1, MV2, Blade.Left_Contraction)); end Scalar_Product_Local; -- ------------------------------------------------------------------------- function Scalar_Product (MV1, MV2 : Multivector; Met : Metric_Record := C3_Metric) return float is begin return Scalar_Part (Inner_Product (MV1, MV2, Met)); end Scalar_Product; -- ------------------------------------------------------------------------- procedure Set_Geometry (theGeometry : Geometry_Type) is begin case theGeometry is when E1_Geometry => Spatial_Dimension := 1; when E2_Geometry => Spatial_Dimension := 2; when E3_Geometry => Spatial_Dimension := 3; when H3_Geometry => Spatial_Dimension := 4; when C3_Geometry => Spatial_Dimension := 5; when others => raise MV_Exception with "Multivectors.Set_Geometry, invalid geometry."; end case; end Set_Geometry; -- ------------------------------------------------------------------------- procedure Simplify (MV : in out Multivector) is Blades : Blade.Blade_List := MV.Blades; begin if Blade.List_Length (Blades) > 0 then Blade.Simplify (Blades); MV.Blades := Blades; end if; end Simplify; -- ------------------------------------------------------------------------- function Sine (MV : Multivector) return Multivector is begin return Sine (MV, 12); end Sine; -- ------------------------------------------------------------------------- function Sine (MV : Multivector; Order : Integer) return Multivector is use GA_Maths.Float_Functions; A2 : Multivector := Geometric_Product (MV, MV); A2_Scalar : Float; Alpha : Float; Result : Multivector; begin Compress (A2); if Is_Null (A2, epsilon) then Result := MV; elsif Is_Scalar (A2) then A2_Scalar := Scalar_Part (A2); if A2_Scalar < 0.0 then Alpha := Sqrt (-A2_Scalar); Result := Geometric_Product (MV, Sinh (Alpha) / Alpha); else Alpha := Sqrt (A2_Scalar); Result := Geometric_Product (MV, Sin (Alpha) / Alpha); end if; else -- Not null and not scalar Result := Sine_Series (MV, Order); end if; return Result; end Sine; -- ------------------------------------------------------------------------- function Sine_Series (MV : Multivector; Order : Integer) return Multivector is use Interfaces; Scaled : constant Multivector := MV; Scaled_GP : Multivector; Temp : Multivector := Scaled; Sign : Integer := -1; Result : Multivector := Scaled; begin -- Taylor approximation for Count in 2 .. Order loop Scaled_GP := Geometric_Product (Scaled, 1.0 / Float (Count)); Temp := Geometric_Product (Temp, Scaled_GP); if (Unsigned_32 (Count) and 1) /= 0 then -- use only the odd part of the series Result := Result + Geometric_Product (Temp, Float (Sign)); Sign := -Sign; end if; end loop; return Result; end Sine_Series; -- ------------------------------------------------------------------------- -- Space_Dimension returns the dimension of the space that this blade -- (apparently) lives in. -- function Space_Dimension (MV : Multivector) return Natural is -- use Blade; -- use Blade_List_Package; -- Max_D : Natural := 0; -- Blade_Cursor : Cursor := MV.Blades.First; -- begin -- while Has_Element (Blade_Cursor) loop -- Max_D := GA_Maths.Maximum (Max_D, -- Bits.Highest_One_Bit (Bitmap (Element (Blade_Cursor)))); -- Next (Blade_Cursor); -- end loop; -- -- return Max_D + 1; -- end Space_Dimension; -- ------------------------------------------------------------------------- -- To_Geometric_Matrix constructs a matrix 'Matrix_AG' such that -- matrix multiplication of 'Matrix_AG' with the coordinates of another -- multivector 'x' (stored in a M_Vector) would result in the -- geometric product of 'Matrix_AG' and 'x' -- Metric version: function To_Geometric_Matrix (MV : Multivector; BBs_L : Basis_Blade_Array; Met : Metric_Record) return GA_Maths.Float_Matrix is use Blade; use GA_Maths; use Blade_List_Package; L_Max : constant integer := BBs_L'Length; Matrix_AG : Float_Matrix (1 .. L_Max, 1 .. L_Max) := (others => (others => 0.0)); BL_Curs_i : Cursor := MV.Blades.First; Blade_b : Basis_Blade; -- b GP_List : Blade_List; begin while Has_Element (BL_Curs_i) loop -- for each blade of BL Blade_B := Element (BL_Curs_i); -- for each bitmap -- geometric multiply the multivector blade by each unit basis blade -- and add each result to matrix M at rows corresponding to the -- the product and the column corresponding to the unit basis blade. for index_j in BBs_L'Range loop -- metric instance of Metric -- gp(aBlade, BBs (index_j), Met) corresponds to L_k L_j of equation (20.1) GP_List := Geometric_Product (Blade_b, BBs_L (index_j), Met); if not Is_Empty (GP_List) then Add_To_Matrix (Matrix_AG, BBs_L (index_j), GP_List); end if; end loop; Next (BL_Curs_i); end loop; return Matrix_AG; end To_Geometric_Matrix; -- ------------------------------------------------------------------------- function Top_Grade_Index (MV : Multivector) return Integer is use Blade; use Blade_List_Package; use GA_Maths; Max_Grade_Count : Integer := 0; Grade_Count : Integer := 0; Blades : constant Blade_List := MV.Blades; Blade_Cursor : Cursor := Blades.First; begin while Has_Element (Blade_Cursor) loop -- Grade_Count = bit count Grade_Count := Blade.Grade (Element (Blade_Cursor)); Max_Grade_Count := Maximum (Max_Grade_Count, Grade_Count); Next (Blade_Cursor); end loop; return Grade_Count; end Top_Grade_Index; -- ------------------------------------------------------------------------- function To_Bivector (R : Rotor) return Bivector is use Interfaces; use Blade; use Blade_List_Package; Blades : constant Blade_List := R.Blades; Curs : Cursor := Blades.First; aBlade : Basis_Blade; BM : Unsigned_32; BV : Bivector; begin while Has_Element (Curs) loop aBlade := Element (Curs); BM := aBlade.Bitmap; if BM = C3_Base'Enum_Rep (C3_e1_e2) or BM = C3_Base'Enum_Rep (C3_e1_e3) or BM = C3_Base'Enum_Rep (C3_e2_e3) then Add_Blade (BV, aBlade); end if; Next (Curs); end loop; return BV; end To_Bivector; -- ------------------------------------------------------------------------- function To_Circle (MV : Multivector) return Circle is theCircle : Circle; begin theCircle.Blades := MV.Blades; theCircle.Sorted := MV.Sorted; return theCircle; end To_Circle; -- ------------------------------------------------------------------------- function To_Dual_Line (MV : Multivector) return Dual_Line is DL : Dual_Line; begin DL.Blades := MV.Blades; DL.Sorted := MV.Sorted; return DL; end To_Dual_Line; -- ------------------------------------------------------------------------- function To_Dual_Plane (MV : Multivector) return Dual_Plane is theDual_Plane : Dual_Plane; begin theDual_Plane.Blades := MV.Blades; theDual_Plane.Sorted := MV.Sorted; return theDual_Plane; end To_Dual_Plane; -- ------------------------------------------------------------------------- function To_Line (MV : Multivector) return Line is theLine : Line; begin theLine.Blades := MV.Blades; theLine.Sorted := MV.Sorted; return theLine; end To_Line; -- ------------------------------------------------------------------------- function To_Normalized_Point (MV : Multivector) return Normalized_Point is thePoint : Normalized_Point; begin thePoint.Blades := MV.Blades; thePoint.Sorted := MV.Sorted; return thePoint; end To_Normalized_Point; -- ------------------------------------------------------------------------- function To_Rotor (MV : Multivector) return Rotor is use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; Curs : Cursor := Blades.First; Rot : Rotor; begin while Has_Element (Curs) loop Add_Blade (Rot, Element (Curs)); Next (Curs); end loop; return Rot; end To_Rotor; -- ------------------------------------------------------------------------- function To_TRversor (MV : Multivector) return TR_Versor is use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; Curs : Cursor := Blades.First; TRV : TR_Versor; begin while Has_Element (Curs) loop Add_Blade (TRV, Element (Curs)); Next (Curs); end loop; return TRV; end To_TRversor; -- ------------------------------------------------------------------------- function To_Vector (MV : Multivector) return M_Vector is use Blade; use Blade_List_Package; Blades : constant Blade_List := MV.Blades; Curs : Cursor := Blades.First; Vec : M_Vector; begin while Has_Element (Curs) loop Add_Blade (Vec, Element (Curs)); Next (Curs); end loop; return Vec; end To_Vector; -- ------------------------------------------------------------------------- function Unit_E (MV : Multivector) return Multivector is begin return Unit_R (MV); exception when others => Put_Line ("An exception occurred in Multivectors.Unit_E."); raise; end Unit_E; -- ------------------------------------------------------------------------- -- function Unit_R (MV : Multivector) return Multivector is -- use GA_Maths.Float_Functions; -- Norm_Sq : constant Float := Scalar_Product (MV, Reverse_MV (MV)); -- begin -- if Norm_Sq = 0.0 then -- raise MV_Exception with -- "Multivectors.Unit_R encountered a null multivector"; -- end if; -- -- return Geometric_Product (MV, 1.0 / Sqrt (Abs (Norm_Sq))); -- -- exception -- when others => -- Put_Line ("An exception occurred in Multivectors.Unit_R."); -- raise; -- end Unit_R; -- ------------------------------------------------------------------------- function Unit_R (MV : Multivector; Met : Metric_Record := C3_Metric) return Multivector is use GA_Maths.Float_Functions; Norm_Sq : constant Float := Scalar_Product (MV, Reverse_MV (MV), Met); begin if Norm_Sq = 0.0 then raise MV_Exception with "Multivectors.Unit_R Metric encountered a null multivector"; end if; return Geometric_Product (MV, 1.0 / Sqrt (Abs (Norm_Sq))); exception when others => Put_Line ("An exception occurred in Multivectors.Unit_R Metric."); raise; end Unit_R; -- ------------------------------------------------------------------------- procedure Update (MV : in out Multivector; Blades : Blade.Blade_List; Sorted : Boolean := False) is begin MV.Blades := Blades; MV.Sorted := Sorted; end Update; -- ------------------------------------------------------------------------- procedure Update_Scalar_Part (MV : in out Multivector; Value : Float) is Blades : constant Blade.Blade_List := Get_Blade_List (MV); begin MV.Blades.Replace_Element (Blades.First, Blade.New_Scalar_Blade (Value)); end Update_Scalar_Part; -- ------------------------------------------------------------------------- -- Geometric ALgebra for Computer Scientists, Section 21.1 -- function Versor_Inverse (MV : Multivector) return Multivector is -- Rev : constant Multivector := Reverse_MV (MV); -- Weight : constant Float := Scalar_Product (MV, Rev); -- begin -- if Weight = 0.0 then -- raise MV_Exception with -- "Multivector.Versor_Inverse encountered a non-invertible multivector" ; -- end if; -- -- return Rev / Weight; -- -- end Versor_Inverse; -- ------------------------------------------------------------------------- function Versor_Inverse (MV : Multivector; Met : Metric_Record := C3_Metric) return Multivector is Rev : constant Multivector := Reverse_MV (MV); Weight : constant Float := Scalar_Product (MV, Rev, Met); begin if Weight = 0.0 then Put_Line ("Multivector.Versor_Inverse encountered a non-invertible multivector"); raise MV_Exception; end if; return Rev / Weight; exception when others => Put_Line ("An exception occurred in Multivector.Versor_Inverse."); raise; end Versor_Inverse; -- ------------------------------------------------------------------------- begin MV_Basis_Vector_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("no")); MV_Basis_Vector_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e1")); MV_Basis_Vector_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e2")); MV_Basis_Vector_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e3")); MV_Basis_Vector_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("ni")); end Multivectors;
-- { dg-do run } with Aggr14_Pkg; use Aggr14_Pkg; procedure Aggr14 is begin Proc; end;
-- Swaggy Jenkins -- Jenkins API clients generated from Swagger / Open API specification -- ------------ EDIT NOTE ------------ -- This file was generated with openapi-generator. You can modify it to implement -- the server. After you modify this file, you should add the following line -- to the .openapi-generator-ignore file: -- -- src/.ads -- -- Then, you can drop this edit note comment. -- ------------ EDIT NOTE ------------ package is end ;
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015, 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. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Googlecode is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line); end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Write_Line (File, "{{{"); when L_END_CODE => Formatter.Write_Line (File, "}}}"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Write_Line (File, "= " & Line.Content & " ="); when L_HEADER_2 => Formatter.Write_Line (File, "== " & Line.Content & " =="); when L_HEADER_3 => Formatter.Write_Line (File, "=== " & Line.Content & " ==="); when L_HEADER_4 => Formatter.Write_Line (File, "==== " & Line.Content & " ===="); when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter); begin Ada.Text_IO.New_Line (File); if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[https://github.com/stcarrez/dynamo Generated by Dynamo] from _" & Source & "_"); end if; end Finish_Document; end Gen.Artifacts.Docs.Googlecode;
-- Julian.Ada_conversion, a sub-package of Julian. -- This package focuses on conversion between the Julian time -- i.e. duration and time expressed in fractional Julian days, -- and Ada.Calendar duration and time data. -- These routines are only usefull for implementations -- where conversions to and from the Ada time system are necessary. ---------------------------------------------------------------------------- -- Copyright Miletus 2015 -- 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: -- 1. The above copyright notice and this permission notice shall be included -- in all copies or substantial portions of the Software. -- 2. Changes with respect to any former version shall be documented. -- -- The software is provided "as is", without warranty of any kind, -- express of implied, including but not limited to the warranties of -- merchantability, fitness for a particular purpose and noninfringement. -- In no event shall the authors of 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. -- Inquiries: www.calendriermilesien.org ------------------------------------------------------------------------------- with Calendar; use Calendar; package Scaliger.Ada_conversion is function Julian_Time_Of (Ada_Timestamp : Time) return Historical_Time; -- return Julian time following the classical convention i.e.: -- Julian time takes integer values at noon GMT. function Time_Of (Julian_Timestamp : Historical_Time) return Time; -- convert Julian time into Ada time. function Julian_Duration_Of (Ada_Offset : Duration) return Historical_Duration; -- convert Ada duration (seconds) -- to Julian duration (fractional days stored in seconds) function Julian_Duration_Of (Day : Julian_Day_Duration) return Historical_Duration; -- convert a Julian day (an integer) into a julian duration -- which is expressed in seconds to the 1/8s. function Duration_Of (Julian_Offset : Historical_Duration) return Duration; function Day_Julian_Offset (Ada_Daytime : Day_Duration) return Day_Historical_Duration; -- Time of the day expressed in UTC time (0..86_400.0 s) -- to Julian duration expressed in (-0.5..+0.5) function Day_Offset (Julian_Offset : Day_Historical_Duration) return Day_Duration; -- Julian day duration -0.5..+0.5 to time of day 0..86_400.0 s function Julian_Day_Of (Julian_Timestamp : Historical_Time) return Julian_Day; -- gives the nearest integer of a Julian time function Julian_Day_Of (Ada_Timestamp : Time) return Julian_Day; -- the day corresponding to the UTC day of Ada_Timestamp function Time_Of_At_Noon (Julian_Date : Julian_Day) return Time; -- By convention, the "seconds" field is set to 12.00 UTC in this routine. end Scaliger.Ada_conversion;
-- part of OpenGLAda, (c) 2018 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with GL.API; package body GL.Enums.Getter is use Types; function Get_Max (Getter_Param : Parameter) return Types.Int is Max : aliased Int; begin API.Get_Integer (Getter_Param, Max'Access); return Max - 1; end Get_Max; end GL.Enums.Getter;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- I N T E R F A C E S . R A S P B E R R Y _ P I -- -- -- -- S p e c -- -- -- -- Copyright (C) 2016-2017, 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 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/>. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by Ada Core Technologies, Inc. -- -- -- ------------------------------------------------------------------------------ -- This package provides declarations for hardware registers on Raspberry-Pi 2 pragma Ada_2012; -- Uses aspects with System; package Interfaces.Raspberry_Pi is pragma No_Elaboration_Code_All; pragma Preelaborate; IO_Base : constant := 16#3f00_0000#; -- IO peripherals base address. Depends on the Raspberry Pi version: -- 16#2000_000# for RPi1 -- 16#3f00_000# for RPi2 and RPi3 -- Local peripherals defined in Quad-A7 control (QA7_rev3.4.pdf) type Core_Unsigned_32 is array (1 .. 4) of Unsigned_32; type Core_Mailbox_Unsigned_32 is array (1 .. 4, 0 .. 3) of Unsigned_32; type Local_Registers_Type is record -- At 0x00: Control : Unsigned_32; Unused_1 : Unsigned_32; Core_Timer_Prescaler : Unsigned_32; GPU_Int_Routing : Unsigned_32; -- At 0x10: PMU_Int_Routing_Set : Unsigned_32; PMU_Int_Routing_Clr : Unsigned_32; Unused_2 : Unsigned_32; Core_Timer_LS : Unsigned_32; -- At 0x20: Core_Timer_MS : Unsigned_32; Local_Int_Routing : Unsigned_32; Unused_3 : Unsigned_32; AXI_Counters : Unsigned_32; -- At 0x30: AXI_Int : Unsigned_32; Local_Timer_Ctr : Unsigned_32; Local_Timer_Flags : Unsigned_32; Unused_4 : Unsigned_32; -- At 0x40 - 0x7f: Cores_Timer_Int_Ctr : Core_Unsigned_32; Cores_Mailboxes_Int_Ctr : Core_Unsigned_32; Cores_IRQ_Source : Core_Unsigned_32; Cores_FIQ_Source : Core_Unsigned_32; -- At 0x80: Cores_Mailboxes_Write_Set : Core_Mailbox_Unsigned_32; -- At 0xc0: Cores_Mailboxes_Read_Clr : Core_Mailbox_Unsigned_32; end record; Local_Registers_Base : constant := 16#4000_0000#; Local_Registers : Local_Registers_Type with Import, Volatile, Address => System'To_Address (Local_Registers_Base); -- GPIO registers GP_Base : constant := IO_Base + 16#20_0000#; type GPIO_Registers_Type is record GPFSEL0 : Unsigned_32; GPFSEL1 : Unsigned_32; GPFSEL2 : Unsigned_32; GPFSEL3 : Unsigned_32; GPFSEL4 : Unsigned_32; GPFSEL5 : Unsigned_32; Pad_18 : Unsigned_32; GPSET0 : Unsigned_32; GPSET1 : Unsigned_32; Pad_24 : Unsigned_32; GPCLR0 : Unsigned_32; GPCLR1 : Unsigned_32; Pad_30 : Unsigned_32; GPLEV0 : Unsigned_32; GPLEV1 : Unsigned_32; Pad_3c : Unsigned_32; GPEDS0 : Unsigned_32; GPEDS1 : Unsigned_32; Pad_48 : Unsigned_32; GPREN0 : Unsigned_32; GPREN1 : Unsigned_32; Pad_54 : Unsigned_32; GPFEN0 : Unsigned_32; GPFEN1 : Unsigned_32; Pad_60 : Unsigned_32; GPHEN0 : Unsigned_32; GPHEN1 : Unsigned_32; Pad_6c : Unsigned_32; GPLEN0 : Unsigned_32; GPLEN1 : Unsigned_32; Pad_78 : Unsigned_32; GPAREN0 : Unsigned_32; GPAREN1 : Unsigned_32; Pad_84 : Unsigned_32; GPAFEN0 : Unsigned_32; GPAFEN1 : Unsigned_32; Pad_90 : Unsigned_32; GPPUD : Unsigned_32; GPPUDCLK0 : Unsigned_32; GPPUDCLK1 : Unsigned_32; Pad_A0 : Unsigned_32; Pad_A4 : Unsigned_32; Pad_A8 : Unsigned_32; Pad_Ac : Unsigned_32; Test : Unsigned_32; end record; GPIO_Registers : GPIO_Registers_Type with Address => System'To_Address (GP_Base), Volatile, Import; -- Mini-UART registers MU_Base : constant := IO_Base + 16#21_5000#; Aux_ENB : Unsigned_32 with Address => System'To_Address (MU_Base + 16#04#), Import, Volatile; MU_IO : Unsigned_32 with Address => System'To_Address (MU_Base + 16#40#), Import, Volatile; MU_IIR : Unsigned_32 with Address => System'To_Address (MU_Base + 16#44#), Import, Volatile; MU_IER : Unsigned_32 with Address => System'To_Address (MU_Base + 16#48#), Import, Volatile; MU_LCR : Unsigned_32 with Address => System'To_Address (MU_Base + 16#4c#), Import, Volatile; MU_LSR : Unsigned_32 with Address => System'To_Address (MU_Base + 16#54#), Import, Volatile; MU_CNTL : Unsigned_32 with Address => System'To_Address (MU_Base + 16#60#), Import, Volatile; MU_BAUD : Unsigned_32 with Address => System'To_Address (MU_Base + 16#68#), Import, Volatile; -- Mailboxes Mail_Base_Addr : constant := IO_Base + 16#00_b880#; Mail_Read_Reg : Unsigned_32 with Address => System'To_Address (Mail_Base_Addr + 16#00#), Volatile, Import; Mail_Status_Reg : Unsigned_32 with Address => System'To_Address (Mail_Base_Addr + 16#18#), Volatile, Import; Mail_Write_Reg : Unsigned_32 with Address => System'To_Address (Mail_Base_Addr + 16#20#), Volatile, Import; -- For status: Mail_Empty : constant Unsigned_32 := 16#4000_0000#; -- Cannot read Mail_Full : constant Unsigned_32 := 16#8000_0000#; -- Cannot write -- Peripheral interrupt controller Arm_Interrupt_Base : constant := IO_Base + 16#00_b200#; type Arm_Interrupt_Type is record Irq_Basic_Pending : Unsigned_32; Irq_Pending_1 : Unsigned_32; Irq_Pending_2 : Unsigned_32; Fiq_Control : Unsigned_32; Enable_Irq_1 : Unsigned_32; Enable_Irq_2 : Unsigned_32; Enable_Basic_Irq : Unsigned_32; Disable_Irq_1 : Unsigned_32; Disable_Irq_2 : Unsigned_32; Disable_Basic_Irq : Unsigned_32; end record; Arm_Interrupts : Arm_Interrupt_Type with Import, Volatile, Address => System'To_Address (Arm_Interrupt_Base); -- Peripheral timer type Arm_Timer_Type is record Load : Unsigned_32; Value : Unsigned_32; Ctl : Unsigned_32; Irq_Ack : Unsigned_32; Raw_Irq : Unsigned_32; Masked_Irq : Unsigned_32; Reload : Unsigned_32; Divider : Unsigned_32; Free_Counter : Unsigned_32; end record; Arm_Timer_Base : constant := IO_Base + 16#00_b400#; Arm_Timer : Arm_Timer_Type with Import, Volatile, Address => System'To_Address (Arm_Timer_Base); -- EMMC type EMMC_Registers_Type is record -- At 0x00 ACMD : Unsigned_32; BLKSIZECNT : Unsigned_32; Arg1 : Unsigned_32; CMDTM : Unsigned_32; -- At 0x10 RSP0 : Unsigned_32; RSP1 : Unsigned_32; RSP2 : Unsigned_32; RSP3 : Unsigned_32; -- At 0x20 Data : Unsigned_32; Status : Unsigned_32; Control0 : Unsigned_32; Control1 : Unsigned_32; -- At 0x30 Interrupt : Unsigned_32; IRPT_Mask : Unsigned_32; IRPT_En : Unsigned_32; Control2 : Unsigned_32; -- At 0x40 Pad_40 : Unsigned_32; Pad_44 : Unsigned_32; Pad_48 : Unsigned_32; Pad_4c : Unsigned_32; -- At 0x50 Force_IRPT : Unsigned_32; Pad_54 : Unsigned_32; Pad_58 : Unsigned_32; Pad_5c : Unsigned_32; -- At 0x60 Pad_60 : Unsigned_32; Pad_64 : Unsigned_32; Pad_68 : Unsigned_32; Pad_6c : Unsigned_32; -- At 0x70 Boot_Timeout : Unsigned_32; DBG_Sel : Unsigned_32; Pad_78 : Unsigned_32; Pad_7c : Unsigned_32; -- At 0x80 EXRDFIFO_CFG : Unsigned_32; EXRDFIFO_En : Unsigned_32; Tune_Step : Unsigned_32; Tune_Steps_STD : Unsigned_32; -- At 0x90 Tune_Steps_DDR : Unsigned_32; Pad_94 : Unsigned_32; Pad_98 : Unsigned_32; Pad_9c : Unsigned_32; -- At 0xa0 Pad_a0 : Unsigned_32; Pad_a4 : Unsigned_32; Pad_a8 : Unsigned_32; Pad_ac : Unsigned_32; -- At 0xb0 Pad_b0 : Unsigned_32; Pad_b4 : Unsigned_32; Pad_b8 : Unsigned_32; Pad_bc : Unsigned_32; -- At 0xc0 Pad_c0 : Unsigned_32; Pad_c4 : Unsigned_32; Pad_c8 : Unsigned_32; Pad_cc : Unsigned_32; -- At 0xd0 Pad_d0 : Unsigned_32; Pad_d4 : Unsigned_32; Pad_d8 : Unsigned_32; Pad_dc : Unsigned_32; -- At 0xe0 Pad_e0 : Unsigned_32; Pad_e4 : Unsigned_32; Pad_e8 : Unsigned_32; Pad_ec : Unsigned_32; -- At 0xf0 Spi_Int_Spt : Unsigned_32; Pad_f4 : Unsigned_32; Pad_f8 : Unsigned_32; SlotISR_Ver : Unsigned_32; end record; package EMMC_Bits is -- Status CMD_INHIBIT : constant := 2**0; DAT_INHIBIT : constant := 2**1; -- Control 1 SRST_DATA : constant := 2**26; SRST_CMD : constant := 2**25; SRST_HC : constant := 2**24; CLK_INTLEN : constant := 2**0; CLK_STABLE : constant := 2**1; CLK_EN : constant := 2**2; -- Interrupt CMD_DONE : constant := 2**0; DATA_DONE : constant := 2**1; WRITE_RDY : constant := 2**4; READ_RDY : constant := 2**5; ERR : constant := 2**15; end EMMC_Bits; EMMC_Base : constant := IO_Base + 16#30_0000#; EMMC : EMMC_Registers_Type with Import, Volatile, Address => System'To_Address (EMMC_Base); -- Mailbox interface with VC package Mailbox_Interfaces is -- Channels Channel_Frame_Buffer : constant Unsigned_32 := 1; Channel_Tags_ARM_To_VC : constant Unsigned_32 := 8; -- Header of message is aligned on 16 bytes, and contains: -- Size : Unsigned_32; -- Code : Unsigned_32; -- Request or answer Request_Code : constant Unsigned_32 := 16#0#; Response_Success : constant Unsigned_32 := 16#8000_0000#; Response_Error : constant Unsigned_32 := 16#8000_0001#; -- The header is then followed by tags and then by a null word: -- Tag : Unsigned_32; -- Size : Unsigned_32; -- In bytes -- Indicator : Unsigned_32; Request_Indicator : constant Unsigned_32 := 0; Response_Indicator : constant Unsigned_32 := 16#8000_0000#; -- Tags Tag_Get_Board_Serial : constant Unsigned_32 := 16#1_0004#; Tag_Get_ARM_Memory : constant Unsigned_32 := 16#1_0005#; Tag_Get_VC_Memory : constant Unsigned_32 := 16#1_0006#; Tag_Get_Power_State : constant Unsigned_32 := 16#2_0001#; Tag_Set_Power_State : constant Unsigned_32 := 16#2_8001#; Tag_Get_Clock_Rate : constant Unsigned_32 := 16#3_0002#; Tag_Allocate_Buffer : constant Unsigned_32 := 16#4_0001#; Tag_Release_Buffer : constant Unsigned_32 := 16#4_8001#; Tag_Blank_Screen : constant Unsigned_32 := 16#4_0002#; Tag_Set_Physical_Size : constant Unsigned_32 := 16#4_8003#; Tag_Set_Virtual_Size : constant Unsigned_32 := 16#4_8004#; Tag_Set_Depth : constant Unsigned_32 := 16#4_8005#; Tag_Get_Pitch : constant Unsigned_32 := 16#4_0008#; -- Power Id Power_Id_SDCard : constant Unsigned_32 := 0; Power_Id_UART0 : constant Unsigned_32 := 1; Power_Id_UART1 : constant Unsigned_32 := 2; Power_Id_USB : constant Unsigned_32 := 3; Power_Id_I2C0 : constant Unsigned_32 := 4; Power_Id_I2C1 : constant Unsigned_32 := 5; Power_Id_I2C2 : constant Unsigned_32 := 6; Power_Id_SPI : constant Unsigned_32 := 7; Power_Id_CCP2TX : constant Unsigned_32 := 8; -- Clocks Id Clock_Id_EMMC : constant Unsigned_32 := 1; Clock_Id_UART : constant Unsigned_32 := 2; Clock_Id_ARM : constant Unsigned_32 := 3; Clock_Id_Core : constant Unsigned_32 := 4; Clock_Id_V3D : constant Unsigned_32 := 5; Clock_Id_H264 : constant Unsigned_32 := 6; Clock_Id_ISP : constant Unsigned_32 := 7; Clock_Id_SDRAM : constant Unsigned_32 := 8; Clock_Id_PIXEL : constant Unsigned_32 := 9; Clock_Id_PWM : constant Unsigned_32 := 10; end Mailbox_Interfaces; -- PL011 (UART0) type Pl011_Registers_Type is record DR : Unsigned_32; RSRECR : Unsigned_32; Pad08 : Unsigned_32; Pad0c : Unsigned_32; Pad10 : Unsigned_32; Pad14 : Unsigned_32; FR : Unsigned_32; Pad1c : Unsigned_32; ILPR : Unsigned_32; IBRD : Unsigned_32; FBRD : Unsigned_32; LCRH : Unsigned_32; CR : Unsigned_32; IFLS : Unsigned_32; IMSC : Unsigned_32; RIS : Unsigned_32; MIS : Unsigned_32; ICR : Unsigned_32; DMACR : Unsigned_32; Pad4c : Unsigned_32; end record; PL011_Base : constant := IO_Base + 16#20_1000#; PL011_Registers : Pl011_Registers_Type with Address => System'To_Address (PL011_Base), Volatile, Import; package PL011_Bits is FR_TXFF : constant := 2**5; FR_RXFE : constant := 2**4; FR_BUSY : constant := 2**3; MASK_RT : constant := 2**6; MASK_TX : constant := 2**5; MASK_RX : constant := 2**4; end PL011_Bits; end Interfaces.Raspberry_Pi;
with Vectors2D; use Vectors2D; with Materials; use Materials; with Interfaces; use Interfaces; package Entities is -- Lists all the entity types type EntityTypes is (EntCircle, EntRectangle); -- Required for layering subtype Byte is Unsigned_8; -- Abstract superclass of all entities -- Lists the minimum fields for an entity to exist type Entity is abstract tagged record EntityType : EntityTypes; Coords : Vec2D := (0.0, 0.0); Velocity : Vec2D := (0.0, 0.0); Force : Vec2D := (0.0, 0.0); InvMass : Float; Mass : Float; Mat : Material; Gravity : Vec2D := (0.0, 0.0); Layer : Byte := 2#00000001#; end record; pragma Pack (Entity); type EntityClassAcc is access all Entity'Class; -- Frees the entity procedure FreeEnt(This : access Entity) is abstract; -- Apply a force to the entity procedure ApplyForce(This : in out Entity; Force : Vec2D); -- Update material procedure ChangeMaterial(This : in out Entity'Class; NewMat : Material); -- Get distance between two entities function GetDistance(A, B : in Entity'Class) return Float; procedure SetGravity(This : in out Entity; Grav : Vec2D); procedure SetLayer(This : in out Entity; Lay : Byte); -- Gets the center position of an entity function GetPosition(This : in Entity) return Vec2D is abstract; procedure AddLayer(This : in out Entity; Lay : Byte); -- This must be implemented in each new entity class -- It converts the Material data into an inverse mass float procedure ComputeMass(This : in out Entity) is abstract; procedure Initialize(This : out Entity; EntType : in EntityTypes; Pos, Vel, Grav : in Vec2D; Mat : in Material); end Entities;
-- -- The following uses 32+ decimal digit rational polynomial -- approximations of the log_gamma function on [1,3], derived -- from John Maddock's extended precision -- (Boost Library) gamma function, so let's use the Boost License. -- Many thanks are due to John Maddock. -------------------------------------------------------------------------- --(C) Copyright John Maddock 2006. --Use, modification and distribution are subject to the --Boost Software License, Version 1.0. (See accompanying file --LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -- --Boost Software License - Version 1.0 - August 17th, 2003 -- --Permission is hereby granted, free of charge, to any person or organization --obtaining a copy of the software and accompanying documentation covered by --this license (the "Software") to use, reproduce, display, distribute, --execute, and transmit the Software, and to prepare derivative works of the --Software, and to permit third-parties to whom the Software is furnished to --do so, all subject to the following: -- --The copyright notices in the Software and this entire statement, including --the above license grant, this restriction and the following disclaimer, --must be included in all copies of the Software, in whole or in part, and --all derivative works of the Software, unless such copies or derivative --works are solely in the form of machine-executable object code generated by --a source language processor. -- --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, TITLE AND NON-INFRINGEMENT. IN NO EVENT --SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE --FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, --ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER --DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------- package body Gamma_1_to_3 is Zero : constant Real := +0.0; One : constant Real := +1.0; Two : constant Real := +2.0; Three : constant Real := +3.0; ----------------------- -- Log_Gamma_1_to_3 -- ----------------------- -- Rational poly coefficients. type Remez_Coeff_Range is range 1..13; type Remez_Rational_Poly is array(Remez_Coeff_Range) of Real; Y_1_to_1pt35 : constant Real := +0.54076099395751953125; Numerator_Log_Gamma_1_to_1pt35 : constant Remez_Rational_Poly := ( 0.036454670944013329356512090082402429697, -0.066235835556476033710068679907798799959, -0.67492399795577182387312206593595565371, -1.4345555263962411429855341651960000166, -1.4894319559821365820516771951249649563, -0.87210277668067964629483299712322411566, -0.29602090537771744401524080430529369136, -0.0561832587517836908929331992218879676, -0.0053236785487328044334381502530383140443, -0.00018629360291358130461736386077971890789, -0.10164985672213178500790406939467614498e-6, 0.13680157145361387405588201461036338274e-8, 0.0 ); Denominator_Log_Gamma_1_to_1pt35 : constant Remez_Rational_Poly := ( 1.0, 4.9106336261005990534095838574132225599, 10.258804800866438510889341082793078432, 11.88588976846826108836629960537466889, 8.3455000546999704314454891036700998428, 3.6428823682421746343233362007194282703, 0.97465989807254572142266753052776132252, 0.15121052897097822172763084966793352524, 0.012017363555383555123769849654484594893, 0.0003583032812720649835431669893011257277, 0.0, 0.0, 0.0 ); Y_1pt35_to_1pt625 : constant Real := +0.483787059783935546875; Numerator_Log_Gamma_1pt35_to_1pt625 : constant Remez_Rational_Poly := ( -0.017977422421608624353488126610933005432, 0.18484528905298309555089509029244135703, -0.40401251514859546989565001431430884082, 0.40277179799147356461954182877921388182, -0.21993421441282936476709677700477598816, 0.069595742223850248095697771331107571011, -0.012681481427699686635516772923547347328, 0.0012489322866834830413292771335113136034, -0.57058739515423112045108068834668269608e-4, 0.8207548771933585614380644961342925976e-6, 0.0, 0.0, 0.0 ); Denominator_Log_Gamma_1pt35_to_1pt625 : constant Remez_Rational_Poly := ( 1.0, -2.9629552288944259229543137757200262073, 3.7118380799042118987185957298964772755, -2.5569815272165399297600586376727357187, 1.0546764918220835097855665680632153367, -0.26574021300894401276478730940980810831, 0.03996289731752081380552901986471233462, -0.0033398680924544836817826046380586480873, 0.00013288854760548251757651556792598235735, -0.17194794958274081373243161848194745111e-5, 0.0, 0.0, 0.0 ); Y_1pt625_to_2 : constant Real := +0.443811893463134765625; Numerator_Log_Gamma_1pt625_to_2 : constant Remez_Rational_Poly := ( -0.021027558364667626231512090082402429494, 0.15128811104498736604523586803722368377, -0.26249631480066246699388544451126410278, 0.21148748610533489823742352180628489742, -0.093964130697489071999873506148104370633, 0.024292059227009051652542804957550866827, -0.0036284453226534839926304745756906117066, 0.0002939230129315195346843036254392485984, -0.11088589183158123733132268042570710338e-4, 0.13240510580220763969511741896361984162e-6, 0.0, 0.0, 0.0 ); Denominator_Log_Gamma_1pt625_to_2 : constant Remez_Rational_Poly := ( 1.0, -2.4240003754444040525462170802796471996, 2.4868383476933178722203278602342786002, -1.4047068395206343375520721509193698547, 0.47583809087867443858344765659065773369, -0.09865724264554556400463655444270700132, 0.012238223514176587501074150988445109735, -0.00084625068418239194670614419707491797097, 0.2796574430456237061420839429225710602e-4, -0.30202973883316730694433702165188835331e-6, 0.0, 0.0, 0.0 ); Y_2_to_3 : constant Real := +0.158963680267333984375; Numerator_Log_Gamma_2_to_3 : constant Remez_Rational_Poly := ( -0.018035568567844937910504030027467476655, 0.013841458273109517271750705401202404195, 0.062031842739486600078866923383017722399, 0.052518418329052161202007865149435256093, 0.01881718142472784129191838493267755758, 0.0025104830367021839316463675028524702846, -0.00021043176101831873281848891452678568311, -0.00010249622350908722793327719494037981166, -0.11381479670982006841716879074288176994e-4, -0.49999811718089980992888533630523892389e-6, -0.70529798686542184668416911331718963364e-8, 0.0, 0.0 ); Denominator_Log_Gamma_2_to_3 : constant Remez_Rational_Poly := ( 1.0, 2.5877485070422317542808137697939233685, 2.8797959228352591788629602533153837126, 1.8030885955284082026405495275461180977, 0.69774331297747390169238306148355428436, 0.17261566063277623942044077039756583802, 0.02729301254544230229429621192443000121, 0.0026776425891195270663133581960016620433, 0.00015244249160486584591370355730402168106, 0.43997034032479866020546814475414346627e-5, 0.46295080708455613044541885534408170934e-7, -0.93326638207459533682980757982834180952e-11, 0.42316456553164995177177407325292867513e-13 ); function Log_Gamma_1_to_3 (x : in Real) return Real is Result, Arg : Real := Zero; R, c : Real; -- Evaluate P(n) x^n + P(n-1) x^(n-1) + ... + P(0): function Remez_Poly_Sum (x : in Real; P : Remez_Rational_Poly) return Real is Sum : Real := Zero; begin for j in reverse Remez_Coeff_Range loop Sum := Sum * x + P(j); end loop; return Sum; end Remez_Poly_Sum; begin if x > Three then raise Constraint_Error; end if; if x >= Two then -- x in [2,3): -- Log_Gamma(x) := (x-2)(x+1)(Y + R(x-2)) Arg := x - Two; R := Remez_Poly_Sum (Arg, Numerator_Log_Gamma_2_to_3) / Remez_Poly_Sum (Arg, Denominator_Log_Gamma_2_to_3); c := Arg * (x + One); Result := c * Y_2_to_3 + c * R; elsif x > (+1.625) then -- x in (1.625, 2.0]: -- Log_Gamma(z) := (2-x)(1-x)(Y + R(2-x)) Arg := Two - x; R := Remez_Poly_Sum (Arg, Numerator_Log_Gamma_1pt625_to_2) / Remez_Poly_Sum (Arg, Denominator_Log_Gamma_1pt625_to_2); c := Arg * (One - x); Result := c * Y_1pt625_to_2 + c * R; elsif x > (+1.35) then -- x in (1.35, 1.625]: -- Log_Gamma(x) := (x-1)(x-2)(Y + R(1.625 - x)) Arg := +1.625 - x; R := Remez_Poly_Sum (Arg, Numerator_Log_Gamma_1pt35_to_1pt625) / Remez_Poly_Sum (Arg, Denominator_Log_Gamma_1pt35_to_1pt625); c := (x - One) * (x - Two); Result := c * Y_1pt35_to_1pt625 + c * R; elsif x >= One then -- x in [1,1.35]: -- Log_Gamma(x) := (x-1)(x-2)(Y + R(x-1)) Arg := x - One; R := Remez_Poly_Sum (Arg, Numerator_Log_Gamma_1_to_1pt35) / Remez_Poly_Sum (Arg, Denominator_Log_Gamma_1_to_1pt35); c := Arg * (x - Two); Result := c * Y_1_to_1pt35 + c * R; else raise Constraint_Error; -- or Argument_Error? end if; return Result; end Log_Gamma_1_to_3; end Gamma_1_to_3;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. with Apsepp.Output; package body Apsepp.Debug_Trace_Class.Output is ---------------------------------------------------------------------------- overriding procedure Trace (Obj : in out Debug_Trace_Output; Message : String; Entity_Name : String := "") is begin Apsepp.Output.Output.Put_Line (if Entity_Name'Length /= 0 then Debug_Trace_Output'Class (Obj).Message_W_Entity (Message, Entity_Name) else Message); end Trace; ---------------------------------------------------------------------------- end Apsepp.Debug_Trace_Class.Output;
pragma License (Unrestricted); -- implementation unit specialized for Darwin with C; function System.Environment_Block return C.char_ptr_ptr; pragma Preelaborate (System.Environment_Block); pragma Inline (System.Environment_Block);
-- AOC, Day 4 with Ada.Text_IO; use Ada.Text_IO; with Password; procedure main is first : constant Natural := 134564; last : constant Natural := 585159; begin put_line("Part 1: " & Positive'Image(Password.part1_count(first, last))); put_line("Part 2: " & Positive'Image(Password.part2_count(first, last))); end main;
package Hailstones is type Integer_Sequence is array(Positive range <>) of Integer; function Create_Sequence (N : Positive) return Integer_Sequence; end Hailstones;
package Operation is type NaturalDouble is range -1 .. +(2 ** 63 - 1); type OperationMethod is access function(Left: NaturalDouble; Right: NaturalDouble) return NaturalDouble; function Add (Left: NaturalDouble; Right: NaturalDouble) return NaturalDouble; function Multiple (Left: NaturalDouble; Right: NaturalDouble) return NaturalDouble; end Operation;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- G N A T . E X C E P T I O N _ T R A C E S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2000-2010, 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 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. -- -- -- -- -- -- -- -- -- -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ -- This package provides an interface allowing to control *automatic* output -- to standard error upon exception occurrences (as opposed to explicit -- generation of traceback information using GNAT.Traceback). -- This output includes the basic information associated with the exception -- (name, message) as well as a backtrace of the call chain at the point -- where the exception occurred. This backtrace is only output if the call -- chain information is available, depending if the binder switch dedicated -- to that purpose has been used or not. -- The default backtrace is in the form of absolute code locations which may -- be converted to corresponding source locations using the addr2line utility -- or from within GDB. Please refer to GNAT.Traceback for information about -- what is necessary to be able to exploit this possibility. -- The backtrace output can also be customized by way of a "decorator" which -- may return any string output in association with a provided call chain. -- The decorator replaces the default backtrace mentioned above. with GNAT.Traceback; use GNAT.Traceback; package GNAT.Exception_Traces is -- The following defines the exact situations in which raises will -- cause automatic output of trace information. type Trace_Kind is (Every_Raise, -- Denotes the initial raise event for any exception occurrence, either -- explicit or due to a specific language rule, within the context of a -- task or not. Unhandled_Raise -- Denotes the raise events corresponding to exceptions for which there -- is no user defined handler, in particular, when a task dies due to an -- unhandled exception. ); -- The following procedures can be used to activate and deactivate -- traces identified by the above trace kind values. procedure Trace_On (Kind : Trace_Kind); -- Activate the traces denoted by Kind procedure Trace_Off; -- Stop the tracing requested by the last call to Trace_On. -- Has no effect if no such call has ever occurred. -- The following provide the backtrace decorating facilities type Traceback_Decorator is access function (Traceback : Tracebacks_Array) return String; -- A backtrace decorator is a function which returns the string to be -- output for a call chain provided by way of a tracebacks array. procedure Set_Trace_Decorator (Decorator : Traceback_Decorator); -- Set the decorator to be used for future automatic outputs. Restore -- the default behavior (output of raw addresses) if the provided -- access value is null. -- -- Note: GNAT.Traceback.Symbolic.Symbolic_Traceback may be used as the -- Decorator, to get a symbolic traceback. This will cause a significant -- cpu and memory overhead. end GNAT.Exception_Traces;
----------------------------------------------------------------------- -- awa-tags-components -- Tags component -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Beans.Objects; with Util.Strings.Vectors; with EL.Expressions; with ASF.Components.Html.Forms; with ASF.Contexts.Faces; with ASF.Contexts.Writer; with ASF.Events.Faces; with ASF.Factory; with AWA.Tags.Models; -- == HTML components == -- -- === Displaying a list of tags === -- The <tt>awa:tagList</tt> component displays a list of tags. Each tag can be rendered as -- a link if the <tt>tagLink</tt> attribute is defined. The list of tags is passed in the -- <tt>value</tt> attribute. When rending that list, the <tt>var</tt> attribute is used to -- setup a variable with the tag value. The <tt>tagLink</tt> attribute is then evaluated -- against that variable and the result defines the link. -- -- <awa:tagList value='#{questionList.tags}' id='qtags' styleClass="tagedit-list" -- tagLink="#{contextPath}/questions/tagged.html?tag=#{tagName}" -- var="tagName" -- tagClass="tagedit-listelement tagedit-listelement-old"/> -- -- === Tag editing === -- The <tt>awa:tagList</tt> component allows to add or remove tags associated with a given -- database entity. The tag management works with the jQuery plugin <b>Tagedit</b>. For this, -- the page must include the <b>/js/jquery.tagedit.js</b> Javascript resource. -- -- The tag edition is active only if the <tt>awa:tagList</tt> component is placed within an -- <tt>h:form</tt> component. The <tt>value</tt> attribute defines the list of tags. This must -- be a <tt>Tag_List_Bean</tt> object. -- -- <awa:tagList value='#{question.tags}' id='qtags' -- autoCompleteUrl='#{contextPath}/questions/lists/tag-search.html'/> -- -- When the form is submitted and validated, the procedure <tt>Set_Added</tt> and -- <tt>Set_Deleted</tt> are called on the value bean with the list of tags that were -- added and removed. These operations are called in the <tt>UPDATE_MODEL_VALUES</tt> -- phase (ie, before calling the action's bean operation). -- -- === Tag cloud === -- The <tt>awa:tagCloud</tt> component displays a list of tags as a tag cloud. -- The tags list passed in the <tt>value</tt> attribute must inherit from the -- <tt>Tag_Info_List_Bean</tt> type which indicates for each tag the number of -- times it is used. -- -- <awa:tagCloud value='#{questionTagList}' id='cloud' styleClass="tag-cloud" -- var="tagName" rows="30" -- tagLink="#{contextPath}/questions/tagged.html?tag=#{tagName}" -- tagClass="tag-link"/> -- package AWA.Tags.Components is use ASF.Contexts.Writer; -- Get the Tags component factory. function Definition return ASF.Factory.Factory_Bindings_Access; -- ------------------------------ -- Input component -- ------------------------------ -- The AWA input component overrides the ASF input component to build a compact component -- that displays a label, the input field and the associated error message if necessary. -- -- The generated HTML looks like: -- -- <ul class='taglist'> -- <li><span>tag</span></li> -- </ul> -- -- or -- -- <input type='text' name='' value='tag'/> -- type Tag_UIInput is new ASF.Components.Html.Forms.UIInput with record -- List of tags that have been added. Added : Util.Strings.Vectors.Vector; -- List of tags that have been removed. Deleted : Util.Strings.Vectors.Vector; -- True if the submitted values are correct. Is_Valid : Boolean := False; end record; type Tag_UIInput_Access is access all Tag_UIInput'Class; -- Returns True if the tag component must be rendered as readonly. function Is_Readonly (UI : in Tag_UIInput; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean; -- Get the tag after convertion with the optional converter. function Get_Tag (UI : in Tag_UIInput; Tag : in Util.Beans.Objects.Object; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the tag as a readonly item. procedure Render_Readonly_Tag (UI : in Tag_UIInput; Tag : in Util.Beans.Objects.Object; Class : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tag as a link. procedure Render_Link_Tag (UI : in Tag_UIInput; Name : in String; Tag : in Util.Beans.Objects.Object; Link : in EL.Expressions.Expression; Class : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tag for an input form. procedure Render_Form_Tag (UI : in Tag_UIInput; Id : in String; Tag : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- a link is rendered for each tag. Otherwise, each tag is rendered as a <tt>span</tt>. procedure Render_Readonly (UI : in Tag_UIInput; List : in Util.Beans.Basic.List_Bean_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the list of tags for a form. procedure Render_Form (UI : in Tag_UIInput; List : in Util.Beans.Basic.List_Bean_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the javascript to enable the tag edition. procedure Render_Script (UI : in Tag_UIInput; Id : in String; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the input component. Starts the DL/DD list and write the input -- component with the possible associated error message. overriding procedure Encode_Begin (UI : in Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the end of the input component. Closes the DL/DD list. overriding procedure Encode_End (UI : in Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Get the action method expression to invoke if the command is pressed. function Get_Action_Expression (UI : in Tag_UIInput; Context : in ASF.Contexts.Faces.Faces_Context'Class) return EL.Expressions.Method_Expression; -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. overriding procedure Process_Decodes (UI : in out Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> overriding procedure Process_Updates (UI : in out Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. overriding procedure Broadcast (UI : in out Tag_UIInput; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Tag Cloud Component -- ------------------------------ -- The tag cloud component type Tag_UICloud is new ASF.Components.Html.UIHtmlComponent with null record; type Tag_Info_Array is array (Positive range <>) of AWA.Tags.Models.Tag_Info; type Tag_Info_Array_Access is access all Tag_Info_Array; -- Render the tag cloud component. overriding procedure Encode_Children (UI : in Tag_UICloud; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Compute the weight for each tag in the list according to the <tt>minWeight</tt> and -- <tt>maxWeight</tt> attributes. The computed weight is an integer multiplied by 100 -- and will range from 100x<i>minWeight</i> and 100x<i>maxWeight</i>. procedure Compute_Cloud_Weight (UI : in Tag_UICloud; List : in out Tag_Info_Array; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the list of tags. If the <tt>tagLink</tt> attribute is defined, a link -- is rendered for each tag. procedure Render_Cloud (UI : in Tag_UICloud; List : in Tag_Info_Array; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end AWA.Tags.Components;
with Ada.Numerics.Discrete_Random; with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure Upg2 is function Generate return Integer is subtype Nums is Integer range 0..99; package RN is new Ada.Numerics.Discrete_Random(Nums); Gen : RN.Generator; begin RN.Reset(Gen); return RN.Random(Gen); end; type Data_Type is record Name: String(1..20); Len: Integer; end record; type StringArray_Type is array(1..5) of Data_Type; Revolvers : StringArray_Type; begin Put("Mata in revolvrar:"); New_Line; for I in StringArray_Type'Range loop Get_Line(Revolvers(I).Name,Revolvers(I).Len); end loop; New_Line; Put("Nya Priser:"); New_Line; for X in reverse StringArray_Type'Range loop Put(Revolvers(X).Name(1..Revolvers(X).Len)); Put(" - $"); Put(Generate,1); Put(".99"); New_Line; end loop; end;
with Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Text_IO; procedure Fich_1 is package ASU renames Ada.Strings.Unbounded; Fich : Ada.Text_IO.File_Type; S : ASU.Unbounded_String; T : ASU.Unbounded_String; begin -- Abre fichero prueba.tmp Open(Fich, Ada.Text_IO.Out_File, "prueba.tmp"); S := ASU.To_Unbounded_String(Ada.Text_IO.Get_Line(Fich)); Put(ASU.To_String(S)); New_Line; T := ASU.To_Unbounded_String(Ada.Text_IO.Get_Line(Fich)); New_Line; Put(ASU.To_String(T));New_Line; Close(Fich); -- Cierro el fichero -- CREA Create(Fich, Out_File, "prueba3.txt"); Put_Line(Fich, "esto es una linea"); Put_Line(Fich, "esto es la segunda linea"); Close(Fich); -- ANYADE Open(Fich, Append_File, "prueba3.txt"); Put_Line(Fich, "esto es la tercera linea"); S := ASU.To_Unbounded_String(Ada.Text_IO.Get_Line(Fich)); -- da error, ya que estamos en modo escritura, no lectura Put(ASU.To_String(S)); New_Line; Close(Fich); end Fich_1;
with Lumen.Window; with Lumen.Events; with Lumen.Events.Animate; with GL; with GLU; procedure OpenGL is The_Window : Lumen.Window.Handle; Program_Exit : Exception; -- simply exit this program procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is begin raise Program_Exit; end; -- Resize the scene procedure Resize_Scene (Width, Height : in Natural) is use GL; use GLU; begin -- reset current viewport glViewport (0, 0, GLsizei (Width), GLsizei (Height)); -- select projection matrix and reset it glMatrixMode (GL_PROJECTION); glLoadIdentity; -- calculate aspect ratio gluPerspective (45.0, GLdouble (Width) / GLdouble (Height), 0.1, 100.0); -- select modelview matrix and reset it glMatrixMode (GL_MODELVIEW); glLoadIdentity; end Resize_Scene; procedure Init_GL is use GL; use GLU; begin -- smooth shading glShadeModel (GL_SMOOTH); -- black background glClearColor (0.0, 0.0, 0.0, 0.0); -- depth buffer setup glClearDepth (1.0); -- enable depth testing glEnable (GL_DEPTH_TEST); -- type of depth test glDepthFunc (GL_LEQUAL); glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); end Init_GL; -- Resize and Initialize the GL window procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is Height : Natural := Event.Resize_Data.Height; Width : Natural := Event.Resize_Data.Width; begin -- prevent div by zero if Height = 0 then Height := 1; end if; Resize_Scene (Width, Height); end; procedure Draw is use GL; begin -- clear screen and depth buffer glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); -- reset current modelview matrix glLoadIdentity; -- draw triangle glBegin (GL_TRIANGLES); glColor3f (1.0, 0.0, 0.0); glVertex3f ( 0.0, 1.0, 0.0); glColor3f (0.0, 1.0, 0.0); glVertex3f (-1.0, -1.0, 0.0); glColor3f (0.0, 0.0, 1.0); glVertex3f ( 1.0, -1.0, 0.0); glEnd; end Draw; procedure Frame_Handler (Frame_Delta : in Duration) is begin Draw; Lumen.Window.Swap (The_Window); end Frame_Handler; begin Lumen.Window.Create (Win => The_Window, Name => "OpenGL Demo", Width => 640, Height => 480, Events => (Lumen.Window.Want_Key_Press => True, Lumen.Window.Want_Exposure => True, others => False)); Resize_Scene (640, 480); Init_GL; Lumen.Events.Animate.Select_Events (Win => The_Window, FPS => Lumen.Events.Animate.Flat_Out, Frame => Frame_Handler'Unrestricted_Access, Calls => (Lumen.Events.Resized => Resize_Handler'Unrestricted_Access, Lumen.Events.Close_Window => Quit_Handler'Unrestricted_Access, others => Lumen.Events.No_Callback)); exception when Program_Exit => null; -- normal termination end OpenGL;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $: with Asis.Errors; with Asis.Exceptions; with Asis.Implementation; package body Asis.Gela.Base_Lists is function Is_Pragma (Item : Asis.Element) return Boolean; --------- -- Add -- --------- procedure Add (Container : in out Primary_Base_List_Node; Item : in Element) is use ER_Element_Lists; Item_Pos : constant Text_Position := End_Position (Item.all); List_Pos : Text_Position; begin if Length (Container) > 0 then List_Pos := Start_Position (First (Container.Content).all); else List_Pos := Start_Position (Container); end if; Set_Start_Position (Container, Start_Position (Item.all)); Set_End_Position (Container, End_Position (Item.all)); if List_Pos < Item_Pos or else Item_Pos = Nil_Text_Position Then Append (Container.Content, Item); else Prepend (Container.Content, Item); end if; Container.Last_Index := 0; Container.Length := Container.Length + 1; end Add; --------------- -- Add_After -- --------------- procedure Add_After (Container : in out Primary_Base_List_Node; Target : in Element; Item : in Element) is use ER_Element_Lists; begin Set_Start_Position (Container, Start_Position (Item.all)); Set_End_Position (Container, End_Position (Item.all)); if not Assigned (Target) then Prepend (Container.Content, Item); else Insert_After (Container.Content, Target, Item); end if; Container.Last_Index := 0; Container.Length := Container.Length + 1; end Add_After; --------------------- -- Check_Item_Kind -- --------------------- procedure Check_Item_Kind (Item : in Element; Allowed : in Element_Kind_List) is Kind : constant Element_Kinds := Element_Kind (Item.all); begin for I in Allowed'Range loop if Kind = Allowed (I) then return; end if; end loop; Implementation.Set_Status (Asis.Errors.Internal_Error, "Check_Item_Kind: " & Element_Kinds'Wide_Image (Kind)); raise Exceptions.ASIS_Inappropriate_Element; end Check_Item_Kind; ----------- -- Clone -- ----------- function Clone (Item : Primary_Base_List_Node; Parent : Asis.Element) return Asis.Element is begin return Asis.Nil_Element; end Clone; ------------------ -- Element_Kind -- ------------------ function Element_Kind (Element : in Primary_Base_List_Node) return Element_Kinds is begin return Not_An_Element; end Element_Kind; ------------------ -- End_Position -- ------------------ function End_Position (Element : Primary_Base_List_Node) return Text_Position is use ER_Element_Lists; begin return Element.End_Position; end End_Position; ---------- -- Find -- ---------- function Find (Container : Primary_Base_List_Node; Item : Element) return Boolean is use ER_Element_Lists; Next : aliased Asis.Element; begin while Iterate (Container.Content, Next'Access) loop if Is_Equal (Next, Item) then return True; end if; end loop; return False; end Find; -------------- -- Get_Item -- -------------- function Get_Item (Item : access Primary_Base_List_Node; Index : Positive) return Element is use ER_Element_Lists; begin if Index not in 1 .. Item.Length then raise Constraint_Error; elsif Item.Last_Index = 0 then Item.Last_Index := 1; Item.Last_Item := First (Item.Content); end if; loop if Item.Last_Index = Index then return Item.Last_Item; elsif Item.Last_Index = Item.Length then Item.Last_Index := 1; Item.Last_Item := First (Item.Content); else Item.Last_Index := Item.Last_Index + 1; Item.Last_Item := Get_Next (Item.Last_Item); end if; end loop; return Nil_Element; end Get_Item; -------------- -- Get_Next -- -------------- function Get_Next (Item : Element) return Element is begin return Next_Element (Item.all); end Get_Next; -------------- -- Get_Next -- -------------- function Get_Next (Item : Primary_Base_List_Node) return Element is begin return Nil_Element; end Get_Next; ------------- -- Is_List -- ------------- function Is_List (Item : Primary_Base_List_Node) return Boolean is begin return True; end Is_List; --------------- -- Is_Pragma -- --------------- function Is_Pragma (Item : Asis.Element) return Boolean is begin return Element_Kind (Item.all) = A_Pragma; end Is_Pragma; ------------ -- Length -- ------------ function Length (Item : Primary_Base_List_Node) return Natural is begin return Item.Length; end Length; ------------ -- Remove -- ------------ procedure Remove (Container : in out Primary_Base_List_Node; Item : in Element) is begin ER_Element_Lists.Delete (Container.Content, Item); Container.Last_Index := 0; Container.Length := Container.Length - 1; end Remove; --------------------- -- Secondary_Lists -- --------------------- package body Secondary_Lists is --------- -- Add -- --------- procedure Add (Container : in out List_Node; Item : in Element) is use Element_Lists; Item_Pos : constant Text_Position := Start_Position (Item.all); begin Check_Item_Kind (Item, Allowed); if Is_Empty (Container) or else End_Position (Last_Element (Container).all) < Item_Pos then Append (List (Container), Item); else Prepend (List (Container), Item); end if; end Add; --------- -- Get -- --------- function Get (Item : List_Node; Index : Positive) return Asis.Element is use Element_Lists; Ptr : Cursor := First (Item); begin for J in 2 .. Index loop Ptr := Next (Ptr); end loop; return Element_Lists.Element (Ptr); end Get; ------------ -- Length -- ------------ function Length (Item : List_Node) return Natural is use Element_Lists; Result : Natural := 0; Ptr : Cursor := First (Item); begin while Has_Element (Ptr) loop Result := Result + 1; Ptr := Next (Ptr); end loop; return Result; end Length; ------------ -- Remove -- ------------ procedure Remove (Container : in out List_Node; Item : in Element) is use Element_Lists; Ptr : Cursor := Find (Container, Item); begin if Has_Element (Ptr) then Delete (Container, Ptr); end if; end Remove; --------- -- Set -- --------- procedure Set (Container : in out List_Node; Items : in Element_List) is begin Clear (Container); for I in Items'Range loop Add (Container, Items (I)); end loop; end Set; ------------------------------ -- To_Compilation_Unit_List -- ------------------------------ function To_Compilation_Unit_List (Item : List_Node) return Asis.Compilation_Unit_List is List : constant Asis.Element_List := To_Element_List (Item); Result : Compilation_Unit_List (List'Range); begin for I in List'Range loop Result (I) := Compilation_Unit (List (I)); end loop; return Result; end To_Compilation_Unit_List; --------------------- -- To_Element_List -- --------------------- function To_Element_List (Item : List_Node) return Asis.Element_List is begin return To_Element_List (Item, True); end To_Element_List; --------------------- -- To_Element_List -- --------------------- function To_Element_List (Item : List_Node; Include_Pragmas : Boolean) return Asis.Element_List is use Element_Lists; Result : Asis.Element_List (1 .. ASIS_Natural (Length (Item))); Index : ASIS_Natural := 0; Temp : Asis.Element; Ptr : Cursor := First (Item); begin while Has_Element (Ptr) loop Temp := Element_Lists.Element (Ptr); if Include_Pragmas or else not Is_Pragma (Temp) then Index := Index + 1; Result (Index) := Temp; end if; Ptr := Next (Ptr); end loop; return Result (1 .. Index); end To_Element_List; -------------------- -- To_Pragma_List -- -------------------- function To_Pragma_List (Item : List_Node) return Asis.Element_List is use Element_Lists; Result : Asis.Element_List (1 .. ASIS_Natural (Length (Item))); Index : ASIS_Natural := 0; Temp : Asis.Element; Ptr : Cursor := First (Item); begin while Has_Element (Ptr) loop Temp := Element_Lists.Element (Ptr); if Is_Pragma (Temp) then Index := Index + 1; Result (Index) := Temp; end if; Ptr := Next (Ptr); end loop; return Result (1 .. Index); end To_Pragma_List; end Secondary_Lists; -------------- -- Set_Next -- -------------- procedure Set_Next (Item, Next : Element) is begin Set_Next_Element (Item.all, Next); end Set_Next; -------------- -- Set_Next -- -------------- procedure Set_Next (Item : in out Primary_Base_List_Node; Next : in Element) is begin null; end Set_Next; ------------------------ -- Set_Start_Position -- ------------------------ procedure Set_Start_Position (Element : in out Primary_Base_List_Node'Class; Value : in Asis.Text_Position) is begin if Length (Element) = 0 or else Value < Element.Start_Position then Element.Start_Position := Value; end if; end Set_Start_Position; ---------------------- -- Set_End_Position -- ---------------------- procedure Set_End_Position (Element : in out Primary_Base_List_Node'Class; Value : in Asis.Text_Position) is begin if Length (Element) = 0 or else Element.End_Position < Value then Element.End_Position := Value; end if; end Set_End_Position; -------------------- -- Start_Position -- -------------------- function Start_Position (Element : Primary_Base_List_Node) return Text_Position is begin return Element.Start_Position; end Start_Position; ------------------------------ -- To_Compilation_Unit_List -- ------------------------------ function To_Compilation_Unit_List (Item : Primary_Base_List_Node) return Asis.Compilation_Unit_List is List : constant Asis.Element_List := To_Element_List (Item); Result : Compilation_Unit_List (List'Range); Last : ASIS_Natural := 0; List_I : Asis.Element; begin for I in List'Range loop List_I := List (I); if List_I.all in Compilation_Unit_Node'Class then Last := Last + 1; Result (Last) := Compilation_Unit (List_I); end if; end loop; return Result (1 .. Last); end To_Compilation_Unit_List; --------------------- -- To_Element_List -- --------------------- function To_Element_List (Item : Primary_Base_List_Node) return Asis.Element_List is begin return To_Element_List (Item, True); end To_Element_List; --------------------- -- To_Element_List -- --------------------- function To_Element_List (Item : Primary_Base_List_Node; Include_Pragmas : Boolean) return Asis.Element_List is use ER_Element_Lists; Result : Asis.Element_List (1 .. ASIS_Natural (Item.Length)); Next : aliased Element; Index : ASIS_Natural := 0; begin while Iterate (Item.Content, Next'Access) loop if Include_Pragmas or else not Is_Pragma (Next) then Index := Index + 1; Result (Index) := Next; end if; end loop; return Result (1 .. Index); end To_Element_List; -------------------- -- To_Pragma_List -- -------------------- function To_Pragma_List (Item : Primary_Base_List_Node) return Asis.Element_List is use ER_Element_Lists; Result : Asis.Element_List (1 .. ASIS_Natural (Item.Length)); Next : aliased Element; Index : ASIS_Natural := 0; begin while Iterate (Item.Content, Next'Access) loop if Is_Pragma (Next) then Index := Index + 1; Result (Index) := Next; end if; end loop; return Result (1 .. Index); end To_Pragma_List; end Asis.Gela.Base_Lists; ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
------------------------------------------------------------------------------ -- Copyright (c) 2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and 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. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Backends provides an interface for stream-based backends -- -- used in web elements. -- -- Even though how parameters are used by implementations is not defined, -- -- the following constraints apply: -- -- * Directory and Name have filesystem-like semantics, in that together -- -- they define a unique stream, but distinct streams can have the same -- -- name in a different directory, or different names in the same -- -- directory. -- -- * Directories can be enumerated to reach all the files it contains. -- ------------------------------------------------------------------------------ with Ada.Streams; with Natools.S_Expressions; package Natools.Web.Backends is pragma Preelaborate; type Backend is interface; function Create (Self : in out Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is abstract; -- Create a new file, which must not exist previously procedure Delete (Self : in out Backend; Directory, Name : in S_Expressions.Atom) is abstract; -- Destroy a file, which must exist previously function Read (Self : in Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is abstract; -- Read the contents of an existing file function Append (Self : in out Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is abstract; -- Return a stream to append data to the given file function Overwrite (Self : in out Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is abstract; -- Reset the given file to empty and return a stream to write on it procedure Iterate (Self : in Backend; Directory : in S_Expressions.Atom; Process : not null access procedure (Name : in S_Expressions.Atom)) is abstract; -- Iterate over all the existing file names in Directory end Natools.Web.Backends;
package Discr36 is type R (D : Boolean := True) is record case D is when True => I : Integer; when False => null; end case; end record; function N return Natural; end Discr36;
-- -- The author disclaims copyright to this source code. In place of -- a legal notice, here is a blessing: -- -- May you do good and not evil. -- May you find forgiveness for yourself and forgive others. -- May you share freely, not taking more than you give. -- package body Symbols is -- package Hex_IO is -- new Ada.Text_IO.Integer_IO (Integer); -- subtype Image_Type is String (1 .. 2); -- function To_Hex (I : Integer) return Image_Type; -- function To_Hex (I : Integer) return Image_Type is -- Image : String (1 .. 10); -- begin -- Hex_IO.Put (Image, I, Base => 16); -- if Image (Image'Last - 2) = '#' then -- Image (Image'Last - 2) := '0'; -- end if; -- return Image (Image'Last - 2 .. Image'Last - 1); -- end To_Hex; -- function HTML_Image (Symbol : Symbol_Type) return String is -- begin -- return "&#x" -- & To_Hex (Character'Pos (Symbol (1))) -- & To_Hex (Character'Pos (Symbol (2))) & ";"; -- end HTML_Image; type Ss_Type is record UTF8 : String (1 .. 3); HTML : String (1 .. 8); end record; ESC : constant Character := Character'Val (16#E2#); List : constant array (Symbol_Type) of Ss_Type := (Space => (" ", "&#x0020;"), Plus_Sign => (" + ", "&#x002B;"), Minus_Sign => (" - ", "&#x2212;"), Multiplication_Sign => (" * ", "&#x00D7;"), Division_Sign => (" / ", "&#x00F7;"), Black_Star => ((ESC & Character'Val (16#98#) & Character'Val (16#85#)), "&#x2605;"), White_Star => ((ESC & Character'Val (16#98#) & Character'Val (16#86#)), "&#x2606;"), Black_Right_Pointing_Index => ((ESC & Character'Val (16#98#) & Character'Val (16#9B#)), "&#x261B;"), White_Right_Pointing_Index => ((ESC & Character'Val (16#98#) & Character'Val (16#9E#)), "&#x261E;"), Check_Mark => ((ESC & Character'Val (16#9C#) & Character'Val (16#93#)), "&#x2713;"), Heavy_Check_Mark => ((ESC & Character'Val (16#9C#) & Character'Val (16#94#)), "&#x2714;"), Multiplication_X => ((ESC & Character'Val (16#9C#) & Character'Val (16#95#)), "&#x2715;"), Heavy_Multiplication_X => ((ESC & Character'Val (16#9C#) & Character'Val (16#96#)), "&#x2716;"), Ballot_X => ((ESC & Character'Val (16#9C#) & Character'Val (16#97#)), "&#x2717;"), Heavy_Ballot_X => ((ESC & Character'Val (16#9C#) & Character'Val (16#98#)), "&#x2718;"), Medium_Left_Parenthesis_Ornament => (" ( ", "&#x2768;"), Medium_Right_Parenthesis_Ornament => (" ) ", "&#x2769;"), Medium_Flattened_Left_Parenthesis_Ornament => (" ( ", "&#x276A;"), Medium_Flattened_Right_Parenthesis_Ornament => (" ) ", "&#x276B;"), Medium_Left_Pointing_Angle_Bracket_Ornament => (" < ", "&#x276C;"), Medium_Right_Pointing_Angle_Bracket_Ornament => (" > ", "&#x276D;")); function UTF8 (Symbol : in Symbol_Type) return String is (List (Symbol).UTF8); function HTML (Symbol : in Symbol_Type) return String is (List (Symbol).HTML); end Symbols;
--***************************************************************************** --* --* PROJECT: BINGADA --* --* FILE: q_sound.adb --* --* AUTHOR: Manuel <mgrojo at github> --* --***************************************************************************** -- External sound library -- with Canberra; with Ada.Directories; with Ada.Strings.Fixed; with Gtkada.Intl; package body Q_Sound is V_Context : Canberra.Context := Canberra.Create (Name => "BingAda", Id => "bingada.lovelace", Icon => "applications-games"); --================================================================== procedure P_Play_Number (V_Number : Positive) is C_Number_Image : constant String := Ada.Strings.Fixed.Trim (V_Number'Image, Ada.Strings.Left); C_Path : constant String := "media/"; C_Extension : constant String := ".ogg"; C_Lang_Code_Last : constant := 2; C_Locale : constant String := Gtkada.Intl.Getlocale; C_Default_Lang : constant String := "en"; V_Lang : String (1 .. C_Lang_Code_Last) := C_Default_Lang; V_Sound : Canberra.Sound; begin if C_Locale'Length >= C_Lang_Code_Last then V_Lang := C_Locale (C_Locale'First .. C_Locale'First + C_Lang_Code_Last - 1); end if; if not Ada.Directories.Exists (C_Path & V_Lang & '/' & C_Number_Image & C_Extension) then V_Lang := C_Default_Lang; end if; V_Context.Play_File (File_Name => C_Path & V_Lang & '/' & C_Number_Image & C_Extension, File_Sound => V_Sound, Kind => Canberra.Music, Name => "Number"); end P_Play_Number; --================================================================== -- Nothing to do in the canberra version -- procedure P_Clean_Up is null; end Q_Sound;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2018, Universidad Politécnica de Madrid -- -- -- -- This 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. This software 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. See the GNU General Public -- -- License for more details. You should have received a copy of the GNU -- -- General Public License distributed with this software; see file -- -- COPYING3. If not, go to http://www.gnu.org/licenses for a complete copy -- -- of the license. -- -- -- ------------------------------------------------------------------------------ with HK_Data; use HK_Data; with Sensor; with Storage; with Ada.Real_Time; use Ada.Real_Time; package body Housekeeping is ------------------------- -- Internal operations -- ------------------------- procedure Read_Data; -- Read a value from a temperature sensor ---------------------------- -- Housekeeping task body -- ---------------------------- task body Housekeeping_Task is -- cyclic Next_Time : Time := Clock + Milliseconds (Start_Delay); begin loop delay until Next_Time; Read_Data; Next_Time := Next_Time + Milliseconds (Period); end loop; end Housekeeping_Task; ---------- -- Read -- ---------- procedure Read_Data is Reading : Sensor_Reading; Data : Sensor_Data; SC : Seconds_Count; TS : Time_Span; begin Sensor.Get (Reading); Split (Clock, SC, TS); Data := (Value => Reading, Timestamp => Mission_Time (SC)); Storage.Put (Data); end Read_Data; end Housekeeping;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with Ada.Unchecked_Deallocation; with FT.Glyphs; with GL.Attributes; with GL.Buffers; with GL.Objects.Framebuffers; with GL.Objects.Shaders; with GL.Objects.Textures.Targets; with GL.Pixels; with GL.Window; with GL.Text.UTF8; package body GL.Text is procedure Load_Vectors is new GL.Objects.Buffers.Load_To_Buffer (GL.Types.Singles.Vector2_Pointers); procedure Create (Object : in out Shader_Program_Reference) is Vertex_Shader : GL.Objects.Shaders.Shader (GL.Objects.Shaders.Vertex_Shader); Fragment_Shader : GL.Objects.Shaders.Shader (GL.Objects.Shaders.Fragment_Shader); Square : constant GL.Types.Singles.Vector2_Array := ((0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)); LF : constant Character := Character'Val (10); begin Object.Id.Initialize_Id; -- shader sources are included here so that the user does not need to -- handle additional resource files bundled with this library. Vertex_Shader.Initialize_Id; Vertex_Shader.Set_Source ("#version 410 core" & LF & "layout(location = 0) in vec2 vertex;" & LF & "uniform vec4 character_info;" & LF & "uniform mat4 transformation;" & LF & "out vec2 texture_coords;" & LF & "void main() {" & LF & " vec2 translated = vec2(" & "character_info.z * vertex.x + character_info.x," & "character_info.w * vertex.y + character_info.y);" & LF & " gl_Position = transformation * vec4(translated, 0.0, 1.0);" & LF & " texture_coords = vec2(vertex.x, 1.0 - vertex.y);" & LF & "}"); Vertex_Shader.Compile; if not Vertex_Shader.Compile_Status then raise Rendering_Error with "could not compile vertex shader:" & Character'Val (10) & Vertex_Shader.Info_Log; end if; Object.Id.Attach (Vertex_Shader); Fragment_Shader.Initialize_Id; Fragment_Shader.Set_Source ("#version 410 core" & LF & "in vec2 texture_coords;" & LF & "layout(location = 0) out float color;" & LF & "uniform sampler2D text_sampler;" & LF & "uniform vec4 text_color;" & LF & "void main() {" & LF & " float alpha = texture(text_sampler, texture_coords).r;" & LF & " color = alpha;" & LF & "}"); Fragment_Shader.Compile; if not Fragment_Shader.Compile_Status then raise Rendering_Error with "could not compile fragment shader: " & Character'Val (10) & Fragment_Shader.Info_Log; end if; Object.Id.Attach (Fragment_Shader); Object.Id.Link; if not Object.Id.Link_Status then raise Rendering_Error with "could not link program:" & Character'Val (10) & Object.Id.Info_Log; end if; GL.Objects.Shaders.Release_Shader_Compiler; Object.Square_Buffer.Initialize_Id; Object.Square_Array.Initialize_Id; Object.Square_Array.Bind; GL.Objects.Buffers.Array_Buffer.Bind (Object.Square_Buffer); Load_Vectors (GL.Objects.Buffers.Array_Buffer, Square, GL.Objects.Buffers.Static_Draw); GL.Attributes.Set_Vertex_Attrib_Pointer (0, 2, GL.Types.Single_Type, False, 0, 0); Object.Info_Id := Object.Id.Uniform_Location ("character_info"); Object.Texture_Id := Object.Id.Uniform_Location ("text_sampler"); Object.Color_Id := Object.Id.Uniform_Location ("text_colour"); Object.Transform_Id := Object.Id.Uniform_Location ("transformation"); end Create; function Created (Object : Shader_Program_Reference) return Boolean is begin return Object.Id.Initialized; end Created; procedure Create (Object : in out Renderer_Reference; Program : Shader_Program_Reference; Face : FT.Faces.Face_Reference) is begin Finalize (Object); Object.Data := new Renderer_Data'(Face => Face, Refcount => 1, Program => Program, Characters => <>); end Create; procedure Create (Object : in out Renderer_Reference; Program : Shader_Program_Reference; Font_Path : UTF_8_String; Face_Index : FT.Faces.Face_Index_Type; Size : Pixel_Size) is Lib : FT.Library_Reference; begin Finalize (Object); Lib.Init; Object.Data := new Renderer_Data; Object.Data.Program := Program; FT.Faces.New_Face (Lib, Font_Path, Face_Index, Object.Data.Face); Object.Data.Face.Set_Pixel_Sizes (0, FT.UInt (Size)); end Create; function Created (Object : Renderer_Reference) return Boolean is begin return Object.Data /= null; end Created; function Character_Data (Object : Renderer_Reference; Code_Point : UTF8.UTF8_Code_Point) return Loaded_Characters.Cursor is use type FT.Position; use type FT.Faces.Char_Index_Type; use type UTF8.UTF8_Code_Point; begin return Ret : Loaded_Characters.Cursor := Object.Data.Characters.Find (FT.ULong (Code_Point)) do if not Loaded_Characters.Has_Element (Ret) then declare Index : constant FT.Faces.Char_Index_Type := Object.Data.Face.Character_Index (FT.ULong (Code_Point)); begin if Index = FT.Faces.Undefined_Character_Code then if Code_Point = Character'Pos ('?') then raise FT.FreeType_Exception with "Font is missing character '?'"; else Ret := Character_Data (Object, Character'Pos ('?')); return; end if; else Object.Data.Face.Load_Glyph (Index, FT.Faces.Load_Render); FT.Glyphs.Render_Glyph (Object.Data.Face.Glyph_Slot, FT.Faces.Render_Mode_Mono); end if; end; declare use GL.Objects.Textures.Targets; New_Data : Loaded_Character; Bitmap : constant FT.Bitmap_Record := FT.Glyphs.Bitmap (Object.Data.Face.Glyph_Slot); Inserted : Boolean; Top : constant Pixel_Difference := Pixel_Difference (FT.Glyphs.Bitmap_Top (Object.Data.Face.Glyph_Slot)); Height : constant Pixel_Difference := Pixel_Difference (Bitmap.Rows); Old_Alignment : constant GL.Pixels.Alignment := GL.Pixels.Unpack_Alignment; begin New_Data.Width := Pixel_Difference (Bitmap.Width); New_Data.Y_Min := Top - Height; New_Data.Y_Max := Top; New_Data.Advance := Pixel_Difference (FT.Glyphs.Advance (Object.Data.Face.Glyph_Slot).X / 64); New_Data.Left := Pixel_Difference (FT.Glyphs.Bitmap_Left (Object.Data.Face.Glyph_Slot)); New_Data.Image.Initialize_Id; Texture_2D.Bind (New_Data.Image); Texture_2D.Set_Minifying_Filter (GL.Objects.Textures.Linear); Texture_2D.Set_Magnifying_Filter (GL.Objects.Textures.Linear); Texture_2D.Set_X_Wrapping (GL.Objects.Textures.Clamp_To_Edge); Texture_2D.Set_Y_Wrapping (GL.Objects.Textures.Clamp_To_Edge); GL.Pixels.Set_Unpack_Alignment (GL.Pixels.Bytes); Texture_2D.Load_From_Data (0, GL.Pixels.Red, GL.Types.Size (Bitmap.Width), GL.Types.Size (Bitmap.Rows), GL.Pixels.Red, GL.Pixels.Unsigned_Byte, GL.Objects.Textures.Image_Source (Bitmap.Buffer)); GL.Pixels.Set_Unpack_Alignment (Old_Alignment); Object.Data.Characters.Insert (FT.ULong (Code_Point), New_Data, Ret, Inserted); end; end if; end return; end Character_Data; procedure Calculate_Dimensions (Object : Renderer_Reference; Content : UTF_8_String; Width : out Pixel_Size; Y_Min : out Pixel_Difference; Y_Max : out Pixel_Size) is Char_Position : Integer := Content'First; Map_Position : Loaded_Characters.Cursor; Code_Point : UTF8.UTF8_Code_Point; begin Width := 0; Y_Min := 0; Y_Max := 0; while Char_Position <= Content'Last loop UTF8.Read (Content, Char_Position, Code_Point); Map_Position := Character_Data (Object, Code_Point); declare Char_Data : constant Loaded_Character := Loaded_Characters.Element (Map_Position); begin Width := Width + Char_Data.Advance; Y_Min := Pixel_Difference'Min (Y_Min, Char_Data.Y_Min); Y_Max := Pixel_Difference'Max (Y_Max, Char_Data.Y_Max); end; end loop; end Calculate_Dimensions; function To_Texture (Object : Renderer_Reference; Content : UTF_8_String; Text_Color : GL.Types.Colors.Color) return GL.Objects.Textures.Texture is Width, Y_Min, Y_Max : Pixel_Difference; begin Object.Calculate_Dimensions (Content, Width, Y_Min, Y_Max); return Object.To_Texture (Content, Width, Y_Min, Y_Max, Text_Color); end To_Texture; function To_Texture (Object : Renderer_Reference; Content : UTF_8_String; Width, Y_Min, Y_Max : Pixel_Difference; Text_Color : GL.Types.Colors.Color) return GL.Objects.Textures.Texture is use type GL.Types.Singles.Matrix4; use type GL.Types.Single; package Fb renames GL.Objects.Framebuffers; package Tx renames GL.Objects.Textures; package Va renames GL.Objects.Vertex_Arrays; FrameBuf : Fb.Framebuffer; Target : GL.Objects.Textures.Texture; Char_Position : Integer := Content'First; Map_Position : Loaded_Characters.Cursor; Code_Point : UTF8.UTF8_Code_Point; X_Offset : Pixel_Difference := 0; Height : constant Pixel_Difference := Y_Max - Y_Min; Transformation : constant GL.Types.Singles.Matrix4 := ((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (-1.0, -1.0, 0.0, 1.0)) * ((2.0 / GL.Types.Single (Width), 0.0, 0.0, 0.0), (0.0, 2.0 / GL.Types.Single (Height), 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 1.0)); Old_X, Old_Y : GL.Types.Int; Old_Width, Old_Height : GL.Types.Size; begin FrameBuf.Initialize_Id; Fb.Draw_Target.Bind (FrameBuf); Target.Initialize_Id; Tx.Targets.Texture_2D.Bind (Target); Tx.Targets.Texture_2D.Load_Empty_Texture (0, GL.Pixels.Red, GL.Types.Int (Width), GL.Types.Int (Height)); Tx.Targets.Texture_2D.Set_Minifying_Filter (Tx.Nearest); Tx.Targets.Texture_2D.Set_Magnifying_Filter (Tx.Nearest); GL.Window.Get_Viewport (Old_X, Old_Y, Old_Width, Old_Height); GL.Window.Set_Viewport (0, 0, GL.Types.Size (Width), GL.Types.Size (Y_Max - Y_Min)); Fb.Draw_Target.Attach_Texture (Fb.Color_Attachment_0, Target, 0); GL.Buffers.Set_Active_Buffer (GL.Buffers.Color_Attachment0); Tx.Set_Active_Unit (0); Object.Data.Program.Id.Use_Program; GL.Attributes.Enable_Vertex_Attrib_Array (0); GL.Uniforms.Set_Int (Object.Data.Program.Texture_Id, 0); GL.Uniforms.Set_Single (Object.Data.Program.Color_Id, GL.Types.Single (Text_Color (GL.Types.Colors.R)), GL.Types.Single (Text_Color (GL.Types.Colors.G)), GL.Types.Single (Text_Color (GL.Types.Colors.B)), GL.Types.Single (Text_Color (GL.Types.Colors.A))); GL.Uniforms.Set_Single (Object.Data.Program.Transform_Id, Transformation); Object.Data.Program.Square_Array.Bind; GL.Objects.Buffers.Array_Buffer.Bind (Object.Data.Program.Square_Buffer); GL.Buffers.Set_Color_Clear_Value ((0.0, 0.0, 0.0, 1.0)); GL.Buffers.Clear ((Color => True, others => False)); while Char_Position <= Content'Last loop UTF8.Read (Content, Char_Position, Code_Point); Map_Position := Character_Data (Object, Code_Point); declare Char_Data : constant Loaded_Character := Loaded_Characters.Element (Map_Position); begin GL.Uniforms.Set_Single (Object.Data.Program.Info_Id, GL.Types.Single (X_Offset + Char_Data.Left), GL.Types.Single (Char_Data.Y_Min - Y_Min), GL.Types.Single (Char_Data.Width), GL.Types.Single (Char_Data.Y_Max - Char_Data.Y_Min)); Tx.Targets.Texture_2D.Bind (Loaded_Characters.Element (Map_Position).Image); Va.Draw_Arrays (GL.Types.Triangle_Strip, 0, 4); X_Offset := X_Offset + Loaded_Characters.Element (Map_Position).Advance; end; end loop; GL.Flush; GL.Attributes.Disable_Vertex_Attrib_Array (0); GL.Window.Set_Viewport (Old_X, Old_Y, Old_Width, Old_Height); Fb.Draw_Target.Bind (Fb.Default_Framebuffer); return Target; end To_Texture; procedure Adjust (Object : in out Renderer_Reference) is begin if Object.Data /= null then Object.Data.Refcount := Object.Data.Refcount + 1; end if; end Adjust; procedure Finalize (Object : in out Renderer_Reference) is procedure Free is new Ada.Unchecked_Deallocation (Renderer_Data, Pointer); begin if Object.Data /= null then Object.Data.Refcount := Object.Data.Refcount - 1; if Object.Data.Refcount = 0 then Free (Object.Data); end if; end if; end Finalize; function Hash (Value : FT.ULong) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type'Mod (Value); end Hash; end GL.Text;
pragma License (Unrestricted); -- with Ada.Strings.Unbounded; with Ada.Strings.Unbounded_Strings; with Ada.Text_IO.Generic_Unbounded_IO; package Ada.Text_IO.Unbounded_IO is new Generic_Unbounded_IO ( Strings.Unbounded_Strings, Put => Put, Put_Line => Put_Line, Get_Line => Get_Line);
-- A74205E.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 THE ADDITIONAL OPERATIONS FOR A COMPOSITE TYPE WITH A -- COMPONENT OF A PRIVATE TYPE ARE AVAILABLE AT THE EARLIEST -- PLACE WITHIN THE IMMEDIATE SCOPE OF THE DECLARATION OF THE COMPOSITE -- TYPE AND AFTER THE FULL DECLARATION OF THE PRIVATE TYPE. -- IN PARTICULAR, CHECH FOR THE FOLLOWING : -- (1) RELATIONAL OPERATORS WITH ARRAYS OF SCALAR TYPES -- (2) EQUALITY WITH ARRAYS AND RECORDS OF LIMITED PRIVATE TYPES -- (3) LOGICAL OPERATORS WITH ARRAYS OF BOOLEAN TYPES -- (4) CATENATION WITH ARRAYS OF LIMITED PRIVATE TYPES -- (5) INITIALIZATION WITH ARRAYS AND RECORDS OF LIMITED PRIVATE TYPES -- (6) ASSIGNMENT WITH ARRAYS AND RECORDS OF LIMITED PRIVATE TYPES -- (7) SELECTED COMPONENTS WITH COMPOSITES OF PRIVATE RECORD TYPES -- (8) INDEXED COMPONENTS WITH COMPOSITES OF PRIVATE ARRAY TYPES -- (9) SLICES WITH COMPOSITES OF PRIVATE ARRAY TYPES -- (10) QUALIFICATION FOR COMPOSITES OF PRIVATE TYPES -- (11) AGGREGATES FOR ARRAYS AND RECORDS OF PRIVATES TYPES -- (12) USE OF 'SIZE FOR ARRAYS AND RECORDS OF PRIVATE TYPES -- DSJ 5/2/83 WITH REPORT ; PROCEDURE A74205E IS USE REPORT ; BEGIN TEST("A74205E", "CHECK THAT ADDITIONAL OPERATIONS FOR " & "COMPOSITE TYPES OF PRIVATE TYPES ARE " & "AVAILABLE AT THE EARLIEST PLACE AFTER THE " & "FULL DECLARATION AND IN THE IMMEDIATE " & "SCOPE OF THE COMPOSITE TYPE") ; DECLARE PACKAGE PACK1 IS TYPE LP1 IS LIMITED PRIVATE ; PACKAGE PACK_LP IS TYPE LP_ARR IS ARRAY (INTEGER RANGE <>) OF LP1 ; SUBTYPE LP_ARR2 IS LP_ARR ( 1 .. 2 ) ; SUBTYPE LP_ARR4 IS LP_ARR ( 1 .. 4 ) ; END PACK_LP ; TYPE T1 IS PRIVATE ; PACKAGE PACK2 IS TYPE ARR IS ARRAY (INTEGER RANGE <>) OF T1 ; SUBTYPE ARR2 IS ARR ( 1 .. 2 ) ; SUBTYPE ARR4 IS ARR ( 1 .. 4 ) ; END PACK2 ; TYPE T2 IS PRIVATE ; TYPE T3 IS PRIVATE ; PACKAGE PACK3 IS TYPE ARR_T2 IS ARRAY ( 1 .. 2 ) OF T2 ; TYPE ARR_T3 IS ARRAY ( 1 .. 2 ) OF T3 ; END PACK3 ; PRIVATE TYPE LP1 IS NEW BOOLEAN ; TYPE T1 IS NEW BOOLEAN ; TYPE T2 IS ARRAY ( 1 .. 2 ) OF INTEGER ; TYPE T3 IS RECORD C1 : INTEGER ; END RECORD ; END PACK1 ; PACKAGE BODY PACK1 IS PACKAGE BODY PACK_LP IS L1, L2 : LP_ARR2 := (TRUE,FALSE) ; -- LEGAL A3 : LP_ARR2 := L1 ; -- LEGAL B3 : BOOLEAN := L1 = L2 ; -- LEGAL B4 : BOOLEAN := L1 /= L2 ; -- LEGAL END PACK_LP ; PACKAGE BODY PACK2 IS A1, A2 : ARR2 := (FALSE,TRUE) ; -- LEGAL A4 : ARR2 := ARR2'(A1) ; -- LEGAL B1 : BOOLEAN := A1 < A2 ; -- LEGAL B2 : BOOLEAN := A1 >= A2 ; -- LEGAL N3 : INTEGER := A1'SIZE ; -- LEGAL PROCEDURE G1 (X : ARR2 := NOT A1) IS -- LEGAL BEGIN NULL ; END G1 ; PROCEDURE G2 (X : ARR2 := A1 AND A2) IS -- LEGAL BEGIN NULL ; END G2 ; PROCEDURE G3 (X : ARR4 := A1 & A2) IS -- LEGAL BEGIN NULL ; END G3 ; PROCEDURE G4 (X : ARR2 := (FALSE,TRUE) ) IS -- LEGAL BEGIN NULL ; END G4 ; END PACK2 ; PACKAGE BODY PACK3 IS X2 : ARR_T2 := (1=>(1,2), 2=>(3,4)) ; -- LEGAL X3 : ARR_T3 := (1=>(C1=>5), 2=>(C1=>6)) ; -- LEGAL N1 : INTEGER := X3(1).C1 ; -- LEGAL N2 : INTEGER := X2(1)(2) ; -- LEGAL N4 : T2 := X2(1)(1..2) ; -- LEGAL END PACK3 ; END PACK1 ; BEGIN NULL ; END ; RESULT ; END A74205E ;
just a line context-2 context-1 line with match - abc context+1 context+2 bloop groop line matching 'abc' again derm germ blah 1 2 3
-- C45431A.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 FOR FIXED POINT TYPES +A = A AND THAT, FOR MODEL NUMBERS, -- -(-A) = A. -- CASE A: BASIC TYPES THAT FIT THE CHARACTERISTICS OF DURATION'BASE. -- WRG 8/28/86 -- PWN 02/02/95 REMOVED INCONSISTENCIES WITH ADA 9X. WITH REPORT; USE REPORT; PROCEDURE C45431A IS BEGIN TEST ("C45431A", "CHECK THAT FOR FIXED POINT TYPES +A = A AND " & "THAT, FOR MODEL NUMBERS, -(-A) = A " & "-- BASIC TYPES"); ------------------------------------------------------------------- A: DECLARE TYPE LIKE_DURATION IS DELTA 0.020 RANGE -86_400.0 .. 86_400.0; NON_MODEL_CONST : CONSTANT := 2.0 / 3; NON_MODEL_VAR : LIKE_DURATION := 0.0; SMALL, MAX, MIN, ZERO : LIKE_DURATION := 0.5; X : LIKE_DURATION := 0.0; BEGIN -- INITIALIZE "CONSTANTS": IF EQUAL (3, 3) THEN NON_MODEL_VAR := NON_MODEL_CONST; SMALL := LIKE_DURATION'SMALL; MAX := LIKE_DURATION'LAST; MIN := LIKE_DURATION'FIRST; ZERO := 0.0; END IF; -- CHECK + OR - ZERO = ZERO: IF "+"(RIGHT => ZERO) /= 0.0 OR +LIKE_DURATION'(0.0) /= ZERO THEN FAILED ("+0.0 /= 0.0"); END IF; IF "-"(RIGHT => ZERO) /= 0.0 OR -LIKE_DURATION'(0.0) /= ZERO THEN FAILED ("-0.0 /= 0.0"); END IF; IF -(-ZERO) /= 0.0 THEN FAILED ("-(-0.0) /= 0.0"); END IF; -- CHECK + AND - MAX: IF EQUAL (3, 3) THEN X := MAX; END IF; IF +X /= MAX OR +LIKE_DURATION'LAST /= MAX THEN FAILED ("+LIKE_DURATION'LAST /= LIKE_DURATION'LAST"); END IF; IF -(-X) /= MAX OR -(-LIKE_DURATION'LAST) /= MAX THEN FAILED ("-(-LIKE_DURATION'LAST) /= LIKE_DURATION'LAST"); END IF; -- CHECK + AND - MIN: IF EQUAL (3, 3) THEN X := MIN; END IF; IF +X /= MIN OR +LIKE_DURATION'FIRST /= MIN THEN FAILED ("+LIKE_DURATION'FIRST /= LIKE_DURATION'FIRST"); END IF; IF -(-X) /= MIN OR -(-LIKE_DURATION'FIRST) /= MIN THEN FAILED("-(-LIKE_DURATION'FIRST) /= LIKE_DURATION'FIRST"); END IF; -- CHECK + AND - SMALL: IF EQUAL (3, 3) THEN X := SMALL; END IF; IF +X /= SMALL OR +LIKE_DURATION'SMALL /= SMALL THEN FAILED ("+LIKE_DURATION'SMALL /= LIKE_DURATION'SMALL"); END IF; IF -(-X) /= SMALL OR -(-LIKE_DURATION'SMALL) /= SMALL THEN FAILED("-(-LIKE_DURATION'SMALL) /= LIKE_DURATION'SMALL"); END IF; -- CHECK ARBITRARY MID-RANGE NUMBERS: IF EQUAL (3, 3) THEN X := 1000.984_375; END IF; IF +X /= 1000.984_375 OR +1000.984_375 /= X THEN FAILED ("+1000.984_375 /= 1000.984_375"); END IF; IF -(-X) /= 1000.984_375 OR -(-1000.984_375) /= X THEN FAILED ("-(-1000.984_375) /= 1000.984_375"); END IF; -- CHECK "+" AND "-" FOR NON-MODEL NUMBER: IF +LIKE_DURATION'(NON_MODEL_CONST) NOT IN 0.656_25 .. 0.671_875 OR +NON_MODEL_VAR NOT IN 0.656_25 .. 0.671_875 THEN FAILED ("+LIKE_DURATION'(2.0 / 3) NOT IN 0.656_25 .. " & "0.671_875"); END IF; IF -LIKE_DURATION'(NON_MODEL_CONST) NOT IN -0.671_875 .. -0.656_25 OR -NON_MODEL_VAR NOT IN -0.671_875 .. -0.656_25 THEN FAILED ("-LIKE_DURATION'(2.0 / 3) NOT IN -0.671_875 " & ".. -0.656_25"); END IF; EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION RAISED -- A"); END A; ------------------------------------------------------------------- B: DECLARE TYPE DECIMAL_M4 IS DELTA 100.0 RANGE -1000.0 .. 1000.0; NON_MODEL_CONST : CONSTANT := 2.0 / 3; NON_MODEL_VAR : DECIMAL_M4 := 0.0; SMALL, MAX, MIN, ZERO : DECIMAL_M4 := -128.0; X : DECIMAL_M4 := 0.0; BEGIN -- INITIALIZE "CONSTANTS": IF EQUAL (3, 3) THEN NON_MODEL_VAR := NON_MODEL_CONST; SMALL := DECIMAL_M4'SMALL; ZERO := 0.0; END IF; -- CHECK + OR - ZERO = ZERO: IF +ZERO /= 0.0 OR +DECIMAL_M4'(0.0) /= ZERO THEN FAILED ("+0.0 /= 0.0"); END IF; IF -ZERO /= 0.0 OR -DECIMAL_M4'(0.0) /= ZERO THEN FAILED ("-0.0 /= 0.0"); END IF; IF -(-ZERO) /= 0.0 THEN FAILED ("-(-0.0) /= 0.0"); END IF; -- CHECK + AND - MAX: IF EQUAL (3, 3) THEN X := MAX; END IF; -- CHECK + AND - SMALL: IF EQUAL (3, 3) THEN X := SMALL; END IF; IF +X /= SMALL OR +DECIMAL_M4'SMALL /= SMALL THEN FAILED ("+DECIMAL_M4'SMALL /= DECIMAL_M4'SMALL"); END IF; IF -(-X) /= SMALL OR -(-DECIMAL_M4'SMALL) /= SMALL THEN FAILED ("-(-DECIMAL_M4'SMALL) /= DECIMAL_M4'SMALL"); END IF; -- CHECK ARBITRARY MID-RANGE NUMBERS: IF EQUAL (3, 3) THEN X := 256.0; END IF; IF +X /= 256.0 OR +256.0 /= X THEN FAILED ("+256.0 /= 256.0"); END IF; IF -(-X) /= 256.0 OR -(-256.0) /= X THEN FAILED ("-(-256.0) /= 256.0"); END IF; -- CHECK "+" AND "-" FOR NON-MODEL NUMBER: IF +DECIMAL_M4'(NON_MODEL_CONST) NOT IN 0.0 .. 64.0 OR +NON_MODEL_VAR NOT IN 0.0 .. 64.0 THEN FAILED ("+DECIMAL_M4'(2.0 / 3) NOT IN 0.0 .. 64.0"); END IF; IF -DECIMAL_M4'(NON_MODEL_CONST) NOT IN -64.0 .. 0.0 OR -NON_MODEL_VAR NOT IN -64.0 .. 0.0 THEN FAILED ("-DECIMAL_M4'(2.0 / 3) NOT IN -64.0 .. 0.0"); END IF; EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION RAISED -- B"); END B; ------------------------------------------------------------------- RESULT; END C45431A;
-- Functions_Example -- A example of using the Ada 2012 interface to Lua for functions / closures etc -- Copyright (c) 2015, James Humphry - see LICENSE for terms with Ada.IO_Exceptions; with Ada.Text_IO; use Ada.Text_IO; with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO; with Ada.Characters.Latin_1; with Lua; use Lua; with Lua.Libs; with Lua.Util; use Lua.Util; with Example_AdaFunctions; procedure Functions_Example is L : Lua_State; Success : Thread_Status; R : Lua_Reference; LF : Character renames Ada.Characters.Latin_1.LF; Coroutine_Source : aliased constant String := "" & "function co (x) " & LF & " for i = 1, x do " & LF & " yield(i) " & LF & " end " & LF & " return -1 " & LF & " end " & LF & ""; begin Put_Line("A simple example of using Lua and Ada functions together"); Put("Lua version: "); Put(Item => L.Version, Aft => 0, Exp => 0); New_Line; New_Line; Put_Line("Loading chunk: function f (x) return 2*x end"); Success := L.LoadString_By_Copy("function f (x) return 2*x end"); Put_Line("Load" & (if Success /= OK then " not" else "") & " successful."); L.Call(nargs => 0, nresults =>0); Put_Line("Compiled chunk."); Put("Result of calling f (3): "); L.PushInteger(3); L.Call_Function(name => "f", nargs => 1, nresults => 1); Put(L.ToNumber(-1), Aft => 0, Exp => 0); New_Line; New_Line; Put_Line("Saving a reference to the top of the stack and clearing it."); R := Ref(L); L.SetTop(0); Print_Stack(L); Put_Line("Retrieving reference..."); L.Get(R); Print_Stack(L); New_Line; Put_Line("Attempting to save function f to a file as a binary chunk."); L.GetGlobal("f"); begin L.DumpFile("function_f.luachunk"); Put_Line("Saving function f to a file appears to have succeeded."); exception when Lua_Error | Ada.IO_Exceptions.Status_Error | Ada.IO_Exceptions.Name_Error | Ada.IO_Exceptions.Use_Error => Put_Line("Saving function f to a file failed!"); end; New_Line; Put_Line("Loading IO library and running example Lua file"); Libs.Require_Standard_Library(L, Libs.IO_Lib); Success := L.LoadFile("examples/example_lua.lua"); Put_Line("Load" & (if Success /= OK then " not" else "") & " successful."); if Success = OK then L.Call(nargs => 0, nresults =>0); Put_Line("Compiled chunk. Result of calling triangle (5):"); L.PushNumber(5.0); L.Call_Function(name => "triangle", nargs => 1, nresults => 0); end if; New_Line; L.SetTop(0); Put_Line("Registering an AdaFunction foobar in Lua"); L.Register("foobar", AdaFunction'(Example_AdaFunctions.FooBar'Access)); Success := L.LoadString_By_Copy("baz = foobar(5.0)"); Put_Line("Loading code snippet 'baz = foobar(5.0)'" & (if Success /= OK then " not" else "") & " successful."); Put_Line("Calling 'baz = foobar(5.0)' from Lua"); L.Call(nargs => 0, nresults =>0); Put("baz = "); L.GetGlobal("baz"); Put(L.ToNumber(-1), Aft => 0, Exp => 0); New_Line; New_Line; L.SetTop(0); Put_Line("Checking foobar can be retrieved"); L.GetGlobal("foobar"); if not L.IsAdaFunction(-1) then Put_Line("Error - foobar does not contain an AdaFunction?"); end if; if L.ToAdaFunction(-1) = AdaFunction'(Example_AdaFunctions.FooBar'Access) then Put_Line("AdaFunction foobar retrieved successfully from Lua"); else Put_Line("AdaFunction foobar was NOT retrieved from Lua"); end if; New_Line; L.SetTop(0); Put_Line("Registering an AdaFunction multret in Lua"); L.Register("multret", AdaFunction'(Example_AdaFunctions.Multret'Access)); Put_Line("Calling 'multret(5)' from Lua"); L.PushInteger(5); L.Call_Function(name => "multret", nargs => 1, nresults => MultRet_Sentinel); Print_Stack(L); New_Line; L.SetTop(0); Put_Line("Registering an AdaFunction closure (with upvalue 2.0) in Lua"); L.PushNumber(2.0); L.PushAdaClosure(AdaFunction'(Example_AdaFunctions.Closure'Access), 1); L.SetGlobal("closure"); Put_Line("Calling 'closure(3.5)' from Lua"); L.PushNumber(3.5); L.Call_Function(name => "closure", nargs => 1, nresults => MultRet_Sentinel); Print_Stack(L); New_Line; L.SetTop(0); Put_Line("Now to look at using coroutines"); Libs.Add_Yield_Function(L); Put_Line("Loading coroutine source: "); Put_Line(Coroutine_Source); Success := L.LoadString(Coroutine_Source); Put_Line("Load" & (if Success /= OK then " not" else "") & " successful."); L.Call(nargs => 0, nresults =>0); Put_Line("Compiled coroutine code."); declare Coroutine : constant Lua_Thread := L.NewThread; Coroutine_Status : Thread_Status; begin Put_Line("New thread created"); Put_Line("Resuming coroutine with parameter 3 in this thread:"); Coroutine.GetGlobal("co"); Coroutine.PushInteger(3); Coroutine_Status := Coroutine.Resume(nargs => 1); Put("Coroutine status : " & Thread_Status'Image(Coroutine_Status)); Put(" Result: "); Put(Coroutine.ToNumber(-1)); New_Line; L.Pop(1); -- argument no longer needed in this example while Coroutine_Status = YIELD loop Coroutine_Status := Coroutine.Resume(nargs => 0); Put("Coroutine status : " & Thread_Status'Image(Coroutine_Status)); Put(" Result: "); Put(Coroutine.ToNumber(-1)); New_Line; end loop; end; New_Line; L.SetTop(0); declare S : constant Lua_Reference := R; begin Put_Line("Retrieving a copy of reference saved earlier..."); L.Get(S); Print_Stack(L); end; Put_Line("Retrieving reference saved earlier..."); L.Get(R); Print_Stack(L); New_Line; end Functions_Example;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- Copyright (C) 2014, 2015, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; with MAT.Events; package MAT.Expressions is type Resolver_Type is limited interface; type Resolver_Type_Access is access all Resolver_Type'Class; -- Find the region that matches the given name. function Find_Region (Resolver : in Resolver_Type; Name : in String) return MAT.Memory.Region_Info is abstract; -- Find the symbol in the symbol table and return the start and end address. function Find_Symbol (Resolver : in Resolver_Type; Name : in String) return MAT.Memory.Region_Info is abstract; -- Find the symbol region in the symbol table that contains the given address -- and return the start and end address of that region. function Find_Symbol (Resolver : in Resolver_Type; Addr : in MAT.Types.Target_Addr) return MAT.Memory.Region_Info is abstract; -- Get the start time for the tick reference. function Get_Start_Time (Resolver : in Resolver_Type) return MAT.Types.Target_Tick_Ref is abstract; type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_REGION, INSIDE_DIRECT_REGION, INSIDE_FUNCTION, INSIDE_DIRECT_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; function Create_Inside (Addr : in MAT.Types.Uint64; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Create an event ID range expression node. function Create_Event (Min : in MAT.Events.Event_Id_Type; Max : in MAT.Events.Event_Id_Type) return Expression_Type; -- Create a thread ID range expression node. function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type; -- Create a event type expression check. function Create_Event_Type (Event_Kind : in MAT.Events.Probe_Index_Type) return Expression_Type; -- Create an expression node to keep allocation events which don't have any associated free. function Create_No_Free return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Target_Event_Type) return Boolean; -- Parse the string and return the expression tree. function Parse (Expr : in String; Resolver : in Resolver_Type_Access) return Expression_Type; -- Empty expression. EMPTY : constant Expression_Type; type yystype is record low : MAT.Types.Uint64 := 0; high : MAT.Types.Uint64 := 0; bval : Boolean := False; name : Ada.Strings.Unbounded.Unbounded_String; expr : Expression_Type; end record; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_EVENT, N_HAS_ADDR, N_CONDITION, N_THREAD, N_TYPE, N_NO_FREE); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT | N_HAS_ADDR | N_IN_FUNC | N_IN_FUNC_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Min_Thread : MAT.Types.Target_Thread_Ref; Max_Thread : MAT.Types.Target_Thread_Ref; when N_EVENT => Min_Event : MAT.Events.Event_Id_Type; Max_Event : MAT.Events.Event_Id_Type; when N_TYPE => Event_Kind : MAT.Events.Probe_Index_Type; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Target_Event_Type) return Boolean; type Expression_Type is new Ada.Finalization.Controlled with record Node : Node_Type_Access; end record; -- Release the reference and destroy the expression tree if it was the last reference. overriding procedure Finalize (Obj : in out Expression_Type); -- Update the reference after an assignment. overriding procedure Adjust (Obj : in out Expression_Type); -- Empty expression. EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with Node => null); end MAT.Expressions;
package Dynamic_Elab_Pkg is type R is record Code : Integer; Val : Boolean; end record; function Get_R return R; end Dynamic_Elab_Pkg;
----------------------------------------------------------------------- -- asf-events -- ASF Events -- Copyright (C) 2010, 2012 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Events; with ASF.Lifecycles; with ASF.Components.Base; with ASF.Events.Phases; with Ada.Containers.Vectors; -- The <b>ASF.Events</b> package defines the application events that an ASF -- application can receive. Events are queued while processing the JSF phases -- (See UIComponent.Queue_Event). They are dispatched after each phase -- (See UIComponent.Broadcast). -- -- This package is an Ada adaptation for the Java Server Faces Specification -- JSR 314 - 3.4.2 Application Events. package ASF.Events.Faces is -- ------------------------------ -- Faces event -- ------------------------------ -- The <b>Faces_Event</b> represents the root type for ASF events. -- The event is associated with a component and a lifecycle phase after -- which it will be processed. type Faces_Event is new Util.Events.Event with private; -- Get the lifecycle phase where the event must be processed. function Get_Phase (Event : in Faces_Event) return ASF.Lifecycles.Phase_Type; -- Set the lifecycle phase when this event must be processed. procedure Set_Phase (Event : in out Faces_Event; Phase : in ASF.Lifecycles.Phase_Type); -- Get the component onto which the event was posted. function Get_Component (Event : in Faces_Event) return Components.Base.UIComponent_Access; private type Faces_Event_Access is access all Faces_Event'Class; package Event_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Faces_Event_Access); type Faces_Event is new Util.Events.Event with record Phase : ASF.Events.Phases.Phase_Type := ASF.Events.Phases.RESTORE_VIEW; Component : Components.Base.UIComponent_Access := null; end record; end ASF.Events.Faces;
private with AdaM.Subprogram, AdaM.a_Package, AdaM.Environment; package aIDE is procedure start; procedure stop; private -- the_Environ : AdaM.Environment.item; all_Apps : AdaM.Subprogram.vector; the_selected_App : AdaM.Subprogram.view; procedure build_Project; function fetch_App (Named : in AdaM.Identifier) return adam.Subprogram.view; anonymous_Procedure : constant String := "Anon"; the_applet_Package : adam.a_Package.view; the_entity_Environ : AdaM.Environment.item; end aIDE;
package Iban_Code is function Is_Legal(Iban : String) return Boolean; end Iban_Code;
with AVTAS.LMCP.ByteBuffers; use AVTAS.LMCP.ByteBuffers; package -<full_series_name_dots>-.Factory is HEADER_SIZE : constant := 8; CHECKSUM_SIZE : constant := 4; SERIESNAME_SIZE : constant := 8; LMCP_CONTROL_STR : constant := 16#4c4d4350#; function packMessage(rootObject : in avtas.lmcp.object.Object_Any; enableChecksum : in Boolean) return ByteBuffer; procedure getObject(buffer : in out ByteBuffer; output : out avtas.lmcp.object.Object_Any); function createObject(seriesId : in Int64; msgType : in UInt32; version: in UInt16) return avtas.lmcp.object.Object_Any; function CalculateChecksum (Buffer : in ByteBuffer) return UInt32; -- Computes the modular checksum for the Buffer contents. Assumes -- Big Endian order. -- -- The checksum calculation does not include those bytes that either will, -- or already do hold the UInt32 checksum stored at the very end of the -- buffer function getObjectSize(buffer : in ByteBuffer) return UInt32; function Validate (Buffer : in ByteBuffer) return Boolean; -- Validates a buffer by comparing a newly computed checksum with the -- previously computed checksum value stored with the message -- in the buffer. Assumes the buffer is in Big Endian byte order. end -<full_series_name_dots>-.Factory;
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Regpat; with Ada.Strings.Unbounded; with Util.Files; with ASF.Streams; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Servlets.Measures; with ASF.Responses; with ASF.Responses.Tools; with ASF.Filters.Dump; package body ASF.Tests is use Ada.Strings.Unbounded; use Util.Tests; CONTEXT_PATH : constant String := "/asfunit"; Server : access ASF.Server.Container; App : ASF.Applications.Main.Application_Access := null; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Save the response headers and content in a file procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response); -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class) is use type ASF.Applications.Main.Application_Access; C : ASF.Applications.Config; begin if Application /= null then App := Application; else App := new ASF.Applications.Main.Application; end if; Server := new ASF.Server.Container; Server.Register_Application (CONTEXT_PATH, App.all'Access); C.Copy (Props); App.Initialize (C, Factory); App.Register ("layoutMsg", "layout"); App.Set_Global ("contextPath", CONTEXT_PATH); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Access); App.Add_Servlet (Name => "files", Server => Files'Access); App.Add_Servlet (Name => "ajax", Server => Ajax'Access); App.Add_Servlet (Name => "measures", Server => Measures'Access); App.Add_Filter (Name => "dump", Filter => Dump'Access); App.Add_Filter (Name => "measures", Filter => Measures'Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.properties"); App.Add_Mapping (Name => "files", Pattern => "*.xhtml"); App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*"); App.Add_Mapping (Name => "measures", Pattern => "stats.xml"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*"); end Initialize; -- ------------------------------ -- Get the server -- ------------------------------ function Get_Server return access ASF.Server.Container is begin return Server; end Get_Server; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return ASF.Applications.Main.Application_Access is begin return App; end Get_Application; -- ------------------------------ -- Save the response headers and content in a file -- ------------------------------ procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response) is use ASF.Responses; Info : constant String := Tools.To_String (Reply => Response, Html => False, Print_Headers => True); Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Content : Unbounded_String; Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Response.Read_Content (Content); Stream.Write (Content); Insert (Content, 1, Info); Util.Files.Write_File (Result_Path & "/" & Name, Content); end Save_Response; -- ------------------------------ -- Simulate a raw request. The URI and method must have been set on the Request object. -- ------------------------------ procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response) is begin -- For the purpose of writing tests, clear the buffer before invoking the service. Response.Clear; Server.Service (Request => Request, Response => Response); end Do_Req; -- ------------------------------ -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "GET"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Get; -- ------------------------------ -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "POST"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Post; -- ------------------------------ -- Check that the response body contains the string -- ------------------------------ procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Index (Content, Value) > 0, Message => Message & ": value '" & Value & "' not found", Source => Source, Line => Line); end Assert_Contains; -- ------------------------------ -- Check that the response body matches the regular expression -- ------------------------------ procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is use GNAT.Regpat; Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern, Flags => Multiple_Lines); begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, Status, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Match (Regexp, To_String (Content)), Message => Message & ": does not match '" & Pattern & "'", Source => Source, Line => Line); end Assert_Matches; -- ------------------------------ -- Check that the response body is a redirect to the given URI. -- ------------------------------ procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is begin Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status, "Invalid response", Source, Line); Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"), Message & ": missing Location", Source, Line); end Assert_Redirect; end ASF.Tests;
with Gtk.Main; package body GA_Sine_Package is function Delete_Event (Widget : access Gtk_Widget_Record'Class; Event : Gdk_Event) return Boolean is pragma Unreferenced (Event); pragma Unreferenced (Widget); begin -- If you return False in the "delete_event" signal handler, -- GtkAda will emit the "destroy" signal. Returning True means -- you don't want the window to be destroyed. This is useful -- for popping up 'are you sure you want to quit?' type -- dialogs. -- Change True to False and the main window will be destroyed -- with a "delete_event". return False; end Delete_Event; -- Another callback procedure Destroy (Widget : access Gtk_Widget_Record'Class) is pragma Unreferenced (Widget); begin Gtk.Main.Main_Quit; end Destroy; end GA_Sine_Package;
------------------------------------------------------------------------------- -- Copyright 2021, The Septum Developers (see AUTHORS file) -- 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.Directories; with SP.Strings; -- Wraps file system operations to make them simpler, and handle cases without -- using exceptions. package SP.File_System is use SP.Strings; -- Checks that a file at the given path exists. function Is_File (Target : String) return Boolean; -- Checks that a dir at the given path exists. function Is_Dir (Target : String) return Boolean; -- Ada.Directories.Hierarchical_File_Names is optional, and doesn't exist -- on some of the Linux platforms tested for Alire crates. function Is_Current_Or_Parent_Directory (Dir_Entry : Ada.Directories.Directory_Entry_Type) return Boolean; type Dir_Contents is record Files : String_Vectors.Vector; Subdirs : String_Vectors.Vector; end record; -- The immediate, non-recursive, contents of the given directory. function Contents (Dir_Name : String) return Dir_Contents; -- Pulls the contents of a textual file, which might possibly fail due to -- the file not existing or being a directory instead of a file. function Read_Lines (File_Name : in String; Result : out String_Vectors.Vector) return Boolean; -- Finds a path similar to the given one with the same basic stem. function Similar_Path (Path : String) return String; -- Rewrite a path with all forward slashes for simplicity. function Rewrite_Path (Path : String) return String; -- Produces all of the possible options for a path. function File_Completions (Path : String) return String_Vectors.Vector; end SP.File_System;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ C H 7 -- -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ -- This package contains virtually all expansion mechanisms related to -- - controlled types -- - transient scopes with Atree; use Atree; with Debug; use Debug; with Einfo; use Einfo; with Exp_Ch9; use Exp_Ch9; with Exp_Ch11; use Exp_Ch11; with Exp_Dbug; use Exp_Dbug; with Exp_Tss; use Exp_Tss; with Exp_Util; use Exp_Util; with Freeze; use Freeze; with Hostparm; use Hostparm; with Lib; use Lib; with Lib.Xref; use Lib.Xref; with Nlists; use Nlists; with Nmake; use Nmake; with Opt; use Opt; with Output; use Output; with Restrict; use Restrict; with Rtsfind; use Rtsfind; with Targparm; use Targparm; with Sinfo; use Sinfo; with Sem; use Sem; with Sem_Ch3; use Sem_Ch3; with Sem_Ch7; use Sem_Ch7; with Sem_Ch8; use Sem_Ch8; with Sem_Res; use Sem_Res; with Sem_Type; use Sem_Type; with Sem_Util; use Sem_Util; with Snames; use Snames; with Stand; use Stand; with Tbuild; use Tbuild; with Uintp; use Uintp; package body Exp_Ch7 is -------------------------------- -- Transient Scope Management -- -------------------------------- -- A transient scope is created when temporary objects are created by the -- compiler. These temporary objects are allocated on the secondary stack -- and the transient scope is responsible for finalizing the object when -- appropriate and reclaiming the memory at the right time. The temporary -- objects are generally the objects allocated to store the result of a -- function returning an unconstrained or a tagged value. Expressions -- needing to be wrapped in a transient scope (functions calls returning -- unconstrained or tagged values) may appear in 3 different contexts which -- lead to 3 different kinds of transient scope expansion: -- 1. In a simple statement (procedure call, assignment, ...). In -- this case the instruction is wrapped into a transient block. -- (See Wrap_Transient_Statement for details) -- 2. In an expression of a control structure (test in a IF statement, -- expression in a CASE statement, ...). -- (See Wrap_Transient_Expression for details) -- 3. In a expression of an object_declaration. No wrapping is possible -- here, so the finalization actions, if any are done right after the -- declaration and the secondary stack deallocation is done in the -- proper enclosing scope (see Wrap_Transient_Declaration for details) -- Note about function returning tagged types: It has been decided to -- always allocate their result in the secondary stack while it is not -- absolutely mandatory when the tagged type is constrained because the -- caller knows the size of the returned object and thus could allocate the -- result in the primary stack. But, allocating them always in the -- secondary stack simplifies many implementation hassles: -- - If it is dispatching function call, the computation of the size of -- the result is possible but complex from the outside. -- - If the returned type is controlled, the assignment of the returned -- value to the anonymous object involves an Adjust, and we have no -- easy way to access the anonymous object created by the back-end -- - If the returned type is class-wide, this is an unconstrained type -- anyway -- Furthermore, the little loss in efficiency which is the result of this -- decision is not such a big deal because function returning tagged types -- are not very much used in real life as opposed to functions returning -- access to a tagged type -------------------------------------------------- -- Transient Blocks and Finalization Management -- -------------------------------------------------- function Find_Node_To_Be_Wrapped (N : Node_Id) return Node_Id; -- N is a node wich may generate a transient scope. Loop over the -- parent pointers of N until it find the appropriate node to -- wrap. It it returns Empty, it means that no transient scope is -- needed in this context. function Make_Clean (N : Node_Id; Clean : Entity_Id; Mark : Entity_Id; Flist : Entity_Id; Is_Task : Boolean; Is_Master : Boolean; Is_Protected_Subprogram : Boolean; Is_Task_Allocation_Block : Boolean; Is_Asynchronous_Call_Block : Boolean) return Node_Id; -- Expand a the clean-up procedure for controlled and/or transient -- block, and/or task master or task body, or blocks used to -- implement task allocation or asynchronous entry calls, or -- procedures used to implement protected procedures. Clean is the -- entity for such a procedure. Mark is the entity for the secondary -- stack mark, if empty only controlled block clean-up will be -- performed. Flist is the entity for the local final list, if empty -- only transient scope clean-up will be performed. The flags -- Is_Task and Is_Master control the calls to the corresponding -- finalization actions for a task body or for an entity that is a -- task master. procedure Set_Node_To_Be_Wrapped (N : Node_Id); -- Set the field Node_To_Be_Wrapped of the current scope procedure Insert_Actions_In_Scope_Around (N : Node_Id); -- Insert the before-actions kept in the scope stack before N, and the -- after after-actions, after N which must be a member of a list. function Make_Transient_Block (Loc : Source_Ptr; Action : Node_Id) return Node_Id; -- Create a transient block whose name is Scope, which is also a -- controlled block if Flist is not empty and whose only code is -- Action (either a single statement or single declaration). type Final_Primitives is (Initialize_Case, Adjust_Case, Finalize_Case); -- This enumeration type is defined in order to ease sharing code for -- building finalization procedures for composite types. Name_Of : constant array (Final_Primitives) of Name_Id := (Initialize_Case => Name_Initialize, Adjust_Case => Name_Adjust, Finalize_Case => Name_Finalize); Deep_Name_Of : constant array (Final_Primitives) of Name_Id := (Initialize_Case => Name_uDeep_Initialize, Adjust_Case => Name_uDeep_Adjust, Finalize_Case => Name_uDeep_Finalize); procedure Build_Record_Deep_Procs (Typ : Entity_Id); -- Build the deep Initialize/Adjust/Finalize for a record Typ with -- Has_Component_Component set and store them using the TSS mechanism. procedure Build_Array_Deep_Procs (Typ : Entity_Id); -- Build the deep Initialize/Adjust/Finalize for a record Typ with -- Has_Controlled_Component set and store them using the TSS mechanism. function Make_Deep_Proc (Prim : Final_Primitives; Typ : Entity_Id; Stmts : List_Id) return Node_Id; -- This function generates the tree for Deep_Initialize, Deep_Adjust -- or Deep_Finalize procedures according to the first parameter, -- these procedures operate on the type Typ. The Stmts parameter -- gives the body of the procedure. function Make_Deep_Array_Body (Prim : Final_Primitives; Typ : Entity_Id) return List_Id; -- This function generates the list of statements for implementing -- Deep_Initialize, Deep_Adjust or Deep_Finalize procedures -- according to the first parameter, these procedures operate on the -- array type Typ. function Make_Deep_Record_Body (Prim : Final_Primitives; Typ : Entity_Id) return List_Id; -- This function generates the list of statements for implementing -- Deep_Initialize, Deep_Adjust or Deep_Finalize procedures -- according to the first parameter, these procedures operate on the -- record type Typ. function Convert_View (Proc : Entity_Id; Arg : Node_Id; Ind : Pos := 1) return Node_Id; -- Proc is one of the Initialize/Adjust/Finalize operations, and -- Arg is the argument being passed to it. Ind indicates which -- formal of procedure Proc we are trying to match. This function -- will, if necessary, generate an conversion between the partial -- and full view of Arg to match the type of the formal of Proc, -- or force a conversion to the class-wide type in the case where -- the operation is abstract. ----------------------------- -- Finalization Management -- ----------------------------- -- This part describe how Initialization/Adjusment/Finalization procedures -- are generated and called. Two cases must be considered, types that are -- Controlled (Is_Controlled flag set) and composite types that contain -- controlled components (Has_Controlled_Component flag set). In the first -- case the procedures to call are the user-defined primitive operations -- Initialize/Adjust/Finalize. In the second case, GNAT generates -- Deep_Initialize, Deep_Adjust and Deep_Finalize that are in charge of -- calling the former procedures on the controlled components. -- For records with Has_Controlled_Component set, a hidden "controller" -- component is inserted. This controller component contains its own -- finalization list on which all controlled components are attached -- creating an indirection on the upper-level Finalization list. This -- technique facilitates the management of objects whose number of -- controlled components changes during execution. This controller -- component is itself controlled and is attached to the upper-level -- finalization chain. Its adjust primitive is in charge of calling -- adjust on the components and adusting the finalization pointer to -- match their new location (see a-finali.adb) -- It is not possible to use a similar technique for arrays that have -- Has_Controlled_Component set. In this case, deep procedures are -- generated that call initialize/adjust/finalize + attachment or -- detachment on the finalization list for all component. -- Initialize calls: they are generated for declarations or dynamic -- allocations of Controlled objects with no initial value. They are -- always followed by an attachment to the current Finalization -- Chain. For the dynamic allocation case this the chain attached to -- the scope of the access type definition otherwise, this is the chain -- of the current scope. -- Adjust Calls: They are generated on 2 occasions: (1) for -- declarations or dynamic allocations of Controlled objects with an -- initial value. (2) after an assignment. In the first case they are -- followed by an attachment to the final chain, in the second case -- they are not. -- Finalization Calls: They are generated on (1) scope exit, (2) -- assignments, (3) unchecked deallocations. In case (3) they have to -- be detached from the final chain, in case (2) they must not and in -- case (1) this is not important since we are exiting the scope -- anyway. -- Here is a simple example of the expansion of a controlled block : -- declare -- X : Controlled ; -- Y : Controlled := Init; -- -- type R is record -- C : Controlled; -- end record; -- W : R; -- Z : R := (C => X); -- begin -- X := Y; -- W := Z; -- end; -- -- is expanded into -- -- declare -- _L : System.FI.Finalizable_Ptr; -- procedure _Clean is -- begin -- Abort_Defer; -- System.FI.Finalize_List (_L); -- Abort_Undefer; -- end _Clean; -- X : Controlled; -- Initialize (X); -- Attach_To_Final_List (_L, Finalizable (X), 1); -- Y : Controlled := Init; -- Adjust (Y); -- Attach_To_Final_List (_L, Finalizable (Y), 1); -- -- type R is record -- _C : Record_Controller; -- C : Controlled; -- end record; -- W : R; -- Deep_Initialize (W, _L, 1); -- Z : R := (C => X); -- Deep_Adjust (Z, _L, 1); -- begin -- Finalize (X); -- X := Y; -- Adjust (X); -- Deep_Finalize (W, False); -- W := Z; -- Deep_Adjust (W, _L, 0); -- at end -- _Clean; -- end; function Global_Flist_Ref (Flist_Ref : Node_Id) return Boolean; -- Return True if Flist_Ref refers to a global final list, either -- the object GLobal_Final_List which is used to attach standalone -- objects, or any of the list controllers associated with library -- level access to controlled objects ---------------------------- -- Build_Array_Deep_Procs -- ---------------------------- procedure Build_Array_Deep_Procs (Typ : Entity_Id) is begin Set_TSS (Typ, Make_Deep_Proc ( Prim => Initialize_Case, Typ => Typ, Stmts => Make_Deep_Array_Body (Initialize_Case, Typ))); if not Is_Return_By_Reference_Type (Typ) then Set_TSS (Typ, Make_Deep_Proc ( Prim => Adjust_Case, Typ => Typ, Stmts => Make_Deep_Array_Body (Adjust_Case, Typ))); end if; Set_TSS (Typ, Make_Deep_Proc ( Prim => Finalize_Case, Typ => Typ, Stmts => Make_Deep_Array_Body (Finalize_Case, Typ))); end Build_Array_Deep_Procs; ----------------------------- -- Build_Controlling_Procs -- ----------------------------- procedure Build_Controlling_Procs (Typ : Entity_Id) is begin if Is_Array_Type (Typ) then Build_Array_Deep_Procs (Typ); else pragma Assert (Is_Record_Type (Typ)); Build_Record_Deep_Procs (Typ); end if; end Build_Controlling_Procs; ---------------------- -- Build_Final_List -- ---------------------- procedure Build_Final_List (N : Node_Id; Typ : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); begin Set_Associated_Final_Chain (Typ, Make_Defining_Identifier (Loc, New_External_Name (Chars (Typ), 'L'))); Insert_Action (N, Make_Object_Declaration (Loc, Defining_Identifier => Associated_Final_Chain (Typ), Object_Definition => New_Reference_To (RTE (RE_List_Controller), Loc))); end Build_Final_List; ----------------------------- -- Build_Record_Deep_Procs -- ----------------------------- procedure Build_Record_Deep_Procs (Typ : Entity_Id) is begin Set_TSS (Typ, Make_Deep_Proc ( Prim => Initialize_Case, Typ => Typ, Stmts => Make_Deep_Record_Body (Initialize_Case, Typ))); if not Is_Return_By_Reference_Type (Typ) then Set_TSS (Typ, Make_Deep_Proc ( Prim => Adjust_Case, Typ => Typ, Stmts => Make_Deep_Record_Body (Adjust_Case, Typ))); end if; Set_TSS (Typ, Make_Deep_Proc ( Prim => Finalize_Case, Typ => Typ, Stmts => Make_Deep_Record_Body (Finalize_Case, Typ))); end Build_Record_Deep_Procs; --------------------- -- Controlled_Type -- --------------------- function Controlled_Type (T : Entity_Id) return Boolean is begin -- Class-wide types are considered controlled because they may contain -- an extension that has controlled components return (Is_Class_Wide_Type (T) and then not No_Run_Time and then not In_Finalization_Root (T)) or else Is_Controlled (T) or else Has_Controlled_Component (T) or else (Is_Concurrent_Type (T) and then Present (Corresponding_Record_Type (T)) and then Controlled_Type (Corresponding_Record_Type (T))); end Controlled_Type; -------------------------- -- Controller_Component -- -------------------------- function Controller_Component (Typ : Entity_Id) return Entity_Id is T : Entity_Id := Base_Type (Typ); Comp : Entity_Id; Comp_Scop : Entity_Id; Res : Entity_Id := Empty; Res_Scop : Entity_Id := Empty; begin if Is_Class_Wide_Type (T) then T := Root_Type (T); end if; if Is_Private_Type (T) then T := Underlying_Type (T); end if; -- Fetch the outermost controller Comp := First_Entity (T); while Present (Comp) loop if Chars (Comp) = Name_uController then Comp_Scop := Scope (Original_Record_Component (Comp)); -- If this controller is at the outermost level, no need to -- look for another one if Comp_Scop = T then return Comp; -- Otherwise record the outermost one and continue looking elsif Res = Empty or else Is_Ancestor (Res_Scop, Comp_Scop) then Res := Comp; Res_Scop := Comp_Scop; end if; end if; Next_Entity (Comp); end loop; -- If we fall through the loop, there is no controller component return Res; end Controller_Component; ------------------ -- Convert_View -- ------------------ function Convert_View (Proc : Entity_Id; Arg : Node_Id; Ind : Pos := 1) return Node_Id is Fent : Entity_Id := First_Entity (Proc); Ftyp : Entity_Id; Atyp : Entity_Id; begin for J in 2 .. Ind loop Next_Entity (Fent); end loop; Ftyp := Etype (Fent); if Nkind (Arg) = N_Type_Conversion or else Nkind (Arg) = N_Unchecked_Type_Conversion then Atyp := Entity (Subtype_Mark (Arg)); else Atyp := Etype (Arg); end if; if Is_Abstract (Proc) and then Is_Tagged_Type (Ftyp) then return Unchecked_Convert_To (Class_Wide_Type (Ftyp), Arg); elsif Ftyp /= Atyp and then Present (Atyp) and then (Is_Private_Type (Ftyp) or else Is_Private_Type (Atyp)) and then Underlying_Type (Atyp) = Underlying_Type (Ftyp) then return Unchecked_Convert_To (Ftyp, Arg); -- If the argument is already a conversion, as generated by -- Make_Init_Call, set the target type to the type of the formal -- directly, to avoid spurious typing problems. elsif (Nkind (Arg) = N_Unchecked_Type_Conversion or else Nkind (Arg) = N_Type_Conversion) and then not Is_Class_Wide_Type (Atyp) then Set_Subtype_Mark (Arg, New_Occurrence_Of (Ftyp, Sloc (Arg))); Set_Etype (Arg, Ftyp); return Arg; else return Arg; end if; end Convert_View; ------------------------------- -- Establish_Transient_Scope -- ------------------------------- -- This procedure is called each time a transient block has to be inserted -- that is to say for each call to a function with unconstrained ot tagged -- result. It creates a new scope on the stack scope in order to enclose -- all transient variables generated procedure Establish_Transient_Scope (N : Node_Id; Sec_Stack : Boolean) is Loc : constant Source_Ptr := Sloc (N); Wrap_Node : Node_Id; Sec_Stk : constant Boolean := Sec_Stack and not Functions_Return_By_DSP_On_Target; -- We never need a secondary stack if functions return by DSP begin -- Do not create a transient scope if we are already inside one for S in reverse Scope_Stack.First .. Scope_Stack.Last loop if Scope_Stack.Table (S).Is_Transient then if Sec_Stk then Set_Uses_Sec_Stack (Scope_Stack.Table (S).Entity); end if; return; -- If we have encountered Standard there are no enclosing -- transient scopes. elsif Scope_Stack.Table (S).Entity = Standard_Standard then exit; end if; end loop; Wrap_Node := Find_Node_To_Be_Wrapped (N); -- Case of no wrap node, false alert, no transient scope needed if No (Wrap_Node) then null; -- Transient scope is required else New_Scope (New_Internal_Entity (E_Block, Current_Scope, Loc, 'B')); Set_Scope_Is_Transient; if Sec_Stk then Set_Uses_Sec_Stack (Current_Scope); Check_Restriction (No_Secondary_Stack, N); end if; Set_Etype (Current_Scope, Standard_Void_Type); Set_Node_To_Be_Wrapped (Wrap_Node); if Debug_Flag_W then Write_Str (" <Transient>"); Write_Eol; end if; end if; end Establish_Transient_Scope; ---------------------------- -- Expand_Cleanup_Actions -- ---------------------------- procedure Expand_Cleanup_Actions (N : Node_Id) is Loc : Source_Ptr; S : constant Entity_Id := Current_Scope; Flist : constant Entity_Id := Finalization_Chain_Entity (S); Is_Task : constant Boolean := (Nkind (Original_Node (N)) = N_Task_Body); Is_Master : constant Boolean := Nkind (N) /= N_Entry_Body and then Is_Task_Master (N); Is_Protected : constant Boolean := Nkind (N) = N_Subprogram_Body and then Is_Protected_Subprogram_Body (N); Is_Task_Allocation : constant Boolean := Nkind (N) = N_Block_Statement and then Is_Task_Allocation_Block (N); Is_Asynchronous_Call : constant Boolean := Nkind (N) = N_Block_Statement and then Is_Asynchronous_Call_Block (N); Clean : Entity_Id; Mark : Entity_Id := Empty; New_Decls : List_Id := New_List; Blok : Node_Id; Wrapped : Boolean; Chain : Entity_Id := Empty; Decl : Node_Id; Old_Poll : Boolean; begin -- Compute a location that is not directly in the user code in -- order to avoid to generate confusing debug info. A good -- approximation is the name of the outer user-defined scope declare S1 : Entity_Id := S; begin while not Comes_From_Source (S1) and then S1 /= Standard_Standard loop S1 := Scope (S1); end loop; Loc := Sloc (S1); end; -- There are cleanup actions only if the secondary stack needs -- releasing or some finalizations are needed or in the context -- of tasking if Uses_Sec_Stack (Current_Scope) and then not Sec_Stack_Needed_For_Return (Current_Scope) then null; elsif No (Flist) and then not Is_Master and then not Is_Task and then not Is_Protected and then not Is_Task_Allocation and then not Is_Asynchronous_Call then return; end if; -- Set polling off, since we don't need to poll during cleanup -- actions, and indeed for the cleanup routine, which is executed -- with aborts deferred, we don't want polling. Old_Poll := Polling_Required; Polling_Required := False; -- Make sure we have a declaration list, since we will add to it if No (Declarations (N)) then Set_Declarations (N, New_List); end if; -- The task activation call has already been built for task -- allocation blocks. if not Is_Task_Allocation then Build_Task_Activation_Call (N); end if; if Is_Master then Establish_Task_Master (N); end if; -- If secondary stack is in use, expand: -- _Mxx : constant Mark_Id := SS_Mark; -- Suppress calls to SS_Mark and SS_Release if Java_VM, -- since we never use the secondary stack on the JVM. if Uses_Sec_Stack (Current_Scope) and then not Sec_Stack_Needed_For_Return (Current_Scope) and then not Java_VM then Mark := Make_Defining_Identifier (Loc, New_Internal_Name ('M')); Append_To (New_Decls, Make_Object_Declaration (Loc, Defining_Identifier => Mark, Object_Definition => New_Reference_To (RTE (RE_Mark_Id), Loc), Expression => Make_Function_Call (Loc, Name => New_Reference_To (RTE (RE_SS_Mark), Loc)))); Set_Uses_Sec_Stack (Current_Scope, False); end if; -- If finalization list is present then expand: -- Local_Final_List : System.FI.Finalizable_Ptr; if Present (Flist) then Append_To (New_Decls, Make_Object_Declaration (Loc, Defining_Identifier => Flist, Object_Definition => New_Reference_To (RTE (RE_Finalizable_Ptr), Loc))); end if; -- Clean-up procedure definition Clean := Make_Defining_Identifier (Loc, Name_uClean); Set_Suppress_Elaboration_Warnings (Clean); Append_To (New_Decls, Make_Clean (N, Clean, Mark, Flist, Is_Task, Is_Master, Is_Protected, Is_Task_Allocation, Is_Asynchronous_Call)); -- If exception handlers are present, wrap the Sequence of -- statements in a block because it is not possible to get -- exception handlers and an AT END call in the same scope. if Present (Exception_Handlers (Handled_Statement_Sequence (N))) then Blok := Make_Block_Statement (Loc, Handled_Statement_Sequence => Handled_Statement_Sequence (N)); Set_Handled_Statement_Sequence (N, Make_Handled_Sequence_Of_Statements (Loc, New_List (Blok))); Wrapped := True; -- Otherwise we do not wrap else Wrapped := False; Blok := Empty; end if; -- Don't move the _chain Activation_Chain declaration in task -- allocation blocks. Task allocation blocks use this object -- in their cleanup handlers, and gigi complains if it is declared -- in the sequence of statements of the scope that declares the -- handler. if Is_Task_Allocation then Chain := Activation_Chain_Entity (N); Decl := First (Declarations (N)); while Nkind (Decl) /= N_Object_Declaration or else Defining_Identifier (Decl) /= Chain loop Next (Decl); pragma Assert (Present (Decl)); end loop; Remove (Decl); Prepend_To (New_Decls, Decl); end if; -- Now we move the declarations into the Sequence of statements -- in order to get them protected by the AT END call. It may seem -- weird to put declarations in the sequence of statement but in -- fact nothing forbids that at the tree level. We also set the -- First_Real_Statement field so that we remember where the real -- statements (i.e. original statements) begin. Note that if we -- wrapped the statements, the first real statement is inside the -- inner block. If the First_Real_Statement is already set (as is -- the case for subprogram bodies that are expansions of task bodies) -- then do not reset it, because its declarative part would migrate -- to the statement part. if not Wrapped then if No (First_Real_Statement (Handled_Statement_Sequence (N))) then Set_First_Real_Statement (Handled_Statement_Sequence (N), First (Statements (Handled_Statement_Sequence (N)))); end if; else Set_First_Real_Statement (Handled_Statement_Sequence (N), Blok); end if; Append_List_To (Declarations (N), Statements (Handled_Statement_Sequence (N))); Set_Statements (Handled_Statement_Sequence (N), Declarations (N)); -- We need to reset the Sloc of the handled statement sequence to -- properly reflect the new initial "statement" in the sequence. Set_Sloc (Handled_Statement_Sequence (N), Sloc (First (Declarations (N)))); -- The declarations of the _Clean procedure and finalization chain -- replace the old declarations that have been moved inward Set_Declarations (N, New_Decls); Analyze_Declarations (New_Decls); -- The At_End call is attached to the sequence of statements. declare HSS : Node_Id; begin -- If the construct is a protected subprogram, then the call to -- the corresponding unprotected program appears in a block which -- is the last statement in the body, and it is this block that -- must be covered by the At_End handler. if Is_Protected then HSS := Handled_Statement_Sequence (Last (Statements (Handled_Statement_Sequence (N)))); else HSS := Handled_Statement_Sequence (N); end if; Set_At_End_Proc (HSS, New_Occurrence_Of (Clean, Loc)); Expand_At_End_Handler (HSS, Empty); end; -- Restore saved polling mode Polling_Required := Old_Poll; end Expand_Cleanup_Actions; ------------------------------- -- Expand_Ctrl_Function_Call -- ------------------------------- procedure Expand_Ctrl_Function_Call (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Rtype : constant Entity_Id := Etype (N); Utype : constant Entity_Id := Underlying_Type (Rtype); Ref : Node_Id; Action : Node_Id; Attach_Level : Uint := Uint_1; Len_Ref : Node_Id := Empty; function Last_Array_Component (Ref : Node_Id; Typ : Entity_Id) return Node_Id; -- Creates a reference to the last component of the array object -- designated by Ref whose type is Typ. function Last_Array_Component (Ref : Node_Id; Typ : Entity_Id) return Node_Id is N : Int; Index_List : List_Id := New_List; begin N := 1; while N <= Number_Dimensions (Typ) loop Append_To (Index_List, Make_Attribute_Reference (Loc, Prefix => Duplicate_Subexpr (Ref), Attribute_Name => Name_Last, Expressions => New_List ( Make_Integer_Literal (Loc, N)))); N := N + 1; end loop; return Make_Indexed_Component (Loc, Prefix => Duplicate_Subexpr (Ref), Expressions => Index_List); end Last_Array_Component; -- Start of processing for Expand_Ctrl_Function_Call begin -- Optimization, if the returned value (which is on the sec-stack) -- is returned again, no need to copy/readjust/finalize, we can just -- pass the value thru (see Expand_N_Return_Statement), and thus no -- attachment is needed if Nkind (Parent (N)) = N_Return_Statement then return; end if; -- Resolution is now finished, make sure we don't start analysis again -- because of the duplication Set_Analyzed (N); Ref := Duplicate_Subexpr (N); -- Now we can generate the Attach Call, note that this value is -- always in the (secondary) stack and thus is attached to a singly -- linked final list: -- -- Resx := F (X)'reference; -- Attach_To_Final_List (_Lx, Resx.all, 1); -- or when there are controlled components -- Attach_To_Final_List (_Lx, Resx._controller, 1); -- or if it is an array with is_controlled components -- Attach_To_Final_List (_Lx, Resx (Resx'last), 3); -- An attach level of 3 means that a whole array is to be -- attached to the finalization list -- or if it is an array with has_controlled components -- Attach_To_Final_List (_Lx, Resx (Resx'last)._controller, 3); if Has_Controlled_Component (Rtype) then declare T1 : Entity_Id := Rtype; T2 : Entity_Id := Utype; begin if Is_Array_Type (T2) then Len_Ref := Make_Attribute_Reference (Loc, Prefix => Duplicate_Subexpr (Unchecked_Convert_To (T2, Ref)), Attribute_Name => Name_Length); end if; while Is_Array_Type (T2) loop if T1 /= T2 then Ref := Unchecked_Convert_To (T2, Ref); end if; Ref := Last_Array_Component (Ref, T2); Attach_Level := Uint_3; T1 := Component_Type (T2); T2 := Underlying_Type (T1); end loop; if Has_Controlled_Component (T2) then if T1 /= T2 then Ref := Unchecked_Convert_To (T2, Ref); end if; Ref := Make_Selected_Component (Loc, Prefix => Ref, Selector_Name => Make_Identifier (Loc, Name_uController)); end if; end; -- Here we know that 'Ref' has a controller so we may as well -- attach it directly Action := Make_Attach_Call ( Obj_Ref => Ref, Flist_Ref => Find_Final_List (Current_Scope), With_Attach => Make_Integer_Literal (Loc, Attach_Level)); else -- Here, we have a controlled type that does not seem to have -- controlled components but it could be a class wide type whose -- further derivations have controlled components. So we don't know -- if the object itself needs to be attached or if it -- has a record controller. We need to call a runtime function -- (Deep_Tag_Attach) which knows what to do thanks to the -- RC_Offset in the dispatch table. Action := Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (RTE (RE_Deep_Tag_Attach), Loc), Parameter_Associations => New_List ( Find_Final_List (Current_Scope), Make_Attribute_Reference (Loc, Prefix => Ref, Attribute_Name => Name_Address), Make_Integer_Literal (Loc, Attach_Level))); end if; if Present (Len_Ref) then Action := Make_Implicit_If_Statement (N, Condition => Make_Op_Gt (Loc, Left_Opnd => Len_Ref, Right_Opnd => Make_Integer_Literal (Loc, 0)), Then_Statements => New_List (Action)); end if; Insert_Action (N, Action); end Expand_Ctrl_Function_Call; --------------------------- -- Expand_N_Package_Body -- --------------------------- -- Add call to Activate_Tasks if body is an activator (actual -- processing is in chapter 9). -- Generate subprogram descriptor for elaboration routine -- ENcode entity names in package body procedure Expand_N_Package_Body (N : Node_Id) is Ent : Entity_Id := Corresponding_Spec (N); begin -- This is done only for non-generic packages if Ekind (Ent) = E_Package then New_Scope (Corresponding_Spec (N)); Build_Task_Activation_Call (N); Pop_Scope; end if; Set_Elaboration_Flag (N, Corresponding_Spec (N)); -- Generate a subprogram descriptor for the elaboration routine of -- a package body if the package body has no pending instantiations -- and it has generated at least one exception handler if Present (Handler_Records (Body_Entity (Ent))) and then Is_Compilation_Unit (Ent) and then not Delay_Subprogram_Descriptors (Body_Entity (Ent)) then Generate_Subprogram_Descriptor_For_Package (N, Body_Entity (Ent)); end if; Set_In_Package_Body (Ent, False); -- Set to encode entity names in package body before gigi is called Qualify_Entity_Names (N); end Expand_N_Package_Body; ---------------------------------- -- Expand_N_Package_Declaration -- ---------------------------------- -- Add call to Activate_Tasks if there are tasks declared and the -- package has no body. Note that in Ada83, this may result in -- premature activation of some tasks, given that we cannot tell -- whether a body will eventually appear. procedure Expand_N_Package_Declaration (N : Node_Id) is begin if Nkind (Parent (N)) = N_Compilation_Unit and then not Body_Required (Parent (N)) and then not Unit_Requires_Body (Defining_Entity (N)) and then Present (Activation_Chain_Entity (N)) then New_Scope (Defining_Entity (N)); Build_Task_Activation_Call (N); Pop_Scope; end if; -- Note: it is not necessary to worry about generating a subprogram -- descriptor, since the only way to get exception handlers into a -- package spec is to include instantiations, and that would cause -- generation of subprogram descriptors to be delayed in any case. -- Set to encode entity names in package spec before gigi is called Qualify_Entity_Names (N); end Expand_N_Package_Declaration; --------------------- -- Find_Final_List -- --------------------- function Find_Final_List (E : Entity_Id; Ref : Node_Id := Empty) return Node_Id is Loc : constant Source_Ptr := Sloc (Ref); S : Entity_Id; Id : Entity_Id; R : Node_Id; begin -- Case of an internal component. The Final list is the record -- controller of the enclosing record if Present (Ref) then R := Ref; loop case Nkind (R) is when N_Unchecked_Type_Conversion | N_Type_Conversion => R := Expression (R); when N_Indexed_Component | N_Explicit_Dereference => R := Prefix (R); when N_Selected_Component => R := Prefix (R); exit; when N_Identifier => exit; when others => raise Program_Error; end case; end loop; return Make_Selected_Component (Loc, Prefix => Make_Selected_Component (Loc, Prefix => R, Selector_Name => Make_Identifier (Loc, Name_uController)), Selector_Name => Make_Identifier (Loc, Name_F)); -- Case of a dynamically allocated object. The final list is the -- corresponding list controller (The next entity in the scope of -- the access type with the right type). If the type comes from a -- With_Type clause, no controller was created, and we use the -- global chain instead. elsif Is_Access_Type (E) then if not From_With_Type (E) then return Make_Selected_Component (Loc, Prefix => New_Reference_To (Associated_Final_Chain (Base_Type (E)), Loc), Selector_Name => Make_Identifier (Loc, Name_F)); else return New_Reference_To (RTE (RE_Global_Final_List), Sloc (E)); end if; else if Is_Dynamic_Scope (E) then S := E; else S := Enclosing_Dynamic_Scope (E); end if; -- When the finalization chain entity is 'Error', it means that -- there should not be any chain at that level and that the -- enclosing one should be used -- This is a nasty kludge, see ??? note in exp_ch11 while Finalization_Chain_Entity (S) = Error loop S := Enclosing_Dynamic_Scope (S); end loop; if S = Standard_Standard then return New_Reference_To (RTE (RE_Global_Final_List), Sloc (E)); else if No (Finalization_Chain_Entity (S)) then Id := Make_Defining_Identifier (Sloc (S), New_Internal_Name ('F')); Set_Finalization_Chain_Entity (S, Id); -- Set momentarily some semantics attributes to allow normal -- analysis of expansions containing references to this chain. -- Will be fully decorated during the expansion of the scope -- itself Set_Ekind (Id, E_Variable); Set_Etype (Id, RTE (RE_Finalizable_Ptr)); end if; return New_Reference_To (Finalization_Chain_Entity (S), Sloc (E)); end if; end if; end Find_Final_List; ----------------------------- -- Find_Node_To_Be_Wrapped -- ----------------------------- function Find_Node_To_Be_Wrapped (N : Node_Id) return Node_Id is P : Node_Id; The_Parent : Node_Id; begin The_Parent := N; loop P := The_Parent; pragma Assert (P /= Empty); The_Parent := Parent (P); case Nkind (The_Parent) is -- Simple statement can be wrapped when N_Pragma => return The_Parent; -- Usually assignments are good candidate for wrapping -- except when they have been generated as part of a -- controlled aggregate where the wrapping should take -- place more globally. when N_Assignment_Statement => if No_Ctrl_Actions (The_Parent) then null; else return The_Parent; end if; -- An entry call statement is a special case if it occurs in -- the context of a Timed_Entry_Call. In this case we wrap -- the entire timed entry call. when N_Entry_Call_Statement | N_Procedure_Call_Statement => if Nkind (Parent (The_Parent)) = N_Entry_Call_Alternative and then Nkind (Parent (Parent (The_Parent))) = N_Timed_Entry_Call then return Parent (Parent (The_Parent)); else return The_Parent; end if; -- Object declarations are also a boundary for the transient scope -- even if they are not really wrapped -- (see Wrap_Transient_Declaration) when N_Object_Declaration | N_Object_Renaming_Declaration | N_Subtype_Declaration => return The_Parent; -- The expression itself is to be wrapped if its parent is a -- compound statement or any other statement where the expression -- is known to be scalar when N_Accept_Alternative | N_Attribute_Definition_Clause | N_Case_Statement | N_Code_Statement | N_Delay_Alternative | N_Delay_Until_Statement | N_Delay_Relative_Statement | N_Discriminant_Association | N_Elsif_Part | N_Entry_Body_Formal_Part | N_Exit_Statement | N_If_Statement | N_Iteration_Scheme | N_Terminate_Alternative => return P; when N_Attribute_Reference => if Is_Procedure_Attribute_Name (Attribute_Name (The_Parent)) then return The_Parent; end if; -- ??? No scheme yet for "for I in Expression'Range loop" -- ??? the current scheme for Expression wrapping doesn't apply -- ??? because a RANGE is NOT an expression. Tricky problem... -- ??? while this problem is not solved we have a potential for -- ??? leak and unfinalized intermediate objects here. when N_Loop_Parameter_Specification => return Empty; -- The following nodes contains "dummy calls" which don't -- need to be wrapped. when N_Parameter_Specification | N_Discriminant_Specification | N_Component_Declaration => return Empty; -- The return statement is not to be wrapped when the function -- itself needs wrapping at the outer-level when N_Return_Statement => if Requires_Transient_Scope (Return_Type (The_Parent)) then return Empty; else return The_Parent; end if; -- If we leave a scope without having been able to find a node to -- wrap, something is going wrong but this can happen in error -- situation that are not detected yet (such as a dynamic string -- in a pragma export) when N_Subprogram_Body | N_Package_Declaration | N_Package_Body | N_Block_Statement => return Empty; -- otherwise continue the search when others => null; end case; end loop; end Find_Node_To_Be_Wrapped; ---------------------- -- Global_Flist_Ref -- ---------------------- function Global_Flist_Ref (Flist_Ref : Node_Id) return Boolean is Flist : Entity_Id; begin -- Look for the Global_Final_List if Is_Entity_Name (Flist_Ref) then Flist := Entity (Flist_Ref); -- Look for the final list associated with an access to controlled elsif Nkind (Flist_Ref) = N_Selected_Component and then Is_Entity_Name (Prefix (Flist_Ref)) then Flist := Entity (Prefix (Flist_Ref)); else return False; end if; return Present (Flist) and then Present (Scope (Flist)) and then Enclosing_Dynamic_Scope (Flist) = Standard_Standard; end Global_Flist_Ref; ---------------------------------- -- Has_New_Controlled_Component -- ---------------------------------- function Has_New_Controlled_Component (E : Entity_Id) return Boolean is Comp : Entity_Id; begin if not Is_Tagged_Type (E) then return Has_Controlled_Component (E); elsif not Is_Derived_Type (E) then return Has_Controlled_Component (E); end if; Comp := First_Component (E); while Present (Comp) loop if Chars (Comp) = Name_uParent then null; elsif Scope (Original_Record_Component (Comp)) = E and then Controlled_Type (Etype (Comp)) then return True; end if; Next_Component (Comp); end loop; return False; end Has_New_Controlled_Component; -------------------------- -- In_Finalization_Root -- -------------------------- -- It would seem simpler to test Scope (RTE (RE_Root_Controlled)) but -- the purpose of this function is to avoid a circular call to Rtsfind -- which would been caused by such a test. function In_Finalization_Root (E : Entity_Id) return Boolean is S : constant Entity_Id := Scope (E); begin return Chars (Scope (S)) = Name_System and then Chars (S) = Name_Finalization_Root and then Scope (Scope (S)) = Standard_Standard; end In_Finalization_Root; ------------------------------------ -- Insert_Actions_In_Scope_Around -- ------------------------------------ procedure Insert_Actions_In_Scope_Around (N : Node_Id) is SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last); begin if Present (SE.Actions_To_Be_Wrapped_Before) then Insert_List_Before (N, SE.Actions_To_Be_Wrapped_Before); SE.Actions_To_Be_Wrapped_Before := No_List; end if; if Present (SE.Actions_To_Be_Wrapped_After) then Insert_List_After (N, SE.Actions_To_Be_Wrapped_After); SE.Actions_To_Be_Wrapped_After := No_List; end if; end Insert_Actions_In_Scope_Around; ----------------------- -- Make_Adjust_Call -- ----------------------- function Make_Adjust_Call (Ref : Node_Id; Typ : Entity_Id; Flist_Ref : Node_Id; With_Attach : Node_Id) return List_Id is Loc : constant Source_Ptr := Sloc (Ref); Res : constant List_Id := New_List; Utyp : Entity_Id; Proc : Entity_Id; Cref : Node_Id := Ref; Cref2 : Node_Id; Attach : Node_Id := With_Attach; begin if Is_Class_Wide_Type (Typ) then Utyp := Underlying_Type (Base_Type (Root_Type (Typ))); else Utyp := Underlying_Type (Base_Type (Typ)); end if; Set_Assignment_OK (Cref); -- Deal with non-tagged derivation of private views if Is_Untagged_Derivation (Typ) then Utyp := Underlying_Type (Root_Type (Base_Type (Typ))); Cref := Unchecked_Convert_To (Utyp, Cref); Set_Assignment_OK (Cref); -- To prevent problems with UC see 1.156 RH ??? 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); Cref := Unchecked_Convert_To (Utyp, Cref); end if; -- We do not need to attach to one of the Global Final Lists -- the objects whose type is Finalize_Storage_Only if Finalize_Storage_Only (Typ) and then (Global_Flist_Ref (Flist_Ref) or else Entity (Constant_Value (RTE (RE_Garbage_Collected))) = Standard_True) then Attach := Make_Integer_Literal (Loc, 0); end if; -- Generate: -- Deep_Adjust (Flist_Ref, Ref, With_Attach); if Has_Controlled_Component (Utyp) or else Is_Class_Wide_Type (Typ) then if Is_Tagged_Type (Utyp) then Proc := Find_Prim_Op (Utyp, Deep_Name_Of (Adjust_Case)); else Proc := TSS (Utyp, Deep_Name_Of (Adjust_Case)); end if; Cref := Convert_View (Proc, Cref, 2); Append_To (Res, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (Proc, Loc), Parameter_Associations => New_List (Flist_Ref, Cref, Attach))); -- Generate: -- if With_Attach then -- Attach_To_Final_List (Ref, Flist_Ref); -- end if; -- Adjust (Ref); else -- Is_Controlled (Utyp) Proc := Find_Prim_Op (Utyp, Name_Of (Adjust_Case)); Cref := Convert_View (Proc, Cref); Cref2 := New_Copy_Tree (Cref); Append_To (Res, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (Proc, Loc), Parameter_Associations => New_List (Cref2))); Append_To (Res, Make_Attach_Call (Cref, Flist_Ref, Attach)); -- Treat this as a reference to Adjust if the Adjust routine -- comes from source. The call is not explicit, but it is near -- enough, and we won't typically get explicit adjust calls. if Comes_From_Source (Proc) then Generate_Reference (Proc, Ref); end if; end if; return Res; end Make_Adjust_Call; ---------------------- -- Make_Attach_Call -- ---------------------- -- Generate: -- System.FI.Attach_To_Final_List (Flist, Ref, Nb_Link) function Make_Attach_Call (Obj_Ref : Node_Id; Flist_Ref : Node_Id; With_Attach : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Obj_Ref); begin -- Optimization: If the number of links is statically '0', don't -- call the attach_proc. if Nkind (With_Attach) = N_Integer_Literal and then Intval (With_Attach) = Uint_0 then return Make_Null_Statement (Loc); end if; return Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (RTE (RE_Attach_To_Final_List), Loc), Parameter_Associations => New_List ( Flist_Ref, OK_Convert_To (RTE (RE_Finalizable), Obj_Ref), With_Attach)); end Make_Attach_Call; ---------------- -- Make_Clean -- ---------------- function Make_Clean (N : Node_Id; Clean : Entity_Id; Mark : Entity_Id; Flist : Entity_Id; Is_Task : Boolean; Is_Master : Boolean; Is_Protected_Subprogram : Boolean; Is_Task_Allocation_Block : Boolean; Is_Asynchronous_Call_Block : Boolean) return Node_Id is Loc : constant Source_Ptr := Sloc (Clean); Stmt : List_Id := New_List; Sbody : Node_Id; Spec : Node_Id; Name : Node_Id; Param : Node_Id; Unlock : Node_Id; Param_Type : Entity_Id; Pid : Entity_Id := Empty; Cancel_Param : Entity_Id; begin if Is_Task then if Restricted_Profile then Append_To (Stmt, Build_Runtime_Call (Loc, RE_Complete_Restricted_Task)); else Append_To (Stmt, Build_Runtime_Call (Loc, RE_Complete_Task)); end if; elsif Is_Master then if Restrictions (No_Task_Hierarchy) = False then Append_To (Stmt, Build_Runtime_Call (Loc, RE_Complete_Master)); end if; elsif Is_Protected_Subprogram then -- Add statements to the cleanup handler of the (ordinary) -- subprogram expanded to implement a protected subprogram, -- unlocking the protected object parameter and undeferring abortion. -- If this is a protected procedure, and the object contains -- entries, this also calls the entry service routine. -- NOTE: This cleanup handler references _object, a parameter -- to the procedure. -- Find the _object parameter representing the protected object. Spec := Parent (Corresponding_Spec (N)); Param := First (Parameter_Specifications (Spec)); loop Param_Type := Etype (Parameter_Type (Param)); if Ekind (Param_Type) = E_Record_Type then Pid := Corresponding_Concurrent_Type (Param_Type); end if; exit when not Present (Param) or else Present (Pid); Next (Param); end loop; pragma Assert (Present (Param)); -- If the associated protected object declares entries, -- a protected procedure has to service entry queues. -- In this case, add -- Service_Entries (_object._object'Access); -- _object is the record used to implement the protected object. -- It is a parameter to the protected subprogram. if Nkind (Specification (N)) = N_Procedure_Specification and then Has_Entries (Pid) then if Abort_Allowed or else Restrictions (No_Entry_Queue) = False or else Number_Entries (Pid) > 1 then Name := New_Reference_To (RTE (RE_Service_Entries), Loc); else Name := New_Reference_To (RTE (RE_Service_Entry), Loc); end if; Append_To (Stmt, Make_Procedure_Call_Statement (Loc, Name => Name, Parameter_Associations => New_List ( Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Reference_To ( Defining_Identifier (Param), Loc), Selector_Name => Make_Identifier (Loc, Name_uObject)), Attribute_Name => Name_Unchecked_Access)))); end if; -- Unlock (_object._object'Access); -- _object is the record used to implement the protected object. -- It is a parameter to the protected subprogram. -- If the protected object is controlled (i.e it has entries or -- needs finalization for interrupt handling), call Unlock_Entries, -- except if the protected object follows the ravenscar profile, in -- which case call Unlock_Entry, otherwise call the simplified -- version, Unlock. if Has_Entries (Pid) or else Has_Interrupt_Handler (Pid) or else Has_Attach_Handler (Pid) then if Abort_Allowed or else Restrictions (No_Entry_Queue) = False or else Number_Entries (Pid) > 1 then Unlock := New_Reference_To (RTE (RE_Unlock_Entries), Loc); else Unlock := New_Reference_To (RTE (RE_Unlock_Entry), Loc); end if; else Unlock := New_Reference_To (RTE (RE_Unlock), Loc); end if; Append_To (Stmt, Make_Procedure_Call_Statement (Loc, Name => Unlock, Parameter_Associations => New_List ( Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Reference_To (Defining_Identifier (Param), Loc), Selector_Name => Make_Identifier (Loc, Name_uObject)), Attribute_Name => Name_Unchecked_Access)))); if Abort_Allowed then -- Abort_Undefer; Append_To (Stmt, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To ( RTE (RE_Abort_Undefer), Loc), Parameter_Associations => Empty_List)); end if; elsif Is_Task_Allocation_Block then -- Add a call to Expunge_Unactivated_Tasks to the cleanup -- handler of a block created for the dynamic allocation of -- tasks: -- Expunge_Unactivated_Tasks (_chain); -- where _chain is the list of tasks created by the allocator -- but not yet activated. This list will be empty unless -- the block completes abnormally. -- This only applies to dynamically allocated tasks; -- other unactivated tasks are completed by Complete_Task or -- Complete_Master. -- NOTE: This cleanup handler references _chain, a local -- object. Append_To (Stmt, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To ( RTE (RE_Expunge_Unactivated_Tasks), Loc), Parameter_Associations => New_List ( New_Reference_To (Activation_Chain_Entity (N), Loc)))); elsif Is_Asynchronous_Call_Block then -- Add a call to attempt to cancel the asynchronous entry call -- whenever the block containing the abortable part is exited. -- NOTE: This cleanup handler references C, a local object -- Get the argument to the Cancel procedure Cancel_Param := Entry_Cancel_Parameter (Entity (Identifier (N))); -- If it is of type Communication_Block, this must be a -- protected entry call. if Is_RTE (Etype (Cancel_Param), RE_Communication_Block) then Append_To (Stmt, -- if Enqueued (Cancel_Parameter) then Make_Implicit_If_Statement (Clean, Condition => Make_Function_Call (Loc, Name => New_Reference_To ( RTE (RE_Enqueued), Loc), Parameter_Associations => New_List ( New_Reference_To (Cancel_Param, Loc))), Then_Statements => New_List ( -- Cancel_Protected_Entry_Call (Cancel_Param); Make_Procedure_Call_Statement (Loc, Name => New_Reference_To ( RTE (RE_Cancel_Protected_Entry_Call), Loc), Parameter_Associations => New_List ( New_Reference_To (Cancel_Param, Loc)))))); -- Asynchronous delay elsif Is_RTE (Etype (Cancel_Param), RE_Delay_Block) then Append_To (Stmt, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (RTE (RE_Cancel_Async_Delay), Loc), Parameter_Associations => New_List ( Make_Attribute_Reference (Loc, Prefix => New_Reference_To (Cancel_Param, Loc), Attribute_Name => Name_Unchecked_Access)))); -- Task entry call else -- Append call to Cancel_Task_Entry_Call (C); Append_To (Stmt, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To ( RTE (RE_Cancel_Task_Entry_Call), Loc), Parameter_Associations => New_List ( New_Reference_To (Cancel_Param, Loc)))); end if; end if; if Present (Flist) then Append_To (Stmt, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (RTE (RE_Finalize_List), Loc), Parameter_Associations => New_List ( New_Reference_To (Flist, Loc)))); end if; if Present (Mark) then Append_To (Stmt, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (RTE (RE_SS_Release), Loc), Parameter_Associations => New_List ( New_Reference_To (Mark, Loc)))); end if; Sbody := Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Clean), Declarations => New_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmt)); if Present (Flist) or else Is_Task or else Is_Master then Wrap_Cleanup_Procedure (Sbody); end if; -- We do not want debug information for _Clean routines, -- since it just confuses the debugging operation unless -- we are debugging generated code. if not Debug_Generated_Code then Set_Debug_Info_Off (Clean, True); end if; return Sbody; end Make_Clean; -------------------------- -- Make_Deep_Array_Body -- -------------------------- -- Array components are initialized and adjusted in the normal order -- and finalized in the reverse order. Exceptions are handled and -- Program_Error is re-raise in the Adjust and Finalize case -- (RM 7.6.1(12)). Generate the following code : -- -- procedure Deep_<P> -- with <P> being Initialize or Adjust or Finalize -- (L : in out Finalizable_Ptr; -- V : in out Typ) -- is -- begin -- for J1 in Typ'First (1) .. Typ'Last (1) loop -- ^ reverse ^ -- in the finalization case -- ... -- for J2 in Typ'First (n) .. Typ'Last (n) loop -- Make_<P>_Call (Typ, V (J1, .. , Jn), L, V); -- end loop; -- ... -- end loop; -- exception -- not in the -- when others => raise Program_Error; -- Initialize case -- end Deep_<P>; function Make_Deep_Array_Body (Prim : Final_Primitives; Typ : Entity_Id) return List_Id is Loc : constant Source_Ptr := Sloc (Typ); Index_List : constant List_Id := New_List; -- Stores the list of references to the indexes (one per dimension) function One_Component return List_Id; -- Create one statement to initialize/adjust/finalize one array -- component, designated by a full set of indices. function One_Dimension (N : Int) return List_Id; -- Create loop to deal with one dimension of the array. The single -- statement in the body of the loop initializes the inner dimensions if -- any, or else a single component. ------------------- -- One_Component -- ------------------- function One_Component return List_Id is Comp_Typ : constant Entity_Id := Component_Type (Typ); Comp_Ref : constant Node_Id := Make_Indexed_Component (Loc, Prefix => Make_Identifier (Loc, Name_V), Expressions => Index_List); begin -- Set the etype of the component Reference, which is used to -- determine whether a conversion to a parent type is needed. Set_Etype (Comp_Ref, Comp_Typ); case Prim is when Initialize_Case => return Make_Init_Call (Comp_Ref, Comp_Typ, Make_Identifier (Loc, Name_L), Make_Identifier (Loc, Name_B)); when Adjust_Case => return Make_Adjust_Call (Comp_Ref, Comp_Typ, Make_Identifier (Loc, Name_L), Make_Identifier (Loc, Name_B)); when Finalize_Case => return Make_Final_Call (Comp_Ref, Comp_Typ, Make_Identifier (Loc, Name_B)); end case; end One_Component; ------------------- -- One_Dimension -- ------------------- function One_Dimension (N : Int) return List_Id is Index : Entity_Id; begin if N > Number_Dimensions (Typ) then return One_Component; else Index := Make_Defining_Identifier (Loc, New_External_Name ('J', N)); Append_To (Index_List, New_Reference_To (Index, Loc)); return New_List ( Make_Implicit_Loop_Statement (Typ, Identifier => Empty, Iteration_Scheme => Make_Iteration_Scheme (Loc, Loop_Parameter_Specification => Make_Loop_Parameter_Specification (Loc, Defining_Identifier => Index, Discrete_Subtype_Definition => Make_Attribute_Reference (Loc, Prefix => Make_Identifier (Loc, Name_V), Attribute_Name => Name_Range, Expressions => New_List ( Make_Integer_Literal (Loc, N))), Reverse_Present => Prim = Finalize_Case)), Statements => One_Dimension (N + 1))); end if; end One_Dimension; -- Start of processing for Make_Deep_Array_Body begin return One_Dimension (1); end Make_Deep_Array_Body; -------------------- -- Make_Deep_Proc -- -------------------- -- Generate: -- procedure DEEP_<prim> -- (L : IN OUT Finalizable_Ptr; -- not for Finalize -- V : IN OUT <typ>; -- B : IN Short_Short_Integer) is -- begin -- <stmts>; -- exception -- Finalize and Adjust Cases only -- raise Program_Error; -- idem -- end DEEP_<prim>; function Make_Deep_Proc (Prim : Final_Primitives; Typ : Entity_Id; Stmts : List_Id) return Entity_Id is Loc : constant Source_Ptr := Sloc (Typ); Formals : List_Id; Proc_Name : Entity_Id; Handler : List_Id := No_List; Subp_Body : Node_Id; Type_B : Entity_Id; begin if Prim = Finalize_Case then Formals := New_List; Type_B := Standard_Boolean; else Formals := New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_L), In_Present => True, Out_Present => True, Parameter_Type => New_Reference_To (RTE (RE_Finalizable_Ptr), Loc))); Type_B := Standard_Short_Short_Integer; end if; Append_To (Formals, Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_V), In_Present => True, Out_Present => True, Parameter_Type => New_Reference_To (Typ, Loc))); Append_To (Formals, Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_B), Parameter_Type => New_Reference_To (Type_B, Loc))); if Prim = Finalize_Case or else Prim = Adjust_Case then Handler := New_List ( Make_Exception_Handler (Loc, Exception_Choices => New_List (Make_Others_Choice (Loc)), Statements => New_List ( Make_Raise_Program_Error (Loc)))); end if; Proc_Name := Make_Defining_Identifier (Loc, Deep_Name_Of (Prim)); Subp_Body := Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Proc_Name, Parameter_Specifications => Formals), Declarations => Empty_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Stmts, Exception_Handlers => Handler)); return Proc_Name; end Make_Deep_Proc; --------------------------- -- Make_Deep_Record_Body -- --------------------------- -- The Deep procedures call the appropriate Controlling proc on the -- the controller component. In the init case, it also attach the -- controller to the current finalization list. function Make_Deep_Record_Body (Prim : Final_Primitives; Typ : Entity_Id) return List_Id is Loc : constant Source_Ptr := Sloc (Typ); Controller_Typ : Entity_Id; Obj_Ref : constant Node_Id := Make_Identifier (Loc, Name_V); Controller_Ref : constant Node_Id := Make_Selected_Component (Loc, Prefix => Obj_Ref, Selector_Name => Make_Identifier (Loc, Name_uController)); begin if Is_Return_By_Reference_Type (Typ) then Controller_Typ := RTE (RE_Limited_Record_Controller); else Controller_Typ := RTE (RE_Record_Controller); end if; case Prim is when Initialize_Case => declare Res : constant List_Id := New_List; begin Append_List_To (Res, Make_Init_Call ( Ref => Controller_Ref, Typ => Controller_Typ, Flist_Ref => Make_Identifier (Loc, Name_L), With_Attach => Make_Identifier (Loc, Name_B))); -- When the type is also a controlled type by itself, -- Initialize it and attach it at the end of the internal -- finalization chain if Is_Controlled (Typ) then Append_To (Res, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To ( Find_Prim_Op (Typ, Name_Of (Prim)), Loc), Parameter_Associations => New_List (New_Copy_Tree (Obj_Ref)))); Append_To (Res, Make_Attach_Call ( Obj_Ref => New_Copy_Tree (Obj_Ref), Flist_Ref => Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Controller_Ref), Selector_Name => Make_Identifier (Loc, Name_F)), With_Attach => Make_Integer_Literal (Loc, 1))); end if; return Res; end; when Adjust_Case => return Make_Adjust_Call (Controller_Ref, Controller_Typ, Make_Identifier (Loc, Name_L), Make_Identifier (Loc, Name_B)); when Finalize_Case => return Make_Final_Call (Controller_Ref, Controller_Typ, Make_Identifier (Loc, Name_B)); end case; end Make_Deep_Record_Body; ---------------------- -- Make_Final_Call -- ---------------------- function Make_Final_Call (Ref : Node_Id; Typ : Entity_Id; With_Detach : Node_Id) return List_Id is Loc : constant Source_Ptr := Sloc (Ref); Res : constant List_Id := New_List; Cref : Node_Id; Cref2 : Node_Id; Proc : Entity_Id; Utyp : Entity_Id; begin if Is_Class_Wide_Type (Typ) then Utyp := Root_Type (Typ); Cref := Ref; elsif Is_Concurrent_Type (Typ) then Utyp := Corresponding_Record_Type (Typ); Cref := Convert_Concurrent (Ref, Typ); elsif Is_Private_Type (Typ) and then Present (Full_View (Typ)) and then Is_Concurrent_Type (Full_View (Typ)) then Utyp := Corresponding_Record_Type (Full_View (Typ)); Cref := Convert_Concurrent (Ref, Full_View (Typ)); else Utyp := Typ; Cref := Ref; end if; Utyp := Underlying_Type (Base_Type (Utyp)); Set_Assignment_OK (Cref); -- Deal with non-tagged derivation of private views if Is_Untagged_Derivation (Typ) then Utyp := Underlying_Type (Root_Type (Base_Type (Typ))); Cref := Unchecked_Convert_To (Utyp, Cref); Set_Assignment_OK (Cref); -- To prevent problems with UC see 1.156 RH ??? 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); Cref := Unchecked_Convert_To (Utyp, Cref); end if; -- Generate: -- Deep_Finalize (Ref, With_Detach); if Has_Controlled_Component (Utyp) or else Is_Class_Wide_Type (Typ) then if Is_Tagged_Type (Utyp) then Proc := Find_Prim_Op (Utyp, Deep_Name_Of (Finalize_Case)); else Proc := TSS (Utyp, Deep_Name_Of (Finalize_Case)); end if; Cref := Convert_View (Proc, Cref); Append_To (Res, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (Proc, Loc), Parameter_Associations => New_List (Cref, With_Detach))); -- Generate: -- if With_Detach then -- Finalize_One (Ref); -- else -- Finalize (Ref); -- end if; else Proc := Find_Prim_Op (Utyp, Name_Of (Finalize_Case)); if Chars (With_Detach) = Chars (Standard_True) then Append_To (Res, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (RTE (RE_Finalize_One), Loc), Parameter_Associations => New_List ( OK_Convert_To (RTE (RE_Finalizable), Cref)))); elsif Chars (With_Detach) = Chars (Standard_False) then Append_To (Res, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (Proc, Loc), Parameter_Associations => New_List (Convert_View (Proc, Cref)))); else Cref2 := New_Copy_Tree (Cref); Append_To (Res, Make_Implicit_If_Statement (Ref, Condition => With_Detach, Then_Statements => New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (RTE (RE_Finalize_One), Loc), Parameter_Associations => New_List ( OK_Convert_To (RTE (RE_Finalizable), Cref)))), Else_Statements => New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (Proc, Loc), Parameter_Associations => New_List (Convert_View (Proc, Cref2)))))); end if; end if; -- Treat this as a reference to Finalize if the Finalize routine -- comes from source. The call is not explicit, but it is near -- enough, and we won't typically get explicit adjust calls. if Comes_From_Source (Proc) then Generate_Reference (Proc, Ref); end if; return Res; end Make_Final_Call; -------------------- -- Make_Init_Call -- -------------------- function Make_Init_Call (Ref : Node_Id; Typ : Entity_Id; Flist_Ref : Node_Id; With_Attach : Node_Id) return List_Id is Loc : constant Source_Ptr := Sloc (Ref); Is_Conc : Boolean; Res : constant List_Id := New_List; Proc : Entity_Id; Utyp : Entity_Id; Cref : Node_Id; Cref2 : Node_Id; Attach : Node_Id := With_Attach; begin if Is_Concurrent_Type (Typ) then Is_Conc := True; Utyp := Corresponding_Record_Type (Typ); Cref := Convert_Concurrent (Ref, Typ); elsif Is_Private_Type (Typ) and then Present (Full_View (Typ)) and then Is_Concurrent_Type (Underlying_Type (Typ)) then Is_Conc := True; Utyp := Corresponding_Record_Type (Underlying_Type (Typ)); Cref := Convert_Concurrent (Ref, Underlying_Type (Typ)); else Is_Conc := False; Utyp := Typ; Cref := Ref; end if; Utyp := Underlying_Type (Base_Type (Utyp)); Set_Assignment_OK (Cref); -- Deal with non-tagged derivation of private views if Is_Untagged_Derivation (Typ) and then not Is_Conc then Utyp := Underlying_Type (Root_Type (Base_Type (Typ))); Cref := Unchecked_Convert_To (Utyp, Cref); Set_Assignment_OK (Cref); -- To prevent problems with UC see 1.156 RH ??? 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); Cref := Unchecked_Convert_To (Utyp, Cref); end if; -- We do not need to attach to one of the Global Final Lists -- the objects whose type is Finalize_Storage_Only if Finalize_Storage_Only (Typ) and then (Global_Flist_Ref (Flist_Ref) or else Entity (Constant_Value (RTE (RE_Garbage_Collected))) = Standard_True) then Attach := Make_Integer_Literal (Loc, 0); end if; -- Generate: -- Deep_Initialize (Ref, Flist_Ref); if Has_Controlled_Component (Utyp) then Proc := TSS (Utyp, Deep_Name_Of (Initialize_Case)); Cref := Convert_View (Proc, Cref, 2); Append_To (Res, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (Proc, Loc), Parameter_Associations => New_List ( Node1 => Flist_Ref, Node2 => Cref, Node3 => Attach))); -- Generate: -- Attach_To_Final_List (Ref, Flist_Ref); -- Initialize (Ref); else -- Is_Controlled (Utyp) Proc := Find_Prim_Op (Utyp, Name_Of (Initialize_Case)); Cref := Convert_View (Proc, Cref); Cref2 := New_Copy_Tree (Cref); Append_To (Res, Make_Procedure_Call_Statement (Loc, Name => New_Reference_To (Proc, Loc), Parameter_Associations => New_List (Cref2))); Append_To (Res, Make_Attach_Call (Cref, Flist_Ref, Attach)); -- Treat this as a reference to Initialize if Initialize routine -- comes from source. The call is not explicit, but it is near -- enough, and we won't typically get explicit adjust calls. if Comes_From_Source (Proc) then Generate_Reference (Proc, Ref); end if; end if; return Res; end Make_Init_Call; -------------------------- -- Make_Transient_Block -- -------------------------- -- If finalization is involved, this function just wraps the instruction -- into a block whose name is the transient block entity, and then -- Expand_Cleanup_Actions (called on the expansion of the handled -- sequence of statements will do the necessary expansions for -- cleanups). function Make_Transient_Block (Loc : Source_Ptr; Action : Node_Id) return Node_Id is Flist : constant Entity_Id := Finalization_Chain_Entity (Current_Scope); Decls : constant List_Id := New_List; Par : constant Node_Id := Parent (Action); Instrs : constant List_Id := New_List (Action); Blk : Node_Id; begin -- Case where only secondary stack use is involved if Uses_Sec_Stack (Current_Scope) and then No (Flist) and then Nkind (Action) /= N_Return_Statement and then Nkind (Par) /= N_Exception_Handler then declare S : Entity_Id; K : Entity_Kind; begin S := Scope (Current_Scope); loop K := Ekind (S); -- At the outer level, no need to release the sec stack if S = Standard_Standard then Set_Uses_Sec_Stack (Current_Scope, False); exit; -- In a function, only release the sec stack if the -- function does not return on the sec stack otherwise -- the result may be lost. The caller is responsible for -- releasing. elsif K = E_Function then Set_Uses_Sec_Stack (Current_Scope, False); if not Requires_Transient_Scope (Etype (S)) then if not Functions_Return_By_DSP_On_Target then Set_Uses_Sec_Stack (S, True); Check_Restriction (No_Secondary_Stack, Action); end if; end if; exit; -- In a loop or entry we should install a block encompassing -- all the construct. For now just release right away. elsif K = E_Loop or else K = E_Entry then exit; -- In a procedure or a block, we release on exit of the -- procedure or block. ??? memory leak can be created by -- recursive calls. elsif K = E_Procedure or else K = E_Block then if not Functions_Return_By_DSP_On_Target then Set_Uses_Sec_Stack (S, True); Check_Restriction (No_Secondary_Stack, Action); end if; Set_Uses_Sec_Stack (Current_Scope, False); exit; else S := Scope (S); end if; end loop; end; end if; -- Insert actions stuck in the transient scopes as well as all -- freezing nodes needed by those actions Insert_Actions_In_Scope_Around (Action); declare Last_Inserted : Node_Id := Prev (Action); begin if Present (Last_Inserted) then Freeze_All (First_Entity (Current_Scope), Last_Inserted); end if; end; Blk := Make_Block_Statement (Loc, Identifier => New_Reference_To (Current_Scope, Loc), Declarations => Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Instrs), Has_Created_Identifier => True); -- When the transient scope was established, we pushed the entry for -- the transient scope onto the scope stack, so that the scope was -- active for the installation of finalizable entities etc. Now we -- must remove this entry, since we have constructed a proper block. Pop_Scope; return Blk; end Make_Transient_Block; ------------------------ -- Node_To_Be_Wrapped -- ------------------------ function Node_To_Be_Wrapped return Node_Id is begin return Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped; end Node_To_Be_Wrapped; ---------------------------- -- Set_Node_To_Be_Wrapped -- ---------------------------- procedure Set_Node_To_Be_Wrapped (N : Node_Id) is begin Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped := N; end Set_Node_To_Be_Wrapped; ---------------------------------- -- Store_After_Actions_In_Scope -- ---------------------------------- procedure Store_After_Actions_In_Scope (L : List_Id) is SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last); begin if Present (SE.Actions_To_Be_Wrapped_After) then Insert_List_Before_And_Analyze ( First (SE.Actions_To_Be_Wrapped_After), L); else SE.Actions_To_Be_Wrapped_After := L; if Is_List_Member (SE.Node_To_Be_Wrapped) then Set_Parent (L, Parent (SE.Node_To_Be_Wrapped)); else Set_Parent (L, SE.Node_To_Be_Wrapped); end if; Analyze_List (L); end if; end Store_After_Actions_In_Scope; ----------------------------------- -- Store_Before_Actions_In_Scope -- ----------------------------------- procedure Store_Before_Actions_In_Scope (L : List_Id) is SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last); begin if Present (SE.Actions_To_Be_Wrapped_Before) then Insert_List_After_And_Analyze ( Last (SE.Actions_To_Be_Wrapped_Before), L); else SE.Actions_To_Be_Wrapped_Before := L; if Is_List_Member (SE.Node_To_Be_Wrapped) then Set_Parent (L, Parent (SE.Node_To_Be_Wrapped)); else Set_Parent (L, SE.Node_To_Be_Wrapped); end if; Analyze_List (L); end if; end Store_Before_Actions_In_Scope; -------------------------------- -- Wrap_Transient_Declaration -- -------------------------------- -- If a transient scope has been established during the processing of the -- Expression of an Object_Declaration, it is not possible to wrap the -- declaration into a transient block as usual case, otherwise the object -- would be itself declared in the wrong scope. Therefore, all entities (if -- any) defined in the transient block are moved to the proper enclosing -- scope, furthermore, if they are controlled variables they are finalized -- right after the declaration. The finalization list of the transient -- scope is defined as a renaming of the enclosing one so during their -- initialization they will be attached to the proper finalization -- list. For instance, the following declaration : -- X : Typ := F (G (A), G (B)); -- (where G(A) and G(B) return controlled values, expanded as _v1 and _v2) -- is expanded into : -- _local_final_list_1 : Finalizable_Ptr; -- X : Typ := [ complex Expression-Action ]; -- Finalize_One(_v1); -- Finalize_One (_v2); procedure Wrap_Transient_Declaration (N : Node_Id) is S : Entity_Id; LC : Entity_Id := Empty; Nodes : List_Id; Loc : constant Source_Ptr := Sloc (N); Enclosing_S : Entity_Id; Uses_SS : Boolean; Next_N : constant Node_Id := Next (N); begin S := Current_Scope; Enclosing_S := Scope (S); -- Insert Actions kept in the Scope stack Insert_Actions_In_Scope_Around (N); -- If the declaration is consuming some secondary stack, mark the -- Enclosing scope appropriately. Uses_SS := Uses_Sec_Stack (S); Pop_Scope; -- Create a List controller and rename the final list to be its -- internal final pointer: -- Lxxx : Simple_List_Controller; -- Fxxx : Finalizable_Ptr renames Lxxx.F; if Present (Finalization_Chain_Entity (S)) then LC := Make_Defining_Identifier (Loc, New_Internal_Name ('L')); Nodes := New_List ( Make_Object_Declaration (Loc, Defining_Identifier => LC, Object_Definition => New_Reference_To (RTE (RE_Simple_List_Controller), Loc)), Make_Object_Renaming_Declaration (Loc, Defining_Identifier => Finalization_Chain_Entity (S), Subtype_Mark => New_Reference_To (RTE (RE_Finalizable_Ptr), Loc), Name => Make_Selected_Component (Loc, Prefix => New_Reference_To (LC, Loc), Selector_Name => Make_Identifier (Loc, Name_F)))); -- Put the declaration at the beginning of the declaration part -- to make sure it will be before all other actions that have been -- inserted before N. Insert_List_Before_And_Analyze (First (List_Containing (N)), Nodes); -- Generate the Finalization calls by finalizing the list -- controller right away. It will be re-finalized on scope -- exit but it doesn't matter. It cannot be done when the -- call initializes a renaming object though because in this -- case, the object becomes a pointer to the temporary and thus -- increases its life span. if Nkind (N) = N_Object_Renaming_Declaration and then Controlled_Type (Etype (Defining_Identifier (N))) then null; else Nodes := Make_Final_Call ( Ref => New_Reference_To (LC, Loc), Typ => Etype (LC), With_Detach => New_Reference_To (Standard_False, Loc)); if Present (Next_N) then Insert_List_Before_And_Analyze (Next_N, Nodes); else Append_List_To (List_Containing (N), Nodes); end if; end if; end if; -- Put the local entities back in the enclosing scope, and set the -- Is_Public flag appropriately. Transfer_Entities (S, Enclosing_S); -- Mark the enclosing dynamic scope so that the sec stack will be -- released upon its exit unless this is a function that returns on -- the sec stack in which case this will be done by the caller. if Uses_SS then S := Enclosing_Dynamic_Scope (S); if Ekind (S) = E_Function and then Requires_Transient_Scope (Etype (S)) then null; else Set_Uses_Sec_Stack (S); Check_Restriction (No_Secondary_Stack, N); end if; end if; end Wrap_Transient_Declaration; ------------------------------- -- Wrap_Transient_Expression -- ------------------------------- -- Insert actions before <Expression>: -- (lines marked with <CTRL> are expanded only in presence of Controlled -- objects needing finalization) -- _E : Etyp; -- declare -- _M : constant Mark_Id := SS_Mark; -- Local_Final_List : System.FI.Finalizable_Ptr; <CTRL> -- procedure _Clean is -- begin -- Abort_Defer; -- System.FI.Finalize_List (Local_Final_List); <CTRL> -- SS_Release (M); -- Abort_Undefer; -- end _Clean; -- begin -- _E := <Expression>; -- at end -- _Clean; -- end; -- then expression is replaced by _E procedure Wrap_Transient_Expression (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); E : constant Entity_Id := Make_Defining_Identifier (Loc, New_Internal_Name ('E')); Etyp : Entity_Id := Etype (N); begin Insert_Actions (N, New_List ( Make_Object_Declaration (Loc, Defining_Identifier => E, Object_Definition => New_Reference_To (Etyp, Loc)), Make_Transient_Block (Loc, Action => Make_Assignment_Statement (Loc, Name => New_Reference_To (E, Loc), Expression => Relocate_Node (N))))); Rewrite (N, New_Reference_To (E, Loc)); Analyze_And_Resolve (N, Etyp); end Wrap_Transient_Expression; ------------------------------ -- Wrap_Transient_Statement -- ------------------------------ -- Transform <Instruction> into -- (lines marked with <CTRL> are expanded only in presence of Controlled -- objects needing finalization) -- declare -- _M : Mark_Id := SS_Mark; -- Local_Final_List : System.FI.Finalizable_Ptr ; <CTRL> -- procedure _Clean is -- begin -- Abort_Defer; -- System.FI.Finalize_List (Local_Final_List); <CTRL> -- SS_Release (_M); -- Abort_Undefer; -- end _Clean; -- begin -- <Instr uction>; -- at end -- _Clean; -- end; procedure Wrap_Transient_Statement (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); New_Statement : constant Node_Id := Relocate_Node (N); begin Rewrite (N, Make_Transient_Block (Loc, New_Statement)); -- With the scope stack back to normal, we can call analyze on the -- resulting block. At this point, the transient scope is being -- treated like a perfectly normal scope, so there is nothing -- special about it. -- Note: Wrap_Transient_Statement is called with the node already -- analyzed (i.e. Analyzed (N) is True). This is important, since -- otherwise we would get a recursive processing of the node when -- we do this Analyze call. Analyze (N); end Wrap_Transient_Statement; end Exp_Ch7;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2018 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package body Orka.Rendering.Buffers.Mapped.Unsynchronized is function Create_Buffer (Kind : Orka.Types.Element_Type; Length : Natural; Mode : IO_Mode) return Unsynchronized_Mapped_Buffer is Storage_Flags : constant GL.Objects.Buffers.Storage_Bits := (Write => Mode = Write, Read => Mode = Read, others => False); begin return Result : Unsynchronized_Mapped_Buffer (Kind, Mode) do Result.Buffer := Buffers.Create_Buffer (Storage_Flags, Kind, Length); Result.Offset := 0; end return; end Create_Buffer; procedure Map (Object : in out Unsynchronized_Mapped_Buffer) is Access_Flags : constant GL.Objects.Buffers.Access_Bits := (Write => Object.Mode = Write, Read => Object.Mode = Read, Unsynchronized => True, Invalidate_Range => Object.Mode = Write, others => False); begin Object.Map (Size (Object.Length), Access_Flags); end Map; procedure Unmap (Object : in out Unsynchronized_Mapped_Buffer) is begin Object.Buffer.Buffer.Unmap; end Unmap; function Mapped (Object : in out Unsynchronized_Mapped_Buffer) return Boolean is (Object.Buffer.Buffer.Mapped); function Buffer (Object : in out Unsynchronized_Mapped_Buffer) return Buffers.Buffer is (Object.Buffer); end Orka.Rendering.Buffers.Mapped.Unsynchronized;
------------------------------------------------------------------------------ -- -- -- Ada User Repository Annex (AURA) -- -- ANNEXI-STRAYLINE Reference Implementation -- -- -- -- Core -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2020, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Richard Wai (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.Assertions; with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Ada.Containers.Hashed_Sets; with Ada.Containers.Synchronized_Queue_Interfaces; with Ada.Containers.Unbounded_Synchronized_Queues; with Registrar.Queries; with Registrar.Registry; with Registrar.Subsystems; with Registrar.Library_Units; with Registrar.Registration.Unchecked_Deregister_Unit; with Unit_Names, Unit_Names.Hash, Unit_Names.Sets; with Workers, Workers.Reporting; package body Registrar.Dependency_Processing is use type Unit_Names.Unit_Name; New_Line: Character renames Workers.Reporting.New_Line; -- -- Common infrastructure -- package UNQI is new Ada.Containers.Synchronized_Queue_Interfaces (Unit_Names.Unit_Name); package Name_Queues is new Ada.Containers.Unbounded_Synchronized_Queues (UNQI); type Name_Queue_Access is access Name_Queues.Queue; type Reverse_Dependency_Queue is record Map_Key : Unit_Names.Unit_Name; Name_Queue: Name_Queue_Access := null; end record; function Key_Hash (RDQ: Reverse_Dependency_Queue) return Ada.Containers.Hash_Type is (Unit_Names.Hash (RDQ.Map_Key)); function Equivalent_Queues (Left, Right: Reverse_Dependency_Queue) return Boolean is (Left.Map_Key = Right.Map_Key); package Map_Queue_Sets is new Ada.Containers.Hashed_Sets (Element_Type => Reverse_Dependency_Queue, Hash => Key_Hash, Equivalent_Elements => Equivalent_Queues); type Map_Queue_Set_Access is access Map_Queue_Sets.Set; -- -- Work Orders Declarations -- ----------------------------- -- Phase 1: Merge Subunits -- ----------------------------- -- This phase is a bit of a "fake" one. It wouldn't be terribly efficient to -- parallelize this operation since the operations between each manipulation -- of the map are generally insignficant. The contention and scheduling -- overhead would likely far outstrip the performance gains of parallelizing -- it. type Merge_Subunits_Order is new Workers.Work_Order with record All_Units : Library_Units.Library_Unit_Sets.Set; All_Subsys: Subsystems.Subsystem_Sets.Set; end record; overriding function Image (Order: Merge_Subunits_Order) return String; overriding procedure Execute (Order: in out Merge_Subunits_Order); ---------------------- -- Phase 2: Fan-out -- ---------------------- type Fan_Out_Order is new Workers.Work_Order with record Target: Unit_Names.Unit_Name; -- The unit that needs to be fanned-out Unit_Map_Queues : Map_Queue_Set_Access; Subsys_Map_Queues: Map_Queue_Set_Access; -- Target deposits it's own name into the queue for each -- of its dependencies (unit and subsystem) end record; overriding function Image (Order: Fan_Out_Order) return String; overriding procedure Execute (Order: in out Fan_Out_Order); overriding procedure Phase_Trigger (Order: in out Fan_Out_Order); ---------------------------- -- Phase 3: Build Reverse -- ---------------------------- type Map_Domain is (Library_Units_Domain, Subsystems_Domain); -- Used to select which map is having its reverse dependency set -- build for -- Library_Units or Subsystems type Build_Reverse_Order is new Workers.Work_Order with record Domain : Map_Domain; Queue_Cursor: Map_Queue_Sets.Cursor; -- The queue that should be used to build a reverse-dependency -- map for the unit/subsystem that "owns" the queue Unit_Map_Queues : Map_Queue_Set_Access; Subsys_Map_Queues: Map_Queue_Set_Access; -- Both queues need to be referenced from all orders (hence not -- discriminated), since the Phase_Trigger needs to deallocate -- all end record; overriding function Image (Order: Build_Reverse_Order) return String; overriding procedure Execute (Order: in out Build_Reverse_Order); overriding procedure Phase_Trigger (Order: in out Build_Reverse_Order); -- -- Work Order Implementations -- -------------------------- -- Merge_Subunits_Order -- -------------------------- -- Image -- ----------- function Image (Order: Merge_Subunits_Order) return String is ("[Merge_Subunits_Order] (Registrar.Dependency_Processing)"); -- Execute -- ------------- -- After doing our main job of merging subunit dependencies up to the -- parent, we also need to set-up the reverse depependency queues, -- and then dispatch Fan-Out orders (Phase 2) procedure Execute (Order: in out Merge_Subunits_Order) is use Subsystems; use Library_Units; use type Ada.Containers.Count_Type; Move_Set: Unit_Names.Sets.Set; Fan_Out: Fan_Out_Order; procedure Set_Extraction (Mod_Set: in out Unit_Names.Sets.Set) is begin Move_Set := Mod_Set; Mod_Set := Unit_Names.Sets.Empty_Set; end Set_Extraction; procedure Merge_Extraction (Merge_Set: in out Unit_Names.Sets.Set) is begin Merge_Set.Union (Move_set); end Merge_Extraction; begin Fan_Out.Tracker := Fan_Out_Progress'Access; Fan_Out.Unit_Map_Queues := new Map_Queue_Sets.Set; Fan_Out.Subsys_Map_Queues := new Map_Queue_Sets.Set; for Unit of Order.All_Units loop if Unit.State = Requested then -- For Requested units - if we have them here it means none of the -- subsystems that were supposed to contain them actually do, or -- the entire subsystem could not be aquired. -- -- We still want to compute the dependency maps so that we can give -- the user a picture of where the missing units were being withed -- from (similarily for subystems). -- -- For those units, we need to add an empty set to the forward -- dependency map so that we don't need to check for No_Element -- cursors everywhere else. This makes particular sense considering -- this work order is single issue (not parallel), so there will be -- no contention on the dependency maps anyways. declare Inserted: Boolean; begin Registry.Unit_Forward_Dependencies.Insert (Key => Unit.Name, New_Item => Unit_Names.Sets.Empty_Set, Inserted => Inserted); pragma Assert (Inserted); end; -- Subunits can't be requested! Every time a dependency request -- is processed by the registrar, it is entered as a library unit. -- I.e. a subsystem unit can only get into the registry by being -- entered, and therefore can't have a state of Requested. pragma Assert (Unit.Kind /= Subunit); end if; if Unit.Kind = Subunit then -- Merge Subunit forward dependencies up to the fist non-subunit -- parent -- Take the forward dependency set from the subunit Registry.Unit_Forward_Dependencies.Modify (Key => Unit.Name, Process => Set_Extraction'Access); -- And migrate to its parent. This will keep happening until -- it reaches a unit that is not a subunit Registry.Unit_Forward_Dependencies.Modify (Key => Registrar.Queries.Trace_Subunit_Parent(Unit).Name, Process => Merge_Extraction'Access); else -- A normal unit, which actually needs to be processesed. We want -- each dependency of this unit to have this unit registered as -- a reverse dependency for that dependent unit (this is what -- the Fan_Out order accomplishes). Fan_Out.Unit_Map_Queues.Insert (Reverse_Dependency_Queue'(Map_Key => Unit.Name, Name_Queue => new Name_Queues.Queue)); end if; Merge_Subunits_Progress.Increment_Completed_Items; end loop; -- We set the Fan_Out progress tracker now, before we do the subsystems -- so that they are set before we cause the Merge_Subunits tracker to -- complete (we know there must be subsystems if there are units!). -- The number of Fan_Out orders is not dependent on the number of -- subsystems, since the subsystem dependencies are registered -- during the normal course of Fan_Out. Since all units have a subsystem, -- we can be sure all subsystem dependencies will be computed Fan_Out_Progress.Increase_Total_Items_By (Natural (Fan_Out.Unit_Map_Queues.Length)); for Subsys of Order.All_Subsys loop -- We don't really care what the state of the subsystem is, we just -- want to ensure that we have a queue for each subsystem we know -- about, so that the fan-out process can register subsystem -- dependencies declare Inserted: Boolean; begin Registry.Subsystem_Forward_Dependencies.Insert (Key => Subsys.Name, New_Item => Unit_Names.Sets.Empty_Set, Inserted => Inserted); pragma Assert (Inserted); end; Fan_Out.Subsys_Map_Queues.Insert (Reverse_Dependency_Queue'(Map_Key => Subsys.Name, Name_Queue => new Name_Queues.Queue)); Merge_Subunits_Progress.Increment_Completed_Items; end loop; -- Launch the fan-out phase. We only need to launch an order per -- unit (not subsystem), since each unit dependency will the related -- subsystem dependency to the relevent subsystem map queue. for Queue of Fan_Out.Unit_Map_Queues.all loop Fan_Out.Target := Queue.Map_Key; Workers.Enqueue_Order (Fan_Out); end loop; end Execute; ------------------- -- Fan_Out_Order -- ------------------- -- Image -- ----------- function Image (Order: Fan_Out_Order) return String is ( "[Fan_Out_Order] (Registrar.Dependency_Processing)" & New_Line & " Target Unit: " & Order.Target.To_UTF8_String); -- Execute -- ------------- procedure Execute (Order: in out Fan_Out_Order) is use type Map_Queue_Sets.Cursor; use type Library_Units.Library_Unit_Kind; Dependencies: constant Unit_Names.Sets.Set := Registry.Unit_Forward_Dependencies.Extract_Element (Order.Target); Subsys_Dependencies: Unit_Names.Sets.Set; -- We will also build the subsystem forward dependencies for the unit's -- subsystem as we go here (which will then be reversed in the -- Build Reverse phase Target_SS: constant Unit_Names.Unit_Name := Order.Target.Subsystem_Name; Unit_Map_Queues : Map_Queue_Sets.Set renames Order.Unit_Map_Queues.all; Subsys_Map_Queues: Map_Queue_Sets.Set renames Order.Subsys_Map_Queues.all; Unit_Lookup, Subsys_Lookup: Reverse_Dependency_Queue; Unit_Cursor, Subsys_Cursor: Map_Queue_Sets.Cursor; procedure Union_Subsys_Dependencies (Existing_Set: in out Unit_Names.Sets.Set) is begin Existing_Set.Union (Subsys_Dependencies); end Union_Subsys_Dependencies; begin -- Go through our (Order.Target's) dependencies and put our name on the -- reverse dependency queue for that unit. for Name of Dependencies loop -- Add the name of our target unit, and our subsystem -- to the queue of each of our dependencies Unit_Lookup.Map_Key := Name; Subsys_Lookup.Map_Key := Name.Subsystem_Name; Subsys_Dependencies.Include (Subsys_Lookup.Map_Key); Unit_Cursor := Order.Unit_Map_Queues.Find (Unit_Lookup); Subsys_Cursor := Order.Subsys_Map_Queues.Find (Subsys_Lookup); Unit_Map_Queues(Unit_Cursor).Name_Queue.Enqueue (Order.Target); Subsys_Map_Queues(Subsys_Cursor).Name_Queue.Enqueue (Target_SS); end loop; -- Add a link back to our parent, except for External_Units, but -- including requested units if Registrar.Queries.Lookup_Unit(Order.Target).Kind /= Library_Units.External_Unit then Unit_Lookup.Map_Key := Order.Target.Parent_Name; if not Unit_Lookup.Map_Key.Empty then Unit_Cursor := Unit_Map_Queues.Find (Unit_Lookup); Unit_Map_Queues(Unit_Cursor).Name_Queue.Enqueue (Order.Target); end if; end if; -- Register the subsystem forward dependencies. We know that the Key -- exists because we added an empty set for each registered Subsystem Registry.Subsystem_Forward_Dependencies.Modify (Key => Target_SS, Process => Union_Subsys_Dependencies'Access); end Execute; -- Phase_Trigger -- ------------------- procedure Phase_Trigger (Order: in out Fan_Out_Order) is New_Order: Build_Reverse_Order := (Tracker => Build_Reverse_Progress'Access, Domain => Library_Units_Domain, Unit_Map_Queues => Order.Unit_Map_Queues, Subsys_Map_Queues => Order.Subsys_Map_Queues, others => <>); use type Ada.Containers.Count_Type; begin Build_Reverse_Progress.Increase_Total_Items_By (Natural (Order.Unit_Map_Queues.Length + Order.Subsys_Map_Queues.Length)); for Unit_Cursor in Order.Unit_Map_Queues.Iterate loop New_Order.Queue_Cursor := Unit_Cursor; Workers.Enqueue_Order (New_Order); end loop; New_Order.Domain := Subsystems_Domain; for Subsys_Cursor in Order.Subsys_Map_Queues.Iterate loop New_Order.Queue_Cursor := Subsys_Cursor; Workers.Enqueue_Order (New_Order); end loop; end Phase_Trigger; ------------------------- -- Build_Reverse_Order -- ------------------------- -- Image -- ----------- function Image (Order: Build_Reverse_Order) return String is ( "[Build_Reverse_Order] (Registrar.Dependency_Processing)" & New_Line & (if Map_Queue_Sets."=" (Order.Queue_Cursor, Map_Queue_Sets.No_Element) then " ** Phase Trigger **" -- If something goes wrong in the phase trigger, either -- of the queues might be already deallocated, which would -- make the "else" portion very erronious to execute else " Domain: " & Map_Domain'Image (Order.Domain) & New_Line & (case Order.Domain is when Library_Units_Domain => "Unit Queue: " & Order.Unit_Map_Queues.all (Order.Queue_Cursor).Map_Key.To_UTF8_String, when Subsystems_Domain => "Subsystem Queue: " & Order.Subsys_Map_Queues.all (Order.Queue_Cursor).Map_Key.To_UTF8_String))); -- Note that if an exception is raised during the phase trigger, -- it is possible t hat this -- Execute -- ------------- procedure Execute (Order: in out Build_Reverse_Order) is use type Ada.Containers.Count_Type; Queue_Set: constant Map_Queue_Set_Access := (case Order.Domain is when Library_Units_Domain => Order.Unit_Map_Queues, when Subsystems_Domain => Order.Subsys_Map_Queues); Queue_Descriptor: Reverse_Dependency_Queue renames Queue_Set.all(Order.Queue_Cursor); Queue: Name_Queues.Queue renames Queue_Descriptor.Name_Queue.all; Rev_Deps: Unit_Names.Sets.Set; Name: Unit_Names.Unit_Name; procedure Include_Reverse_Dependencies (Set: in out Unit_Names.Sets.Set) is begin -- Thge target set already has a map for this unit, so we simply -- union-in the names we have. Set.Union (Rev_Deps); end Include_Reverse_Dependencies; begin while Queue.Current_Use > 0 loop -- Note that in this phase (phase "3", each queue is assigned to a -- single Work Order, and therefore we will not see concurrent access -- to our queue from this Order Queue.Dequeue (Name); Rev_Deps.Include (Name); -- The same name will likely appear twice. end loop; case Order.Domain is when Library_Units_Domain => Registry.Unit_Reverse_Dependencies.Insert_Or_Modify (Key => Queue_Descriptor.Map_Key, New_Item => Rev_Deps, Process_Existing => Include_Reverse_Dependencies'Access); when Subsystems_Domain => Registry.Subsystem_Reverse_Dependencies.Insert_Or_Modify (Key => Queue_Descriptor.Map_Key, New_Item => Rev_Deps, Process_Existing => Include_Reverse_Dependencies'Access); end case; -- Finalize the order's Queue_Cursor element. This is important because -- the Phase trigger might complete before all of the "completed orders" -- are actually finalized. This would cause a Tampering with Cursors -- check to fail. Order.Queue_Cursor := Map_Queue_Sets.No_Element; end Execute; -- Phase_Trigger -- ------------------- procedure Phase_Trigger (Order: in out Build_Reverse_Order) is procedure Free_Queue is new Ada.Unchecked_Deallocation (Object => Name_Queues.Queue, Name => Name_Queue_Access); procedure Free_Queue_Set is new Ada.Unchecked_Deallocation (Object => Map_Queue_Sets.Set, Name => Map_Queue_Set_Access); Queue_Disposal: Name_Queue_Access; -- Since hash map only have constant referencing, we'll copy out -- the access value for the queue in order to deallocate it begin pragma Assert (Map_Queue_Sets."=" (Order.Queue_Cursor, Map_Queue_Sets.No_Element)); -- The phase trigger just needs to clean-up the allocated objects. -- This is nice because the Consolodate_Dependencies process is now -- finished and everything else can proceed while this worker deals -- with this clean-up. -- -- This is why we didn't deallocate the queues during Execute. for QD of Order.Unit_Map_Queues.all loop Queue_Disposal := QD.Name_Queue; Free_Queue (Queue_Disposal); end loop; Free_Queue_Set (Order.Unit_Map_Queues); for QD of Order.Subsys_Map_Queues.all loop Queue_Disposal := QD.Name_Queue; Free_Queue (Queue_Disposal); end loop; Free_Queue_Set (Order.Subsys_Map_Queues); end Phase_Trigger; -- -- Dispatch -- ------------------------------ -- Consolidate_Dependencies -- ------------------------------ procedure Consolidate_Dependencies is use type Ada.Containers.Count_Type; Order: Merge_Subunits_Order; begin Order.Tracker := null; -- Only one order, and the tracker is manually -- adjusted Order.All_Units := Registrar.Queries.All_Library_Units; Order.All_Subsys := Registrar.Queries.All_Subsystems; Merge_Subunits_Progress.Increase_Total_Items_By (Natural (Order.All_Units.Length + Order.All_Subsys.Length)); Workers.Enqueue_Order (Order); end Consolidate_Dependencies; end Registrar.Dependency_Processing;
----------------------------------------------------------------------- -- util-processes-tools -- System specific and low level operations -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; with Util.Streams.Pipes; package Util.Processes.Tools is -- Execute the command and append the output in the vector array. -- The program output is read line by line and the standard input is closed. -- Return the program exit status. procedure Execute (Command : in String; Output : in out Util.Strings.Vectors.Vector; Status : out Integer); procedure Execute (Command : in String; Input_Path : in String; Output : in out Util.Strings.Vectors.Vector; Status : out Integer); procedure Execute (Command : in String; Process : in out Util.Streams.Pipes.Pipe_Stream; Output : in out Util.Strings.Vectors.Vector; Status : out Integer); end Util.Processes.Tools;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y M B O L S . P R O C E S S I N G -- -- -- -- B o d y -- -- -- -- Copyright (C) 2004-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. -- -- -- ------------------------------------------------------------------------------ -- This is the VMS/IA64 version of this package with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; separate (Symbols) package body Processing is type String_Array is array (Positive range <>) of String_Access; type Strings_Ptr is access String_Array; procedure Free is new Ada.Unchecked_Deallocation (String_Array, Strings_Ptr); type Section_Header is record Shname : Integer; Shtype : Integer; Shoffset : Integer; Shsize : Integer; Shlink : Integer; end record; type Section_Header_Array is array (Natural range <>) of Section_Header; type Section_Header_Ptr is access Section_Header_Array; procedure Free is new Ada.Unchecked_Deallocation (Section_Header_Array, Section_Header_Ptr); ------------- -- Process -- ------------- procedure Process (Object_File : String; Success : out Boolean) is B : Byte; H : Integer; W : Integer; Str : String (1 .. 1000) := (others => ' '); Str_Last : Natural; Strings : Strings_Ptr; Shoff : Integer; Shnum : Integer; Shentsize : Integer; Shname : Integer; Shtype : Integer; Shoffset : Integer; Shsize : Integer; Shlink : Integer; Symtab_Index : Natural := 0; String_Table_Index : Natural := 0; End_Symtab : Integer; Stname : Integer; Stinfo : Character; Sttype : Integer; Stbind : Integer; Stshndx : Integer; Section_Headers : Section_Header_Ptr; Offset : Natural := 0; procedure Get_Byte (B : out Byte); procedure Get_Half (H : out Integer); procedure Get_Word (W : out Integer); procedure Reset; procedure Get_Byte (B : out Byte) is begin Byte_IO.Read (File, B); Offset := Offset + 1; end Get_Byte; procedure Get_Half (H : out Integer) is C1, C2 : Character; begin Get_Byte (C1); Get_Byte (C2); H := Integer'(Character'Pos (C2)) * 256 + Integer'(Character'Pos (C1)); end Get_Half; procedure Get_Word (W : out Integer) is H1, H2 : Integer; begin Get_Half (H1); Get_Half (H2); W := H2 * 256 * 256 + H1; end Get_Word; procedure Reset is begin Offset := 0; Byte_IO.Reset (File); end Reset; begin -- Open the object file with Byte_IO. Return with Success = False if -- this fails. begin Open (File, In_File, Object_File); exception when others => Put_Line ("*** Unable to open object file """ & Object_File & """"); Success := False; return; end; -- Assume that the object file has a correct format Success := True; -- Skip ELF identification while Offset < 16 loop Get_Byte (B); end loop; -- Skip e_type Get_Half (H); -- Skip e_machine Get_Half (H); -- Skip e_version Get_Word (W); -- Skip e_entry for J in 1 .. 8 loop Get_Byte (B); end loop; -- Skip e_phoff for J in 1 .. 8 loop Get_Byte (B); end loop; Get_Word (Shoff); -- Skip upper half of Shoff for J in 1 .. 4 loop Get_Byte (B); end loop; -- Skip e_flags Get_Word (W); -- Skip e_ehsize Get_Half (H); -- Skip e_phentsize Get_Half (H); -- Skip e_phnum Get_Half (H); Get_Half (Shentsize); Get_Half (Shnum); Section_Headers := new Section_Header_Array (0 .. Shnum - 1); -- Go to Section Headers while Offset < Shoff loop Get_Byte (B); end loop; -- Reset Symtab_Index Symtab_Index := 0; for J in Section_Headers'Range loop -- Get the data for each Section Header Get_Word (Shname); Get_Word (Shtype); for K in 1 .. 16 loop Get_Byte (B); end loop; Get_Word (Shoffset); Get_Word (W); Get_Word (Shsize); Get_Word (W); Get_Word (Shlink); while (Offset - Shoff) mod Shentsize /= 0 loop Get_Byte (B); end loop; -- If this is the Symbol Table Section Header, record its index if Shtype = 2 then Symtab_Index := J; end if; Section_Headers (J) := (Shname, Shtype, Shoffset, Shsize, Shlink); end loop; if Symtab_Index = 0 then Success := False; return; end if; End_Symtab := Section_Headers (Symtab_Index).Shoffset + Section_Headers (Symtab_Index).Shsize; String_Table_Index := Section_Headers (Symtab_Index).Shlink; Strings := new String_Array (1 .. Section_Headers (String_Table_Index).Shsize); -- Go get the String Table section for the Symbol Table Reset; while Offset < Section_Headers (String_Table_Index).Shoffset loop Get_Byte (B); end loop; Offset := 0; Get_Byte (B); -- zero while Offset < Section_Headers (String_Table_Index).Shsize loop Str_Last := 0; loop Get_Byte (B); if B /= ASCII.NUL then Str_Last := Str_Last + 1; Str (Str_Last) := B; else Strings (Offset - Str_Last - 1) := new String'(Str (1 .. Str_Last)); exit; end if; end loop; end loop; -- Go get the Symbol Table Reset; while Offset < Section_Headers (Symtab_Index).Shoffset loop Get_Byte (B); end loop; while Offset < End_Symtab loop Get_Word (Stname); Get_Byte (Stinfo); Get_Byte (B); Get_Half (Stshndx); for J in 1 .. 4 loop Get_Word (W); end loop; Sttype := Integer'(Character'Pos (Stinfo)) mod 16; Stbind := Integer'(Character'Pos (Stinfo)) / 16; if (Sttype = 1 or else Sttype = 2) and then Stbind /= 0 and then Stshndx /= 0 then declare S_Data : Symbol_Data; begin S_Data.Name := new String'(Strings (Stname).all); if Sttype = 1 then S_Data.Kind := Data; else S_Data.Kind := Proc; end if; -- Put the new symbol in the table Symbol_Table.Increment_Last (Complete_Symbols); Complete_Symbols.Table (Symbol_Table.Last (Complete_Symbols)) := S_Data; end; end if; end loop; -- The object file has been processed, close it Close (File); -- Free the allocated memory Free (Section_Headers); for J in Strings'Range loop if Strings (J) /= null then Free (Strings (J)); end if; end loop; Free (Strings); exception -- For any exception, output an error message, close the object file -- and return with Success = False. when Ada.IO_Exceptions.End_Error => Close (File); when X : others => Put_Line ("unexpected exception raised while processing """ & Object_File & """"); Put_Line (Exception_Information (X)); Close (File); Success := False; end Process; end Processing;
--****p* Fakedsp/Fakedsp.card -- DESCRIPTION -- This package provides the interface to a "virtual DSP card" with an ADC -- and a DAC. The virtual ADC reads sample at a specified sampling frequency -- and at the same instants the virtual DAC updates its output. -- The user needs to register a "virtual interrupt handler" -- that will be called every time the virtual ADC reads a new sample. -- The interrupt handler can read data from the ADC using the function -- Read_ADC and can write data to the DAC usign Write_DAC. -- -- The interrupt handler must be a variable of a type that implements -- (is a descendant of) the interface Callback_Handler. Every -- implementation of Callback_Handler must provide a procedure Sample_Ready -- that will be called after the virtual ADC acquired a new sample. -- -- The typical way of using this package is as follows: -- * The user codes an implementation of the interface Callback_Handler -- with the processing code (typically) included in the Sample_Ready -- procedure. -- * The user creates a Data_Source (see Fakedsp.Data_Streams) that will -- be read by the virtual ADC in order to get the "virtually -- acquired" samples. The easiest way to create a Data_Source is to -- use the "broker constructor" in Fakedsp.Data_Streams.Files. -- * The user creates a Data_Destination (see Fakedsp.Data_Streams) that will -- be written by the virtual DAC with the value produced by the processing -- code written by the user. -- The easiest way to create a Data_Source is to -- use the "broker constructor" in Fakedsp.Data_Streams.Files. --*** with Fakedsp.Data_Streams; package Fakedsp.Card is --****t* Fakedsp.card/State_Type -- DESCRIPTION -- The "virtual acquisition card" can be in one of 3 states: Sleeping, -- Running, End_Of_Data. -- -- At the beginning, before calling the function Start, it -- is in Sleeping; after start it goes Running until it ends the -- data from the source; when out of data, the card goes in End_Of_Data. -- -- SOURCE type State_Type is (Sleeping, Running, End_Of_Data); --*** --****m* Fakedsp.card/Current_State -- SOURCE function Current_State return State_Type; -- DESCRIPTION -- Return the current state of the virtual card --*** --****m* Fakedsp.card/Wait_For -- SOURCE procedure Wait_For (State : State_Type); -- DESCRIPTION -- Wait for the state to get equal to State and return. -- Similar to a while loop calling Current_State, but more efficient -- since it checks the state only when it changes. --*** --****I* Fakedsp.card/Callback_Handler -- SOURCE type Callback_Handler is interface; procedure Sample_Ready (H : in out Callback_Handler) is abstract; -- DESCRIPTION -- A Callback_Handler defines an interface similar to that of -- an interrupt handler. -- -- A concrete implementation of interface Callback_Handler is just -- required to define a procedure Sample_Ready that -- will be called when a new sample from the ADC is ready to be -- acquired. -- -- Why an object rather than a simple callback? Because an object -- can carry a state. For example, if the handler implements some -- filter it needs to keep the past story of the signal and this -- would be more cumbersome with a simple callback. --*** --****t* Fakedsp.card/Callback_Handler_Access -- SOURCE type Callback_Handler_Access is access all Callback_Handler'Class; --*** --****m* Callback_Handler/Sample_Ready -- SOURCE -- procedure Sample_Ready (H : in out Callback_Handler) is abstract; -- -- DESCRIPTION -- Procedure to be implemented by any concrete implementation of -- Callback_Handler. It will be called every time a new sample -- is ready. --*** --****m* Fakedsp.card/Start -- SOURCE procedure Start (Callback : Callback_Handler_Access; Input : Data_Streams.Data_Source_Access; Output : Data_Streams.Data_Destination_Access; In_Buffer_Size : Positive := 1; Out_Buffer_Size : Positive := 1) with Pre => Current_State = Sleeping, Post => Current_State = Running and ADC_DMA_Size = In_Buffer_Size and DAC_DMA_Size = Out_Buffer_Size; -- DESCRIPTION -- Turn on the "virtual acquisition card." Data will be read from the -- input source Input and written to Output. Data can be read/write -- sample by sample or blockwise (simulating a kind of DMA). The size -- of an input/output block (in samples) is specified by In_Buffer_Size -- and Out_Buffer_Size. -- -- Samples are read from the source at the sampling frequency determined -- by the data source. -- -- NOTES -- So far I tested it only for In_Buffer_Size=1 and Out_Buffer_Size=1. -- The more general case most probably works, but it is untested. --*** --****m* Fakedsp.card/ADC_DMA_Size,DAC_DMA_Size -- SOURCE function ADC_DMA_Size return Positive with Pre => Current_State > Sleeping; function DAC_DMA_Size return Positive with Pre => Current_State > Sleeping; --*** --****m* Fakedsp.card/Read_ADC -- SOURCE function Read_ADC return Sample_Array with Pre => Current_State > Sleeping; function Read_ADC return Sample_Type with Pre => Current_State > Sleeping and ADC_DMA_Size = 1; function Read_ADC return Float with Pre => Current_State > Sleeping and ADC_DMA_Size = 1; -- DESCRIPTION -- Read the sample (or block of samples) previously -- read by the virtual ADC. Note that if this function is called -- more than once before the Sample_Ready method of the handler is -- called, the same value is returned. Samples that are not read -- (because, say, the processing is too slow) are lost. -- -- The three functions differ in their return argument. The functions -- that return single samples (Sample_Type or Float) can be called -- only if Start was called with Out_Buffer_Size=1 --*** --****m* Fakedsp.card/Write_DAC -- SOURCE procedure Write_Dac (Data : Sample_Array) with Pre => Current_State > Sleeping; procedure Write_Dac (Data : Sample_Type) with Pre => Current_State > Sleeping and DAC_DMA_Size = 1; procedure Write_Dac (Data : Float) with Pre => Current_State > Sleeping and DAC_DMA_Size = 1; -- DESCRIPTION -- Write a sample (or a block of samples) to the virtual DAC. -- -- The two procedures accepting scalars (Sample_Type or Float) -- Can be called only if Start was called with Out_Buffer_Size=1 --*** end Fakedsp.Card;
package body constants with SPARK_Mode is type Buffer_Wrap_Idx is mod BUFLEN; head : Arr_T (0 .. 3); -- THIS must come before procedure, otherwise checks fail procedure readFromDev (data : out UBX_Data) is data_rx : Arr_T (0 .. BUFLEN - 1):= (others => 0); msg_start_idx : Buffer_Wrap_Idx; begin data := (others => 0); for i in 0 .. data_rx'Length - 2 loop if data_rx (i) = UBX_SYNC1 and data_rx (i + 1) = UBX_SYNC2 then msg_start_idx := Buffer_Wrap_Idx (i); declare idx_start : constant Buffer_Wrap_Idx := msg_start_idx + 2; idx_end : constant Buffer_Wrap_Idx := msg_start_idx + 5; pragma Assert (idx_start + 3 = idx_end); -- modulo works as ecpected begin if idx_start > idx_end then -- wrap head := data_rx (Integer (idx_start) .. data_rx'Last) & data_rx (data_rx'First .. Integer (idx_end)); else -- no wrap head := data_rx (Integer (idx_start) .. Integer (idx_end)); end if; end; exit; end if; end loop; end readFromDev; procedure Do_Something is test : UBX_Data; begin readFromDev (test); pragma Unreferenced (test); end Do_Something; end constants;
-- PR middle-end/36575 -- reporter: Laurent Guerby <laurent@guerby.net> -- { dg-do run } procedure Conv_Decimal is type Unsigned_Over_8 is mod 2**8+2; type Signed_Over_8 is range -200 .. 200; procedure Assert(Truth: Boolean) is begin if not Truth then raise Program_Error; end if; end; type Decim is delta 0.1 digits 5; Halfway : Decim := 2.5; Neg_Half : Decim := -2.5; Big : Unsigned_Over_8; Also_Big : Signed_Over_8; begin Big := Unsigned_Over_8 (Halfway); -- Rounds up by 4.6(33). Assert(Big = 3); Also_Big := Signed_Over_8 (Halfway); -- Rounds up by 4.6(33). Assert(Also_Big = 3); Also_Big := Signed_Over_8 (Neg_Half); -- Rounds down by 4.6(33). Assert(Also_Big = -3); end;
with Greeter; use Greeter; with Ada.Text_IO; use Ada.Text_IO; procedure Hello is package Int_IO is new Ada.Text_IO.Integer_IO (Integer); X : Integer := 2; procedure Do_It with Global => (Input => X); procedure Do_It is begin if X > 20 then Greeter.Greet ("Hello"); end if; end Do_It; begin -- Put_Line (Greeter.Hello_Text); Greeter.X := 10; for I in Integer range 0 .. 25 loop X := X + I; Do_It; end loop; Put_Line (Integer'Image (Greeter.X)); Put_Line (Integer'Image (X)); Int_IO.Put (X); New_Line; end Hello;
-- { dg-do compile } -- { dg-options "-gnatd.h" } with Concat1_Pkg; use Concat1_Pkg; package Concat1 is C : constant Natural := Id_For ("_" & Image_Of); end Concat1;
------------------------------------------------------------------------------ -- Copyright (c) 2015-2019, Natacha Porté -- -- -- -- Permission to use, copy, modify, and 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. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Reload_Pages provides a URL endpoint that unconditionally -- -- reloads the site upon POST request and redirects to the given path. -- -- -- -- WARNING: site reload can be a very expensive operation, and no access -- -- restriction or rate-limiting is implemented at this time, so care should -- -- be taken to ensure this endpoint is only accessible to trusted clients. -- ------------------------------------------------------------------------------ with Natools.S_Expressions; with Natools.Web.Sites; private with Natools.S_Expressions.Atom_Refs; package Natools.Web.Reload_Pages is type Reload_Page is new Sites.Page with private; overriding procedure Respond (Object : in out Reload_Page; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom); type Loader is new Sites.Transient_Page_Loader with private; overriding function Can_Be_Stored (Object : in Loader) return Boolean is (False); overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom); function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class; private type Reload_Page is new Sites.Page with record Target : S_Expressions.Atom_Refs.Immutable_Reference; end record; type Loader is new Sites.Transient_Page_Loader with record Target : S_Expressions.Atom_Refs.Immutable_Reference; end record; end Natools.Web.Reload_Pages;
pragma License (Unrestricted); -- extended unit generic type Index_Type is range <>; type Element_Type is private; type Array_Type is array (Index_Type range <>) of Element_Type; type Array_Access is access Array_Type; with procedure Free (X : in out Array_Access) is <>; package Ada.Containers.Generic_Array_Access_Types is -- Ada.Containers.Vectors-like utilities for access-to-array types. pragma Preelaborate; subtype Extended_Index is Index_Type'Base range Index_Type'Base'Pred (Index_Type'First) .. Index_Type'Last; function Length (Container : Array_Access) return Count_Type; procedure Set_Length ( Container : in out Array_Access; Length : Count_Type); procedure Clear (Container : in out Array_Access) renames Free; procedure Assign (Target : in out Array_Access; Source : Array_Access); procedure Move ( Target : in out Array_Access; Source : in out Array_Access); procedure Insert ( Container : in out Array_Access; Before : Extended_Index; New_Item : Array_Type); procedure Insert ( Container : in out Array_Access; Before : Extended_Index; New_Item : Array_Access); procedure Insert ( Container : in out Array_Access; Before : Extended_Index; New_Item : Element_Type; Count : Count_Type := 1); procedure Insert ( Container : in out Array_Access; Before : Extended_Index; Count : Count_Type := 1); procedure Prepend ( Container : in out Array_Access; New_Item : Array_Type); procedure Prepend ( Container : in out Array_Access; New_Item : Array_Access); procedure Prepend ( Container : in out Array_Access; New_Item : Element_Type; Count : Count_Type := 1); procedure Prepend ( Container : in out Array_Access; Count : Count_Type := 1); procedure Append ( Container : in out Array_Access; New_Item : Array_Type); procedure Append ( Container : in out Array_Access; New_Item : Array_Access); procedure Append ( Container : in out Array_Access; New_Item : Element_Type; Count : Count_Type := 1); procedure Append ( Container : in out Array_Access; Count : Count_Type := 1); procedure Delete ( Container : in out Array_Access; Index : Extended_Index; Count : Count_Type := 1); procedure Delete_First ( Container : in out Array_Access; Count : Count_Type := 1); procedure Delete_Last ( Container : in out Array_Access; Count : Count_Type := 1); procedure Swap (Container : in out Array_Access; I, J : Index_Type); function First_Index (Container : Array_Access) return Index_Type; function Last_Index (Container : Array_Access) return Extended_Index; generic with procedure Swap ( Container : in out Array_Access; I, J : Index_Type) is Generic_Array_Access_Types.Swap; package Generic_Reversing is procedure Reverse_Elements (Container : in out Array_Access); procedure Reverse_Rotate_Elements ( Container : in out Array_Access; Before : Extended_Index); procedure Juggling_Rotate_Elements ( Container : in out Array_Access; Before : Extended_Index); procedure Rotate_Elements ( Container : in out Array_Access; Before : Extended_Index) renames Juggling_Rotate_Elements; end Generic_Reversing; generic with function "<" (Left, Right : Element_Type) return Boolean is <>; with procedure Swap ( Container : in out Array_Access; I, J : Index_Type) is Generic_Array_Access_Types.Swap; package Generic_Sorting is function Is_Sorted (Container : Array_Access) return Boolean; procedure Insertion_Sort (Container : in out Array_Access); procedure Merge_Sort (Container : in out Array_Access); procedure Sort (Container : in out Array_Access) renames Merge_Sort; procedure Merge ( Target : in out Array_Access; Source : in out Array_Access); end Generic_Sorting; -- Allocating concatenation operators type New_Array (<>) is limited private; procedure Assign (Target : in out Array_Access; Source : New_Array); generic package Operators is type New_Array_1 (<>) is limited private; type New_Array_2 (<>) is limited private; function "&" (Left : Array_Access; Right : Element_Type) return New_Array; function "&" (Left : New_Array_1; Right : Element_Type) return New_Array; function "&" (Left : Array_Access; Right : Element_Type) return New_Array_1; function "&" (Left : New_Array_2; Right : Element_Type) return New_Array_1; function "&" (Left : Array_Access; Right : Element_Type) return New_Array_2; private type New_Array_1 is record Data : Array_Access; Last : Extended_Index; end record; pragma Suppress_Initialization (New_Array_1); type New_Array_2 is new New_Array_1; end Operators; private type New_Array is new Array_Access; end Ada.Containers.Generic_Array_Access_Types;
with System.Value_Errors; package body System.Val_Enum is function Value_Enumeration_8 ( Names : String; Indexes : Address; Num : Natural; Str : String) return Natural is First : Positive; Last : Natural; begin Trim (Str, First, Last); if First <= Last then declare type Index_Type is mod 2 ** 8; type Index_Array_Type is array (0 .. Num + 1) of Index_Type; Indexes_All : Index_Array_Type; for Indexes_All'Address use Indexes; S : String := Str (First .. Last); Next : Natural := Natural (Indexes_All (0)); begin if S (First) /= ''' then To_Upper (S); end if; for I in 0 .. Num loop declare P : constant Positive := Next; begin Next := Natural (Indexes_All (I + 1)); if S = Names (P .. Next - 1) then return I; end if; end; end loop; end; end if; Value_Errors.Raise_Discrete_Value_Failure ("Enum", Str); declare Uninitialized : Natural; pragma Unmodified (Uninitialized); begin return Uninitialized; end; end Value_Enumeration_8; function Value_Enumeration_16 ( Names : String; Indexes : Address; Num : Natural; Str : String) return Natural is First : Positive; Last : Natural; begin Trim (Str, First, Last); if First <= Last then declare type Index_Type is mod 2 ** 16; type Index_Array_Type is array (0 .. Num + 1) of Index_Type; Indexes_All : Index_Array_Type; for Indexes_All'Address use Indexes; S : String := Str (First .. Last); Next : Natural := Natural (Indexes_All (0)); begin if S (First) /= ''' then To_Upper (S); end if; for I in 0 .. Num loop declare P : constant Positive := Next; begin Next := Natural (Indexes_All (I + 1)); if S = Names (P .. Next - 1) then return I; end if; end; end loop; end; end if; Value_Errors.Raise_Discrete_Value_Failure ("Enum", Str); declare Uninitialized : Natural; pragma Unmodified (Uninitialized); begin return Uninitialized; end; end Value_Enumeration_16; function Value_Enumeration_32 ( Names : String; Indexes : Address; Num : Natural; Str : String) return Natural is First : Positive; Last : Natural; begin Trim (Str, First, Last); if First <= Last then declare type Index_Type is mod 2 ** 32; type Index_Array_Type is array (0 .. Num + 1) of Index_Type; Indexes_All : Index_Array_Type; for Indexes_All'Address use Indexes; S : String := Str (First .. Last); Next : Natural := Natural (Indexes_All (0)); begin if S (First) /= ''' then To_Upper (S); end if; for I in 0 .. Num loop declare P : constant Positive := Next; begin Next := Natural (Indexes_All (I + 1)); if S = Names (P .. Next - 1) then return I; end if; end; end loop; end; end if; Value_Errors.Raise_Discrete_Value_Failure ("Enum", Str); declare Uninitialized : Natural; pragma Unmodified (Uninitialized); begin return Uninitialized; end; end Value_Enumeration_32; procedure Trim (S : String; First : out Positive; Last : out Natural) is begin First := S'First; Last := S'Last; while First <= Last and then S (First) = ' ' loop First := First + 1; end loop; while First <= Last and then S (Last) = ' ' loop Last := Last - 1; end loop; end Trim; procedure To_Upper (S : in out String) is begin for I in S'Range loop if S (I) in 'a' .. 'z' then S (I) := Character'Val ( Character'Pos (S (I)) - (Character'Pos ('a') - Character'Pos ('A'))); end if; end loop; end To_Upper; end System.Val_Enum;
with any_Math; package short_Math is new any_Math (Real_t => short_Float); pragma Pure (short_Math);
package pointer_protected_p is type T; type Ptr is access protected procedure (Data : T); type T is record Data : Ptr; end record; end pointer_protected_p;
-- ___ _ ___ _ _ -- -- / __| |/ (_) | | Common SKilL implementation -- -- \__ \ ' <| | | |__ field handling in skill -- -- |___/_|\_\_|_|____| by: Timm Felden -- -- -- pragma Ada_2012; with Skill.Field_Types; with Skill.Field_Restrictions; with Skill.Internal.Parts; with Skill.Streams.Reader; with Skill.Streams.Writer; with Ada.Containers.Doubly_Linked_Lists; with Skill.Containers.Vectors; limited with Skill.Types.Pools; with Skill.Types; with Ada.Containers.Hashed_Maps; with Ada.Unchecked_Conversion; with Ada.Containers.Vectors; package Skill.Field_Declarations is -- pragma Preelaborate; --Data chunk information, as it is required for parsing of field data type Chunk_Entry_T is record C : Skill.Internal.Parts.Chunk; Input : Skill.Streams.Reader.Sub_Stream; end record; type Chunk_Entry is access Chunk_Entry_T; package Chunk_List_P is new Skill.Containers.Vectors (Natural, Chunk_Entry); type Owner_T is not null access Skill.Types.Pools.Pool_T; type Field_Declaration_T is abstract tagged record Data_Chunks : Chunk_List_P.Vector := Chunk_List_P.Empty_Vector; T : Skill.Field_Types.Field_Type; Name : Types.String_Access; Index : Natural; Owner : Owner_T; -- runtime restrictions Restrictions : Field_Restrictions.Vector; -- used for offset calculation -- note: ada has no futures, thus we will store the value in the field and -- synchronize over a barrier Future_Offset : Types.v64; end record; -- can not be not null, because we need to store them in arrays :-/ type Field_Declaration is access all Field_Declaration_T'Class; function Hash (This : Field_Declaration) return Ada.Containers.Hash_Type; use type Internal.Parts.Chunk; package Chunk_Map_P is new Ada.Containers.Hashed_Maps(Key_Type => Field_Declaration, Element_Type => Internal.Parts.Chunk, Hash => Hash, Equivalent_Keys => "=", "=" => "="); type Chunk_Map is not null access Chunk_Map_P.Map; package Field_Vector_P is new Skill.Containers.Vectors (Positive, Field_Declaration); subtype Field_Vector is Field_Vector_P.Vector; type Lazy_Field_T is new Field_Declaration_T with private; type Lazy_Field is access Lazy_Field_T'Class; type Auto_Field_T is abstract new Field_Declaration_T with private; type Auto_Field is access Auto_Field_T'Class; procedure Delete_Chunk (This : Chunk_Entry); function Name (This : access Field_Declaration_T'Class) return Types.String_Access; function Owner (This : access Field_Declaration_T'Class) return Types.Pools.Pool; -- @return ∀ r ∈ restrictinos, i ∈ owner. r.check(i) function Check (This : access Field_Declaration_T) return Boolean; function Check (This : access Lazy_Field_T) return Boolean; function Check (This : access Auto_Field_T) return Boolean is (True); procedure Read (This : access Field_Declaration_T; CE : Chunk_Entry) is abstract; procedure Read (This : access Lazy_Field_T; CE : Chunk_Entry); procedure Read (This : access Auto_Field_T; CE : Chunk_Entry) is null; -- offset calculation as preparation of writing data belonging to the -- owners last block procedure Offset (This : access Field_Declaration_T) is abstract; procedure Offset (This : access Lazy_Field_T); procedure Offset (This : access Auto_Field_T) is null; -- write data into a map at the end of a write/append operation -- @note this will always write the last chunk, as, in contrast to read, it is impossible to write to fields in -- parallel -- @note only called, if there actually is field data to be written procedure Write (This : access Field_Declaration_T; Output : Streams.Writer.Sub_Stream) is abstract; procedure Write (This : access Lazy_Field_T; Output : Streams.Writer.Sub_Stream); procedure Write (This : access Auto_Field_T; Output : Streams.Writer.Sub_Stream) is null; -- internal use only function Field_ID (This : access Field_Declaration_T'Class) return Natural; -- internal use only procedure Add_Chunk (This : access Field_Declaration_T'Class; C : Skill.Internal.Parts.Chunk); -- internal use only -- Fix offset and create memory map for field data parsing. function Add_Offset_To_Last_Chunk (This : access Field_Declaration_T'Class; Input : Skill.Streams.Reader.Input_Stream; File_Offset : Types.v64) return Types.v64; -- internal use only function Make_Lazy_Field (Owner : Owner_T; ID : Natural; T : Field_Types.Field_Type; Name : Skill.Types.String_Access; Restrictions : Field_Restrictions.Vector) return Lazy_Field; procedure Ensure_Is_Loaded (This : access Lazy_Field_T); procedure Free (This : access Field_Declaration_T) is abstract; procedure Free (This : access Lazy_Field_T); procedure Free (This : access Auto_Field_T) is null; private pragma Warnings (Off); function Hash is new Ada.Unchecked_Conversion(Internal.Parts.Chunk, Ada.Containers.Hash_Type); use type Streams.Reader.Sub_Stream; package Part_P is new Ada.Containers.Vectors(Natural, Chunk_Entry); function Hash is new Ada.Unchecked_Conversion(Types.Annotation, Ada.Containers.Hash_Type); use type Types.Box; use type Types.Annotation; package Data_P is new Ada.Containers.Hashed_Maps(Types.Annotation, Types.Box, Hash, "=", "="); type Lazy_Field_T is new Field_Declaration_T with record -- data held as in storage pools -- @note see paper notes for O(1) implementation -- @note in contrast to all other implementations, we deliberately wast -- time and space, because it is the only implementation that will make it -- through the compiler without me jumping out of the window trying to -- find an efficient workaround Data : Data_P.Map; -- Sparse Array[T]() -- pending parts that have to be loaded Parts : Part_P.Vector; end record; function Is_Loaded (This : access Lazy_Field_T'Class) return Boolean is (This.Parts.Is_Empty); procedure Load (This : access Lazy_Field_T'Class); type Auto_Field_T is new Field_Declaration_T with record null; end record; type Auto_Field_Array is array (Integer range <>) of Auto_Field; end Skill.Field_Declarations;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package body Orka.Timers is function Create_Timer return Timer is begin return Timer'(others => <>); end Create_Timer; use GL.Types; function Get_Duration (Value : UInt64) return Duration is Seconds : constant UInt64 := Value / 1e9; Nanoseconds : constant UInt64 := Value - Seconds * 1e9; begin return Duration (Seconds) + Duration (Nanoseconds) / 1e9; end Get_Duration; procedure Record_GPU_Duration (Object : in out Timer) is begin declare Stop_Time : constant UInt64 := Object.Query_Stop.Result; Start_Time : constant UInt64 := Object.Query_Start.Result; begin if Stop_Time > Start_Time then Object.GPU_Duration := Get_Duration (Stop_Time - Start_Time); end if; end; end Record_GPU_Duration; procedure Start (Object : in out Timer) is use GL.Objects.Queries; begin if Object.State = Waiting and then Object.Query_Stop.Result_Available then Object.Record_GPU_Duration; Object.State := Idle; end if; if Object.State = Idle then Object.CPU_Start := Get_Current_Time; Object.Query_Start.Record_Current_Time; Object.State := Busy; end if; end Start; procedure Stop (Object : in out Timer) is use GL.Objects.Queries; begin if Object.State = Busy then declare Current_Time : constant Long := Get_Current_Time; begin if Current_Time > Object.CPU_Start then Object.CPU_Duration := Get_Duration (UInt64 (Current_Time - Object.CPU_Start)); end if; end; Object.Query_Stop.Record_Current_Time; Object.State := Waiting; end if; end Stop; procedure Wait_For_Result (Object : in out Timer) is begin Object.Record_GPU_Duration; Object.State := Idle; end Wait_For_Result; function CPU_Duration (Object : Timer) return Duration is (Object.CPU_Duration); function GPU_Duration (Object : Timer) return Duration is (Object.GPU_Duration); end Orka.Timers;
with Ada.Containers.Hashed_Maps, Ada.Execution_Time, Ada.Long_Long_Integer_Text_IO, Ada.Real_Time, Ada.Strings.Fixed, Ada.Strings.Hash, Ada.Strings.Unbounded, Ada.Text_IO; with Utils; procedure Main is use Ada.Execution_Time, Ada.Real_Time, Ada.Strings.Unbounded, Ada.Text_IO; use Utils; Max_Steps : constant := 10; subtype Rule_Str is String (1 .. 2); subtype Long_Long_Natural is Long_Long_Integer range 0 .. Long_Long_Integer'Last; package Rule_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Rule_Str, Element_Type => Character, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); package Rule_Counter_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Rule_Str, Element_Type => Long_Long_Natural, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); use Rule_Maps; use Rule_Counter_Maps; File : File_Type; Start_Time, End_Time : CPU_Time; Execution_Duration : Time_Span; File_Is_Empty : Boolean := True; Result : Long_Long_Natural := Long_Long_Natural'First; Rules : Rule_Maps.Map := Rule_Maps.Empty_Map; Counter : Rule_Counter_Maps.Map := Rule_Counter_Maps.Empty_Map; Polymer_Template : Unbounded_String; begin Get_File (File); Polymer_Template := To_Unbounded_String (Get_Line (File)); -- Get all rules begin while not End_Of_File (File) loop declare Str : constant String := Get_Line (File); begin if Str'Length = 0 then goto Continue_Next_Line; end if; declare Pattern : constant String := " -> "; Separator_Index : constant Integer := Ada.Strings.Fixed.Index (Source => Str (1 .. Str'Last), Pattern => Pattern); Left_Str : constant String := Str (1 .. Separator_Index - 1); Right_Str : constant String := Str (Separator_Index + Pattern'Length .. Str'Last); begin Rules.Include (Rule_Str (Left_Str), Right_Str (Right_Str'First)); end; end; File_Is_Empty := False; <<Continue_Next_Line>> end loop; end; -- Exit the program if there is no values if File_Is_Empty then Close_If_Open (File); Put_Line ("The input file is empty."); return; end if; -- Initialize Counter for Index in 1 .. Length (Polymer_Template) - 1 loop if not Counter.Contains (Element (Polymer_Template, Index) & Element (Polymer_Template, Index + 1)) then Counter.Include (Element (Polymer_Template, Index) & Element (Polymer_Template, Index + 1), 0); end if; Counter.Include (Element (Polymer_Template, Index) & Element (Polymer_Template, Index + 1), Counter.Element (Element (Polymer_Template, Index) & Element (Polymer_Template, Index + 1)) + 1 ); end loop; -- Do the puzzle Start_Time := Ada.Execution_Time.Clock; Solve_Puzzle : declare begin for Step in 1 .. Max_Steps loop declare Temp_Counter : Rule_Counter_Maps.Map := Rule_Counter_Maps.Empty_Map; Current_Key : Rule_Str; Current_Rule_Key : Rule_Str; begin for Curs in Counter.Iterate loop Current_Key := Key (Curs); Current_Rule_Key := Current_Key (Rule_Str'First) & Rules (Current_Key); if not Temp_Counter.Contains (Current_Rule_Key) then Temp_Counter.Insert (Current_Rule_Key, 0); end if; Temp_Counter.Include (Current_Rule_Key, Temp_Counter.Element (Current_Rule_Key) + Counter.Element (Current_Key)); Current_Rule_Key := Rules (Current_Key) & Current_Key (Rule_Str'Last); if not Temp_Counter.Contains (Current_Rule_Key) then Temp_Counter.Insert (Current_Rule_Key, 0); end if; Temp_Counter.Include (Current_Rule_Key, Temp_Counter.Element (Current_Rule_Key) + Counter.Element (Current_Key)); end loop; Counter := Temp_Counter; end; end loop; Get_Result : declare function Character_Hash (Elt : Character) return Ada.Containers.Hash_Type is (Ada.Containers.Hash_Type (Character'Pos (Elt))); package Character_Counter_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Character, Element_Type => Long_Long_Natural, Hash => Character_Hash, Equivalent_Keys => "=", "=" => "="); use Character_Counter_Maps; Final_Counter : Character_Counter_Maps.Map := Character_Counter_Maps.Empty_Map; Min : Long_Long_Natural := Long_Long_Natural'Last; Max : Long_Long_Natural := Long_Long_Natural'First; Current_Key : Character; Current_Value : Long_Long_Natural; begin for Curs in Counter.Iterate loop Current_Key := Key (Curs) (Rule_Str'First); if not Final_Counter.Contains (Current_Key) then Final_Counter.Insert (Current_Key, 0); end if; Final_Counter.Include (Current_Key, Final_Counter.Element (Current_Key) + Counter.Element (Key (Curs))); end loop; Current_Key := Element (Polymer_Template, Length (Polymer_Template)); Final_Counter.Include (Current_Key, Final_Counter.Element (Current_Key) + 1); for Curs in Final_Counter.Iterate loop Current_Value := Element (Curs); if Current_Value < Min then Min := Current_Value; end if; if Current_Value > Max then Max := Current_Value; end if; end loop; Result := Max - Min; end Get_Result; end Solve_Puzzle; End_Time := Ada.Execution_Time.Clock; Execution_Duration := End_Time - Start_Time; Put ("Result: "); Ada.Long_Long_Integer_Text_IO.Put (Item => Result, Width => 0); New_Line; Put_Line ("(Took " & Duration'Image (To_Duration (Execution_Duration) * 1_000_000) & "µs)"); exception when others => Close_If_Open (File); raise; end Main;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-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 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 HAL.SPI; package body OpenMV is --------------------- -- Initialize_LEDs -- --------------------- procedure Initialize_LEDs is Conf : GPIO_Port_Configuration; begin Enable_Clock (All_LEDs); Conf.Mode := Mode_Out; Conf.Output_Type := Push_Pull; Conf.Speed := Speed_100MHz; Conf.Resistors := Floating; Configure_IO (All_LEDs, Conf); end Initialize_LEDs; ----------------- -- Set_RGB_LED -- ----------------- procedure Set_RGB_LED (C : LED_Color) is begin -- Clear to turn on LED -- Set to turn off case C is when White | Red | Yellow | Magenta => Clear (Red_LED); when others => Set (Red_LED); end case; case C is when White | Green | Yellow | Cyan => Clear (Green_LED); when others => Set (Green_LED); end case; case C is when White | Cyan | Blue | Magenta => Clear (Blue_LED); when others => Set (Blue_LED); end case; end Set_RGB_LED; ---------------- -- Turn_On_IR -- ---------------- procedure Turn_On_IR is begin Set (IR_LED); end Turn_On_IR; ----------------- -- Turn_Off_IR -- ----------------- procedure Turn_Off_IR is begin Clear (IR_LED); end Turn_Off_IR; --------------------------- -- Initialize_Shield_SPI -- --------------------------- procedure Initialize_Shield_SPI is SPI_Conf : STM32.SPI.SPI_Configuration; GPIO_Conf : STM32.GPIO.GPIO_Port_Configuration; begin STM32.Device.Enable_Clock (Shield_SPI_Points); GPIO_Conf.Speed := STM32.GPIO.Speed_100MHz; GPIO_Conf.Mode := STM32.GPIO.Mode_AF; GPIO_Conf.Output_Type := STM32.GPIO.Push_Pull; GPIO_Conf.Resistors := STM32.GPIO.Pull_Down; -- SPI low polarity STM32.GPIO.Configure_IO (Shield_SPI_Points, GPIO_Conf); STM32.GPIO.Configure_Alternate_Function (Shield_SPI_Points, GPIO_AF_SPI2_5); STM32.Device.Enable_Clock (Shield_SPI); STM32.SPI.Disable (Shield_SPI); SPI_Conf.Direction := STM32.SPI.D2Lines_FullDuplex; SPI_Conf.Mode := STM32.SPI.Master; SPI_Conf.Data_Size := HAL.SPI.Data_Size_8b; SPI_Conf.Clock_Polarity := STM32.SPI.Low; SPI_Conf.Clock_Phase := STM32.SPI.P1Edge; SPI_Conf.Slave_Management := STM32.SPI.Software_Managed; SPI_Conf.Baud_Rate_Prescaler := STM32.SPI.BRP_2; SPI_Conf.First_Bit := STM32.SPI.MSB; SPI_Conf.CRC_Poly := 7; STM32.SPI.Configure (Shield_SPI, SPI_Conf); STM32.SPI.Enable (Shield_SPI); end Initialize_Shield_SPI; ----------------------------- -- Initialize_Shield_USART -- ----------------------------- procedure Initialize_Shield_USART (Baud : STM32.USARTs.Baud_Rates) is Configuration : GPIO_Port_Configuration; begin Enable_Clock (Shield_USART); Enable_Clock (Shield_USART_Points); Configuration.Mode := Mode_AF; Configuration.Speed := Speed_50MHz; Configuration.Output_Type := Push_Pull; Configuration.Resistors := Pull_Up; Configure_IO (Shield_USART_Points, Configuration); Configure_Alternate_Function (Shield_USART_Points, Shield_USART_AF); Disable (Shield_USART); Set_Baud_Rate (Shield_USART, Baud); Set_Mode (Shield_USART, Tx_Rx_Mode); Set_Stop_Bits (Shield_USART, Stopbits_1); Set_Word_Length (Shield_USART, Word_Length_8); Set_Parity (Shield_USART, No_Parity); Set_Flow_Control (Shield_USART, No_Flow_Control); Enable (Shield_USART); end Initialize_Shield_USART; ---------------------- -- Get_Shield_USART -- ---------------------- function Get_Shield_USART return not null HAL.UART.Any_UART_Port is (USART_3'Access); end OpenMV;
with ada.strings.unbounded; use ada.strings.unbounded; package commandline_args is -- Exception indiquant l'absence d'un argument requis argument_missing : exception; -- lit les arguments de la ligne de commande -- exceptions: argument_missing en l'absence -- d'un argument obligatoire procedure initialize; -- Obtient le paramètre t function get_t return integer; -- Obtient le paramètre l function get_l return integer; -- Obtient le paramètre w function get_w return integer; -- Obtient le paramètre q function get_q return integer; -- Obtient le paramètre h function get_h return integer; -- Obtient le paramètre b function get_b return integer; -- Obtient le paramètre f function get_f return string; -- Obtient le paramètre fill function get_fill_color return string; -- Obtient le paramètre border function get_border_color return string; -- Obtient le paramètre help function get_show_help return boolean; -- Obtient le paramètre show-debug function get_show_debug return boolean; -- Obtient le paramètre log function get_log_file return string; -- Obtient le paramètre pattern function get_pattern return string; private -- Constante définissant l'état non initialise int_no_value : constant integer := -1; -- Les paramètres de l'application t, l, w, q, h, b : integer := int_no_value; f, border_color, fill_color, log_file, pattern : unbounded_string := null_unbounded_string; show_help, show_debug : boolean; end commandline_args;
with Ada.Command_Line; with Ada.Text_IO; function Example return Integer is function Square(num : Integer) return Integer is begin return num**2; end Square; function ReadCmdArgumentOrDefault(default: Integer) return Integer is begin if Ada.Command_Line.Argument_Count > 0 then return Integer'Value(Ada.Command_Line.Argument(1)); else return Default; end if; end ReadCmdArgumentOrDefault; NumberToSquare: Integer; Answer: Integer; begin NumberToSquare := ReadCmdArgumentOrDefault(4); Ada.Text_IO.Put_Line("Number to square: " & NumberToSquare'Image); Answer := Square(NumberToSquare); Ada.Text_IO.Put_Line("Square answer: " & Answer'Image); return Answer; end Example;
------------------------------------------------------------------------------ -- -- -- 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 . E X T E N S I O N S -- -- -- -- S p e c -- -- -- -- Copyright (c) 1995-2008, 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, 59 Temple Place -- -- - Suite 330, Boston, MA 02111-1307, 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 Ada Core Technologies Inc -- -- (http://www.gnat.com). -- -- -- ------------------------------------------------------------------------------ -- This package contains queries yielding various representation information -- which may be useful for ASIS applications, and which can not be obtained -- through the Asis.Data_Decomposition package as defined by the ASIS -- Standard. package Asis.Data_Decomposition.Extensions is generic type Constrained_Subtype is private; function Portable_Data_Value (Value : Constrained_Subtype) return Portable_Data; -- This is the inverse function for -- Asis.Data_Decomposition.Portable_Constrained_Subtype. Instantiated with -- an appropriate scalar type, (e.g., System.Integer, can be used to -- convert value to a data stream that can be used by ASIS Data -- Decomposition queries, in particular, for passing as an actual for the -- Value parameter of -- Asis.Data_Decomposition.Construct_Artificial_Data_Stream. -- -- Instantiated with a record type, can be used to convert a value to a -- data stream that can be analyzed by ASIS Data Decomposition queries. function Component_Name_Definition (Component : Record_Component) return Asis.Declaration; -- For the argument Compononent, returns the corresponding -- A_Defining_Identified Element. -- Asis.Data_Decomposition.Component_Declaration query can not be used to -- determine the name of the component in case if two or more record -- components are defined by the same component declaration or discriminant -- specification, that's why this query may be needed. -- -- All non-Nil component values are appropriate. -- -- Returns Defining_Name_Kinds: -- A_Defining_Identifier ---------------------------- -- Static type attributes -- ---------------------------- -- Queries defined in this section returns static representation -- attributes of types and subtypes. Some, but not all of the attributes -- defined in RM 95 which return representation information about types -- and subtypes and which are not functions are mapped onto -- Asis.Data_Decomposition.Extensions queries. -- --|AN Application Note: -- -- In contrast to Asis.Data_Decomposition queries which operates on type -- definitions, these queries operates on type and subtype defining names. -- The reason is that type and its subtypes may have different values of -- the same representation attribute, and this difference may be -- important for application. -------------------------------------------------------- -- Floating Point Types and Decimal Fixed Point Types -- -------------------------------------------------------- function Digits_Value (Floating_Point_Subtype : Asis.Element) return ASIS_Natural; -- Provided that Floating_Point_Subtype is the defining name of some -- floating point or decimal fixed point type or subtype (including types -- derived from floating point or decimal fixed point types), this -- function returns the requested decimal precision for this type or -- subtype, as defined in RM 95, 3.5.8(2), 3.5.10(7) -- -- Appropriate Defining_Name_Kinds -- A_Defining_Identifier, provided that it defines some floating -- point or decimal fixed point type -- or subtype ----------------------------------------------------- -- Fixed Point Types and Decimal Fixed Point Types -- ----------------------------------------------------- -- --|AN Application Note: -- -- For fixed point types, it is important to return the precise values of -- 'small' and 'delta'. The corresponding Ada attributes 'Small and 'Delta -- are defined in RM95 as being of universal_real type. But in this unit, -- we can not use universal_real as a return type of a query, and using -- any explicitly defined real type can not guarantee that the exact -- values of 'small' and 'delta' will be returned by the corresponding -- queries, since these values have arbitrary exact precision. -- -- To represent the value of universal_real type, the Small_Value -- and Delta_Value functions return a pair of integers representing -- the normalized fraction with integer numerator and denominator -- ("normalized means that the fraction is reduced to lowest terms), -- or alternatively a string is returned that contains the fraction -- represented in this manner. The latter form is the only one that -- can be used if the numerator or denominator is outside the range -- of ASIS_Integer. type Fraction is record Num : ASIS_Integer; Denum : ASIS_Positive; end record; function Small_Value (Fixed_Point_Subtype : Asis.Element) return String; -- Provided that Fixed_Point_Subtype is the defining name of some -- fixed point type or subtype (including types derived from fixed -- point types), this function returns the string image of 'small' of -- this type or subtype, as defined in RM 95, 3.5.10(2) as a string -- value representing a fraction (numerator / denominator), with no -- spaces, and both numerator and denominator represented in decimal. -- -- Appropriate Defining_Name_Kinds -- A_Defining_Identifier, provided that it defines some fixed point -- or decimal fixed point type or subtype function Small_Value (Fixed_Point_Subtype : Asis.Element) return Fraction; -- Provided that Fixed_Point_Subtype is the defining name of some -- fixed point type or subtype (including types derived from fixed -- point types), this function returns the fraction representation of -- 'small' of this type or subtype, as defined in RM 95, 3.5.10(2) -- ASIS_Failed is raised and the corresponding Diagnosis tring is set -- if the numerator or denominator is outside the representable range. -- -- Appropriate Defining_Name_Kinds -- A_Defining_Identifier, provided that it defines some fixed point -- or decimal fixed point type or subtype function Delta_Value (Fixed_Point_Subtype : Asis.Element) return String; -- Provided that Fixed_Point_Subtype is the defining name of some -- fixed point type or subtype (including types derived from fixed -- point types), this function returns the string image of 'delta' of -- this type or subtype, as defined in RM 95, 3.5.10(2) as a string -- value representing a fraction (numerator / denominator), with no -- spaces, and both numerator and denominator represented in decimal. -- -- Appropriate Defining_Name_Kinds -- A_Defining_Identifier, provided that it defines some fixed point -- or decimal fixed point type or subtype function Delta_Value (Fixed_Point_Subtype : Asis.Element) return Fraction; -- Provided that Fixed_Point_Subtype is the defining name of some -- fixed point type or subtype (including types derived from fixed -- point types), this function returns the fraction representation of -- 'delta' of this type or subtype, as defined in RM 95, 3.5.10(3) -- ASIS_Failed is raised and the corresponding Diagnosis tring is set -- if the numerator or denominator is outside the representable range. -- -- Appropriate Defining_Name_Kinds -- A_Defining_Identifier, provided that it defines some fixed point -- or decimal fixed point type or subtype ---------------------- -- Other Attributes -- ---------------------- -- The current version of Asis.Data_Decomposition.Extensions does not -- provide queries for the 'Fore or 'Aft attributes of fixed point types. ------------------------------- -- Decimal Fixed Point Types -- ------------------------------- function Scale_Value (Desimal_Fixed_Point_Subtype : Asis.Element) return ASIS_Natural; -- Provided that Desimal_Fixed_Point_Subtype is the defining name of some -- decimal fixed point type or subtype (including types derived from -- decimal fixed point types), this function returns the scale of -- this type or subtype, as defined in RM 95 3.5.10(11). -- -- Appropriate Defining_Name_Kinds -- A_Defining_Identifier, provided that it defines some decimal fixed -- point type or subtype end Asis.Data_Decomposition.Extensions;
-- DEMONSTRATION PROGRAM: -- Features: -- Recursive functions, separate compilation units, -- dynamic exception handling. with TEXT_IO; package SHORT_IO is new TEXT_IO.INTEGER_IO(integer); with TEXT_IO; use TEXT_IO; with SHORT_IO; use SHORT_IO; procedure factr is subtype short_int is integer range 0..9999; x : short_int; function factorial (x : short_int) return short_int is separate; begin outer: loop -- Compute factorial of each input item. begin put_line ("Factorial of:" ); loop -- Get an integer. begin exit outer when end_of_file ; get (x); exit; exception when others => put_line ("Enter a valid integer between 0 and 99"); end; end loop; put (" "); put (x); put ("! = "); put (factorial(x)); new_line(2); exception when constraint_error => put ("OVERFLOW" ); new_line(2); when others => exit; end; end loop outer; put_line("Glad to have been of service!" ); end factr; separate (factr) function factorial (x:short_int)return short_int is begin if x <= 1 then return 1; else return x * factorial (x-1); end if; end factorial;
-- -*- Mode: Ada -*- -- Filename : ether-forms.ads -- Description : Abstraction around the form data returned from the SCGI client (HTTP server). -- Author : Luke A. Guest -- Created On : Tue May 1 13:10:29 2012 with GNAT.Sockets; with Unicode.CES; package Ether.Forms is -- Form data is transmitted to the SCGI server in 1 of 2 ways, GET and PUT. GET provides -- the form data in the URI -- Each item in a form will have some data associated with it. This data will either be -- Unicode.CES.Byte_Sequence if it is normal data or it will be data, i.e. a file that -- has been encoded, Base64? -- -- We will handle the translation of text from whatever it comes in as, i.e. UTF-8 to -- the abstract type, Unicode.CES.Byte_Sequence, the application must then translate it to -- it's preferred encoding. -- -- Some forms can send multiple items per field, this will be handled internally as a list. -- The data stored will look something like this: -- -- +------------------------+ -- | Field | Data | -- +------------------------+ -- | forename | Barry | -- | surname | Watkins | -- | filename | hello.txt | - First in the filename list -- | filename | hello2.txt | - Second in the filename list -- +------------------------+ -- -- Obviously, any file that is transmitted to the SCGI server will also include the file -- data. -- -- Both urlencoded and multipart type forms will be supported by this package and will -- present the data in the same way. -- -- The form data is essentially mapping of: -- field name :-> list of data. -- type Data_Type is -- (Octet, -- This represents a file. -- String -- This is a unicode string encoded to Byte_Sequence. -- ); -- type Form is private; Form_Error : exception; procedure Decode_Query (Data : in String); procedure Decode_Content (Data : access String); -- private -- type Form is -- null record -- end record; end Ether.Forms;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 onox <denkpadje@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 GL.Barriers; with GL.Compute; with GL.Types.Compute; with Orka.Rendering.Programs.Modules; package body Orka.Algorithms.FFT is function Create_FFT (Location : Resources.Locations.Location_Ptr) return FFT is use Rendering.Programs; begin return Result : FFT := (Program_FFT => Create_Program (Modules.Create_Module (Location, CS => "algorithms/fft.comp")), others => <>) do Result.Uniform_Size := Result.Program_FFT.Uniform ("size"); Result.Uniform_Transpose := Result.Program_FFT.Uniform ("transposeData"); Result.Uniform_Inverse := Result.Program_FFT.Uniform ("inverseFFT"); declare Work_Group_Size : constant GL.Types.Compute.Dimension_Size_Array := Result.Program_FFT.Compute_Work_Group_Size; begin Result.Local_Size := Positive (Work_Group_Size (X)); end; end return; end Create_FFT; procedure Compute_FFT (Object : in out FFT; Buffer : Rendering.Buffers.Buffer; Width, Height : Positive; Transpose, Inverse : Boolean) is use GL.Types; use all type Rendering.Buffers.Indexed_Buffer_Target; Columns : constant Positive := (if Transpose then Height else Width); Rows : constant Positive := (if Transpose then Width else Height); pragma Assert (Columns <= Object.Local_Size); Rows_In_Shared : constant Size := Size (Object.Local_Size / Columns); begin Object.Uniform_Size.Set_Vector (GL.Types.UInt_Array'(UInt (Width), UInt (Height))); Object.Uniform_Transpose.Set_Boolean (Transpose); Object.Uniform_Inverse.Set_Boolean (Inverse); Object.Program_FFT.Use_Program; Buffer.Bind (Shader_Storage, 0); GL.Barriers.Memory_Barrier ((Shader_Storage => True, others => False)); GL.Compute.Dispatch_Compute (X => UInt (Single'Ceiling (Single (Rows) / Single (Rows_In_Shared)))); end Compute_FFT; end Orka.Algorithms.FFT;
with Ada.Finalization; package SoE is -- process Odd will be activated as part of the elaboration -- of the enclosing package ----------------------------------- task Odd is -- we want the user to set the limit of the search range entry Set_Limit (User_Limit : Positive); end Odd; ----------------------------------- task type Sieve_T (Id : Positive) is entry Relay (Int : Positive); end Sieve_T; type Sieve_Ref is access Sieve_T; -- for terminating processes to express last wishes -- we need to place explicitly finalizable objects -- within the scope of tasks that may be finalized: -- in this way, the task finalization will first require finalization -- of all objects in its scope, which will occur by automatic -- invocation of the method Finalize on each such object ----------------------------------- type Last_Wishes_T is new Ada.Finalization.Limited_Controlled with record Id : Positive; end record; procedure Finalize (Last_Wishes : in out Last_Wishes_T); -- the type of finalizable objects must be an extension of this -- special type of the language ----------------------------------- end SoE;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- B U T I L -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Opt; use Opt; with Output; use Output; with Unchecked_Deallocation; with GNAT; use GNAT; with System.OS_Lib; use System.OS_Lib; package body Butil is ----------------------- -- Local subprograms -- ----------------------- procedure Parse_Next_Unit_Name (Iter : in out Forced_Units_Iterator); -- Parse the name of the next available unit accessible through iterator -- Iter and save it in the iterator. function Read_Forced_Elab_Order_File return String_Ptr; -- Read the contents of the forced-elaboration-order file supplied to the -- binder via switch -f and return them as a string. Return null if the -- file is not available. -------------- -- Has_Next -- -------------- function Has_Next (Iter : Forced_Units_Iterator) return Boolean is begin return Present (Iter.Unit_Name); end Has_Next; ---------------------- -- Is_Internal_Unit -- ---------------------- -- Note: the reason we do not use the Fname package for this function -- is that it would drag too much junk into the binder. function Is_Internal_Unit return Boolean is begin return Is_Predefined_Unit or else (Name_Len > 4 and then (Name_Buffer (1 .. 5) = "gnat%" or else Name_Buffer (1 .. 5) = "gnat.")); end Is_Internal_Unit; ------------------------ -- Is_Predefined_Unit -- ------------------------ -- Note: the reason we do not use the Fname package for this function -- is that it would drag too much junk into the binder. function Is_Predefined_Unit return Boolean is L : Natural renames Name_Len; B : String renames Name_Buffer; begin return (L > 3 and then B (1 .. 4) = "ada.") or else (L > 6 and then B (1 .. 7) = "system.") or else (L > 10 and then B (1 .. 11) = "interfaces.") or else (L > 3 and then B (1 .. 4) = "ada%") or else (L > 8 and then B (1 .. 9) = "calendar%") or else (L > 9 and then B (1 .. 10) = "direct_io%") or else (L > 10 and then B (1 .. 11) = "interfaces%") or else (L > 13 and then B (1 .. 14) = "io_exceptions%") or else (L > 12 and then B (1 .. 13) = "machine_code%") or else (L > 13 and then B (1 .. 14) = "sequential_io%") or else (L > 6 and then B (1 .. 7) = "system%") or else (L > 7 and then B (1 .. 8) = "text_io%") or else (L > 20 and then B (1 .. 21) = "unchecked_conversion%") or else (L > 22 and then B (1 .. 23) = "unchecked_deallocation%") or else (L > 4 and then B (1 .. 5) = "gnat%") or else (L > 4 and then B (1 .. 5) = "gnat."); end Is_Predefined_Unit; -------------------------- -- Iterate_Forced_Units -- -------------------------- function Iterate_Forced_Units return Forced_Units_Iterator is Iter : Forced_Units_Iterator; begin Iter.Order := Read_Forced_Elab_Order_File; Parse_Next_Unit_Name (Iter); return Iter; end Iterate_Forced_Units; ---------- -- Next -- ---------- procedure Next (Iter : in out Forced_Units_Iterator; Unit_Name : out Unit_Name_Type; Unit_Line : out Logical_Line_Number) is begin if not Has_Next (Iter) then raise Iterator_Exhausted; end if; Unit_Line := Iter.Unit_Line; Unit_Name := Iter.Unit_Name; pragma Assert (Present (Unit_Name)); Parse_Next_Unit_Name (Iter); end Next; -------------------------- -- Parse_Next_Unit_Name -- -------------------------- procedure Parse_Next_Unit_Name (Iter : in out Forced_Units_Iterator) is Body_Suffix : constant String := " (body)"; Body_Type : constant String := "%b"; Body_Length : constant Positive := Body_Suffix'Length; Body_Offset : constant Natural := Body_Length - 1; Comment_Header : constant String := "--"; Comment_Offset : constant Natural := Comment_Header'Length - 1; Spec_Suffix : constant String := " (spec)"; Spec_Type : constant String := "%s"; Spec_Length : constant Positive := Spec_Suffix'Length; Spec_Offset : constant Natural := Spec_Length - 1; Index : Positive renames Iter.Order_Index; Line : Logical_Line_Number renames Iter.Order_Line; Order : String_Ptr renames Iter.Order; function At_Comment return Boolean; pragma Inline (At_Comment); -- Determine whether iterator Iter is positioned over the start of a -- comment. function At_Terminator return Boolean; pragma Inline (At_Terminator); -- Determine whether iterator Iter is positioned over a line terminator -- character. function At_Whitespace return Boolean; pragma Inline (At_Whitespace); -- Determine whether iterator Iter is positioned over a whitespace -- character. function Is_Terminator (C : Character) return Boolean; pragma Inline (Is_Terminator); -- Determine whether character C denotes a line terminator function Is_Whitespace (C : Character) return Boolean; pragma Inline (Is_Whitespace); -- Determine whether character C denotes a whitespace procedure Parse_Unit_Name; pragma Inline (Parse_Unit_Name); -- Find and parse the first available unit name procedure Skip_Comment; pragma Inline (Skip_Comment); -- Skip a comment by reaching a line terminator procedure Skip_Terminator; pragma Inline (Skip_Terminator); -- Skip a line terminator and deal with the logical line numbering procedure Skip_Whitespace; pragma Inline (Skip_Whitespace); -- Skip whitespace function Within_Order (Low_Offset : Natural := 0; High_Offset : Natural := 0) return Boolean; pragma Inline (Within_Order); -- Determine whether index of iterator Iter is still within the range of -- the order string. Low_Offset may be used to inspect the area that is -- less than the index. High_Offset may be used to inspect the area that -- is greater than the index. ---------------- -- At_Comment -- ---------------- function At_Comment return Boolean is begin -- The interator is over a comment when the index is positioned over -- the start of a comment header. -- -- unit (spec) -- comment -- ^ -- Index return Within_Order (High_Offset => Comment_Offset) and then Order (Index .. Index + Comment_Offset) = Comment_Header; end At_Comment; ------------------- -- At_Terminator -- ------------------- function At_Terminator return Boolean is begin return Within_Order and then Is_Terminator (Order (Index)); end At_Terminator; ------------------- -- At_Whitespace -- ------------------- function At_Whitespace return Boolean is begin return Within_Order and then Is_Whitespace (Order (Index)); end At_Whitespace; ------------------- -- Is_Terminator -- ------------------- function Is_Terminator (C : Character) return Boolean is begin -- Carriage return is treated intentionally as whitespace since it -- appears only on certain targets, while line feed is consistent on -- all of them. return C = ASCII.LF; end Is_Terminator; ------------------- -- Is_Whitespace -- ------------------- function Is_Whitespace (C : Character) return Boolean is begin return C = ' ' or else C = ASCII.CR -- carriage return or else C = ASCII.FF -- form feed or else C = ASCII.HT -- horizontal tab or else C = ASCII.VT; -- vertical tab end Is_Whitespace; --------------------- -- Parse_Unit_Name -- --------------------- procedure Parse_Unit_Name is pragma Assert (not At_Comment); pragma Assert (not At_Terminator); pragma Assert (not At_Whitespace); pragma Assert (Within_Order); procedure Find_End_Index_Of_Unit_Name; pragma Inline (Find_End_Index_Of_Unit_Name); -- Position the index of iterator Iter at the last character of the -- first available unit name. --------------------------------- -- Find_End_Index_Of_Unit_Name -- --------------------------------- procedure Find_End_Index_Of_Unit_Name is begin -- At this point the index points at the start of a unit name. The -- unit name may be legal, in which case it appears as: -- -- unit (body) -- -- However, it may also be illegal: -- -- unit without suffix -- unit with multiple prefixes (spec) -- -- In order to handle both forms, find the construct following the -- unit name. This is either a comment, a terminator, or the end -- of the order: -- -- unit (body) -- comment -- unit without suffix <terminator> -- unit with multiple prefixes (spec)<end of order> -- -- Once the construct is found, truncate the unit name by skipping -- all white space between the construct and the end of the unit -- name. -- Find the construct that follows the unit name while Within_Order loop if At_Comment then exit; elsif At_Terminator then exit; end if; Index := Index + 1; end loop; -- Position the index prior to the construct that follows the unit -- name. Index := Index - 1; -- Truncate towards the end of the unit name while Within_Order loop if At_Whitespace then Index := Index - 1; else exit; end if; end loop; end Find_End_Index_Of_Unit_Name; -- Local variables Start_Index : constant Positive := Index; End_Index : Positive; Is_Body : Boolean := False; Is_Spec : Boolean := False; -- Start of processing for Parse_Unit_Name begin Find_End_Index_Of_Unit_Name; End_Index := Index; pragma Assert (Start_Index <= End_Index); -- At this point the indices are positioned as follows: -- -- End_Index -- Index -- v -- unit (spec) -- comment -- ^ -- Start_Index -- Rewind the index, skipping over the legal suffixes -- -- Index End_Index -- v v -- unit (spec) -- comment -- ^ -- Start_Index if Within_Order (Low_Offset => Body_Offset) and then Order (Index - Body_Offset .. Index) = Body_Suffix then Is_Body := True; Index := Index - Body_Length; elsif Within_Order (Low_Offset => Spec_Offset) and then Order (Index - Spec_Offset .. Index) = Spec_Suffix then Is_Spec := True; Index := Index - Spec_Length; end if; -- Capture the line where the unit name is defined Iter.Unit_Line := Line; -- Transform the unit name to match the format recognized by the -- name table. if Is_Body then Iter.Unit_Name := Name_Find (Order (Start_Index .. Index) & Body_Type); elsif Is_Spec then Iter.Unit_Name := Name_Find (Order (Start_Index .. Index) & Spec_Type); -- Otherwise the unit name is illegal, so leave it as is else Iter.Unit_Name := Name_Find (Order (Start_Index .. Index)); end if; -- Advance the index past the unit name -- -- End_IndexIndex -- vv -- unit (spec) -- comment -- ^ -- Start_Index Index := End_Index + 1; end Parse_Unit_Name; ------------------ -- Skip_Comment -- ------------------ procedure Skip_Comment is begin pragma Assert (At_Comment); while Within_Order loop if At_Terminator then exit; end if; Index := Index + 1; end loop; end Skip_Comment; --------------------- -- Skip_Terminator -- --------------------- procedure Skip_Terminator is begin pragma Assert (At_Terminator); Index := Index + 1; Line := Line + 1; end Skip_Terminator; --------------------- -- Skip_Whitespace -- --------------------- procedure Skip_Whitespace is begin while Within_Order loop if At_Whitespace then Index := Index + 1; else exit; end if; end loop; end Skip_Whitespace; ------------------ -- Within_Order -- ------------------ function Within_Order (Low_Offset : Natural := 0; High_Offset : Natural := 0) return Boolean is begin return Order /= null and then Index - Low_Offset >= Order'First and then Index + High_Offset <= Order'Last; end Within_Order; -- Start of processing for Parse_Next_Unit_Name begin -- A line in the forced-elaboration-order file has the following -- grammar: -- -- LINE ::= -- [WHITESPACE] UNIT_NAME [WHITESPACE] [COMMENT] TERMINATOR -- -- WHITESPACE ::= -- <any whitespace character> -- | <carriage return> -- -- UNIT_NAME ::= -- UNIT_PREFIX [WHITESPACE] UNIT_SUFFIX -- -- UNIT_PREFIX ::= -- <any string> -- -- UNIT_SUFFIX ::= -- (body) -- | (spec) -- -- COMMENT ::= -- -- <any string> -- -- TERMINATOR ::= -- <line feed> -- <end of file> -- -- Items in <> brackets are semantic notions -- Assume that the order has no remaining units Iter.Unit_Line := No_Line_Number; Iter.Unit_Name := No_Unit_Name; -- Try to find the first available unit name from the current position -- of iteration. while Within_Order loop Skip_Whitespace; if At_Comment then Skip_Comment; elsif not Within_Order then exit; elsif At_Terminator then Skip_Terminator; else Parse_Unit_Name; exit; end if; end loop; end Parse_Next_Unit_Name; --------------------------------- -- Read_Forced_Elab_Order_File -- --------------------------------- function Read_Forced_Elab_Order_File return String_Ptr is procedure Free is new Unchecked_Deallocation (String, String_Ptr); Descr : File_Descriptor; Len : Natural; Len_Read : Natural; Result : String_Ptr; Success : Boolean; begin if Force_Elab_Order_File = null then return null; end if; -- Obtain and sanitize a descriptor to the elaboration-order file Descr := Open_Read (Force_Elab_Order_File.all, Binary); if Descr = Invalid_FD then return null; end if; -- Determine the size of the file, allocate a result large enough to -- house its contents, and read it. Len := Natural (File_Length (Descr)); if Len = 0 then return null; end if; Result := new String (1 .. Len); Len_Read := Read (Descr, Result (1)'Address, Len); -- The read failed to acquire the whole content of the file if Len_Read /= Len then Free (Result); return null; end if; Close (Descr, Success); -- The file failed to close if not Success then Free (Result); return null; end if; return Result; end Read_Forced_Elab_Order_File; ---------------- -- Uname_Less -- ---------------- function Uname_Less (U1, U2 : Unit_Name_Type) return Boolean is begin Get_Name_String (U1); declare U1_Name : constant String (1 .. Name_Len) := Name_Buffer (1 .. Name_Len); Min_Length : Natural; begin Get_Name_String (U2); if Name_Len < U1_Name'Last then Min_Length := Name_Len; else Min_Length := U1_Name'Last; end if; for J in 1 .. Min_Length loop if U1_Name (J) > Name_Buffer (J) then return False; elsif U1_Name (J) < Name_Buffer (J) then return True; end if; end loop; return U1_Name'Last < Name_Len; end; end Uname_Less; --------------------- -- Write_Unit_Name -- --------------------- procedure Write_Unit_Name (U : Unit_Name_Type) is begin Get_Name_String (U); Write_Str (Name_Buffer (1 .. Name_Len - 2)); if Name_Buffer (Name_Len) = 's' then Write_Str (" (spec)"); else Write_Str (" (body)"); end if; Name_Len := Name_Len + 5; end Write_Unit_Name; end Butil;
-- FILE: oedipus-elementary_functions.adb LICENSE: MIT © 2021 Mae Morella with Oedipus; use Oedipus; package body Oedipus.Elementary_Functions is function "+" (C1, C2 : in Complex) return Complex is Sum : Complex := Create_Complex (Get_Real (C1) + Get_Real (C2), Get_Imaginary (C1) + Get_Imaginary (C2)); begin return Sum; end "+"; function "-" (C : in Complex) return Complex is Neg : Complex := Create_Complex (-Get_Real (C), -Get_Imaginary (C)); begin return Neg; end "-"; function "+" (C : in Complex) return Complex is begin return C; end "+"; function "-" (C1, C2 : in Complex) return Complex is begin -- Depends on "+" and "-" operation return C1 + (-C2); end "-"; function "*" (C1, C2 : in Complex) return Complex is Prod : Complex := Create_Complex (Get_Real (C1) * Get_Real (C2) - Get_Imaginary (C1) * Get_Imaginary (C2), Get_Real (C1) * Get_Imaginary (C2) + Get_Imaginary (C1) * Get_Real (C2)); begin return Prod; end "*"; function Reciprocal (C : in Complex) return Complex is Denom : Float := Get_Real (C) * Get_Real (C) + Get_Imaginary (C) * Get_Imaginary (C); Recip : Complex := Create_Complex (A => Get_Real (C) / Denom, B => -Get_Imaginary (C) / Denom); begin if Denom = 0.0 then raise Div_By_Zero with "Cannot take reciprocal of 0.0 + 0.0i"; end if; return Recip; end Reciprocal; function "/" (C1, C2 : in Complex) return Complex is begin return C1 * Reciprocal (C2); end "/"; end Oedipus.Elementary_Functions;
---------------------------------------------------- -- agar_ada_core_demo.adb: Agar Ada bindings demo -- ---------------------------------------------------- with Agar; with Agar.Init; with Agar.Error; with Agar.Object; use Agar.Object; with Agar.Event; with Agar.DSO; with Agar.Types; use Agar.Types; with Ada.Text_IO; with System; with myatexit; with myeventhandler; with Animal; with Ada.Real_Time; use Ada.Real_Time; procedure agar_ada_core_demo is package T_IO renames Ada.Text_IO; package EV renames Agar.Event; package RT renames Ada.Real_Time; Major : Natural; Minor : Natural; Patch : Natural; My_Parent : Object_Access; My_Child_1 : Object_Access; My_Child_2 : Object_Access; Animal_Class : Class_Access; Cow : Object_Access; Event : EV.Event_Access; Epoch : constant RT.Time := RT.Clock; begin if not Agar.Init.Init_Core (Program_Name => "agar_ada_core_demo", Create_Directory => True) then raise program_error with Agar.Error.Get_Error; end if; T_IO.Put_Line("Agar-Core initialized in " & Duration'Image(RT.To_Duration(RT.Clock - Epoch)) & "s"); -- Register a test atexit callback. Agar.Init.At_Exit(myatexit.atexit'Access); -- Print Agar's version number. Agar.Init.Get_Version(Major, Minor, Patch); T_IO.Put_Line ("Agar version" & Integer'Image(Major) & " ." & Integer'Image(Minor) & " ." & Integer'Image(Patch)); T_IO.Put_Line ("Memory model: " & Natural'Image(AG_MODEL)); -- Register the Agar object class "Animal" specified in animal.ads. T_IO.Put_Line("Registering Animal class (" & Natural'Image(Animal.Animal'Size / System.Storage_Unit) & " bytes)"); Animal_Class := Animal.Create_Class; -- Create an instance the Animal class. Cow := New_Object(Animal_Class); Set_Name(Cow, "Cow"); Debug(Cow, "Moo!"); -- Create a generic AG_Object(3) instance. My_Parent := New_Object(Lookup_Class("AG_Object")); Set_Name(My_Parent, "My_Test_Object"); -- Access the class description of the object. T_IO.Put_Line("Object is" & Natural'Image(Natural(My_Parent.Class.Size)) & " bytes"); -- Configure an event handler for `some-event' and pass it some arguments. Event := Set_Event (Object => My_Parent, Event => "some-event", Func => myeventhandler.Some_Event'Access); EV.Push_String (Event, "This is a string argument"); -- untagged arguments EV.Push_Float (Event, 1234.0); EV.Push_Natural (Event, "width", 640); -- tagged arguments EV.Push_Natural (Event, "height", 480); -- Raise `some-event' by name. T_IO.Put_Line("Raising some-event by name"); Post_Event (My_Parent, "some-event"); -- Raise `some-event' by access (as returned by Set_Event). T_IO.Put_Line("Raising some-event by access"); Post_Event (My_Parent, Event); -- -- Raise `some-event' and pass the callback procedure some extra arguments -- on top of the existing argument list constructed by Set_Event. -- --Event := Prepare_Event (My_Parent, "Some-Event"); --EV.Push_Integer (Event, "timestamp", Ada.Real_Time.Clock - Epoch); --EV.Push_String (Event, "Hello there!"); --Post_Event (Event); -- Create two child objects under My_Parent. T_IO.Put_Line("Creating child objects"); My_Child_1 := New_Object(My_Parent, "My_Child_1", Lookup_Class("AG_Object")); My_Child_2 := New_Object(My_Parent, "My_Child_2", Lookup_Class("AG_Object")); -- Objects can send events to each other. Post_Event (Source => My_Child_1, Target => My_Child_2, Event => "Ping"); -- Propagate makes events broadcast to the object's descendants. Set_Event (Object => My_Parent, Event => "Ping", Func => myeventhandler.Ping'Access, Async => False, Propagate => True); Post_Event (Target => My_Parent, Event => "Ping"); T_IO.Put_Line("My_Parent path = " & Get_Name(My_Parent)); T_IO.Put_Line("My_Child_1 path = " & Get_Name(My_Child_1)); T_IO.Put_Line("My_Child_2 path = " & Get_Name(My_Child_2)); -- The Parent and Root members of an object are protected by the parent VFS. Lock_VFS(My_Child_2); T_IO.Put_Line("Parent of My_Child_2 is = " & Get_Name(My_Child_2.Parent)); T_IO.Put_Line("Root of My_Child_2 is = " & Get_Name(My_Child_2.Root)); Unlock_VFS(My_Child_2); -- Serialize an object to a file. if not Save(Cow, "Cow.obj") then raise program_error with Agar.Error.Get_Error; end if; T_IO.Put_Line("Saved Cow to Cow.obj"); if not Save(My_Parent, "My_Parent.obj") then raise program_error with Agar.Error.Get_Error; end if; T_IO.Put_Line("Saved My_Parent to My_Parent.obj"); -- Serialize the entire VFS to the default data directory. if not Save_All(My_Parent) then raise program_error with Agar.Error.Get_Error; end if; T_IO.Put_Line("Saved My_Parent to VFS"); -- Register a module directory and list all available DSOs. Agar.Object.Register_Module_Directory ("/tmp/dsotest"); declare DSO_List : constant Agar.DSO.DSO_List := Agar.DSO.Get_List; begin for DSO of DSO_List loop T_IO.Put("Available DSO: "); T_IO.Put_Line(DSO); end loop; end; Detach(My_Child_1); Detach(My_Child_2); Destroy(My_Child_1); Destroy(My_Child_2); Destroy(My_Parent); Destroy(Cow); Destroy_Class(Animal_Class); T_IO.Put_Line("Exiting after " & Duration'Image(RT.To_Duration(RT.Clock - Epoch)) & "s"); Agar.Init.Quit; end agar_ada_core_demo;
pragma License (Unrestricted); with System; package GNAT.Debug_Utilities is pragma Pure; function Value (S : String) return System.Address; end GNAT.Debug_Utilities;
-- { dg-do compile } package aggr1 is type Buffer_Array is array (1 .. 2 ** 23) of Integer; type Message is record Data : Buffer_Array := (others => 0); end record; end;
package body Tkmrpc.Contexts.ae is pragma Warnings (Off, "* already use-visible through previous use type clause"); use type Types.ae_id_type; use type Types.iag_id_type; use type Types.dhag_id_type; use type Types.ca_id_type; use type Types.lc_id_type; use type Types.ri_id_type; use type Types.authag_id_type; use type Types.init_type; use type Types.nonce_type; use type Types.nonce_type; use type Types.key_type; use type Types.key_type; use type Types.rel_time_type; use type Types.abs_time_type; use type Types.abs_time_type; pragma Warnings (On, "* already use-visible through previous use type clause"); type ae_FSM_Type is record State : ae_State_Type; iag_id : Types.iag_id_type; dhag_id : Types.dhag_id_type; ca_id : Types.ca_id_type; lc_id : Types.lc_id_type; ri_id : Types.ri_id_type; authag_id : Types.authag_id_type; initiator : Types.init_type; nonce_loc : Types.nonce_type; nonce_rem : Types.nonce_type; sk_ike_auth_loc : Types.key_type; sk_ike_auth_rem : Types.key_type; creation_time : Types.rel_time_type; cc_not_before : Types.abs_time_type; cc_not_after : Types.abs_time_type; end record; -- Authentication Endpoint Context Null_ae_FSM : constant ae_FSM_Type := ae_FSM_Type' (State => clean, iag_id => Types.iag_id_type'First, dhag_id => Types.dhag_id_type'First, ca_id => Types.ca_id_type'First, lc_id => Types.lc_id_type'First, ri_id => Types.ri_id_type'First, authag_id => Types.authag_id_type'First, initiator => Types.init_type'First, nonce_loc => Types.Null_nonce_type, nonce_rem => Types.Null_nonce_type, sk_ike_auth_loc => Types.Null_key_type, sk_ike_auth_rem => Types.Null_key_type, creation_time => Types.rel_time_type'First, cc_not_before => Types.abs_time_type'First, cc_not_after => Types.abs_time_type'First); type Context_Array_Type is array (Types.ae_id_type) of ae_FSM_Type; Context_Array : Context_Array_Type := Context_Array_Type' (others => (Null_ae_FSM)); ------------------------------------------------------------------------- function Get_State (Id : Types.ae_id_type) return ae_State_Type is begin return Context_Array (Id).State; end Get_State; ------------------------------------------------------------------------- function Has_authag_id (Id : Types.ae_id_type; authag_id : Types.authag_id_type) return Boolean is (Context_Array (Id).authag_id = authag_id); ------------------------------------------------------------------------- function Has_ca_id (Id : Types.ae_id_type; ca_id : Types.ca_id_type) return Boolean is (Context_Array (Id).ca_id = ca_id); ------------------------------------------------------------------------- function Has_cc_not_after (Id : Types.ae_id_type; cc_not_after : Types.abs_time_type) return Boolean is (Context_Array (Id).cc_not_after = cc_not_after); ------------------------------------------------------------------------- function Has_cc_not_before (Id : Types.ae_id_type; cc_not_before : Types.abs_time_type) return Boolean is (Context_Array (Id).cc_not_before = cc_not_before); ------------------------------------------------------------------------- function Has_creation_time (Id : Types.ae_id_type; creation_time : Types.rel_time_type) return Boolean is (Context_Array (Id).creation_time = creation_time); ------------------------------------------------------------------------- function Has_dhag_id (Id : Types.ae_id_type; dhag_id : Types.dhag_id_type) return Boolean is (Context_Array (Id).dhag_id = dhag_id); ------------------------------------------------------------------------- function Has_iag_id (Id : Types.ae_id_type; iag_id : Types.iag_id_type) return Boolean is (Context_Array (Id).iag_id = iag_id); ------------------------------------------------------------------------- function Has_initiator (Id : Types.ae_id_type; initiator : Types.init_type) return Boolean is (Context_Array (Id).initiator = initiator); ------------------------------------------------------------------------- function Has_lc_id (Id : Types.ae_id_type; lc_id : Types.lc_id_type) return Boolean is (Context_Array (Id).lc_id = lc_id); ------------------------------------------------------------------------- function Has_nonce_loc (Id : Types.ae_id_type; nonce_loc : Types.nonce_type) return Boolean is (Context_Array (Id).nonce_loc = nonce_loc); ------------------------------------------------------------------------- function Has_nonce_rem (Id : Types.ae_id_type; nonce_rem : Types.nonce_type) return Boolean is (Context_Array (Id).nonce_rem = nonce_rem); ------------------------------------------------------------------------- function Has_ri_id (Id : Types.ae_id_type; ri_id : Types.ri_id_type) return Boolean is (Context_Array (Id).ri_id = ri_id); ------------------------------------------------------------------------- function Has_sk_ike_auth_loc (Id : Types.ae_id_type; sk_ike_auth_loc : Types.key_type) return Boolean is (Context_Array (Id).sk_ike_auth_loc = sk_ike_auth_loc); ------------------------------------------------------------------------- function Has_sk_ike_auth_rem (Id : Types.ae_id_type; sk_ike_auth_rem : Types.key_type) return Boolean is (Context_Array (Id).sk_ike_auth_rem = sk_ike_auth_rem); ------------------------------------------------------------------------- function Has_State (Id : Types.ae_id_type; State : ae_State_Type) return Boolean is (Context_Array (Id).State = State); ------------------------------------------------------------------------- pragma Warnings (Off, "condition can only be False if invalid values present"); function Is_Valid (Id : Types.ae_id_type) return Boolean is (Context_Array'First <= Id and Id <= Context_Array'Last); pragma Warnings (On, "condition can only be False if invalid values present"); ------------------------------------------------------------------------- procedure activate (Id : Types.ae_id_type) is begin Context_Array (Id).State := active; end activate; ------------------------------------------------------------------------- procedure authenticate (Id : Types.ae_id_type; ca_context : Types.ca_id_type; authag_id : Types.authag_id_type; ri_id : Types.ri_id_type; not_before : Types.abs_time_type; not_after : Types.abs_time_type) is begin Context_Array (Id).ca_id := ca_context; Context_Array (Id).authag_id := authag_id; Context_Array (Id).ri_id := ri_id; Context_Array (Id).cc_not_before := not_before; Context_Array (Id).cc_not_after := not_after; Context_Array (Id).State := authenticated; end authenticate; ------------------------------------------------------------------------- procedure create (Id : Types.ae_id_type; iag_id : Types.iag_id_type; dhag_id : Types.dhag_id_type; creation_time : Types.rel_time_type; initiator : Types.init_type; sk_ike_auth_loc : Types.key_type; sk_ike_auth_rem : Types.key_type; nonce_loc : Types.nonce_type; nonce_rem : Types.nonce_type) is begin Context_Array (Id).iag_id := iag_id; Context_Array (Id).dhag_id := dhag_id; Context_Array (Id).creation_time := creation_time; Context_Array (Id).initiator := initiator; Context_Array (Id).sk_ike_auth_loc := sk_ike_auth_loc; Context_Array (Id).sk_ike_auth_rem := sk_ike_auth_rem; Context_Array (Id).nonce_loc := nonce_loc; Context_Array (Id).nonce_rem := nonce_rem; Context_Array (Id).State := unauth; end create; ------------------------------------------------------------------------- function get_lc_id (Id : Types.ae_id_type) return Types.lc_id_type is begin return Context_Array (Id).lc_id; end get_lc_id; ------------------------------------------------------------------------- function get_nonce_loc (Id : Types.ae_id_type) return Types.nonce_type is begin return Context_Array (Id).nonce_loc; end get_nonce_loc; ------------------------------------------------------------------------- function get_nonce_rem (Id : Types.ae_id_type) return Types.nonce_type is begin return Context_Array (Id).nonce_rem; end get_nonce_rem; ------------------------------------------------------------------------- function get_ri_id (Id : Types.ae_id_type) return Types.ri_id_type is begin return Context_Array (Id).ri_id; end get_ri_id; ------------------------------------------------------------------------- function get_sk_ike_auth_loc (Id : Types.ae_id_type) return Types.key_type is begin return Context_Array (Id).sk_ike_auth_loc; end get_sk_ike_auth_loc; ------------------------------------------------------------------------- function get_sk_ike_auth_rem (Id : Types.ae_id_type) return Types.key_type is begin return Context_Array (Id).sk_ike_auth_rem; end get_sk_ike_auth_rem; ------------------------------------------------------------------------- procedure invalidate (Id : Types.ae_id_type) is begin Context_Array (Id).State := invalid; end invalidate; ------------------------------------------------------------------------- function is_initiator (Id : Types.ae_id_type) return Types.init_type is begin return Context_Array (Id).initiator; end is_initiator; ------------------------------------------------------------------------- procedure reset (Id : Types.ae_id_type) is begin Context_Array (Id).iag_id := Types.iag_id_type'First; Context_Array (Id).dhag_id := Types.dhag_id_type'First; Context_Array (Id).ca_id := Types.ca_id_type'First; Context_Array (Id).lc_id := Types.lc_id_type'First; Context_Array (Id).ri_id := Types.ri_id_type'First; Context_Array (Id).authag_id := Types.authag_id_type'First; Context_Array (Id).initiator := Types.init_type'First; Context_Array (Id).nonce_loc := Types.Null_nonce_type; Context_Array (Id).nonce_rem := Types.Null_nonce_type; Context_Array (Id).sk_ike_auth_loc := Types.Null_key_type; Context_Array (Id).sk_ike_auth_rem := Types.Null_key_type; Context_Array (Id).creation_time := Types.rel_time_type'First; Context_Array (Id).cc_not_before := Types.abs_time_type'First; Context_Array (Id).cc_not_after := Types.abs_time_type'First; Context_Array (Id).State := clean; end reset; ------------------------------------------------------------------------- procedure sign (Id : Types.ae_id_type; lc_id : Types.lc_id_type) is begin Context_Array (Id).lc_id := lc_id; Context_Array (Id).State := loc_auth; end sign; end Tkmrpc.Contexts.ae;
------------------------------------------------------------------------------ -- -- -- 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.Sim.Memory_Bus; with LibRISCV.Except; with LibRISCV.CSR; private with LibRISCV.Instructions; package LibRISCV.Sim.Hart with SPARK_Mode => On is type Breakpoint_Number is range 0 .. 100; type Instance (Number_Of_Breakpoints : Breakpoint_Number := 1) is tagged limited private; subtype Class is Instance'Class; type Ptr is access all Class; procedure Reset (This : in out Instance); procedure Cycle (This : in out Instance; Bus : in out Sim.Memory_Bus.Class); type State_Kind is (Running, Debug_Halt, Single_Step); function State (This : Instance) return State_Kind; type Halt_Source_Kind is (None, Single_Step, Breakpoint, Watchpoint); function Halt_Source (This : in out Instance) return Halt_Source_Kind with Pre => This.State = Debug_Halt; procedure Halt (This : in out Instance) with Post => This.State = Debug_Halt; procedure Resume (This : in out Instance) with Pre => This.State = Debug_Halt; procedure Single_Step (This : in out Instance) with Post => This.State = Single_Step; function Read_GPR (This : Instance; Id : GPR_Id) return Register; procedure Write_GPR (This : in out Instance; Id : GPR_Id; Value : Register); function Read_PC (This : Instance) return Register; procedure Write_PC (This : in out Instance; Addr : Register); procedure Set_Debugger_Attached (This : in out Instance; Attached : Boolean := True); function Debug_Read_CSR (This : Instance; Id : CSR.Id) return Register; procedure Add_Breakpoint (This : in out Instance; Addr : Address; Success : out Boolean); procedure Remove_Breakpoint (This : in out Instance; Addr : Address; Success : out Boolean); procedure Dump (This : Instance); type Privilege_Level is (User, Machine) with Size => 2; private for Privilege_Level use (User => 0, Machine => 3); type GPR_Array is array (GPR_Id) of Register; type CSR_Array is array (CSR.Name) of Register; type Breakpoint_Rec is record Enabled : Boolean := False; Addr : Address; end record; type Breakpoint_Array is array (Breakpoint_Number range <>) of Breakpoint_Rec; type Instance (Number_Of_Breakpoints : Breakpoint_Number := 1) is tagged limited record Privilege : Privilege_Level := Machine; State : State_Kind := Debug_Halt; Halt_Src : Halt_Source_Kind := None; PC : Register; Next_PC : Register; Mcause : Except.Kind; Mepc : U_Register; GPR : GPR_Array; CSRs : CSR_Array; Debugger_Attached : Boolean := False; Breakpoints : Breakpoint_Array (1 .. Number_Of_Breakpoints); end record with Type_Invariant => Instance.GPR (0).U = 0; type Branch_Condition is (Cond_EQ, Cond_NE, Cond_LT, Cond_GE, Cond_GEU, Cond_LTU); procedure Fetch (This : in out Instance; Bus : in out Sim.Memory_Bus.Class; Raw_Insn : out Word; Success : out Boolean); function Evaluate (Cond : Branch_Condition; R1, R2 : Register) return Boolean; procedure Raise_Exception (This : in out Instance; E : Except.Kind; tval : U_Register := 0); procedure Read_CSR (This : in out Instance; Data : out Register; Id : CSR.Id); procedure Write_CSR (This : in out Instance; Data : Register; Id : CSR.Id); procedure Exec_Branch (This : in out Instance; Insn : Instructions.Instruction) with Pre => Insn.Kind in Instructions.B_Insn_Kind; procedure Exec_Instruction (This : in out Instance; Raw : Word; Bus : in out Sim.Memory_Bus.Class); procedure Exec_Invalid (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SLLI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SRLI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SRAI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_ADD (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SUB (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SLL (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SLT (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SLTU (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_XOR (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SRL (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SRA (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_OR (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_AND (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SB (This : in out Instance; Insn : Instructions.Instruction; Bus : in out Sim.Memory_Bus.Class); procedure Exec_SH (This : in out Instance; Insn : Instructions.Instruction; Bus : in out Sim.Memory_Bus.Class); procedure Exec_SW (This : in out Instance; Insn : Instructions.Instruction; Bus : in out Sim.Memory_Bus.Class); procedure Exec_JALR (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_LB (This : in out Instance; Insn : Instructions.Instruction; Bus : Sim.Memory_Bus.Class); procedure Exec_LH (This : in out Instance; Insn : Instructions.Instruction; Bus : Sim.Memory_Bus.Class); procedure Exec_LW (This : in out Instance; Insn : Instructions.Instruction; Bus : Sim.Memory_Bus.Class); procedure Exec_LBU (This : in out Instance; Insn : Instructions.Instruction; Bus : Sim.Memory_Bus.Class); procedure Exec_LHU (This : in out Instance; Insn : Instructions.Instruction; Bus : Sim.Memory_Bus.Class); procedure Exec_ADDI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SLTI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_SLTIU (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_XORI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_ORI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_ANDI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_FENCE (This : in out Instance); procedure Exec_FENCE_I (This : in out Instance); procedure Exec_ECALL (This : in out Instance); procedure Exec_EBREAK (This : in out Instance); procedure Exec_CSRRW (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_CSRRS (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_CSRRC (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_CSRRWI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_CSRRSI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_CSRRCI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_LUI (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_AUIPC (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_JAL (This : in out Instance; Insn : Instructions.Instruction); procedure Exec_XRET (This : in out Instance; Insn : Instructions.Instruction); end LibRISCV.Sim.Hart;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 onox <denkpadje@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.Fixed; package body EGL is package SF renames Ada.Strings.Fixed; function Trim (Value : C.Strings.chars_ptr) return String is (SF.Trim (C.Strings.Value (Value), Ada.Strings.Right)); function Extensions (Value : C.Strings.chars_ptr) return String_List is Extensions : constant String := Trim (Value); Index : Positive := Extensions'First; begin return Result : String_List (1 .. SF.Count (Extensions, " ") + 1) do for I in Result'First .. Result'Last - 1 loop declare Next_Index : constant Positive := SF.Index (Extensions, " ", Index + 1); begin Result (I) := SU.To_Unbounded_String (Extensions (Index .. Next_Index - 1)); Index := Next_Index + 1; end; end loop; Result (Result'Last) := SU.To_Unbounded_String (Extensions (Index .. Extensions'Last)); end return; end Extensions; function Has_Extension (Extensions : String_List; Name : String) return Boolean is use type SU.Unbounded_String; begin return (for some Extension of Extensions => Extension = Name); end Has_Extension; procedure Check_Extension (Extensions : String_List; Name : String) is begin if not Has_Extension (Extensions, Name) then raise Feature_Not_Supported with Name & " not supported"; end if; end Check_Extension; end EGL;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- XML Processor -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with League.Strings; with XML.DOM.Attributes; with XML.DOM.Elements; with XML.DOM.Nodes; with XML.DOM.Texts; package XML.DOM.Documents is pragma Preelaborate; type DOM_Document is limited interface and XML.DOM.Nodes.DOM_Node; type DOM_Document_Access is access all DOM_Document'Class with Storage_Size => 0; not overriding function Create_Attribute_NS (Self : not null access DOM_Document; Namespace_URI : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String) return not null XML.DOM.Attributes.DOM_Attribute_Access is abstract; -- Creates an attribute of the given qualified name and namespace URI. -- -- Per [XML Namespaces], applications must use the value null as the -- namespaceURI parameter for methods if they wish to have no namespace. -- -- Parameters -- -- namespaceURI of type DOMString -- The namespace URI of the attribute to create. -- -- qualifiedName of type DOMString -- The qualified name of the attribute to instantiate. -- -- Return Value -- -- Attr -- A new Attr object with the following attributes: -- -- Attribute Value -- Node.nodeName qualifiedName -- Node.namespaceURI namespaceURI -- Node.prefix prefix, extracted from qualifiedName, or null if -- there is no prefix -- Node.localName local name, extracted from qualifiedName -- Attr.name qualifiedName -- Node.nodeValue the empty string -- -- Exceptions -- -- DOMException -- -- INVALID_CHARACTER_ERR: Raised if the specified qualifiedName is not -- an XML name according to the XML version in use specified in the -- Document.xmlVersion attribute. -- -- NAMESPACE_ERR: Raised if the qualifiedName is a malformed qualified -- name, if the qualifiedName has a prefix and the namespaceURI is -- null, if the qualifiedName has a prefix that is "xml" and the -- namespaceURI is different from -- "http://www.w3.org/XML/1998/namespace", if the qualifiedName or its -- prefix is "xmlns" and the namespaceURI is different from -- "http://www.w3.org/2000/xmlns/", or if the namespaceURI is -- "http://www.w3.org/2000/xmlns/" and neither the qualifiedName nor -- its prefix is "xmlns". -- -- NOT_SUPPORTED_ERR: Always thrown if the current document does not -- support the "XML" feature, since namespaces were defined by XML. not overriding function Create_Element_NS (Self : not null access DOM_Document; Namespace_URI : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String) return not null XML.DOM.Elements.DOM_Element_Access is abstract; -- Creates an element of the given qualified name and namespace URI. -- -- Per [XML Namespaces], applications must use the value null as the -- namespaceURI parameter for methods if they wish to have no namespace. -- -- Parameters -- -- namespaceURI of type DOMString -- The namespace URI of the element to create. -- -- qualifiedName of type DOMString -- The qualified name of the element type to instantiate. -- -- Return Value -- -- Element -- A new Element object with the following attributes: -- -- Attribute Value -- Node.nodeName qualifiedName -- Node.namespaceURI namespaceURI -- Node.prefix prefix, extracted from qualifiedName, or null if -- there is no prefix -- Node.localName local name, extracted from qualifiedName -- Element.tagName qualifiedName -- -- Exceptions -- -- DOMException -- -- INVALID_CHARACTER_ERR: Raised if the specified qualifiedName is not -- an XML name according to the XML version in use specified in the -- Document.xmlVersion attribute. -- -- NAMESPACE_ERR: Raised if the qualifiedName is a malformed qualified -- name, if the qualifiedName has a prefix and the namespaceURI is -- null, or if the qualifiedName has a prefix that is "xml" and the -- namespaceURI is different from -- "http://www.w3.org/XML/1998/namespace" [XML Namespaces], or if the -- qualifiedName or its prefix is "xmlns" and the namespaceURI is -- different from "http://www.w3.org/2000/xmlns/", or if the -- namespaceURI is "http://www.w3.org/2000/xmlns/" and neither the -- qualifiedName nor its prefix is "xmlns". -- -- NOT_SUPPORTED_ERR: Always thrown if the current document does not -- support the "XML" feature, since namespaces were defined by XML. not overriding function Create_Text_Node (Self : not null access DOM_Document; Data : League.Strings.Universal_String) return not null XML.DOM.Texts.DOM_Text_Access is abstract; -- Creates a Text node given the specified string. -- -- Parameters -- -- data of type DOMString -- The data for the node. -- -- Return Value -- -- Text -- The new Text object. not overriding function Error_Code (Self : not null access constant DOM_Document) return XML.DOM.Error_Code is abstract; -- Returns DOM error code for last raised DOM_Exception. not overriding function Error_String (Self : not null access constant DOM_Document) return League.Strings.Universal_String is abstract; -- Returns error string for last raised DOM_Exception. end XML.DOM.Documents;
package body Discr42_Pkg is function F (Pos : in out Natural) return Rec is begin Pos := Pos + 1; if Pos > 1 then return (D => True, N => Pos * 2); else return (D => False); end if; end; end Discr42_Pkg;
-- -- Copyright (C) 2022 Jeremy Grosser <jeremy@synack.me> -- -- SPDX-License-Identifier: BSD-3-Clause -- package body CRC is procedure Update (Data : Word) is Bits : constant Positive := Word'Size; MSB : constant Word := 2 ** (Bits - 1); begin Sum := Sum xor Data; for I in 1 .. Bits loop if (Sum and MSB) /= 0 then Sum := (Sum * 2) xor Poly; else Sum := (Sum * 2); end if; end loop; end Update; procedure Update (Data : Word_Array) is begin for D of Data loop Update (D); end loop; end Update; function Calculate (Data : Word_Array; Initial : Word := 0) return Word is begin Sum := Initial; Update (Data); return Sum; end Calculate; end CRC;
package Nodes is -- Type Node definition type Node is tagged private; type Node_Ptr is access Node; private -- Type node data-structre type Node is tagged record end record; end Nodes;