content
stringlengths
23
1.05M
pragma License (Unrestricted); -- implementation unit required by compiler with System.Storage_Elements; with System.Storage_Pools; package System.Pool_Size is pragma Preelaborate; use type Storage_Elements.Storage_Offset; type Aligned_Storage_Array is new Storage_Elements.Storage_Array; for Aligned_Storage_Array'Alignment use Standard'Maximum_Alignment; -- mixed type Bounded_Allocator ( Size : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count) is limited record First_Free : Storage_Elements.Storage_Offset := -1; -- offset First_Empty : Storage_Elements.Storage_Count := 0; -- offset Storage : aliased Aligned_Storage_Array (1 .. Size); end record; for Bounded_Allocator'Alignment use Standard'Maximum_Alignment; procedure Allocate ( Allocator : aliased in out Bounded_Allocator; Storage_Address : out Address; Size_In_Storage_Elements : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count); procedure Deallocate ( Allocator : aliased in out Bounded_Allocator; Storage_Address : Address; Size_In_Storage_Elements : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count); function Storage_Size (Allocator : Bounded_Allocator) return Storage_Elements.Storage_Count; pragma Inline (Storage_Size); pragma Simple_Storage_Pool_Type (Bounded_Allocator); -- fixed type Bounded_Fixed_Allocator ( Size : Storage_Elements.Storage_Count; Component_Size : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count) is limited record First_Free : Storage_Elements.Storage_Offset := -1; -- offset First_Empty : Storage_Elements.Storage_Count := 0; -- offset Storage : aliased Aligned_Storage_Array (1 .. Size); end record; for Bounded_Fixed_Allocator'Alignment use Standard'Maximum_Alignment; procedure Allocate ( Allocator : aliased in out Bounded_Fixed_Allocator; Storage_Address : out Address; Size_In_Storage_Elements : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count); procedure Deallocate ( Allocator : aliased in out Bounded_Fixed_Allocator; Storage_Address : Address; Size_In_Storage_Elements : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count); function Storage_Size (Allocator : Bounded_Fixed_Allocator) return Storage_Elements.Storage_Count; pragma Inline (Storage_Size); pragma Simple_Storage_Pool_Type (Bounded_Fixed_Allocator); -- required for access types having explicit 'Storage_Size > 0 by compiler -- (s-poosiz.ads) type Stack_Bounded_Pool ( Pool_Size : Storage_Elements.Storage_Count; Elmt_Size : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count) is limited new Storage_Pools.Root_Storage_Pool with record case Elmt_Size is when 0 => Mixed : aliased Bounded_Allocator (Pool_Size, Alignment); when others => Fixed : aliased Bounded_Fixed_Allocator (Pool_Size, Elmt_Size, Alignment); end case; end record with Disable_Controlled => True; pragma Finalize_Storage_Only (Stack_Bounded_Pool); overriding procedure Allocate ( Pool : in out Stack_Bounded_Pool; Storage_Address : out Address; Size_In_Storage_Elements : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count); pragma Inline (Allocate); overriding procedure Deallocate ( Pool : in out Stack_Bounded_Pool; Storage_Address : Address; Size_In_Storage_Elements : Storage_Elements.Storage_Count; Alignment : Storage_Elements.Storage_Count); pragma Inline (Deallocate); overriding function Storage_Size (Pool : Stack_Bounded_Pool) return Storage_Elements.Storage_Count; pragma Inline (Storage_Size); end System.Pool_Size;
-- Package to provide information on how memories can be implemented in BRAM. -- This package relies on the Device package for information on BRAMs. package BRAM is -- Get the number of BRAMs that would be required for the -- specified memory aspect ratio. function Get_Count(width : Natural; depth : Natural) return Natural; end BRAM;
-- This file is generated by SWIG. Do *not* modify by hand. -- package LLVM_bit_Reader is end LLVM_bit_Reader;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- B I N D O . E L A B O R A T O R S -- -- -- -- B o d y -- -- -- -- Copyright (C) 2019-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 Butil; use Butil; with Debug; use Debug; with Output; use Output; with Types; use Types; with Bindo.Augmentors; use Bindo.Augmentors; use Bindo.Augmentors.Library_Graph_Augmentors; with Bindo.Builders; use Bindo.Builders; use Bindo.Builders.Invocation_Graph_Builders; use Bindo.Builders.Library_Graph_Builders; with Bindo.Diagnostics; use Bindo.Diagnostics; with Bindo.Units; use Bindo.Units; with Bindo.Validators; use Bindo.Validators; use Bindo.Validators.Elaboration_Order_Validators; with Bindo.Writers; use Bindo.Writers; use Bindo.Writers.ALI_Writers; use Bindo.Writers.Dependency_Writers; use Bindo.Writers.Elaboration_Order_Writers; use Bindo.Writers.Invocation_Graph_Writers; use Bindo.Writers.Library_Graph_Writers; use Bindo.Writers.Phase_Writers; use Bindo.Writers.Unit_Closure_Writers; with GNAT; use GNAT; with GNAT.Graphs; use GNAT.Graphs; package body Bindo.Elaborators is -- The following type defines the advancement of the elaboration order -- algorithm in terms of steps. type Elaboration_Order_Step is new Natural; Initial_Step : constant Elaboration_Order_Step := Elaboration_Order_Step'First; ---------------------------------------------- -- Invocation_And_Library_Graph_Elaborators -- ---------------------------------------------- package body Invocation_And_Library_Graph_Elaborators is ----------------------- -- Local subprograms -- ----------------------- procedure Create_Component_Vertex_Sets (G : Library_Graph; Comp : Component_Id; Elaborable_Vertices : out LGV_Sets.Membership_Set; Waiting_Vertices : out LGV_Sets.Membership_Set; Step : Elaboration_Order_Step); pragma Inline (Create_Component_Vertex_Sets); -- Split all vertices of component Comp of library graph G as follows: -- -- * Elaborable vertices are added to set Elaborable_Vertices. -- -- * Vertices that are still waiting on their predecessors to be -- elaborated are added to set Waiting_Vertices. -- -- Step is the current step in the elaboration order. procedure Create_Vertex_Sets (G : Library_Graph; Elaborable_Vertices : out LGV_Sets.Membership_Set; Waiting_Vertices : out LGV_Sets.Membership_Set; Step : Elaboration_Order_Step); pragma Inline (Create_Vertex_Sets); -- Split all vertices of library graph G as follows: -- -- * Elaborable vertices are added to set Elaborable_Vertices. -- -- * Vertices that are still waiting on their predecessors to be -- elaborated are added to set Waiting_Vertices. -- -- Step is the current step in the elaboration order. procedure Elaborate_Component (G : Library_Graph; Comp : Component_Id; All_Elaborable_Vertices : LGV_Sets.Membership_Set; All_Waiting_Vertices : LGV_Sets.Membership_Set; Order : in out Unit_Id_Table; Step : Elaboration_Order_Step); pragma Inline (Elaborate_Component); -- Elaborate as many vertices as possible that appear in component Comp -- of library graph G. The sets contain vertices arranged as follows: -- -- * All_Elaborable_Vertices - all elaborable vertices in the library -- graph. -- -- * All_Waiting_Vertices - all vertices in the library graph that are -- waiting on predecessors to be elaborated. -- -- Order is the elaboration order. Step denotes the current step in the -- elaboration order. procedure Elaborate_Library_Graph (G : Library_Graph; Order : out Unit_Id_Table; Status : out Elaboration_Order_Status); pragma Inline (Elaborate_Library_Graph); -- Elaborate as many vertices as possible of library graph G. Order is -- the elaboration order. Status is the condition of the elaboration -- order. procedure Elaborate_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; All_Elaborable_Vertices : LGV_Sets.Membership_Set; All_Waiting_Vertices : LGV_Sets.Membership_Set; Comp_Elaborable_Vertices : LGV_Sets.Membership_Set; Comp_Waiting_Vertices : LGV_Sets.Membership_Set; Order : in out Unit_Id_Table; Step : Elaboration_Order_Step; Indent : Indentation_Level); pragma Inline (Elaborate_Vertex); -- Elaborate vertex Vertex of library graph G by adding its unit to -- elaboration order Order. The routine updates awaiting successors -- where applicable. The sets contain vertices arranged as follows: -- -- * All_Elaborable_Vertices - all elaborable vertices in the library -- graph. -- -- * All_Waiting_Vertices - all vertices in the library graph that are -- waiting on predecessors to be elaborated. -- -- * Comp_Elaborable_Vertices - all elaborable vertices found in the -- component of Vertex. -- -- * Comp_Waiting_Vertices - all vertices found in the component of -- Vertex that are still waiting on predecessors to be elaborated. -- -- Order denotes the elaboration order. Step is the current step in the -- elaboration order. Indent denotes the desired indentation level for -- tracing. function Find_Best_Elaborable_Vertex (G : Library_Graph; Set : LGV_Sets.Membership_Set; Step : Elaboration_Order_Step; Indent : Indentation_Level) return Library_Graph_Vertex_Id; pragma Inline (Find_Best_Elaborable_Vertex); -- Find the best vertex of library graph G from membership set S that -- can be elaborated. Step is the current step in the elaboration order. -- Indent is the desired indentation level for tracing. function Find_Best_Vertex (G : Library_Graph; Set : LGV_Sets.Membership_Set; Is_Suitable_Vertex : LGV_Predicate_Ptr; Compare_Vertices : LGV_Comparator_Ptr; Initial_Best_Msg : String; Subsequent_Best_Msg : String; Step : Elaboration_Order_Step; Indent : Indentation_Level) return Library_Graph_Vertex_Id; pragma Inline (Find_Best_Vertex); -- Find the best vertex of library graph G from membership set S which -- satisfies predicate Is_Suitable_Vertex and is preferred by comparator -- Compare_Vertices. Initial_Best_Msg is emitted on the first candidate -- vertex. Subsequent_Best_Msg is emitted whenever a better vertex is -- discovered. Step is the current step in the elaboration order. Indent -- is the desired indentation level for tracing. function Find_Best_Weakly_Elaborable_Vertex (G : Library_Graph; Set : LGV_Sets.Membership_Set; Step : Elaboration_Order_Step; Indent : Indentation_Level) return Library_Graph_Vertex_Id; pragma Inline (Find_Best_Weakly_Elaborable_Vertex); -- Find the best vertex of library graph G from membership set S that -- can be weakly elaborated. Step is the current step in the elaboration -- order. Indent is the desired indentation level for tracing. function Has_Elaborable_Body (G : Library_Graph; Vertex : Library_Graph_Vertex_Id) return Boolean; pragma Inline (Has_Elaborable_Body); -- Determine whether vertex Vertex of library graph G has a body that is -- elaborable. It is assumed that the vertex has been elaborated. procedure Insert_Elaborable_Successor (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; Elaborable_Vertices : LGV_Sets.Membership_Set; All_Waiting_Vertices : LGV_Sets.Membership_Set; Comp_Waiting_Vertices : LGV_Sets.Membership_Set; Msg : String; Step : Elaboration_Order_Step; Indent : Indentation_Level); pragma Inline (Insert_Elaborable_Successor); -- Add elaborable successor Vertex of library graph G to membership set -- Elaborable_Vertices and remove it from both All_Waiting_Vertices and -- Comp_Waiting_Vertices. Msg is a message emitted for tracing purposes. -- Step is the current step in the elaboration order. Indent denotes the -- desired indentation level for tracing. procedure Insert_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; Set : LGV_Sets.Membership_Set; Msg : String; Step : Elaboration_Order_Step; Indent : Indentation_Level); pragma Inline (Insert_Vertex); -- Add vertex Vertex of library graph G to membership set Set. Msg is -- a message emitted for tracing purposes. Step is the current step in -- the elaboration order. Indent is the desired indentation level for -- tracing. function Is_Better_Elaborable_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; Compared_To : Library_Graph_Vertex_Id) return Precedence_Kind; pragma Inline (Is_Better_Elaborable_Vertex); -- Determine whether vertex Vertex of library graph G is a better choice -- for elaboration compared to vertex Compared_To. function Is_Better_Weakly_Elaborable_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; Compared_To : Library_Graph_Vertex_Id) return Precedence_Kind; pragma Inline (Is_Better_Weakly_Elaborable_Vertex); -- Determine whether vertex Vertex of library graph G is a better choice -- for weak elaboration compared to vertex Compared_To. function Is_Suitable_Elaborable_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id) return Boolean; pragma Inline (Is_Suitable_Elaborable_Vertex); -- Determine whether vertex Vertex of library graph G is suitable for -- elaboration. function Is_Suitable_Weakly_Elaborable_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id) return Boolean; pragma Inline (Is_Suitable_Weakly_Elaborable_Vertex); -- Determine whether vertex Vertex of library graph G is suitable for -- weak elaboration. procedure Set_Unit_Elaboration_Positions (Order : Unit_Id_Table); pragma Inline (Set_Unit_Elaboration_Positions); -- Set the ALI.Units positions of all elaboration units in order Order procedure Trace_Component (G : Library_Graph; Comp : Component_Id; Msg : String; Step : Elaboration_Order_Step); pragma Inline (Trace_Component); -- Write elaboration-related information for component Comp of library -- graph G to standard output, starting with message Msg. Step is the -- current step in the elaboration order. procedure Trace_Step (Step : Elaboration_Order_Step); pragma Inline (Trace_Step); -- Write current step Step of the elaboration order to standard output procedure Trace_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; Msg : String; Step : Elaboration_Order_Step; Indent : Indentation_Level); pragma Inline (Trace_Vertex); -- Write elaboration-related information for vertex Vertex of library -- graph G to standard output, starting with message Msg. Step is the -- current step in the elaboration order. Indent denotes the desired -- indentation level for tracing. procedure Trace_Vertices (G : Library_Graph; Set : LGV_Sets.Membership_Set; Set_Msg : String; Vertex_Msg : String; Step : Elaboration_Order_Step; Indent : Indentation_Level); pragma Inline (Trace_Vertices); -- Write the candidate vertices of library graph G present in membership -- set Set to standard output, starting with message Set_Msg. Vertex_Msg -- is the message emitted prior to each vertex. Step denotes the current -- step in the elaboration order. Indent denotes the desired indentation -- level for tracing. procedure Update_Successor (G : Library_Graph; Edge : Library_Graph_Edge_Id; All_Elaborable_Vertices : LGV_Sets.Membership_Set; All_Waiting_Vertices : LGV_Sets.Membership_Set; Comp_Elaborable_Vertices : LGV_Sets.Membership_Set; Comp_Waiting_Vertices : LGV_Sets.Membership_Set; Step : Elaboration_Order_Step; Indent : Indentation_Level); pragma Inline (Update_Successor); -- Notify the successor of edge Edge of library graph G along with its -- component that their predecessor has just been elaborated. This may -- cause new vertices to become elaborable. The sets contain vertices -- arranged as follows: -- -- * All_Elaborable_Vertices - all elaborable vertices in the library -- graph. -- -- * All_Waiting_Vertices - all vertices in the library graph that are -- waiting on predecessors to be elaborated. -- -- * Comp_Elaborable_Vertices - all elaborable vertices found in the -- component of Vertex. -- -- * Comp_Waiting_Vertices - all vertices found in the component of -- Vertex that are still waiting on predecessors to be elaborated. -- -- Step is the current step in the elaboration order. Indent denotes the -- desired indentation level for tracing. procedure Update_Successors (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; All_Elaborable_Vertices : LGV_Sets.Membership_Set; All_Waiting_Vertices : LGV_Sets.Membership_Set; Comp_Elaborable_Vertices : LGV_Sets.Membership_Set; Comp_Waiting_Vertices : LGV_Sets.Membership_Set; Step : Elaboration_Order_Step; Indent : Indentation_Level); pragma Inline (Update_Successors); -- Notify all successors of vertex Vertex of library graph G along with -- their components that their predecessor has just been elaborated. -- This may cause new vertices to become elaborable. The sets contain -- vertices arranged as follows: -- -- * All_Elaborable_Vertices - all elaborable vertices in the library -- graph. -- -- * All_Waiting_Vertices - all vertices in the library graph that are -- waiting on predecessors to be elaborated. -- -- * Comp_Elaborable_Vertices - all elaborable vertices found in the -- component of Vertex. -- -- * Comp_Waiting_Vertices - all vertices found in the component of -- Vertex that are still waiting on predecessors to be elaborated. -- -- Step is the current step in the elaboration order. Indent denotes the -- desired indentation level for tracing. ---------------------------------- -- Create_Component_Vertex_Sets -- ---------------------------------- procedure Create_Component_Vertex_Sets (G : Library_Graph; Comp : Component_Id; Elaborable_Vertices : out LGV_Sets.Membership_Set; Waiting_Vertices : out LGV_Sets.Membership_Set; Step : Elaboration_Order_Step) is pragma Assert (Present (G)); pragma Assert (Present (Comp)); Num_Of_Vertices : constant Natural := Number_Of_Component_Vertices (G, Comp); Iter : Component_Vertex_Iterator; Vertex : Library_Graph_Vertex_Id; begin Elaborable_Vertices := LGV_Sets.Create (Num_Of_Vertices); Waiting_Vertices := LGV_Sets.Create (Num_Of_Vertices); Iter := Iterate_Component_Vertices (G, Comp); while Has_Next (Iter) loop Next (Iter, Vertex); -- Add the vertex to the proper set depending on whether it can be -- elaborated. if Is_Elaborable_Vertex (G, Vertex) then Insert_Vertex (G => G, Vertex => Vertex, Set => Elaborable_Vertices, Msg => "add elaborable component vertex", Step => Step, Indent => No_Indentation); else Insert_Vertex (G => G, Vertex => Vertex, Set => Waiting_Vertices, Msg => "add waiting component vertex", Step => Step, Indent => No_Indentation); end if; end loop; end Create_Component_Vertex_Sets; ------------------------ -- Create_Vertex_Sets -- ------------------------ procedure Create_Vertex_Sets (G : Library_Graph; Elaborable_Vertices : out LGV_Sets.Membership_Set; Waiting_Vertices : out LGV_Sets.Membership_Set; Step : Elaboration_Order_Step) is pragma Assert (Present (G)); Num_Of_Vertices : constant Natural := Number_Of_Vertices (G); Iter : Library_Graphs.All_Vertex_Iterator; Vertex : Library_Graph_Vertex_Id; begin Elaborable_Vertices := LGV_Sets.Create (Num_Of_Vertices); Waiting_Vertices := LGV_Sets.Create (Num_Of_Vertices); Iter := Iterate_All_Vertices (G); while Has_Next (Iter) loop Next (Iter, Vertex); -- Add the vertex to the proper set depending on whether it can be -- elaborated. if Is_Elaborable_Vertex (G, Vertex) then Insert_Vertex (G => G, Vertex => Vertex, Set => Elaborable_Vertices, Msg => "add elaborable vertex", Step => Step, Indent => No_Indentation); else Insert_Vertex (G => G, Vertex => Vertex, Set => Waiting_Vertices, Msg => "add waiting vertex", Step => Step, Indent => No_Indentation); end if; end loop; end Create_Vertex_Sets; ------------------------- -- Elaborate_Component -- ------------------------- procedure Elaborate_Component (G : Library_Graph; Comp : Component_Id; All_Elaborable_Vertices : LGV_Sets.Membership_Set; All_Waiting_Vertices : LGV_Sets.Membership_Set; Order : in out Unit_Id_Table; Step : Elaboration_Order_Step) is Comp_Elaborable_Vertices : LGV_Sets.Membership_Set; Comp_Waiting_Vertices : LGV_Sets.Membership_Set; Vertex : Library_Graph_Vertex_Id; begin pragma Assert (Present (G)); pragma Assert (Present (Comp)); pragma Assert (LGV_Sets.Present (All_Elaborable_Vertices)); pragma Assert (LGV_Sets.Present (All_Waiting_Vertices)); Trace_Component (G => G, Comp => Comp, Msg => "elaborating component", Step => Step); -- Divide all vertices of the component into an elaborable and -- waiting vertex set. Create_Component_Vertex_Sets (G => G, Comp => Comp, Elaborable_Vertices => Comp_Elaborable_Vertices, Waiting_Vertices => Comp_Waiting_Vertices, Step => Step); loop Trace_Vertices (G => G, Set => Comp_Elaborable_Vertices, Set_Msg => "elaborable component vertices", Vertex_Msg => "elaborable component vertex", Step => Step, Indent => Nested_Indentation); Trace_Vertices (G => G, Set => Comp_Waiting_Vertices, Set_Msg => "waiting component vertices", Vertex_Msg => "waiting component vertex", Step => Step, Indent => Nested_Indentation); Vertex := Find_Best_Elaborable_Vertex (G => G, Set => Comp_Elaborable_Vertices, Step => Step, Indent => Nested_Indentation); -- The component lacks an elaborable vertex. This indicates that -- either all vertices of the component have been elaborated or -- the graph has a circularity. Locate the best weak vertex that -- was compiled with the dynamic model to elaborate from the set -- waiting vertices. This action assumes that certain invocations -- will not take place at elaboration time. An order produced in -- this fashion may fail an ABE check at run time. if not Present (Vertex) then Vertex := Find_Best_Weakly_Elaborable_Vertex (G => G, Set => Comp_Waiting_Vertices, Step => Step, Indent => Nested_Indentation); end if; -- Stop the elaboration when either all vertices of the component -- have been elaborated, or the graph contains a circularity. exit when not Present (Vertex); -- Try to elaborate as many vertices within the component as -- possible. Each successful elaboration signals the appropriate -- successors and components that they have one less predecessor -- to wait on. Elaborate_Vertex (G => G, Vertex => Vertex, All_Elaborable_Vertices => All_Elaborable_Vertices, All_Waiting_Vertices => All_Waiting_Vertices, Comp_Elaborable_Vertices => Comp_Elaborable_Vertices, Comp_Waiting_Vertices => Comp_Waiting_Vertices, Order => Order, Step => Step, Indent => Nested_Indentation); end loop; LGV_Sets.Destroy (Comp_Elaborable_Vertices); LGV_Sets.Destroy (Comp_Waiting_Vertices); end Elaborate_Component; ----------------------------- -- Elaborate_Library_Graph -- ----------------------------- procedure Elaborate_Library_Graph (G : Library_Graph; Order : out Unit_Id_Table; Status : out Elaboration_Order_Status) is Elaborable_Vertices : LGV_Sets.Membership_Set; Step : Elaboration_Order_Step; Vertex : Library_Graph_Vertex_Id; Waiting_Vertices : LGV_Sets.Membership_Set; begin pragma Assert (Present (G)); Step := Initial_Step; -- Divide all vertices of the library graph into an elaborable and -- waiting vertex set. Create_Vertex_Sets (G => G, Elaborable_Vertices => Elaborable_Vertices, Waiting_Vertices => Waiting_Vertices, Step => Step); loop Step := Step + 1; Trace_Vertices (G => G, Set => Elaborable_Vertices, Set_Msg => "elaborable vertices", Vertex_Msg => "elaborable vertex", Step => Step, Indent => No_Indentation); Trace_Vertices (G => G, Set => Waiting_Vertices, Set_Msg => "waiting vertices", Vertex_Msg => "waiting vertex", Step => Step, Indent => No_Indentation); Vertex := Find_Best_Elaborable_Vertex (G => G, Set => Elaborable_Vertices, Step => Step, Indent => No_Indentation); -- The graph lacks an elaborable vertex. This indicates that -- either all vertices have been elaborated or the graph has a -- circularity. Find the best weak vertex that was compiled with -- the dynamic model to elaborate from set of waiting vertices. -- This action assumes that certain invocations will not take -- place at elaboration time. An order produced in this fashion -- may fail an ABE check at run time. if not Present (Vertex) then Vertex := Find_Best_Weakly_Elaborable_Vertex (G => G, Set => Waiting_Vertices, Step => Step, Indent => No_Indentation); end if; -- Stop the elaboration when either all vertices of the graph have -- been elaborated, or the graph contains a circularity. exit when not Present (Vertex); -- Elaborate the component of the vertex by trying to elaborate as -- many vertices within the component as possible. Each successful -- elaboration signals the appropriate successors and components -- that they have one less predecessor to wait on. Elaborate_Component (G => G, Comp => Component (G, Vertex), All_Elaborable_Vertices => Elaborable_Vertices, All_Waiting_Vertices => Waiting_Vertices, Order => Order, Step => Step); end loop; -- The graph contains an Elaborate_All circularity when at least one -- edge subject to the related pragma appears in a component. if Has_Elaborate_All_Cycle (G) then Status := Order_Has_Elaborate_All_Circularity; -- The graph contains a circularity when at least one vertex failed -- to elaborate. elsif LGV_Sets.Size (Waiting_Vertices) /= 0 then Status := Order_Has_Circularity; -- Otherwise the elaboration order is satisfactory else Status := Order_OK; end if; LGV_Sets.Destroy (Elaborable_Vertices); LGV_Sets.Destroy (Waiting_Vertices); end Elaborate_Library_Graph; --------------------- -- Elaborate_Units -- --------------------- procedure Elaborate_Units (Order : out Unit_Id_Table; Main_Lib_File : File_Name_Type) is pragma Unreferenced (Main_Lib_File); Inv_Graph : Invocation_Graph; Lib_Graph : Library_Graph; Status : Elaboration_Order_Status; begin Start_Phase (Unit_Elaboration); -- Initialize all unit-related data structures and gather all units -- that need elaboration. Initialize_Units; Collect_Elaborable_Units; -- Create the library graph that captures the dependencies between -- library items. Lib_Graph := Build_Library_Graph; -- Create the invocation graph that represents the flow of execution Inv_Graph := Build_Invocation_Graph (Lib_Graph); -- Traverse the invocation graph starting from elaboration code in -- order to discover transitions of the execution flow from a unit -- to a unit that result in extra edges within the library graph. Augment_Library_Graph (Inv_Graph); -- Create the component graph by collapsing all library items into -- library units and traversing the library graph. Find_Components (Lib_Graph); -- Output the contents of the ALI tables and both graphs to standard -- output now that they have been fully decorated. Write_ALI_Tables; Write_Invocation_Graph (Inv_Graph); Write_Library_Graph (Lib_Graph); -- Traverse the library graph to determine the elaboration order of -- units. Elaborate_Library_Graph (Lib_Graph, Order, Status); -- The elaboration order is satisfactory if Status = Order_OK then Validate_Elaboration_Order (Order); -- Set attribute Elab_Position of table ALI.Units for all units in -- the elaboration order. Set_Unit_Elaboration_Positions (Order); -- Output the dependencies among units when switch -e (output -- complete list of elaboration order dependencies) is active. Write_Dependencies (Lib_Graph); -- Output the elaboration order when switch -l (output chosen -- elaboration order) is in effect. Write_Elaboration_Order (Order); -- Output the sources referenced in the closure of the order when -- switch -R (list sources referenced in closure) is in effect. Write_Unit_Closure (Order); -- Otherwise the library graph contains at least one circularity else Diagnose_Circularities (Inv_Graph); end if; Destroy (Inv_Graph); Destroy (Lib_Graph); -- Destroy all unit-related data structures Finalize_Units; End_Phase (Unit_Elaboration); -- Halt the bind when there is no satisfactory elaboration order if Status /= Order_OK then raise Unrecoverable_Error; end if; end Elaborate_Units; ---------------------- -- Elaborate_Vertex -- ---------------------- procedure Elaborate_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; All_Elaborable_Vertices : LGV_Sets.Membership_Set; All_Waiting_Vertices : LGV_Sets.Membership_Set; Comp_Elaborable_Vertices : LGV_Sets.Membership_Set; Comp_Waiting_Vertices : LGV_Sets.Membership_Set; Order : in out Unit_Id_Table; Step : Elaboration_Order_Step; Indent : Indentation_Level) is begin pragma Assert (Present (G)); pragma Assert (Present (Vertex)); pragma Assert (Needs_Elaboration (G, Vertex)); pragma Assert (LGV_Sets.Present (All_Elaborable_Vertices)); pragma Assert (LGV_Sets.Present (All_Waiting_Vertices)); pragma Assert (LGV_Sets.Present (Comp_Elaborable_Vertices)); pragma Assert (LGV_Sets.Present (Comp_Waiting_Vertices)); Trace_Vertex (G => G, Vertex => Vertex, Msg => "elaborating vertex", Step => Step, Indent => Indent); -- Remove the vertex from both elaborable sets. This is needed when -- the vertex is both an overall best candidate among all vertices, -- and the best candidate within the component. LGV_Sets.Delete (All_Elaborable_Vertices, Vertex); LGV_Sets.Delete (Comp_Elaborable_Vertices, Vertex); -- Remove the vertex from both waiting sets. This is needed when a -- weakly elaborable vertex is both an overall best candidate among -- all waiting vertices and the best waiting candidate within the -- component. LGV_Sets.Delete (All_Waiting_Vertices, Vertex); LGV_Sets.Delete (Comp_Waiting_Vertices, Vertex); -- Mark the vertex as elaborated in order to prevent further attempts -- to re-elaborate it. Set_In_Elaboration_Order (G, Vertex); -- Add the unit represented by the vertex to the elaboration order Unit_Id_Tables.Append (Order, Unit (G, Vertex)); -- Notify all successors and their components that they have one -- fewer predecessor to wait on. This may cause some successors to -- be included in one of the sets. Update_Successors (G => G, Vertex => Vertex, All_Elaborable_Vertices => All_Elaborable_Vertices, All_Waiting_Vertices => All_Waiting_Vertices, Comp_Elaborable_Vertices => Comp_Elaborable_Vertices, Comp_Waiting_Vertices => Comp_Waiting_Vertices, Step => Step, Indent => Indent + Nested_Indentation); -- Elaborate an eligible completing body immediately after its spec. -- This action satisfies the semantics of pragma Elaborate_Body. In -- addition, it ensures that a body will not "drift" too far from its -- spec in case invocation edges are removed from the library graph. if Has_Elaborable_Body (G, Vertex) then Elaborate_Vertex (G => G, Vertex => Proper_Body (G, Vertex), All_Elaborable_Vertices => All_Elaborable_Vertices, All_Waiting_Vertices => All_Waiting_Vertices, Comp_Elaborable_Vertices => Comp_Elaborable_Vertices, Comp_Waiting_Vertices => Comp_Waiting_Vertices, Order => Order, Step => Step, Indent => Indent); end if; end Elaborate_Vertex; --------------------------------- -- Find_Best_Elaborable_Vertex -- --------------------------------- function Find_Best_Elaborable_Vertex (G : Library_Graph; Set : LGV_Sets.Membership_Set; Step : Elaboration_Order_Step; Indent : Indentation_Level) return Library_Graph_Vertex_Id is begin pragma Assert (Present (G)); pragma Assert (LGV_Sets.Present (Set)); return Find_Best_Vertex (G => G, Set => Set, Is_Suitable_Vertex => Is_Suitable_Elaborable_Vertex'Access, Compare_Vertices => Is_Better_Elaborable_Vertex'Access, Initial_Best_Msg => "initial best elaborable vertex", Subsequent_Best_Msg => "better elaborable vertex", Step => Step, Indent => Indent); end Find_Best_Elaborable_Vertex; ---------------------- -- Find_Best_Vertex -- ---------------------- function Find_Best_Vertex (G : Library_Graph; Set : LGV_Sets.Membership_Set; Is_Suitable_Vertex : LGV_Predicate_Ptr; Compare_Vertices : LGV_Comparator_Ptr; Initial_Best_Msg : String; Subsequent_Best_Msg : String; Step : Elaboration_Order_Step; Indent : Indentation_Level) return Library_Graph_Vertex_Id is Best_Vertex : Library_Graph_Vertex_Id; Current_Vertex : Library_Graph_Vertex_Id; Iter : LGV_Sets.Iterator; begin pragma Assert (Present (G)); pragma Assert (LGV_Sets.Present (Set)); pragma Assert (Is_Suitable_Vertex /= null); pragma Assert (Compare_Vertices /= null); -- Assume that there is no candidate Best_Vertex := No_Library_Graph_Vertex; -- Inspect all vertices in the set, looking for the best candidate -- according to the comparator. Iter := LGV_Sets.Iterate (Set); while LGV_Sets.Has_Next (Iter) loop LGV_Sets.Next (Iter, Current_Vertex); pragma Assert (Needs_Elaboration (G, Current_Vertex)); if Is_Suitable_Vertex.all (G, Current_Vertex) then -- A previous iteration already picked the best candidate. -- Update the best candidate when the current vertex is a -- better choice. if Present (Best_Vertex) then if Compare_Vertices.all (G => G, Vertex => Current_Vertex, Compared_To => Best_Vertex) = Higher_Precedence then Best_Vertex := Current_Vertex; Trace_Vertex (G => G, Vertex => Best_Vertex, Msg => Subsequent_Best_Msg, Step => Step, Indent => Indent); end if; -- Otherwise this is the first candidate else Best_Vertex := Current_Vertex; Trace_Vertex (G => G, Vertex => Best_Vertex, Msg => Initial_Best_Msg, Step => Step, Indent => Indent); end if; end if; end loop; return Best_Vertex; end Find_Best_Vertex; ---------------------------------------- -- Find_Best_Weakly_Elaborable_Vertex -- ---------------------------------------- function Find_Best_Weakly_Elaborable_Vertex (G : Library_Graph; Set : LGV_Sets.Membership_Set; Step : Elaboration_Order_Step; Indent : Indentation_Level) return Library_Graph_Vertex_Id is begin pragma Assert (Present (G)); pragma Assert (LGV_Sets.Present (Set)); return Find_Best_Vertex (G => G, Set => Set, Is_Suitable_Vertex => Is_Suitable_Weakly_Elaborable_Vertex'Access, Compare_Vertices => Is_Better_Weakly_Elaborable_Vertex'Access, Initial_Best_Msg => "initial best weakly elaborable vertex", Subsequent_Best_Msg => "better weakly elaborable vertex", Step => Step, Indent => Indent); end Find_Best_Weakly_Elaborable_Vertex; ------------------------- -- Has_Elaborable_Body -- ------------------------- function Has_Elaborable_Body (G : Library_Graph; Vertex : Library_Graph_Vertex_Id) return Boolean is begin pragma Assert (Present (G)); pragma Assert (Present (Vertex)); -- The body of an already-elaborated spec subject to Elaborate_Body -- is always elaborable. if Is_Spec_With_Elaborate_Body (G, Vertex) then return True; elsif Is_Spec_With_Body (G, Vertex) then return Is_Elaborable_Vertex (G, Proper_Body (G, Vertex)); end if; return False; end Has_Elaborable_Body; --------------------------------- -- Insert_Elaborable_Successor -- --------------------------------- procedure Insert_Elaborable_Successor (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; Elaborable_Vertices : LGV_Sets.Membership_Set; All_Waiting_Vertices : LGV_Sets.Membership_Set; Comp_Waiting_Vertices : LGV_Sets.Membership_Set; Msg : String; Step : Elaboration_Order_Step; Indent : Indentation_Level) is pragma Assert (Present (G)); pragma Assert (Present (Vertex)); pragma Assert (LGV_Sets.Present (Elaborable_Vertices)); pragma Assert (LGV_Sets.Present (All_Waiting_Vertices)); pragma Assert (LGV_Sets.Present (Comp_Waiting_Vertices)); Complement : constant Library_Graph_Vertex_Id := Complementary_Vertex (G => G, Vertex => Vertex, Force_Complement => False); begin -- Remove the successor from both waiting vertex sets because it may -- be the best vertex to elaborate across the whole graph and within -- its component. LGV_Sets.Delete (All_Waiting_Vertices, Vertex); LGV_Sets.Delete (Comp_Waiting_Vertices, Vertex); Insert_Vertex (G => G, Vertex => Vertex, Set => Elaborable_Vertices, Msg => Msg, Step => Step, Indent => Indent); if Present (Complement) then -- Remove the complement of the successor from both waiting vertex -- sets because it may be the best vertex to elaborate across the -- whole graph and within its component. LGV_Sets.Delete (All_Waiting_Vertices, Complement); LGV_Sets.Delete (Comp_Waiting_Vertices, Complement); Insert_Vertex (G => G, Vertex => Complement, Set => Elaborable_Vertices, Msg => Msg, Step => Step, Indent => Indent); end if; end Insert_Elaborable_Successor; ------------------- -- Insert_Vertex -- ------------------- procedure Insert_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; Set : LGV_Sets.Membership_Set; Msg : String; Step : Elaboration_Order_Step; Indent : Indentation_Level) is begin pragma Assert (Present (G)); pragma Assert (Present (Vertex)); pragma Assert (Needs_Elaboration (G, Vertex)); pragma Assert (LGV_Sets.Present (Set)); -- Nothing to do when the vertex is already present in the set if LGV_Sets.Contains (Set, Vertex) then return; end if; Trace_Vertex (G => G, Vertex => Vertex, Msg => Msg, Step => Step, Indent => Indent); -- Add the vertex to the set LGV_Sets.Insert (Set, Vertex); end Insert_Vertex; --------------------------------- -- Is_Better_Elaborable_Vertex -- --------------------------------- function Is_Better_Elaborable_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; Compared_To : Library_Graph_Vertex_Id) return Precedence_Kind is begin pragma Assert (Present (G)); pragma Assert (Present (Vertex)); pragma Assert (Present (Compared_To)); -- Prefer a spec with Elaborate_Body over its corresponding body if Is_Elaborate_Body_Pair (G => G, Spec_Vertex => Vertex, Body_Vertex => Compared_To) then return Higher_Precedence; elsif Is_Elaborate_Body_Pair (G => G, Spec_Vertex => Compared_To, Body_Vertex => Vertex) then return Lower_Precedence; -- Prefer a predefined unit over a non-predefined unit elsif Is_Predefined_Unit (G, Vertex) and then not Is_Predefined_Unit (G, Compared_To) then return Higher_Precedence; elsif not Is_Predefined_Unit (G, Vertex) and then Is_Predefined_Unit (G, Compared_To) then return Lower_Precedence; -- Prefer an internal unit over a non-internal unit elsif Is_Internal_Unit (G, Vertex) and then not Is_Internal_Unit (G, Compared_To) then return Higher_Precedence; elsif not Is_Internal_Unit (G, Vertex) and then Is_Internal_Unit (G, Compared_To) then return Lower_Precedence; -- Prefer a preelaborated unit over a non-preelaborated unit elsif Is_Preelaborated_Unit (G, Vertex) and then not Is_Preelaborated_Unit (G, Compared_To) then return Higher_Precedence; elsif not Is_Preelaborated_Unit (G, Vertex) and then Is_Preelaborated_Unit (G, Compared_To) then return Lower_Precedence; -- Otherwise default to lexicographical order to ensure deterministic -- behavior. elsif Uname_Less (Name (G, Vertex), Name (G, Compared_To)) then return Higher_Precedence; else return Lower_Precedence; end if; end Is_Better_Elaborable_Vertex; ---------------------------------------- -- Is_Better_Weakly_Elaborable_Vertex -- ---------------------------------------- function Is_Better_Weakly_Elaborable_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; Compared_To : Library_Graph_Vertex_Id) return Precedence_Kind is Comp_Strong_Preds : Natural; Comp_Weak_Preds : Natural; Vertex_Strong_Preds : Natural; Vertex_Weak_Preds : Natural; begin pragma Assert (Present (G)); pragma Assert (Present (Vertex)); pragma Assert (Present (Compared_To)); -- Obtain the number of pending predecessors for both candidates, -- taking into account Elaborate_Body pairs. Pending_Predecessors_For_Elaboration (G => G, Vertex => Vertex, Strong_Preds => Vertex_Strong_Preds, Weak_Preds => Vertex_Weak_Preds); Pending_Predecessors_For_Elaboration (G => G, Vertex => Compared_To, Strong_Preds => Comp_Strong_Preds, Weak_Preds => Comp_Weak_Preds); -- Neither candidate should be waiting on strong predecessors, -- otherwise the candidate cannot be weakly elaborated. pragma Assert (Vertex_Strong_Preds = 0); pragma Assert (Comp_Strong_Preds = 0); -- Prefer a unit with fewer weak predecessors over a unit with more -- weak predecessors. if Vertex_Weak_Preds < Comp_Weak_Preds then return Higher_Precedence; elsif Vertex_Weak_Preds > Comp_Weak_Preds then return Lower_Precedence; -- Otherwise default to lexicographical order to ensure deterministic -- behavior. elsif Uname_Less (Name (G, Vertex), Name (G, Compared_To)) then return Higher_Precedence; else return Lower_Precedence; end if; end Is_Better_Weakly_Elaborable_Vertex; ----------------------------------- -- Is_Suitable_Elaborable_Vertex -- ----------------------------------- function Is_Suitable_Elaborable_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id) return Boolean is begin pragma Assert (Present (G)); pragma Assert (Present (Vertex)); -- A vertex is suitable for elaboration as long it is not waiting on -- any predecessors, ignoring the static or dynamic model. return Is_Elaborable_Vertex (G, Vertex); end Is_Suitable_Elaborable_Vertex; ------------------------------------------ -- Is_Suitable_Weakly_Elaborable_Vertex -- ------------------------------------------ function Is_Suitable_Weakly_Elaborable_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id) return Boolean is begin pragma Assert (Present (G)); pragma Assert (Present (Vertex)); -- A vertex is suitable for weak elaboration when it is waiting on -- weak predecessors only, and the unit it represents was compiled -- using the dynamic model. return Is_Dynamically_Elaborated (G, Vertex) and then Is_Weakly_Elaborable_Vertex (G, Vertex); end Is_Suitable_Weakly_Elaborable_Vertex; ------------------------------------ -- Set_Unit_Elaboration_Positions -- ------------------------------------ procedure Set_Unit_Elaboration_Positions (Order : Unit_Id_Table) is U_Id : Unit_Id; begin for Position in Unit_Id_Tables.First .. Unit_Id_Tables.Last (Order) loop U_Id := Order.Table (Position); ALI.Units.Table (U_Id).Elab_Position := Position; end loop; end Set_Unit_Elaboration_Positions; --------------------- -- Trace_Component -- --------------------- procedure Trace_Component (G : Library_Graph; Comp : Component_Id; Msg : String; Step : Elaboration_Order_Step) is begin pragma Assert (Present (G)); pragma Assert (Present (Comp)); -- Nothing to do when switch -d_T (output elaboration order and cycle -- detection trace information) is not in effect. if not Debug_Flag_Underscore_TT then return; end if; Trace_Step (Step); Write_Str (Msg); Write_Str (" (Comp_Id_"); Write_Int (Int (Comp)); Write_Str (")"); Write_Eol; Trace_Step (Step); Indent_By (Nested_Indentation); Write_Str ("pending strong predecessors: "); Write_Num (Int (Pending_Strong_Predecessors (G, Comp))); Write_Eol; Trace_Step (Step); Indent_By (Nested_Indentation); Write_Str ("pending weak predecessors : "); Write_Num (Int (Pending_Weak_Predecessors (G, Comp))); Write_Eol; end Trace_Component; ---------------- -- Trace_Step -- ---------------- procedure Trace_Step (Step : Elaboration_Order_Step) is begin -- Nothing to do when switch -d_T (output elaboration order and cycle -- detection trace information) is not in effect. if not Debug_Flag_Underscore_TT then return; end if; Write_Num (Val => Int (Step), Val_Indent => Step_Column); Write_Str (": "); end Trace_Step; ------------------ -- Trace_Vertex -- ------------------ procedure Trace_Vertex (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; Msg : String; Step : Elaboration_Order_Step; Indent : Indentation_Level) is pragma Assert (Present (G)); pragma Assert (Present (Vertex)); Attr_Indent : constant Indentation_Level := Indent + Nested_Indentation; Comp : constant Component_Id := Component (G, Vertex); begin -- Nothing to do when switch -d_T (output elaboration order and cycle -- detection trace information) is not in effect. if not Debug_Flag_Underscore_TT then return; end if; Trace_Step (Step); Indent_By (Indent); Write_Str (Msg); Write_Str (" (LGV_Id_"); Write_Int (Int (Vertex)); Write_Str (")"); Write_Eol; Trace_Step (Step); Indent_By (Attr_Indent); Write_Str ("name = "); Write_Name (Name (G, Vertex)); Write_Eol; Trace_Step (Step); Indent_By (Attr_Indent); Write_Str ("Component (Comp_Id_"); Write_Int (Int (Comp)); Write_Str (")"); Write_Eol; Trace_Step (Step); Indent_By (Attr_Indent); Write_Str ("pending strong predecessors: "); Write_Num (Int (Pending_Strong_Predecessors (G, Vertex))); Write_Eol; Trace_Step (Step); Indent_By (Attr_Indent); Write_Str ("pending weak predecessors : "); Write_Num (Int (Pending_Weak_Predecessors (G, Vertex))); Write_Eol; Trace_Step (Step); Indent_By (Attr_Indent); Write_Str ("pending strong components : "); Write_Num (Int (Pending_Strong_Predecessors (G, Comp))); Write_Eol; Trace_Step (Step); Indent_By (Attr_Indent); Write_Str ("pending weak components : "); Write_Num (Int (Pending_Weak_Predecessors (G, Comp))); Write_Eol; end Trace_Vertex; -------------------- -- Trace_Vertices -- -------------------- procedure Trace_Vertices (G : Library_Graph; Set : LGV_Sets.Membership_Set; Set_Msg : String; Vertex_Msg : String; Step : Elaboration_Order_Step; Indent : Indentation_Level) is Vertex_Indent : constant Indentation_Level := Indent + Nested_Indentation; Iter : LGV_Sets.Iterator; Vertex : Library_Graph_Vertex_Id; begin pragma Assert (Present (G)); pragma Assert (LGV_Sets.Present (Set)); -- Nothing to do when switch -d_T (output elaboration order and cycle -- detection trace information) is not in effect. if not Debug_Flag_Underscore_TT then return; end if; Trace_Step (Step); Indent_By (Indent); Write_Str (Set_Msg); Write_Str (": "); Write_Int (Int (LGV_Sets.Size (Set))); Write_Eol; Iter := LGV_Sets.Iterate (Set); while LGV_Sets.Has_Next (Iter) loop LGV_Sets.Next (Iter, Vertex); Trace_Vertex (G => G, Vertex => Vertex, Msg => Vertex_Msg, Step => Step, Indent => Vertex_Indent); end loop; end Trace_Vertices; ---------------------- -- Update_Successor -- ---------------------- procedure Update_Successor (G : Library_Graph; Edge : Library_Graph_Edge_Id; All_Elaborable_Vertices : LGV_Sets.Membership_Set; All_Waiting_Vertices : LGV_Sets.Membership_Set; Comp_Elaborable_Vertices : LGV_Sets.Membership_Set; Comp_Waiting_Vertices : LGV_Sets.Membership_Set; Step : Elaboration_Order_Step; Indent : Indentation_Level) is pragma Assert (Present (G)); pragma Assert (Present (Edge)); pragma Assert (LGV_Sets.Present (All_Elaborable_Vertices)); pragma Assert (LGV_Sets.Present (All_Waiting_Vertices)); pragma Assert (LGV_Sets.Present (Comp_Elaborable_Vertices)); pragma Assert (LGV_Sets.Present (Comp_Waiting_Vertices)); Pred : constant Library_Graph_Vertex_Id := Predecessor (G, Edge); Succ : constant Library_Graph_Vertex_Id := Successor (G, Edge); pragma Assert (Needs_Elaboration (G, Pred)); pragma Assert (Needs_Elaboration (G, Succ)); In_Different_Components : constant Boolean := not In_Same_Component (G => G, Left => Pred, Right => Succ); Succ_Comp : constant Component_Id := Component (G, Succ); Vertex_Indent : constant Indentation_Level := Indent + Nested_Indentation; Iter : Component_Vertex_Iterator; Vertex : Library_Graph_Vertex_Id; begin Trace_Vertex (G => G, Vertex => Succ, Msg => "updating successor", Step => Step, Indent => Indent); -- Notify the successor that it has one less predecessor to wait on. -- This effectively eliminates the edge that links the two. Decrement_Pending_Predecessors (G => G, Vertex => Succ, Edge => Edge); -- The predecessor and successor reside in different components. -- Notify the successor component it has one fewer components to -- wait on. if In_Different_Components then Decrement_Pending_Predecessors (G => G, Comp => Succ_Comp, Edge => Edge); end if; -- At this point the successor may become elaborable when its final -- predecessor or final predecessor component has been elaborated. if Is_Elaborable_Vertex (G, Succ) then -- The predecessor and successor reside in different components. -- The successor must not be added to the candidates of Pred's -- component because this will mix units from the two components. -- Instead, the successor is added to the set of all elaborable -- vertices. if In_Different_Components then Insert_Elaborable_Successor (G => G, Vertex => Succ, Elaborable_Vertices => All_Elaborable_Vertices, All_Waiting_Vertices => All_Waiting_Vertices, Comp_Waiting_Vertices => Comp_Waiting_Vertices, Msg => "add elaborable successor", Step => Step, Indent => Vertex_Indent); -- Otherwise the predecessor and successor reside within the same -- component. Pred's component gains another elaborable vertex. else Insert_Elaborable_Successor (G => G, Vertex => Succ, Elaborable_Vertices => Comp_Elaborable_Vertices, All_Waiting_Vertices => All_Waiting_Vertices, Comp_Waiting_Vertices => Comp_Waiting_Vertices, Msg => "add elaborable component successor", Step => Step, Indent => Vertex_Indent); end if; end if; -- At this point the successor component may become elaborable when -- its final predecessor component is elaborated. This in turn may -- allow vertices of the successor component to be elaborated. if In_Different_Components and then Is_Elaborable_Component (G, Succ_Comp) then Iter := Iterate_Component_Vertices (G, Succ_Comp); while Has_Next (Iter) loop Next (Iter, Vertex); if Is_Elaborable_Vertex (G, Vertex) then Insert_Elaborable_Successor (G => G, Vertex => Vertex, Elaborable_Vertices => All_Elaborable_Vertices, All_Waiting_Vertices => All_Waiting_Vertices, Comp_Waiting_Vertices => Comp_Waiting_Vertices, Msg => "add elaborable vertex", Step => Step, Indent => Vertex_Indent); end if; end loop; end if; end Update_Successor; ----------------------- -- Update_Successors -- ----------------------- procedure Update_Successors (G : Library_Graph; Vertex : Library_Graph_Vertex_Id; All_Elaborable_Vertices : LGV_Sets.Membership_Set; All_Waiting_Vertices : LGV_Sets.Membership_Set; Comp_Elaborable_Vertices : LGV_Sets.Membership_Set; Comp_Waiting_Vertices : LGV_Sets.Membership_Set; Step : Elaboration_Order_Step; Indent : Indentation_Level) is Edge : Library_Graph_Edge_Id; Iter : Edges_To_Successors_Iterator; begin pragma Assert (Present (G)); pragma Assert (Present (Vertex)); pragma Assert (Needs_Elaboration (G, Vertex)); pragma Assert (LGV_Sets.Present (All_Elaborable_Vertices)); pragma Assert (LGV_Sets.Present (All_Waiting_Vertices)); pragma Assert (LGV_Sets.Present (Comp_Elaborable_Vertices)); pragma Assert (LGV_Sets.Present (Comp_Waiting_Vertices)); Iter := Iterate_Edges_To_Successors (G, Vertex); while Has_Next (Iter) loop Next (Iter, Edge); pragma Assert (Predecessor (G, Edge) = Vertex); Update_Successor (G => G, Edge => Edge, All_Elaborable_Vertices => All_Elaborable_Vertices, All_Waiting_Vertices => All_Waiting_Vertices, Comp_Elaborable_Vertices => Comp_Elaborable_Vertices, Comp_Waiting_Vertices => Comp_Waiting_Vertices, Step => Step, Indent => Indent); end loop; end Update_Successors; end Invocation_And_Library_Graph_Elaborators; end Bindo.Elaborators;
pragma License (Unrestricted); -- BSD 3-Clause -- translated unit from SFMT (SFMT-params216091.h) with Ada.Numerics.SFMT; package Ada.Numerics.SFMT_216091 is new SFMT ( MEXP => 216091, POS1 => 627, SL1 => 11, SL2 => 3, SR1 => 10, SR2 => 1, MSK1 => 16#bff7bff7#, MSK2 => 16#bfffffff#, MSK3 => 16#bffffa7f#, MSK4 => 16#ffddfbfb#, PARITY1 => 16#f8000001#, PARITY2 => 16#89e80709#, PARITY3 => 16#3bd2b64b#, PARITY4 => 16#0c64b1e4#); -- The largest periods. pragma Preelaborate (Ada.Numerics.SFMT_216091);
generic type Element_Type is private; Zero : Element_Type; with function "-" (Left, Right : in Element_Type) return Element_Type is <>; with function "*" (Left, Right : in Element_Type) return Element_Type is <>; with function "/" (Left, Right : in Element_Type) return Element_Type is <>; package Matrices is type Matrix is array (Positive range <>, Positive range <>) of Element_Type; function Reduced_Row_Echelon_form (Source : Matrix) return Matrix; end Matrices;
-- This spec has been automatically generated from STM32F303xE.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with System; package STM32_SVD.DBGMCU is pragma Preelaborate; --------------- -- Registers -- --------------- subtype IDCODE_DEV_ID_Field is STM32_SVD.UInt12; subtype IDCODE_REV_ID_Field is STM32_SVD.UInt16; -- MCU Device ID Code Register type IDCODE_Register is record -- Read-only. Device Identifier DEV_ID : IDCODE_DEV_ID_Field; -- unspecified Reserved_12_15 : STM32_SVD.UInt4; -- Read-only. Revision Identifier REV_ID : IDCODE_REV_ID_Field; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for IDCODE_Register use record DEV_ID at 0 range 0 .. 11; Reserved_12_15 at 0 range 12 .. 15; REV_ID at 0 range 16 .. 31; end record; subtype CR_DBG_SLEEP_Field is STM32_SVD.Bit; subtype CR_DBG_STOP_Field is STM32_SVD.Bit; subtype CR_DBG_STANDBY_Field is STM32_SVD.Bit; subtype CR_TRACE_IOEN_Field is STM32_SVD.Bit; subtype CR_TRACE_MODE_Field is STM32_SVD.UInt2; -- Debug MCU Configuration Register type CR_Register is record -- Debug Sleep mode DBG_SLEEP : CR_DBG_SLEEP_Field := 16#0#; -- Debug Stop Mode DBG_STOP : CR_DBG_STOP_Field := 16#0#; -- Debug Standby Mode DBG_STANDBY : CR_DBG_STANDBY_Field := 16#0#; -- unspecified Reserved_3_4 : STM32_SVD.UInt2 := 16#0#; -- Trace pin assignment control TRACE_IOEN : CR_TRACE_IOEN_Field := 16#0#; -- Trace pin assignment control TRACE_MODE : CR_TRACE_MODE_Field := 16#0#; -- unspecified Reserved_8_31 : STM32_SVD.UInt24 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record DBG_SLEEP at 0 range 0 .. 0; DBG_STOP at 0 range 1 .. 1; DBG_STANDBY at 0 range 2 .. 2; Reserved_3_4 at 0 range 3 .. 4; TRACE_IOEN at 0 range 5 .. 5; TRACE_MODE at 0 range 6 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype APB1FZ_DBG_TIM2_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_TIM3_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_TIM4_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_TIM5_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_TIM6_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_TIM7_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_TIM12_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_TIM13_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_TIMER14_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_TIM18_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_RTC_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_WWDG_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_IWDG_STOP_Field is STM32_SVD.Bit; subtype APB1FZ_I2C1_SMBUS_TIMEOUT_Field is STM32_SVD.Bit; subtype APB1FZ_I2C2_SMBUS_TIMEOUT_Field is STM32_SVD.Bit; subtype APB1FZ_DBG_CAN_STOP_Field is STM32_SVD.Bit; -- APB Low Freeze Register type APB1FZ_Register is record -- Debug Timer 2 stopped when Core is halted DBG_TIM2_STOP : APB1FZ_DBG_TIM2_STOP_Field := 16#0#; -- Debug Timer 3 stopped when Core is halted DBG_TIM3_STOP : APB1FZ_DBG_TIM3_STOP_Field := 16#0#; -- Debug Timer 4 stopped when Core is halted DBG_TIM4_STOP : APB1FZ_DBG_TIM4_STOP_Field := 16#0#; -- Debug Timer 5 stopped when Core is halted DBG_TIM5_STOP : APB1FZ_DBG_TIM5_STOP_Field := 16#0#; -- Debug Timer 6 stopped when Core is halted DBG_TIM6_STOP : APB1FZ_DBG_TIM6_STOP_Field := 16#0#; -- Debug Timer 7 stopped when Core is halted DBG_TIM7_STOP : APB1FZ_DBG_TIM7_STOP_Field := 16#0#; -- Debug Timer 12 stopped when Core is halted DBG_TIM12_STOP : APB1FZ_DBG_TIM12_STOP_Field := 16#0#; -- Debug Timer 13 stopped when Core is halted DBG_TIM13_STOP : APB1FZ_DBG_TIM13_STOP_Field := 16#0#; -- Debug Timer 14 stopped when Core is halted DBG_TIMER14_STOP : APB1FZ_DBG_TIMER14_STOP_Field := 16#0#; -- Debug Timer 18 stopped when Core is halted DBG_TIM18_STOP : APB1FZ_DBG_TIM18_STOP_Field := 16#0#; -- Debug RTC stopped when Core is halted DBG_RTC_STOP : APB1FZ_DBG_RTC_STOP_Field := 16#0#; -- Debug Window Wachdog stopped when Core is halted DBG_WWDG_STOP : APB1FZ_DBG_WWDG_STOP_Field := 16#0#; -- Debug Independent Wachdog stopped when Core is halted DBG_IWDG_STOP : APB1FZ_DBG_IWDG_STOP_Field := 16#0#; -- unspecified Reserved_13_20 : STM32_SVD.Byte := 16#0#; -- SMBUS timeout mode stopped when Core is halted I2C1_SMBUS_TIMEOUT : APB1FZ_I2C1_SMBUS_TIMEOUT_Field := 16#0#; -- SMBUS timeout mode stopped when Core is halted I2C2_SMBUS_TIMEOUT : APB1FZ_I2C2_SMBUS_TIMEOUT_Field := 16#0#; -- unspecified Reserved_23_24 : STM32_SVD.UInt2 := 16#0#; -- Debug CAN stopped when core is halted DBG_CAN_STOP : APB1FZ_DBG_CAN_STOP_Field := 16#0#; -- unspecified Reserved_26_31 : STM32_SVD.UInt6 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for APB1FZ_Register use record DBG_TIM2_STOP at 0 range 0 .. 0; DBG_TIM3_STOP at 0 range 1 .. 1; DBG_TIM4_STOP at 0 range 2 .. 2; DBG_TIM5_STOP at 0 range 3 .. 3; DBG_TIM6_STOP at 0 range 4 .. 4; DBG_TIM7_STOP at 0 range 5 .. 5; DBG_TIM12_STOP at 0 range 6 .. 6; DBG_TIM13_STOP at 0 range 7 .. 7; DBG_TIMER14_STOP at 0 range 8 .. 8; DBG_TIM18_STOP at 0 range 9 .. 9; DBG_RTC_STOP at 0 range 10 .. 10; DBG_WWDG_STOP at 0 range 11 .. 11; DBG_IWDG_STOP at 0 range 12 .. 12; Reserved_13_20 at 0 range 13 .. 20; I2C1_SMBUS_TIMEOUT at 0 range 21 .. 21; I2C2_SMBUS_TIMEOUT at 0 range 22 .. 22; Reserved_23_24 at 0 range 23 .. 24; DBG_CAN_STOP at 0 range 25 .. 25; Reserved_26_31 at 0 range 26 .. 31; end record; subtype APB2FZ_DBG_TIM15_STOP_Field is STM32_SVD.Bit; subtype APB2FZ_DBG_TIM16_STOP_Field is STM32_SVD.Bit; subtype APB2FZ_DBG_TIM17_STO_Field is STM32_SVD.Bit; subtype APB2FZ_DBG_TIM19_STOP_Field is STM32_SVD.Bit; -- APB High Freeze Register type APB2FZ_Register is record -- unspecified Reserved_0_1 : STM32_SVD.UInt2 := 16#0#; -- Debug Timer 15 stopped when Core is halted DBG_TIM15_STOP : APB2FZ_DBG_TIM15_STOP_Field := 16#0#; -- Debug Timer 16 stopped when Core is halted DBG_TIM16_STOP : APB2FZ_DBG_TIM16_STOP_Field := 16#0#; -- Debug Timer 17 stopped when Core is halted DBG_TIM17_STO : APB2FZ_DBG_TIM17_STO_Field := 16#0#; -- Debug Timer 19 stopped when Core is halted DBG_TIM19_STOP : APB2FZ_DBG_TIM19_STOP_Field := 16#0#; -- unspecified Reserved_6_31 : STM32_SVD.UInt26 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for APB2FZ_Register use record Reserved_0_1 at 0 range 0 .. 1; DBG_TIM15_STOP at 0 range 2 .. 2; DBG_TIM16_STOP at 0 range 3 .. 3; DBG_TIM17_STO at 0 range 4 .. 4; DBG_TIM19_STOP at 0 range 5 .. 5; Reserved_6_31 at 0 range 6 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Debug support type DBGMCU_Peripheral is record -- MCU Device ID Code Register IDCODE : aliased IDCODE_Register; -- Debug MCU Configuration Register CR : aliased CR_Register; -- APB Low Freeze Register APB1FZ : aliased APB1FZ_Register; -- APB High Freeze Register APB2FZ : aliased APB2FZ_Register; end record with Volatile; for DBGMCU_Peripheral use record IDCODE at 16#0# range 0 .. 31; CR at 16#4# range 0 .. 31; APB1FZ at 16#8# range 0 .. 31; APB2FZ at 16#C# range 0 .. 31; end record; -- Debug support DBGMCU_Periph : aliased DBGMCU_Peripheral with Import, Address => System'To_Address (16#E0042000#); end STM32_SVD.DBGMCU;
-- -- Copyright 2018 The wookey project team <wookey@ssi.gouv.fr> -- - Ryad Benadjila -- - Arnauld Michelizza -- - Mathieu Renard -- - Philippe Thierry -- - Philippe Trebuchet -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- #if CONFIG_KERNEL_DOMAIN with ewok.tasks; #end if; package body ewok.perm with spark_mode => on is function dmashm_is_granted (from : in t_real_task_id; to : in t_real_task_id) return boolean is begin return ewok.perm_auto.com_dmashm_perm (from, to); end dmashm_is_granted; function ipc_is_granted (from : in t_real_task_id; to : in t_real_task_id) return boolean is begin return ewok.perm_auto.com_ipc_perm (from, to); end ipc_is_granted; #if CONFIG_KERNEL_DOMAIN function is_same_domain (from : in t_real_task_id; to : in t_real_task_id) return boolean with spark_mode => off -- implies tasks.get_domain() to be SPARK compatible is begin return ewok.tasks.get_domain (from) = ewok.tasks.get_domain (to); end is_same_domain; #end if; function ressource_is_granted (perm_name : in t_perm_name; task_id : in applications.t_real_task_id) return boolean is begin -- is there some assertion checking that some ressources tuples are -- forbidden case perm_name is when PERM_RES_DEV_DMA => return ewok.perm_auto.ressource_perm_register_tab(task_id).DEV_DMA = 1; when PERM_RES_DEV_CRYPTO_USR => return ewok.perm_auto.ressource_perm_register_tab(task_id).DEV_CRYPTO = 1 or ewok.perm_auto.ressource_perm_register_tab(task_id).DEV_CRYPTO = 3; when PERM_RES_DEV_CRYPTO_CFG => return ewok.perm_auto.ressource_perm_register_tab(task_id).DEV_CRYPTO = 2 or ewok.perm_auto.ressource_perm_register_tab(task_id).DEV_CRYPTO = 3; when PERM_RES_DEV_CRYPTO_FULL => return ewok.perm_auto.ressource_perm_register_tab(task_id).DEV_CRYPTO = 3; when PERM_RES_DEV_BUSES => return ewok.perm_auto.ressource_perm_register_tab(task_id).DEV_BUS = 1; when PERM_RES_DEV_EXTI => return ewok.perm_auto.ressource_perm_register_tab(task_id).DEV_EXTI = 1; when PERM_RES_DEV_TIM => return ewok.perm_auto.ressource_perm_register_tab(task_id).DEV_TIM = 1; when PERM_RES_TIM_GETMILLI => return ewok.perm_auto.ressource_perm_register_tab(task_id).TIM_TIME > 0; when PERM_RES_TIM_GETMICRO => return ewok.perm_auto.ressource_perm_register_tab(task_id).TIM_TIME > 1; when PERM_RES_TIM_GETCYCLE => return ewok.perm_auto.ressource_perm_register_tab(task_id).TIM_TIME > 2; when PERM_RES_TSK_FISR => return ewok.perm_auto.ressource_perm_register_tab(task_id).TSK_FISR = 1; when PERM_RES_TSK_FIPC => return ewok.perm_auto.ressource_perm_register_tab(task_id).TSK_FIPC = 1; when PERM_RES_TSK_RESET => return ewok.perm_auto.ressource_perm_register_tab(task_id).TSK_RESET = 1; when PERM_RES_TSK_UPGRADE => return ewok.perm_auto.ressource_perm_register_tab(task_id).TSK_UPGRADE = 1; when PERM_RES_TSK_RNG => return ewok.perm_auto.ressource_perm_register_tab(task_id).TSK_RNG = 1; when PERM_RES_MEM_DYNAMIC_MAP => return ewok.perm_auto.ressource_perm_register_tab(task_id).MEM_DYNAMIC_MAP = 1; end case; end ressource_is_granted; end ewok.perm;
-- Copyright (c) 2017 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with League.String_Vectors; with League.Strings; private with League.Pretty_Printers; package Ada_Pretty is type Node is abstract tagged private; type Node_Access is access constant Node'Class; type Node_Access_Array is array (Positive range <>) of not null Node_Access; type Factory is tagged private; not overriding function To_Text (Self : access Factory; Unit : not null Node_Access) return League.String_Vectors.Universal_String_Vector; -- Compilation units not overriding function New_Compilation_Unit (Self : access Factory; Root : not null Node_Access; Clauses : Node_Access := null; License : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access; not overriding function New_Subunit (Self : access Factory; Parent_Name : not null Node_Access; Proper_Body : not null Node_Access) return not null Node_Access; -- Node lists not overriding function New_List (Self : access Factory; List : Node_Access_Array) return not null Node_Access; not overriding function New_List (Self : access Factory; Head : Node_Access; Tail : not null Node_Access) return not null Node_Access; -- Add a Tail item to a Head list. Head could be -- * a null value, that means an empty list. Result is Tail then. -- * a non-list node, that means a list with single node inside. -- * a list of items. -- Clauses, Pragmas and Aspects not overriding function New_Aspect (Self : access Factory; Name : not null Node_Access; Value : Node_Access := null) return not null Node_Access; not overriding function New_Pragma (Self : access Factory; Name : not null Node_Access; Arguments : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access; not overriding function New_Use (Self : access Factory; Name : not null Node_Access; Use_Type : Boolean := False) return not null Node_Access; not overriding function New_With (Self : access Factory; Name : not null Node_Access; Is_Limited : Boolean := False; Is_Private : Boolean := False) return not null Node_Access; -- Declarations not overriding function New_Package (Self : access Factory; Name : not null Node_Access; Public_Part : Node_Access := null; Private_Part : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access; not overriding function New_Package_Body (Self : access Factory; Name : not null Node_Access; List : Node_Access := null) return not null Node_Access; not overriding function New_Package_Instantiation (Self : access Factory; Name : not null Node_Access; Template : not null Node_Access; Actual_Part : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access; not overriding function New_Parameter (Self : access Factory; Name : not null Node_Access; Type_Definition : not null Node_Access; Initialization : Node_Access := null; Is_In : Boolean := False; Is_Out : Boolean := False; Is_Aliased : Boolean := False; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access; not overriding function New_Subprogram_Body (Self : access Factory; Specification : not null Node_Access; Declarations : Node_Access := null; Statements : Node_Access := null; Exceptions : Node_Access := null) return not null Node_Access; not overriding function New_Subprogram_Declaration (Self : access Factory; Specification : not null Node_Access; Aspects : Node_Access := null; Is_Abstract : Boolean := False; Is_Null : Boolean := False; Expression : Node_Access := null; Renamed : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access; not overriding function New_Subtype (Self : access Factory; Name : not null Node_Access; Definition : not null Node_Access; Constrain : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access; not overriding function New_Type (Self : access Factory; Name : not null Node_Access; Discriminants : Node_Access := null; Definition : Node_Access := null; Aspects : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access; not overriding function New_Variable (Self : access Factory; Name : not null Node_Access; Type_Definition : Node_Access := null; Initialization : Node_Access := null; Rename : Node_Access := null; Is_Constant : Boolean := False; Is_Aliased : Boolean := False; Aspects : Node_Access := null; Comment : League.Strings.Universal_String := League.Strings.Empty_Universal_String) return not null Node_Access; -- Definitions type Access_Modifier is (Access_All, Access_Constant, Unspecified); not overriding function New_Access (Self : access Factory; Modifier : Access_Modifier := Unspecified; Target : not null Node_Access) return not null Node_Access; not overriding function New_Derived (Self : access Factory; Parent : not null Node_Access) return not null Node_Access; not overriding function New_Null_Exclusion (Self : access Factory; Definition : not null Node_Access; Exclude : Boolean := True) return not null Node_Access; not overriding function New_Interface (Self : access Factory; Is_Limited : Boolean := False; Parents : Node_Access := null) return not null Node_Access; not overriding function New_Private_Record (Self : access Factory; Is_Tagged : Boolean := False; Is_Limited : Boolean := False; Parents : Node_Access := null) return not null Node_Access; not overriding function New_Record (Self : access Factory; Parent : Node_Access := null; Components : Node_Access := null; Is_Abstract : Boolean := False; Is_Tagged : Boolean := False; Is_Limited : Boolean := False) return not null Node_Access; not overriding function New_Array (Self : access Factory; Indexes : not null Node_Access; Component : not null Node_Access) return not null Node_Access; type Trilean is (False, True, Unspecified); not overriding function New_Subprogram_Specification (Self : access Factory; Is_Overriding : Trilean := Unspecified; Name : Node_Access := null; Parameters : Node_Access := null; Result : Node_Access := null) return not null Node_Access; -- Expressions and Names not overriding function New_Apply (Self : access Factory; Prefix : not null Node_Access; Arguments : not null Node_Access) return not null Node_Access; -- This node represent construction in form 'prefix (arguments)' -- This includes function_call, indexed_component, slice, -- subtype_indication, etc not overriding function New_Qualified_Expession (Self : access Factory; Prefix : not null Node_Access; Argument : not null Node_Access) return not null Node_Access; not overriding function New_Infix (Self : access Factory; Operator : League.Strings.Universal_String; Left : not null Node_Access) return not null Node_Access; not overriding function New_Literal (Self : access Factory; Value : Natural; Base : Positive := 10) return not null Node_Access; not overriding function New_Name (Self : access Factory; Name : League.Strings.Universal_String) return not null Node_Access; -- Identifier, character literal ('X'), operator ("<") not overriding function New_Selected_Name (Self : access Factory; Name : League.Strings.Universal_String) return not null Node_Access; not overriding function New_Selected_Name (Self : access Factory; Prefix : not null Node_Access; Selector : not null Node_Access) return not null Node_Access; not overriding function New_String_Literal (Self : access Factory; Text : League.Strings.Universal_String) return not null Node_Access; not overriding function New_Parentheses (Self : access Factory; Child : not null Node_Access) return not null Node_Access; not overriding function New_Argument_Association (Self : access Factory; Value : not null Node_Access; Choice : Node_Access := null) return not null Node_Access; not overriding function New_Component_Association (Self : access Factory; Value : not null Node_Access; Choices : Node_Access := null) return not null Node_Access; not overriding function New_If_Expression (Self : access Factory; Condition : not null Node_Access; Then_Path : not null Node_Access; Elsif_List : Node_Access := null; Else_Path : Node_Access := null) return not null Node_Access; -- Statements and Paths not overriding function New_Assignment (Self : access Factory; Left : not null Node_Access; Right : not null Node_Access) return not null Node_Access; not overriding function New_Case (Self : access Factory; Expression : not null Node_Access; List : not null Node_Access) return not null Node_Access; not overriding function New_Case_Path (Self : access Factory; Choice : not null Node_Access; List : not null Node_Access) return not null Node_Access; not overriding function New_Elsif (Self : access Factory; Condition : not null Node_Access; List : not null Node_Access) return not null Node_Access; not overriding function New_If (Self : access Factory; Condition : not null Node_Access; Then_Path : not null Node_Access; Elsif_List : Node_Access := null; Else_Path : Node_Access := null) return not null Node_Access; not overriding function New_For (Self : access Factory; Name : not null Node_Access; Iterator : not null Node_Access; Statements : not null Node_Access) return not null Node_Access; not overriding function New_Loop (Self : access Factory; Condition : Node_Access; Statements : not null Node_Access) return not null Node_Access; not overriding function New_Return (Self : access Factory; Expression : Node_Access := null) return not null Node_Access; not overriding function New_Extended_Return (Self : access Factory; Name : not null Node_Access; Type_Definition : not null Node_Access; Initialization : Node_Access := null; Statements : not null Node_Access) return not null Node_Access; not overriding function New_Statement (Self : access Factory; Expression : Node_Access := null) return not null Node_Access; not overriding function New_Block (Self : access Factory; Declarations : Node_Access := null; Statements : Node_Access := null; Exceptions : Node_Access := null) return not null Node_Access; private type Node is abstract tagged null record; not overriding function Document (Self : Node; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document; not overriding function Max_Pad (Self : Node) return Natural is (0); -- Return maximum lengh of name in Node not overriding function Join (Self : Node; List : Node_Access_Array; Pad : Natural; Printer : not null access League.Pretty_Printers.Printer'Class) return League.Pretty_Printers.Document; -- Join documents of several nodes in a list type Expression is abstract new Node with null record; overriding function Join (Self : Expression; List : Node_Access_Array; Pad : Natural; Printer : not null access League.Pretty_Printers.Printer'Class) return League.Pretty_Printers.Document; type Declaration is abstract new Node with null record; overriding function Join (Self : Declaration; List : Node_Access_Array; Pad : Natural; Printer : not null access League.Pretty_Printers.Printer'Class) return League.Pretty_Printers.Document; -- Declarations are separated by an extra new line type Factory is tagged null record; function Print_Aspect (Aspect : Node_Access; Printer : not null access League.Pretty_Printers.Printer'Class) return League.Pretty_Printers.Document; end Ada_Pretty;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Sf.System.Randomizer; use Sf.System.Randomizer; procedure Main is begin sfRandom_SetSeed (10); for I in 1 .. 10 loop Put (sfRandom_Int (0, 10), 0); New_Line; end loop; end Main;
-- Copyright 2016-2021 Bartek thindil Jasicki -- -- This file is part of Steam Sky. -- -- Steam Sky is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Steam Sky is distributed in the hope that it will be useful, -- but WITHOUT 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 -- along with Steam Sky. If not, see <http://www.gnu.org/licenses/>. with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; use Ada.Containers; with Ada.Containers.Hashed_Maps; with DOM.Readers; use DOM.Readers; with Game; use Game; -- ****h* Items/Items -- FUNCTION -- Provice code for manipulate items -- SOURCE package Items is -- **** -- ****v* Items/Items.Items_Types -- FUNCTION -- Types of items -- SOURCE Items_Types: UnboundedString_Container.Vector; -- **** -- ****s* Items/Items.Object_Data -- FUNCTION -- Data structure for objects prototypes -- PARAMETERS -- Name - Name of item -- Weight - Weight of item -- IType - Type of item -- Price - Price of item in bases -- Value - Additional item data (damage for ammo, etc) -- ShowType - Displayed type of item (can be group of items, renamed -- type, etc) -- Description - Description of item -- Reputation - Minimal reputation in base needed to buy that module -- SOURCE type Object_Data is record Name: Unbounded_String; Weight: Positive := 1; IType: Unbounded_String; Price: Natural := 0; Value: Integer_Container.Vector; ShowType: Unbounded_String; Description: Unbounded_String; Reputation: Reputation_Range; end record; -- **** -- ****t* Items/Items.Objects_Container -- FUNCTION -- Used to store items data -- SOURCE package Objects_Container is new Hashed_Maps (Unbounded_String, Object_Data, Ada.Strings.Unbounded.Hash, "="); -- **** -- ****t* Items/Items.Items_Durability -- FUNCTION -- Used to mark items durability -- SOURCE subtype Items_Durability is Natural range 0 .. 101; -- **** -- ****d* Items/Items.Default_Item_Durability -- FUNCTION -- Default value for items durability -- SOURCE Default_Item_Durability: constant Items_Durability := 100; -- **** -- ****s* Items/Items.InventoryData -- FUNCTION -- Data structure for item in inventory -- PARAMETERS -- ProtoIndex - Index of prototype -- Amount - Amount of item -- Name - Name of item if different than default -- Durability - Current durability of item -- Price - Price for which item was bought -- SOURCE type InventoryData is record ProtoIndex: Unbounded_String; Amount: Positive := 1; Name: Unbounded_String; Durability: Items_Durability; Price: Natural := 0; end record; -- **** -- ****t* Items/Items.Inventory_Container -- FUNCTION -- Used to store inventory data -- SOURCE package Inventory_Container is new Vectors(Positive, InventoryData); -- **** -- ****v* Items/Items.Items_List -- FUNCTION -- List of item available in game -- SOURCE Items_List: Objects_Container.Map; -- **** -- ****v* Items/Items.Tools_List -- FUNCTION -- List of all tools types in game -- SOURCE Tools_List: UnboundedString_Container.Vector; -- **** -- ****v* Items/Items.Weapons_List -- FUNCTION -- List of indexes of all weapons in game -- SOURCE Weapons_List: UnboundedString_Container.Vector; -- **** -- ****v* Items/Items.Shields_List -- FUNCTION -- List of indexes of all shields in game -- SOURCE Shields_List: UnboundedString_Container.Vector; -- **** -- ****v* Items/Items.HeadArmors_List -- FUNCTION -- List of indexes of all head armors in game -- SOURCE HeadArmors_List: UnboundedString_Container.Vector; -- **** -- ****v* Items/Items.ChestArmors_List -- FUNCTION -- List of indexes of all chest armors in game -- SOURCE ChestArmors_List: UnboundedString_Container.Vector; -- **** -- ****v* Items/Items.ArmsArmors_List -- FUNCTION -- List of indexes of all arms armors in game -- SOURCE ArmsArmors_List: UnboundedString_Container.Vector; -- **** -- ****v* Items/Items.LegsArmors_List -- FUNCTION -- List of indexes of all legs armors in game -- SOURCE LegsArmors_List: UnboundedString_Container.Vector; -- **** -- ****f* Items/Items.LoadItems -- FUNCTION -- Load items from files -- PARAMETERS -- Reader - XML Reader from which items data will be read -- SOURCE procedure LoadItems(Reader: Tree_Reader); -- **** -- ****f* Items/Items.FindProtoItem -- FUNCTION -- Search for map index of selected item -- PARAMETERS -- ItemType - Item type of item which map index is looking for -- RESULT -- Map index of item or empty string if item not found -- SOURCE function FindProtoItem (ItemType: Unbounded_String) return Unbounded_String with Pre => (ItemType /= Null_Unbounded_String), Test_Case => (Name => "Test_FindProtoItem", Mode => Nominal); -- **** -- ****f* Items/Items.GetItemDamage -- FUNCTION -- Get description of item damage -- PARAMETERS -- ItemDurability - Numeric value of current durability of the item -- ToLower - If true, convert description to lower cases. Default -- is false -- RESULT -- Description of item damage level -- SOURCE function GetItemDamage (ItemDurability: Items_Durability; ToLower: Boolean := False) return String with Post => GetItemDamage'Result'Length > 0, Test_Case => (Name => "Test_GetItemDamage", Mode => Nominal); -- **** -- ****f* Items/Items.GetItemName -- FUNCTION -- Get name of item in ship cargo or character inventory -- Item - Item to get it name -- DamageInfo - If true, include description of the item damage in name. -- Default is true. -- ToLower - If true, convert damage info to lower case. Default is -- true. -- RESULT -- Name of item with additional damage level info -- SOURCE function GetItemName (Item: InventoryData; DamageInfo, ToLower: Boolean := True) return String with Post => GetItemName'Result'Length > 0, Test_Case => (Name => "Test_GetItemName", Mode => Nominal); -- **** -- ****f* Items/Items.DamageItem -- FUNCTION -- Check if item in ship cargo or character inventory was damaged -- PARAMETERS -- Inventory - Inventory in which selected item is -- ItemIndex - Inventory index of selected item -- SkillLevel - Level of skill character which uses that item. Default -- is 0 -- MemberIndex - Index of crew member of player ship which uses that -- item. Default is 0 -- RESULT -- Updated inventory in which item was -- SOURCE procedure DamageItem (Inventory: in out Inventory_Container.Vector; ItemIndex: Positive; SkillLevel, MemberIndex: Natural := 0) with Pre => (ItemIndex <= Inventory.Last_Index), Test_Case => (Name => "Test_DamageItem", Mode => Nominal); -- **** -- ****f* Items/Items.FindItem -- FUNCTION -- Find item in ship cargo or character inventory -- PARAMETERS -- Inventory - Inventory in which item will be looking for -- ProtoIndex - Prototype index of item. Can be empty if ItemType is set -- ItemType - Type of item to search. Can be empty if ProtoIndex is set -- Durability - Durability of item to search. Can be empty -- Quality - Quality of item to search. Can be empty -- RESULT -- Iventory index of item or 0 if item was not found -- SOURCE function FindItem (Inventory: Inventory_Container.Vector; ProtoIndex, ItemType: Unbounded_String := Null_Unbounded_String; Durability: Items_Durability := Items_Durability'Last; Quality: Positive := 100) return Natural with Post => FindItem'Result <= Inventory.Last_Index, Test_Case => (Name => "Test_FindItem", Mode => Nominal); -- **** -- ****f* Items/Items.SetToolsList -- FUNCTION -- Fill tools types list -- SOURCE procedure SetToolsList; -- **** -- ****f* Items/Items.GetItemChanceToDamage -- FUNCTION -- Get item chance to damage info -- PARAMETERS -- ItemData: Numeric chance to damage for selected item -- RESULT -- String with chance to damage level description -- SOURCE function GetItemChanceToDamage(ItemData: Natural) return String with Post => GetItemChanceToDamage'Result'Length > 0, Test_Case => (Name => "Test_GetItemChanceToDamage", Mode => Nominal); -- **** end Items;
with C.malloc.malloc; function System.System_Allocators.Allocated_Size ( Storage_Address : Address) return Storage_Elements.Storage_Count is pragma Suppress (All_Checks); begin return Storage_Elements.Storage_Offset ( C.malloc.malloc.malloc_size (C.void_const_ptr (Storage_Address))); end System.System_Allocators.Allocated_Size;
-- 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 Orka.SIMD.SSE2.Doubles; with Orka.SIMD.AVX.Doubles; package Orka.SIMD.FMA.Doubles.Arithmetic is pragma Pure; use SSE2.Doubles; use AVX.Doubles; function Multiply_Add (A, B, C : m128d) return m128d with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_vfmaddpd"; function Multiply_Add_Sub (A, B, C : m128d) return m128d with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_vfmaddsubpd"; function Multiply_Add (A, B, C : m256d) return m256d with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_vfmaddpd256"; function Multiply_Add_Sub (A, B, C : m256d) return m256d with Import, Convention => Intrinsic, External_Name => "__builtin_ia32_vfmaddsubpd256"; function "*" (Left, Right : m256d_Array) return m256d_Array with Inline; -- Multiplies the left matrix with the right matrix. Matrix multiplication -- is associative, but not commutative. function "*" (Left : m256d_Array; Right : m256d) return m256d with Inline; -- Multiplies the left matrix with the right vector. Matrix multiplication -- is associative, but not commutative. end Orka.SIMD.FMA.Doubles.Arithmetic;
-- Copyright (C)2021,2022 Steve Merrony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- See include/gtkada/gtkada.relocatable/gtkada/gdk-types-keysyms.ads for key symbol definitions with Gdk.Types.Keysyms; use Gdk.Types.Keysyms; with Dasher_Codes; use Dasher_Codes; with Redirector; package body Keyboard is procedure Handle_Key_Press (Key : in Gdk_Key_Type) is begin case Key is when GDK_Control_L | GDK_Control_R => Ctrl_Pressed := True; when GDK_Shift_L | GDK_Shift_R => Shift_Pressed := True; when others => null; end case; end Handle_Key_Press; procedure Enqueue_Key (Ch : in Character) is Str : String(1..1); begin Str(1) := Ch; Redirector.Router.Send_Data (Str); end Enqueue_Key; function Modify (C : in Character) return Character is MC : Character := C; begin if C >= Dasher_C1 and C <= Dasher_C4 then if Shift_Pressed then MC := Character'Val(Character'Pos(MC) - 4); end if; else if Shift_Pressed then MC := Character'Val(Character'Pos(MC) - 16); end if; if Ctrl_Pressed then MC := Character'Val(Character'Pos(MC) - 64); end if; end if; return MC; end Modify; procedure Enqueue_Pair (C1, C2 : in Character) is Str2 : String(1..2); begin Str2(1) := C1; Str2(2) := C2; Redirector.Router.Send_Data (Str2); end Enqueue_Pair; procedure Handle_Key_Release (Key : in Gdk_Key_Type) is Char : Character; begin -- Ada.Text_IO.Put_Line ("DEBUG: Handle_Key_Release got key:" & Key'Image); case Key is when GDK_Control_L | GDK_Control_R => Ctrl_Pressed := False; when GDK_Shift_L | GDK_Shift_R => Shift_Pressed := False; when GDK_Return => Enqueue_Key (Dasher_NL); -- convert PC-style Return to DG NL when GDK_KP_Enter => Enqueue_Key (Dasher_CR); -- convert PC Keypad Enter to DG CR when GDK_Tab => Enqueue_Key (Dasher_Tab); when GDK_Down => Enqueue_Key (Dasher_Cursor_Down); when GDK_Up => Enqueue_Key (Dasher_Cursor_Up); when GDK_Left => Enqueue_Key (Dasher_Cursor_Left); when GDK_Right => Enqueue_Key (Dasher_Cursor_Right); when GDK_Home => Enqueue_Key (Dasher_Home); -- The DEL key must map to 127 which is the DASHER DEL code when GDK_Delete => Enqueue_Key (Dasher_Delete); when GDK_Escape => Enqueue_Key (Dasher_Escape); -- N.B. At least on Debian with $TERM set to "d210-dg", the host -- expects both bytes to arrive in the same packet... when GDK_F1 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F1)); when GDK_F2 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F2)); when GDK_F3 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F3)); when GDK_F4 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F4)); when GDK_F5 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F5)); when GDK_F6 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F6)); when GDK_F7 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F7)); when GDK_F8 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F8)); when GDK_F9 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F9)); when GDK_F10 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F10)); when GDK_F11 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F11)); when GDK_F12 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F12)); when GDK_F13 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F13)); when GDK_F14 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F14)); when GDK_F15 => Enqueue_Pair (Dasher_Command, Modify (Dasher_F15)); -- Special codes from the virtual key buttons on the GUI when GDK_3270_EraseEOF => Enqueue_Key (Dasher_Erase_Page); when GDK_3270_EraseInput => Enqueue_Key (Dasher_Erase_EOL); when GDK_F31 => Enqueue_Pair (Dasher_Command, Modify (Dasher_C1)); when GDK_F32 => Enqueue_Pair (Dasher_Command, Modify (Dasher_C2)); when GDK_F33 => Enqueue_Pair (Dasher_Command, Modify (Dasher_C3)); when GDK_F34 => Enqueue_Pair (Dasher_Command, Modify (Dasher_C4)); when others => if Key < 256 then Char := Character'Val(Key); if Ctrl_Pressed then Char := Character'Val(Character'Pos(Char) mod 32); end if; Enqueue_Key (Char); end if; end case; end Handle_Key_Release; end Keyboard;
------------------------------------------------------------------------------ -- Copyright (c) 2013-2014, 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. -- ------------------------------------------------------------------------------ with Ada.Characters.Latin_1; with Ada.Unchecked_Deallocation; with System.Machine_Code; package body Natools.References is --------------------------------- -- Low-level memory management -- --------------------------------- overriding procedure Adjust (Object : in out Immutable_Reference) is begin if Object.Count /= null then Increment (Object.Count); end if; end Adjust; overriding procedure Finalize (Object : in out Immutable_Reference) is procedure Free is new Ada.Unchecked_Deallocation (Held_Data, Data_Access); procedure Free is new Ada.Unchecked_Deallocation (Counter, Counter_Access); Deallocate : Boolean; begin if Object.Count /= null then Decrement (Object.Count, Deallocate); if Deallocate then Free (Object.Count); Free (Object.Data); else Object.Count := null; Object.Data := null; end if; end if; end Finalize; ----------------------------------------- -- Object construction and destruction -- ----------------------------------------- function Create (Constructor : not null access function return Held_Data) return Immutable_Reference is begin return (Ada.Finalization.Controlled with Data => new Held_Data'(Constructor.all), Count => new Counter'(1)); end Create; procedure Replace (Ref : in out Immutable_Reference; Constructor : not null access function return Held_Data) is begin Finalize (Ref); Ref.Data := new Held_Data'(Constructor.all); Ref.Count := new Counter'(1); end Replace; function Create (Data : in Data_Access) return Immutable_Reference is begin if Data = null then return Null_Immutable_Reference; else return (Ada.Finalization.Controlled with Data => Data, Count => new Counter'(1)); end if; end Create; procedure Replace (Ref : in out Immutable_Reference; Data : in Data_Access) is begin Finalize (Ref); if Data /= null then Ref.Data := Data; Ref.Count := new Counter'(1); end if; end Replace; procedure Reset (Ref : in out Immutable_Reference) is begin Finalize (Ref); end Reset; function Is_Empty (Ref : Immutable_Reference) return Boolean is begin return Ref.Count = null; end Is_Empty; function Is_Last (Ref : Immutable_Reference) return Boolean is begin return Ref.Count.all = 1; end Is_Last; function "=" (Left, Right : Immutable_Reference) return Boolean is begin return Left.Data = Right.Data; end "="; ---------------------- -- Dereferenciation -- ---------------------- function Query (Ref : in Immutable_Reference) return Accessor is begin return Accessor'(Data => Ref.Data, Parent => Ref); end Query; function Update (Ref : in Reference) return Mutator is begin return Mutator'(Data => Ref.Data, Parent => Ref); end Update; procedure Query (Ref : in Immutable_Reference; Process : not null access procedure (Object : in Held_Data)) is begin Process.all (Ref.Data.all); end Query; procedure Update (Ref : in Reference; Process : not null access procedure (Object : in out Held_Data)) is begin Process.all (Ref.Data.all); end Update; ------------------------ -- Counter Management -- ------------------------ -- procedure Increment (Object : in Counter_Access) is -- begin -- Object.all := Object.all + 1; -- end Increment; -- -- procedure Decrement (Object : in Counter_Access; Zero : out Boolean) is -- begin -- Object.all := Object.all - 1; -- Zero := Object.all = 0; -- end Decrement; procedure Increment (Object : in Counter_Access) is begin System.Machine_Code.Asm (Template => "lock incl %0", Outputs => Counter'Asm_Output ("+m", Object.all), Volatile => True, Clobber => "cc, memory"); end Increment; procedure Decrement (Object : in Counter_Access; Zero : out Boolean) is package Latin_1 renames Ada.Characters.Latin_1; use type Interfaces.Unsigned_8; Z_Flag : Interfaces.Unsigned_8; begin System.Machine_Code.Asm (Template => "lock decl %0" & Latin_1.LF & Latin_1.HT & "setz %1", Outputs => (Counter'Asm_Output ("+m", Object.all), Interfaces.Unsigned_8'Asm_Output ("=q", Z_Flag)), Volatile => True, Clobber => "cc, memory"); Zero := Z_Flag = 1; end Decrement; end Natools.References;
-- Copyright (c) 2017 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- package body Ada_Pretty.Units is -------------- -- Document -- -------------- overriding function Document (Self : Compilation_Unit; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin if not Self.License.Is_Empty then Result.New_Line; Result.Put (Self.License); end if; if Self.Clauses /= null then Result.Append (Self.Clauses.Document (Printer, Pad)); Result.New_Line; end if; Result.Append (Self.Root.Document (Printer, Pad)); return Result; end Document; -------------- -- Document -- -------------- overriding function Document (Self : Subunit; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is Result : League.Pretty_Printers.Document := Printer.New_Document; begin Result.New_Line; Result.Put ("separate ("); Result.Append (Self.Parent_Name.Document (Printer, Pad)); Result.Put (")"); Result.Append (Self.Proper_Body.Document (Printer, Pad)); return Result; end Document; -------------------------- -- New_Compilation_Unit -- -------------------------- function New_Compilation_Unit (Root : not null Node_Access; Clauses : Node_Access := null; License : League.Strings.Universal_String) return Node'Class is begin return Compilation_Unit'(Root, Clauses, License); end New_Compilation_Unit; ----------------- -- New_Subunit -- ----------------- function New_Subunit (Parent_Name : not null Node_Access; Proper_Body : not null Node_Access) return Node'Class is begin return Subunit'(Parent_Name, Proper_Body); end New_Subunit; end Ada_Pretty.Units;
------------------------------------------------------------------------------ -- -- -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . T A S K I N G . R E N D E Z V O U S -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1991-2001, Florida State University -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNARL is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNARL; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. It is -- -- now maintained by Ada Core Technologies Inc. in cooperation with Florida -- -- State University (http://www.gnat.com). -- -- -- ------------------------------------------------------------------------------ with Ada.Exceptions; -- Used for Exception_ID -- Null_Id -- Save_Occurrence -- Raise_Exception with System.Task_Primitives.Operations; -- used for Get_Priority -- Set_Priority -- Write_Lock -- Unlock -- Sleep -- Wakeup -- Timed_Sleep with System.Tasking.Entry_Calls; -- Used for Wait_For_Completion -- Wait_For_Completion_With_Timeout -- Wait_Until_Abortable with System.Tasking.Initialization; -- used for Defer_Abort -- Undefer_Abort -- Poll_Base_Priority_Change with System.Tasking.Queuing; -- used for Enqueue -- Dequeue_Head -- Select_Task_Entry_Call -- Count_Waiting with System.Tasking.Utilities; -- used for Check_Exception -- Make_Passive -- Wakeup_Entry_Caller with System.Tasking.Protected_Objects.Operations; -- used for PO_Do_Or_Queue -- PO_Service_Entries -- Lock_Entries -- Unlock_Entries with System.Tasking.Debug; -- used for Trace package body System.Tasking.Rendezvous is package STPO renames System.Task_Primitives.Operations; package POO renames System.Tasking.Protected_Objects.Operations; package POE renames System.Tasking.Protected_Objects.Entries; use System.Task_Primitives; use System.Task_Primitives.Operations; type Select_Treatment is ( Accept_Alternative_Selected, -- alternative with non-null body Accept_Alternative_Completed, -- alternative with null body Else_Selected, Terminate_Selected, Accept_Alternative_Open, No_Alternative_Open); Default_Treatment : constant array (Select_Modes) of Select_Treatment := (Simple_Mode => No_Alternative_Open, Else_Mode => Else_Selected, Terminate_Mode => Terminate_Selected, Delay_Mode => No_Alternative_Open); New_State : constant array (Boolean, Entry_Call_State) of Entry_Call_State := (True => (Never_Abortable => Never_Abortable, Not_Yet_Abortable => Now_Abortable, Was_Abortable => Now_Abortable, Now_Abortable => Now_Abortable, Done => Done, Cancelled => Cancelled), False => (Never_Abortable => Never_Abortable, Not_Yet_Abortable => Not_Yet_Abortable, Was_Abortable => Was_Abortable, Now_Abortable => Now_Abortable, Done => Done, Cancelled => Cancelled) ); ----------------------- -- Local Subprograms -- ----------------------- procedure Local_Defer_Abort (Self_Id : Task_ID) renames System.Tasking.Initialization.Defer_Abort_Nestable; procedure Local_Undefer_Abort (Self_Id : Task_ID) renames System.Tasking.Initialization.Undefer_Abort_Nestable; -- Florist defers abort around critical sections that -- make entry calls to the Interrupt_Manager task, which -- violates the general rule about top-level runtime system -- calls from abort-deferred regions. It is not that this is -- unsafe, but when it occurs in "normal" programs it usually -- means either the user is trying to do a potentially blocking -- operation from within a protected object, or there is a -- runtime system/compiler error that has failed to undefer -- an earlier abort deferral. Thus, for debugging it may be -- wise to modify the above renamings to the non-nestable forms. procedure Boost_Priority (Call : Entry_Call_Link; Acceptor : Task_ID); pragma Inline (Boost_Priority); -- Call this only with abort deferred and holding lock of Acceptor. procedure Call_Synchronous (Acceptor : Task_ID; E : Task_Entry_Index; Uninterpreted_Data : System.Address; Mode : Call_Modes; Rendezvous_Successful : out Boolean); pragma Inline (Call_Synchronous); -- This call is used to make a simple or conditional entry call. procedure Setup_For_Rendezvous_With_Body (Entry_Call : Entry_Call_Link; Acceptor : Task_ID); pragma Inline (Setup_For_Rendezvous_With_Body); -- Call this only with abort deferred and holding lock of Acceptor. -- When a rendezvous selected (ready for rendezvous) we need to save -- privious caller and adjust the priority. Also we need to make -- this call not Abortable (Cancellable) since the rendezvous has -- already been started. function Is_Entry_Open (T : Task_ID; E : Task_Entry_Index) return Boolean; pragma Inline (Is_Entry_Open); -- Call this only with abort deferred and holding lock of T. procedure Wait_For_Call (Self_Id : Task_ID); pragma Inline (Wait_For_Call); -- Call this only with abort deferred and holding lock of Self_Id. -- An accepting task goes into Sleep by calling this routine -- waiting for a call from the caller or waiting for an abortion. -- Make sure Self_Id is locked before calling this routine. ----------------- -- Accept_Call -- ----------------- -- Compiler interface only. Do not call from within the RTS. -- source: -- accept E do ...A... end E; -- expansion: -- A27b : address; -- L26b : label -- begin -- accept_call (1, A27b); -- ...A... -- complete_rendezvous; -- <<L26b>> -- exception -- when all others => -- exceptional_complete_rendezvous (get_gnat_exception); -- end; -- The handler for Abort_Signal (*all* others) is to handle the case when -- the acceptor is aborted between Accept_Call and the corresponding -- Complete_Rendezvous call. We need to wake up the caller in this case. -- See also Selective_Wait procedure Accept_Call (E : Task_Entry_Index; Uninterpreted_Data : out System.Address) is Self_Id : constant Task_ID := STPO.Self; Caller : Task_ID := null; Open_Accepts : aliased Accept_List (1 .. 1); Entry_Call : Entry_Call_Link; begin Initialization.Defer_Abort (Self_Id); STPO.Write_Lock (Self_Id); if not Self_Id.Callable then pragma Assert (Self_Id.Pending_ATC_Level = 0); pragma Assert (Self_Id.Pending_Action); STPO.Unlock (Self_Id); Initialization.Undefer_Abort (Self_Id); -- Should never get here ??? pragma Assert (False); raise Standard'Abort_Signal; end if; -- If someone completed this task, this task should not try to -- access its pending entry calls or queues in this case, as they -- are being emptied. Wait for abortion to kill us. -- ????? -- Recheck the correctness of the above, now that we have made -- changes. The logic above seems to be based on the assumption -- that one task can safely clean up another's in-service accepts. -- ????? -- Why do we need to block here in this case? -- Why not just return and let Undefer_Abort do its work? Queuing.Dequeue_Head (Self_Id.Entry_Queues (E), Entry_Call); if Entry_Call /= null then Caller := Entry_Call.Self; Setup_For_Rendezvous_With_Body (Entry_Call, Self_Id); Uninterpreted_Data := Entry_Call.Uninterpreted_Data; else -- Wait for a caller Open_Accepts (1).Null_Body := False; Open_Accepts (1).S := E; Self_Id.Open_Accepts := Open_Accepts'Unrestricted_Access; -- Wait for normal call pragma Debug (Debug.Trace (Self_Id, "Accept_Call: wait", 'R')); Wait_For_Call (Self_Id); pragma Assert (Self_Id.Open_Accepts = null); if Self_Id.Pending_ATC_Level >= Self_Id.ATC_Nesting_Level then Caller := Self_Id.Common.Call.Self; Uninterpreted_Data := Caller.Entry_Calls (Caller.ATC_Nesting_Level).Uninterpreted_Data; end if; -- If this task has been aborted, skip the Uninterpreted_Data load -- (Caller will not be reliable) and fall through to -- Undefer_Abort which will allow the task to be killed. -- ????? -- Perhaps we could do the code anyway, if it has no harm, in order -- to get better performance for the normal case. end if; -- Self_Id.Common.Call should already be updated by the Caller -- On return, we will start the rendezvous. STPO.Unlock (Self_Id); Initialization.Undefer_Abort (Self_Id); end Accept_Call; -------------------- -- Accept_Trivial -- -------------------- -- Compiler interface only. Do not call from within the RTS. -- This should only be called when there is no accept body, -- or the except body is empty. -- source: -- accept E; -- expansion: -- accept_trivial (1); -- The compiler is also able to recognize the following and -- translate it the same way. -- accept E do null; end E; procedure Accept_Trivial (E : Task_Entry_Index) is Self_Id : constant Task_ID := STPO.Self; Caller : Task_ID := null; Open_Accepts : aliased Accept_List (1 .. 1); Entry_Call : Entry_Call_Link; begin Initialization.Defer_Abort_Nestable (Self_Id); STPO.Write_Lock (Self_Id); if not Self_Id.Callable then pragma Assert (Self_Id.Pending_ATC_Level = 0); pragma Assert (Self_Id.Pending_Action); STPO.Unlock (Self_Id); Initialization.Undefer_Abort_Nestable (Self_Id); -- Should never get here ??? pragma Assert (False); raise Standard'Abort_Signal; end if; -- If someone completed this task, this task should not try to -- access its pending entry calls or queues in this case, as they -- are being emptied. Wait for abortion to kill us. -- ????? -- Recheck the correctness of the above, now that we have made -- changes. Queuing.Dequeue_Head (Self_Id.Entry_Queues (E), Entry_Call); if Entry_Call = null then -- Need to wait for entry call Open_Accepts (1).Null_Body := True; Open_Accepts (1).S := E; Self_Id.Open_Accepts := Open_Accepts'Unrestricted_Access; pragma Debug (Debug.Trace (Self_Id, "Accept_Trivial: wait", 'R')); Wait_For_Call (Self_Id); pragma Assert (Self_Id.Open_Accepts = null); -- No need to do anything special here for pending abort. -- Abort_Signal will be raised by Undefer on exit. STPO.Unlock (Self_Id); else -- found caller already waiting pragma Assert (Entry_Call.State < Done); STPO.Unlock (Self_Id); Caller := Entry_Call.Self; STPO.Write_Lock (Caller); Initialization.Wakeup_Entry_Caller (Self_Id, Entry_Call, Done); STPO.Unlock (Caller); end if; Initialization.Undefer_Abort_Nestable (Self_Id); end Accept_Trivial; -------------------- -- Boost_Priority -- -------------------- -- Call this only with abort deferred and holding lock of Acceptor. procedure Boost_Priority (Call : Entry_Call_Link; Acceptor : Task_ID) is Caller : Task_ID := Call.Self; Caller_Prio : System.Any_Priority := Get_Priority (Caller); Acceptor_Prio : System.Any_Priority := Get_Priority (Acceptor); begin if Caller_Prio > Acceptor_Prio then Call.Acceptor_Prev_Priority := Acceptor_Prio; Set_Priority (Acceptor, Caller_Prio); else Call.Acceptor_Prev_Priority := Priority_Not_Boosted; end if; end Boost_Priority; ----------------- -- Call_Simple -- ----------------- -- Compiler interface only. Do not call from within the RTS. procedure Call_Simple (Acceptor : Task_ID; E : Task_Entry_Index; Uninterpreted_Data : System.Address) is Rendezvous_Successful : Boolean; begin Call_Synchronous (Acceptor, E, Uninterpreted_Data, Simple_Call, Rendezvous_Successful); end Call_Simple; ---------------------- -- Call_Synchronous -- ---------------------- -- Compiler interface. -- Also called from inside Call_Simple and Task_Entry_Call. procedure Call_Synchronous (Acceptor : Task_ID; E : Task_Entry_Index; Uninterpreted_Data : System.Address; Mode : Call_Modes; Rendezvous_Successful : out Boolean) is Self_Id : constant Task_ID := STPO.Self; Level : ATC_Level; Entry_Call : Entry_Call_Link; begin pragma Assert (Mode /= Asynchronous_Call); Local_Defer_Abort (Self_Id); Self_Id.ATC_Nesting_Level := Self_Id.ATC_Nesting_Level + 1; pragma Debug (Debug.Trace (Self_Id, "CS: entered ATC level: " & ATC_Level'Image (Self_Id.ATC_Nesting_Level), 'A')); Level := Self_Id.ATC_Nesting_Level; Entry_Call := Self_Id.Entry_Calls (Level)'Access; Entry_Call.Next := null; Entry_Call.Mode := Mode; Entry_Call.Cancellation_Attempted := False; -- If this is a call made inside of an abort deferred region, -- the call should be never abortable. if Self_Id.Deferral_Level > 1 then Entry_Call.State := Never_Abortable; else Entry_Call.State := Now_Abortable; end if; Entry_Call.E := Entry_Index (E); Entry_Call.Prio := Get_Priority (Self_Id); Entry_Call.Uninterpreted_Data := Uninterpreted_Data; Entry_Call.Called_Task := Acceptor; Entry_Call.Exception_To_Raise := Ada.Exceptions.Null_Id; -- Note: the caller will undefer abortion on return (see WARNING above) if not Task_Do_Or_Queue (Self_Id, Entry_Call, With_Abort => True) then Self_Id.ATC_Nesting_Level := Self_Id.ATC_Nesting_Level - 1; Initialization.Undefer_Abort (Self_Id); pragma Debug (Debug.Trace (Self_Id, "CS: exited to ATC level: " & ATC_Level'Image (Self_Id.ATC_Nesting_Level), 'A')); raise Tasking_Error; end if; STPO.Write_Lock (Self_Id); pragma Debug (Debug.Trace (Self_Id, "Call_Synchronous: wait", 'R')); Entry_Calls.Wait_For_Completion (Self_Id, Entry_Call); pragma Debug (Debug.Trace (Self_Id, "Call_Synchronous: done waiting", 'R')); Rendezvous_Successful := Entry_Call.State = Done; STPO.Unlock (Self_Id); Local_Undefer_Abort (Self_Id); Entry_Calls.Check_Exception (Self_Id, Entry_Call); end Call_Synchronous; -------------- -- Callable -- -------------- -- Compiler interface. -- Do not call from within the RTS, -- except for body of Ada.Task_Identification. function Callable (T : Task_ID) return Boolean is Result : Boolean; Self_Id : constant Task_ID := STPO.Self; begin Initialization.Defer_Abort (Self_Id); STPO.Write_Lock (T); Result := T.Callable; STPO.Unlock (T); Initialization.Undefer_Abort (Self_Id); return Result; end Callable; ---------------------------- -- Cancel_Task_Entry_Call -- ---------------------------- -- Compiler interface only. Do not call from within the RTS. -- Call only with abort deferred. procedure Cancel_Task_Entry_Call (Cancelled : out Boolean) is begin Entry_Calls.Try_To_Cancel_Entry_Call (Cancelled); end Cancel_Task_Entry_Call; ------------------------- -- Complete_Rendezvous -- ------------------------- -- See comments for Exceptional_Complete_Rendezvous. procedure Complete_Rendezvous is begin Exceptional_Complete_Rendezvous (Ada.Exceptions.Null_Id); end Complete_Rendezvous; ------------------------------------- -- Exceptional_Complete_Rendezvous -- ------------------------------------- -- Compiler interface. -- Also called from Complete_Rendezvous. -- ????? -- Consider phasing out Complete_Rendezvous in favor -- of direct call to this with Ada.Exceptions.Null_ID. -- See code expansion examples for Accept_Call and Selective_Wait. -- ????? -- If we don't change the interface, consider instead -- putting an explicit re-raise after this call, in -- the generated code. That way we could eliminate the -- code here that reraises the exception. -- The deferral level is critical here, -- since we want to raise an exception or allow abort to take -- place, if there is an exception or abort pending. procedure Exceptional_Complete_Rendezvous (Ex : Ada.Exceptions.Exception_Id) is Self_Id : constant Task_ID := STPO.Self; Entry_Call : Entry_Call_Link := Self_Id.Common.Call; Caller : Task_ID; Called_PO : STPE.Protection_Entries_Access; Exception_To_Raise : Ada.Exceptions.Exception_Id := Ex; Ceiling_Violation : Boolean; use type Ada.Exceptions.Exception_Id; procedure Internal_Reraise; pragma Import (C, Internal_Reraise, "__gnat_reraise"); use type STPE.Protection_Entries_Access; begin pragma Debug (Debug.Trace (Self_Id, "Exceptional_Complete_Rendezvous", 'R')); if Ex = Ada.Exceptions.Null_Id then -- The call came from normal end-of-rendezvous, -- so abort is not yet deferred. Initialization.Defer_Abort_Nestable (Self_Id); end if; -- We need to clean up any accepts which Self may have -- been serving when it was aborted. if Ex = Standard'Abort_Signal'Identity then while Entry_Call /= null loop Entry_Call.Exception_To_Raise := Tasking_Error'Identity; -- All forms of accept make sure that the acceptor is not -- completed, before accepting further calls, so that we -- can be sure that no further calls are made after the -- current calls are purged. Caller := Entry_Call.Self; -- Take write lock. This follows the lock precedence rule that -- Caller may be locked while holding lock of Acceptor. -- Complete the call abnormally, with exception. STPO.Write_Lock (Caller); Initialization.Wakeup_Entry_Caller (Self_Id, Entry_Call, Done); STPO.Unlock (Caller); Entry_Call := Entry_Call.Acceptor_Prev_Call; end loop; else Caller := Entry_Call.Self; if Entry_Call.Needs_Requeue then -- We dare not lock Self_Id at the same time as Caller, -- for fear of deadlock. Entry_Call.Needs_Requeue := False; Self_Id.Common.Call := Entry_Call.Acceptor_Prev_Call; if Entry_Call.Called_Task /= null then -- Requeue to another task entry if not Task_Do_Or_Queue (Self_Id, Entry_Call, Entry_Call.Requeue_With_Abort) then Initialization.Undefer_Abort (Self_Id); raise Tasking_Error; end if; else -- Requeue to a protected entry Called_PO := POE.To_Protection (Entry_Call.Called_PO); STPE.Lock_Entries (Called_PO, Ceiling_Violation); if Ceiling_Violation then pragma Assert (Ex = Ada.Exceptions.Null_Id); Exception_To_Raise := Program_Error'Identity; Entry_Call.Exception_To_Raise := Exception_To_Raise; STPO.Write_Lock (Caller); Initialization.Wakeup_Entry_Caller (Self_Id, Entry_Call, Done); STPO.Unlock (Caller); else POO.PO_Do_Or_Queue (Self_Id, Called_PO, Entry_Call, Entry_Call.Requeue_With_Abort); POO.PO_Service_Entries (Self_Id, Called_PO); STPE.Unlock_Entries (Called_PO); end if; end if; Entry_Calls.Reset_Priority (Entry_Call.Acceptor_Prev_Priority, Self_Id); else -- The call does not need to be requeued. Self_Id.Common.Call := Entry_Call.Acceptor_Prev_Call; Entry_Call.Exception_To_Raise := Ex; STPO.Write_Lock (Caller); -- Done with Caller locked to make sure that Wakeup is not lost. if Ex /= Ada.Exceptions.Null_Id then Ada.Exceptions.Save_Occurrence (Caller.Common.Compiler_Data.Current_Excep, Self_Id.Common.Compiler_Data.Current_Excep); end if; Initialization.Wakeup_Entry_Caller (Self_Id, Entry_Call, Done); STPO.Unlock (Caller); Entry_Calls.Reset_Priority (Entry_Call.Acceptor_Prev_Priority, Self_Id); end if; end if; Initialization.Undefer_Abort (Self_Id); if Exception_To_Raise /= Ada.Exceptions.Null_Id then Internal_Reraise; end if; -- ????? -- Do we need to -- give precedence to Program_Error that might be raised -- due to failure of finalization, over Tasking_Error from -- failure of requeue? end Exceptional_Complete_Rendezvous; ------------------- -- Is_Entry_Open -- ------------------- -- Call this only with abort deferred and holding lock of T. function Is_Entry_Open (T : Task_ID; E : Task_Entry_Index) return Boolean is begin pragma Assert (T.Open_Accepts /= null); if T.Open_Accepts /= null then for J in T.Open_Accepts'Range loop pragma Assert (J > 0); if E = T.Open_Accepts (J).S then return True; end if; end loop; end if; return False; end Is_Entry_Open; ------------------------------------- -- Requeue_Protected_To_Task_Entry -- ------------------------------------- -- Compiler interface only. Do not call from within the RTS. -- entry e2 when b is -- begin -- b := false; -- ...A... -- requeue t.e2; -- end e2; -- procedure rPT__E14b (O : address; P : address; E : -- protected_entry_index) is -- type rTVP is access rTV; -- freeze rTVP [] -- _object : rTVP := rTVP!(O); -- begin -- declare -- rR : protection renames _object._object; -- vP : integer renames _object.v; -- bP : boolean renames _object.b; -- begin -- b := false; -- ...A... -- requeue_protected_to_task_entry (rR'unchecked_access, tTV!(t). -- _task_id, 2, false); -- return; -- end; -- complete_entry_body (_object._object'unchecked_access, objectF => -- 0); -- return; -- exception -- when others => -- abort_undefer.all; -- exceptional_complete_entry_body (_object._object' -- unchecked_access, current_exception, objectF => 0); -- return; -- end rPT__E14b; procedure Requeue_Protected_To_Task_Entry (Object : STPE.Protection_Entries_Access; Acceptor : Task_ID; E : Task_Entry_Index; With_Abort : Boolean) is Entry_Call : constant Entry_Call_Link := Object.Call_In_Progress; begin pragma Assert (STPO.Self.Deferral_Level > 0); Entry_Call.E := Entry_Index (E); Entry_Call.Called_Task := Acceptor; Entry_Call.Called_PO := Null_Address; Entry_Call.Requeue_With_Abort := With_Abort; Object.Call_In_Progress := null; end Requeue_Protected_To_Task_Entry; ------------------------ -- Requeue_Task_Entry -- ------------------------ -- Compiler interface only. Do not call from within the RTS. -- The code generation for task entry requeues is different from that -- for protected entry requeues. There is a "goto" that skips around -- the call to Complete_Rendezous, so that Requeue_Task_Entry must also -- do the work of Complete_Rendezvous. The difference is that it does -- not report that the call's State = Done. -- accept e1 do -- ...A... -- requeue e2; -- ...B... -- end e1; -- A62b : address; -- L61b : label -- begin -- accept_call (1, A62b); -- ...A... -- requeue_task_entry (tTV!(t)._task_id, 2, false); -- goto L61b; -- ...B... -- complete_rendezvous; -- <<L61b>> -- exception -- when others => -- exceptional_complete_rendezvous (current_exception); -- end; procedure Requeue_Task_Entry (Acceptor : Task_ID; E : Task_Entry_Index; With_Abort : Boolean) is Self_Id : constant Task_ID := STPO.Self; Entry_Call : constant Entry_Call_Link := Self_Id.Common.Call; begin Initialization.Defer_Abort (Self_Id); Entry_Call.Needs_Requeue := True; Entry_Call.Requeue_With_Abort := With_Abort; Entry_Call.E := Entry_Index (E); Entry_Call.Called_Task := Acceptor; Initialization.Undefer_Abort (Self_Id); end Requeue_Task_Entry; -------------------- -- Selective_Wait -- -------------------- -- Compiler interface only. Do not call from within the RTS. -- See comments on Accept_Call. -- source code: -- select accept e1 do -- ...A... -- end e1; -- ...B... -- or accept e2; -- ...C... -- end select; -- expansion: -- A32b : address; -- declare -- null; -- if accept_alternative'size * 2 >= 16#8000_0000# then -- raise storage_error; -- end if; -- A37b : T36b; -- A37b (1) := (null_body => false, s => 1); -- A37b (2) := (null_body => true, s => 2); -- if accept_alternative'size * 2 >= 16#8000_0000# then -- raise storage_error; -- end if; -- S0 : aliased T36b := accept_list'A37b; -- J1 : select_index := 0; -- L3 : label -- L1 : label -- L2 : label -- procedure e1A is -- begin -- abort_undefer.all; -- L31b : label -- ...A... -- <<L31b>> -- complete_rendezvous; -- exception -- when all others => -- exceptional_complete_rendezvous (get_gnat_exception); -- end e1A; -- begin -- selective_wait (S0'unchecked_access, simple_mode, A32b, J1); -- case J1 is -- when 0 => -- goto L3; -- when 1 => -- e1A; -- goto L1; -- when 2 => -- goto L2; -- when others => -- goto L3; -- end case; -- <<L1>> -- ...B... -- goto L3; -- <<L2>> -- ...C... -- goto L3; -- <<L3>> -- end; procedure Selective_Wait (Open_Accepts : Accept_List_Access; Select_Mode : Select_Modes; Uninterpreted_Data : out System.Address; Index : out Select_Index) is Self_Id : constant Task_ID := STPO.Self; Entry_Call : Entry_Call_Link; Treatment : Select_Treatment; Caller : Task_ID; Selection : Select_Index; Open_Alternative : Boolean; begin Initialization.Defer_Abort (Self_Id); STPO.Write_Lock (Self_Id); if not Self_Id.Callable then pragma Assert (Self_Id.Pending_ATC_Level = 0); pragma Assert (Self_Id.Pending_Action); STPO.Unlock (Self_Id); -- ??? In some cases abort is deferred more than once. Need to figure -- out why. Self_Id.Deferral_Level := 1; Initialization.Undefer_Abort (Self_Id); -- Should never get here ??? pragma Assert (False); raise Standard'Abort_Signal; end if; -- If someone completed this task, this task should not try to -- access its pending entry calls or queues in this case, as they -- are being emptied. Wait for abortion to kill us. -- ????? -- Recheck the correctness of the above, now that we have made -- changes. pragma Assert (Open_Accepts /= null); Queuing.Select_Task_Entry_Call (Self_Id, Open_Accepts, Entry_Call, Selection, Open_Alternative); -- Determine the kind and disposition of the select. Treatment := Default_Treatment (Select_Mode); Self_Id.Chosen_Index := No_Rendezvous; if Open_Alternative then if Entry_Call /= null then if Open_Accepts (Selection).Null_Body then Treatment := Accept_Alternative_Completed; else Setup_For_Rendezvous_With_Body (Entry_Call, Self_Id); Treatment := Accept_Alternative_Selected; end if; Self_Id.Chosen_Index := Selection; elsif Treatment = No_Alternative_Open then Treatment := Accept_Alternative_Open; end if; end if; -- ?????? -- Recheck the logic above against the ARM. -- Handle the select according to the disposition selected above. case Treatment is when Accept_Alternative_Selected => -- Ready to rendezvous Uninterpreted_Data := Self_Id.Common.Call.Uninterpreted_Data; -- In this case the accept body is not Null_Body. Defer abortion -- until it gets into the accept body. pragma Assert (Self_Id.Deferral_Level = 1); Initialization.Defer_Abort_Nestable (Self_Id); STPO.Unlock (Self_Id); when Accept_Alternative_Completed => -- Accept body is null, so rendezvous is over immediately. STPO.Unlock (Self_Id); Caller := Entry_Call.Self; STPO.Write_Lock (Caller); Initialization.Wakeup_Entry_Caller (Self_Id, Entry_Call, Done); STPO.Unlock (Caller); when Accept_Alternative_Open => -- Wait for caller. Self_Id.Open_Accepts := Open_Accepts; pragma Debug (Debug.Trace (Self_Id, "Selective_Wait: wait", 'R')); Wait_For_Call (Self_Id); pragma Assert (Self_Id.Open_Accepts = null); -- Self_Id.Common.Call should already be updated by the Caller if -- not aborted. It might also be ready to do rendezvous even if -- this wakes up due to an abortion. -- Therefore, if the call is not empty we need to do the rendezvous -- if the accept body is not Null_Body. -- ????? -- aren't the first two conditions below redundant? if Self_Id.Chosen_Index /= No_Rendezvous and then Self_Id.Common.Call /= null and then not Open_Accepts (Self_Id.Chosen_Index).Null_Body then Uninterpreted_Data := Self_Id.Common.Call.Uninterpreted_Data; pragma Assert (Self_Id.Deferral_Level = 1); Initialization.Defer_Abort_Nestable (Self_Id); -- Leave abort deferred until the accept body end if; STPO.Unlock (Self_Id); when Else_Selected => pragma Assert (Self_Id.Open_Accepts = null); STPO.Unlock (Self_Id); when Terminate_Selected => -- Terminate alternative is open Self_Id.Open_Accepts := Open_Accepts; Self_Id.Common.State := Acceptor_Sleep; STPO.Unlock (Self_Id); -- ????? -- We need to check if a signal is pending on an open interrupt -- entry. Otherwise this task would become potentially terminatable -- and, if none of the siblings are active -- any more, the task could not wake up any more, even though a -- signal might be pending on an open interrupt entry. -- ------------- -- This comment paragraph does not make sense. Is it obsolete? -- There was no code here to check for pending signals. -- Notify ancestors that this task is on a terminate alternative. Utilities.Make_Passive (Self_Id, Task_Completed => False); -- Wait for normal entry call or termination pragma Assert (Self_Id.ATC_Nesting_Level = 1); STPO.Write_Lock (Self_Id); loop Initialization.Poll_Base_Priority_Change (Self_Id); exit when Self_Id.Open_Accepts = null; Sleep (Self_Id, Acceptor_Sleep); end loop; Self_Id.Common.State := Runnable; pragma Assert (Self_Id.Open_Accepts = null); if Self_Id.Terminate_Alternative then -- An entry call should have reset this to False, -- so we must be aborted. -- We cannot be in an async. select, since that -- is not legal, so the abort must be of the entire -- task. Therefore, we do not need to cancel the -- terminate alternative. The cleanup will be done -- in Complete_Master. pragma Assert (Self_Id.Pending_ATC_Level = 0); pragma Assert (Self_Id.Awake_Count = 0); -- Trust that it is OK to fall through. null; else -- Self_Id.Common.Call and Self_Id.Chosen_Index -- should already be updated by the Caller. if Self_Id.Chosen_Index /= No_Rendezvous and then not Open_Accepts (Self_Id.Chosen_Index).Null_Body then Uninterpreted_Data := Self_Id.Common.Call.Uninterpreted_Data; pragma Assert (Self_Id.Deferral_Level = 1); -- We need an extra defer here, to keep abort -- deferred until we get into the accept body Initialization.Defer_Abort_Nestable (Self_Id); end if; end if; STPO.Unlock (Self_Id); when No_Alternative_Open => -- In this case, Index will be No_Rendezvous on return, which -- should cause a Program_Error if it is not a Delay_Mode. -- If delay alternative exists (Delay_Mode) we should suspend -- until the delay expires. Self_Id.Open_Accepts := null; if Select_Mode = Delay_Mode then Self_Id.Common.State := Delay_Sleep; loop Initialization.Poll_Base_Priority_Change (Self_Id); exit when Self_Id.Pending_ATC_Level < Self_Id.ATC_Nesting_Level; Sleep (Self_Id, Delay_Sleep); end loop; Self_Id.Common.State := Runnable; STPO.Unlock (Self_Id); else STPO.Unlock (Self_Id); Initialization.Undefer_Abort (Self_Id); Ada.Exceptions.Raise_Exception (Program_Error'Identity, "Entry call not a delay mode"); end if; end case; -- Caller has been chosen. -- Self_Id.Common.Call should already be updated by the Caller. -- Self_Id.Chosen_Index should either be updated by the Caller -- or by Test_Selective_Wait. -- On return, we sill start rendezvous unless the accept body is -- null. In the latter case, we will have already completed the RV. Index := Self_Id.Chosen_Index; Initialization.Undefer_Abort_Nestable (Self_Id); end Selective_Wait; ------------------------------------ -- Setup_For_Rendezvous_With_Body -- ------------------------------------ -- Call this only with abort deferred and holding lock of Acceptor. procedure Setup_For_Rendezvous_With_Body (Entry_Call : Entry_Call_Link; Acceptor : Task_ID) is begin Entry_Call.Acceptor_Prev_Call := Acceptor.Common.Call; Acceptor.Common.Call := Entry_Call; if Entry_Call.State = Now_Abortable then Entry_Call.State := Was_Abortable; end if; Boost_Priority (Entry_Call, Acceptor); end Setup_For_Rendezvous_With_Body; ---------------- -- Task_Count -- ---------------- -- Compiler interface only. Do not call from within the RTS. function Task_Count (E : Task_Entry_Index) return Natural is Self_Id : constant Task_ID := STPO.Self; Return_Count : Natural; begin Initialization.Defer_Abort (Self_Id); STPO.Write_Lock (Self_Id); Return_Count := Queuing.Count_Waiting (Self_Id.Entry_Queues (E)); STPO.Unlock (Self_Id); Initialization.Undefer_Abort (Self_Id); return Return_Count; end Task_Count; ---------------------- -- Task_Do_Or_Queue -- ---------------------- -- Call this only with abort deferred and holding no locks. -- May propagate an exception, including Abort_Signal & Tasking_Error. -- ????? -- See Check_Callable. Check all call contexts to verify -- it is OK to raise an exception. -- Find out whether Entry_Call can be accepted immediately. -- If the Acceptor is not callable, raise Tasking_Error. -- If the rendezvous can start, initiate it. -- If the accept-body is trivial, also complete the rendezvous. -- If the acceptor is not ready, enqueue the call. -- ????? -- This should have a special case for Accept_Call and -- Accept_Trivial, so that -- we don't have the loop setup overhead, below. -- ????? -- The call state Done is used here and elsewhere to include -- both the case of normal successful completion, and the case -- of an exception being raised. The difference is that if an -- exception is raised no one will pay attention to the fact -- that State = Done. Instead the exception will be raised in -- Undefer_Abort, and control will skip past the place where -- we normally would resume from an entry call. function Task_Do_Or_Queue (Self_ID : Task_ID; Entry_Call : Entry_Call_Link; With_Abort : Boolean) return Boolean is E : constant Task_Entry_Index := Task_Entry_Index (Entry_Call.E); Old_State : constant Entry_Call_State := Entry_Call.State; Acceptor : constant Task_ID := Entry_Call.Called_Task; Parent : constant Task_ID := Acceptor.Common.Parent; Parent_Locked : Boolean := False; Null_Body : Boolean; begin pragma Assert (not Queuing.Onqueue (Entry_Call)); -- We rely that the call is off-queue for protection, -- that the caller will not exit the Entry_Caller_Sleep, -- and so will not reuse the call record for another call. -- We rely on the Caller's lock for call State mod's. -- We can't lock Acceptor.Parent while holding Acceptor, -- so lock it in advance if we expect to need to lock it. -- ????? -- Is there some better solution? if Acceptor.Terminate_Alternative then STPO.Write_Lock (Parent); Parent_Locked := True; end if; STPO.Write_Lock (Acceptor); -- If the acceptor is not callable, abort the call -- and raise Tasking_Error. The call is not aborted -- for an asynchronous call, since Cancel_Task_Entry_Call -- will do the cancelation in that case. -- ????? ..... -- Does the above still make sense? if not Acceptor.Callable then STPO.Unlock (Acceptor); if Parent_Locked then STPO.Unlock (Acceptor.Common.Parent); end if; pragma Assert (Entry_Call.State < Done); -- In case we are not the caller, set up the caller -- to raise Tasking_Error when it wakes up. STPO.Write_Lock (Entry_Call.Self); Entry_Call.Exception_To_Raise := Tasking_Error'Identity; Initialization.Wakeup_Entry_Caller (Self_ID, Entry_Call, Done); STPO.Unlock (Entry_Call.Self); return False; end if; -- Try to serve the call immediately. if Acceptor.Open_Accepts /= null then for J in Acceptor.Open_Accepts'Range loop if Entry_Call.E = Entry_Index (Acceptor.Open_Accepts (J).S) then -- Commit acceptor to rendezvous with us. Acceptor.Chosen_Index := J; Null_Body := Acceptor.Open_Accepts (J).Null_Body; Acceptor.Open_Accepts := null; -- Prevent abort while call is being served. if Entry_Call.State = Now_Abortable then Entry_Call.State := Was_Abortable; end if; if Acceptor.Terminate_Alternative then -- Cancel terminate alternative. -- See matching code in Selective_Wait and -- Vulnerable_Complete_Master. Acceptor.Terminate_Alternative := False; Acceptor.Awake_Count := Acceptor.Awake_Count + 1; if Acceptor.Awake_Count = 1 then -- Notify parent that acceptor is awake. pragma Assert (Parent.Awake_Count > 0); Parent.Awake_Count := Parent.Awake_Count + 1; if Parent.Common.State = Master_Completion_Sleep and then Acceptor.Master_of_Task = Parent.Master_Within then Parent.Common.Wait_Count := Parent.Common.Wait_Count + 1; end if; end if; end if; if Null_Body then -- Rendezvous is over immediately. STPO.Wakeup (Acceptor, Acceptor_Sleep); STPO.Unlock (Acceptor); if Parent_Locked then STPO.Unlock (Parent); end if; STPO.Write_Lock (Entry_Call.Self); Initialization.Wakeup_Entry_Caller (Self_ID, Entry_Call, Done); STPO.Unlock (Entry_Call.Self); else Setup_For_Rendezvous_With_Body (Entry_Call, Acceptor); -- For terminate_alternative, acceptor may not be -- asleep yet, so we skip the wakeup if Acceptor.Common.State /= Runnable then STPO.Wakeup (Acceptor, Acceptor_Sleep); end if; STPO.Unlock (Acceptor); if Parent_Locked then STPO.Unlock (Parent); end if; end if; return True; end if; end loop; -- The acceptor is accepting, but not this entry. end if; -- If the acceptor was ready to accept this call, -- we would not have gotten this far, so now we should -- (re)enqueue the call, if the mode permits that. if Entry_Call.Mode /= Conditional_Call or else not With_Abort then -- Timed_Call, Simple_Call, or Asynchronous_Call Queuing.Enqueue (Acceptor.Entry_Queues (E), Entry_Call); -- Update abortability of call pragma Assert (Old_State < Done); Entry_Call.State := New_State (With_Abort, Entry_Call.State); STPO.Unlock (Acceptor); if Parent_Locked then STPO.Unlock (Parent); end if; if Old_State /= Entry_Call.State and then Entry_Call.State = Now_Abortable and then Entry_Call.Mode > Simple_Call and then -- Asynchronous_Call or Conditional_Call Entry_Call.Self /= Self_ID then -- Because of ATCB lock ordering rule STPO.Write_Lock (Entry_Call.Self); if Entry_Call.Self.Common.State = Async_Select_Sleep then -- Caller may not yet have reached wait-point STPO.Wakeup (Entry_Call.Self, Async_Select_Sleep); end if; STPO.Unlock (Entry_Call.Self); end if; else -- Conditional_Call and With_Abort STPO.Unlock (Acceptor); if Parent_Locked then STPO.Unlock (Parent); end if; STPO.Write_Lock (Entry_Call.Self); pragma Assert (Entry_Call.State >= Was_Abortable); Initialization.Wakeup_Entry_Caller (Self_ID, Entry_Call, Cancelled); STPO.Unlock (Entry_Call.Self); end if; return True; end Task_Do_Or_Queue; --------------------- -- Task_Entry_Call -- --------------------- procedure Task_Entry_Call (Acceptor : Task_ID; E : Task_Entry_Index; Uninterpreted_Data : System.Address; Mode : Call_Modes; Rendezvous_Successful : out Boolean) is Self_Id : constant Task_ID := STPO.Self; Entry_Call : Entry_Call_Link; begin if Mode = Simple_Call or else Mode = Conditional_Call then Call_Synchronous (Acceptor, E, Uninterpreted_Data, Mode, Rendezvous_Successful); else -- This is an asynchronous call -- Abortion must already be deferred by the compiler-generated -- code. Without this, an abortion that occurs between the time -- that this call is made and the time that the abortable part's -- cleanup handler is set up might miss the cleanup handler and -- leave the call pending. Self_Id.ATC_Nesting_Level := Self_Id.ATC_Nesting_Level + 1; pragma Debug (Debug.Trace (Self_Id, "TEC: entered ATC level: " & ATC_Level'Image (Self_Id.ATC_Nesting_Level), 'A')); Entry_Call := Self_Id.Entry_Calls (Self_Id.ATC_Nesting_Level)'Access; Entry_Call.Next := null; Entry_Call.Mode := Mode; Entry_Call.Cancellation_Attempted := False; Entry_Call.State := Not_Yet_Abortable; Entry_Call.E := Entry_Index (E); Entry_Call.Prio := Get_Priority (Self_Id); Entry_Call.Uninterpreted_Data := Uninterpreted_Data; Entry_Call.Called_Task := Acceptor; Entry_Call.Called_PO := Null_Address; Entry_Call.Exception_To_Raise := Ada.Exceptions.Null_Id; if not Task_Do_Or_Queue (Self_Id, Entry_Call, With_Abort => True) then Self_Id.ATC_Nesting_Level := Self_Id.ATC_Nesting_Level - 1; pragma Debug (Debug.Trace (Self_Id, "TEC: exited to ATC level: " & ATC_Level'Image (Self_Id.ATC_Nesting_Level), 'A')); Initialization.Undefer_Abort (Self_Id); raise Tasking_Error; end if; -- The following is special for async. entry calls. -- If the call was not queued abortably, we need to wait until -- it is before proceeding with the abortable part. -- Wait_Until_Abortable can be called unconditionally here, -- but it is expensive. if Entry_Call.State < Was_Abortable then Entry_Calls.Wait_Until_Abortable (Self_Id, Entry_Call); end if; -- Note: following assignment needs to be atomic. Rendezvous_Successful := Entry_Call.State = Done; end if; end Task_Entry_Call; ----------------------- -- Task_Entry_Caller -- ----------------------- -- Compiler interface only. function Task_Entry_Caller (D : Task_Entry_Nesting_Depth) return Task_ID is Self_Id : constant Task_ID := STPO.Self; Entry_Call : Entry_Call_Link; begin Entry_Call := Self_Id.Common.Call; for Depth in 1 .. D loop Entry_Call := Entry_Call.Acceptor_Prev_Call; pragma Assert (Entry_Call /= null); end loop; return Entry_Call.Self; end Task_Entry_Caller; -------------------------- -- Timed_Selective_Wait -- -------------------------- -- Compiler interface only. Do not call from within the RTS. procedure Timed_Selective_Wait (Open_Accepts : Accept_List_Access; Select_Mode : Select_Modes; Uninterpreted_Data : out System.Address; Timeout : Duration; Mode : Delay_Modes; Index : out Select_Index) is Self_Id : constant Task_ID := STPO.Self; Treatment : Select_Treatment; Entry_Call : Entry_Call_Link; Caller : Task_ID; Selection : Select_Index; Open_Alternative : Boolean; Timedout : Boolean := False; Yielded : Boolean := False; begin pragma Assert (Select_Mode = Delay_Mode); Initialization.Defer_Abort (Self_Id); -- If we are aborted here, the effect will be pending STPO.Write_Lock (Self_Id); if not Self_Id.Callable then pragma Assert (Self_Id.Pending_ATC_Level = 0); pragma Assert (Self_Id.Pending_Action); STPO.Unlock (Self_Id); Initialization.Undefer_Abort (Self_Id); -- Should never get here ??? pragma Assert (False); raise Standard'Abort_Signal; end if; -- If someone completed this task, this task should not try to -- access its pending entry calls or queues in this case, as they -- are being emptied. Wait for abortion to kill us. -- ????? -- Recheck the correctness of the above, now that we have made -- changes. pragma Assert (Open_Accepts /= null); Queuing.Select_Task_Entry_Call (Self_Id, Open_Accepts, Entry_Call, Selection, Open_Alternative); -- Determine the kind and disposition of the select. Treatment := Default_Treatment (Select_Mode); Self_Id.Chosen_Index := No_Rendezvous; if Open_Alternative then if Entry_Call /= null then if Open_Accepts (Selection).Null_Body then Treatment := Accept_Alternative_Completed; else Setup_For_Rendezvous_With_Body (Entry_Call, Self_Id); Treatment := Accept_Alternative_Selected; end if; Self_Id.Chosen_Index := Selection; elsif Treatment = No_Alternative_Open then Treatment := Accept_Alternative_Open; end if; end if; -- Handle the select according to the disposition selected above. case Treatment is when Accept_Alternative_Selected => -- Ready to rendezvous -- In this case the accept body is not Null_Body. Defer abortion -- until it gets into the accept body. Uninterpreted_Data := Self_Id.Common.Call.Uninterpreted_Data; Initialization.Defer_Abort (Self_Id); STPO.Unlock (Self_Id); when Accept_Alternative_Completed => -- Rendezvous is over STPO.Unlock (Self_Id); Caller := Entry_Call.Self; STPO.Write_Lock (Caller); Initialization.Wakeup_Entry_Caller (Self_Id, Entry_Call, Done); STPO.Unlock (Caller); when Accept_Alternative_Open => -- Wait for caller. Self_Id.Open_Accepts := Open_Accepts; -- Wait for a normal call and a pending action until the -- Wakeup_Time is reached. Self_Id.Common.State := Acceptor_Sleep; loop Initialization.Poll_Base_Priority_Change (Self_Id); exit when Self_Id.Open_Accepts = null; if Timedout then Sleep (Self_Id, Acceptor_Sleep); else STPO.Timed_Sleep (Self_Id, Timeout, Mode, Acceptor_Sleep, Timedout, Yielded); end if; if Timedout then Self_Id.Open_Accepts := null; end if; end loop; Self_Id.Common.State := Runnable; -- Self_Id.Common.Call should already be updated by the Caller if -- not aborted. It might also be ready to do rendezvous even if -- this wakes up due to an abortion. -- Therefore, if the call is not empty we need to do the rendezvous -- if the accept body is not Null_Body. if Self_Id.Chosen_Index /= No_Rendezvous and then Self_Id.Common.Call /= null and then not Open_Accepts (Self_Id.Chosen_Index).Null_Body then Uninterpreted_Data := Self_Id.Common.Call.Uninterpreted_Data; pragma Assert (Self_Id.Deferral_Level = 1); Initialization.Defer_Abort_Nestable (Self_Id); -- Leave abort deferred until the accept body end if; STPO.Unlock (Self_Id); if not Yielded then Yield; end if; when No_Alternative_Open => -- In this case, Index will be No_Rendezvous on return. We sleep -- for the time we need to. -- Wait for a signal or timeout. A wakeup can be made -- for several reasons: -- 1) Delay is expired -- 2) Pending_Action needs to be checked -- (Abortion, Priority change) -- 3) Spurious wakeup Self_Id.Open_Accepts := null; Self_Id.Common.State := Acceptor_Sleep; Initialization.Poll_Base_Priority_Change (Self_Id); STPO.Timed_Sleep (Self_Id, Timeout, Mode, Acceptor_Sleep, Timedout, Yielded); Self_Id.Common.State := Runnable; STPO.Unlock (Self_Id); if not Yielded then Yield; end if; when others => -- Should never get here ??? pragma Assert (False); null; end case; -- Caller has been chosen -- Self_Id.Common.Call should already be updated by the Caller -- Self_Id.Chosen_Index should either be updated by the Caller -- or by Test_Selective_Wait Index := Self_Id.Chosen_Index; Initialization.Undefer_Abort_Nestable (Self_Id); -- Start rendezvous, if not already completed end Timed_Selective_Wait; --------------------------- -- Timed_Task_Entry_Call -- --------------------------- -- Compiler interface only. Do not call from within the RTS. procedure Timed_Task_Entry_Call (Acceptor : Task_ID; E : Task_Entry_Index; Uninterpreted_Data : System.Address; Timeout : Duration; Mode : Delay_Modes; Rendezvous_Successful : out Boolean) is Self_Id : constant Task_ID := STPO.Self; Level : ATC_Level; Entry_Call : Entry_Call_Link; begin Initialization.Defer_Abort (Self_Id); Self_Id.ATC_Nesting_Level := Self_Id.ATC_Nesting_Level + 1; pragma Debug (Debug.Trace (Self_Id, "TTEC: entered ATC level: " & ATC_Level'Image (Self_Id.ATC_Nesting_Level), 'A')); Level := Self_Id.ATC_Nesting_Level; Entry_Call := Self_Id.Entry_Calls (Level)'Access; Entry_Call.Next := null; Entry_Call.Mode := Timed_Call; Entry_Call.Cancellation_Attempted := False; -- If this is a call made inside of an abort deferred region, -- the call should be never abortable. if Self_Id.Deferral_Level > 1 then Entry_Call.State := Never_Abortable; else Entry_Call.State := Now_Abortable; end if; Entry_Call.E := Entry_Index (E); Entry_Call.Prio := Get_Priority (Self_Id); Entry_Call.Uninterpreted_Data := Uninterpreted_Data; Entry_Call.Called_Task := Acceptor; Entry_Call.Called_PO := Null_Address; Entry_Call.Exception_To_Raise := Ada.Exceptions.Null_Id; -- Note: the caller will undefer abortion on return (see WARNING above) if not Task_Do_Or_Queue (Self_Id, Entry_Call, With_Abort => True) then Self_Id.ATC_Nesting_Level := Self_Id.ATC_Nesting_Level - 1; pragma Debug (Debug.Trace (Self_Id, "TTEC: exited to ATC level: " & ATC_Level'Image (Self_Id.ATC_Nesting_Level), 'A')); Initialization.Undefer_Abort (Self_Id); raise Tasking_Error; end if; Entry_Calls.Wait_For_Completion_With_Timeout (Self_Id, Entry_Call, Timeout, Mode); Rendezvous_Successful := Entry_Call.State = Done; Initialization.Undefer_Abort (Self_Id); Entry_Calls.Check_Exception (Self_Id, Entry_Call); end Timed_Task_Entry_Call; ------------------- -- Wait_For_Call -- ------------------- -- Call this only with abort deferred and holding lock of Self_Id. -- Wait for normal call and a pending action. procedure Wait_For_Call (Self_Id : Task_ID) is begin Self_Id.Common.State := Acceptor_Sleep; loop Initialization.Poll_Base_Priority_Change (Self_Id); exit when Self_Id.Open_Accepts = null; Sleep (Self_Id, Acceptor_Sleep); end loop; Self_Id.Common.State := Runnable; end Wait_For_Call; end System.Tasking.Rendezvous;
with Interfaces.C, System; use type Interfaces.C.int, System.Address; package body FLTK.Images is function new_fl_image (W, H, D : in Interfaces.C.int) return System.Address; pragma Import (C, new_fl_image, "new_fl_image"); pragma Inline (new_fl_image); procedure free_fl_image (I : in System.Address); pragma Import (C, free_fl_image, "free_fl_image"); pragma Inline (free_fl_image); function fl_image_get_rgb_scaling return Interfaces.C.int; pragma Import (C, fl_image_get_rgb_scaling, "fl_image_get_rgb_scaling"); pragma Inline (fl_image_get_rgb_scaling); procedure fl_image_set_rgb_scaling (T : in Interfaces.C.int); pragma Import (C, fl_image_set_rgb_scaling, "fl_image_set_rgb_scaling"); pragma Inline (fl_image_set_rgb_scaling); function fl_image_copy (I : in System.Address; W, H : in Interfaces.C.int) return System.Address; pragma Import (C, fl_image_copy, "fl_image_copy"); pragma Inline (fl_image_copy); function fl_image_copy2 (I : in System.Address) return System.Address; pragma Import (C, fl_image_copy2, "fl_image_copy2"); pragma Inline (fl_image_copy2); procedure fl_image_color_average (I : in System.Address; C : in Interfaces.C.int; B : in Interfaces.C.C_float); pragma Import (C, fl_image_color_average, "fl_image_color_average"); pragma Inline (fl_image_color_average); procedure fl_image_desaturate (I : in System.Address); pragma Import (C, fl_image_desaturate, "fl_image_desaturate"); pragma Inline (fl_image_desaturate); procedure fl_image_inactive (I : in System.Address); pragma Import (C, fl_image_inactive, "fl_image_inactive"); pragma Inline (fl_image_inactive); function fl_image_w (I : in System.Address) return Interfaces.C.int; pragma Import (C, fl_image_w, "fl_image_w"); pragma Inline (fl_image_w); function fl_image_h (I : in System.Address) return Interfaces.C.int; pragma Import (C, fl_image_h, "fl_image_h"); pragma Inline (fl_image_h); function fl_image_d (I : in System.Address) return Interfaces.C.int; pragma Import (C, fl_image_d, "fl_image_d"); pragma Inline (fl_image_d); procedure fl_image_draw (I : in System.Address; X, Y : in Interfaces.C.int); pragma Import (C, fl_image_draw, "fl_image_draw"); pragma Inline (fl_image_draw); procedure fl_image_draw2 (I : in System.Address; X, Y, W, H, CX, CY : in Interfaces.C.int); pragma Import (C, fl_image_draw2, "fl_image_draw2"); pragma Inline (fl_image_draw2); procedure fl_image_draw_empty (I : in System.Address; X, Y : in Interfaces.C.int); pragma Import (C, fl_image_draw_empty, "fl_image_draw_empty"); pragma Inline (fl_image_draw_empty); overriding procedure Finalize (This : in out Image) is begin if This.Void_Ptr /= System.Null_Address and then This in Image'Class then free_fl_image (This.Void_Ptr); This.Void_Ptr := System.Null_Address; end if; end Finalize; package body Forge is function Create (Width, Height, Depth : in Natural) return Image is begin return This : Image do This.Void_Ptr := new_fl_image (Interfaces.C.int (Width), Interfaces.C.int (Height), Interfaces.C.int (Depth)); case fl_image_fail (This.Void_Ptr) is when 1 => raise No_Image_Error; when 2 => raise File_Access_Error; when 3 => raise Format_Error; when others => null; end case; end return; end Create; end Forge; function Get_Copy_Algorithm return Scaling_Kind is begin return Scaling_Kind'Val (fl_image_get_rgb_scaling); end Get_Copy_Algorithm; procedure Set_Copy_Algorithm (To : in Scaling_Kind) is begin fl_image_set_rgb_scaling (Scaling_Kind'Pos (To)); end Set_Copy_Algorithm; function Copy (This : in Image; Width, Height : in Natural) return Image'Class is begin return Copied : Image do Copied.Void_Ptr := fl_image_copy (This.Void_Ptr, Interfaces.C.int (Width), Interfaces.C.int (Height)); end return; end Copy; function Copy (This : in Image) return Image'Class is begin return Copied : Image do Copied.Void_Ptr := fl_image_copy2 (This.Void_Ptr); end return; end Copy; procedure Color_Average (This : in out Image; Col : in Color; Amount : in Blend) is begin fl_image_color_average (This.Void_Ptr, Interfaces.C.int (Col), Interfaces.C.C_float (Amount)); end Color_Average; procedure Desaturate (This : in out Image) is begin fl_image_desaturate (This.Void_Ptr); end Desaturate; procedure Inactive (This : in out Image) is begin fl_image_inactive (This.Void_Ptr); end Inactive; function Is_Empty (This : in Image) return Boolean is begin return fl_image_fail (This.Void_Ptr) /= 0; end Is_Empty; function Get_W (This : in Image) return Natural is begin return Natural (fl_image_w (This.Void_Ptr)); end Get_W; function Get_H (This : in Image) return Natural is begin return Natural (fl_image_h (This.Void_Ptr)); end Get_H; function Get_D (This : in Image) return Natural is begin return Natural (fl_image_d (This.Void_Ptr)); end Get_D; procedure Draw (This : in Image; X, Y : in Integer) is begin fl_image_draw (This.Void_Ptr, Interfaces.C.int (X), Interfaces.C.int (Y)); end Draw; procedure Draw (This : in Image; X, Y, W, H : in Integer; CX, CY : in Integer := 0) is begin fl_image_draw2 (This.Void_Ptr, Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H), Interfaces.C.int (CX), Interfaces.C.int (CY)); end Draw; procedure Draw_Empty (This : in Image; X, Y : in Integer) is begin fl_image_draw_empty (This.Void_Ptr, Interfaces.C.int (X), Interfaces.C.int (Y)); end Draw_Empty; end FLTK.Images;
with Ada.Text_IO; procedure Unbounded_Compile_Time_Calculation is F_10 : constant Integer := 10*9*8*7*6*5*4*3*2*1; A_11_15 : constant Integer := 15*14*13*12*11; A_16_20 : constant Integer := 20*19*18*17*16; begin Ada.Text_IO.Put_Line -- prints out ("20 choose 10 =" & Integer'Image((A_11_15 * A_16_20 * F_10) / (F_10 * F_10))); -- Ada.Text_IO.Put_Line -- would not compile -- ("Factorial(20) =" & Integer'Image(A_11_15 * A_16_20 * F_10)); end Unbounded_Compile_Time_Calculation;
with System; use System; with Interfaces; use Interfaces; package Memory is Flash_Start : Unsigned_16 with Import, Convention => Asm, External_Name => "__flash_start"; Flash_Size : Unsigned_16 with Import, Convention => Asm, External_Name => "__flash_size"; Info_Start : Unsigned_16 with Import, Convention => Asm, External_Name => "__info_start"; Info_Size : Unsigned_16 with Import, Convention => Asm, External_Name => "__info_size"; Flash_Segment_Size : constant Unsigned_16 := 512; Info_Segment_Size : constant Unsigned_16 := 64; type Flash_Memory_Range is new Unsigned_16 range Flash_Start .. Flash_Start + Flash_Size - 2; type Info_Memory_Range is new Unsigned_16 range Info_Start .. Info_Start + Info_Size - 2; type Flash_Segment_Range is new Unsigned_16 range 1 .. Flash_Size / Flash_Segment_Size; Flash_Memory : array (Flash_Memory_Range) of Unsigned_8 with Address => System'To_Address (Flash_Start); Info_Memory : array (Info_Memory_Range) of Unsigned_8 with Address => System'To_Address (Info_Start); function "+" (Addr : Flash_Memory_Range; Offset : Unsigned_16) return Flash_Memory_Range; end Memory;
-- Copyright 2019 Simon Symeonidis (psyomn) -- -- 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.Calendar; with Ada.Strings; use Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with GNAT.Calendar.Time_IO; with Common_Utils; use Common_Utils; package body Response_Helpers is function Headers (Status : HTTP_Status.Code) return String is Content_Type : constant String := "Content-Type: text/html; charset=iso-8859-1"; begin return First_Header_Line (Status) & Response_Date & CRLF & "Server: ash" & CRLF & Content_Type & CRLF & "Content-Length: "; end Headers; function Response_Date return String is package ac renames Ada.Calendar; package gct renames GNAT.Calendar.Time_IO; Current_Time : constant ac.Time := ac.Clock; Format : constant gct.Picture_String := "%a, %d %B %Y %H:%M:%S EST"; Field_Name : constant String := "Date: "; Result : constant String := Field_Name & gct.Image (Current_Time, Format); begin return Result; end Response_Date; function Make_Response (Status : HTTP_Status.Code; S : String) return String is Length : constant Positive := S'Length; Length_Str : constant String := Trim ( Source => Positive'Image (Length), Side => Both ); begin return Headers (Status) & Length_Str & CRLF & CRLF & S; end Make_Response; function First_Header_Line (Status : HTTP_Status.Code) return String is use HTTP_Status; Status_Str : constant String := Integer_To_Trimmed_String (Integer (Status)); Message : constant String := Message_Of_Code (Status); HTTP_Version : constant String := "1.0"; Result : constant String := "HTTP/" & HTTP_Version & " " & Status_Str & " " & Message & CRLF; begin return Result; end First_Header_Line; end Response_Helpers;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . H I E _ B A C K _ E N D -- -- -- -- S p e c -- -- -- -- Copyright (C) 2001-2009, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package provides an interface used in HI-E mode to determine -- whether or not the back end can handle certain constructs in a manner -- that is consistent with certification requirements. -- The approach is to define entities which may or may not be present in -- a HI-E configured library. If the entity is present then the compiler -- operating in HI-E mode will allow the corresponding operation. If the -- entity is not present, the corresponding construct will be flagged as -- not permitted in High Integrity mode. -- The default version of this unit delivered with the HI-E compiler is -- configured in a manner appropriate for the target, but it is possible -- to reconfigure the run-time to change the settings as required. -- This unit is not used and never accessed by the compiler unless it is -- operating in HI-E mode, so the settings are irrelevant. However, we -- do include a standard version with all entities present in the standard -- run-time for use when pragma No_Run_Time is specified. package System.HIE_Back_End is type Dummy is null record; pragma Suppress_Initialization (Dummy); -- This is the type used for the entities below. No properties of this -- type are ever referenced, and in particular, the entities are defined -- as variables, but their values are never referenced HIE_64_Bit_Divides : Dummy; -- This entity controls whether the front end allows 64-bit integer -- divide operations, including the case where division of 32-bit -- fixed-point operands requires 64-bit arithmetic. This can safely -- be set as High_Integrity on 64-bit machines which provide this -- operation as a native instruction, but on most 32-bit machines -- a run time call (e.g. to __divdi3 in gcclib) is required. If a -- certifiable version of this routine is available, then setting -- this entity to High_Integrity with a pragma will cause appropriate -- calls to be generated, allowing 64-bit integer division operations. HIE_Long_Shifts : Dummy; -- This entity controls whether the front end allows generation of -- long shift instructions, i.e. shifts that operate on 64-bit values. -- Such shifts are required for the implementation of fixed-point -- types longer than 32 bits. This can safely be set as High_Integrity -- on 64-bit machines that provide this operation at the hardware level, -- but on some 32-bit machines a run time call is required. If there -- is a certifiable version available of the relevant run-time routines, -- then setting this entity to High_Integrity with a pragma will cause -- appropriate calls to be generated, allowing the declaration and use -- of fixed-point types longer than 32 bits. HIE_Aggregates : Dummy; -- In the general case, the use of aggregates may generate calls -- to run-time routines in the C library, including memset, memcpy, -- memmove, and bcopy. This entity can be set to High_Integrity with -- a pragma if certifiable versions of all these routines are available, -- in which case aggregates are permitted in HI-E mode. Otherwise the -- HI-E compiler will reject any use of aggregates. HIE_Composite_Assignments : Dummy; -- The assignment of composite objects other than small records and -- arrays whose size is 64-bits or less and is set by an explicit -- size clause may generate calls to memcpy, memmove, and bcopy. -- If certifiable versions of all these routines are available, then -- this entity may be set to High_Integrity using a pragma, in which -- case such assignments are permitted. Otherwise the HI-E compiler -- will reject any such composite assignments. end System.HIE_Back_End;
package PolyPaver.Exact is --# function Square (X : Float) return Float; --# function Int_Power (X : Float; N : Integer) return Float; --# function Sqrt (X : Float) return Float; --# function Exp (X : Float) return Float; --# function Sin (X : Float) return Float; --# function Cos (X : Float) return Float; --# function Pi return Float; --# function Integral (Lo,Hi,Integrand : Float) return Float; --# function Integration_Variable return Float; end PolyPaver.Exact;
-- -*- Mode: Ada -*- -- Filename : last_chance_handler.ads -- Description : Definition of the exception handler for the kernel. -- Author : Luke A. Guest -- Created On : Thu Jun 14 12:06:21 2012 -- Licence : See LICENCE in the root directory. with System; procedure Last_Chance_Handler (Source_Location : System.Address; Line : Integer); pragma Export (C, Last_Chance_Handler, "__gnat_last_chance_handler"); pragma Preelaborate (Last_Chance_Handler);
----------------------------------------------------------------------- -- util-events-channel -- Event Channels -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 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 Ada.Strings.Unbounded; with Ada.Containers.Doubly_Linked_Lists; -- The <b>Util.Events.Channels</b> package implements a publish/subscribe event -- channel. It is inspired from Event pattern and CosEvent service. package Util.Events.Channels is type Subscriber is limited interface; type Subscriber_Access is access all Subscriber'Class; procedure Receive_Event (Sub : in out Subscriber; Item : in Event'Class) is abstract; ---------------------- -- Event Channel ---------------------- -- Channel on which events are pushed. type Channel is tagged limited private; type Channel_Access is access all Channel'Class; -- Get the name of this event channel. function Get_Name (C : Channel) return String; -- Post an event (may be asynchronous) procedure Post (To : in out Channel; Item : in Event'Class); -- Subscribe to events sent on the event channel. procedure Subscribe (To : in out Channel; Client : in Subscriber_Access); -- Unsubscribe to events sent on the event channel. procedure Unsubscribe (To : in out Channel; Client : in Subscriber_Access); type Channel_Creator is access function (Name : String) return Channel_Access; -- Create an event channel with the given name. The type of channel -- is controlled by <b>Kind</b>. function Create (Name : String; Kind : String) return Channel_Access; -- Create an event channel that post the event immediately. -- This is similar to calling <b>Create</b> with <b>"direct"</b> as kind. function Create_Direct_Channel (Name : String) return Channel_Access; private package Containers is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Subscriber_Access); subtype List is Containers.List; type Channel is tagged limited record Name : Ada.Strings.Unbounded.Unbounded_String; Clients : List; end record; end Util.Events.Channels;
with Lumen.Image; package Noise is function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor; end Noise;
-- -- Copyright (C) 2022 Jeremy Grosser <jeremy@synack.me> -- -- SPDX-License-Identifier: BSD-3-Clause -- with HAL.GPIO; with HAL.SPI; with HAL; package ADXL345_SPI is generic Address : HAL.UInt8; type Register_Type is private; package Register is function Get (Port : not null HAL.SPI.Any_SPI_Port; CS : not null HAL.GPIO.Any_GPIO_Point; Value : out Register_Type) return Boolean; -- Returns False if the read failed function Get (Port : not null HAL.SPI.Any_SPI_Port; CS : not null HAL.GPIO.Any_GPIO_Point) return Register_Type; -- Raises Program_Error if the read failed function Set (Port : not null HAL.SPI.Any_SPI_Port; CS : not null HAL.GPIO.Any_GPIO_Point; Value : Register_Type) return Boolean; -- Returns False if the write failed procedure Set (Port : not null HAL.SPI.Any_SPI_Port; CS : not null HAL.GPIO.Any_GPIO_Point; Value : Register_Type); -- Raises Program_Error if the write failed end Register; end ADXL345_SPI;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2015, 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 Ada.Containers.Generic_Array_Sort; with Ada.Unchecked_Deallocation; package body Matreshka.Internals.Graphs is procedure Free is new Ada.Unchecked_Deallocation (Edge_Array, Edge_Array_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Array, Node_Array_Access); ----------- -- Clear -- ----------- procedure Clear (Self : in out Graph) is begin Free (Self.Nodes); Free (Self.Edges); Self.Last_Node := 0; Self.Last_Edge := 0; end Clear; package body Constructor is ----------- -- Clear -- ----------- procedure Clear (Self : in out Graph) is begin Free (Self.Nodes); Free (Self.Edges); Self.Last_Node := 0; Self.Last_Edge := 0; end Clear; ----------- -- Index -- ----------- function Index (Self : Node) return Node_Index is begin return Self.Index; end Index; -------------- -- New_Node -- -------------- function New_Node (Self : Graph'Class) return Node is procedure Resize; procedure Resize is begin if Self.Nodes = null or else Self.Nodes'Length < Self.Last_Node + 1 then declare -- 6 15 28 48 78 123 190 Old : Node_Array_Access := Self.Nodes; New_Length : constant Node_Index := (Self.Last_Node + 4) * 3 / 2; begin Self.Self.Nodes := new Node_Array (1 .. New_Length); if Old /= null then Self.Nodes.all (Old'Range) := Old.all; Free (Old); end if; end; end if; Self.Self.Last_Node := Self.Self.Last_Node + 1; end Resize; begin Resize; Self.Nodes (Self.Last_Node) := (Graph => <>, Index => Self.Last_Node, First => 1, Last => 0); return (Self.Self, Self.Last_Node); end New_Node; -------------- -- New_Edge -- -------------- procedure New_Edge (From, To : Node) is Ignore : constant Edge_Identifier := New_Edge (From, To); pragma Unreferenced (Ignore); begin null; end New_Edge; -------------- -- New_Edge -- -------------- function New_Edge (From, To : Node) return Edge_Identifier is procedure Resize; Self : constant Graph_Access := From.Graph; procedure Resize is begin if Self.Edges = null or else Self.Edges'Length < Self.Last_Edge + 1 then declare Old : Edge_Array_Access := Self.Edges; New_Length : constant Edge_Index := (Self.Last_Edge + 2) * 2; begin Self.Edges := new Edge_Array (1 .. New_Length); if Old /= null then Self.Edges.all (Old'Range) := Old.all; Free (Old); end if; end; end if; Self.Last_Edge := Self.Last_Edge + 1; end Resize; begin if To.Graph /= Self then raise Constraint_Error; end if; Resize; Self.Edges (Self.Last_Edge) := (Graph => <>, Index => Self.Last_Edge, Id => Edge_Identifier (Self.Last_Edge), Source => From.Index, Target => To.Index); return Edge_Identifier (Self.Last_Edge); end New_Edge; procedure Complete (Input : in out Graph'Class; Output : out Graphs.Graph) is function Less (Left, Right : Edge) return Boolean; function Less (Left, Right : Edge) return Boolean is begin return Left.Source < Right.Source or (Left.Source = Right.Source and Left.Index < Right.Index); end Less; procedure Sort is new Ada.Containers.Generic_Array_Sort (Edge_Index, Edge, Edge_Array, Less); begin Sort (Input.Edges (1 .. Input.Last_Edge)); for J in 1 .. Input.Last_Node loop Input.Nodes (J).Graph := Output.Self; Input.Nodes (J).First := 1; Input.Nodes (J).Last := 0; end loop; for J in 1 .. Input.Last_Edge loop Input.Edges (J).Graph := Output.Self; Input.Edges (J).Index := J; if Input.Nodes (Input.Edges (J).Source).Last = 0 then Input.Nodes (Input.Edges (J).Source).First := J; end if; Input.Nodes (Input.Edges (J).Source).Last := J; end loop; Output.Last_Node := Input.Last_Node; Output.Last_Edge := Input.Last_Edge; Output.Nodes := Input.Nodes; Output.Edges := Input.Edges; Input.Last_Node := 0; Input.Last_Edge := 0; Input.Nodes := null; Input.Edges := null; end Complete; end Constructor; ---------------- -- Edge_Count -- ---------------- function Edge_Count (Self : Graph) return Edge_List_Length is begin return Self.Last_Edge; end Edge_Count; ---------------- -- Edge_Count -- ---------------- function Edge_Count (Self : Node) return Edge_List_Length is begin return Self.Last - Self.First + 1; end Edge_Count; ------------- -- Edge_Id -- ------------- function Edge_Id (Self : Edge) return Edge_Identifier is begin return Self.Id; end Edge_Id; ---------------------- -- First_Edge_Index -- ---------------------- function First_Edge_Index (Self : Node) return Edge_Index is begin return Self.First; end First_Edge_Index; -------------- -- Get_Edge -- -------------- function Get_Edge (Self : Graph'Class; Index : Edge_Index) return Edge is begin return Self.Edges (Index); end Get_Edge; -------------- -- Get_Edge -- -------------- function Get_Edge (Self : Node'Class; Index : Edge_Index) return Edge is begin return Get_Edge (Self.Graph.all, Index); end Get_Edge; --------------- -- Get_Edges -- --------------- function Get_Edges (Self : Graph) return Edge_Array is begin return Self.Edges (1 .. Self.Last_Edge); end Get_Edges; -------------- -- Get_Node -- -------------- function Get_Node (Self : Graph'Class; Index : Node_Index) return Node is begin return Self.Nodes (Index); end Get_Node; --------------- -- Get_Nodes -- --------------- function Get_Nodes (Self : Graph) return Node_Array is begin return Self.Nodes (1 .. Self.Last_Node); end Get_Nodes; ----------- -- Index -- ----------- function Index (Self : Node) return Node_Index is begin return Self.Index; end Index; ----------- -- Index -- ----------- function Index (Self : Edge) return Edge_Index is begin return Self.Index; end Index; --------------------- -- Last_Edge_Index -- --------------------- function Last_Edge_Index (Self : Node) return Edge_List_Length is begin return Self.Last; end Last_Edge_Index; ---------------- -- Node_Count -- ---------------- function Node_Count (Self : Graph) return Node_List_Length is begin return Self.Last_Node; end Node_Count; -------------------- -- Outgoing_Edges -- -------------------- function Outgoing_Edges (Self : Node) return Edge_Array is begin return Self.Graph.Edges (Self.First .. Self.Last); end Outgoing_Edges; ----------------- -- Source_Node -- ----------------- function Source_Node (Self : Edge'Class) return Node is begin return Self.Graph.Nodes (Self.Source); end Source_Node; ----------------- -- Target_Node -- ----------------- function Target_Node (Self : Edge'Class) return Node is begin return Self.Graph.Nodes (Self.Target); end Target_Node; end Matreshka.Internals.Graphs;
-- This spec has been automatically generated from STM32L0x3.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.Firewall is pragma Preelaborate; --------------- -- Registers -- --------------- subtype FIREWALL_CSSA_ADD_Field is HAL.UInt16; -- Code segment start address type FIREWALL_CSSA_Register is record -- unspecified Reserved_0_7 : HAL.UInt8 := 16#0#; -- code segment start address ADD : FIREWALL_CSSA_ADD_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_CSSA_Register use record Reserved_0_7 at 0 range 0 .. 7; ADD at 0 range 8 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype FIREWALL_CSL_LENG_Field is HAL.UInt14; -- Code segment length type FIREWALL_CSL_Register is record -- unspecified Reserved_0_7 : HAL.UInt8 := 16#0#; -- code segment length LENG : FIREWALL_CSL_LENG_Field := 16#0#; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_CSL_Register use record Reserved_0_7 at 0 range 0 .. 7; LENG at 0 range 8 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; subtype FIREWALL_NVDSSA_ADD_Field is HAL.UInt16; -- Non-volatile data segment start address type FIREWALL_NVDSSA_Register is record -- unspecified Reserved_0_7 : HAL.UInt8 := 16#0#; -- Non-volatile data segment start address ADD : FIREWALL_NVDSSA_ADD_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_NVDSSA_Register use record Reserved_0_7 at 0 range 0 .. 7; ADD at 0 range 8 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype FIREWALL_NVDSL_LENG_Field is HAL.UInt14; -- Non-volatile data segment length type FIREWALL_NVDSL_Register is record -- unspecified Reserved_0_7 : HAL.UInt8 := 16#0#; -- Non-volatile data segment length LENG : FIREWALL_NVDSL_LENG_Field := 16#0#; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_NVDSL_Register use record Reserved_0_7 at 0 range 0 .. 7; LENG at 0 range 8 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; subtype FIREWALL_VDSSA_ADD_Field is HAL.UInt10; -- Volatile data segment start address type FIREWALL_VDSSA_Register is record -- unspecified Reserved_0_5 : HAL.UInt6 := 16#0#; -- Volatile data segment start address ADD : FIREWALL_VDSSA_ADD_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_VDSSA_Register use record Reserved_0_5 at 0 range 0 .. 5; ADD at 0 range 6 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype FIREWALL_VDSL_LENG_Field is HAL.UInt10; -- Volatile data segment length type FIREWALL_VDSL_Register is record -- unspecified Reserved_0_5 : HAL.UInt6 := 16#0#; -- Non-volatile data segment length LENG : FIREWALL_VDSL_LENG_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_VDSL_Register use record Reserved_0_5 at 0 range 0 .. 5; LENG at 0 range 6 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- Configuration register type FIREWALL_CR_Register is record -- Firewall pre alarm FPA : Boolean := False; -- Volatile data shared VDS : Boolean := False; -- Volatile data execution VDE : Boolean := False; -- unspecified Reserved_3_31 : HAL.UInt29 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_CR_Register use record FPA at 0 range 0 .. 0; VDS at 0 range 1 .. 1; VDE at 0 range 2 .. 2; Reserved_3_31 at 0 range 3 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Firewall type Firewall_Peripheral is record -- Code segment start address FIREWALL_CSSA : aliased FIREWALL_CSSA_Register; -- Code segment length FIREWALL_CSL : aliased FIREWALL_CSL_Register; -- Non-volatile data segment start address FIREWALL_NVDSSA : aliased FIREWALL_NVDSSA_Register; -- Non-volatile data segment length FIREWALL_NVDSL : aliased FIREWALL_NVDSL_Register; -- Volatile data segment start address FIREWALL_VDSSA : aliased FIREWALL_VDSSA_Register; -- Volatile data segment length FIREWALL_VDSL : aliased FIREWALL_VDSL_Register; -- Configuration register FIREWALL_CR : aliased FIREWALL_CR_Register; end record with Volatile; for Firewall_Peripheral use record FIREWALL_CSSA at 16#0# range 0 .. 31; FIREWALL_CSL at 16#4# range 0 .. 31; FIREWALL_NVDSSA at 16#8# range 0 .. 31; FIREWALL_NVDSL at 16#C# range 0 .. 31; FIREWALL_VDSSA at 16#10# range 0 .. 31; FIREWALL_VDSL at 16#14# range 0 .. 31; FIREWALL_CR at 16#20# range 0 .. 31; end record; -- Firewall Firewall_Periph : aliased Firewall_Peripheral with Import, Address => System'To_Address (16#40011C00#); end STM32_SVD.Firewall;
pragma License (Unrestricted); -- implementation unit package Ada.Strings.Naked_Maps.Set_Constants is pragma Preelaborate; function Decimal_Digit_Set return not null Character_Set_Access; function Hexadecimal_Digit_Set return not null Character_Set_Access; function ISO_646_Set return not null Character_Set_Access; function Character_Set return not null Character_Set_Access renames ISO_646_Set; -- 16#00# .. 16#7F# function Wide_Character_Set return not null Character_Set_Access; function Letter_Set return not null Character_Set_Access; -- Ll, Lu, Lt, Lm, Lo function Alphanumeric_Set return not null Character_Set_Access; -- Letter + Nd, Nl, No function Special_Set return not null Character_Set_Access; -- Mn, Me, Mc, Zs, Pd, Ps, Pe, Pc, Po, Sm, Sc, Sk, So, Pi, Pf function Graphic_Set return not null Character_Set_Access; -- Alphanumeric + Special end Ada.Strings.Naked_Maps.Set_Constants;
-- -- Copyright 2018 The wookey project team <wookey@ssi.gouv.fr> -- - Ryad Benadjila -- - Arnauld Michelizza -- - Mathieu Renard -- - Philippe Thierry -- - Philippe Trebuchet -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- with ada.unchecked_conversion; package body ewok.ipc with spark_mode => off is function to_task_id (eid : t_extended_task_id) return ewok.tasks_shared.t_task_id is pragma warnings (off); -- size may differ function convert is new ada.unchecked_conversion (t_extended_task_id, ewok.tasks_shared.t_task_id); pragma warnings (on); ret : constant ewok.tasks_shared.t_task_id := convert (eid); begin if ret'valid then return ret; else raise constraint_error; end if; end to_task_id; function to_ext_task_id (id : ewok.tasks_shared.t_task_id) return t_extended_task_id is pragma warnings (off); -- size may differ function convert is new ada.unchecked_conversion (ewok.tasks_shared.t_task_id, t_extended_task_id); pragma warnings (on); ret : constant t_extended_task_id := convert (id); begin if ret'valid then return ret; else raise constraint_error; end if; end to_ext_task_id; procedure init_endpoint (ep : in out t_endpoint) is begin ep.from := ewok.ipc.ID_UNUSED; ep.to := ewok.ipc.ID_UNUSED; ep.state := FREE; ep.size := 0; for i in ep.data'range loop ep.data(i) := 0; end loop; end init_endpoint; procedure init_endpoints is begin for i in ipc_endpoints'range loop init_endpoint (ipc_endpoints(i)); end loop; end init_endpoints; procedure get_endpoint (endpoint_a : out t_endpoint_access; success : out boolean) is begin for i in ipc_endpoints'range loop if ipc_endpoints(i).state = FREE then ipc_endpoints(i).state := READY; endpoint_a := ipc_endpoints(i)'access; success := true; return; end if; end loop; endpoint_a := NULL; success := false; end get_endpoint; procedure release_endpoint (endpoint_a : in t_endpoint_access) is begin init_endpoint (endpoint_a.all); end release_endpoint; end ewok.ipc;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; -- Afficher la somme des valeurs d'un série dont les valeurs sont lues au clavier. -- Pour marquer la fin de la série, la dernière valeur est doublée. procedure Somme_Serie is Somme: Integer; -- Somme des valeurs de la série Valeur: Integer; -- Valeur lu au clavier Valeur_Prec: Integer; -- Valeur precedente; begin Somme := 0; -- Déterminer la somme des valeurs d'une série lue un clavier Get(Valeur); Valeur_Prec := Valeur + 1; while Valeur /= Valeur_Prec loop Somme := Somme + Valeur; Valeur_Prec := Valeur; Get(Valeur); end loop; -- Afficher la longueur Put ("Somme : "); Put (Somme, 1); New_Line; end Somme_Serie;
separate (openGL) function Profile return profile_Kind is begin return Lean; end Profile;
with AZ3_Suite; with AUnit.Run; with AUnit.Reporter.Text; with Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO; procedure Tests is function Run is new AUnit.Run.Test_Runner_With_Status (AZ3_Suite.Suite); Reporter : AUnit.Reporter.Text.Text_Reporter; use AUnit; S : Status; begin Put_Line ("Running AZ3 tests..."); Reporter.Set_Use_ANSI_Colors (True); S := Run (Reporter); Ada.Command_Line.Set_Exit_Status (if S = Success then 0 else 1); end Tests;
with Ada.Text_IO, Ada.Command_Line; procedure Magic_Square is N: constant Positive := Positive'Value(Ada.Command_Line.Argument(1)); subtype Constants is Natural range 1 .. N*N; package CIO is new Ada.Text_IO.Integer_IO(Constants); Undef: constant Natural := 0; subtype Index is Natural range 0 .. N-1; function Inc(I: Index) return Index is (if I = N-1 then 0 else I+1); function Dec(I: Index) return Index is (if I = 0 then N-1 else I-1); A: array(Index, Index) of Natural := (others => (others => Undef)); -- initially undefined; at the end holding the magic square X: Index := 0; Y: Index := N/2; -- start position for the algorithm begin for I in Constants loop -- write 1, 2, ..., N*N into the magic array A(X, Y) := I; -- write I into the magic array if A(Dec(X), Inc(Y)) = Undef then X := Dec(X); Y := Inc(Y); -- go right-up else X := Inc(X); -- go down end if; end loop; for Row in Index loop -- output the magic array for Collumn in Index loop CIO.Put(A(Row, Collumn), Width => (if N*N < 10 then 2 elsif N*N < 100 then 3 else 4)); end loop; Ada.Text_IO.New_Line; end loop; end Magic_Square;
-- Ascon.Access_Internals -- Allow access to some internal parts of Ascon for testing and verification -- purposes. Not part of the standard API -- Copyright (c) 2016, James Humphry - see LICENSE file for details generic package Ascon.Access_Internals is subtype State is Ascon.State; function Make_State return State; function Initialise (Key : in Key_Type; Nonce : in Nonce_Type) return State; procedure Absorb (S : in out State; X : in Storage_Array); procedure Encrypt (S : in out State; M : in Storage_Array; C : out Storage_Array) with Pre => (C'Length = M'Length); procedure Decrypt (S : in out State; C : in Storage_Array; M : out Storage_Array) with Pre => (C'Length = M'Length); procedure Finalise (S : in out State; Key : in Key_Type; Tag : out Tag_Type); private function Make_State return State renames Ascon.Make_State; function Initialise (Key : in Key_Type; Nonce : in Nonce_Type) return State renames Ascon.Initialise; procedure Absorb (S : in out State; X : in Storage_Array) renames Ascon.Absorb; procedure Encrypt (S : in out State; M : in Storage_Array; C : out Storage_Array) renames Ascon.Encrypt; procedure Decrypt (S : in out State; C : in Storage_Array; M : out Storage_Array) renames Ascon.Decrypt; procedure Finalise (S : in out State; Key : in Key_Type; Tag : out Tag_Type) renames Ascon.Finalise; end Ascon.Access_Internals;
with Ada.Directories; use Ada.Directories; package Rejuvenation.File_Utils is procedure Write_String_To_File (Contents : String; File_Name : String); -- Write the Contents string to a file with the given File_Name. function Get_String_From_File (File_Name : String) return String; -- Return the contents string of a file with the given File_Name. procedure Walk_Files (Directory_Name : String; File_Pattern : String; Process_File : not null access procedure (Item : Directory_Entry_Type); Recursive : Boolean := True); -- Apply the procedure to all files that match the pattern -- in the given directory. -- The Recursive flags determines whether subdirectory are also include. end Rejuvenation.File_Utils;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- A U N I T . R E P O R T E R . X M L -- -- -- -- B o d y -- -- -- -- -- -- Copyright (C) 2000-2013, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT is maintained by AdaCore (http://www.adacore.com) -- -- -- ------------------------------------------------------------------------------ with AUnit.Time_Measure; use AUnit.Time_Measure; with Ada_Containers; use Ada_Containers; -- This is a xUnit reporter with output compatible with jUnit capable of -- reporing to Streams. package body AUnit.Reporter.Stream_XML is use Ada.Streams; use GNAT.OS_Lib; procedure Dump_Result_List (Engine : XML_Reporter; L : Result_Lists.List); -- List failed assertions -- procedure Put_Measure is new Gen_Put_Measure; -- Output elapsed time procedure Report_Test (Engine : XML_Reporter; Test : Test_Result); -- Report a single assertion failure or unexpected exception ------------------------------ -- Catch_Output_And_Error -- ------------------------------ procedure Catch_Output_And_Error (Engine : in out XML_Reporter) is begin GNAT.OS_Lib.Close (GNAT.OS_Lib.Standout); GNAT.OS_Lib.Close (GNAT.OS_Lib.Standerr); GNAT.OS_Lib.Create_Temp_Output_File (Engine.Stdout, Engine.Stdout_Name); GNAT.OS_Lib.Create_Temp_Output_File (Engine.Stderr, Engine.Stderr_Name); end; ---------------------- -- Dump_Result_List -- ---------------------- procedure Dump_Result_List (Engine : XML_Reporter; L : Result_Lists.List) is use Result_Lists; C : Cursor := First (L); begin -- Note: can't use Iterate because it violates restriction -- No_Implicit_Dynamic_Code while Has_Element (C) loop Report_Test (Engine, Element (C)); Next (C); end loop; end Dump_Result_List; ------------- -- Image -- ------------- function Image (S : Ada_Containers.Count_Type) return String is I : constant String := S'Img; begin return (if I (I'First) = ' ' then I (I'First + 1 .. I'Last) else I); end; ------------- -- Image -- ------------- function Image (S : Integer) return String is I : constant String := S'Img; begin return (if I (I'First) = ' 'then I (I'First + 1 .. I'Last) else I); end; ------------- -- Image -- ------------- function Image (S : AUnit_Duration) return String is Buffer : String (1 .. 40) := (others => ' '); Cursor : Natural := Buffer'First; Dummy : AUnit.IO.File_Type; procedure Put (Dummy_F : AUnit.IO.File_Type; S : String) is begin Buffer (Cursor .. Cursor + S'Length - 1) := S; Cursor := Cursor + S'Length; end; procedure Put is new Gen_Put_Measure; begin Put (Dummy, S); return Buffer (Buffer'First .. Cursor - 1); end; ------------------ -- Set_Output -- ------------------ procedure Set_Output (Engine : in out XML_Reporter; Stream : Stream_Access) is begin Engine.Output := Stream; end; ------------- -- Write -- ------------- procedure Write (Stream : not null access Ada.Streams.Root_Stream_Type'Class; From_Path : String) is Last : Integer; Fd : File_Descriptor; begin Fd := Open_Read (From_Path, GNAT.OS_Lib.Binary); declare Buffer : Stream_Element_Array (1 .. Stream_Element_Offset (File_Length (Fd))); begin Last := Read (Fd, Buffer'Address, Buffer'Length); Stream_Element_Array'Write (Stream, Buffer); if Last /= Buffer'Length then String'Write (Stream, "<<< Warning Output is incopmplete>>>" & ASCII.LF); end if; end; GNAT.OS_Lib.Close (Fd); end; ------------ -- Report -- ------------ procedure Report (Engine : XML_Reporter; R : in out Result'Class; Options : AUnit_Options := Default_Options) is T : AUnit_Duration; Dummy_OK : Boolean; begin String'Write (Engine.Output, "<?xml version='1.0' encoding='utf-8' ?>" & ASCII.LF); String'Write (Engine.Output, "<TestRun"); if Elapsed (R) /= Time_Measure.Null_Time then T := Get_Measure (Elapsed (R)); String'Write (Engine.Output, " elapsed="""); String'Write (Engine.Output, Image (T)); String'Write (Engine.Output, """>" & ASCII.LF); else String'Write (Engine.Output, ">" & ASCII.LF); end if; String'Write (Engine.Output, " <Statistics>" & ASCII.LF); String'Write (Engine.Output, " <Tests>"); String'Write (Engine.Output, Image (Test_Count (R))); String'Write (Engine.Output, "</Tests>" & ASCII.LF); String'Write (Engine.Output, " <FailuresTotal>"); String'Write (Engine.Output, Image (Integer (Failure_Count (R)) + Integer (Error_Count (R)))); String'Write (Engine.Output, "</FailuresTotal>" & ASCII.LF); String'Write (Engine.Output, " <Failures>"); String'Write (Engine.Output, Image (Integer (Failure_Count (R)))); String'Write (Engine.Output, "</Failures>" & ASCII.LF); String'Write (Engine.Output, " <Errors>"); String'Write (Engine.Output, Image (Integer (Error_Count (R)))); String'Write (Engine.Output, "</Errors>" & ASCII.LF); String'Write (Engine.Output, " </Statistics>" & ASCII.LF); declare S : Result_Lists.List; begin String'Write (Engine.Output, " <SuccessfulTests>" & ASCII.LF); if Options.Report_Successes then Successes (R, S); Dump_Result_List (Engine, S); end if; String'Write (Engine.Output, " </SuccessfulTests>" & ASCII.LF); end; String'Write (Engine.Output, " <FailedTests>" & ASCII.LF); declare F : Result_Lists.List; begin Failures (R, F); Dump_Result_List (Engine, F); end; declare E : Result_Lists.List; begin Errors (R, E); Dump_Result_List (Engine, E); end; String'Write (Engine.Output, " </FailedTests>" & ASCII.LF); if Engine.Stdout_Name /= null then GNAT.OS_Lib.Close (Engine.Stdout); GNAT.OS_Lib.Close (Engine.Stderr); String'Write (Engine.Output, " <StandardOutput>"); Write (Engine.Output, Engine.Stdout_Name.all); String'Write (Engine.Output, "</StandardOutput>" & ASCII.LF); String'Write (Engine.Output, " <StandardError>"); Write (Engine.Output, Engine.Stderr_Name.all); String'Write (Engine.Output, "</StandardError>" & ASCII.LF); GNAT.OS_Lib.Delete_File (Engine.Stderr_Name.all, Dummy_OK); GNAT.OS_Lib.Delete_File (Engine.Stdout_Name.all, Dummy_OK); end if; String'Write (Engine.Output, "</TestRun>" & ASCII.LF); end Report; ------------------ -- Report_Test -- ------------------ procedure Report_Test (Engine : XML_Reporter; Test : Test_Result) is Is_Assert : Boolean; T : AUnit_Duration; begin String'Write (Engine.Output, " <Test"); if Test.Elapsed /= Time_Measure.Null_Time then T := Get_Measure (Test.Elapsed); String'Write (Engine.Output, " elapsed="""); String'Write (Engine.Output, Image (T)); String'Write (Engine.Output, """>" & ASCII.LF); else String'Write (Engine.Output, ">" & ASCII.LF); end if; String'Write (Engine.Output, " <Name>"); String'Write (Engine.Output, Test.Test_Name.all); if Test.Routine_Name /= null then String'Write (Engine.Output, " : "); String'Write (Engine.Output, Test.Routine_Name.all); end if; String'Write (Engine.Output, "</Name>" & ASCII.LF); if Test.Failure /= null or else Test.Error /= null then if Test.Failure /= null then Is_Assert := True; else Is_Assert := False; end if; String'Write (Engine.Output, " <FailureType>"); if Is_Assert then String'Write (Engine.Output, "Assertion"); else String'Write (Engine.Output, "Error"); end if; String'Write (Engine.Output, "</FailureType>" & ASCII.LF); String'Write (Engine.Output, " <Message>"); if Is_Assert then String'Write (Engine.Output, Test.Failure.Message.all); else String'Write (Engine.Output, Test.Error.Exception_Name.all); end if; String'Write (Engine.Output, "</Message>" & ASCII.LF); if Is_Assert then String'Write (Engine.Output, " <Location>" & ASCII.LF); String'Write (Engine.Output, " <File>"); String'Write (Engine.Output, Test.Failure.Source_Name.all); String'Write (Engine.Output, "</File>" & ASCII.LF); String'Write (Engine.Output, " <Line>"); String'Write (Engine.Output, Image (Test.Failure.Line)); String'Write (Engine.Output, "</Line>" & ASCII.LF); String'Write (Engine.Output, " </Location>" & ASCII.LF); else String'Write (Engine.Output, " <Exception>" & ASCII.LF); String'Write (Engine.Output, " <Message>"); String'Write (Engine.Output, Test.Error.Exception_Name.all); String'Write (Engine.Output, "</Message>" & ASCII.LF); if Test.Error.Exception_Message /= null then String'Write (Engine.Output, " <Information>"); String'Write (Engine.Output, Test.Error.Exception_Message.all); String'Write (Engine.Output, "</Information>" & ASCII.LF); end if; if Test.Error.Traceback /= null then String'Write (Engine.Output, " <Traceback>"); String'Write (Engine.Output, Test.Error.Traceback.all); String'Write (Engine.Output, "</Traceback>" & ASCII.LF); end if; String'Write (Engine.Output, " </Exception>" & ASCII.LF); end if; end if; String'Write (Engine.Output, " </Test>" & ASCII.LF); end Report_Test; end AUnit.Reporter.Stream_XML;
-- Copyright (c) 2021 Devin Hill -- zlib License -- see LICENSE for details. package GBA.Interrupts is type Interrupt_ID is ( VBlank , HBlank , VCounter_Match , Timer_0_Overflow , Timer_1_Overflow , Timer_2_Overflow , Timer_3_Overflow , Serial_Communication , DMA_0 , DMA_1 , DMA_2 , DMA_3 , Keypad , Game_Pak ) with Size => 16; for Interrupt_ID use ( VBlank => 0 , HBlank => 1 , VCounter_Match => 2 , Timer_0_Overflow => 3 , Timer_1_Overflow => 4 , Timer_2_Overflow => 5 , Timer_3_Overflow => 6 , Serial_Communication => 7 , DMA_0 => 8 , DMA_1 => 9 , DMA_2 => 10 , DMA_3 => 11 , Keypad => 12 , Game_Pak => 13 ); type Interrupt_Flags is mod 2**14 with Size => 16; All_Interrupts : constant Interrupt_Flags := Interrupt_Flags'Mod(-1); function "or" (I1, I2 : Interrupt_ID) return Interrupt_Flags with Pure_Function, Inline_Always; function "or" (F : Interrupt_Flags; I : Interrupt_ID) return Interrupt_Flags with Pure_Function, Inline_Always; type Interrupt_Handler is access procedure; procedure Enable_Receiving_Interrupts (Enabled : Boolean) with Inline; procedure Enable_Receiving_Interrupts with Inline; procedure Disable_Receiving_Interrupts with Inline; procedure Disable_Receiving_Interrupts (Enabled : out Boolean) with Inline; procedure Enable_Interrupt (ID : Interrupt_ID) with Inline; procedure Enable_Interrupt (Flags : Interrupt_Flags) with Inline; procedure Disable_Interrupt (ID : Interrupt_ID) with Inline; procedure Disable_Interrupt (Flags : Interrupt_Flags) with Inline; procedure Disable_Interrupts_And_Save (Flags : out Interrupt_Flags) with Inline; procedure Acknowledge_Interrupt (ID : Interrupt_ID) with Inline; procedure Acknowledge_Interrupt (Flags : Interrupt_Flags) with Inline; procedure Attach_Interrupt_Handler (ID : Interrupt_ID; Handler : not null Interrupt_Handler) with Inline; procedure Attach_Interrupt_Handler_And_Save (ID : Interrupt_ID; Handler : not null Interrupt_Handler; Old_Handler : out Interrupt_Handler) with Inline; procedure Detach_Interrupt_Handler (ID : Interrupt_ID) with Inline; procedure Detach_Interrupt_Handler_And_Save (ID : Interrupt_ID; Old_Handler : out Interrupt_Handler) with Inline; private procedure Default_Interrupt_Dispatcher with Linker_Section => ".iwram"; pragma Machine_Attribute(Default_Interrupt_Dispatcher, "target", "arm"); end GBA.Interrupts;
with GNAT.Sockets; use GNAT.Sockets; with Ada.Command_Line; with GNAT.Exception_Traces; with GNAT.Traceback.Symbolic; procedure Spawn_Manager.Server.Main is Address : Sock_Addr_Type; Server : Socket_Type; Channel : Stream_Access; Id : Long_Integer; Request : Spawn_Request; Response : Spawn_Response; begin GNAT.Exception_Traces.Set_Trace_Decorator (GNAT.Traceback.Symbolic.Symbolic_Traceback'Access); GNAT.Exception_Traces.Trace_On (GNAT.Exception_Traces.Every_Raise); Address.Addr := Inet_Addr (Ada.Command_Line.Argument (1)); Address.Port := Port_Type'Value (Ada.Command_Line.Argument (2)); Id := Long_Integer'Value (Ada.Command_Line.Argument (3)); Create_Socket (Server); Connect_Socket (Server, Address); Channel := Stream (Server); loop Spawn_Request'Read (Channel, Request); exit when Is_Exit_Message (Request); if Request.Id /= Id then Response := (False, -1, Invalid_Pid, To_Unbounded_String ("Invalid id from client")); Spawn_Response'Write (Channel, Response); Close_Socket (Server); raise Program_Error with "Invalid id from client"; elsif Request.Version /= Version then Response := (False, -1, Invalid_Pid, To_Unbounded_String ("Server and client versions missmatch Server:") & Version & ", Client:" & Request.Version); Spawn_Response'Write (Channel, Response); Close_Socket (Server); raise Program_Error with "Server and client versions missmatch Server:" & Version & ", Client:" & To_String (Request.Version); else Response := Spawn (Request); Spawn_Response'Write (Channel, Response); end if; end loop; Close_Socket (Server); end Spawn_Manager.Server.Main;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers; use Ada.Containers; with AUnit.Assertions; use AUnit.Assertions; with GNAT.Source_Info; use GNAT.Source_Info; with Libadalang.Analysis; use Libadalang.Analysis; with Libadalang.Common; use Libadalang.Common; with Rejuvenation; use Rejuvenation; with Rejuvenation.Finder; use Rejuvenation.Finder; with Rejuvenation.Match_Patterns; use Rejuvenation.Match_Patterns; with Rejuvenation.Patterns; use Rejuvenation.Patterns; with Rejuvenation.Simple_Factory; use Rejuvenation.Simple_Factory; with Rejuvenation.Text_Rewrites; use Rejuvenation.Text_Rewrites; package body Test_Exercises_Rewrite is procedure Test_Rejuvenation_Rewrite_Assign_Condition_In_If_Statement (T : in out Test_Case'Class); procedure Test_Rejuvenation_Rewrite_Assign_Condition_In_If_Statement (T : in out Test_Case'Class) is pragma Unreferenced (T); Function_Body_Start : constant String := "function Example (condition : in Boolean) return Boolean is" & " returnValue : Boolean;" & "begin"; Function_Body_End : constant String := " return returnValue;" & "end Example;"; Function_Body : constant String := Function_Body_Start & " if condition then" & " returnValue := True;" & " else" & " returnValue := False;" & " end if;" & Function_Body_End; Unit : constant Analysis_Unit := Analyze_Fragment (Function_Body, Subp_Body_Rule); Expected : constant String := Function_Body_Start & " returnValue := condition;" & Function_Body_End; Pattern_Assign_Condition_In_If_Statement : constant Pattern := Make_Pattern ("if $S_Condition then $S_Variable := True; " & "else $S_Variable := False; end if;", Stmt_Rule); Found_Matches : constant Match_Pattern_List.Vector := Find_Full (Unit.Root, Pattern_Assign_Condition_In_If_Statement); TR : Text_Rewrite_Unit := Make_Text_Rewrite_Unit (Unit); begin Put_Line ("Begin - " & Enclosing_Entity); Assert (Found_Matches.Length = 1, "One instance in unit expected, got " & Found_Matches.Length'Image); for Found_Match of Found_Matches loop declare Condition : constant String := Found_Match.Get_Single_As_Raw_Signature ("$S_Condition"); Variable : constant String := Found_Match.Get_Single_As_Raw_Signature ("$S_Variable"); begin TR.Replace (Found_Match.Get_Nodes.First_Element, Variable & " := " & Condition & ";"); end; end loop; declare Actual : constant String := TR.ApplyToString; begin Assert (Actual = Expected, "* Expected :" & ASCII.LF & Expected & ASCII.LF & "* Actual :" & ASCII.LF & Actual); end; Put_Line ("End - " & Enclosing_Entity); end Test_Rejuvenation_Rewrite_Assign_Condition_In_If_Statement; procedure Test_Rejuvenation_Rewrite_Assign_Condition_In_Statement_List (T : in out Test_Case'Class); procedure Test_Rejuvenation_Rewrite_Assign_Condition_In_Statement_List (T : in out Test_Case'Class) is pragma Unreferenced (T); Function_Body_Start : constant String := "function Example (boolCond : in Boolean) return Boolean is" & " answer : Boolean;" & "begin"; Function_Body_End : constant String := " return answer;" & "end Example;"; Function_Body : constant String := Function_Body_Start & " answer := False;" & " if boolCond then" & " answer := True;" & " end if;" & Function_Body_End; Unit : constant Analysis_Unit := Analyze_Fragment (Function_Body, Subp_Body_Rule); Expected : constant String := Function_Body_Start & " answer := boolCond;" & Function_Body_End; Pattern_Assign_Condition_In_Statement_List : constant Pattern := Make_Pattern ("$S_Variable := False; " & "if $S_Condition then $S_Variable := True; end if;", Stmts_Rule); Found_Matches : constant Match_Pattern_List.Vector := Find_Sub_List (Unit.Root, Pattern_Assign_Condition_In_Statement_List); TR : Text_Rewrite_Unit := Make_Text_Rewrite_Unit (Unit); begin Put_Line ("Begin - " & Enclosing_Entity); Assert (Found_Matches.Length = 1, "One instance in unit expected, got " & Found_Matches.Length'Image); for Found_Match of Found_Matches loop declare Condition : constant String := Found_Match.Get_Single_As_Raw_Signature ("$S_Condition"); Variable : constant String := Found_Match.Get_Single_As_Raw_Signature ("$S_Variable"); begin TR.Replace (Found_Match.Get_Nodes.First_Element, Found_Match.Get_Nodes.Last_Element, Variable & " := " & Condition & ";"); end; end loop; declare Actual : constant String := TR.ApplyToString; begin Assert (Actual = Expected, "* Expected :" & ASCII.LF & Expected & ASCII.LF & "* Actual :" & ASCII.LF & Actual); end; Put_Line ("End - " & Enclosing_Entity); end Test_Rejuvenation_Rewrite_Assign_Condition_In_Statement_List; -- Test plumbing overriding function Name (T : Exercise_Rewrite_Test_Case) return AUnit.Message_String is pragma Unreferenced (T); begin return AUnit.Format ("Exercises Rewrite"); end Name; overriding procedure Register_Tests (T : in out Exercise_Rewrite_Test_Case) is begin Registration.Register_Routine (T, Test_Rejuvenation_Rewrite_Assign_Condition_In_If_Statement'Access, "Use Rejuvenation Match Pattern to " & "find assignment of condition to variable " & "using if statement. Pattern 1"); Registration.Register_Routine (T, Test_Rejuvenation_Rewrite_Assign_Condition_In_Statement_List'Access, "Use Rejuvenation Match Pattern to " & "find assignment of condition to variable " & "using statements. Pattern 2"); end Register_Tests; end Test_Exercises_Rewrite;
-- -- Copyright (C) 2015-2016 secunet Security Networks AG -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- with HW.Debug; with GNAT.Source_Info; with System.Storage_Elements; with System.Address_To_Access_Conversions; package body HW.MMIO_Range with Refined_State => (State => null, -- the contents accessed, Range_A points to it Base_Address => Range_A) -- the address, stored in Range_A is pragma Warnings (Off, "implicit dereference", Reason => "This is what this package is about."); Debug_Reads : constant Boolean := False; Debug_Writes : constant Boolean := False; type Range_Access is access all Array_T; package Conv_Range is new System.Address_To_Access_Conversions (Array_T); Range_A : Range_Access := Range_Access (Conv_Range.To_Pointer (System'To_Address (Base_Addr))); procedure Read (Value : out Element_T; Index : in Index_T) is use type Word32; begin Value := Range_A (Index); pragma Debug (Debug_Reads, Debug.Put (GNAT.Source_Info.Enclosing_Entity & ": ")); pragma Debug (Debug_Reads, Debug.Put_Word32 (Word32 (Value))); pragma Debug (Debug_Reads, Debug.Put (" <- ")); pragma Debug (Debug_Reads, Debug.Put_Word32 (Word32 (System.Storage_Elements.To_Integer (Conv_Range.To_Address (Conv_Range.Object_Pointer (Range_A)))) + Word32 (Index) * (Element_T'Size / 8))); pragma Debug (Debug_Reads, Debug.New_Line); end Read; procedure Write (Index : in Index_T; Value : in Element_T) is use type Word32; begin pragma Debug (Debug_Writes, Debug.Put (GNAT.Source_Info.Enclosing_Entity & ": ")); pragma Debug (Debug_Writes, Debug.Put_Word32 (Word32 (Value))); pragma Debug (Debug_Writes, Debug.Put (" -> ")); pragma Debug (Debug_Writes, Debug.Put_Word32 (Word32 (System.Storage_Elements.To_Integer (Conv_Range.To_Address (Conv_Range.Object_Pointer (Range_A)))) + Word32 (Index) * (Element_T'Size / 8))); pragma Debug (Debug_Writes, Debug.New_Line); Range_A (Index) := Value; end Write; procedure Set_Base_Address (Base : Word64) is begin Range_A := Range_Access (Conv_Range.To_Pointer (System'To_Address (Base))); end Set_Base_Address; end HW.MMIO_Range;
-- with Neural.Pattern; with Neural.Net; -- with float_Math; package linear_Net is package Math renames Neural.Math; type Item is new neural.Net.Item with private; type View is access all Item; procedure define (Self : out Item; Name : in String); function Pattern_For (Self : in Item; the_Input : in math.Real; Inputs_Only : in Boolean := False; the_Output : in math.Real := 0.0 ) return Neural.Pattern; function Output_for (Self : access Item; the_Input : in math.Real) return math.Real; private type Item is new Neural.Net.Item with record null; end record; end linear_Net;
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Element_Vectors; with Program.Elements.Associations; with Program.Elements.Identifiers; with Program.Lexical_Elements; with Program.Elements.Expressions; package Program.Elements.Discriminant_Associations is pragma Pure (Program.Elements.Discriminant_Associations); type Discriminant_Association is limited interface and Program.Elements.Associations.Association; type Discriminant_Association_Access is access all Discriminant_Association'Class with Storage_Size => 0; not overriding function Selector_Names (Self : Discriminant_Association) return Program.Elements.Identifiers.Identifier_Vector_Access is abstract; not overriding function Discriminant_Value (Self : Discriminant_Association) return not null Program.Elements.Expressions.Expression_Access is abstract; type Discriminant_Association_Text is limited interface; type Discriminant_Association_Text_Access is access all Discriminant_Association_Text'Class with Storage_Size => 0; not overriding function To_Discriminant_Association_Text (Self : in out Discriminant_Association) return Discriminant_Association_Text_Access is abstract; not overriding function Arrow_Token (Self : Discriminant_Association_Text) return Program.Lexical_Elements.Lexical_Element_Access is abstract; type Discriminant_Association_Vector is limited interface and Program.Element_Vectors.Element_Vector; type Discriminant_Association_Vector_Access is access all Discriminant_Association_Vector'Class with Storage_Size => 0; overriding function Element (Self : Discriminant_Association_Vector; Index : Positive) return not null Program.Elements.Element_Access is abstract with Post'Class => Element'Result.Is_Discriminant_Association; function To_Discriminant_Association (Self : Discriminant_Association_Vector'Class; Index : Positive) return not null Discriminant_Association_Access is (Self.Element (Index).To_Discriminant_Association); end Program.Elements.Discriminant_Associations;
with Ada.Environment_Variables; with Dotenv; with Print_Variable; procedure Example_2 is begin Dotenv.Config (Path => "bin/.env.interpolation", File_Form => "wcem=8", Overwrite => True, Debug => True, Interpolate => True); Ada.Environment_Variables.Iterate (Print_Variable'Access); end Example_2;
------------------------------------------------------------------------------ -- Copyright (c) 2014, 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.Time_IO provides subprograms to serialize and deserialize times -- -- to and from various String representations. -- ------------------------------------------------------------------------------ with Ada.Calendar.Formatting; package body Natools.Time_IO.RFC_3339 is --------------------- -- Validity Checks -- --------------------- function Is_Valid_Prefix (Image : String) return Boolean is (Image (Image'First) in Digit_Character and then Image (Image'First + 1) in Digit_Character and then Image (Image'First + 2) in Digit_Character and then Image (Image'First + 3) in Digit_Character and then Image (Image'First + 4) = Date_Separator and then Image (Image'First + 5) in Digit_Character and then Image (Image'First + 6) in Digit_Character and then Image (Image'First + 7) = Date_Separator and then Image (Image'First + 8) in Digit_Character and then Image (Image'First + 9) in Digit_Character and then Image (Image'First + 10) = Date_Time_Separator and then Image (Image'First + 11) in Digit_Character and then Image (Image'First + 12) in Digit_Character and then Image (Image'First + 13) = Time_Separator and then Image (Image'First + 14) in Digit_Character and then Image (Image'First + 15) in Digit_Character and then Image (Image'First + 16) = Time_Separator and then Image (Image'First + 17) in Digit_Character and then Image (Image'First + 18) in Digit_Character); function Is_Valid_Time_Zone (Image : String) return Boolean is (Image (Image'Last - 5) in '+' | '-' and then Image (Image'Last - 4) in Digit_Character and then Image (Image'Last - 3) in Digit_Character and then Image (Image'Last - 2) = Time_Separator and then Image (Image'Last - 1) in Digit_Character and then Image (Image'Last) in Digit_Character); function Is_Valid_Subsecond (Sub_Image : String) return Boolean is (Sub_Image'Length = 0 or else (Sub_Image'Length >= 2 and then Sub_Image (Sub_Image'First) = Subsecond_Separator and then (for all I in Sub_Image'First + 1 .. Sub_Image'Last => Sub_Image (I) in Digit_Character))); function Is_Valid (Image : String) return Boolean is begin return Image'Length >= 20 and then Is_Valid_Prefix (Image) and then ((Image (Image'Last) = 'Z' and then Is_Valid_Subsecond (Image (Image'First + 19 .. Image'Last - 1))) or else (Is_Valid_Time_Zone (Image) and then Is_Valid_Subsecond (Image (Image'First + 19 .. Image'Last - 6)))); end Is_Valid; -------------------- -- Time To String -- -------------------- function Image (Date : Ada.Calendar.Time; Subsecond_Digits : Natural := 0; Force_Leap_Second : Boolean := False) return String is begin return Image (Date, Ada.Calendar.Time_Zones.UTC_Time_Offset (Date), Subsecond_Digits, Force_Leap_Second); end Image; function Image (Date : Ada.Calendar.Time; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset; Subsecond_Digits : Natural := 0; Force_Leap_Second : Boolean := False) return String is function Subsecond_Image (Subsecond : Ada.Calendar.Formatting.Second_Duration) return String; function Time_Zone_Image return String; function Subsecond_Image (Subsecond : Ada.Calendar.Formatting.Second_Duration) return String is Remaining : Duration := Subsecond; Number : Digit_Number; N : Natural; begin if Subsecond_Digits = 0 then return ""; end if; return Result : String (1 .. Subsecond_Digits + 1) do Result (1) := Subsecond_Separator; for I in 2 .. Subsecond_Digits + 1 loop Remaining := Remaining * 10; N := Natural (Remaining); if Duration (N) > Remaining then Number := N - 1; else Number := N; end if; Remaining := Remaining - Duration (Number); Result (I) := Image (Number); end loop; end return; end Subsecond_Image; function Time_Zone_Image return String is use type Ada.Calendar.Time_Zones.Time_Offset; begin if Time_Zone = 0 then return "Z"; else declare Hour : constant Ada.Calendar.Time_Zones.Time_Offset := (abs Time_Zone) / 60; Minute : constant Ada.Calendar.Time_Zones.Time_Offset := (abs Time_Zone) mod 60; Sign : Character; begin if Time_Zone < 0 then Sign := '-'; else Sign := '+'; end if; return String'(Sign, Image (Digit_Number (Hour / 10)), Image (Digit_Number (Hour mod 10)), Time_Separator, Image (Digit_Number (Minute / 10)), Image (Digit_Number (Minute mod 10))); end; end if; end Time_Zone_Image; Year : Ada.Calendar.Year_Number; Month : Ada.Calendar.Month_Number; Day : Ada.Calendar.Day_Number; Hour : Ada.Calendar.Formatting.Hour_Number; Minute : Ada.Calendar.Formatting.Minute_Number; Second : Ada.Calendar.Formatting.Second_Number; Subsecond : Ada.Calendar.Formatting.Second_Duration; Leap_Second : Boolean; Used_Second : Natural; begin Ada.Calendar.Formatting.Split (Date, Year, Month, Day, Hour, Minute, Second, Subsecond, Leap_Second, Time_Zone); if Leap_Second or Force_Leap_Second then pragma Assert (Second = 59); Used_Second := 60; else Used_Second := Second; end if; return (Image (Year / 1000), Image ((Year / 100) mod 10), Image ((Year / 10) mod 10), Image (Year mod 10), Date_Separator, Image (Month / 10), Image (Month mod 10), Date_Separator, Image (Day / 10), Image (Day mod 10), Date_Time_Separator, Image (Hour / 10), Image (Hour mod 10), Time_Separator, Image (Minute / 10), Image (Minute mod 10), Time_Separator, Image (Used_Second / 10), Image (Used_Second mod 10)) & Subsecond_Image (Subsecond) & Time_Zone_Image; end Image; -------------------- -- String To Time -- -------------------- function Value (Image : String) return Ada.Calendar.Time is Result : Ada.Calendar.Time; Discarded : Ada.Calendar.Time_Zones.Time_Offset; begin Value (Image, Result, Discarded); return Result; end Value; procedure Value (Image : in String; Date : out Ada.Calendar.Time; Time_Zone : out Ada.Calendar.Time_Zones.Time_Offset) is Discarded : Boolean; begin Value (Image, Date, Time_Zone, Discarded); end Value; procedure Value (Image : in String; Date : out Ada.Calendar.Time; Time_Zone : out Ada.Calendar.Time_Zones.Time_Offset; Leap_Second : out Boolean) is Year : Ada.Calendar.Year_Number; Month : Ada.Calendar.Month_Number; Day : Ada.Calendar.Day_Number; Hour : Ada.Calendar.Formatting.Hour_Number; Minute : Ada.Calendar.Formatting.Minute_Number; Second : Ada.Calendar.Formatting.Second_Number; Subsecond : Ada.Calendar.Formatting.Second_Duration := 0.0; begin Year := Natural'Value (Image (Image'First .. Image'First + 3)); Month := Natural'Value (Image (Image'First + 5 .. Image'First + 6)); Day := Natural'Value (Image (Image'First + 8 .. Image'First + 9)); Hour := Natural'Value (Image (Image'First + 11 .. Image'First + 12)); Minute := Natural'Value (Image (Image'First + 14 .. Image'First + 15)); declare Number : constant Natural := Natural'Value (Image (Image'First + 17 .. Image'First + 18)); begin if Number = 60 then Leap_Second := True; Second := 59; else Leap_Second := False; Second := Number; end if; end; if Image (Image'First + 19) = Subsecond_Separator then declare I : Positive := Image'First + 20; Current : Duration := 0.1; begin while Image (I) in Digit_Character loop Subsecond := Subsecond + Current * (Character'Pos (Image (I)) - Character'Pos ('0')); Current := Current / 10; I := I + 1; end loop; end; end if; if Image (Image'Last) = 'Z' then Time_Zone := 0; else Time_Zone := Ada.Calendar.Time_Zones.Time_Offset (Natural'Value (Image (Image'Last - 4 .. Image'Last - 3)) * 60 + Natural'Value (Image (Image'Last - 1 .. Image'Last))); case Image (Image'Last - 5) is when '-' => Time_Zone := Ada.Calendar.Time_Zones."-" (Time_Zone); when '+' => null; when others => raise Constraint_Error with "Invalid time zone separator in RFC 3339 date"; end case; end if; if Leap_Second then begin Date := Ada.Calendar.Formatting.Time_Of (Year, Month, Day, Hour, Minute, Second, Subsecond, True, Time_Zone); return; exception when Ada.Calendar.Time_Error => null; end; end if; Date := Ada.Calendar.Formatting.Time_Of (Year, Month, Day, Hour, Minute, Second, Subsecond, False, Time_Zone); end Value; end Natools.Time_IO.RFC_3339;
----------------------------------------------------------------------- -- servlet-server-tests - Unit tests for server requests -- Copyright (C) 2018, 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Files; with Servlet.Tests; with Servlet.Core.Files; with Servlet.Core.Measures; with Servlet.Core.Tests; with Servlet.Filters.Dump; with Servlet.Requests.Mockup; with Servlet.Responses.Mockup; package body Servlet.Server.Tests is use Servlet.Tests; use Util.Tests; package Caller is new Util.Test_Caller (Test, "Server"); Except_Servlet : aliased Servlet.Core.Tests.Test_Servlet3; Upload : aliased Servlet.Core.Tests.Test_Servlet2; Files : aliased Servlet.Core.Files.File_Servlet; Dump : aliased Servlet.Filters.Dump.Dump_Filter; Measures : aliased Servlet.Core.Measures.Measure_Servlet; All_Servlet : aliased Servlet.Core.Tests.Test_Servlet3; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Servlet.Server.Service", Test_Service'Access); Caller.Add_Test (Suite, "Test Servlet.Server.Service (GET)", Test_Get_File'Access); Caller.Add_Test (Suite, "Test Servlet.Server.Service (GET 404)", Test_Get_404'Access); Caller.Add_Test (Suite, "Test Servlet.Server.Service (POST)", Test_Post_File_Error'Access); Caller.Add_Test (Suite, "Test Servlet.Server.Service (POST)", Test_Post_Content'Access); Caller.Add_Test (Suite, "Test Servlet.Server.Service (GET measures)", Test_Get_Measures'Access); Caller.Add_Test (Suite, "Test Servlet.Server.Service (GET with exception)", Test_Get_With_Exception'Access); Caller.Add_Test (Suite, "Test Servlet.Server.Register_Application", Test_Register_Remove_Application'Access); Caller.Add_Test (Suite, "Test Servlet.Server.Register_Application (all)", Test_Register_Application'Access); end Add_Tests; -- ------------------------------ -- Initialize the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); use type Servlet.Core.Servlet_Registry_Access; App : Servlet.Core.Servlet_Registry_Access; begin if Servlet.Tests.Get_Application = null then Servlet.Tests.Initialize (Util.Tests.Get_Properties); App := Servlet.Tests.Get_Application; App.Add_Servlet ("Except", Except_Servlet'Access); App.Add_Mapping ("*.exc", "Except"); -- Register the servlets and filters App.Add_Servlet (Name => "files", Server => Files'Access); App.Add_Servlet (Name => "measures", Server => Measures'Access); App.Add_Filter (Name => "dump", Filter => Dump'Access); App.Add_Filter (Name => "measures", Filter => Servlet.Filters.Filter'Class (Measures)'Access); App.Add_Servlet ("Upload", Upload'Access); App.Add_Mapping ("*.upload", "Upload"); -- Define servlet mappings App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.txt"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Mapping (Name => "files", Pattern => "*.jpg"); App.Add_Mapping (Name => "files", Pattern => "*.gif"); App.Add_Mapping (Name => "files", Pattern => "*.pdf"); App.Add_Mapping (Name => "files", Pattern => "*.properties"); App.Add_Mapping (Name => "files", Pattern => "*.xhtml"); 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 if; Servlet.Tests.Get_Application.Start; end Set_Up; -- ------------------------------ -- Test the Service procedure. -- ------------------------------ procedure Test_Service (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Request.Set_Method (Method => "GET"); Request.Set_Request_URI (URI => "tst", Split => True); Request.Set_Protocol (Protocol => "HTTP/1.1"); Servlet.Tests.Get_Server.Service (Request, Reply); Assert_Equals (T, Servlet.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid response"); Assert_Matches (T, ".*servlet.error.status_code.*404.*", Reply, "Invalid 404 page returned", Status => Servlet.Responses.SC_NOT_FOUND); end Test_Service; -- ------------------------------ -- Test a GET request on a static file served by the File_Servlet. -- ------------------------------ procedure Test_Get_404 (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/file-does-not-exist.txt", "test-404.html"); Assert_Equals (T, Servlet.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid response"); Assert_Matches (T, ".*servlet.error.status_code.*404.*", Reply, "Invalid 404 page returned", Status => Servlet.Responses.SC_NOT_FOUND); Do_Get (Request, Reply, "/file-does-not-exist.js", "test-404.html"); Assert_Equals (T, Servlet.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid response"); Assert_Matches (T, ".*servlet.error.status_code.*404.*", Reply, "Invalid 404 page returned", Status => Servlet.Responses.SC_NOT_FOUND); end Test_Get_404; -- ------------------------------ -- Test a GET request on a static file served by the File_Servlet. -- ------------------------------ procedure Test_Get_File (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/tests/file.txt", "get-file.txt"); Assert_Contains (T, "A plain text file.", Reply, "Wrong content"); Assert_Header (T, "Content-Type", "text/plain", Reply, "Content-Type"); Do_Get (Request, Reply, "/tests/file.html", "get-file-set.html"); Assert_Matches (T, "<html></html>", Reply, "Wrong content"); Assert_Header (T, "Content-Type", "text/html", Reply, "Content-Type"); Do_Get (Request, Reply, "/tests/file.js", "get-file.js"); Assert_Matches (T, "^\s*var n = 0;.*", Reply, "Wrong content"); Assert_Header (T, "Content-Type", "text/javascript", Reply, "Content-Type"); Do_Get (Request, Reply, "/tests/file.css", "get-file.css"); Assert_Matches (T, "^\s*div { margin: 0 }.*", Reply, "Wrong content"); Assert_Header (T, "Content-Type", "text/css", Reply, "Content-Type"); end Test_Get_File; -- ------------------------------ -- Test a GET request on the measure servlet -- ------------------------------ procedure Test_Get_Measures (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/stats.xml", "stats.xml"); -- We must get at least one measure value (assuming the Test_Get_File test -- was executed). Assert_Matches (T, "<time count=""\d+"" time=""\d+.\d+ [um]s"" title="".*""/>", Reply, "Wrong content"); end Test_Get_Measures; -- ------------------------------ -- Test a POST on a file served by the File_Servlet. -- ------------------------------ procedure Test_Post_File_Error (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Do_Post (Request, Reply, "/tests/file.css", "post-file.css"); Assert_Header (T, "Content-Type", "text/html", Reply, "Content-Type", Status => Servlet.Responses.SC_METHOD_NOT_ALLOWED); end Test_Post_File_Error; -- ------------------------------ -- Test a POST with a part file to a test servlet. -- ------------------------------ procedure Test_Post_Content (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/upload.txt"); Request : Servlet.Requests.Mockup.Part_Request (1); Reply : Servlet.Responses.Mockup.Response; begin Util.Files.Write_File (Path, "Some content"); Request.Set_Part (Position => 1, Name => "file.txt", Path => Path, Content_Type => "text/plain"); Do_Post (Request, Reply, "/tests/file.upload", "post-file.upload"); Assert_Header (T, "Content-Type", "text/plain", Reply, "Content-Type", Status => Servlet.Responses.SC_OK); end Test_Post_Content; -- ------------------------------ -- Test a GET request on servlet that raises an exception. -- ------------------------------ procedure Test_Get_With_Exception (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Except_Servlet.Raise_Exception := True; Do_Get (Request, Reply, "/exception-raised.exc", "exception-raised.exc"); Assert_Header (T, "Content-Type", "text/html", Reply, "Content-Type", Status => Servlet.Responses.SC_INTERNAL_SERVER_ERROR); Assert_Matches (T, ".*CONSTRAINT_ERROR.*", Reply, "No exception reported", Status => Servlet.Responses.SC_INTERNAL_SERVER_ERROR); end Test_Get_With_Exception; -- ------------------------------ -- Test a Register_Application and Remove_Application. -- ------------------------------ procedure Test_Register_Remove_Application (T : in out Test) is App1 : aliased Servlet.Core.Servlet_Registry; begin Servlet.Tests.Get_Server.Register_Application ("my-app", App1'Unchecked_Access); T.Test_Get_File; for I in 1 .. 2 loop Servlet.Tests.Get_Server.Remove_Application (App1'Unchecked_Access); T.Test_Get_File; end loop; exception when others => Servlet.Tests.Get_Server.Remove_Application (App1'Unchecked_Access); raise; end Test_Register_Remove_Application; -- ------------------------------ -- Test a Register_Application and Remove_Application. -- ------------------------------ procedure Test_Register_Application (T : in out Test) is App1 : aliased Servlet.Core.Servlet_Registry; Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin App1.Add_Servlet ("all", All_Servlet'Access); App1.Add_Mapping ("/", "all"); App1.Add_Mapping ("/test", "all"); Servlet.Tests.Get_Server.Register_Application ("", App1'Unchecked_Access); Servlet.Tests.Get_Server.Start; Request.Set_Method (Method => "GET"); Request.Set_Request_URI (URI => "/test", Split => True); Request.Set_Protocol (Protocol => "HTTP/1.1"); Servlet.Tests.Get_Server.Service (Request, Reply); Assert_Equals (T, Servlet.Responses.SC_OK, Reply.Get_Status, "Invalid response"); T.Test_Get_File; Servlet.Tests.Get_Server.Remove_Application (App1'Unchecked_Access); end Test_Register_Application; end Servlet.Server.Tests;
-- SPDX-FileCopyrightText: 2020 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ---------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Exceptions; with Ada.Wide_Wide_Text_IO; with League.JSON.Objects; with League.Stream_Element_Vectors; with League.String_Vectors; with League.Strings; with Spawn.Processes; with Jupyter.Kernels; with Processes; package Ada_Kernels is type Kernel is limited new Jupyter.Kernels.Kernel with private; procedure Initialize (Self : in out Kernel'Class; Top_Dir : League.Strings.Universal_String; Error : out League.Strings.Universal_String); private type Gprbuild_Options is record Path : League.Strings.Universal_String; Gargs : League.String_Vectors.Universal_String_Vector; Cargs : League.String_Vectors.Universal_String_Vector; Largs : League.String_Vectors.Universal_String_Vector; Bargs : League.String_Vectors.Universal_String_Vector; end record; procedure Append (Args : in out League.String_Vectors.Universal_String_Vector; Option : Gprbuild_Options); type Session is limited new Jupyter.Kernels.Session and Spawn.Processes.Process_Listener with record Gprbuild : Gprbuild_Options; Gnatchop : League.Strings.Universal_String; ALR : League.Strings.Universal_String; Process : Spawn.Processes.Process; Directory : League.Strings.Universal_String; -- Each session has its own directory IO_Pub : Jupyter.Kernels.IO_Pub_Access; Stdout : League.Stream_Element_Vectors.Stream_Element_Vector; Stderr : League.Stream_Element_Vectors.Stream_Element_Vector; Service : League.Stream_Element_Vectors.Stream_Element_Vector; Injected : Boolean := False; Finished : Boolean := True; Ready : Boolean := True; -- Driver's ready to get next Command Clauses : League.String_Vectors.Universal_String_Vector; Runs : League.String_Vectors.Universal_String_Vector; Build_Env : Processes.Environment; Trace : Ada.Wide_Wide_Text_IO.File_Type; end record; overriding procedure Execute (Self : aliased in out Session; IO_Pub : not null Jupyter.Kernels.IO_Pub_Access; Execution_Counter : Positive; Code : League.Strings.Universal_String; Silent : Boolean; User_Expressions : League.JSON.Objects.JSON_Object; Allow_Stdin : Boolean; Stop_On_Error : Boolean; Expression_Values : out League.JSON.Objects.JSON_Object; Error : in out Jupyter.Kernels.Execution_Error); overriding procedure Standard_Output_Available (Self : in out Session); overriding procedure Standard_Error_Available (Self : in out Session); overriding procedure Finished (Self : in out Session; Exit_Status : Spawn.Processes.Process_Exit_Status; Exit_Code : Spawn.Processes.Process_Exit_Code); overriding procedure Error_Occurred (Self : in out Session; Process_Error : Integer); overriding procedure Exception_Occurred (Self : in out Session; Occurrence : Ada.Exceptions.Exception_Occurrence); type Session_Access is access all Session; function Hash (Value : Positive) return Ada.Containers.Hash_Type is (Ada.Containers.Hash_Type'Mod (Value)); package Session_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Positive, Element_Type => Session_Access, Hash => Hash, Equivalent_Keys => "="); type Kernel is limited new Jupyter.Kernels.Kernel with record Top_Dir : League.Strings.Universal_String; Gprbuild : League.Strings.Universal_String; Gnatchop : League.Strings.Universal_String; ALR : League.Strings.Universal_String; Driver : League.Strings.Universal_String; Map : Session_Maps.Map; Last_Id : Natural := 0; end record; overriding procedure Kernel_Info (Self : aliased in out Kernel; Result : out League.JSON.Objects.JSON_Object); overriding procedure Create_Session (Self : aliased in out Kernel; Session_Id : Positive; Result : out Jupyter.Kernels.Session_Access); overriding function Get_Session (Self : aliased in out Kernel; Session_Id : Positive) return Jupyter.Kernels.Session_Access; end Ada_Kernels;
------------------------------------------------------------------------------ -- -- -- GNAT SYSTEM UTILITIES -- -- -- -- G N A T P S T A -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1997-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. -- -- -- ------------------------------------------------------------------------------ -- Program to print out listing of Standard package for the target (not -- the host) with all constants appearing explicitly. This is not really -- valid Ada, since one cannot really define new base types, but it is a -- helpful listing from a documentation point of view. -- Note that special care has been taken to use the host parameters for -- integer and floating point sizes. with Ada.Text_IO; use Ada.Text_IO; with Gnatvsn; with Ttypef; use Ttypef; with Ttypes; use Ttypes; with Types; use Types; procedure GnatPsta is pragma Ident (Gnatvsn.Gnat_Version_String); procedure P (Item : String) renames Ada.Text_IO.Put_Line; procedure P_Int_Range (Size : Pos; Put_First : Boolean := True); -- Prints the range of an integer based on its Size. If Put_First is -- False, then skip the first bound. procedure P_Float_Range (Nb_Digits : Pos); -- Prints the maximum range of a Float whose 'Digits is given by Nb_Digits ------------------- -- P_Float_Range -- ------------------- procedure P_Float_Range (Nb_Digits : Pos) is begin -- This routine assumes only IEEE floats. -- ??? Should the following be adapted for OpenVMS ? case Nb_Digits is when IEEES_Digits => P (" range " & IEEES_First'Universal_Literal_String & " .. " & IEEES_Last'Universal_Literal_String & ";"); when IEEEL_Digits => P (" range " & IEEEL_First'Universal_Literal_String & " .. " & IEEEL_Last'Universal_Literal_String & ";"); when IEEEX_Digits => P (" range " & IEEEX_First'Universal_Literal_String & " .. " & IEEEX_Last'Universal_Literal_String & ";"); when others => P (";"); end case; -- If one of the floating point types of the host computer has the -- same digits as the target float we are processing, then print out -- the float range using the host computer float type. if Nb_Digits = Short_Float'Digits then P (" -- " & Short_Float'First'Img & " .. " & Short_Float'Last'Img); elsif Nb_Digits = Float'Digits then P (" -- " & Float'First'Img & " .. " & Float'Last'Img); elsif Nb_Digits = Long_Float'Digits then P (" -- " & Long_Float'First'Img & " .. " & Long_Float'Last'Img); elsif Nb_Digits = Long_Long_Float'Digits then P (" -- " & Long_Long_Float'First'Img & " .. " & Long_Long_Float'Last'Img); end if; New_Line; end P_Float_Range; ----------------- -- P_Int_Range -- ----------------- procedure P_Int_Range (Size : Pos; Put_First : Boolean := True) is begin if Put_First then Put (" is range -(2 **" & Pos'Image (Size - 1) & ")"); end if; P (" .. +(2 **" & Pos'Image (Size - 1) & " - 1);"); end P_Int_Range; -- Start of processing for GnatPsta begin P ("package Standard is"); P ("pragma Pure(Standard);"); New_Line; P (" type Boolean is (False, True);"); New_Line; -- Integer types Put (" type Integer"); P_Int_Range (Standard_Integer_Size); New_Line; Put (" subtype Natural is Integer range 0"); P_Int_Range (Standard_Integer_Size, Put_First => False); Put (" subtype Positive is Integer range 1"); P_Int_Range (Standard_Integer_Size, Put_First => False); New_Line; Put (" type Short_Short_Integer"); P_Int_Range (Standard_Short_Short_Integer_Size); Put (" type Short_Integer "); P_Int_Range (Standard_Short_Integer_Size); Put (" type Long_Integer "); P_Int_Range (Standard_Long_Integer_Size); Put (" type Long_Long_Integer "); P_Int_Range (Standard_Long_Long_Integer_Size); New_Line; -- Floating point types P (" type Short_Float is digits" & Standard_Short_Float_Digits'Img); P_Float_Range (Standard_Short_Float_Digits); P (" type Float is digits" & Standard_Float_Digits'Img); P_Float_Range (Standard_Float_Digits); P (" type Long_Float is digits" & Standard_Long_Float_Digits'Img); P_Float_Range (Standard_Long_Float_Digits); P (" type Long_Long_Float is digits" & Standard_Long_Long_Float_Digits'Img); P_Float_Range (Standard_Long_Long_Float_Digits); P (" -- function ""*"" (Left : root_integer; Right : root_real)"); P (" -- return root_real;"); New_Line; P (" -- function ""*"" (Left : root_real; Right : root_integer)"); P (" -- return root_real;"); New_Line; P (" -- function ""/"" (Left : root_real; Right : root_integer)"); P (" -- return root_real;"); New_Line; P (" -- function ""*"" (Left : universal_fixed; " & "Right : universal_fixed)"); P (" -- return universal_fixed;"); New_Line; P (" -- function ""/"" (Left : universal_fixed; " & "Right : universal_fixed)"); P (" -- return universal_fixed;"); New_Line; P (" -- The declaration of type Character is based on the standard"); P (" -- ISO 8859-1 character set."); New_Line; P (" -- There are no character literals corresponding to the positions"); P (" -- for control characters. They are indicated by lower case"); P (" -- identifiers in the following list."); New_Line; P (" -- Note: this type cannot be represented accurately in Ada"); New_Line; P (" -- type Character is"); New_Line; P (" -- (nul, soh, stx, etx, eot, enq, ack, bel,"); P (" -- bs, ht, lf, vt, ff, cr, so, si,"); New_Line; P (" -- dle, dc1, dc2, dc3, dc4, nak, syn, etb,"); P (" -- can, em, sub, esc, fs, gs, rs, us,"); New_Line; P (" -- ' ', '!', '""', '#', '$', '%', '&', ''',"); P (" -- '(', ')', '*', '+', ',', '-', '.', '/',"); New_Line; P (" -- '0', '1', '2', '3', '4', '5', '6', '7',"); P (" -- '8', '9', ':', ';', '<', '=', '>', '?',"); New_Line; P (" -- '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',"); P (" -- 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',"); New_Line; P (" -- 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',"); P (" -- 'X', 'Y', 'Z', '[', '\', ']', '^', '_',"); New_Line; P (" -- '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',"); P (" -- 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',"); New_Line; P (" -- 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',"); P (" -- 'x', 'y', 'z', '{', '|', '}', '~', del,"); New_Line; P (" -- reserved_128, reserved_129, bph, nbh,"); P (" -- reserved_132, nel, ssa, esa,"); New_Line; P (" -- hts, htj, vts, pld, plu, ri, ss2, ss3,"); New_Line; P (" -- dcs, pu1, pu2, sts, cch, mw, spa, epa,"); New_Line; P (" -- sos, reserved_153, sci, csi,"); P (" -- st, osc, pm, apc,"); New_Line; P (" -- ... );"); New_Line; P (" -- The declaration of type Wide_Character is based " & "on the standard"); P (" -- ISO 10646 BMP character set."); New_Line; P (" -- Note: this type cannot be represented accurately in Ada"); New_Line; P (" -- The first 256 positions have the same contents as " & "type Character"); New_Line; P (" -- type Wide_Character is (nul, soh ... FFFE, FFFF);"); New_Line; P (" package ASCII is"); New_Line; P (" -- Control characters:"); New_Line; P (" NUL : constant Character := Character'Val (16#00#);"); P (" SOH : constant Character := Character'Val (16#01#);"); P (" STX : constant Character := Character'Val (16#02#);"); P (" ETX : constant Character := Character'Val (16#03#);"); P (" EOT : constant Character := Character'Val (16#04#);"); P (" ENQ : constant Character := Character'Val (16#05#);"); P (" ACK : constant Character := Character'Val (16#06#);"); P (" BEL : constant Character := Character'Val (16#07#);"); P (" BS : constant Character := Character'Val (16#08#);"); P (" HT : constant Character := Character'Val (16#09#);"); P (" LF : constant Character := Character'Val (16#0A#);"); P (" VT : constant Character := Character'Val (16#0B#);"); P (" FF : constant Character := Character'Val (16#0C#);"); P (" CR : constant Character := Character'Val (16#0D#);"); P (" SO : constant Character := Character'Val (16#0E#);"); P (" SI : constant Character := Character'Val (16#0F#);"); P (" DLE : constant Character := Character'Val (16#10#);"); P (" DC1 : constant Character := Character'Val (16#11#);"); P (" DC2 : constant Character := Character'Val (16#12#);"); P (" DC3 : constant Character := Character'Val (16#13#);"); P (" DC4 : constant Character := Character'Val (16#14#);"); P (" NAK : constant Character := Character'Val (16#15#);"); P (" SYN : constant Character := Character'Val (16#16#);"); P (" ETB : constant Character := Character'Val (16#17#);"); P (" CAN : constant Character := Character'Val (16#18#);"); P (" EM : constant Character := Character'Val (16#19#);"); P (" SUB : constant Character := Character'Val (16#1A#);"); P (" ESC : constant Character := Character'Val (16#1B#);"); P (" FS : constant Character := Character'Val (16#1C#);"); P (" GS : constant Character := Character'Val (16#1D#);"); P (" RS : constant Character := Character'Val (16#1E#);"); P (" US : constant Character := Character'Val (16#1F#);"); P (" DEL : constant Character := Character'Val (16#7F#);"); New_Line; P (" -- Other characters:"); New_Line; P (" Exclam : constant Character := '!';"); P (" Quotation : constant Character := '""';"); P (" Sharp : constant Character := '#';"); P (" Dollar : constant Character := '$';"); P (" Percent : constant Character := '%';"); P (" Ampersand : constant Character := '&';"); P (" Colon : constant Character := ':';"); P (" Semicolon : constant Character := ';';"); P (" Query : constant Character := '?';"); P (" At_Sign : constant Character := '@';"); P (" L_Bracket : constant Character := '[';"); P (" Back_Slash : constant Character := '\';"); P (" R_Bracket : constant Character := ']';"); P (" Circumflex : constant Character := '^';"); P (" Underline : constant Character := '_';"); P (" Grave : constant Character := '`';"); P (" L_Brace : constant Character := '{';"); P (" Bar : constant Character := '|';"); P (" R_Brace : constant Character := '}';"); P (" Tilde : constant Character := '~';"); New_Line; P (" -- Lower case letters:"); New_Line; for C in Character range 'a' .. 'z' loop P (" LC_" & Character'Val (Character'Pos (C) - 32) & " : constant Character := '" & C & "';"); end loop; New_Line; P (" end ASCII;"); New_Line; P (" type String is array (Positive range <>) of Character;"); P (" pragma Pack (String);"); New_Line; P (" type Wide_String is array (Positive range <>) of Wide_Character;"); P (" pragma Pack (Wide_String);"); New_Line; -- Here it's OK to use the Duration type of the host compiler since -- the implementation of Duration in GNAT is target independent. P (" type Duration is delta" & Duration'Image (Duration'Delta)); P (" range -((2 **" & Natural'Image (Duration'Size - 1) & " - 1) *" & Duration'Image (Duration'Delta) & ") .."); P (" +((2 **" & Natural'Image (Duration'Size - 1) & " - 1) *" & Duration'Image (Duration'Delta) & ");"); P (" for Duration'Small use" & Duration'Image (Duration'Small) & ";"); New_Line; P (" Constraint_Error : exception;"); P (" Program_Error : exception;"); P (" Storage_Error : exception;"); P (" Tasking_Error : exception;"); New_Line; P ("end Standard;"); end GnatPsta;
-------------------------------------------------------------------------------- -- Fichier : foret.ads -- Auteur : MOUDDENE Hamza & CAZES Noa -- Objectif : Spécification du module Foret -- Crée : Jeudi Déc 12 2019 -------------------------------------------------------------------------------- with Ensemble; with Arbre_Genealogique; use Arbre_Genealogique; package Foret is -- Type du package Foret qui est privé. type Forest is private; ABSENT_TREE_EXCEPTION : Exception; -- Arbre inexistant. ----------------------------------Constuctor-------------------------------- -- Nom : Initialize_Forest -- Sémantique : Initialiser Forest. Forest est vide. -- Paramètres : -- F -- Forest que l'on va initialiser. procedure Initialize_Forest (F : out Forest); -- Nom : Add_To_Forest -- Sémantique : Ajouter un Arbre dans la Forest. -- Paramètres : -- F -- Forest que l'on va initialiser. -- Ab -- L'arbre qu'on va ajouter procedure Add_To_Forest (F : in out Forest; Ab : in T_ABG); ---------------------------------------------------------------------------- -- Nom : Is_Empty_Forest -- Sémantique : Vérifier si une foret donnée est vide. -- Type_De_Retour : Boolean True si la foret est vide, sinon False. -- Paramètre : -- F : La foret qu'on va parcourir. function Is_Empty_Forest (F : in Forest) return Boolean; -- Nom : Is_Present_Forest -- Sémantique : Vérifier si un arbre est dans la foret. -- Type_De_Retour : Boolean True si un arbre est dans la foret, sinon False. -- Paramètre : -- F : La foret qu'on va parcourir. -- ID : identifiant unique d'un individu dans la foret. function Is_Present_Forest (F : in Forest; ID : Integer) return Boolean; -- Nom : Find_Tree -- Sémantique : Trouver un ID dans la foret. -- Paramètre : -- F : La foret qu'on va parcourir. -- ID : L'ID d'une racine d'arbre dans la foret. procedure Find_Tree (F : in Forest; Ab : out T_ABG; ID : in Integer); -- Nom : Update_Forest -- Sémantique : Mettre à jour la foret. -- Paramètre : -- F : La foret qu'on va parcourir. -- Old_Ab : L'arbre avant la modification. -- New_Ab : L'arbre après la modification. procedure Update_Forest (F : in Forest; Old_Ab, New_Ab : in T_ABG); -- Nom : Remove_Tree -- Sémantique : Supprimer un arbre de la foret. -- Paramètre : -- F : La foret qu'on va parcourir. -- Old_Ab : L'arbre avant la modification. -- New_Ab : L'arbre après la modification. procedure Remove_Tree (F : in out Forest; Ab : in T_ABG); -- Nom : Get_Set_Cohabitant -- Sémantique : Ajouter un concubain à un individu donné. -- Paramètre : -- F : La foret qu'on va parcourir. -- Ab : L'arbre d'un individu dans la foret. procedure Get_Set_Cohabitant (F : in out Forest; ID, Child_ID : in Integer); -- Nom : Get_Set_Half_Brother -- Sémantique : Obtenir l'ensemble des demis frères et demie-soeur d'un individu donné. -- Paramètre : -- F : La foret qu'on va parcourir. -- ID : identifiant unique d'un individu dans la foret. procedure Get_Set_Half_Brother (F : in Forest; ID, Father_ID, Mother_ID : in Integer); -- Nom : Destruct_Forest -- Sémantique : Détruire Forest. Forest est vide. -- Paramètres : -- F -- Forest que l'on va détruire. procedure Destruct_Forest (F : in out Forest); private -- Instancier Ensemble avec T_Element comme T_ABG. package Ens is New Ensemble (T_Element => T_ABG); use Ens; -- Déclaration du type forest comme une liste chainée. type Forest is new T_Ensemble; end Foret;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with GL.Types; package GL.Window is use GL.Types; procedure Set_Viewport (X, Y : Int; Width, Height : Size); procedure Get_Viewport (X, Y : out Int; Width, Height : out Size); procedure Set_Depth_Range (Near, Far : Double); procedure Get_Depth_Range (Near, Far : out Double); end GL.Window;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings; use Ada.Strings; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure primitivos is name: String(1 .. 10); begin Put_Line("Digite seu nome: "); Get(name); Put_line(name); end primitivos;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- SQL Database Access -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2013, 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 Interfaces.C; with League.Strings.Internals; with Matreshka.Internals.Strings; with Matreshka.Internals.Strings.C; with Matreshka.Internals.SQL_Parameter_Rewriters.SQLite3; package body Matreshka.Internals.SQL_Drivers.SQLite3.Queries is use type Interfaces.C.int; use type Matreshka.Internals.Utf16.Utf16_String_Index; procedure Call (Self : not null access SQLite3_Query'Class; Code : Interfaces.C.int); -- Process return code, constructs error message when code is error. Last_Insert_Rowid_Parameter : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("last_insert_rowid"); -- Name of the pseudo-parameter to obtain value of identifier of last -- inserted row. This name must be in casefolded form to pass parameter -- name check. Rewriter : SQL_Parameter_Rewriters.SQLite3.SQLite3_Parameter_Rewriter; -- SQL statement parameter rewriter. ---------------- -- Bind_Value -- ---------------- overriding procedure Bind_Value (Self : not null access SQLite3_Query; Name : League.Strings.Universal_String; Value : League.Holders.Holder; Direction : SQL.Parameter_Directions) is pragma Unreferenced (Direction); -- SQLite3 supports 'in' parameters only. begin Self.Parameters.Set_Value (Name, Value); end Bind_Value; ----------------- -- Bound_Value -- ----------------- overriding function Bound_Value (Self : not null access SQLite3_Query; Name : League.Strings.Universal_String) return League.Holders.Holder is use type League.Strings.Universal_String; begin if Name = Last_Insert_Rowid_Parameter then -- Handle LAST_INSERT_ROWID pseudo-parameter. return Result : League.Holders.Holder do League.Holders.Set_Tag (Result, League.Holders.Universal_Integer_Tag); League.Holders.Replace_Element (Result, Self.Last_Row_Id); end return; end if; return League.Holders.Empty_Holder; end Bound_Value; ---------- -- Call -- ---------- procedure Call (Self : not null access SQLite3_Query'Class; Code : Interfaces.C.int) is begin -- Clear previous error state. Self.Success := True; Self.Error.Clear; case Code is when SQLITE_OK => -- Operation executed successfully. null; when SQLITE_DONE => -- When operation can retrieve row this reasult means that there -- is no row retrived. Self.Has_Row := False; when SQLITE_ROW => -- When operation can retrieve row this reasult means that there -- is row retrived. Self.Has_Row := True; when others => -- All others return codes are errors. Self.Success := False; Self.Error := Matreshka.Internals.Strings.C.To_Valid_Universal_String (sqlite3_errmsg16 (Databases.SQLite3_Database'Class (Self.Database.all).Database_Handle)); end case; end Call; ------------------- -- Error_Message -- ------------------- overriding function Error_Message (Self : not null access SQLite3_Query) return League.Strings.Universal_String is begin return Self.Error; end Error_Message; ------------- -- Execute -- ------------- overriding function Execute (Self : not null access SQLite3_Query) return Boolean is Value : League.Holders.Holder; begin if Self.Handle = null then -- Statement was not prepared. return False; end if; if Self.Is_Active then -- Finish execution of the current statement when it is active. Self.Finish; end if; -- Bind parameters. for J in 1 .. Self.Parameters.Number_Of_Positional loop Value := Self.Parameters.Value (J); if League.Holders.Is_Empty (Value) then -- Bind NULL value of any type (SQLite3 doesn't distinguish type -- of NULL value). Self.Call (sqlite3_bind_null (Self.Handle, Interfaces.C.int (J))); elsif League.Holders.Is_Universal_String (Value) then -- Bind text value. Self.Call (sqlite3_bind_text16 (Self.Handle, Interfaces.C.int (J), League.Strings.Internals.Internal (League.Holders.Element (Value)).Value (0)'Access, Interfaces.C.int (League.Strings.Internals.Internal (League.Holders.Element (Value)).Unused * 2), null)); -- Copy of string value is stored in the parameters map, so -- provides warranty that it will not be deallocated/modified till -- another value will be bind. As result, copy of string data is -- not needed. elsif League.Holders.Is_Abstract_Integer (Value) then -- Bind integer value. Self.Call (sqlite3_bind_int64 (Self.Handle, Interfaces.C.int (J), League.Holders.Element (Value))); elsif League.Holders.Is_Abstract_Float (Value) then -- Bind float value. Self.Call (sqlite3_bind_double (Self.Handle, Interfaces.C.int (J), Interfaces.C.double (League.Holders.Universal_Float' (League.Holders.Element (Value))))); end if; end loop; -- Execute statement. Self.Call (sqlite3_step (Self.Handle)); Self.Skip_Step := Self.Has_Row; if Self.Success then Self.Is_Active := True; end if; -- Store value of last_insert_rowid, it is accessible through -- LAST_INSERT_ROWID output parameter. Self.Last_Row_Id := League.Holders.Universal_Integer (sqlite3_last_insert_rowid (Databases.SQLite3_Database'Class (Self.Database.all).Database_Handle)); return Self.Success; end Execute; ------------ -- Finish -- ------------ overriding procedure Finish (Self : not null access SQLite3_Query) is begin if not Self.Is_Active then -- Returns when query is not active. return; end if; Self.Call (sqlite3_reset (Self.Handle)); Self.Is_Active := False; end Finish; ---------------- -- Initialize -- ---------------- procedure Initialize (Self : not null access SQLite3_Query'Class; Database : not null access Databases.SQLite3_Database'Class) is begin SQL_Drivers.Initialize (Self, Database_Access (Database)); end Initialize; ---------------- -- Invalidate -- ---------------- overriding procedure Invalidate (Self : not null access SQLite3_Query) is begin if Self.Database /= null then if Self.Handle /= null then Self.Call (sqlite3_finalize (Self.Handle)); Self.Handle := null; end if; end if; -- Call Invalidate of parent tagged type. Abstract_Query (Self.all).Invalidate; end Invalidate; --------------- -- Is_Active -- --------------- overriding function Is_Active (Self : not null access SQLite3_Query) return Boolean is begin return Self.Is_Active; end Is_Active; -------------- -- Is_Valid -- -------------- overriding function Is_Valid (Self : not null access SQLite3_Query) return Boolean is begin return Self.Has_Row and not Self.Skip_Step; end Is_Valid; ---------- -- Next -- ---------- overriding function Next (Self : not null access SQLite3_Query) return Boolean is begin if not Self.Is_Active then -- Returns immidiatly when statement is not active. return False; end if; if Self.Skip_Step then Self.Skip_Step := False; elsif Self.Has_Row then Self.Call (sqlite3_step (Self.Handle)); end if; return Self.Has_Row; end Next; ------------- -- Prepare -- ------------- overriding function Prepare (Self : not null access SQLite3_Query; Query : League.Strings.Universal_String) return Boolean is Rewritten : League.Strings.Universal_String; Aux : aliased Matreshka.Internals.Strings.C.Utf16_Code_Unit_Access; begin if Self.Handle /= null then -- Release existing handle. Self.Call (sqlite3_finalize (Self.Handle)); Self.Handle := null; end if; -- Rewrite statement and prepare set of parameters. Rewriter.Rewrite (Query, Rewritten, Self.Parameters); -- Note: http://www.sqlite.org/c3ref/prepare.html -- -- "If the caller knows that the supplied string is nul-terminated, then -- there is a small performance advantage to be gained by passing an -- nByte parameter that is equal to the number of bytes in the input -- string including the nul-terminator bytes." -- -- And it's exactly our case. Self.Call (sqlite3_prepare16_v2 (Databases.SQLite3_Database'Class (Self.Database.all).Database_Handle, League.Strings.Internals.Internal (Rewritten).Value, Interfaces.C.int ((League.Strings.Internals.Internal (Rewritten).Unused + 1) * 2), Self.Handle'Unchecked_Access, Aux'Unchecked_Access)); Self.Is_Active := False; return Self.Success; end Prepare; ----------- -- Value -- ----------- overriding function Value (Self : not null access SQLite3_Query; Index : Positive) return League.Holders.Holder is Text : Matreshka.Internals.Strings.C.Utf16_Code_Unit_Access; Length : Matreshka.Internals.Utf16.Utf16_String_Index; Value : League.Holders.Holder; begin case sqlite3_column_type (Self.Handle, Interfaces.C.int (Index - 1)) is when SQLITE_INTEGER => -- Create universal integer value. League.Holders.Set_Tag (Value, League.Holders.Universal_Integer_Tag); League.Holders.Replace_Element (Value, sqlite3_column_int64 (Self.Handle, Interfaces.C.int (Index - 1))); when SQLITE_FLOAT => -- Create universal float value. League.Holders.Set_Tag (Value, League.Holders.Universal_Float_Tag); League.Holders.Replace_Element (Value, League.Holders.Universal_Float (sqlite3_column_double (Self.Handle, Interfaces.C.int (Index - 1)))); when SQLITE_TEXT => -- Create universal string value. Text := sqlite3_column_text16 (Self.Handle, Interfaces.C.int (Index - 1)); Length := Matreshka.Internals.Utf16.Utf16_String_Index (sqlite3_column_bytes16 (Self.Handle, Interfaces.C.int (Index - 1))); League.Holders.Set_Tag (Value, League.Holders.Universal_String_Tag); if Length = 0 then League.Holders.Replace_Element (Value, League.Strings.Empty_Universal_String); else League.Holders.Replace_Element (Value, Matreshka.Internals.Strings.C.To_Valid_Universal_String (Text, Length / 2)); end if; when SQLITE_BLOB => -- Not supported yet. null; when SQLITE_NULL => -- Value is initialized to be empty by default. null; when others => null; end case; return Value; end Value; end Matreshka.Internals.SQL_Drivers.SQLite3.Queries;
----------------------------------------------------------------------- -- net-interfaces-stm32 -- Ethernet driver for STM32F74x -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Ada.Interrupts.Names; with Ada.Unchecked_Conversion; with STM32.SDRAM; with STM32.Eth; use STM32; with STM32_SVD.Ethernet; with HAL; with Cortex_M.Cache; package body Net.Interfaces.STM32 is use HAL; use STM32_SVD.Ethernet; function W is new Ada.Unchecked_Conversion (System.Address, HAL.UInt32); type Tx_Position is new Uint32 range 0 .. TX_RING_SIZE; type Rx_Position is new Uint32 range 0 .. RX_RING_SIZE; type Tx_Ring is limited record Buffer : Net.Buffers.Buffer_Type; Desc : Eth.Tx_Desc_Type; end record; type Tx_Ring_Access is access all Tx_Ring; type Tx_Ring_Array_Type is array (Tx_Position) of aliased Tx_Ring; type Tx_Ring_Array_Type_Access is access all Tx_Ring_Array_Type; type Rx_Ring is limited record Buffer : Net.Buffers.Buffer_Type; Desc : Eth.Rx_Desc_Type; end record; type Rx_Ring_Access is access all Rx_Ring; type Rx_Ring_Array_Type is array (Rx_Position) of aliased Rx_Ring; type Rx_Ring_Array_Type_Access is access all Rx_Ring_Array_Type; function As_Rx_Ring_Array_Type_Access is new Ada.Unchecked_Conversion (System.Address, Rx_Ring_Array_Type_Access); Tx_Ring_Instance : aliased Tx_Ring_Array_Type; function Next_Tx (Value : in Tx_Position) return Tx_Position; function Next_Rx (Value : in Rx_Position) return Rx_Position; function Next_Rx (Value : in Rx_Position) return Rx_Position is begin if Value = Rx_Position'Last then return Rx_Position'First; else return Value + 1; end if; end Next_Rx; function Next_Tx (Value : in Tx_Position) return Tx_Position is begin if Value = Tx_Position'Last then return Tx_Position'First; else return Value + 1; end if; end Next_Tx; protected Transmit_Queue with Priority => Net.Network_Priority is entry Send (Buf : in out Net.Buffers.Buffer_Type); procedure Transmit_Interrupt; procedure Initialize; -- Check if the transmit queue is initialized. function Is_Ready return Boolean; private -- Transmit queue management. Tx_Space : Uint32 := 0; Tx_Ready : Boolean := False; Cur_Tx : Tx_Position := 0; Dma_Tx : Tx_Position := 0; Tx_Ring : Tx_Ring_Array_Type_Access; end Transmit_Queue; protected Receive_Queue with Interrupt_Priority => Net.Network_Priority is entry Wait_Packet (Buf : in out Net.Buffers.Buffer_Type); procedure Initialize (List : in out Net.Buffers.Buffer_List); procedure Receive_Interrupt; procedure Interrupt with Attach_Handler => Ada.Interrupts.Names.ETH_Interrupt, Unreferenced; -- Check if the receive queue is initialized. function Is_Ready return Boolean; private -- Receive queue management. Rx_Count : Uint32 := 0; Rx_Available : Boolean := False; Cur_Rx : Rx_Position := 0; Dma_Rx : Rx_Position := 0; Rx_Total : Uint32 := 0; Rx_Ring : Rx_Ring_Array_Type_Access; end Receive_Queue; overriding procedure Send (Ifnet : in out STM32_Ifnet; Buf : in out Net.Buffers.Buffer_Type) is use type Net.Uint64; begin Ifnet.Tx_Stats.Packets := Ifnet.Tx_Stats.Packets + 1; Ifnet.Tx_Stats.Bytes := Ifnet.Tx_Stats.Bytes + Net.Uint64 (Buf.Get_Length); Transmit_Queue.Send (Buf); end Send; overriding procedure Receive (Ifnet : in out STM32_Ifnet; Buf : in out Net.Buffers.Buffer_Type) is use type Net.Uint64; begin Receive_Queue.Wait_Packet (Buf); Ifnet.Rx_Stats.Packets := Ifnet.Rx_Stats.Packets + 1; Ifnet.Rx_Stats.Bytes := Ifnet.Rx_Stats.Bytes + Net.Uint64 (Buf.Get_Length); end Receive; -- ------------------------------ -- Returns true if the interface driver is ready to receive or send packets. -- ------------------------------ function Is_Ready (Ifnet : in STM32_Ifnet) return Boolean is pragma Unreferenced (Ifnet); begin return Receive_Queue.Is_Ready and Transmit_Queue.Is_Ready; end Is_Ready; -- ------------------------------ -- Initialize the network interface. -- ------------------------------ overriding procedure Initialize (Ifnet : in out STM32_Ifnet) is pragma Unreferenced (Ifnet); Size : constant Uint32 := Rx_Ring_Array_Type'Length * Buffers.NET_ALLOC_SIZE; Addr : System.Address; List : Net.Buffers.Buffer_List; begin Eth.Initialize_RMII; -- Allocate Rx buffers. Addr := SDRAM.Reserve (Amount => HAL.UInt32 (Size)); Net.Buffers.Add_Region (Addr => Addr, Size => Size); -- Get the Rx buffers for the receive ring creation. Net.Buffers.Allocate (List, Rx_Ring_Array_Type'Length); Receive_Queue.Initialize (List); -- Setup the transmit ring (there is no buffer to allocate -- because we have nothing to send). Transmit_Queue.Initialize; end Initialize; protected body Transmit_Queue is entry Send (Buf : in out Net.Buffers.Buffer_Type) when Tx_Ready is Tx : constant Tx_Ring_Access := Tx_Ring (Cur_Tx)'Access; Addr : constant System.Address := Buf.Get_Data_Address; Size : constant UInt13 := UInt13 (Buf.Get_Length); begin Tx.Buffer.Transfer (Buf); Cortex_M.Cache.Clean_DCache (Addr, Integer (Size)); Tx.Desc.Tdes2 := Addr; Tx.Desc.Tdes1.Tbs1 := Size; Tx.Desc.Tdes0 := (Own => 1, Cic => 3, Reserved_2 => 0, Ls => 1, Fs => 1, Ic => 1, Cc => 0, Tch => 1, Ter => (if (Cur_Tx = Tx_Position'Last) then 1 else 0), others => 0); Cortex_M.Cache.Clean_DCache (Tx.Desc'Address, Tx.Desc'Size / 8); Tx_Space := Tx_Space - 1; Tx_Ready := Tx_Space > 0; Ethernet_DMA_Periph.DMAOMR.ST := True; if Ethernet_DMA_Periph.DMASR.TBUS then Ethernet_DMA_Periph.DMASR.TBUS := True; end if; if Ethernet_DMA_Periph.DMASR.TPS = 6 then Ethernet_DMA_Periph.DMAOMR.ST := False; Ethernet_DMA_Periph.DMACHTDR := W (Tx.Desc'Address); Ethernet_DMA_Periph.DMAOMR.ST := True; end if; Ethernet_DMA_Periph.DMATPDR := 1; Cur_Tx := Next_Tx (Cur_Tx); end Send; procedure Transmit_Interrupt is Tx : Tx_Ring_Access; begin loop Tx := Tx_Ring (Dma_Tx)'Access; Cortex_M.Cache.Invalidate_DCache (Tx.Desc'Address, Tx.Desc'Size / 8); exit when Tx.Desc.Tdes0.Own = 1; -- We can release the buffer after it is transmitted. Net.Buffers.Release (Tx.Buffer); Tx_Space := Tx_Space + 1; Dma_Tx := Next_Tx (Dma_Tx); exit when Dma_Tx = Cur_Tx; end loop; Ethernet_DMA_Periph.DMATPDR := 1; end Transmit_Interrupt; procedure Initialize is begin Tx_Ring := Tx_Ring_Instance'Access; --- new Tx_Ring_Array_Type; for I in Tx_Ring'Range loop Tx_Ring (I).Desc.Tdes0 := (Own => 0, Ic => 1, Ls => 1, Fs => 1, Dc => 0, Dp => 0, Ttse => 0, Tch => 1, Ter => (if I = Tx_Ring'Last then 1 else 0), others => <>); Tx_Ring (I).Desc.Tdes1 := (Tbs2 => 0, Tbs1 => 0, Reserved_13_15 => 0, Reserved_29_31 => 0); Tx_Ring (I).Desc.Tdes2 := System.Null_Address; Tx_Ring (I).Desc.Tdes4 := 0; Tx_Ring (I).Desc.Tdes5 := 0; Tx_Ring (I).Desc.Tdes6 := 0; Tx_Ring (I).Desc.Tdes7 := 0; if I /= Tx_Ring'Last then Tx_Ring (I).Desc.Tdes3 := Tx_Ring (I + 1).Desc'Address; else Tx_Ring (I).Desc.Tdes3 := System.Null_Address; end if; end loop; Tx_Space := Tx_Ring'Length; Tx_Ready := True; Cur_Tx := 0; Dma_Tx := 0; Ethernet_DMA_Periph.DMATDLAR := W (Tx_Ring (Tx_Ring'First).Desc'Address); Ethernet_MAC_Periph.MACCR.TE := True; Ethernet_DMA_Periph.DMAIER.TIE := True; Ethernet_DMA_Periph.DMAIER.TBUIE := True; -- Use Store-and-forward mode for the TCP/UDP/ICMP/IP checksum offload calculation. Ethernet_DMA_Periph.DMAOMR.TSF := True; Ethernet_DMA_Periph.DMAOMR.SR := True; end Initialize; -- ------------------------------ -- Check if the transmit queue is initialized. -- ------------------------------ function Is_Ready return Boolean is begin return Tx_Ring /= null; end Is_Ready; end Transmit_Queue; protected body Receive_Queue is entry Wait_Packet (Buf : in out Net.Buffers.Buffer_Type) when Rx_Available is Rx : constant Rx_Ring_Access := Rx_Ring (Cur_Rx)'Access; begin Cortex_M.Cache.Invalidate_DCache (Rx.Desc'Address, Rx.Desc'Size / 8); Rx.Buffer.Set_Length (Net.Uint16 (Rx.Desc.Rdes0.Fl)); Net.Buffers.Switch (Buf, Rx.Buffer); Rx.Desc.Rdes2 := W (Rx.Buffer.Get_Data_Address); Rx.Desc.Rdes0.Own := 1; Cortex_M.Cache.Clean_DCache (Rx.Desc'Address, Integer (Rx.Desc'Size / 8)); Rx_Count := Rx_Count - 1; Rx_Available := Rx_Count > 0; Cur_Rx := Next_Rx (Cur_Rx); Ethernet_MAC_Periph.MACCR.RE := True; end Wait_Packet; procedure Receive_Interrupt is Rx : Rx_Ring_Access; begin loop Rx := Rx_Ring (Dma_Rx)'Access; exit when Rx.Desc.Rdes0.Own = 1; Rx_Count := Rx_Count + 1; Rx_Total := Rx_Total + 1; Rx_Available := True; Dma_Rx := Next_Rx (Dma_Rx); if Dma_Rx = Cur_Rx then Ethernet_MAC_Periph.MACCR.RE := False; return; end if; end loop; end Receive_Interrupt; procedure Initialize (List : in out Net.Buffers.Buffer_List) is Addr : System.Address; begin Addr := SDRAM.Reserve (Amount => Rx_Ring_Array_Type'Size / 8); Rx_Ring := As_Rx_Ring_Array_Type_Access (Addr); -- Setup the RX ring and allocate buffer for each descriptor. for I in Rx_Ring'Range loop Net.Buffers.Peek (List, Rx_Ring (I).Buffer); Rx_Ring (I).Desc.Rdes0 := (Own => 1, others => <>); Rx_Ring (I).Desc.Rdes2 := W (Rx_Ring (I).Buffer.Get_Data_Address); Rx_Ring (I).Desc.Rdes4 := (Reserved_31_14 => 0, Pmt => 0, Ippt => 0, others => 0); Rx_Ring (I).Desc.Rdes5 := 0; Rx_Ring (I).Desc.Rdes6 := 0; Rx_Ring (I).Desc.Rdes7 := 0; if I /= Rx_Ring'Last then Rx_Ring (I).Desc.Rdes1 := (Dic => 0, Rbs2 => 0, Rer => 0, Rch => 1, Rbs => UInt13 (Net.Buffers.NET_BUF_SIZE), others => <>); Rx_Ring (I).Desc.Rdes3 := W (Rx_Ring (I + 1).Desc'Address); else Rx_Ring (I).Desc.Rdes1 := (Dic => 0, Rbs2 => 0, Rer => 1, Rch => 1, Rbs => UInt13 (Net.Buffers.NET_BUF_SIZE), others => <>); Rx_Ring (I).Desc.Rdes3 := W (System.Null_Address); end if; end loop; Ethernet_DMA_Periph.DMARDLAR := W (Rx_Ring (Rx_Ring'First).Desc'Address); -- Ethernet Ethernet_MAC_Periph initialization comes from AdaCore stm32-eth.adb. -- FIXME: check speed, full duplex Ethernet_MAC_Periph.MACCR := (CSTF => True, WD => False, JD => False, IFG => 2#100#, CSD => False, FES => True, ROD => True, LM => False, DM => True, IPCO => False, RD => False, APCS => True, BL => 2#10#, DC => True, TE => False, RE => False, others => <>); Ethernet_MAC_Periph.MACFFR := (RA => True, others => <>); Ethernet_MAC_Periph.MACHTHR := 0; Ethernet_MAC_Periph.MACHTLR := 0; Ethernet_MAC_Periph.MACFCR := (PT => 0, ZQPD => False, PLT => 0, UPFD => False, RFCE => True, TFCE => True, FCB => False, others => <>); Ethernet_MAC_Periph.MACVLANTR := (VLANTC => False, VLANTI => 0, others => <>); Ethernet_MAC_Periph.MACPMTCSR := (WFFRPR => False, GU => False, WFR => False, MPR => False, WFE => False, MPE => False, PD => False, others => <>); Ethernet_MAC_Periph.MACCR.RE := True; Ethernet_DMA_Periph.DMAIER.RIE := True; Ethernet_DMA_Periph.DMAIER.NISE := True; Ethernet_DMA_Periph.DMAOMR.SR := True; Ethernet_DMA_Periph.DMABMR := (SR => False, DA => False, DSL => 0, EDFE => False, PBL => 4, RTPR => 0, FB => True, RDP => 4, USP => True, FPM => False, AAB => False, MB => False, others => <>); -- Start receiver. Ethernet_DMA_Periph.DMARPDR := 1; end Initialize; procedure Interrupt is begin if Ethernet_DMA_Periph.DMASR.RS then Ethernet_DMA_Periph.DMASR.RS := True; Receive_Queue.Receive_Interrupt; end if; if Ethernet_DMA_Periph.DMASR.TS then Ethernet_DMA_Periph.DMASR.TS := True; Transmit_Queue.Transmit_Interrupt; elsif Ethernet_DMA_Periph.DMASR.TBUS then Ethernet_DMA_Periph.DMASR.TBUS := True; end if; Ethernet_DMA_Periph.DMASR.NIS := True; end Interrupt; -- ------------------------------ -- Check if the receive queue is initialized. -- ------------------------------ function Is_Ready return Boolean is begin return Rx_Ring /= null; end Is_Ready; end Receive_Queue; end Net.Interfaces.STM32;
declare type Integer_Ptr is access Integer; Ptr : Integer_Ptr := new Integer; -- Allocated in the heap begin ... end; -- Memory is freed because Integer_Ptr is finalized
with Ada.Text_IO, Crypto.Types.Big_Numbers, Ada.Numerics.Discrete_Random; procedure Miller_Rabin is Bound: constant Positive := 256; -- can be any multiple of 32 package LN is new Crypto.Types.Big_Numbers (Bound); use type LN.Big_Unsigned; -- all computations "mod 2**Bound" function "+"(S: String) return LN.Big_Unsigned renames LN.Utils.To_Big_Unsigned; S: constant String := "4547337172376300111955330758342147474062293202868155909489"; T: constant String := "4547337172376300111955330758342147474062293202868155909393"; K: constant Positive := 10; begin Ada.Text_IO.Put_Line("Prime(" & S & ")=" & Boolean'Image (LN.Mod_Utils.Passed_Miller_Rabin_Test(+S, K))); Ada.Text_IO.Put_Line("Prime(" & T & ")=" & Boolean'Image (LN.Mod_Utils.Passed_Miller_Rabin_Test(+T, K))); end Miller_Rabin;
------------------------------------------------------------------------------- -- LSE -- L-System Editor -- Author: Heziode -- -- License: -- MIT License -- -- Copyright (c) 2018 Quentin Dauprat (Heziode) <Heziode@protonmail.com> -- -- 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.Strings.Unbounded; with LSE.Utils.Angle; with LSE.Model.Interpreter; with LSE.Model.L_System.Growth_Rule_Utils; with LSE.Model.Grammar.Symbol_Utils; with LSE.Model.IO.Turtle_Utils; use Ada.Strings.Unbounded; use LSE.Model.Interpreter; use LSE.Model.IO.Turtle_Utils; -- @description -- This package represent a L-System. -- package LSE.Model.L_System.L_System is -- Representing a L-System type Instance is new Interpreter.Instance with private; -- Constructor procedure Initialize (This : out Instance; Axiom : LSE.Model.Grammar.Symbol_Utils.P_List.List; Angle : LSE.Utils.Angle.Angle; Rules : LSE.Model.L_System.Growth_Rule_Utils.P_List.List; Turtle : LSE.Model.IO.Turtle_Utils.Holder); -- Accessor of current state function Get_State (This : Instance) return Natural; -- Mutator of current state procedure Set_State (This : out Instance; Value : Natural); -- Getting a string representation of this L-System function Get_LSystem (This : Instance) return String; -- Getting a string representation of the current development function Get_Value (This : Instance) return String; -- Getting the current development function Get_Value (This : Instance) return LSE.Model.Grammar.Symbol_Utils.P_List.List; -- Accessor of Turtle function Get_Turtle (This : Instance) return LSE.Model.IO.Turtle_Utils.Holder; -- Mutator of Turtle procedure Set_Turtle (This : out Instance; Value : LSE.Model.IO.Turtle_Utils.Holder); -- Develop this L-System to the next step procedure Develop (This : out Instance); overriding procedure Interpret (This : in out Instance; T : in out Holder); private type Instance is new Interpreter.Instance with record -- State to develop State : Natural := 0; -- Currently developed state Current_State : Natural := 0; -- Axiom Axiom : LSE.Model.Grammar.Symbol_Utils.P_List.List; -- Angle Angle : LSE.Utils.Angle.Angle; -- Growth rules Rules : LSE.Model.L_System.Growth_Rule_Utils.P_List.List; -- List of symbol of the currently developed state Current_Value : LSE.Model.Grammar.Symbol_Utils.P_List.List; -- "Empty" turtle to compute L-System dimensions during develop Turtle : LSE.Model.IO.Turtle_Utils.Holder; end record; -- Getting the string representation of a symbol list function Get_Symbol_List (This : LSE.Model.Grammar.Symbol_Utils.P_List.List) return Unbounded_String; -- Compute dimension of the L-System procedure Compute_Dimension (This : in out Instance); end LSE.Model.L_System.L_System;
with Courbes.Visiteurs; use Courbes.Visiteurs; package body Courbes.Bezier_Cubiques is function Obtenir_Controle1 (Self : Bezier_Cubique) return Point2D is begin return Self.Controles (1); end; function Obtenir_Controle2 (Self : Bezier_Cubique) return Point2D is begin return Self.Controles (2); end; function Ctor_Bezier_Cubique (Debut, Fin, C1, C2 : Point2D) return Bezier_Cubique is Controles : constant Bezier_Cubique_Controles := (1 => C1, 2 => C2); begin return (Debut => Debut, Fin => Fin, Controles => Controles); end; overriding function Obtenir_Point(Self : Bezier_Cubique; X : Coordonnee_Normalisee) return Point2D is begin return (1.0 - X) ** 3 * Self.Debut + 3.0 * X * (1.0 - X) ** 2 * Self.Controles (1) + 3.0 * X ** 2 * (1.0 - X) * Self.Controles (2) + X ** 3 * Self.Fin; end; overriding procedure Accepter (Self : Bezier_Cubique; Visiteur : Visiteur_Courbe'Class) is begin Visiteur.Visiter (Self); end; end Courbes.Bezier_Cubiques;
pragma License (Unrestricted); package Ada.Strings is pragma Pure; Space : constant Character := ' '; Wide_Space : constant Wide_Character := ' '; Wide_Wide_Space : constant Wide_Wide_Character := ' '; Length_Error, Pattern_Error, Index_Error, Translation_Error : exception; type Alignment is (Left, Right, Center); type Truncation is (Left, Right, Error); type Membership is (Inside, Outside); type Direction is (Forward, Backward); type Trim_End is (Left, Right, Both); end Ada.Strings;
-- 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 EGL.API; with EGL.Objects.Displays; with EGL.Errors; package body EGL.Objects.Devices is function Extensions (Object : Device) return String_List is begin Check_Extension (Displays.Client_Extensions, "EGL_EXT_device_query"); declare Result : constant C.Strings.chars_ptr := API.Query_Device_String.Ref (Object.ID, Extensions); use all type C.Strings.chars_ptr; begin if Result = C.Strings.Null_Ptr then Errors.Raise_Exception_On_EGL_Error; return (1 .. 0 => SU.To_Unbounded_String ("")); else return EGL.Extensions (Result); end if; end; end Extensions; function DRM_Name (Object : Device) return String is begin Check_Extension (Object.Extensions, "EGL_EXT_device_drm"); declare Result : constant C.Strings.chars_ptr := API.Query_Device_String.Ref (Object.ID, DRM_Device_File); use all type C.Strings.chars_ptr; begin if Result = C.Strings.Null_Ptr then Errors.Raise_Exception_On_EGL_Error; return ""; else return Trim (Result); end if; end; end DRM_Name; function Name (Object : Device) return String is begin return DRM_Name (Object); exception when Feature_Not_Supported => return ""; end Name; function Devices return Device_List is Max_Devices : constant := 16; Devices : ID_Array (1 .. Max_Devices); Count : Int := 0; begin Check_Extension (Displays.Client_Extensions, "EGL_EXT_device_enumeration"); if API.Query_Devices.Ref (Max_Devices, Devices, Count) then return Result : Device_List (1 .. Natural (Count)) do for Index in Result'Range loop Result (Index).Reference.ID := Devices (Index); pragma Assert (Result (Index).Display = No_Display); end loop; end return; else Errors.Raise_Exception_On_EGL_Error; return (1 .. 0 => <>); end if; end Devices; function Get_Device (Subject : Displays.Display) return Device is Device_Ext : constant Int := 16#322C#; ID : ID_Type; begin Check_Extension (Displays.Client_Extensions, "EGL_EXT_device_query"); if API.Query_Display_Attrib.Ref (Subject.ID, Device_Ext, ID) then return Result : Device do Result.Reference.ID := ID; -- The device needs to keep a reference to the display, -- otherwise the display can get finalized and any further -- use of the device would then give undefined results pragma Assert (Result.Display = No_Display); Result.Display := (Ada.Finalization.Controlled with Reference => EGL_Object (Subject).Reference); Result.Display.Reference.Count := Result.Display.Reference.Count + 1; pragma Assert (Result.Display /= No_Display); end return; else Errors.Raise_Exception_On_EGL_Error; return Result : Device; end if; end Get_Device; end EGL.Objects.Devices;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2013, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.Internals.Tables.CMOF_Types; package AMF.Internals.Tables.CMOF_Attribute_Mappings is pragma Preelaborate; CMOF_Collection_Offset : constant array (AMF.Internals.Tables.CMOF_Types.Element_Kinds, AMF.Internals.CMOF_Element range 34 .. 78) of AMF.Internals.AMF_Collection_Of_Element := (AMF.Internals.Tables.CMOF_Types.E_None => (others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Association => (43 => 9, -- Classifier::attribute 58 => 4, -- Namespace::elementImport 34 => 15, -- Association::endType 44 => 10, -- Classifier::feature 45 => 11, -- Classifier::general 59 => 3, -- Namespace::importedMember 46 => 12, -- Classifier::inheritedMember 60 => 7, -- Namespace::member 35 => 16, -- Association::memberEnd 36 => 17, -- Association::navigableOwnedEnd 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 37 => 14, -- Association::ownedEnd 61 => 6, -- Namespace::ownedMember 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport 77 => 13, -- Relationship::relatedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Class => (43 => 9, -- Classifier::attribute 58 => 4, -- Namespace::elementImport 44 => 10, -- Classifier::feature 45 => 11, -- Classifier::general 59 => 3, -- Namespace::importedMember 46 => 12, -- Classifier::inheritedMember 60 => 7, -- Namespace::member 40 => 13, -- Class::ownedAttribute 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 61 => 6, -- Namespace::ownedMember 41 => 14, -- Class::ownedOperation 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport 42 => 15, -- Class::superClass others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Comment => (47 => 3, -- Comment::annotatedElement 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Constraint => (48 => 3, -- Constraint::constrainedElement 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Data_Type => (43 => 9, -- Classifier::attribute 58 => 4, -- Namespace::elementImport 44 => 10, -- Classifier::feature 45 => 11, -- Classifier::general 59 => 3, -- Namespace::importedMember 46 => 12, -- Classifier::inheritedMember 60 => 7, -- Namespace::member 49 => 13, -- DataType::ownedAttribute 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 61 => 6, -- Namespace::ownedMember 50 => 14, -- DataType::ownedOperation 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Element_Import => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 77 => 13, -- Relationship::relatedElement 51 => 3, -- DirectedRelationship::source 52 => 4, -- DirectedRelationship::target others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Enumeration => (43 => 9, -- Classifier::attribute 58 => 4, -- Namespace::elementImport 44 => 10, -- Classifier::feature 45 => 11, -- Classifier::general 59 => 3, -- Namespace::importedMember 46 => 12, -- Classifier::inheritedMember 60 => 7, -- Namespace::member 49 => 13, -- DataType::ownedAttribute 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 55 => 15, -- Enumeration::ownedLiteral 61 => 6, -- Namespace::ownedMember 50 => 14, -- DataType::ownedOperation 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Enumeration_Literal => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Expression => (56 => 3, -- Expression::operand 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Opaque_Expression => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Operation => (58 => 4, -- Namespace::elementImport 57 => 11, -- Feature::featuringClassifier 59 => 3, -- Namespace::importedMember 60 => 7, -- Namespace::member 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 61 => 6, -- Namespace::ownedMember 64 => 16, -- Operation::ownedParameter 38 => 12, -- BehavioralFeature::ownedParameter 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport 65 => 18, -- Operation::postcondition 66 => 17, -- Operation::precondition 67 => 14, -- Operation::raisedException 39 => 13, -- BehavioralFeature::raisedException 75 => 10, -- RedefinableElement::redefinedElement 68 => 15, -- Operation::redefinedOperation 76 => 9, -- RedefinableElement::redefinitionContext others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package => (58 => 4, -- Namespace::elementImport 59 => 3, -- Namespace::importedMember 60 => 7, -- Namespace::member 69 => 11, -- Package::nestedPackage 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 61 => 6, -- Namespace::ownedMember 62 => 8, -- Namespace::ownedRule 70 => 10, -- Package::ownedType 63 => 5, -- Namespace::packageImport 71 => 12, -- Package::packageMerge 72 => 9, -- Package::packagedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package_Import => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 77 => 13, -- Relationship::relatedElement 51 => 3, -- DirectedRelationship::source 52 => 4, -- DirectedRelationship::target others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package_Merge => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 77 => 13, -- Relationship::relatedElement 51 => 3, -- DirectedRelationship::source 52 => 4, -- DirectedRelationship::target others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Parameter => (53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Primitive_Type => (43 => 9, -- Classifier::attribute 58 => 4, -- Namespace::elementImport 44 => 10, -- Classifier::feature 45 => 11, -- Classifier::general 59 => 3, -- Namespace::importedMember 46 => 12, -- Classifier::inheritedMember 60 => 7, -- Namespace::member 49 => 13, -- DataType::ownedAttribute 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 61 => 6, -- Namespace::ownedMember 50 => 14, -- DataType::ownedOperation 62 => 8, -- Namespace::ownedRule 63 => 5, -- Namespace::packageImport others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Property => (57 => 11, -- Feature::featuringClassifier 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement 75 => 10, -- RedefinableElement::redefinedElement 73 => 3, -- Property::redefinedProperty 76 => 9, -- RedefinableElement::redefinitionContext 74 => 4, -- Property::subsettedProperty others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Tag => (78 => 3, -- Tag::element 53 => 2, -- Element::ownedComment 54 => 1, -- Element::ownedElement others => 0)); CMOF_Member_Offset : constant array (AMF.Internals.Tables.CMOF_Types.Element_Kinds, AMF.Internals.CMOF_Element range 79 .. 135) of Natural := (AMF.Internals.Tables.CMOF_Types.E_None => (others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Association => (79 => 13, -- Association::isDerived 81 => 7, -- Classifier::isFinalSpecialization 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 134 => 6, -- Type::package 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Class => (80 => 8, -- Class::isAbstract 81 => 7, -- Classifier::isFinalSpecialization 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 134 => 6, -- Type::package 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Comment => (82 => 2, -- Comment::body 85 => 1, -- Element::owner others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Constraint => (83 => 7, -- Constraint::context 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 84 => 6, -- Constraint::specification 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Data_Type => (81 => 7, -- Classifier::isFinalSpecialization 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 134 => 6, -- Type::package 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Element_Import => (86 => 3, -- ElementImport::alias 87 => 4, -- ElementImport::importedElement 88 => 5, -- ElementImport::importingNamespace 85 => 1, -- Element::owner 89 => 2, -- ElementImport::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Enumeration => (81 => 7, -- Classifier::isFinalSpecialization 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 134 => 6, -- Type::package 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Enumeration_Literal => (90 => 6, -- EnumerationLiteral::enumeration 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Expression => (95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 135 => 6, -- TypedElement::type 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Opaque_Expression => (99 => 7, -- OpaqueExpression::body 100 => 8, -- OpaqueExpression::language 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 135 => 6, -- TypedElement::type 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Operation => (101 => 15, -- Operation::bodyCondition 102 => 12, -- Operation::class 103 => 13, -- Operation::datatype 130 => 11, -- RedefinableElement::isLeaf 104 => 7, -- Operation::isOrdered 105 => 6, -- Operation::isQuery 106 => 8, -- Operation::isUnique 107 => 9, -- Operation::lower 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 108 => 14, -- Operation::type 109 => 10, -- Operation::upper 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package => (95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 110 => 6, -- Package::nestingPackage 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 111 => 7, -- Package::uri 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package_Import => (112 => 3, -- PackageImport::importedPackage 113 => 4, -- PackageImport::importingNamespace 85 => 1, -- Element::owner 114 => 2, -- PackageImport::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Package_Merge => (115 => 3, -- PackageMerge::mergedPackage 85 => 1, -- Element::owner 116 => 2, -- PackageMerge::receivingPackage others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Parameter => (117 => 12, -- Parameter::default 118 => 11, -- Parameter::direction 91 => 7, -- MultiplicityElement::isOrdered 92 => 8, -- MultiplicityElement::isUnique 93 => 9, -- MultiplicityElement::lower 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 119 => 13, -- Parameter::operation 85 => 1, -- Element::owner 97 => 5, -- NamedElement::qualifiedName 135 => 6, -- TypedElement::type 94 => 10, -- MultiplicityElement::upper 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Primitive_Type => (81 => 7, -- Classifier::isFinalSpecialization 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 85 => 1, -- Element::owner 134 => 6, -- Type::package 97 => 5, -- NamedElement::qualifiedName 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Property => (120 => 21, -- Property::association 121 => 17, -- Property::class 122 => 20, -- Property::datatype 123 => 12, -- Property::default 124 => 15, -- Property::isComposite 125 => 13, -- Property::isDerived 126 => 16, -- Property::isDerivedUnion 130 => 11, -- RedefinableElement::isLeaf 91 => 7, -- MultiplicityElement::isOrdered 127 => 14, -- Property::isReadOnly 92 => 8, -- MultiplicityElement::isUnique 93 => 9, -- MultiplicityElement::lower 95 => 2, -- NamedElement::name 96 => 4, -- NamedElement::namespace 128 => 19, -- Property::opposite 85 => 1, -- Element::owner 129 => 18, -- Property::owningAssociation 97 => 5, -- NamedElement::qualifiedName 135 => 6, -- TypedElement::type 94 => 10, -- MultiplicityElement::upper 98 => 3, -- NamedElement::visibility others => 0), AMF.Internals.Tables.CMOF_Types.E_CMOF_Tag => (131 => 2, -- Tag::name 85 => 1, -- Element::owner 132 => 4, -- Tag::tagOwner 133 => 3, -- Tag::value others => 0)); end AMF.Internals.Tables.CMOF_Attribute_Mappings;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012-2015, 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 Ada.Streams; with League.Stream_Element_Vectors.Internals; with League.Strings.Internals; with Matreshka.Internals.Stream_Element_Vectors; with Matreshka.Internals.Strings.Configuration; with Matreshka.Internals.Utf16; package body League.Base_Codecs is use type Ada.Streams.Stream_Element; use type Ada.Streams.Stream_Element_Offset; use type Matreshka.Internals.Utf16.Utf16_Code_Unit; use type Matreshka.Internals.Utf16.Utf16_String_Index; procedure Decode_64 (Item : Matreshka.Internals.Utf16.Utf16_Code_Unit; Value : out Ada.Streams.Stream_Element; Success : out Boolean); procedure Decode_64_URL (Item : Matreshka.Internals.Utf16.Utf16_Code_Unit; Value : out Ada.Streams.Stream_Element; Success : out Boolean); Encode_64 : constant array (Ada.Streams.Stream_Element range 0 .. 63) of Matreshka.Internals.Utf16.Utf16_Code_Unit := (Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'), Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'), Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'), Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'), Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'), Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'), Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'), Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'), Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'), Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'), Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'), Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'), Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'), Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'), Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'), Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('+'), Character'Pos ('/')); Encode_64_URL : constant array (Ada.Streams.Stream_Element range 0 .. 63) of Matreshka.Internals.Utf16.Utf16_Code_Unit := (Character'Pos ('A'), Character'Pos ('B'), Character'Pos ('C'), Character'Pos ('D'), Character'Pos ('E'), Character'Pos ('F'), Character'Pos ('G'), Character'Pos ('H'), Character'Pos ('I'), Character'Pos ('J'), Character'Pos ('K'), Character'Pos ('L'), Character'Pos ('M'), Character'Pos ('N'), Character'Pos ('O'), Character'Pos ('P'), Character'Pos ('Q'), Character'Pos ('R'), Character'Pos ('S'), Character'Pos ('T'), Character'Pos ('U'), Character'Pos ('V'), Character'Pos ('W'), Character'Pos ('X'), Character'Pos ('Y'), Character'Pos ('Z'), Character'Pos ('a'), Character'Pos ('b'), Character'Pos ('c'), Character'Pos ('d'), Character'Pos ('e'), Character'Pos ('f'), Character'Pos ('g'), Character'Pos ('h'), Character'Pos ('i'), Character'Pos ('j'), Character'Pos ('k'), Character'Pos ('l'), Character'Pos ('m'), Character'Pos ('n'), Character'Pos ('o'), Character'Pos ('p'), Character'Pos ('q'), Character'Pos ('r'), Character'Pos ('s'), Character'Pos ('t'), Character'Pos ('u'), Character'Pos ('v'), Character'Pos ('w'), Character'Pos ('x'), Character'Pos ('y'), Character'Pos ('z'), Character'Pos ('0'), Character'Pos ('1'), Character'Pos ('2'), Character'Pos ('3'), Character'Pos ('4'), Character'Pos ('5'), Character'Pos ('6'), Character'Pos ('7'), Character'Pos ('8'), Character'Pos ('9'), Character'Pos ('-'), Character'Pos ('_')); --------------- -- Decode_64 -- --------------- procedure Decode_64 (Item : Matreshka.Internals.Utf16.Utf16_Code_Unit; Value : out Ada.Streams.Stream_Element; Success : out Boolean) is begin Success := True; case Item is when Character'Pos ('A') .. Character'Pos ('Z') => Value := Ada.Streams.Stream_Element (Item) - Character'Pos ('A'); when Character'Pos ('a') .. Character'Pos ('z') => Value := Ada.Streams.Stream_Element (Item) - Character'Pos ('a') + 26; when Character'Pos ('0') .. Character'Pos ('9') => Value := Ada.Streams.Stream_Element (Item) - Character'Pos ('0') + 52; when Character'Pos ('+') => Value := 62; when Character'Pos ('/') => Value := 63; when Character'Pos ('=') => Value := 0; when others => Success := False; end case; end Decode_64; ------------------- -- Decode_64_URL -- ------------------- procedure Decode_64_URL (Item : Matreshka.Internals.Utf16.Utf16_Code_Unit; Value : out Ada.Streams.Stream_Element; Success : out Boolean) is begin Success := True; case Item is when Character'Pos ('A') .. Character'Pos ('Z') => Value := Ada.Streams.Stream_Element (Item) - Character'Pos ('A'); when Character'Pos ('a') .. Character'Pos ('z') => Value := Ada.Streams.Stream_Element (Item) - Character'Pos ('a') + 26; when Character'Pos ('0') .. Character'Pos ('9') => Value := Ada.Streams.Stream_Element (Item) - Character'Pos ('0') + 52; when Character'Pos ('-') => Value := 62; when Character'Pos ('_') => Value := 63; when Character'Pos ('=') => Value := 0; when others => Success := False; end case; end Decode_64_URL; ------------------ -- From_Base_64 -- ------------------ function From_Base_64 (Data : League.Strings.Universal_String) return League.Stream_Element_Vectors.Stream_Element_Vector is Aux : League.Stream_Element_Vectors.Stream_Element_Vector; Success : Boolean; begin From_Base_64 (Data, Aux, Success); if Success then return Aux; else raise Constraint_Error with "Mailformed base64 data"; end if; end From_Base_64; ------------------ -- From_Base_64 -- ------------------ procedure From_Base_64 (Data : League.Strings.Universal_String; Value : in out League.Stream_Element_Vectors.Stream_Element_Vector; Success : out Boolean) is Source : constant Matreshka.Internals.Strings.Shared_String_Access := League.Strings.Internals.Internal (Data); Size : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (Source.Length) / 4 * 3; Target : Matreshka.Internals.Stream_Element_Vectors .Shared_Stream_Element_Vector_Access := League.Stream_Element_Vectors.Internals.Internal (Value); Unused : Ada.Streams.Stream_Element_Offset := 0; First : Matreshka.Internals.Utf16.Utf16_String_Index := 0; begin if Source.Length = 0 then Value.Clear; Success := True; return; end if; if Source.Length mod 4 /= 0 then Value.Clear; Success := False; return; end if; -- Check whether storage of passed internal object can be reused, and -- create new shared object if can't. if not Matreshka.Internals.Stream_Element_Vectors.Can_Be_Reused (Target, Size) then Target := Matreshka.Internals.Stream_Element_Vectors.Allocate (Size); League.Stream_Element_Vectors.Internals.Replace (Value, Target); end if; while Source.Unused > First loop declare S1 : constant Matreshka.Internals.Utf16.Utf16_Code_Unit := Source.Value (First); S2 : constant Matreshka.Internals.Utf16.Utf16_Code_Unit := Source.Value (First + 1); S3 : constant Matreshka.Internals.Utf16.Utf16_Code_Unit := Source.Value (First + 2); S4 : constant Matreshka.Internals.Utf16.Utf16_Code_Unit := Source.Value (First + 3); A1 : Ada.Streams.Stream_Element; A2 : Ada.Streams.Stream_Element; A3 : Ada.Streams.Stream_Element; A4 : Ada.Streams.Stream_Element; begin Decode_64 (S1, A1, Success); exit when not Success; Decode_64 (S2, A2, Success); exit when not Success; Target.Value (Unused) := (A1 * 4) or ((A2 and 2#0011_0000#) / 16); Unused := Unused + 1; if S3 /= Character'Pos ('=') then Decode_64 (S3, A3, Success); exit when not Success; Target.Value (Unused) := ((A2 and 2#0000_1111#) * 16) or ((A3 and 2#0011_1100#) / 4); Unused := Unused + 1; if S4 /= Character'Pos ('=') then Decode_64 (S4, A4, Success); exit when not Success; Target.Value (Unused) := ((A3 and 2#0000_0011#) * 64) or A4; Unused := Unused + 1; end if; end if; First := First + 4; end; end loop; Target.Length := Unused; end From_Base_64; ---------------------- -- From_Base_64_URL -- ---------------------- function From_Base_64_URL (Data : League.Strings.Universal_String) return League.Stream_Element_Vectors.Stream_Element_Vector is Aux : League.Stream_Element_Vectors.Stream_Element_Vector; Success : Boolean; begin From_Base_64_URL (Data, Aux, Success); if Success then return Aux; else raise Constraint_Error with "Mailformed base64url data"; end if; end From_Base_64_URL; ---------------------- -- From_Base_64_URL -- ---------------------- procedure From_Base_64_URL (Data : League.Strings.Universal_String; Value : in out League.Stream_Element_Vectors.Stream_Element_Vector; Success : out Boolean) is Source : constant Matreshka.Internals.Strings.Shared_String_Access := League.Strings.Internals.Internal (Data); Size : constant Ada.Streams.Stream_Element_Offset := Ada.Streams.Stream_Element_Offset (Source.Length) / 4 * 3; Target : Matreshka.Internals.Stream_Element_Vectors .Shared_Stream_Element_Vector_Access := League.Stream_Element_Vectors.Internals.Internal (Value); Unused : Ada.Streams.Stream_Element_Offset := 0; First : Matreshka.Internals.Utf16.Utf16_String_Index := 0; begin if Source.Length = 0 then Value.Clear; Success := True; return; end if; if Source.Length mod 4 = 0 then -- Check whether storage of passed internal object can be reused, and -- create new shared object if can't. if not Matreshka.Internals.Stream_Element_Vectors.Can_Be_Reused (Target, Size) then Target := Matreshka.Internals.Stream_Element_Vectors.Allocate (Size); League.Stream_Element_Vectors.Internals.Replace (Value, Target); end if; while Source.Unused > First loop declare S1 : constant Matreshka.Internals.Utf16.Utf16_Code_Unit := Source.Value (First); S2 : constant Matreshka.Internals.Utf16.Utf16_Code_Unit := Source.Value (First + 1); S3 : constant Matreshka.Internals.Utf16.Utf16_Code_Unit := Source.Value (First + 2); S4 : constant Matreshka.Internals.Utf16.Utf16_Code_Unit := Source.Value (First + 3); A1 : Ada.Streams.Stream_Element; A2 : Ada.Streams.Stream_Element; A3 : Ada.Streams.Stream_Element; A4 : Ada.Streams.Stream_Element; begin Decode_64_URL (S1, A1, Success); exit when not Success; Decode_64_URL (S2, A2, Success); exit when not Success; Target.Value (Unused) := (A1 * 4) or ((A2 and 2#0011_0000#) / 16); Unused := Unused + 1; if S3 /= Character'Pos ('=') then Decode_64_URL (S3, A3, Success); exit when not Success; Target.Value (Unused) := ((A2 and 2#0000_1111#) * 16) or ((A3 and 2#0011_1100#) / 4); Unused := Unused + 1; if S4 /= Character'Pos ('=') then Decode_64_URL (S4, A4, Success); exit when not Success; Target.Value (Unused) := ((A3 and 2#0000_0011#) * 64) or A4; Unused := Unused + 1; end if; end if; First := First + 4; end; end loop; Target.Length := Unused; if Target.Length = 0 then Value.Clear; end if; else Value.Clear; Success := False; end if; end From_Base_64_URL; ---------------- -- To_Base_64 -- ---------------- function To_Base_64 (Data : League.Stream_Element_Vectors.Stream_Element_Vector) return League.Strings.Universal_String is Source : constant Matreshka.Internals.Stream_Element_Vectors .Shared_Stream_Element_Vector_Access := League.Stream_Element_Vectors.Internals.Internal (Data); Target : Matreshka.Internals.Strings.Shared_String_Access; First : Ada.Streams.Stream_Element_Offset := 0; Unused : Matreshka.Internals.Utf16.Utf16_String_Index := 0; Aux : Ada.Streams.Stream_Element; begin -- Return empty string when data is empty. if Source.Length = 0 then return League.Strings.Empty_Universal_String; end if; -- Allocate string for result. (Length + 2) / 3 * 4 is exact required -- length for the result. Target := Matreshka.Internals.Strings.Allocate (Matreshka.Internals.Utf16.Utf16_String_Index ((Source.Length + 2) / 3 * 4)); -- Encode each triplet of bytes when available. while Source.Length - First >= 3 loop declare S1 : constant Ada.Streams.Stream_Element := Source.Value (First); S2 : constant Ada.Streams.Stream_Element := Source.Value (First + 1); S3 : constant Ada.Streams.Stream_Element := Source.Value (First + 2); begin Aux := (S1 and 2#1111_1100#) / 4; Target.Value (Unused) := Encode_64 (Aux); Unused := Unused + 1; Aux := ((S1 and 2#0000_0011#) * 16) or ((S2 and 2#1111_0000#) / 16); Target.Value (Unused) := Encode_64 (Aux); Unused := Unused + 1; Aux := ((S2 and 2#0000_1111#) * 4) or ((S3 and 2#1100_0000#) / 64); Target.Value (Unused) := Encode_64 (Aux); Unused := Unused + 1; Aux := S3 and 2#0011_1111#; Target.Value (Unused) := Encode_64 (Aux); Unused := Unused + 1; end; First := First + 3; end loop; if Source.Length - First = 1 then declare S1 : constant Ada.Streams.Stream_Element := Source.Value (First); begin Aux := (S1 and 2#1111_1100#) / 4; Target.Value (Unused) := Encode_64 (Aux); Unused := Unused + 1; Aux := (S1 and 2#0000_0011#) * 16; Target.Value (Unused) := Encode_64 (Aux); Unused := Unused + 1; Target.Value (Unused) := Character'Pos ('='); Unused := Unused + 1; Target.Value (Unused) := Character'Pos ('='); Unused := Unused + 1; end; elsif Source.Length - First = 2 then declare S1 : constant Ada.Streams.Stream_Element := Source.Value (First); S2 : constant Ada.Streams.Stream_Element := Source.Value (First + 1); begin Aux := (S1 and 2#1111_1100#) / 4; Target.Value (Unused) := Encode_64 (Aux); Unused := Unused + 1; Aux := ((S1 and 2#0000_0011#) * 16) or ((S2 and 2#1111_0000#) / 16); Target.Value (Unused) := Encode_64 (Aux); Unused := Unused + 1; Aux := (S2 and 2#0000_1111#) * 4; Target.Value (Unused) := Encode_64 (Aux); Unused := Unused + 1; Target.Value (Unused) := Character'Pos ('='); Unused := Unused + 1; end; end if; Target.Unused := Unused; Target.Length := Integer (Target.Unused); -- All characters of base64 character set occupy one code unit, thus -- length of the string is always equal to the number of used code -- units. Matreshka.Internals.Strings.Configuration.String_Handler .Fill_Null_Terminator (Target); return League.Strings.Internals.Wrap (Target); exception when others => Matreshka.Internals.Strings.Dereference (Target); raise; end To_Base_64; -------------------- -- To_Base_64_URL -- -------------------- function To_Base_64_URL (Data : League.Stream_Element_Vectors.Stream_Element_Vector) return League.Strings.Universal_String is Source : constant Matreshka.Internals.Stream_Element_Vectors .Shared_Stream_Element_Vector_Access := League.Stream_Element_Vectors.Internals.Internal (Data); Target : Matreshka.Internals.Strings.Shared_String_Access; First : Ada.Streams.Stream_Element_Offset := 0; Unused : Matreshka.Internals.Utf16.Utf16_String_Index := 0; Aux : Ada.Streams.Stream_Element; begin -- Return empty string when data is empty. if Source.Length = 0 then return League.Strings.Empty_Universal_String; end if; -- Allocate string for result. (Length + 2) / 3 * 4 is exact required -- length for the result. Target := Matreshka.Internals.Strings.Allocate (Matreshka.Internals.Utf16.Utf16_String_Index ((Source.Length + 2) / 3 * 4)); -- Encode each triplet of bytes when available. while Source.Length - First >= 3 loop declare S1 : constant Ada.Streams.Stream_Element := Source.Value (First); S2 : constant Ada.Streams.Stream_Element := Source.Value (First + 1); S3 : constant Ada.Streams.Stream_Element := Source.Value (First + 2); begin Aux := (S1 and 2#1111_1100#) / 4; Target.Value (Unused) := Encode_64_URL (Aux); Unused := Unused + 1; Aux := ((S1 and 2#0000_0011#) * 16) or ((S2 and 2#1111_0000#) / 16); Target.Value (Unused) := Encode_64_URL (Aux); Unused := Unused + 1; Aux := ((S2 and 2#0000_1111#) * 4) or ((S3 and 2#1100_0000#) / 64); Target.Value (Unused) := Encode_64_URL (Aux); Unused := Unused + 1; Aux := S3 and 2#0011_1111#; Target.Value (Unused) := Encode_64_URL (Aux); Unused := Unused + 1; end; First := First + 3; end loop; if Source.Length - First = 1 then declare S1 : constant Ada.Streams.Stream_Element := Source.Value (First); begin Aux := (S1 and 2#1111_1100#) / 4; Target.Value (Unused) := Encode_64_URL (Aux); Unused := Unused + 1; Aux := (S1 and 2#0000_0011#) * 16; Target.Value (Unused) := Encode_64_URL (Aux); Unused := Unused + 1; Target.Value (Unused) := Character'Pos ('='); Unused := Unused + 1; Target.Value (Unused) := Character'Pos ('='); Unused := Unused + 1; end; elsif Source.Length - First = 2 then declare S1 : constant Ada.Streams.Stream_Element := Source.Value (First); S2 : constant Ada.Streams.Stream_Element := Source.Value (First + 1); begin Aux := (S1 and 2#1111_1100#) / 4; Target.Value (Unused) := Encode_64_URL (Aux); Unused := Unused + 1; Aux := ((S1 and 2#0000_0011#) * 16) or ((S2 and 2#1111_0000#) / 16); Target.Value (Unused) := Encode_64_URL (Aux); Unused := Unused + 1; Aux := (S2 and 2#0000_1111#) * 4; Target.Value (Unused) := Encode_64_URL (Aux); Unused := Unused + 1; Target.Value (Unused) := Character'Pos ('='); Unused := Unused + 1; end; end if; Target.Unused := Unused; Target.Length := Integer (Target.Unused); -- All characters of base64 character set occupy one code unit, thus -- length of the string is always equal to the number of used code -- units. Matreshka.Internals.Strings.Configuration.String_Handler .Fill_Null_Terminator (Target); return League.Strings.Internals.Wrap (Target); exception when others => Matreshka.Internals.Strings.Dereference (Target); raise; end To_Base_64_URL; end League.Base_Codecs;
with Ada.Command_Line, Ada.Text_IO; use Ada.Command_Line, Ada.Text_IO; procedure Argv is begin Put_Line( "Command : " & Command_Name ); Put( "Args(" & Integer'Image(Argument_Count) & " ) : " ); Put( "[ " ); for I in 1 .. Argument_Count loop Put( Argument(I) & " "); end loop; Put_Line( "]" ); end Argv;
-- Project: StratoX -- Authors: Martin Becker (becker@rcs.ei.tum.de) -- Emanuel Regnath (emanuel.regnath@tum.de) -- -- Description: -- allows logging of structured messages at several logging levels. -- -- Usage: -- Logger.init -- initializes the Logger -- Logger.log_console (Logger.INFO, "Program started.") -- writes log on info level to console -- Logger.log_sd (Logger.INFO, gps_msg) -- writes GPS record to SD card -- Logger.log (Logger.INFO, "hello") -- writes to both SD and console with Config.Tasking; with SDLog; with NVRAM; with Buildinfo; with HIL.Devices; with HIL.UART; with HIL.Random; with Interfaces; use Interfaces; with Ada.Unchecked_Conversion; with Ada.Real_Time; use Ada.Real_Time; with Bounded_Image; with ULog; -- force elaboration of those before the logging task starts pragma Elaborate_All (SDLog); pragma Elaborate_All (Ulog); -- @summary Simultaneously writes to UART, and SD card. package body Logger with SPARK_Mode, Refined_State => (LogState => (queue_ulog, Logging_Task, logger_level)) is -- the type for the queue buffer type Buffer_Ulog is array (Natural range <>) of ULog.Message; -- IMPORTANT: no discriminant (=mutable) type bufpos is mod LOG_QUEUE_LENGTH; -- if GNATprove crashes with reference to that file, -- then you have run into bug KP-160-P601-005. -- workaround: move decl of protected type to package spec. --------------------- -- LOG QUEUE TYPE --------------------- -- protected type to implement the ULog queue protected type Ulog_Queue_T is procedure Enable; -- initially the queue does not accept messages -- call this after everything has been set up -- (SD log, etc.). procedure New_Msg (msg : in ULog.Message); -- enqueue new message. this is not blocking, except to ensure mutex. -- it is fast (only memcpy), but it can silently fail if buffer is full. -- FIXME: how can we specify a precondition on the private variable? -- for now we put an assertion in the body entry Get_Msg (msg : out ULog.Message; n_queued_before : out Natural) with Pre => not msg'Constrained; -- try to get new message from buffer. if empty, this is blocking -- until buffer has data, and then returns it. -- FIXME: how can we specify a precondition on the private variable? -- for now we put an assertion in the body -- FIXME: we need to specify a precondition, that msg is a mutable -- variant record. Otherwise a discriminant check will fail. function Get_Num_Overflows return Natural; -- query how often the buffer overflowed. If this happens, either increase -- the buffer QUEUE_LENGTH, or increase priority of the logger task. function Get_Length return Natural; -- query number of messages waiting in the logging queue. private Buffer : Buffer_Ulog (0 .. LOG_QUEUE_LENGTH - 1); -- cannot use a discriminant for this (would violate No_Implicit_Heap_Allocations) Queue_Enable : Boolean := False; Num_Queued : Natural := 0; Not_Empty : Boolean := False; -- simple barrier (Ravenscar) Pos_Read : bufpos := 0; Pos_Write : bufpos := 0; Num_Overflows : Natural := 0; -- cannot use a dynamic predicate to etablish relationship, because this requires -- a record. But we cannot have a record, since this would make Not_Empty a -- non-simple barrier (=> Ravenscar violation). end Ulog_Queue_T; -- sporadic logging task waking up when message is enqueued task Logging_Task is pragma Priority (Config.Tasking.TASK_PRIO_LOGGING); -- lowest prio for logging end Logging_Task; pragma Annotate (GNATprove, Intentional, """sdlog.fh_log"" might not be initialized before start of tasks of type ""Logging_Task""", "The queue will not accept values before fh_log is initialized. MBe."); ---------------------------- -- PROTOTYPES ---------------------------- subtype Img_String is String (1 .. 3); function Image (level : Log_Level) return Img_String; procedure Write_Bytes_To_SD (len : Natural; buf : HIL.Byte_Array) with Pre => buf'Last >= buf'First and then len <= Natural (Unsigned_16'Last) and then buf'Length >= len; ---------------------------- -- INTERNAL STATES ---------------------------- queue_ulog : Ulog_Queue_T; logger_level : Log_Level := DEBUG; --With_SDLog : Boolean := False; -------------- -- LOG TASK -------------- -- the task which logs to SD card in the background -- XXX: compiler assumes that all the code in a task body is potentially -- executed at elaboration time if a task is declared at the library level. -- thus, all callees here have to be elaborated before this task. task body Logging_Task is msg : ULog.Message; -- IMPORTANT: no discriminant -> mutable. Otherwise exceptions. BUFLEN : constant := 512; bytes : HIL.Byte_Array (1 .. BUFLEN); len : Natural; type loginfo_ratio is mod 100; -- every one out of this will be a log message about the queue r : loginfo_ratio := 0; n_que : Natural; max_q : Natural := 0; -- max. queue level between queue logs begin loop queue_ulog.Get_Msg (msg, n_que); -- under mutex, must be fast ULog.Serialize_Ulog (msg, len, bytes); -- this can be slow again Write_Bytes_To_SD (len => len, buf => bytes); if n_que > max_q then max_q := n_que; end if; -- occasionally log queue state (overflows, num_queued). r := r + 1; if r = 0 then declare m : ULog.Message (ULog.LOG_QUEUE); n_ovf : constant Natural := queue_ulog.Get_Num_Overflows; begin m.t := Ada.Real_Time.Clock; if n_ovf > Natural (Unsigned_16'Last) then m.n_overflows := Unsigned_16'Last; else m.n_overflows := Unsigned_16 (n_ovf); end if; if max_q > Natural (Unsigned_8'Last) then m.max_queued := Unsigned_8'Last; else m.max_queued := Unsigned_8 (max_q); end if; if n_que > Natural (Unsigned_8'Last) then m.n_queued := Unsigned_8'Last; else m.n_queued := Unsigned_8 (n_que); end if; ULog.Serialize_Ulog (m, len, bytes); Write_Bytes_To_SD (len => len, buf => bytes); max_q := 0; end; end if; end loop; end Logging_Task; -- implementation of the message queue protected body Ulog_Queue_T is procedure Enable is begin Queue_Enable := True; end Enable; procedure New_Msg (msg : in ULog.Message) is begin if Queue_Enable then Buffer (Integer (Pos_Write)) := msg; pragma Annotate (GNATprove, False_Positive, "discriminant check might fail", "GNATprove does not see that the buffer consists of mutable variant records. MBe"); Pos_Write := Pos_Write + 1; if Num_Queued < Buffer'Last then Num_Queued := Num_Queued + 1; else -- =Buffer'Last Pos_Read := Pos_Read + 1; -- overwrite oldest if Num_Overflows < Natural'Last then Num_Overflows := Num_Overflows + 1; end if; end if; Not_Empty := (Num_Queued > 0); pragma Assert ((Not_Empty and (Num_Queued > 0)) or ((not Not_Empty) and (Num_Queued = 0))); end if; end New_Msg; entry Get_Msg (msg : out ULog.Message; n_queued_before : out Natural) when Not_Empty is begin pragma Assume (Num_Queued > 0); -- via barrier and assert in New_Msg msg := Buffer (Integer (Pos_Read)); n_queued_before := Num_Queued; Pos_Read := Pos_Read + 1; Num_Queued := Num_Queued - 1; Not_Empty := Num_Queued > 0; pragma Assert ((Not_Empty and (Num_Queued > 0)) or ((not Not_Empty) and (Num_Queued = 0))); end Get_Msg; function Get_Num_Overflows return Natural is (Num_Overflows); function Get_Length return Natural is (Num_Queued); end Ulog_Queue_T; ----------------------- -- Write_Bytes_To_SD ----------------------- -- slow procedure! Takes Byte_Array, converts to SD data type and writes procedure Write_Bytes_To_SD (len : Natural; buf : HIL.Byte_Array) is begin if len > 0 then declare pragma Assert (len > 0); subtype Bytes_ULog is HIL.Byte_Array (1 .. len); up : constant Unsigned_16 := Unsigned_16 (len); subtype SD_Data_ULog is SDLog.SDLog_Data (1 .. up); function To_FileData is new Ada.Unchecked_Conversion (Bytes_ULog, SD_Data_ULog); buf_last : constant Integer := buf'First + (len - 1); n_wr : Integer; pragma Unreferenced (n_wr); begin if SDLog.Is_Open then -- defensive programming. We should not get here w/o opened log SDLog.Write_Log (To_FileData (buf (buf'First .. buf_last)), n_wr); end if; end; end if; end Write_Bytes_To_SD; -- HAL, only change Adapter to port Code package body Adapter is procedure init_adapter (status : out Init_Error_Code) is begin -- HIL.UART.configure; already done in CPU.initialize status := SUCCESS; end init_adapter; procedure write (message : Message_Type) is CR : constant Character := Character'Val (13); -- ASCII begin if message'Last < Integer'Last then HIL.UART.write(HIL.Devices.Console, HIL.UART.toData_Type ( message & CR ) ); else -- no space left for CR HIL.UART.write(HIL.Devices.Console, HIL.UART.toData_Type ( message )); end if; end write; end Adapter; -------------- -- Init -------------- procedure Init (status : out Init_Error_Code) is begin SDLog.Init; Adapter.init_adapter (status); end Init; ----------- -- Image ----------- function Image (level : Log_Level) return Img_String is begin return (case level is when SENSOR => "S: ", when ERROR => "E: ", when WARN => "W: ", when INFO => "I: ", when DEBUG => "D: ", when TRACE => "T: " ); end Image; procedure log(msg_level : Log_Level; message : Message_Type) is text_msg : ULog.Message( ULog.TEXT ); now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; maxlen : constant Integer := (if message'Length > text_msg.txt'Length then text_msg.txt'Length else message'Length); begin log_console (msg_level, message); if maxlen > 0 then if Log_Level'Pos (msg_level) <= Log_Level'Pos (INFO) then text_msg.t := now; declare idx_t : constant Integer := text_msg.txt'First - 1 + maxlen; idx_m : constant Integer := message'First + (maxlen - 1); begin text_msg.txt(text_msg.txt'First .. idx_t) := message (message'First .. idx_m); text_msg.txt_last := idx_m; end; log_sd (msg_level, text_msg); end if; end if; end log; ----------------- -- log_console ----------------- procedure log_console (msg_level : Log_Level; message : Message_Type) with SPARK_Mode => Off is begin if Log_Level'Pos (msg_level) <= Log_Level'Pos (logger_level) then Adapter.write (Image (msg_level) & message); end if; end log_console; ---------------- -- log_sd ---------------- procedure log_sd (msg_level : Log_Level; message : ULog.Message) is begin if Log_Level'Pos (msg_level) <= Log_Level'Pos (logger_level) then queue_ulog.New_Msg (message); end if; end log_sd; ------------------- -- set_log_level ------------------- procedure Set_Log_Level (level : Log_Level) is begin logger_level := level; end Set_Log_Level; ------------------- -- Start_SDLog ------------------- procedure Start_SDLog is num_boots : HIL.Byte; rand32 : Unsigned_32; begin NVRAM.Load (variable => NVRAM.VAR_BOOTCOUNTER, data => num_boots); HIL.Random.Get_Unsigned (rand32); declare buildstring : constant String := Buildinfo.Short_Datetime; bootstr : constant String := Bounded_Image.Unsigned8_Img (num_boots); rnd : constant Unsigned_8 := Unsigned_8 (16#FF# and rand32); rndstr : constant String := Bounded_Image.Unsigned8_Img (rnd); fname : constant String := bootstr(bootstr'First .. bootstr'Last) & "_" & rndstr & ".log"; BUFLEN : constant := 128; -- header is around 90 bytes long bytes : HIL.Byte_Array (1 .. BUFLEN); len : Natural; valid : Boolean; log_started : Boolean; begin SDLog.Start_Logfile (dirname => buildstring, filename => fname, ret => log_started); if not log_started then log_console (Logger.ERROR, "Cannot create logfile: " & buildstring & "/" & fname); else log_console (Logger.WARN, "Log name: " & buildstring & "/" & fname); -- write file header (ULog message definitions) Get_Ulog_Defs_Loop : loop ULog.Get_Header_Ulog (bytes, len, valid); pragma Annotate (GNATprove, Intentional, """bytes"" might not be initialized", "MBe"); exit Get_Ulog_Defs_Loop when not valid; if len > 0 then Write_Bytes_To_SD (len => len, buf => bytes); end if; end loop Get_Ulog_Defs_Loop; queue_ulog.Enable; end if; end; end Start_SDLog; end Logger;
with AUnit.Assertions; use AUnit.Assertions; with Brackelib; package body Stacks_Tests is Container : State_Stacks.Stack; procedure Set_Up (T : in out Test) is begin null; end Set_Up; procedure Test_Push (T : in out Test) is begin Assert (Size (Container) = 0, "Incorrect size before push"); Push (Container, 314); Assert (Size (Container) = 1, "Incorrect size after push"); end Test_Push; procedure Test_Pop (T : in out Test) is begin Assert (Size (Container) = 1, "Incorrect size after push"); Assert (Pop (Container) = 314, "Incorrect value from pop"); Assert (Size (Container) = 0, "Incorrect size after pop"); Assert (Pop (Container) = 1234, "Exception Stack_Empty not raised"); exception when Stack_Empty => null; end Test_Pop; procedure Test_Top (T : in out Test) is begin Push (Container, 315); Assert (Size (Container) = 1, "Incorrect size after push"); Assert (Top (Container) = 315, "Incorrect value from top"); Assert (Size (Container) = 1, "Incorrect size after top"); end Test_Top; procedure Test_Clear (T : in out Test) is begin Push (Container, 316); Assert (Size (Container) = 2, "Incorrect size after push"); Clear (Container); Assert (Size (Container) = 0, "Incorrect size after clear"); end Test_Clear; end Stacks_Tests;
----------------------------------------------------------------------- -- servlet-responses.web -- Servlet Responses with AWS server -- Copyright (C) 2009, 2010, 2011, 2017, 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 AWS.Headers; with AWS.Messages; with AWS.Response.Set; with AWS.Containers.Tables; package body Servlet.Responses.Web is procedure Initialize (Resp : in out Response) is begin Resp.Content.Initialize (Size => 256 * 1024, Output => Resp'Unchecked_Access); Resp.Stream := Resp.Content'Unchecked_Access; end Initialize; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ procedure Write (Stream : in out Response; Buffer : in Ada.Streams.Stream_Element_Array) is begin AWS.Response.Set.Append_Body (D => Stream.Data, Item => Buffer); end Write; -- ------------------------------ -- Flush the buffer (if any) to the sink. -- ------------------------------ procedure Flush (Stream : in out Response) is begin null; end Flush; function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code; function To_Status_Code (Status : in Natural) return AWS.Messages.Status_Code is use AWS.Messages; begin case Status is when 100 => return S100; when 101 => return S101; when 102 => return S102; when 200 => return S200; when 201 => return S201; when 202 => return S202; when 203 => return S203; when 204 => return S204; when 205 => return S205; when 206 => return S206; when 207 => return S207; when 301 => return S301; when 302 => return S302; when 400 => return S400; when 401 => return S401; when 402 => return S402; when 403 => return S403; when 404 => return S404; when 405 => return S405; when others => return S500; end case; end To_Status_Code; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Resp : in Response; Process : not null access procedure (Name : in String; Value : in String)) is Headers : constant AWS.Headers.List := AWS.Response.Header (Resp.Data); begin AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (Headers), ";", Process); end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Resp : in Response; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- ------------------------------ -- Sets a response header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ procedure Set_Header (Resp : in out Response; Name : in String; Value : in String) is begin if AWS.Response.Header (Resp.Data, Name)'Length = 0 then AWS.Response.Set.Add_Header (D => Resp.Data, Name => Name, Value => Value); end if; end Set_Header; -- ------------------------------ -- Adds a response header with the given name and value. -- This method allows response headers to have multiple values. -- ------------------------------ procedure Add_Header (Resp : in out Response; Name : in String; Value : in String) is begin AWS.Response.Set.Add_Header (D => Resp.Data, Name => Name, Value => Value); end Add_Header; -- ------------------------------ -- Sends a temporary redirect response to the client using the specified redirect -- location URL. This method can accept relative URLs; the servlet container must -- convert the relative URL to an absolute URL before sending the response to the -- client. If the location is relative without a leading '/' the container -- interprets it as relative to the current request URI. If the location is relative -- with a leading '/' the container interprets it as relative to the servlet -- container root. -- -- If the response has already been committed, this method throws an -- IllegalStateException. After using this method, the response should be -- considered to be committed and should not be written to. -- ------------------------------ procedure Send_Redirect (Resp : in out Response; Location : in String) is begin Response'Class (Resp).Set_Status (SC_FOUND); Response'Class (Resp).Set_Header (Name => "Location", Value => Location); Resp.Redirect := True; end Send_Redirect; -- ------------------------------ -- Prepare the response data by collecting the status, content type and message body. -- ------------------------------ procedure Build (Resp : in out Response) is begin if not Resp.Redirect then AWS.Response.Set.Content_Type (D => Resp.Data, Value => Resp.Get_Content_Type); Resp.Content.Flush; if AWS.Response.Is_Empty (Resp.Data) then AWS.Response.Set.Message_Body (Resp.Data, ""); end if; else AWS.Response.Set.Mode (D => Resp.Data, Value => AWS.Response.Header); end if; AWS.Response.Set.Status_Code (D => Resp.Data, Value => To_Status_Code (Resp.Get_Status)); end Build; -- ------------------------------ -- Get the response data -- ------------------------------ function Get_Data (Resp : in Response) return AWS.Response.Data is begin return Resp.Data; end Get_Data; end Servlet.Responses.Web;
------------------------------------------------------------------------------ -- -- -- GNU ADA RUNTIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . T A S K I N G . Q U E U I N G -- -- -- -- S p e c -- -- -- -- $Revision: 2 $ -- -- -- -- Copyright (c) 1991,1992,1993,1994, FSU, All Rights Reserved -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU Library General Public License as published by the -- -- Free Software Foundation; either version 2, or (at your option) any -- -- later version. GNARL is distributed in the hope that it will be use- -- -- ful, but but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Gen- -- -- eral Library Public License for more details. You should have received -- -- a copy of the GNU Library General Public License along with GNARL; see -- -- file COPYING.LIB. If not, write to the Free Software Foundation, 675 -- -- Mass Ave, Cambridge, MA 02139, USA. -- -- -- ------------------------------------------------------------------------------ with System.Tasking.Utilities; -- Used for, Utilities.ATCB_Ptr package System.Tasking.Queuing is procedure Enqueue (E : in out Entry_Queue; Call : Entry_Call_Link); -- Enqueue Call at the end of entry_queue E procedure Dequeue (E : in out Entry_Queue; Call : Entry_Call_Link); -- Dequeue Call from entry_queue E function Head (E : in Entry_Queue) return Entry_Call_Link; -- Return the head of entry_queue E procedure Dequeue_Head (E : in out Entry_Queue; Call : out Entry_Call_Link); -- Remove and return the head of entry_queue E function Onqueue (Call : Entry_Call_Link) return Boolean; -- Return True if Call is on any entry_queue at all function Count_Waiting (E : in Entry_Queue) return Natural; -- Return number of calls on the waiting queue of E procedure Select_Task_Entry_Call (Acceptor : System.Tasking.Utilities.ATCB_Ptr; Open_Accepts : Accept_List_Access; Call : out Entry_Call_Link; Selection : out Select_Index); -- Select an entry for rendezvous procedure Select_Protected_Entry_Call (Object : Protection_Access; Barriers : Barrier_Vector; Call : out Entry_Call_Link); -- Select an entry of a protected object end System.Tasking.Queuing;
with Ada.Integer_Text_IO; with Ada.Text_IO; with Tree_Fast; use Tree_Fast; procedure Main_Fast is t: Tree_Fast.Tree; cur: Integer := 5; res: Integer := 0; mode: Integer; procedure PutI(item: Integer; width: Natural := 0; base: Natural := 10) renames Ada.Integer_Text_IO.Put; procedure New_Line(spacing: Ada.Text_IO.Positive_Count := 1) renames Ada.Text_IO.New_Line; begin initialize; for i in 1..999999 loop mode := i mod 3; cur := (cur * 57 + 43) mod 10007; if mode = 0 then insert(t, cur); elsif mode = 1 then erase(t, cur); else res := res + (if hasValue(t, cur) then 1 else 0); end if; end loop; PutI(res); New_Line(1); end Main_Fast;
----------------------------------------------------------------------- -- keystore-passwords-files -- File based password provider -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C.Strings; with Ada.Directories; with Ada.Streams.Stream_IO; with Util.Systems.Types; with Util.Systems.Os; with Util.Log.Loggers; with Keystore.Random; package body Keystore.Passwords.Files is subtype Key_Length is Util.Encoders.Key_Length; use type Ada.Streams.Stream_Element_Offset; -- GNAT 2019 complains about unused use type but gcc 7.4 fails if it not defined (st_mode). pragma Warnings (Off); use type Interfaces.C.int; use type Interfaces.C.unsigned; use type Interfaces.C.unsigned_short; pragma Warnings (On); function Verify_And_Get_Size (Path : in String) return Ada.Streams.Stream_Element_Count; type Provider (Len : Key_Length) is limited new Keystore.Passwords.Provider with record Password : Ada.Streams.Stream_Element_Array (1 .. Len); end record; type File_Provider_Access is access all Provider; -- Get the password through the Getter operation. overriding procedure Get_Password (From : in Provider; Getter : not null access procedure (Password : in Secret_Key)); type Key_Provider (Len : Key_Length) is new Provider (Len) and Keys.Key_Provider and Internal_Key_Provider with null record; type Key_Provider_Access is access all Key_Provider'Class; -- Get the Key, IV and signature. overriding procedure Get_Keys (From : in Key_Provider; Key : out Secret_Key; IV : out Secret_Key; Sign : out Secret_Key); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Keystore.Passwords.Files"); overriding procedure Save_Key (Provider : in Key_Provider; Data : out Ada.Streams.Stream_Element_Array); function Verify_And_Get_Size (Path : in String) return Ada.Streams.Stream_Element_Count is P : Interfaces.C.Strings.chars_ptr; Stat : aliased Util.Systems.Types.Stat_Type; Res : Integer; Result : Ada.Streams.Stream_Element_Count; Dir : constant String := Ada.Directories.Containing_Directory (Path); begin -- Verify that the file is readable only by the current user. P := Interfaces.C.Strings.New_String (Path); Res := Util.Systems.Os.Sys_Stat (Path => P, Stat => Stat'Access); Interfaces.C.Strings.Free (P); if Res /= 0 then Log.Info ("Password file {0} does not exist", Path); raise Keystore.Bad_Password with "Password file does not exist"; end if; if (Stat.st_mode and 8#0077#) /= 0 and Util.Systems.Os.Directory_Separator = '/' then Log.Info ("Password file {0} is not safe", Path); raise Keystore.Bad_Password with "Password file is not safe"; end if; if Stat.st_size = 0 then Log.Info ("Password file {0} is empty", Path); raise Keystore.Bad_Password with "Password file is empty"; end if; if Stat.st_size > MAX_FILE_SIZE then Log.Info ("Password file {0} is too big", Path); raise Keystore.Bad_Password with "Password file is too big"; end if; Result := Ada.Streams.Stream_Element_Offset (Stat.st_size); -- Verify that the parent directory is readable only by the current user. P := Interfaces.C.Strings.New_String (Dir); Res := Util.Systems.Os.Sys_Stat (Path => P, Stat => Stat'Access); Interfaces.C.Strings.Free (P); if Res /= 0 then Log.Info ("Directory {0} is not safe for password file", Dir); raise Keystore.Bad_Password with "Directory that contains password file cannot be checked"; end if; if (Stat.st_mode and 8#0077#) /= 0 and Util.Systems.Os.Directory_Separator = '/' then Log.Info ("Directory {0} is not safe for password file", Dir); raise Keystore.Bad_Password with "Directory that contains password file is not safe"; end if; Log.Info ("Password file {0} passes the security checks", Path); return Result; end Verify_And_Get_Size; -- ------------------------------ -- Create a password provider that reads the file to build the password. -- The file must have the mode rw------- (600) and its owning directory -- the mode rwx------ (700). The Bad_Password exception is raised if -- these rules are not verified. -- ------------------------------ function Create (Path : in String) return Provider_Access is Size : Ada.Streams.Stream_Element_Offset; File : Ada.Streams.Stream_IO.File_Type; Result : File_Provider_Access; Last : Ada.Streams.Stream_Element_Offset; begin Size := Verify_And_Get_Size (Path); Ada.Streams.Stream_IO.Open (File => File, Mode => Ada.Streams.Stream_IO.In_File, Name => Path); Result := new Provider '(Len => Size, others => <>); Ada.Streams.Stream_IO.Read (File, Result.Password, Last); Ada.Streams.Stream_IO.Close (File); return Result.all'Access; end Create; -- ------------------------------ -- Get the password through the Getter operation. -- ------------------------------ overriding procedure Get_Password (From : in Provider; Getter : not null access procedure (Password : in Secret_Key)) is Password : Keystore.Secret_Key (Length => From.Len); begin Util.Encoders.Create (From.Password, Password); Getter (Password); end Get_Password; -- ------------------------------ -- Create a key provider that reads the file. The file is split in three parts -- the key, the IV, the signature which are extracted by using `Get_Keys`. -- ------------------------------ function Create (Path : in String) return Keys.Key_Provider_Access is Size : Ada.Streams.Stream_Element_Offset; File : Ada.Streams.Stream_IO.File_Type; Result : Key_Provider_Access; Last : Ada.Streams.Stream_Element_Offset; begin Size := Verify_And_Get_Size (Path); Ada.Streams.Stream_IO.Open (File => File, Mode => Ada.Streams.Stream_IO.In_File, Name => Path); Result := new Key_Provider '(Len => Size, others => <>); Ada.Streams.Stream_IO.Read (File, Result.Password, Last); Ada.Streams.Stream_IO.Close (File); return Result.all'Access; end Create; -- ------------------------------ -- Get the Key, IV and signature. -- ------------------------------ overriding procedure Get_Keys (From : in Key_Provider; Key : out Secret_Key; IV : out Secret_Key; Sign : out Secret_Key) is First : Ada.Streams.Stream_Element_Offset := 1; Last : Ada.Streams.Stream_Element_Offset := First + Key.Length - 1; begin if From.Len /= Key.Length + IV.Length + Sign.Length then raise Keystore.Bad_Password with "Invalid length for the key file"; end if; Util.Encoders.Create (From.Password (First .. Last), Key); First := Last + 1; Last := First + IV.Length - 1; Util.Encoders.Create (From.Password (First .. Last), IV); First := Last + 1; Last := First + Sign.Length - 1; Util.Encoders.Create (From.Password (First .. Last), Sign); end Get_Keys; overriding procedure Save_Key (Provider : in Key_Provider; Data : out Ada.Streams.Stream_Element_Array) is begin Data := Provider.Password; end Save_Key; -- ------------------------------ -- Generate a file that contains the keys. Keys are generated using a random generator. -- The file is created with the mode rw------- (600) and the owning directory is forced -- to the mode rwx------ (700). -- ------------------------------ function Generate (Path : in String; Length : in Key_Length := DEFAULT_KEY_FILE_LENGTH) return Keys.Key_Provider_Access is Result : Key_Provider_Access; Random : Keystore.Random.Generator; Dir : constant String := Ada.Directories.Containing_Directory (Path); File : Ada.Streams.Stream_IO.File_Type; P : Interfaces.C.Strings.chars_ptr; Res : Integer with Unreferenced; begin if not Ada.Directories.Exists (Dir) then Log.Info ("Creating directory {0}", Dir); Ada.Directories.Create_Path (Dir); end if; Log.Info ("Creating password file {0}", Path); Ada.Streams.Stream_IO.Create (File => File, Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Result := new Key_Provider '(Len => Length, others => <>); Random.Generate (Result.Password); Ada.Streams.Stream_IO.Write (File, Result.Password); Ada.Streams.Stream_IO.Close (File); P := Interfaces.C.Strings.New_String (Path); Res := Util.Systems.Os.Sys_Chmod (Path => P, Mode => 8#0600#); Interfaces.C.Strings.Free (P); P := Interfaces.C.Strings.New_String (Dir); Res := Util.Systems.Os.Sys_Chmod (Path => P, Mode => 8#0700#); Interfaces.C.Strings.Free (P); return Result.all'Access; end Generate; end Keystore.Passwords.Files;
-- -- Copyright 2021 (C) Jeremy Grosser <jeremy@synack.me> -- -- SPDX-License-Identifier: Apache-2.0 -- with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings; with System; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Notcurses.Context; package body Notcurses.Plane is function Standard_Plane return Notcurses_Plane is begin if Default_Context = null then Notcurses.Context.Initialize; end if; return Thin.notcurses_stdplane (Default_Context); end Standard_Plane; function Context (Plane : Notcurses_Plane) return Notcurses_Context is (Thin.ncplane_notcurses (Plane)); function Dimensions (Plane : Notcurses_Plane) return Coordinate is Y, X : aliased int; begin Thin.ncplane_dim_yx (Plane, Y'Access, X'Access); return (Y => Integer (Y), X => Integer (X)); end Dimensions; function Create_Sub_Plane (Plane : Notcurses_Plane; Position : Coordinate; Size : Coordinate) return Notcurses_Plane is Options : aliased constant Thin.ncplane_options := (y => int (Position.Y), x => int (Position.X), rows => int (Size.Y), cols => int (Size.X), userptr => System.Null_Address, name => Null_Ptr, resizecb => null, flags => 0, margin_b => 0, margin_r => 0); New_Plane : Notcurses_Plane; begin New_Plane := Thin.ncplane_create (Plane, Options'Access); if New_Plane = null then raise Notcurses_Error with "Failed to create subplane"; end if; return New_Plane; end Create_Sub_Plane; procedure Destroy (Plane : in out Notcurses_Plane) is begin if Thin.ncplane_destroy (Plane) /= 0 then raise Notcurses_Error with "Failed to destroy plane"; end if; Plane := null; end Destroy; procedure Erase (Plane : Notcurses_Plane) is begin Thin.ncplane_erase (Plane); end Erase; procedure Erase_Region (Plane : Notcurses_Plane; Start : Coordinate; Size : Coordinate) is Result : int; begin Result := Thin.ncplane_erase_region (Plane, int (Start.Y), int (Start.X), int (Size.Y), int (Size.X)); if Result /= 0 then raise Notcurses_Error with "Failed to erase plane region"; end if; end Erase_Region; procedure Put (Plane : Notcurses_Plane; Str : Wide_Wide_String; Y, X : Integer := -1) is use Ada.Strings.UTF_Encoding.Wide_Wide_Strings; Chars : aliased chars_ptr := New_String (Encode (Str)); Result : int; begin Result := Thin.ncplane_putstr_yx (Plane, int (Y), int (X), Chars); Free (Chars); if Result < 0 then raise Notcurses_Error with "Failed to put Wide_Wide_String on plane"; end if; end Put; procedure Put_Aligned (Plane : Notcurses_Plane; Str : Wide_Wide_String; Y : Integer := -1; Align : Alignment := Unaligned) is use Ada.Strings.UTF_Encoding.Wide_Wide_Strings; Chars : aliased chars_ptr := New_String (Encode (Str)); NCA : Thin.ncalign_e; Result : int; begin case Align is when Unaligned => NCA := Thin.NCALIGN_UNALIGNED; when Left => NCA := Thin.NCALIGN_LEFT; when Right => NCA := Thin.NCALIGN_RIGHT; when Center => NCA := Thin.NCALIGN_CENTER; end case; Result := Thin.ncplane_putstr_aligned (Plane, int (Y), NCA, Chars); Free (Chars); if Result < 0 then raise Notcurses_Error with "Failed to put Wide_Wide_String on plane"; end if; end Put_Aligned; procedure Fill (Plane : Notcurses_Plane; C : Wide_Wide_Character) is Size : constant Coordinate := Dimensions (Plane); S : constant Wide_Wide_String (1 .. Size.X) := (others => C); begin for Y in 0 .. Size.Y - 1 loop Put (Plane, S, Y => Y, X => 0); end loop; end Fill; procedure Set_Background (Plane : Notcurses_Plane; Channel : Notcurses_Channel) is Result : Unsigned_64 with Unreferenced; begin Result := Thin.ncplane_set_bchannel (Plane, To_C (Channel)); end Set_Background; procedure Set_Foreground (Plane : Notcurses_Plane; Channel : Notcurses_Channel) is Result : Unsigned_64 with Unreferenced; begin Result := Thin.ncplane_set_fchannel (Plane, To_C (Channel)); end Set_Foreground; procedure Set_Background_RGB (Plane : Notcurses_Plane; R, G, B : Color_Type) is Channel : constant Notcurses_Channel := (R => R, G => G, B => B, Not_Default => True, Use_Palette => False, Alpha => Opaque); begin Set_Background (Plane, Channel); end Set_Background_RGB; procedure Set_Foreground_RGB (Plane : Notcurses_Plane; R, G, B : Color_Type) is Channel : constant Notcurses_Channel := (R => R, G => G, B => B, Not_Default => True, Use_Palette => False, Alpha => Opaque); begin Set_Foreground (Plane, Channel); end Set_Foreground_RGB; package body Cursor is function Position (Plane : Notcurses_Plane) return Coordinate is Y, X : aliased int; begin Thin.ncplane_cursor_yx (Plane, Y'Access, X'Access); return (Y => Integer (Y), X => Integer (X)); end Position; procedure Move (Plane : Notcurses_Plane; Position : Coordinate) is begin if Thin.ncplane_cursor_move_yx (Plane, int (Position.Y), int (Position.X)) = -1 then raise Notcurses_Error with "Failed to move the cursor"; end if; end Move; procedure Move_Relative (Plane : Notcurses_Plane; Offset : Coordinate) is begin Move (Plane, Cursor.Position (Plane) + Offset); end Move_Relative; procedure Home (Plane : Notcurses_Plane) is begin Thin.ncplane_home (Plane); end Home; end Cursor; end Notcurses.Plane;
-- C48008C.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. --* -- FOR ALLOCATORS OF THE FORM "NEW T X", CHECK THAT CONSTRAINT_ERROR IS -- RAISED IF T IS AN UNCONSTRAINED ARRAY TYPE WITH INDEX SUBTYPE(S) S, X -- IS AN INDEX CONSTRAINT, AND THE BOUNDS OF X ARE NOT COMPATIBLE WITH -- AN INDEX SUBTYPE OF T. -- RM 01/08/80 -- NL 10/13/81 -- EG 07/05/84 WITH REPORT; PROCEDURE C48008C IS USE REPORT; BEGIN TEST("C48008C","FOR ALLOCATORS OF THE FORM 'NEW T X', CHECK " & "THAT CONSTRAINT_ERROR IS RAISED WHEN " & "APPROPRIATE - UNCONSTRAINED ARRAY TYPE"); DECLARE SUBTYPE TWO IS INTEGER RANGE 1..2; TYPE TF IS ARRAY( TWO RANGE <> , TWO RANGE <> ) OF INTEGER; TYPE ATF IS ACCESS TF; VF : ATF; BEGIN BEGIN VF := NEW TF ( 0..1 , 1..2 ); FAILED ("NO EXCEPTION RAISED - CASE 1"); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED - CASE 1"); END; BEGIN VF := NEW TF(1 .. 2, 2 .. IDENT_INT(3)); FAILED ("NO EXCEPTION RAISED - CASE 2"); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED - CASE 2"); END; END; RESULT; END C48008C;
with C_String; with Interfaces.C; package body Agar.Core.Event is package C renames Interfaces.C; procedure Push_Pointer (Event : in Event_Not_Null_Access_t; Key : in String; Value : in System.Address) is Ch_Key : aliased C.char_array := C.To_C (Key); begin Thin.Event.Push_Pointer (Event => Event, Key => C_String.To_C_String (Ch_Key'Unchecked_Access), Value => Value); end Push_Pointer; procedure Push_String (Event : in Event_Not_Null_Access_t; Key : in String; Value : in String) is Ch_Key : aliased C.char_array := C.To_C (Key); Ch_Value : aliased C.char_array := C.To_C (Value); begin Thin.Event.Push_String (Event => Event, Key => C_String.To_C_String (Ch_Key'Unchecked_Access), Value => C_String.To_C_String (Ch_Value'Unchecked_Access)); end Push_String; procedure Push_Integer (Event : in Event_Not_Null_Access_t; Key : in String; Value : in Integer) is Ch_Key : aliased C.char_array := C.To_C (Key); begin Thin.Event.Push_Integer (Event => Event, Key => C_String.To_C_String (Ch_Key'Unchecked_Access), Value => C.int (Value)); end Push_Integer; procedure Push_Natural (Event : in Event_Not_Null_Access_t; Key : in String; Value : in Natural) is Ch_Key : aliased C.char_array := C.To_C (Key); begin Thin.Event.Push_Unsigned_Integer (Event => Event, Key => C_String.To_C_String (Ch_Key'Unchecked_Access), Value => C.unsigned (Value)); end Push_Natural; procedure Push_Long (Event : in Event_Not_Null_Access_t; Key : in String; Value : in Long_Integer) is Ch_Key : aliased C.char_array := C.To_C (Key); begin Thin.Event.Push_Long (Event => Event, Key => C_String.To_C_String (Ch_Key'Unchecked_Access), Value => C.long (Value)); end Push_Long; procedure Push_Long_Natural (Event : in Event_Not_Null_Access_t; Key : in String; Value : in Long_Natural) is Ch_Key : aliased C.char_array := C.To_C (Key); begin Thin.Event.Push_Unsigned_Long (Event => Event, Key => C_String.To_C_String (Ch_Key'Unchecked_Access), Value => C.unsigned_long (Value)); end Push_Long_Natural; procedure Push_Float (Event : in Event_Not_Null_Access_t; Key : in String; Value : in Float) is Ch_Key : aliased C.char_array := C.To_C (Key); begin Thin.Event.Push_Float (Event => Event, Key => C_String.To_C_String (Ch_Key'Unchecked_Access), Value => C.C_float (Value)); end Push_Float; procedure Push_Long_Float (Event : in Event_Not_Null_Access_t; Key : in String; Value : in Long_Float) is Ch_Key : aliased C.char_array := C.To_C (Key); begin Thin.Event.Push_Double (Event => Event, Key => C_String.To_C_String (Ch_Key'Unchecked_Access), Value => C.double (Value)); end Push_Long_Float; procedure Push_Generic_Access (Event : in Event_Not_Null_Access_t; Key : in String; Value : in Element_Access_Type) is begin Push_Pointer (Event => Event, Key => Key, Value => Value.all'Address); end Push_Generic_Access; end Agar.Core.Event;
----------------------------------------------------------------------- -- helios-monitor -- Helios monitor -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Basic; with Util.Log.Loggers; package body Helios.Monitor is use type Helios.Schemas.Value_Index; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Helios.Monitor"); List : Agent_Type_Access; -- ------------------------------ -- The timer handler executed when the timer deadline has passed. -- ------------------------------ overriding procedure Time_Handler (Agent : in out Agent_Type; Event : in out Util.Events.Timers.Timer_Ref'Class) is Data : Helios.Datas.Snapshot_Type_Access; begin Log.Debug ("Running agent {0}", Agent.Node.Name); Helios.Datas.Prepare (Agent.Data, Data); Agent_Type'Class (Agent).Collect (Data.all); Event.Repeat (Agent.Period); Helios.Datas.Finish (Data.all); end Time_Handler; -- ------------------------------ -- Create a new definition with the given name. The filter parameter allows to control -- which definition values are really needed. The "*" indicates that all values are required. -- Otherwise, it is a comma separated list of strings. A null definition is returned if -- the filter does not contain the definition name. -- ------------------------------ function Create_Definition (Agent : in Agent_Type; Name : in String; Filter : in String := "*") return Schemas.Definition_Type_Access is begin return Schemas.Create_Definition (Agent.Node, Name, Filter); end Create_Definition; -- ------------------------------ -- Add a definition to the agent. -- ------------------------------ procedure Add_Definition (Agent : in out Agent_Type; Def : in Schemas.Definition_Type_Access) is begin Schemas.Add_Definition (Agent.Node, Def); end Add_Definition; -- ------------------------------ -- Find a child definition with the given name. -- Returns null if there is no such definition. -- ------------------------------ function Find_Definition (Agent : in Agent_Type; Name : in String) return Schemas.Definition_Type_Access is use type Schemas.Definition_Type_Access; begin if Agent.Node = null or else Agent.Node.Child = null then return null; else return Schemas.Find_Definition (Agent.Node.Child, Name); end if; end Find_Definition; -- ------------------------------ -- Register the agent. -- ------------------------------ procedure Register (Agent : in Agent_Type_Access; Name : in String; Config : in Util.Properties.Manager) is begin Log.Info ("Register agent {0}", Name); Agent.Period := Get_Period (Config, "period", 1); Agent.Node := Schemas.Create_Definition (null, Name, "*", Schemas.V_NONE); Agent.Start (Config); if Agent.Node.Index > 0 then Agent.Next := List; List := Agent; end if; end Register; -- ------------------------------ -- Get the current report and prepare the plugin agents for a new snapshot. -- ------------------------------ function Get_Report return Helios.Datas.Report_Queue_Type is procedure Flush (Agent : in out Agent_Type'Class); procedure Flush (Agent : in out Agent_Type'Class) is begin Helios.Datas.Flush (Agent.Data); end Flush; begin Iterate (Flush'Access); return Helios.Datas.Get_Report; end Get_Report; -- ------------------------------ -- Iterate over the plugin agents that are registered and execute -- the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (Process : not null access procedure (Agent : in out Agent_Type'Class)) is Agent : Agent_Type_Access := List; begin while Agent /= null loop Process (Agent.all); Agent := Agent.Next; end loop; end Iterate; -- ------------------------------ -- Get a period configuration parameter. -- ------------------------------ function Get_Period (Config : in Util.Properties.Manager; Name : in String; Default : in Natural) return Ada.Real_Time.Time_Span is Period : Integer := Util.Properties.Basic.Integer_Property.Get (Config, Name, Default); begin if Period <= 0 then Period := Default; end if; return Ada.Real_Time.Seconds (Period); end Get_Period; end Helios.Monitor;
-- WORDS, a Latin dictionary, by Colonel William Whitaker (USAF, Retired) -- -- Copyright William A. Whitaker (1936–2010) -- -- This is a free program, which means it is proper to copy it and pass -- it on to your friends. Consider it a developmental item for which -- there is no charge. However, just for form, it is Copyrighted -- (c). Permission is hereby freely given for any and all use of program -- and data. You can sell it as your own, but at least tell me. -- -- This version is distributed without obligation, but the developer -- would appreciate comments and suggestions. -- -- All parts of the WORDS system, source code and data files, are made freely -- available to anyone who wishes to use them, for whatever purpose. with Ada.Text_IO; use Ada.Text_IO; with Latin_Utils.Strings_Package; use Latin_Utils.Strings_Package; with Latin_Utils.Config; with Support_Utils.Word_Parameters; use Support_Utils.Word_Parameters; with Latin_Utils.Inflections_Package; use Latin_Utils.Inflections_Package; with Latin_Utils.Dictionary_Package; use Latin_Utils.Dictionary_Package; with Support_Utils.Developer_Parameters; use Support_Utils.Developer_Parameters; with Words_Engine.Word_Package; use Words_Engine.Word_Package; with Words_Engine.English_Support_Package; use Words_Engine.English_Support_Package; with Support_Utils.Dictionary_Form; use Latin_Utils; procedure Words_Engine.Search_English (Input_English_Word : String; Pofs : Part_Of_Speech_Type := X) is use Ewds_Direct_Io; Input_Word : Eword := Lower_Case (Head (Input_English_Word, Eword_Size)); Input_Pofs : constant Part_Of_Speech_Type := Pofs; Output_Array : Ewds_Array (1 .. 500) := (others => Null_Ewds_Record); Number_Of_Hits : Integer := 0; J1, J2, J : Ewds_Direct_Io.Count := 0; D_K : constant Dictionary_Kind := General; -- For the moment Ewds : Ewds_Record := Null_Ewds_Record; First_Try, Second_Try : Boolean := True; procedure Load_Output_Array (Ewds : in Ewds_Record) is begin if Ewds.Pofs <= Input_Pofs then Number_Of_Hits := Number_Of_Hits + 1; Output_Array (Number_Of_Hits) := Ewds; end if; end Load_Output_Array; --procedure TRIM_OUTPUT_ARRAY is procedure Sort_Output_Array is Hits : Integer := 0; begin -- Bubble sort Hit_Loop : loop Hits := 0; Switch : declare Dw : Ewds_Record := Null_Ewds_Record; begin Inner_Loop : -- Order by RANK, FREQ, SEMI for I in 1 .. Number_Of_Hits - 1 loop if Output_Array (I + 1).Rank > Output_Array (I).Rank or else (Output_Array (I + 1).Rank = Output_Array (I).Rank and then Output_Array (I + 1).Freq < Output_Array (I).Freq) or else (Output_Array (I + 1).Rank = Output_Array (I).Rank and then Output_Array (I + 1).Freq = Output_Array (I).Freq and then Output_Array (I + 1).Semi < Output_Array (I).Semi) then Dw := Output_Array (I); Output_Array (I) := Output_Array (I + 1); Output_Array (I + 1) := Dw; Hits := Hits + 1; --PUT_LINE ("HITS " & INTEGER'IMAGE (HITS)); end if; end loop Inner_Loop; end Switch; exit Hit_Loop when Hits = 0; end loop Hit_Loop; end Sort_Output_Array; procedure Dump_Output_Array (Output : in Ada.Text_IO.File_Type) is De : Dictionary_Entry := Null_Dictionary_Entry; Number_To_Show : Integer := Number_Of_Hits; One_Screen : constant Integer := 6; begin --TEXT_IO.PUT_LINE ("DUMP_OUTPUT"); if Number_Of_Hits = 0 then Ada.Text_IO.Put_Line (Output, "No Match"); else Sort_Output_Array; --TEXT_IO.PUT_LINE ("DUMP_OUTPUT SORTED"); Trimmed := False; if Words_Mode (Trim_Output) then if Number_Of_Hits > One_Screen then Number_To_Show := One_Screen; Trimmed := True; else Number_To_Show := Number_Of_Hits; end if; end if; for I in 1 .. Number_To_Show loop Ada.Text_IO.New_Line (Output); Do_Pause : begin if Integer (Ada.Text_IO.Line (Output)) > Scroll_Line_Number + Config.Output_Screen_Size then Pause (Output); Scroll_Line_Number := Integer (Ada.Text_IO.Line (Output)); end if; end Do_Pause; Dict_IO.Read (Dict_File (General), De, Dict_IO.Count (Output_Array (I).N)); Put (Output, Support_Utils.Dictionary_Form (De)); Ada.Text_IO.Put (Output, " "); if De.Part.Pofs = N then Ada.Text_IO.Put (Output, " "); Decn_Record_IO.Put (Output, De.Part.N.Decl); Ada.Text_IO.Put (Output, " " & Gender_Type'Image (De.Part.N.Gender) & " "); end if; if De.Part.Pofs = V then Ada.Text_IO.Put (Output, " "); Decn_Record_IO.Put (Output, De.Part.V.Con); end if; if (De.Part.Pofs = V) and then (De.Part.V.Kind in Gen .. Perfdef) then Ada.Text_IO.Put (Output, " " & Verb_Kind_Type'Image (De.Part.V.Kind) & " "); end if; if Words_Mdev (Show_Dictionary_Codes) then Ada.Text_IO.Put (Output, " ["); -- FIXME: Why noy Translation_Record_IO.Put ? Age_Type_IO.Put (Output, De.Tran.Age); Area_Type_IO.Put (Output, De.Tran.Area); Geo_Type_IO.Put (Output, De.Tran.Geo); Frequency_Type_IO.Put (Output, De.Tran.Freq); Source_Type_IO.Put (Output, De.Tran.Source); Ada.Text_IO.Put (Output, "] "); end if; if Words_Mdev (Show_Dictionary) then Ada.Text_IO.Put (Output, Ext (D_K) & ">"); end if; --TEXT_IO.PUT_LINE ("DUMP_OUTPUT SHOW"); if Words_Mdev (Show_Dictionary_Line) then Ada.Text_IO.Put (Output, "(" & Trim (Integer'Image (Output_Array (I).N)) & ")"); end if; Ada.Text_IO.New_Line (Output); --TEXT_IO.PUT_LINE ("DUMP_OUTPUT MEAN"); Ada.Text_IO.Put (Output, Trim (De.Mean)); Ada.Text_IO.New_Line (Output); end loop; --TEXT_IO.PUT_LINE ("DUMP_OUTPUT TRIMMED"); if Trimmed then Put_Line (Output, "*"); end if; end if; -- On HITS = 0 exception when others => null; -- If N not in DICT_FILE end Dump_Output_Array; begin J1 := 1; J2 := Size (Ewds_File); First_Try := True; Second_Try := True; J := (J1 + J2) / 2; Binary_Search : loop -- TEXT_IO.PUT_LINE ("J = " & INTEGER'IMAGE (INTEGER (J))); if (J1 = J2 - 1) or (J1 = J2) then if First_Try then J := J1; First_Try := False; elsif Second_Try then J := J2; Second_Try := False; else exit Binary_Search; end if; end if; -- Should D_K Set_Index (Ewds_File, J); Read (Ewds_File, Ewds); if "<"(Lower_Case (Ewds.W), Input_Word) then -- Not LTU, not u=v J1 := J; J := (J1 + J2) / 2; elsif ">"(Lower_Case (Ewds.W), Input_Word) then J2 := J; J := (J1 + J2) / 2; else for I in reverse J1 .. J loop Set_Index (Ewds_File, Ewds_Direct_Io.Count (I)); Read (Ewds_File, Ewds); -- Reads and advances index!! if "="(Lower_Case (Ewds.W), Input_Word) then Load_Output_Array (Ewds); else exit; end if; end loop; for I in J + 1 .. J2 loop Set_Index (Ewds_File, Ewds_Direct_Io.Count (I)); Read (Ewds_File, Ewds); if "="(Lower_Case (Ewds.W), Input_Word) then Load_Output_Array (Ewds); else exit Binary_Search; end if; end loop; exit Binary_Search; end if; end loop Binary_Search; if Words_Mode (Write_Output_To_File) then Dump_Output_Array (Output); else Dump_Output_Array (Current_Output); end if; exception when others => Ada.Text_IO.Put_Line ("exception SEARCH NUMBER_OF_HITS = " & Integer'Image (Number_Of_Hits)); raise; end Words_Engine.Search_English;
----------------------------------------------------------------------- -- package body Spline, cubic splines -- Copyright (C) 2018 Jonathan S. Parker -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --------------------------------------------------------------------------- package body Spline is Zero : constant Real := +0.0; One : constant Real := +1.0; Two : constant Real := +2.0; Three : constant Real := +3.0; Six : constant Real := +6.0; One_Third : constant Real := One / Three; -------------------- -- Prepare_X_Data -- -------------------- procedure Prepare_X_Data (X_Stuff : out X_Structure; X_Data : in Data_Vector; I_Start : in Index := Index'first; I_Finish : in Index := Index'Last; Bound_First : in Boundary := Natural_BC; Bound_Last : in Boundary := Natural_BC) is D_1st : constant Tri.DiagonalID := Tri.DiagonalID'First; D_0 : constant Tri.DiagonalID := Tri.DiagonalID'Succ(Tri.DiagonalID'First); D_Last : constant Tri.DiagonalID := Tri.DiagonalID'Last; No_Of_Points_Minus_1 : constant Index'Base := I_Finish - I_Start; S : X_Structure renames X_Stuff; begin if No_Of_Points_Minus_1 < 3 then raise Constraint_Error with "Too few points for spline calculation"; end if; for i in I_Start .. I_Finish-1 loop S.dX(i) := X_Data(i+1) - X_Data(i); if S.dX(i) < Zero then raise Constraint_Error with "X axis points are out of order."; end if; if Abs (S.dX(i)) < Two ** (Real'Machine_Emin / 2) then raise Constraint_Error with "Points too close together on X axis."; end if; end loop; for i in I_Start .. I_Finish-1 loop S.dX_Inverse(i) := One / S.dX(i); end loop; -- We need to solve the matrix equation M*Z = V, for the vector Z. -- First initialize M and V. M is Tridiagonal. The lower diagonal -- is M(-1, .. ). The elements of the diagonal "vectors" are -- indexed by the row index the element would have in -- matrix form, so M(-1,*) starts at I_Start+1, etc. -- -- Impose a value Boundary_Value_First = Alpha*Y_dot_dot + Beta*Y_dot: -- -- (2*h_0*Beta - 6*Alpha)*C_0 + Beta*h_0*C_1 -- = -3*Boundary_Value_First + 3*Beta*(Y_1 - Y_0)/h_0. -- -- At the other end set Boundary_Value_Last = Alpha2*Y_dot_dot + Beta2*Y_dot, -- to get: -- -- (2*h_n-1*Beta2 + 6*Alpha2)*C_n + Beta2*h_n-1*C_n-1 -- = 3*Boundary_Value_Last - 3*Beta2*(Y_n - Y_n-1)/h_n-1. S.M(D_Last)(I_Start) := S.dX(I_Start) * Bound_First.Beta; S.M(D_0)(I_Start) := S.dX(I_Start) * Bound_First.Beta * Two - Six * Bound_First.Alpha; S.M(D_1st)(I_Finish) := S.dX(I_Finish-1) * Bound_Last.Beta; S.M(D_0)(I_Finish) := S.dX(I_Finish-1) * Bound_Last.Beta * Two + Six * Bound_Last.Alpha; -- Get rest of matrix M and vector V. -- Clamped and Natural_BC Spline types have the following in common. for i in I_Start+1 .. I_Finish-1 loop S.M(D_Last)(i) := S.dX(i); end loop; for i in I_Start+1 .. I_Finish-1 loop S.M(D_1st)(i) := S.dX(i-1); end loop; for i in I_Start+1 .. I_Finish-1 loop S.M(D_0)(i) := Two * (S.dX(i) + S.dX(i-1)); end loop; Tri.LU_Decompose (S.M, I_Start, I_Finish); S.I_Start := I_Start; S.I_Finish := I_Finish; S.Bound_First := Bound_First; S.Bound_Last := Bound_Last; S.Initialized := True; end Prepare_X_Data; ---------------- -- Get_Spline -- ---------------- procedure Get_Spline (Spline : out Spline_Coefficients; X_Stuff : in X_Structure; Y_Data : in Data_Vector) is dY : Data_Vector := (others => Zero); dY_Over_dX : Data_Vector := (others => Zero); I_Start : Index renames X_Stuff.I_Start; I_Finish : Index renames X_Stuff.I_Finish; S : X_Structure renames X_Stuff; F : Coefficients renames Spline.F; V, Z : Tri.Column; begin if not S.Initialized then raise Must_Call_Prepare_X_Data_First; end if; -- The Spline variable must carry info about the start and -- and end of the calculated spline. So this stuff was input -- in the call to Prepare_X_Data, placed into variable -- X_Stuff. Now it's placed in variable Spline, so that it -- it can be passed on to the interpolation procedures. It's -- complicated, but less error prone this way. Spline.I_Start := I_Start; Spline.I_Finish := I_Finish; for i in I_Start .. I_Finish-1 loop dY(i) := Y_Data(i+1) - Y_Data(i); end loop; for i in I_Start .. I_Finish-1 loop dY_Over_dX(i) := dY(i) * S.dX_Inverse(i); end loop; -- Solve the matrix equation M*Z = V for vector Z. First get V: -- -- The following boundary conditions differ in the cases of -- Natural Splines, and Clamped Splines. -- -- set Boundary_Value_First = Alpha*Y_dot_dot + Beta*Y_dot to get: -- -- (2*h_0*Beta - 6*Alpha)*C_0 + Beta*h_0*C_1 -- = -3*Boundary_Value_First + 3*Beta*(Y_1 - Y_0)/h_0. -- -- At the other end set Boundary_Value_Last = Alpha2*Y_dot_dot + Beta2*Y_dot, -- to get: -- -- (2*h_n-1*Beta2 + 6*Alpha2)*C_n + Beta2*h_n-1*C_n-1 -- = 3*Boundary_Value_Last - 3*Beta2*(Y_n - Y_n-1)/h_n-1. V(I_Start) := Three * (S.Bound_First.Beta * dY_Over_dX(I_Start) - S.Bound_First.Boundary_Val); V(I_Finish) := Three * (-S.Bound_Last.Beta * dY_Over_dX(I_Finish-1) + S.Bound_Last.Boundary_Val); -- Get rest of matrix M and vector V. -- Both clamped and Natural_BC Spline types have the following in common. for i in I_Start+1 .. I_Finish-1 loop V(i) := Three * (dY_Over_dX(i) - dY_Over_dX(i-1)); end loop; -- Solve for Z in the equation M*Z = V: -- Matrix M has been overwritten with the LU decomposition of M. Tri.Solve (Z, S.M, V, I_Start, I_Finish); -- coefficients of X**2: for i in I_Start .. I_Finish loop F(2)(i) := Z(i); end loop; -- coefficients of X**3: F(3)(I_Finish) := Zero; for i in I_Start .. I_Finish-1 loop F(3)(i) := (F(2)(i+1) - F(2)(i)) * S.dX_Inverse(i) * One_Third; end loop; -- coefficients of X**1: for i in I_Start .. I_Finish-1 loop F(1)(i) := - S.dX(i) * (F(2)(i+1) + Two * F(2)(i)) * One_Third; end loop; for i in I_Start .. I_Finish-1 loop F(1)(i) := F(1)(i) + dY_Over_dX(i); end loop; -- Following is used only for testing: F(1)(I_Finish) := F(1)(I_Finish-1) + S.dX(I_Finish-1)*(F(2)(I_Finish-1) + F(2)(I_Finish)); -- F : Coefficients renames Spline.F; -- So Spline.F is now initialized end Get_Spline; -------------- -- Value_At -- -------------- function Value_At (X : in Real; X_Data : in Data_Vector; Y_Data : in Data_Vector; Spline : in Spline_Coefficients) return Real is S, Segment : Index; Y, dX1, dX2, dX3 : Real; F : Coefficients renames Spline.F; I_Start : Index renames Spline.I_Start; I_Finish : Index renames Spline.I_Finish; begin if X > X_Data(I_Finish) or X < X_Data(I_Start) then raise Constraint_Error with "Independent variable X out of range"; end if; -- Find the spline segment associated with independent variable X. -- "Segment" is the Index of data array X_Data such that -- X_Data(Segment) <= X < X_Data(Segment+1). for Test_Segment in I_Start+1 .. I_Finish loop if X < X_Data(Test_Segment) then Segment := Test_Segment-1; exit; end if; end loop; if X = X_Data(I_Finish) then Segment := I_Finish-1; end if; -- sum the polynomial, return Y S := Segment; dX1 := X - X_Data(Segment); dX2 := dX1 * dX1; dX3 := dX1 * dX2; Y := Y_Data(S) + F(1)(S)*dX1 + F(2)(S)*dX2 + F(3)(S)*dX3; return Y; end Value_At; ------------------------- -- First_Derivative_At -- ------------------------- function First_Derivative_At (X : in Real; X_Data : in Data_Vector; Spline : in Spline_Coefficients) return Real is S, Segment : Index; dY_over_dX, dX1, dX2 : Real; F : Coefficients renames Spline.F; I_Start : Index renames Spline.I_Start; I_Finish : Index renames Spline.I_Finish; begin if X > X_Data(I_Finish) or X < X_Data(I_Start) then raise Constraint_Error with "Independent variable X out of range"; end if; -- Find the spline segment associated with independent variable X. -- "Segment" is the Index of data array X_Data such that -- X_Data(Segment) <= X < X_Data(Segment+1). for Test_Segment in I_Start+1 .. I_Finish loop if X < X_Data(Test_Segment) then Segment := Test_Segment-1; exit; end if; end loop; if X = X_Data(I_Finish) then Segment := I_Finish-1; end if; -- Integrate each polynomial segment from a1=X_Data(i) to b1=X_Data(I+1). -- y = y_1 + F_1 * (x - a1) + F_2 * (x - a1)**2 + F_3 * (x - a1)**3 -- sum the polynomial, return dY / dX S := Segment; dX1 := X - X_Data(Segment); dX2 := dX1 * dX1; dY_over_dX := F(1)(S) + Two * F(2)(S)*dX1 + Three * F(3)(S)*dX2; return dY_over_dX; end First_Derivative_At; -------------------------- -- Second_Derivative_At -- -------------------------- function Second_Derivative_At (X : in Real; X_Data : in Data_Vector; Spline : in Spline_Coefficients) return Real is S, Segment : Index; ddY, dX1 : Real; F : Coefficients renames Spline.F; I_Start : Index renames Spline.I_Start; I_Finish : Index renames Spline.I_Finish; begin -- Independent_Variable_X_Out_Of_Range: if X > X_Data(I_Finish) or X < X_Data(I_Start) then raise Constraint_Error; end if; -- Find the spline segment associated with independent variable X. -- "Segment" is the Index of data array X_Data such that -- X_Data(Segment) <= X < X_Data(Segment+1). for Test_Segment in I_Start+1 .. I_Finish loop if X < X_Data(Test_Segment) then Segment := Test_Segment-1; exit; end if; end loop; if X = X_Data(I_Finish) then Segment := I_Finish-1; end if; -- Integrate each polynomial segment from a1=X_Data(i) to b1=X_Data(I+1). -- y = y_1 + F_1 * (x - a1) + F_2 * (x - a1)**2 + F_3 * (x - a1)**3 -- sum the polynomial, return dY / dX S := Segment; dX1 := X - X_Data(Segment); ddY := Two * F(2)(S) + Six * F(3)(S)*dX1; return ddY; end Second_Derivative_At; -------------- -- Integral -- -------------- function Integral (X_Data : in Data_Vector; Y_Data : in Data_Vector; Spline : in Spline_Coefficients) return Real is Area, Segment_Area : Real; a1, b1 : Real; d1, d2, d3, d4 : Real; F : Coefficients renames Spline.F; I_Start : Index renames Spline.I_Start; I_Finish : Index renames Spline.I_Finish; Half : constant Real := +0.5; Quarter : constant Real := +0.25; begin -- Integrate each polynomial segment from a1=X_Data(i) to b1=X_Data(I+1). -- y = y_1 + F_1 * (x - a1) + F_2 * (x - a1)**2 + F_3 * (x - a1)**3 Area := Zero; for i in I_Start .. I_Finish-1 loop a1 := X_Data(i); b1 := X_Data(i+1); d1 := b1 - a1; d2 := d1 * d1; d3 := d1 * d2; d4 := d2 * d2; Segment_Area := Y_data(i) * d1 + F(1)(i) * d2 * Half + F(2)(i) * d3 * One_Third + F(3)(i) * d4 * Quarter; Area := Area + Segment_Area; end loop; return Area; end Integral; end Spline;
------------------------------------------------------------------------------ -- -- -- Common UUID Handling Package -- -- - RFC 4122 Implementation - -- -- -- -- Version 1.0 -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Version 1 (Time-based) UUID Generation Package -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2018, 2020-2021 ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Richard Wai, Ensi Martini, Aninda Poddar, Noshen Atashe -- -- (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 ANNEXI-STRAYLINE 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 ANNEXI-STRAYLINE -- -- 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 Hex; package UUIDs.Version_1 is ------------- -- Node ID -- ------------- subtype Node_ID_Hex is String (1 .. 12); -- Represents a 48 bit value in hexadecimal form -------------------- -- Clock Sequence -- -------------------- type Clock_Sequence is mod 2**14; -- Represents a Version 1 UUID Clock Sequence value. Used to initialize new -- Version_1_States, and should be provided as a randomized value during -- instantiation of generator packages ---------------------- -- Sequence Overrun -- ---------------------- type Sequence_Overrun is (Delay_or_Error, Delay_Until, Error); -- Selected action in case of the UUID of a clock sequence overrun event. -- -- Delay_or_Error: New generation will be delayed by a 2 * System.Tick. -- If that is insufficient, Generation_Failed will be -- raised. -- -- Delay_Until : New generation will be delayed by a loop of System.Tick -- delays until the timestamp value changes. -- -- Error : A Generation_Failed exception is raised until the -- the system clock advances. -------------------------- -- Timestamp Generation -- -------------------------- type Timestamp is mod 2**60; -- Represents the number of 100ns periods since 0 UTC, Oct 15, 1582, as per -- RFC 4122, Section 4.1.4 function Standard_Source return Timestamp; -- Generates an RFC 4122 Version 1 UUID timestamp based on the reported -- system time, via the Ada.Calendar package. ------------------------------- -- Version_1 Generator State -- ------------------------------- type Version_1_State(<>) is limited private; function New_State (Node_ID : Node_ID_Hex; Initial_Clock_Sequence: Clock_Sequence; Initial_Timestamp : Timestamp := Standard_Source; Fail_Active : Boolean := False) return Version_1_State; -- Generates a Version 1 UUID with the provided Node ID, the current time- -- stamp, and an (assumed) random clock sequence. This can be used to -- initialize the state of a Generator package. For long-lived systems, the -- State should be saved and restored as appropriate. -- -- If Fail_Active is True, any exception raised during state generation is -- suppressed, and the returned state has three properties: -- 1. Node ID is set as provided -- 2. Clock sequence is set as provided -- 3. Initial timestamp is set to zero function Save_State (State: Version_1_State) return UUID; function Restore_State (ID: UUID) return Version_1_State with Pre => Version (ID) = 1; -- Generates a Version 1 State from an existing Version 1 UUID. Overrun -- protection only applies to the clock sequence restored. Saved states -- should always be advanced appropriately (as per RFC 4122, Section function Extract_Node_ID (State: Version_1_State) return Node_ID_Hex; -- Returns the Node_ID Hex string for the Node ID as set for State --------------------------------- -- Version_1 Generic Generator -- --------------------------------- generic with function Timestamp_Source return Timestamp; function Generic_Generator (State : in out Version_1_State; Overrun : in Sequence_Overrun) return UUID; -- Returns a new Version 1 UUID and modifies the State accordingly. -- If any error is encountered during generation, or the clock is not -- available, or the Overrun setting causes an error condition, -- a Generation_Failed exception is raised. -- -- -- Duplicate Generation Avoidance and Timestamp Collision Behavior -- -- If successive calls to generate for the same State encounter a current -- timestamp from Timestamp_Source which is the same as or less than the -- last issued timestamp (in the previous UUID), Generate takes one of two -- possible actions to ensure no duplicate UUIDs, both of which are pursuant -- to the permitted techniques described in RFC 4122 -- -- 1. If the sourced timestamp has not changed since the previous generation, -- a synthetic tick of a single 100ns period is applied to the last-used -- timestamp, and the clock sequence is not changed. -- -- 2. If the source timestamp has changed since the previous generation, but -- is less than the last used timestamp, the synthetic timestamp has -- overrun the system reported (sourced) timestamp, and the issued -- timestamp is held until the sourced timestamp regains the lead. -- -- During a held timestamp period, the clock sequence is incremented for -- each generated UUID. The generator records the sequence at entry to -- the held period, and monitors for sequence overrun. If generation of a -- UUID will cause a sequence overrun, Generate will take action -- according to the Overrun parameter, who's options are described with -- the Sequence_Overrun type specification, above -- -- -- All Possible Exception -- -- * Generation_Failed: Timestamp generation failure, overflow, or -- clock sequence overrun --------------------- -- Local_Generator -- --------------------- -- A local generator is not Task-safe, and is intended for Task-specific -- UUID generation. For global/task-safe UUID generation, use the related -- Global_Generator generic package below. generic Default_Overrun: in Sequence_Overrun; with function Timestamp_Source return Timestamp is Standard_Source; package Local_Generator is function Generate (Overrun: Sequence_Overrun := Default_Overrun) return UUID; -- Returns a new Version 1 UUID, according to RFC 4122 -- Not task-safe. function Export_State (Advance: Duration := 0.0) return Version_1_State; -- Returns the current state of the generator, with the time-stamp -- advanced according to Delay. procedure Import_State (New_State: Version_1_State); -- Sets a new state end Local_Generator; ---------------------- -- Global_Generator -- ---------------------- -- Calling Generate from a Global_Generator package is Task-Safe generic Default_Overrun: in Sequence_Overrun; with function Timestamp_Source return Timestamp is Standard_Source; package Global_Generator is function Generate (Overrun: Sequence_Overrun := Default_Overrun) return UUID; -- Returns a new Version 1 UUID, according to RFC 4122 -- Fully task-safe. function Export_State (Advance: Duration := 0.0) return Version_1_State; -- Fully task-safe. procedure Import_State (New_State: Version_1_State); -- Fully task-safe end Global_Generator; private -- Helper function expression to extract the Clock_Sequence specifically -- Not exposed to the user as this shouldn't have much of a use. -- New Version_1_States shall always be initialized with a random sequence, -- making this user-accessible might give the wrong idea.. function Extract_Sequence (ID: UUID) return Clock_Sequence is ((Clock_Sequence (ID.clock_seq_hi_and_reserved and 2#0011_1111#) * 2**8) or Clock_Sequence (ID.clock_seq_low)); -- Mask out lowest 6 bits of clock_seq_hi and shift left 8 bits, -- then or in clock_seq_low --------------------- -- Version_1_State -- --------------------- type Version_1_State is record Last_ID : UUID := Nil_UUID; Base_TS : Timestamp := 0; Period_Start: Clock_Sequence := 0; end record; -- The actual Version 1 UUID state is simply the last ID issued. However, we -- track extra information during generation to ensure we can detect sequence -- overruns if the generation rate is greater than 16,383 per system clock -- tick function Save_State (State: Version_1_State) return UUID is (State.Last_ID); function Restore_State (ID: UUID) return Version_1_State is (Version_1_State'(Last_ID => ID, Base_TS => 0, Period_Start => Extract_Sequence (ID))); -- This configuration ensures that restoring advanced states (ie UUIDs -- from "the future" always result in clock sequence advancement, instead -- of clock tick synthesis, by setting Base_TS to zero. This conforms with -- RFC 4122 end UUIDs.Version_1;
-- { dg-do compile} -- { dg-options "-gnatwa" } with Text_IO; use Text_IO; package body renaming1 is procedure Fo (A : Text_IO.File_Access) is begin if A = Text_IO.Standard_Output then null; end if; end Fo; end;
-- -- -- package Tables Copyright (c) Dmitry A. Kazakov -- -- Interface Luebeck -- -- Spring, 2000 -- -- -- -- Last revision : 13:11 14 Sep 2019 -- -- -- -- This library is free software; you can redistribute it and/or -- -- modify it under the terms of the GNU General Public License as -- -- published by the Free Software Foundation; either version 2 of -- -- the License, or (at your option) any later version. This library -- -- is distributed in the hope that it will be useful, but WITHOUT -- -- ANY WARRANTY; without even the implied warranty of -- -- 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 along with -- -- this library; if not, write to the Free Software Foundation, -- -- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from -- -- this unit, or you link this unit with other files to produce an -- -- executable, this unit does not by itself cause the resulting -- -- executable to be covered by the GNU General Public License. This -- -- exception does not however invalidate any other reasons why the -- -- executable file might be covered by the GNU Public License. -- --____________________________________________________________________-- -- -- The package Tables provides tables searched using string keys. The -- binary search is used for names of known length. It is also possible -- to search a table for names of unknown length, i.e. to parse a string -- using the table. In this case the search time is near to logarthmic, -- but in worst case can be linear (when table contains tokens like "a", -- "aa", "aaa" and so on). The package is generic. The instantiation -- parameter is the type of the data tag associated with a table item. -- The table is initially empty. It is automatically enlarged as new -- items are added. Upon destruction the memory used by the the table is -- reclaimed. Items in the table can be accessed either by their offsets -- (in alphabethical order) or by names. Text parsing is also supported. -- Table assignment makes a deep copy. -- -- Design notes. Unfortunately the type Table needs to be a controlled -- type. This makes instantiation possible at the library level only. -- This is surely a design flaw (of controlled types). -- with Ada.Finalization; generic type Tag is private; package Tables is type Table is new Ada.Finalization.Controlled with private; -- -- Add -- Insert an item -- -- Folder - To be modified -- Name - Of the item -- Data - The tag associated with the item -- [ Offset ] - Of the item (output) -- -- This procedure is used to add an item. It raises an exception if an -- item with the same name is already in the table. The parameter Offset -- when used, is set the offset of the newly added item. See also -- Replace. -- -- Exceptions : -- -- Name_Error - An item with the name is already in the table -- procedure Add ( Folder : in out Table; Name : String; Data : Tag ); procedure Add ( Folder : in out Table; Name : String; Data : Tag; Offset : out Positive ); -- -- Adjust -- Assignment -- -- Folder - The target -- procedure Adjust (Folder : in out Table); -- -- Delete -- Remove item -- -- Folder - To be modified -- Name - Of the item -- -- This procedure is used to remove item from the table. Nothing happens -- when there is no item with the given name. -- procedure Delete (Folder : in out Table; Name : String); -- -- Delete -- Remove item by its offset -- -- Folder - The table -- Offset - The offset of the item to be deleted -- -- Exceptions : -- -- End_Error - There is no such item -- procedure Delete ( Folder : in out Table; Offset : Positive ); -- -- Erase -- Remove all items -- -- Folder - To be modified -- -- This procedure is used to remove all items from the table. -- procedure Erase (Folder : in out Table); -- -- Finalize -- Destructor -- -- Folder - To be destroyed -- procedure Finalize (Folder : in out Table); -- -- Find -- Search table for an item -- -- Folder - To be searched -- Name - Of the item -- -- Returns : -- -- Tag of the found item -- -- Exceptions : -- -- End_Error - There is no such item -- function Find (Folder : Table; Name : String) return Tag; -- -- Get -- Parse -- -- Source - The source string to be parsed -- Pointer - The current string position -- Folder - To be searched -- Data - The tag associated with the found item -- [ Got_It ] - True an item was matched -- -- This procedure is used to parse the string specified by the parameter -- Source using the table Folder. The procedure tries to find the item -- with the longest name that matches the string Source starting from -- the position defined by the parameter Pointer. On success Pointer is -- advanced to the first position following the name of the found item. -- I.e. Source (OldPointer..Pointer - 1) is the name of the found item. -- Note that unlike Find that searches tables in logarithmic time, Get -- could require linear time in some pathological cases. -- -- Exceptions : -- -- End_Error - There is no such item -- Layout_Error - Pointer is not in Source'First..Source'Last+1 -- procedure Get ( Source : String; Pointer : in out Integer; Folder : Table; Data : out Tag ); procedure Get ( Source : String; Pointer : in out Integer; Folder : Table; Data : out Tag; Got_It : out Boolean ); -- -- GetName -- Get item name -- -- Folder - The table -- Offset - Of the item -- -- This function is used to get the name of a table item. All items in -- the table are enumerated in alphabetical order. The first item has -- the offset 1. See also GetSize. -- -- Returns : -- -- The name -- -- Exceptions : -- -- End_Error - There is no such item -- function GetName (Folder : Table; Offset : Positive) return String; -- -- GetSize -- Get the number of items in the table -- -- Folder - The table -- -- Returns : -- -- The number of items -- function GetSize (Folder : Table) return Natural; -- -- GetTag -- Get item tag -- -- Folder - The table -- Offset - Of the item -- -- This function is used to get the tag of a table item. All items in -- the table are enumerated in alphabetical order. The first item has -- the offset 1. See also GetSize. -- -- Returns : -- -- The tag -- -- Exceptions : -- -- End_Error - There is no such item -- function GetTag (Folder : Table; Offset : Positive) return Tag; -- -- IsIn -- Membership test -- -- Folder - To be searched -- Name - Of the item -- -- Returns : -- -- True if Folder contains an item for Name -- function IsIn (Folder : Table; Name : String) return Boolean; -- -- Locate -- Search table for an item -- -- Folder - To be searched -- Name - Of the item -- -- Returns : -- -- Offset to the item or else 0 -- function Locate (Folder : Table; Name : String) return Natural; -- -- Locate -- Parse -- -- Source - The source string to be parsed -- Pointer - The current string position -- Folder - To be searched -- Offset - To the found item or else 0 -- -- This procedure is similar to Get, but returns the found item offset -- instead. -- -- Exceptions : -- -- Layout_Error - Pointer is not in Source'First..Source'Last+1 -- procedure Locate ( Source : String; Pointer : in out Integer; Folder : Table; Offset : out Natural ); -- -- Replace -- Insert or replace an item -- -- Folder - To be modified -- Name - Of the item -- Data - The tag associated with the item -- [ Offset ] - Of the item (output) -- -- This procedure is used to add an item. If the table already contains -- an item with the same name it is replaced by the new one. The -- parameter Offset, when present, is set to the offset of the item. See -- also Add. -- procedure Replace ( Folder : in out Table; Name : String; Data : Tag ); procedure Replace ( Folder : in out Table; Name : String; Data : Tag; Offset : out Positive ); -- -- Replace -- Replace an item -- -- Folder - To be modified -- Offset - Of the item -- Data - The tag associated with the item -- -- This procedure is used to replace an item. The item is specified by -- its offset 1..GetSize. -- -- Exceptions : -- -- End_Error - There is no such item -- procedure Replace ( Folder : in out Table; Offset : Positive; Data : Tag ); private pragma Inline (Find); pragma Inline (Get); pragma Inline (GetSize); pragma Inline (GetTag); pragma Inline (IsIn); pragma Inline (Replace); type Token (Length : Natural) is record Data : Tag; Name : String (1..Length); end record; type TokenPtr is access Token; type TokenList is array (Positive range <>) of TokenPtr; type TokenListPtr is access TokenList; type Table is new Ada.Finalization.Controlled with record Size : Natural := 0; List : TokenListPtr := null; end record; type Equality is (Less, Equal, Greater); -- -- Insert -- Insert the item -- -- Folder - The table -- Place - The offset of the new item -- Name - Its name -- Data - Its tag -- -- This procedure is used internally to insert a new item into the -- table. No checks made! -- procedure Insert ( Folder : in out Table; Place : Positive; Name : String; Data : Tag ); -- -- Search -- The table -- -- Folder - The table to be searched -- Name - To be searched for -- -- Returns : -- -- [+] The offset of the found item -- [-] The offset where the item could be -- function Search (Folder : Table; Name : String) return Integer; end Tables;
pragma License (Unrestricted); -- extended unit package Ada.Strings.Composites is -- Unicode composite character handling. pragma Preelaborate; type Class is range 0 .. 255; for Class'Size use Standard'Storage_Unit; function Combining_Class (Item : Wide_Wide_Character) return Class; -- get all combining characters that each combining class of them > 0 procedure Iterate ( Process : not null access procedure ( Item : Wide_Wide_Character; Combining_Class : Class)); function Is_Variation_Selector (Item : Wide_Wide_Character) return Boolean; -- for sequence type State is record Next_Character : Wide_Wide_Character; Next_Combining_Class : Class; Next_Is_Illegal_Sequence : Boolean; Next_Last : Natural; end record; procedure Start (Item : String; State : out Composites.State); procedure Start (Item : Wide_String; State : out Composites.State); procedure Start (Item : Wide_Wide_String; State : out Composites.State); -- get one combining character sequence -- including trailing variation selector procedure Get_Combined ( Item : String; Last : out Natural; Is_Illegal_Sequence : out Boolean); procedure Get_Combined ( State : in out Composites.State; Item : String; Last : out Natural; Is_Illegal_Sequence : out Boolean); procedure Get_Combined ( Item : Wide_String; Last : out Natural; Is_Illegal_Sequence : out Boolean); procedure Get_Combined ( State : in out Composites.State; Item : Wide_String; Last : out Natural; Is_Illegal_Sequence : out Boolean); procedure Get_Combined ( Item : Wide_Wide_String; Last : out Natural; Is_Illegal_Sequence : out Boolean); procedure Get_Combined ( State : in out Composites.State; Item : Wide_Wide_String; Last : out Natural; Is_Illegal_Sequence : out Boolean); end Ada.Strings.Composites;
with System.Address_To_Named_Access_Conversions; with System.Growth; with System.Zero_Terminated_Strings; with C.grp; with C.pwd; package body System.Native_Credentials is use type C.pwd.struct_passwd_ptr; use type C.grp.struct_group_ptr; use type C.signed_int; -- use type C.sys.types.gid_t; -- use type C.sys.types.uid_t; function User_Name (Id : User_Id := Current_User) return String is Info : C.pwd.struct_passwd_ptr; begin Info := C.pwd.getpwuid (Id); if Info = null then raise Constraint_Error; else return Zero_Terminated_Strings.Value (Info.pw_name); end if; end User_Name; function Group_Name (Id : Group_Id := Current_Group) return String is Info : C.grp.struct_group_ptr; begin Info := C.grp.getgrgid (Id); if Info = null then raise Constraint_Error; else return Zero_Terminated_Strings.Value (Info.gr_name); end if; end Group_Name; function Belongs_To_Current_User (Id : User_Id) return Boolean is use type C.sys.types.uid_t; begin return Id = C.unistd.getuid; end Belongs_To_Current_User; function Belongs_To_Current_Group (Id : Group_Id) return Boolean is use type C.sys.types.gid_t; begin if Id = C.unistd.getgid then return True; else declare type gid_t_array is array (C.size_t range <>) of aliased C.sys.types.gid_t with Convention => C; type gid_t_ptr is access all C.sys.types.gid_t with Convention => C; package gid_t_ptr_Conv is new Address_To_Named_Access_Conversions ( C.sys.types.gid_t, gid_t_ptr); package Holder is new Growth.Scoped_Holder ( C.signed_int, Component_Size => gid_t_array'Component_Size); Length : C.signed_int; begin Holder.Reserve_Capacity (16); loop Length := C.unistd.getgroups ( Holder.Capacity, gid_t_ptr_Conv.To_Pointer (Holder.Storage_Address)); exit when Length >= 0; -- growth declare function Grow is new Growth.Fast_Grow (C.signed_int); begin Holder.Reserve_Capacity (Grow (Holder.Capacity)); end; end loop; declare Groups : gid_t_array ( 0 .. C.size_t (C.signed_int'Max (0, Length - 1))); for Groups'Address use Holder.Storage_Address; begin for I in 0 .. Length - 1 loop if Id = Groups (C.size_t (I)) then return True; end if; end loop; end; return False; end; end if; end Belongs_To_Current_Group; end System.Native_Credentials;
-- part of OpenGLAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with GL.API; package body GL.Objects.Vertex_Arrays is Current_Object : Vertex_Array_Object := Null_Array_Object; procedure Bind (Object : Vertex_Array_Object) is begin if Object.Reference = null then API.Bind_Vertex_Array (0); Current_Object := Null_Array_Object; elsif Object /= Current_Array_Object then API.Bind_Vertex_Array (Object.Reference.GL_Id); Current_Object := Object; end if; Raise_Exception_On_OpenGL_Error; end Bind; procedure Draw_Arrays (Mode : Connection_Mode; First, Count : Size) is begin API.Draw_Arrays (Mode, First, Count); Raise_Exception_On_OpenGL_Error; end Draw_Arrays; procedure Draw_Arrays_Instanced (Mode : Connection_Mode; First, Count, Instances : Size) is begin API.Draw_Arrays_Instanced (Mode, First, Count, Instances); Raise_Exception_On_OpenGL_Error; end Draw_Arrays_Instanced; procedure Set_Primitive_Restart_Index (Index : UInt) is begin API.Primitive_Restart_Index (Index); Raise_Exception_On_OpenGL_Error; end Set_Primitive_Restart_Index; overriding procedure Internal_Create_Id (Object : Vertex_Array_Object; Id : out UInt) is pragma Unreferenced (Object); begin API.Gen_Vertex_Arrays (1, Id); Raise_Exception_On_OpenGL_Error; end Internal_Create_Id; overriding procedure Internal_Release_Id (Object : Vertex_Array_Object; Id : UInt) is pragma Unreferenced (Object); begin API.Delete_Vertex_Arrays (1, (1 => Id)); Raise_Exception_On_OpenGL_Error; end Internal_Release_Id; function Current_Array_Object return Vertex_Array_Object is begin return Current_Object; end Current_Array_Object; end GL.Objects.Vertex_Arrays;
package body Test_Aircraft.Read is package Skill renames Aircraft.Api; procedure Initialize (T : in out Test) is begin Set_Name (T, "Test_Aircraft.Read"); Ahven.Framework.Add_Test_Routine (T, Airplane_1'Access, "airplane 1: 1, Fokker 100, true"); Ahven.Framework.Add_Test_Routine (T, Airplane_2'Access, "airplane 2: 2, Bombardier Dash 8, false"); Ahven.Framework.Add_Test_Routine (T, Helicopter_1'Access, "helicopter 1: 1, Bell 206, false"); Ahven.Framework.Add_Test_Routine (T, Helicopter_1'Access, "helicopter 2: 2, Sikorsky S-76C+, true"); end Initialize; procedure Airplane_1 is use Ada.Strings.Unbounded; State : access Skill_State := new Skill_State; begin Skill.Read (State, "resources/aircraft.sf"); declare X : Airplane_Type_Access := Skill.Get_Airplane (State, 1); begin Ahven.Assert (X.Get_Id = 1, "'first airplane'.Get_Id is not 1."); Ahven.Assert (X.Get_Name.all = "Fokker 100", "'first airplane'.Get_Name is not 'Fokker 100'."); Ahven.Assert (X.Get_Operational = True, "'first airplane'.Get_Operational is not true."); end; end Airplane_1; procedure Airplane_2 is use Ada.Strings.Unbounded; State : access Skill_State := new Skill_State; begin Skill.Read (State, "resources/aircraft.sf"); declare X : Airplane_Type_Access := Skill.Get_Airplane (State, 2); begin Ahven.Assert (X.Get_Id = 2, "'second airplane'.Get_Id is not 2."); Ahven.Assert (X.Get_Name.all = "Bombardier Dash 8", "'second airplane'.Get_Name is not 'Bombardier Dash 8'."); Ahven.Assert (X.Get_Operational = False, "'second airplane'.Get_Operational is not false."); end; end Airplane_2; procedure Helicopter_1 is use Ada.Strings.Unbounded; State : access Skill_State := new Skill_State; begin Skill.Read (State, "resources/aircraft.sf"); declare X : Helicopter_Type_Access := Skill.Get_Helicopter (State, 1); begin Ahven.Assert (X.Get_Id = 1, "'first helicopter'.Get_Id is not 1."); Ahven.Assert (X.Get_Name.all = "Bell 206", "'first helicopter'.Get_Name is not 'Bell 206'."); Ahven.Assert (X.Get_Operational = False, "'first helicopter'.Get_Operational is not false."); end; end Helicopter_1; procedure Helicopter_2 is use Ada.Strings.Unbounded; State : access Skill_State := new Skill_State; begin Skill.Read (State, "resources/aircraft.sf"); declare X : Helicopter_Type_Access := Skill.Get_Helicopter (State, 2); begin Ahven.Assert (X.Get_Id = 2, "'first helicopter'.Get_Id is not 2."); Ahven.Assert (X.Get_Name.all = "Sikorsky S-76C+", "'first helicopter'.Get_Name is not 'Sikorsky S-76C+'."); Ahven.Assert (X.Get_Operational = True, "'first helicopter'.Get_Operational is not true."); end; end Helicopter_2; end Test_Aircraft.Read;
------------------------------------------------------------------------------ -- 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 Nodes; with Text_Streams.File; with XML_IO.Stream_Readers; with Gela.Embeded_Links.Lists; package body Gramar_Items.Code is --------------- -- Item_Info -- --------------- type Item_Info; type Item_Info_Ptr is access all Item_Info; type Item_Info is record Next : Item_Info_Ptr; Item_Name : Unbounded_String; Attr_Name : Unbounded_String; On_Option_Node_Name : Unbounded_String; Trait_Name : Unbounded_String; Create : Unbounded_String; Choise : Unbounded_String; Value : Unbounded_String; Instance : Positive := 1; Wrapper : Natural; end record; function "=" (Left, Right : Item_Info) return Boolean; function Get_Next (Item : Item_Info_Ptr) return Item_Info_Ptr; procedure Set_Next (Item, Next : Item_Info_Ptr); package Item_Info_Lists is new Gela.Embeded_Links.Lists (Item_Info, Item_Info_Ptr); --------------- -- Wrap_Info -- --------------- type Wrap_Info; type Wrap_Info_Ptr is access all Wrap_Info; type Wrap_Info is record Next : Wrap_Info_Ptr; Node_Name : Unbounded_String; Item_Name : Unbounded_String; Attr_Name : Unbounded_String; Position : Unbounded_String; Index : Positive; Parent : Natural; Instance : Positive := 1; end record; function "=" (Left, Right : Wrap_Info) return Boolean; function Get_Next (Item : Wrap_Info_Ptr) return Wrap_Info_Ptr; procedure Set_Next (Item, Next : Wrap_Info_Ptr); package Wrap_Info_Lists is new Gela.Embeded_Links.Lists (Wrap_Info, Wrap_Info_Ptr); -------------- -- Seq_Info -- -------------- type Seq_Info; type Seq_Info_Ptr is access all Seq_Info; type Seq_Info is record Next : Seq_Info_Ptr; Rule_Name : Unbounded_String; Containts_Name : Unbounded_String; Node_Name : Unbounded_String; True_Node : Unbounded_String; False_Node : Unbounded_String; Infix : Unbounded_String; Pass_Through : Boolean; Inline_Option : Boolean; Items : Item_Info_Lists.List; Wraps : Wrap_Info_Lists.List; end record; function "=" (Left, Right : Seq_Info) return Boolean; function Get_Next (Item : Seq_Info_Ptr) return Seq_Info_Ptr; procedure Set_Next (Item, Next : Seq_Info_Ptr); package Seq_Info_Lists is new Gela.Embeded_Links.Lists (Seq_Info, Seq_Info_Ptr); All_Seq : Seq_Info_Lists.List; Wrap_Stack : Wrap_Info_Lists.List; Last_Wrap : Positive; Conflict_Names : array (1 .. 20) of Unbounded_String; Conflict_Count : Natural := 0; Skip_Rules : array (1 .. 20) of Unbounded_String; Skip_Count : Natural := 0; function Get_Parent_Wrap return Natural; function Find_Seq (Rule_Name : String; Seq : Sequence) return Seq_Info_Ptr; function Find_Item (Rule_Name : String; Seq : Sequence; Item_Name : String; Instance : Positive) return Item_Info_Ptr; function Find_Wrap (Rule_Name : String; Seq : Sequence; Wrapper : Positive) return Wrap_Info_Ptr; function Contains_Name (Seq : Sequence; Name : String) return Boolean; procedure Read_Code_File (Name : String) is use XML_IO; package R renames XML_IO.Stream_Readers; Stream : aliased Text_Streams.File.File_Text_Stream; Parser : R.Reader (Stream'Access, R.Default_Buffer_Size); Current_Rule : Unbounded_String; Last_Seq_Info : Seq_Info_Ptr; function Get_Attribute (Name : String) return String is begin return R.Attribute_Value (Parser, Name); end Get_Attribute; procedure On_Element is Local_Name : constant String := R.Name (Parser); begin if Local_Name = "rule" then declare Name : constant String := Get_Attribute ("name"); Skip : constant String := Get_Attribute ("skip"); begin Current_Rule := To_Unbounded_String (Name); if Skip = "y" then Skip_Count := Skip_Count + 1; Skip_Rules (Skip_Count) := Current_Rule; end if; end; elsif Local_Name = "seq" then declare Name : constant String := Get_Attribute ("contains_name"); Pass : constant String := Get_Attribute ("pass-through"); Node : constant String := Get_Attribute ("node"); True_Node : constant String := Get_Attribute ("true-node"); False_Node : constant String := Get_Attribute ("false-node"); Infix : constant String := Get_Attribute ("infix"); Inline_Opt : constant String := Get_Attribute ("inline-option"); L : Seq_Info_Ptr renames Last_Seq_Info; begin L := new Seq_Info; L.Rule_Name := Current_Rule; L.Containts_Name := To_Unbounded_String (Name); L.Node_Name := To_Unbounded_String (Node); L.True_Node := To_Unbounded_String (True_Node); L.False_Node := To_Unbounded_String (False_Node); L.Infix := To_Unbounded_String (Infix); L.Pass_Through := Pass /= ""; L.Inline_Option := Inline_Opt = "yes"; Seq_Info_Lists.Append (All_Seq, L); Last_Wrap := 1; end; elsif Local_Name = "wrap" then declare Node : constant String := Get_Attribute ("node"); Item : constant String := Get_Attribute ("item"); Attr : constant String := Get_Attribute ("attr"); Pos : constant String := Get_Attribute ("pos"); Instance : constant String := Get_Attribute ("instance"); L : constant Wrap_Info_Ptr := new Wrap_Info; begin L.Node_Name := To_Unbounded_String (Node); L.Item_Name := To_Unbounded_String (Item); L.Attr_Name := To_Unbounded_String (Attr); L.Position := To_Unbounded_String (Pos); L.Index := Last_Wrap; L.Parent := Get_Parent_Wrap; if Instance /= "" then L.Instance := Integer'Value (Instance); end if; Last_Wrap := Last_Wrap + 1; Wrap_Info_Lists.Prepend (Wrap_Stack, L); end; elsif Local_Name = "item" then declare Name : constant String := Get_Attribute ("name"); Attr : constant String := Get_Attribute ("attr"); Trait : constant String := Get_Attribute ("trait"); Opt_Node : constant String := Get_Attribute ("on-option-node"); Instance : constant String := Get_Attribute ("instance"); Create : constant String := Get_Attribute ("create"); Choise : constant String := Get_Attribute ("choise"); Value : constant String := Get_Attribute ("value"); I : constant Item_Info_Ptr := new Item_Info; begin I.Item_Name := To_Unbounded_String (Name); I.Attr_Name := To_Unbounded_String (Attr); I.On_Option_Node_Name := To_Unbounded_String (Opt_Node); I.Trait_Name := To_Unbounded_String (Trait); I.Create := To_Unbounded_String (Create); I.Choise := To_Unbounded_String (Choise); I.Value := To_Unbounded_String (Value); I.Wrapper := Get_Parent_Wrap; if Instance /= "" then I.Instance := Integer'Value (Instance); end if; Item_Info_Lists.Append (Last_Seq_Info.Items, I); end; elsif Local_Name = "conflict" then declare Name : constant String := Get_Attribute ("name"); begin Conflict_Count := Conflict_Count + 1; Conflict_Names (Conflict_Count) := To_Unbounded_String (Name); end; end if; end On_Element; begin Text_Streams.File.Open (Stream, Name); R.Initialize (Parser); while R.More_Pieces (Parser) loop case R.Piece_Kind (Parser) is when Start_Element => On_Element; when End_Element => if R.Name (Parser) = "wrap" then declare L : Seq_Info_Ptr renames Last_Seq_Info; W : Wrap_Info_Ptr; begin Wrap_Info_Lists.Delete_First (Wrap_Stack, W); Wrap_Info_Lists.Append (L.Wraps, W); end; end if; when others => null; end case; R.Next (Parser); end loop; end Read_Code_File; function "=" (Left, Right : Item_Info) return Boolean is begin return Left.Item_Name = Right.Item_Name; end "="; function Get_Next (Item : Item_Info_Ptr) return Item_Info_Ptr is begin return Item.Next; end Get_Next; procedure Set_Next (Item, Next : Item_Info_Ptr) is begin Item.Next := Next; end Set_Next; function "=" (Left, Right : Seq_Info) return Boolean is begin return Left.Rule_Name = Right.Rule_Name and Left.Containts_Name = Right.Containts_Name; end "="; function Get_Next (Item : Seq_Info_Ptr) return Seq_Info_Ptr is begin return Item.Next; end Get_Next; procedure Set_Next (Item, Next : Seq_Info_Ptr) is begin Item.Next := Next; end Set_Next; function "=" (Left, Right : Wrap_Info) return Boolean is begin return Left.Index = Right.Index; end "="; function Get_Next (Item : Wrap_Info_Ptr) return Wrap_Info_Ptr is begin return Item.Next; end Get_Next; procedure Set_Next (Item, Next : Wrap_Info_Ptr) is begin Item.Next := Next; end Set_Next; function Node_Name (Rule_Name : String; Seq : Sequence) return String is Info_Ptr : constant Seq_Info_Ptr := Find_Seq (Rule_Name, Seq); begin if Info_Ptr /= null then return To_String (Info_Ptr.Node_Name); else return ""; end if; end Node_Name; function Infix (Rule_Name : String; Seq : Sequence) return String is Info_Ptr : constant Seq_Info_Ptr := Find_Seq (Rule_Name, Seq); begin if Info_Ptr /= null then return To_String (Info_Ptr.Infix); else return ""; end if; end Infix; function True_Node (Rule_Name : String; Seq : Sequence) return String is Info_Ptr : constant Seq_Info_Ptr := Find_Seq (Rule_Name, Seq); begin if Info_Ptr /= null then return To_String (Info_Ptr.True_Node); else return ""; end if; end True_Node; function False_Node (Rule_Name : String; Seq : Sequence) return String is Info_Ptr : constant Seq_Info_Ptr := Find_Seq (Rule_Name, Seq); begin if Info_Ptr /= null then return To_String (Info_Ptr.False_Node); else return ""; end if; end False_Node; function Inline_Option (Rule_Name : String; Seq : Sequence) return Boolean is Info_Ptr : constant Seq_Info_Ptr := Find_Seq (Rule_Name, Seq); begin if Info_Ptr /= null then return Info_Ptr.Inline_Option; end if; return False; end Inline_Option; function Pass_Throgh (Rule_Name : String; Seq : Sequence) return Boolean is Info_Ptr : constant Seq_Info_Ptr := Find_Seq (Rule_Name, Seq); Ref_Count : Natural := 0; Other_Count : Natural := 0; begin if Info_Ptr /= null then return Info_Ptr.Pass_Through; end if; for I in 1 .. Count (Seq) loop declare Child : Item'Class renames Get_Item (Seq, I).all; begin if Child in Reference then Ref_Count := Ref_Count + 1; elsif Child in List or Child in Option then Other_Count := Other_Count + 1; end if; end; end loop; return Ref_Count = 1 and Other_Count = 0; end Pass_Throgh; function Find_Seq (Rule_Name : String; Seq : Sequence) return Seq_Info_Ptr is use Seq_Info_Lists; Next : aliased Seq_Info_Ptr; begin while Iterate (All_Seq, Next'Access) loop if Rule_Name = Next.Rule_Name then if Next.Containts_Name = "" or else Contains_Name (Seq, To_String (Next.Containts_Name)) then return Next; end if; end if; end loop; return null; end Find_Seq; function Contains_Name (Seq : Sequence; Name : String) return Boolean is begin for I in 1 .. Count (Seq) loop declare Child_Name : constant String := Item_Name (Get_Item (Seq, I).all); begin if Name = Child_Name then return True; end if; end; end loop; return False; end Contains_Name; function Get_Use_Attr (Rule_Name : String; Seq : Sequence; Item_Name : String; Instance : Positive) return String is Info_Ptr : constant Item_Info_Ptr := Find_Item (Rule_Name, Seq, Item_Name, Instance); begin if Info_Ptr /= null then return To_String (Info_Ptr.Attr_Name); else return ""; end if; end Get_Use_Attr; function Find_Item (Rule_Name : String; Seq : Sequence; Item_Name : String; Instance : Positive) return Item_Info_Ptr is use Item_Info_Lists; Found : constant Seq_Info_Ptr := Find_Seq (Rule_Name, Seq); Next : aliased Item_Info_Ptr; begin if Found = null then return null; end if; while Iterate (Found.Items, Next'Access) loop if Next.Item_Name = Item_Name and Next.Instance = Instance then return Next; end if; end loop; return null; end Find_Item; function Alternative_Node_Name (Rule_Name : String; Seq : Sequence; Item_Name : String) return String is Info_Ptr : constant Item_Info_Ptr := Find_Item (Rule_Name, Seq, Item_Name, 1); begin if Info_Ptr /= null then return Nodes.Get_Node_Type_Name (To_String (Info_Ptr.On_Option_Node_Name)); else return ""; end if; end Alternative_Node_Name; function Trait_Name (Rule_Name : String; Seq : Sequence; Item_Name : String) return String is Info_Ptr : constant Item_Info_Ptr := Find_Item (Rule_Name, Seq, Item_Name, 1); begin if Info_Ptr /= null then return To_String (Info_Ptr.Trait_Name); else return ""; end if; end Trait_Name; function Created_Node_Name (Rule_Name : String; Seq : Sequence; Item_Name : String) return String is Info_Ptr : constant Item_Info_Ptr := Find_Item (Rule_Name, Seq, Item_Name, 1); begin if Info_Ptr /= null then return To_String (Info_Ptr.Create); else return ""; end if; end Created_Node_Name; function Choise (Rule_Name : String; Seq : Sequence; Item_Name : String) return String is Info_Ptr : constant Item_Info_Ptr := Find_Item (Rule_Name, Seq, Item_Name, 1); begin if Info_Ptr /= null then return To_String (Info_Ptr.Choise); else return ""; end if; end Choise; function Value (Rule_Name : String; Seq : Sequence; Item_Name : String) return String is Info_Ptr : constant Item_Info_Ptr := Find_Item (Rule_Name, Seq, Item_Name, 1); begin if Info_Ptr /= null then return To_String (Info_Ptr.Value); else return ""; end if; end Value; function Wrapper_Index (Rule_Name : String; Seq : Sequence; Item_Name : String; Instance : Positive) return Natural is Info_Ptr : constant Item_Info_Ptr := Find_Item (Rule_Name, Seq, Item_Name, Instance); begin if Info_Ptr /= null then return Info_Ptr.Wrapper; else return 0; end if; end Wrapper_Index; function Get_Parent_Wrap return Natural is begin if Wrap_Info_Lists.Is_Empty (Wrap_Stack) then return 0; else return Wrap_Info_Lists.First (Wrap_Stack).Index; end if; end Get_Parent_Wrap; function Wrapper_Index (Rule_Name : String; Seq : Sequence; Wrapper : Positive) return Natural is Wrap_Ptr : constant Wrap_Info_Ptr := Find_Wrap (Rule_Name, Seq, Wrapper); begin if Wrap_Ptr /= null then return Wrap_Ptr.Parent; else return 0; end if; end Wrapper_Index; function Wrapper_Instance (Rule_Name : String; Seq : Sequence; Wrapper : Positive) return Positive is Wrap_Ptr : constant Wrap_Info_Ptr := Find_Wrap (Rule_Name, Seq, Wrapper); begin return Wrap_Ptr.Instance; end Wrapper_Instance; function Find_Wrap (Rule_Name : String; Seq : Sequence; Wrapper : Positive) return Wrap_Info_Ptr is use Item_Info_Lists; package Search is new Wrap_Info_Lists.Generic_Search; Found : Seq_Info_Ptr := Find_Seq (Rule_Name, Seq); Wrp : Wrap_Info; begin if Found = null then return null; end if; Wrp.Index := Wrapper; return Search.Find (Found.Wraps, Wrp); end Find_Wrap; function User_Wraps (Rule_Name : String; Seq : Sequence) return Natural is Info_Ptr : constant Seq_Info_Ptr := Find_Seq (Rule_Name, Seq); begin if Info_Ptr = null then return 0; else return Natural (Wrap_Info_Lists.Length (Info_Ptr.Wraps)); end if; end User_Wraps; function User_Wrap_Node (Rule_Name : String; Seq : Sequence; Index : Positive) return String is Wrap_Ptr : constant Wrap_Info_Ptr := Find_Wrap (Rule_Name, Seq, Index); begin if Wrap_Ptr /= null then return To_String (Wrap_Ptr.Node_Name); else return ""; end if; end User_Wrap_Node; function Wrap_Item_Name (Rule_Name : String; Seq : Sequence; Index : Positive) return String is Wrap_Ptr : constant Wrap_Info_Ptr := Find_Wrap (Rule_Name, Seq, Index); begin if Wrap_Ptr /= null then return To_String (Wrap_Ptr.Item_Name); else return ""; end if; end Wrap_Item_Name; function Wrap_Attr_Name (Rule_Name : String; Seq : Sequence; Index : Positive) return String is Wrap_Ptr : constant Wrap_Info_Ptr := Find_Wrap (Rule_Name, Seq, Index); begin if Wrap_Ptr /= null then return To_String (Wrap_Ptr.Attr_Name); else return ""; end if; end Wrap_Attr_Name; function Wrapper_Position (Rule_Name : String; Seq : Sequence; Wrapper : Positive) return String is Wrap_Ptr : constant Wrap_Info_Ptr := Find_Wrap (Rule_Name, Seq, Wrapper); begin if Wrap_Ptr /= null then return To_String (Wrap_Ptr.Position); else return ""; end if; end Wrapper_Position; function Conflict_Name (Rule_Name : String) return Boolean is begin for J in 1 .. Conflict_Count loop if Conflict_Names (J) = Rule_Name then return True; end if; end loop; return False; end Conflict_Name; function Skip_Rule (Rule_Name : String) return Boolean is begin for J in 1 .. Skip_Count loop if Skip_Rules (J) = Rule_Name then return True; end if; end loop; return False; end Skip_Rule; end Gramar_Items.Code; ------------------------------------------------------------------------------ -- 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. ------------------------------------------------------------------------------
pragma Style_Checks (Off); -- This spec has been automatically generated from ATSAMD51G19A.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package SAM_SVD.FREQM is pragma Preelaborate; --------------- -- Registers -- --------------- -- Control A Register type FREQM_CTRLA_Register is record -- Software Reset SWRST : Boolean := False; -- Enable ENABLE : Boolean := False; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for FREQM_CTRLA_Register use record SWRST at 0 range 0 .. 0; ENABLE at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; end record; -- Control B Register type FREQM_CTRLB_Register is record -- Write-only. Start Measurement START : Boolean := False; -- unspecified Reserved_1_7 : HAL.UInt7 := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for FREQM_CTRLB_Register use record START at 0 range 0 .. 0; Reserved_1_7 at 0 range 1 .. 7; end record; subtype FREQM_CFGA_REFNUM_Field is HAL.UInt8; -- Config A register type FREQM_CFGA_Register is record -- Number of Reference Clock Cycles REFNUM : FREQM_CFGA_REFNUM_Field := 16#0#; -- unspecified Reserved_8_15 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 16, Bit_Order => System.Low_Order_First; for FREQM_CFGA_Register use record REFNUM at 0 range 0 .. 7; Reserved_8_15 at 0 range 8 .. 15; end record; -- Interrupt Enable Clear Register type FREQM_INTENCLR_Register is record -- Measurement Done Interrupt Enable DONE : Boolean := False; -- unspecified Reserved_1_7 : HAL.UInt7 := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for FREQM_INTENCLR_Register use record DONE at 0 range 0 .. 0; Reserved_1_7 at 0 range 1 .. 7; end record; -- Interrupt Enable Set Register type FREQM_INTENSET_Register is record -- Measurement Done Interrupt Enable DONE : Boolean := False; -- unspecified Reserved_1_7 : HAL.UInt7 := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for FREQM_INTENSET_Register use record DONE at 0 range 0 .. 0; Reserved_1_7 at 0 range 1 .. 7; end record; -- Interrupt Flag Register type FREQM_INTFLAG_Register is record -- Measurement Done DONE : Boolean := False; -- unspecified Reserved_1_7 : HAL.UInt7 := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for FREQM_INTFLAG_Register use record DONE at 0 range 0 .. 0; Reserved_1_7 at 0 range 1 .. 7; end record; -- Status Register type FREQM_STATUS_Register is record -- FREQM Status BUSY : Boolean := False; -- Sticky Count Value Overflow OVF : Boolean := False; -- unspecified Reserved_2_7 : HAL.UInt6 := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for FREQM_STATUS_Register use record BUSY at 0 range 0 .. 0; OVF at 0 range 1 .. 1; Reserved_2_7 at 0 range 2 .. 7; end record; -- Synchronization Busy Register type FREQM_SYNCBUSY_Register is record -- Read-only. Software Reset SWRST : Boolean; -- Read-only. Enable ENABLE : Boolean; -- unspecified Reserved_2_31 : HAL.UInt30; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for FREQM_SYNCBUSY_Register use record SWRST at 0 range 0 .. 0; ENABLE at 0 range 1 .. 1; Reserved_2_31 at 0 range 2 .. 31; end record; subtype FREQM_VALUE_VALUE_Field is HAL.UInt24; -- Count Value Register type FREQM_VALUE_Register is record -- Read-only. Measurement Value VALUE : FREQM_VALUE_VALUE_Field; -- unspecified Reserved_24_31 : HAL.UInt8; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for FREQM_VALUE_Register use record VALUE at 0 range 0 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Frequency Meter type FREQM_Peripheral is record -- Control A Register CTRLA : aliased FREQM_CTRLA_Register; -- Control B Register CTRLB : aliased FREQM_CTRLB_Register; -- Config A register CFGA : aliased FREQM_CFGA_Register; -- Interrupt Enable Clear Register INTENCLR : aliased FREQM_INTENCLR_Register; -- Interrupt Enable Set Register INTENSET : aliased FREQM_INTENSET_Register; -- Interrupt Flag Register INTFLAG : aliased FREQM_INTFLAG_Register; -- Status Register STATUS : aliased FREQM_STATUS_Register; -- Synchronization Busy Register SYNCBUSY : aliased FREQM_SYNCBUSY_Register; -- Count Value Register VALUE : aliased FREQM_VALUE_Register; end record with Volatile; for FREQM_Peripheral use record CTRLA at 16#0# range 0 .. 7; CTRLB at 16#1# range 0 .. 7; CFGA at 16#2# range 0 .. 15; INTENCLR at 16#8# range 0 .. 7; INTENSET at 16#9# range 0 .. 7; INTFLAG at 16#A# range 0 .. 7; STATUS at 16#B# range 0 .. 7; SYNCBUSY at 16#C# range 0 .. 31; VALUE at 16#10# range 0 .. 31; end record; -- Frequency Meter FREQM_Periph : aliased FREQM_Peripheral with Import, Address => FREQM_Base; end SAM_SVD.FREQM;
package Parent_Ltd_With.Child_Full_View is type Child_Symbol is new Parent_Ltd_With.Symbol with private; type Child_Symbol_Access is access all Child_Symbol; function New_Child_Symbol return Child_Symbol_Access; private type Child_Symbol is new Parent_Ltd_With.Symbol with null record; end Parent_Ltd_With.Child_Full_View;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . D I R E C T _ I O -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2014, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the declaration of the control block used for -- Direct_IO. This must be declared at the outer library level. It also -- contains code that is shared between instances of Direct_IO. with Interfaces.C_Streams; with Ada.Streams; with System.File_Control_Block; with System.Storage_Elements; package System.Direct_IO is package FCB renames System.File_Control_Block; type Operation is (Op_Read, Op_Write, Op_Other); -- Type used to record last operation (to optimize sequential operations) subtype Count is Interfaces.C_Streams.int64; -- The Count type in each instantiation is derived from this type subtype Positive_Count is Count range 1 .. Count'Last; type Direct_AFCB is new FCB.AFCB with record Index : Count := 1; -- Current Index value Bytes : Interfaces.C_Streams.size_t; -- Length of item in bytes (set from inside generic template) Last_Op : Operation := Op_Other; -- Last operation performed on file, used to avoid unnecessary -- repositioning between successive read or write operations. end record; function AFCB_Allocate (Control_Block : Direct_AFCB) return FCB.AFCB_Ptr; procedure AFCB_Close (File : not null access Direct_AFCB); procedure AFCB_Free (File : not null access Direct_AFCB); procedure Read (File : in out Direct_AFCB; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Required overriding of Read, not actually used for Direct_IO procedure Write (File : in out Direct_AFCB; Item : Ada.Streams.Stream_Element_Array); -- Required overriding of Write, not actually used for Direct_IO type File_Type is access all Direct_AFCB; -- File_Type in individual instantiations is derived from this type procedure Create (File : in out File_Type; Mode : FCB.File_Mode := FCB.Inout_File; Name : String := ""; Form : String := ""); function End_Of_File (File : File_Type) return Boolean; function Index (File : File_Type) return Positive_Count; procedure Open (File : in out File_Type; Mode : FCB.File_Mode; Name : String; Form : String := ""); procedure Read (File : File_Type; Item : System.Address; Size : Interfaces.C_Streams.size_t; From : Positive_Count); procedure Read (File : File_Type; Item : System.Address; Size : Interfaces.C_Streams.size_t); procedure Reset (File : in out File_Type; Mode : FCB.File_Mode); procedure Reset (File : in out File_Type); procedure Set_Index (File : File_Type; To : Positive_Count); function Size (File : File_Type) return Count; procedure Write (File : File_Type; Item : System.Address; Size : Interfaces.C_Streams.size_t; Zeroes : System.Storage_Elements.Storage_Array); -- Note: Zeroes is the buffer of zeroes used to fill out partial records -- The following procedures have a File_Type formal of mode IN OUT because -- they may close the original file. The Close operation may raise an -- exception, but in that case we want any assignment to the formal to -- be effective anyway, so it must be passed by reference (or the caller -- will be left with a dangling pointer). pragma Export_Procedure (Internal => Reset, External => "", Parameter_Types => (File_Type), Mechanism => Reference); pragma Export_Procedure (Internal => Reset, External => "", Parameter_Types => (File_Type, FCB.File_Mode), Mechanism => (File => Reference)); end System.Direct_IO;
with Ada.Calendar; use Ada.Calendar; package body Deck is function Draw return Card is Result : Index_Type := Random(Index_Generator); begin while Backing(Result).In_Deck = False loop Result := Random(Index_Generator); end loop; Backing(Result).In_Deck := False; return Card(Backing(Result)); end Draw; begin Reset(Index_Generator, Integer(Seconds(Clock))); end Deck;
-- { dg-do compile } with Ada.Tags.Generic_Dispatching_Constructor; package body Graphic is -- function Dispatching_Input is new Tags.Generic_Dispatching_Constructor (T => Object, Parameters => Streams.Root_Stream_Type'Class, Constructor => Object'Input); -- function XML_Input (S : access Streams.Root_Stream_Type'Class) return Object'Class is Result : constant Object'Class := Dispatching_Input (Tags.Internal_Tag (" "), S); begin return Result; end XML_Input; end Graphic;
-- File: adaid_tests.ads -- Description: Test suite for AdaID -- Author: Anthony Arnold -- License: http://www.gnu.org/licenses/gpl.txt with AUnit; use AUnit; with AUnit.Test_Cases; package AdaID_Tests is type UUID_Test is new AUnit.Test_Cases.Test_Case with null record; type Access_UUID_Test is access UUID_Test; -- Register the tests to run procedure Register_Tests(T : in out UUID_Test); -- Register the test name function Name (T : UUID_Test) return Message_String; private -- Test routines procedure Initialization(T : in out AUnit.Test_Cases.Test_Case'Class); procedure SetNil(T : in out AUnit.Test_Cases.Test_Case'Class); procedure GetVersion(T : in out AUnit.Test_Cases.Test_Case'Class); procedure GetVariant(T : in out AUnit.Test_Cases.Test_Case'Class); procedure Equals(T : in out AUnit.Test_Cases.Test_Case'Class); procedure GetHashCode(T : in out AUnit.Test_Cases.Test_Case'Class); procedure RandomNotNil(T : in out AUnit.Test_Cases.Test_Case'Class); procedure RandomUnique(T : in out AUnit.Test_Cases.Test_Case'Class); procedure FromNameNotNil(T : in out AUnit.Test_Cases.Test_Case'Class); procedure FromNameUnique(T : in out AUnit.Test_Cases.Test_Case'Class); procedure FromNameEqual(T : in out AUnit.Test_Cases.Test_Case'Class); procedure ToString(T : in out AUnit.Test_Cases.Test_Case'Class); procedure FromStringNil(T : in out AUnit.Test_Cases.Test_Case'Class); procedure FromStringEqual(T : in out AUnit.Test_Cases.Test_Case'Class); procedure FromBadString(T : in out AUnit.Test_Cases.Test_Case'Class); end AdaID_Tests;
with Ada.Text_IO; use Ada.Text_IO; procedure Rosetta_Read is File : File_Type; begin Open (File => File, Mode => In_File, Name => "rosetta_read.adb"); Set_Line (File, To => 7); declare Line_7 : constant String := Get_Line (File); begin if Line_7'Length = 0 then Put_Line ("Line 7 is empty."); else Put_Line (Line_7); end if; end; Close (File); exception when End_Error => Put_Line ("The file contains fewer than 7 lines."); Close (File); when Storage_Error => Put_Line ("Line 7 is too long to load."); Close (File); end Rosetta_Read;
with System.Machine_Code; use System.Machine_Code; with System.Storage_Elements; use System.Storage_Elements; with System.Address_To_Access_Conversions; with System; use System; with Interfaces; use Interfaces; with MSPGD.Board; use MSPGD.Board; with MSP430_SVD; use MSP430_SVD; with MSP430_SVD.FLASH; use MSP430_SVD.FLASH; with MSP430_SVD.SYSTEM_CLOCK; use MSP430_SVD.SYSTEM_CLOCK; procedure Main is pragma Preelaborate; Flash_Start : Unsigned_16 with Import, External_Name => "__flash_start"; Flash_Segment_Size : constant Unsigned_16 := 512; type Flash_Memory_Type is array (Unsigned_16 range 0 .. 65535) of Unsigned_8; type Flash_Memory_Pointer is access all Flash_Memory_Type; package Convert is new System.Address_To_Access_Conversions (Flash_Memory_Type); Flash_Memory : constant Convert.Object_Pointer := Convert.To_Pointer (System'To_Address (0)); Line : array (Unsigned_16 range 0 .. 47) of Unsigned_8; Write_Addr : Unsigned_16; Count : Unsigned_8; XON : constant Byte := 17; XOFF : constant Byte := 19; FCTL1 : Unsigned_16 with Import, Address => System'To_Address (16#0128#); FCTL2 : Unsigned_16 with Import, Address => System'To_Address (16#012A#); FCTL3 : Unsigned_16 with Import, Address => System'To_Address (16#012C#); function Nibble (N : Unsigned_8) return Unsigned_8 is begin return (if N >= 65 then N - 65 + 10 else N - 48); end Nibble; function From_Hex (I : Unsigned_16) return Unsigned_8 is begin return 16 * Nibble (Line (I)) + Nibble (Line (I + 1)); end From_Hex; procedure Erase_Flash is Addr : Unsigned_16 := Flash_Start; R_Low : Unsigned_8 := Flash_Memory (65534); R_High : Unsigned_8 := Flash_Memory (65535); begin FCTL3 := 16#A500#; FCTL1 := 16#A502#; Flash_Memory (65534) := 0; while Addr <= 65535 loop if Addr /= 16#FA00# then Flash_Memory (Addr) := 0; end if; Addr := Addr + Flash_Segment_Size; end loop; Flash_Memory (65534) := R_Low; Flash_Memory (65535) := R_High; FCTL1 := 16#A500#; FCTL3 := 16#A510#; end Erase_Flash; procedure Write_Flash is begin FCTL3 := 16#A500#; FCTL1 := 16#A540#; for I in Unsigned_8 range 0 .. Count loop Flash_Memory (Write_Addr) := From_Hex (Unsigned_16 (I) * 2); Write_Addr := Write_Addr + Unsigned_16 (1); end loop; FCTL1 := 16#A500#; FCTL3 := 16#A510#; end Write_Flash; procedure Reset is begin UART.Transmit (XON); FCTL1 := 16#0000#; end Reset; procedure Read_Line is Record_Type : Unsigned_8; begin UART.Transmit (XON); for I in Line'Range loop Line (I) := Unsigned_8 (UART.Receive); exit when Line (I) = 10; end loop; UART.Transmit (XOFF); Count := From_Hex (1); Write_Addr := (Unsigned_16 (From_Hex (3)) * 256 + Unsigned_16 (From_Hex (5))); Record_Type := From_Hex (7); case Record_Type is when 16#00# => Write_Flash; when 16#01# => Reset; when 16#80# => Erase_Flash; when others => null; end case; end Read_Line; procedure Init is CALDCO_8MHz : DCOCTL_Register with Import, Address => System'To_Address (16#10FC#); CALBC1_8MHz : BCSCTL1_Register with Import, Address => System'To_Address (16#10FD#); begin BUTTON.Init; if BUTTON.Is_Set then null; end if; -- SYSTEM_CLOCK_Periph.DCOCTL.MOD_k.Val := 0; -- SYSTEM_CLOCK_Periph.DCOCTL.DCO.Val := 0; SYSTEM_CLOCK_Periph.BCSCTL1 := CALBC1_8MHz; SYSTEM_CLOCK_Periph.DCOCTL := CALDCO_8MHz; RX.Init; TX.Init; UART.Init; FCTL2 := 16#A554#; -- FLASH_Periph.FCTL2 := (FWKEY => 16#A5#, FSSEL => Fssel_1, FN => 20); end Init; begin Init; loop Read_Line; end loop; end Main;
-- Ada regular expression library -- (c) Kristian Klomsten Skordal 2020 <kristian.skordal@wafflemail.net> -- Report bugs and issues on <https://github.com/skordal/ada-regex> with Ada.Containers.Vectors; with Ada.Finalization; with Regex.Syntax_Trees; with Regex.Utilities.Sorted_Sets; package Regex.State_Machines is -- Input symbol type: type Input_Symbol_Type is (Single_Character, Any_Character); type Input_Symbol (Symbol_Type : Input_Symbol_Type) is record case Symbol_Type is when Single_Character => Char : Character; when others => null; end case; end record; type Input_Symbol_Access is access all Input_Symbol; -- Clones an Input_Symbol object: function Clone (Object : in Input_Symbol_Access) return Input_Symbol_Access with Pre => Object /= null; -- Operators allowing Input_Symbols to be used in Sorted_Sets: function Compare_Input_Symbols (Left, Right : in Input_Symbol_Access) return Boolean; function Input_Symbol_Equals (Left, Right : in Input_Symbol_Access) return Boolean; -- State machine forward declarations: type State_Machine_State; type State_Machine_State_Access is access all State_Machine_State; -- State machine transition object: type State_Machine_Transition is new Ada.Finalization.Controlled with record Transition_On : Input_Symbol_Access; Target_State : State_Machine_State_Access; end record; function "<" (Left, Right : in State_Machine_Transition) return Boolean; function "=" (Left, Right : in State_Machine_Transition) return Boolean; function Create_Transition_On_Symbol (Input_Symbol : in Input_Symbol_Access; Target_State : in State_Machine_State_Access) return State_Machine_Transition with Pre => (Input_Symbol /= null and Target_State /= null); overriding procedure Adjust (This : in out State_Machine_Transition); overriding procedure Finalize (This : in out State_Machine_Transition); package State_Machine_Transition_Vectors is new Ada.Containers.Vectors ( Element_type => State_Machine_Transition, Index_Type => Positive); package State_Machine_Transition_Sets is new Regex.Utilities.Sorted_Sets ( Element_Type => State_Machine_Transition); -- State machine state object: type State_Machine_State is record -- Syntax tree nodes represented by this state: Syntax_Tree_Nodes : Regex.Syntax_Trees.Syntax_Tree_Node_Sets.Sorted_Set; -- Outgoing transitions from this state: Transitions : State_Machine_Transition_Vectors.Vector; -- Acceptance ID (can be used by lexer IDs to recognize different tokens): Acceptance_Id : Natural; Marked, Accepting : Boolean := False; end record; package State_Machine_State_Vectors is new Ada.Containers.Vectors ( Element_Type => State_Machine_State_Access, Index_Type => Positive); -- Creates a new, empty state machine state for a specific set of syntax tree nodes,: function Create_State (Syntax_Tree_Nodes : in Regex.Syntax_Trees.Syntax_Tree_Node_Sets.Sorted_Set) return State_Machine_State_Access; end Regex.State_Machines;
with ada.text_io, ada.Integer_text_IO, Ada.Text_IO.Text_Streams, Ada.Strings.Fixed, Interfaces.C; use ada.text_io, ada.Integer_text_IO, Ada.Strings, Ada.Strings.Fixed, Interfaces.C; procedure euler15 is type stringptr is access all char_array; procedure PString(s : stringptr) is begin String'Write (Text_Streams.Stream (Current_Output), To_Ada(s.all)); end; procedure PInt(i : in Integer) is begin String'Write (Text_Streams.Stream (Current_Output), Trim(Integer'Image(i), Left)); end; type a is Array (Integer range <>) of Integer; type a_PTR is access a; type b is Array (Integer range <>) of a_PTR; type b_PTR is access b; tab2 : a_PTR; tab : b_PTR; r : Integer; q : Integer; n : Integer; begin n := 10; -- normalement on doit mettre 20 mais là on se tape un overflow n := n + 1; tab := new b (0..n - 1); for i in integer range 0..n - 1 loop tab2 := new a (0..n - 1); for j in integer range 0..n - 1 loop tab2(j) := 0; end loop; tab(i) := tab2; end loop; for l in integer range 0..n - 1 loop tab(n - 1)(l) := 1; tab(l)(n - 1) := 1; end loop; for o in integer range 2..n loop r := n - o; for p in integer range 2..n loop q := n - p; tab(r)(q) := tab(r + 1)(q) + tab(r)(q + 1); end loop; end loop; for m in integer range 0..n - 1 loop for k in integer range 0..n - 1 loop PInt(tab(m)(k)); PString(new char_array'( To_C(" "))); end loop; PString(new char_array'( To_C("" & Character'Val(10)))); end loop; PInt(tab(0)(0)); PString(new char_array'( To_C("" & Character'Val(10)))); end;
pragma Ada_2012; package body Protypo.Api.Engine_Values.Indefinite_Vector_Wrappers is ------------------ -- Make_Wrapper -- ------------------ function Make_Wrapper (Init : Element_Vectors.Vector) return Handlers.Ambivalent_Interface_Access is Val : Engine_Value_Vectors.Vector; begin for Element of Init loop Val.Append (Create (Element)); end loop; return new Array_Wrapper'(A => Engine_Value_Array_Wrappers.Make_Wrapper (Val)); end Make_Wrapper; --------- -- Set -- --------- procedure Set (Container : in out Array_Wrapper; Index : Index_Type; Value : Element_Type) is begin Container.A.Set (Integer (Index), Create (Value)); end Set; ------------ -- Append -- ------------ procedure Append (Container : in out Array_Wrapper; Value : Element_Type) is begin Container.A.Append (Create (Value)); end Append; end Protypo.Api.Engine_Values.Indefinite_Vector_Wrappers;
-- 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. -- Some DNS records such as NS and CNAME return a common rtype format which is -- just a compressed domain name; this package handles both those cases. with DNSCatcher.DNS.Processor.Packet; use DNSCatcher.DNS.Processor.Packet; -- @description -- -- RData processor for resource records that contain a domain name -- -- @summary -- -- Several DNS record types have a common format that consists of a DNS -- compressed name that acts as a pointer to another object. These records -- include but are not limited to NS, PTR, and CName -- -- The term DNR is used within this class to represent "domain name record" or -- this type of record as a collective whole -- package DNSCatcher.DNS.Processor.RData.Domain_Name_Response_Parser is -- Class object for Domain Name Responses type Parsed_DNR_RData is new DNSCatcher.DNS.Processor.RData.Parsed_RData with private; type Parsed_DNR_RData_Access is access all Parsed_DNR_RData; -- Converts a RR record to logicial representation -- -- @value This -- Class object -- -- @value DNS_Header -- DNS Packet Header -- -- @value Parsed_RR -- DNR parsed Resource Record from Processor.Packet -- procedure From_Parsed_RR (This : in out Parsed_DNR_RData; DNS_Header : DNS_Packet_Header; Parsed_RR : Parsed_DNS_Resource_Record); -- Represents RData as a String for debug logging -- -- @value This -- Class object -- -- @returns -- The represented domain name -- function RData_To_String (This : in Parsed_DNR_RData) return String; -- Represents the resource record packet as a whole as a string -- -- @value This -- Class object -- -- @returns -- String in the format of "record_type *domain name* -- function Print_Packet (This : in Parsed_DNR_RData) return String; -- Frees and deallocates the class object -- -- @value This -- Class object to deallocate -- procedure Delete (This : in out Parsed_DNR_RData); private type Parsed_DNR_RData is new DNSCatcher.DNS.Processor.RData .Parsed_RData with record Domain_Name : Unbounded_String; end record; end DNSCatcher.DNS.Processor.RData.Domain_Name_Response_Parser;
------------------------------------------------------------------------------ -- -- -- 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.Bitmap; package HAL.Framebuffer is subtype FB_Color_Mode is HAL.Bitmap.Bitmap_Color_Mode range HAL.Bitmap.ARGB_8888 .. HAL.Bitmap.M_1; type Display_Orientation is (Default, Landscape, Portrait); type Wait_Mode is (Polling, Interrupt); type Frame_Buffer_Display is limited interface; type Any_Frame_Buffer_Display is access all Frame_Buffer_Display'Class; function Max_Layers (This : Frame_Buffer_Display) return Positive is abstract; function Supported (This : Frame_Buffer_Display; Mode : FB_Color_Mode) return Boolean is abstract; procedure Set_Orientation (This : in out Frame_Buffer_Display; Orientation : Display_Orientation) is abstract; procedure Set_Mode (This : in out Frame_Buffer_Display; Mode : Wait_Mode) is abstract; function Initialized (This : Frame_Buffer_Display) return Boolean is abstract; function Width (This : Frame_Buffer_Display) return Positive is abstract; function Height (This : Frame_Buffer_Display) return Positive is abstract; function Swapped (This : Frame_Buffer_Display) return Boolean is abstract; -- Whether X/Y coordinates are considered Swapped by the drawing primitives -- This simulates Landscape/Portrait orientation on displays not supporting -- hardware orientation change. procedure Set_Background (This : Frame_Buffer_Display; R, G, B : UInt8) is abstract; procedure Initialize_Layer (This : in out Frame_Buffer_Display; Layer : Positive; Mode : FB_Color_Mode; X : Natural := 0; Y : Natural := 0; Width : Positive := Positive'Last; Height : Positive := Positive'Last) is abstract; -- All layers are double buffered, so an explicit call to Update_Layer -- needs to be performed to actually display the current buffer attached -- to the layer. -- Alloc is called to create the actual buffer. function Initialized (This : Frame_Buffer_Display; Layer : Positive) return Boolean is abstract; procedure Update_Layer (This : in out Frame_Buffer_Display; Layer : Positive; Copy_Back : Boolean := False) is abstract; -- Updates the layer so that the hidden buffer is displayed. procedure Update_Layers (This : in out Frame_Buffer_Display) is abstract; -- Updates all initialized layers at once with their respective hidden -- buffer. function Color_Mode (This : Frame_Buffer_Display; Layer : Positive) return FB_Color_Mode is abstract; -- Retrieves the current color mode for the layer. function Hidden_Buffer (This : in out Frame_Buffer_Display; Layer : Positive) return not null HAL.Bitmap.Any_Bitmap_Buffer is abstract; -- Retrieves the current hidden buffer for the layer. function Pixel_Size (Display : Frame_Buffer_Display; Layer : Positive) return Positive is abstract; -- Retrieves the current hidden buffer for the layer. end HAL.Framebuffer;
pragma License (Unrestricted); with Ada.Numerics.Generic_Elementary_Functions; package Ada.Numerics.Long_Long_Elementary_Functions is new Generic_Elementary_Functions (Long_Long_Float); pragma Pure (Ada.Numerics.Long_Long_Elementary_Functions);
-- TCTouch.A -- -- 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. --* -- -- FOUNDATION DESCRIPTION: -- The tools in this foundation are not peculiar to any particular -- aspect of the language, but simplify the test writing and reading -- process. Assert and Assert_Not are used to reduce the textual -- overhead of the test-that-this-condition-is-(not)-true paradigm. -- Touch and Validate are used to simplify tracing an expected path -- of execution. -- A tag comment of the form: -- -- TCTouch.Touch( 'A' ); ----------------------------------------- A -- -- is recommended to improve readability of this feature. -- -- Report.Test must be called before any of the procedures in this -- package with the exception of Touch. -- The usage paradigm is to call Touch in locations in the test where you -- want a trace of execution. Each call to Touch should have a unique -- character associated with it. At each place where a check can -- reasonably be performed to determine correct execution of a -- sub-test, a call to Validate should be made. The first parameter -- passed to Validate is the expected string of characters produced by -- call(s) to Touch in the subtest just executed. The second parameter -- is the message to pass to Report.Failed if the expected sequence was -- not executed. -- -- Validate should always be called after calls to Touch before a test -- completes. -- -- In the event that calls may have been made to Touch that are not -- intended to be recorded, or, the failure of a previous subtest may -- leave Touch calls "Unvalidated", the procedure Flush will reset the -- tracker to the "empty" state. Flush does not make any calls to -- Report. -- -- Calls to Assert and Assert_Not are to replace the idiom: -- -- if BadCondition then -- or if not PositiveTest then -- Report.Failed(Message); -- end if; -- -- with: -- -- Assert_Not( BadCondition, Message ); -- or -- Assert( PositiveTest, Message ); -- -- Implementation_Check is for use with tests that cross the boundary -- between the core and the Special Needs Annexes. There are several -- instances where language in the core becomes enforceable only when -- a Special Needs Annex is supported. Implementation_Check should be -- called in place of Report.Failed in these cases; it examines the -- constants in Impdef that indicate if the particular Special Needs -- Annex is being validated with this validation; and acts accordingly. -- -- The constant Foundation_ID contains the internal change version -- for this software. -- -- ERROR CONDITIONS: -- -- It is an error to perform more than Max_Touch_Count (80) calls to -- Touch without a subsequent call to Validate. To do so will cause -- a false test failure. -- -- CHANGE HISTORY: -- 02 JUN 94 SAIC Initial version -- 27 OCT 94 SAIC Revised version -- 07 AUG 95 SAIC Added Implementation_Check -- 07 FEB 96 SAIC Changed to match new Impdef for 2.1 -- 16 MAR 00 RLB Changed foundation id to reflect test suite version. -- 22 MAR 01 RLB Changed foundation id to reflect test suite version. -- 29 MAR 02 RLB Changed foundation id to reflect test suite version. -- --! package TCTouch is Foundation_ID : constant String := "TCTouch ACATS 2.5"; Max_Touch_Count : constant := 80; procedure Assert ( SB_True : Boolean; Message : String ); procedure Assert_Not( SB_False : Boolean; Message : String ); procedure Touch ( A_Tag : Character ); procedure Validate( Expected: String; Message : String; Order_Meaningful : Boolean := True ); procedure Flush; type Special_Needs_Annexes is ( Annex_C, Annex_D, Annex_E, Annex_F, Annex_G, Annex_H ); procedure Implementation_Check( Message : in String; Annex : in Special_Needs_Annexes := Annex_C ); -- If Impdef.Validating_Annex_<Annex> is true, will call Report.Failed -- otherwise will call Report.Not_Applicable. This is to allow tests -- which are driven by wording in the core of the language, yet have -- their functionality dictated by the Special Needs Annexes to perform -- dual purpose. -- The default of Annex_C for the Annex parameter is to support early -- tests written with the assumption that Implementation_Check was -- expressly for use with the Systems Programming Annex. end TCTouch; with Report; with Impdef; package body TCTouch is procedure Assert( SB_True : Boolean; Message : String ) is begin if not SB_True then Report.Failed( "Assertion failed: " & Message ); end if; end Assert; procedure Assert_Not( SB_False : Boolean; Message : String ) is begin if SB_False then Report.Failed( "Assertion failed: " & Message ); end if; end Assert_Not; Collection : String(1..Max_Touch_Count); Finger : Natural := 0; procedure Touch ( A_Tag : Character ) is begin Finger := Finger+1; Collection(Finger) := A_Tag; exception when Constraint_Error => Report.Failed("Trace Overflow: " & Collection); Finger := 0; end Touch; procedure Sort_String( S: in out String ) is -- algorithm from Booch Components Page 472 No_Swaps : Boolean; procedure Swap(C1, C2: in out Character) is T: Character := C1; begin C1 := C2; C2 := T; end Swap; begin for OI in S'First+1..S'Last loop No_Swaps := True; for II in reverse OI..S'Last loop if S(II) < S(II-1) then Swap(S(II),S(II-1)); No_Swaps := False; end if; end loop; exit when No_Swaps; end loop; end Sort_String; procedure Validate( Expected: String; Message : String; Order_Meaningful : Boolean := True) is Want : String(1..Expected'Length) := Expected; begin if not Order_Meaningful then Sort_String( Want ); Sort_String( Collection(1..Finger) ); end if; if Collection(1..Finger) /= Want then Report.Failed( Message & " Expecting: " & Want & " Got: " & Collection(1..Finger) ); end if; Finger := 0; end Validate; procedure Flush is begin Finger := 0; end Flush; procedure Implementation_Check( Message : in String; Annex : in Special_Needs_Annexes := Annex_C ) is -- default to cover some legacy -- USAGE DISCIPLINE: -- Implementation_Check is designed to be used in tests that have -- interdependency on one of the Special Needs Annexes, yet are _really_ -- tests based in the core language. There will be instances where the -- execution of a test would be failing in the light of the requirements -- of the annex, yet from the point of view of the core language without -- the additional requirements of the annex, the test does not apply. -- In these cases, rather than issuing a call to Report.Failed, calling -- TCTouch.Implementation_Check will check that sensitivity, and if -- the implementation is attempting to validate against the specific -- annex, Report.Failed will be called, otherwise, Report.Not_Applicable -- will be called. begin case Annex is when Annex_C => if ImpDef.Validating_Annex_C then Report.Failed( Message ); else Report.Not_Applicable( Message & " Annex C not supported" ); end if; when Annex_D => if ImpDef.Validating_Annex_D then Report.Failed( Message ); else Report.Not_Applicable( Message & " Annex D not supported" ); end if; when Annex_E => if ImpDef.Validating_Annex_E then Report.Failed( Message ); else Report.Not_Applicable( Message & " Annex E not supported" ); end if; when Annex_F => if ImpDef.Validating_Annex_F then Report.Failed( Message ); else Report.Not_Applicable( Message & " Annex F not supported" ); end if; when Annex_G => if ImpDef.Validating_Annex_G then Report.Failed( Message ); else Report.Not_Applicable( Message & " Annex G not supported" ); end if; when Annex_H => if ImpDef.Validating_Annex_H then Report.Failed( Message ); else Report.Not_Applicable( Message & " Annex H not supported" ); end if; end case; end Implementation_Check; end TCTouch;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- B I N D O . W R I T E R S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2019-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. -- -- -- ------------------------------------------------------------------------------ -- For full architecture, see unit Bindo. -- The following unit contains facilities to output the various graphs used in -- determining the elaboration order, as well as the elaboration order itself -- to standard output. with Types; use Types; with Bindo.Graphs; use Bindo.Graphs; use Bindo.Graphs.Invocation_Graphs; use Bindo.Graphs.Library_Graphs; package Bindo.Writers is ----------------- -- Indentation -- ----------------- -- The following type defines the level of indentation used in various -- output routines. type Indentation_Level is new Natural; No_Indentation : constant Indentation_Level := Indentation_Level'First; Nested_Indentation : constant Indentation_Level := 2; -- The level of indentation for a nested new line Number_Column : constant Indentation_Level := 6; -- The level of right justification of numbers Step_Column : constant Indentation_Level := 4; -- The level of right justification of the elaboration order step procedure Indent_By (Indent : Indentation_Level); pragma Inline (Indent_By); -- Indent the current line by Indent spaces procedure Write_Num (Val : Int; Val_Indent : Indentation_Level := Number_Column); pragma Inline (Write_Num); -- Output integer value Val in a right-justified form based on the value of -- Val_Col. ----------------- -- ALI_Writers -- ----------------- package ALI_Writers is procedure Write_ALI_Tables; -- Write the contents of the following tables to standard output: -- -- * ALI.Invocation_Constructs -- * ALI.Invocation_Relations end ALI_Writers; ------------------- -- Cycle_Writers -- ------------------- package Cycle_Writers is procedure Write_Cycles (G : Library_Graph); -- Write all cycles of library graph G to standard output end Cycle_Writers; ------------------------ -- Dependency_Writers -- ------------------------ package Dependency_Writers is procedure Write_Dependencies (G : Library_Graph); -- Write all elaboration dependencies of the units represented by -- vertices of library graph G. end Dependency_Writers; ------------------------------- -- Elaboration_Order_Writers -- ------------------------------- package Elaboration_Order_Writers is procedure Write_Elaboration_Order (Order : Unit_Id_Table); -- Write elaboration order Order to standard output end Elaboration_Order_Writers; ------------------------------ -- Invocation_Graph_Writers -- ------------------------------ package Invocation_Graph_Writers is procedure Write_Invocation_Graph (G : Invocation_Graph); -- Write invocation graph G to standard output end Invocation_Graph_Writers; --------------------------- -- Library_Graph_Writers -- --------------------------- package Library_Graph_Writers is procedure Write_Library_Graph (G : Library_Graph); -- Write library graph G to standard output end Library_Graph_Writers; ------------------- -- Phase_Writers -- ------------------- package Phase_Writers is procedure End_Phase (Phase : Elaboration_Phase); pragma Inline (End_Phase); -- Write the end message associated with elaboration phase Phase to -- standard output. procedure Start_Phase (Phase : Elaboration_Phase); pragma Inline (Start_Phase); -- Write the start message associated with elaboration phase Phase to -- standard output. end Phase_Writers; -------------------------- -- Unit_Closure_Writers -- -------------------------- package Unit_Closure_Writers is procedure Write_Unit_Closure (Order : Unit_Id_Table); -- Write all sources in the closure of the main unit as enumerated in -- elaboration order Order. end Unit_Closure_Writers; end Bindo.Writers;
----------------------------------------------------------------------- -- search-positions -- Token positions -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; package body Search.Positions is use Ada.Streams; use type Interfaces.Unsigned_64; function LEB_Length (Value : in Interfaces.Unsigned_64) return Stream_Element_Offset; ALIGN_SIZE : constant Stream_Element_Offset := 16; SIZE_INCREMENT : constant Stream_Element_Offset := 16; function Next_Length (Size : in Stream_Element_Size) return Stream_Element_Size is (Size + (Size / 4) + SIZE_INCREMENT); function Align_Length (Size : in Stream_Element_Size) return Stream_Element_Size is (((Size + ALIGN_SIZE - 1) / ALIGN_SIZE) * ALIGN_SIZE); procedure Allocate (Positions : in out Position_Type; Length : in Stream_Element_Size) is R : Position_Refs.Ref; begin R := Position_Refs.Create (new Position_Content_Type '(Util.Refs.Ref_Entity with Length => Length, Size => 0, Last => 0, others => <>)); Positions := Position_Type '(R with others => <>); end Allocate; -- ------------------------------ -- Initialize the positions with the data stream. -- ------------------------------ procedure Initialize (Positions : in out Position_Type; Data : in Ada.Streams.Stream_Element_Array) is Len : constant Stream_Element_Size := Align_Length (Data'Length); R : Position_Refs.Ref; begin R := Position_Refs.Create (new Position_Content_Type '(Util.Refs.Ref_Entity with Length => Len, Size => Data'Length, others => <>)); Positions := Position_Type '(R with others => <>); end Initialize; -- ------------------------------ -- Get the last recorded position. -- ------------------------------ function Last (Positions : in Position_Type) return Natural is begin if Positions.Is_Null then return 0; else return Positions.Value.Last; end if; end Last; function LEB_Length (Value : in Interfaces.Unsigned_64) return Stream_Element_Offset is begin -- 7f 1 -- 03fff 2 -- 1fffff 3 -- fffffff 4 -- 7 ffffffff 5 -- 3ff ffffffff 6 -- 1ffff ffffffff 7 -- ffffff ffffffff 8 -- 7fffffff ffffffff 9 -- ffffffff ffffffff 10 if Value < 16#7f# then return 1; elsif Value < 16#3fff# then return 2; elsif Value < 16#1fffff# then return 3; elsif Value < 16#fffffff# then return 4; else return 10; end if; end LEB_Length; -- ------------------------------ -- Add the position to the list of positions. -- ------------------------------ procedure Add (Positions : in out Position_Type; Value : in Natural) is V : Interfaces.Unsigned_64; begin if Positions.Is_Null then Allocate (Positions, ALIGN_SIZE); V := Interfaces.Unsigned_64 (Value); else declare Item : constant Position_Refs.Element_Accessor := Positions.Value; begin V := Interfaces.Unsigned_64 (Value - Item.Last); if Item.Size + LEB_Length (V) >= Item.Length then declare Length : constant Stream_Element_Offset := Next_Length (Item.Length); R : Position_Refs.Ref; begin R := Position_Refs.Create (new Position_Content_Type '(Util.Refs.Ref_Entity with Length => Length, Size => Item.Size, Last => Item.Last, others => <>)); R.Value.Data (1 .. Item.Size) := Item.Data (1 .. Item.Size); Positions := Position_Type '(R with others => <>); end; end if; end; end if; declare Item : constant Position_Refs.Element_Accessor := Positions.Value; P : Ada.Streams.Stream_Element_Offset := Item.Size + 1; U : Interfaces.Unsigned_64; begin Item.Last := Value; loop if V < 16#07F# then Item.Data (P) := Ada.Streams.Stream_Element (V); Item.Size := P; return; end if; U := V and 16#07F#; Item.Data (P) := Ada.Streams.Stream_Element (U or 16#80#); P := P + 1; V := Interfaces.Shift_Right (V, 7); end loop; end; end Add; -- ------------------------------ -- Give access to the packed array representing the collected positions. -- ------------------------------ procedure Pack (Positions : in Position_Type; Process : not null access procedure (Data : in Ada.Streams.Stream_Element_Array)) is begin Process (Positions.Value.Data (1 .. Positions.Value.Size)); end Pack; -- ------------------------------ -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. -- ------------------------------ procedure Write_LEB128 (Stream : access Ada.Streams.Root_Stream_Type'Class; Val : in Interfaces.Unsigned_64) is V, U : Interfaces.Unsigned_64; begin V := Val; loop if V < 16#07F# then Ada.Streams.Stream_Element'Write (Stream, Ada.Streams.Stream_Element (V)); return; end if; U := V and 16#07F#; Ada.Streams.Stream_Element'Write (Stream, Ada.Streams.Stream_Element (U or 16#80#)); V := Interfaces.Shift_Right (V, 7); end loop; end Write_LEB128; -- ------------------------------ -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. -- ------------------------------ function Read_LEB128 (Stream : access Ada.Streams.Root_Stream_Type'Class) return Interfaces.Unsigned_64 is use type Interfaces.Unsigned_8; Value : Interfaces.Unsigned_64 := 0; V : Interfaces.Unsigned_8; Shift : Integer := 0; begin loop V := Interfaces.Unsigned_8'Input (Stream); if (V and 16#80#) = 0 then return Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; end if; V := V and 16#07F#; Value := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; Shift := Shift + 7; end loop; end Read_LEB128; -- ------------------------------ -- Write the list of positions in the stream. -- ------------------------------ procedure Write (Stream : access Ada.Streams.Root_Stream_Type'Class; Positions : in Position_Type) is begin if Positions.Is_Null then Write_LEB128 (Stream, 0); else declare Value : constant Position_Refs.Element_Accessor := Positions.Value; begin Write_LEB128 (Stream, Interfaces.Unsigned_64 (Value.Size)); Write_LEB128 (Stream, Interfaces.Unsigned_64 (Value.Last)); Stream.Write (Value.Data (1 .. Value.Size)); end; end if; end Write; -- ------------------------------ -- Read a list of positions from the stream. -- ------------------------------ function Read (Stream : access Ada.Streams.Root_Stream_Type'Class) return Position_Type is Size : constant Stream_Element_Size := Stream_Element_Size (Read_LEB128 (Stream)); Result : Position_Type; begin if Size > 0 then declare Length : constant Stream_Element_Size := Align_Length (Size); Last : constant Natural := Natural (Read_LEB128 (Stream)); Pos : Ada.Streams.Stream_Element_Offset; R : Position_Refs.Ref; begin R := Position_Refs.Create (new Position_Content_Type '(Util.Refs.Ref_Entity with Length => Length, Size => Size, Last => Last, others => <>)); Stream.Read (R.Value.Data (1 .. Size), Pos); Result := Position_Type '(R with others => <>); end; end if; return Result; end Read; end Search.Positions;