content
stringlengths
23
1.05M
with Ada.Text_IO; procedure Octal is package IIO is new Ada.Text_IO.Integer_IO(Integer); begin for I in 0 .. Integer'Last loop IIO.Put(I, Base => 8); Ada.Text_IO.New_Line; end loop; end Octal;
----------------------------------------------------------------------- -- druss-commands-bboxes -- Commands to manage the bboxes -- Copyright (C) 2017, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Properties; with Util.Strings; with Util.Strings.Sets; with Bbox.API; with Druss.Gateways; with Druss.Config; with UPnP.SSDP; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes"); -- ------------------------------ -- Add the bbox with the given IP address. -- ------------------------------ procedure Add_Bbox (Command : in Command_Type; IP : in String; Context : in out Context_Type) is pragma Unreferenced (Command); Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; Gw : Druss.Gateways.Gateway_Ref := Druss.Gateways.Find_IP (Context.Gateways, IP); begin if not Gw.Is_Null then Log.Debug ("Bbox {0} is already registered", IP); return; end if; Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Context.Console.Notice (N_INFO, "Found a new bbox at " & IP); Gw := Druss.Gateways.Gateway_Refs.Create; Gw.Value.Ip := Ada.Strings.Unbounded.To_Unbounded_String (IP); Context.Gateways.Append (Gw); end if; exception when others => Log.Debug ("Ignoring IP {0} because some exception happened", IP); end Add_Bbox; procedure Discover (Command : in Command_Type; Context : in out Context_Type) is procedure Process (URI : in String); Retry : Natural := 0; Scanner : UPnP.SSDP.Scanner_Type; Itf_IPs : Util.Strings.Sets.Set; procedure Process (URI : in String) is Pos : Natural; begin if URI'Length <= 7 or else URI (URI'First .. URI'First + 6) /= "http://" then return; end if; Pos := Util.Strings.Index (URI, ':', 6); if Pos > 0 then Command.Add_Bbox (URI (URI'First + 7 .. Pos - 1), Context); end if; end Process; begin Log.Info ("Discovering gateways on the network"); Scanner.Initialize; Scanner.Find_IPv4_Addresses (Itf_IPs); while Retry < 5 loop Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs); Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Process'Access, 1.0); Retry := Retry + 1; end loop; Druss.Config.Save_Gateways (Context.Gateways); end Discover; -- ------------------------------ -- Set the password to be used by the Bbox API to connect to the box. -- ------------------------------ procedure Do_Password (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type; Passwd : in String); procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type; Passwd : in String) is begin Gateway.Passwd := Ada.Strings.Unbounded.To_Unbounded_String (Passwd); end Change_Password; begin Druss.Commands.Gateway_Command (Command, Args, 2, Change_Password'Access, Context); Druss.Config.Save_Gateways (Context.Gateways); end Do_Password; -- ------------------------------ -- Enable or disable the bbox management by Druss. -- ------------------------------ procedure Do_Enable (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is procedure Change_Enable (Gateway : in out Druss.Gateways.Gateway_Type; Command : in String); procedure Change_Enable (Gateway : in out Druss.Gateways.Gateway_Type; Command : in String) is begin Gateway.Enable := Command = "enable"; end Change_Enable; begin Druss.Commands.Gateway_Command (Command, Args, 1, Change_Enable'Access, Context); Druss.Config.Save_Gateways (Context.Gateways); end Do_Enable; -- ------------------------------ -- Execute the command with the arguments. The command name is passed with the command -- arguments. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args, Context); elsif Args.Get_Argument (1) = "discover" then Command.Discover (Context); elsif Args.Get_Argument (1) = "password" then Command.Do_Password (Args, Context); elsif Args.Get_Argument (1) in "enable" | "disable" then Command.Do_Enable (Args, Context); else Context.Console.Notice (N_USAGE, "Invalid sub-command: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args, Context); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "bbox: Manage and define the configuration to connect to the Bbox"); Console.Notice (N_HELP, "Usage: bbox <operation>..."); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " Druss needs to know the list of Bboxes which are available" & " on the network."); Console.Notice (N_HELP, " It also need some credentials to connect to the Bbox using" & " the Bbox API."); Console.Notice (N_HELP, " The 'bbox' command allows to manage that list and configuration."); Console.Notice (N_HELP, " Examples:"); Console.Notice (N_HELP, " bbox discover Discover the bbox(es) connected to the LAN"); Console.Notice (N_HELP, " bbox add IP Add a bbox knowing its IP address"); Console.Notice (N_HELP, " bbox del IP Delete a bbox from the list"); Console.Notice (N_HELP, " bbox enable IP Enable the bbox (it will be used by Druss)"); Console.Notice (N_HELP, " bbox disable IP Disable the bbox (it will not be managed)"); Console.Notice (N_HELP, " bbox password <pass> [IP] Set the bbox API connection password"); end Help; end Druss.Commands.Bboxes;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- O P T -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2015, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Gnatvsn; use Gnatvsn; with System; use System; with Tree_IO; use Tree_IO; package body Opt is SU : constant := Storage_Unit; -- Shorthand for System.Storage_Unit ---------------------------------- -- Register_Opt_Config_Switches -- ---------------------------------- procedure Register_Opt_Config_Switches is begin Ada_Version_Config := Ada_Version; Ada_Version_Pragma_Config := Ada_Version_Pragma; Ada_Version_Explicit_Config := Ada_Version_Explicit; Assertions_Enabled_Config := Assertions_Enabled; Assume_No_Invalid_Values_Config := Assume_No_Invalid_Values; Check_Float_Overflow_Config := Check_Float_Overflow; Check_Policy_List_Config := Check_Policy_List; Default_Pool_Config := Default_Pool; Default_SSO_Config := Default_SSO; Dynamic_Elaboration_Checks_Config := Dynamic_Elaboration_Checks; Exception_Locations_Suppressed_Config := Exception_Locations_Suppressed; Extensions_Allowed_Config := Extensions_Allowed; External_Name_Exp_Casing_Config := External_Name_Exp_Casing; External_Name_Imp_Casing_Config := External_Name_Imp_Casing; Fast_Math_Config := Fast_Math; Initialize_Scalars_Config := Initialize_Scalars; Optimize_Alignment_Config := Optimize_Alignment; Persistent_BSS_Mode_Config := Persistent_BSS_Mode; Polling_Required_Config := Polling_Required; Prefix_Exception_Messages_Config := Prefix_Exception_Messages; SPARK_Mode_Config := SPARK_Mode; SPARK_Mode_Pragma_Config := SPARK_Mode_Pragma; Uneval_Old_Config := Uneval_Old; Use_VADS_Size_Config := Use_VADS_Size; Warnings_As_Errors_Count_Config := Warnings_As_Errors_Count; -- Reset the indication that Optimize_Alignment was set locally, since -- if we had a pragma in the config file, it would set this flag True, -- but that's not a local setting. Optimize_Alignment_Local := False; end Register_Opt_Config_Switches; --------------------------------- -- Restore_Opt_Config_Switches -- --------------------------------- procedure Restore_Opt_Config_Switches (Save : Config_Switches_Type) is begin Ada_Version := Save.Ada_Version; Ada_Version_Pragma := Save.Ada_Version_Pragma; Ada_Version_Explicit := Save.Ada_Version_Explicit; Assertions_Enabled := Save.Assertions_Enabled; Assume_No_Invalid_Values := Save.Assume_No_Invalid_Values; Check_Float_Overflow := Save.Check_Float_Overflow; Check_Policy_List := Save.Check_Policy_List; Default_Pool := Save.Default_Pool; Default_SSO := Save.Default_SSO; Dynamic_Elaboration_Checks := Save.Dynamic_Elaboration_Checks; Exception_Locations_Suppressed := Save.Exception_Locations_Suppressed; Extensions_Allowed := Save.Extensions_Allowed; External_Name_Exp_Casing := Save.External_Name_Exp_Casing; External_Name_Imp_Casing := Save.External_Name_Imp_Casing; Fast_Math := Save.Fast_Math; Initialize_Scalars := Save.Initialize_Scalars; Optimize_Alignment := Save.Optimize_Alignment; Optimize_Alignment_Local := Save.Optimize_Alignment_Local; Persistent_BSS_Mode := Save.Persistent_BSS_Mode; Polling_Required := Save.Polling_Required; Prefix_Exception_Messages := Save.Prefix_Exception_Messages; SPARK_Mode := Save.SPARK_Mode; SPARK_Mode_Pragma := Save.SPARK_Mode_Pragma; Uneval_Old := Save.Uneval_Old; Use_VADS_Size := Save.Use_VADS_Size; Warnings_As_Errors_Count := Save.Warnings_As_Errors_Count; -- Update consistently the value of Init_Or_Norm_Scalars. The value of -- Normalize_Scalars is not saved/restored because after set to True its -- value is never changed. That is, if a compilation unit has pragma -- Normalize_Scalars then it forces that value for all with'ed units. Init_Or_Norm_Scalars := Initialize_Scalars or Normalize_Scalars; end Restore_Opt_Config_Switches; ------------------------------ -- Save_Opt_Config_Switches -- ------------------------------ procedure Save_Opt_Config_Switches (Save : out Config_Switches_Type) is begin Save.Ada_Version := Ada_Version; Save.Ada_Version_Pragma := Ada_Version_Pragma; Save.Ada_Version_Explicit := Ada_Version_Explicit; Save.Assertions_Enabled := Assertions_Enabled; Save.Assume_No_Invalid_Values := Assume_No_Invalid_Values; Save.Check_Float_Overflow := Check_Float_Overflow; Save.Check_Policy_List := Check_Policy_List; Save.Default_Pool := Default_Pool; Save.Default_SSO := Default_SSO; Save.Dynamic_Elaboration_Checks := Dynamic_Elaboration_Checks; Save.Exception_Locations_Suppressed := Exception_Locations_Suppressed; Save.Extensions_Allowed := Extensions_Allowed; Save.External_Name_Exp_Casing := External_Name_Exp_Casing; Save.External_Name_Imp_Casing := External_Name_Imp_Casing; Save.Fast_Math := Fast_Math; Save.Initialize_Scalars := Initialize_Scalars; Save.Optimize_Alignment := Optimize_Alignment; Save.Optimize_Alignment_Local := Optimize_Alignment_Local; Save.Persistent_BSS_Mode := Persistent_BSS_Mode; Save.Polling_Required := Polling_Required; Save.Prefix_Exception_Messages := Prefix_Exception_Messages; Save.SPARK_Mode := SPARK_Mode; Save.SPARK_Mode_Pragma := SPARK_Mode_Pragma; Save.Uneval_Old := Uneval_Old; Save.Use_VADS_Size := Use_VADS_Size; Save.Warnings_As_Errors_Count := Warnings_As_Errors_Count; end Save_Opt_Config_Switches; ----------------------------- -- Set_Opt_Config_Switches -- ----------------------------- procedure Set_Opt_Config_Switches (Internal_Unit : Boolean; Main_Unit : Boolean) is begin -- Case of internal unit if Internal_Unit then -- Set standard switches. Note we do NOT set Ada_Version_Explicit -- since the whole point of this is that it still properly indicates -- the configuration setting even in a run time unit. Ada_Version := Ada_Version_Runtime; Ada_Version_Pragma := Empty; Default_SSO := ' '; Dynamic_Elaboration_Checks := False; Extensions_Allowed := True; External_Name_Exp_Casing := As_Is; External_Name_Imp_Casing := Lowercase; Optimize_Alignment := 'O'; Persistent_BSS_Mode := False; Prefix_Exception_Messages := True; Uneval_Old := 'E'; Use_VADS_Size := False; Optimize_Alignment_Local := True; -- Note: we do not need to worry about Warnings_As_Errors_Count since -- we do not expect to get any warnings from compiling such a unit. -- For an internal unit, assertions/debug pragmas are off unless this -- is the main unit and they were explicitly enabled, or unless the -- main unit was compiled in GNAT mode. We also make sure we do not -- assume that values are necessarily valid and that SPARK_Mode is -- set to its configuration value. if Main_Unit then Assertions_Enabled := Assertions_Enabled_Config; Assume_No_Invalid_Values := Assume_No_Invalid_Values_Config; Check_Policy_List := Check_Policy_List_Config; SPARK_Mode := SPARK_Mode_Config; SPARK_Mode_Pragma := SPARK_Mode_Pragma_Config; else if GNAT_Mode_Config then Assertions_Enabled := Assertions_Enabled_Config; else Assertions_Enabled := False; end if; Assume_No_Invalid_Values := False; Check_Policy_List := Empty; SPARK_Mode := None; SPARK_Mode_Pragma := Empty; end if; -- Case of non-internal unit else Ada_Version := Ada_Version_Config; Ada_Version_Pragma := Ada_Version_Pragma_Config; Ada_Version_Explicit := Ada_Version_Explicit_Config; Assertions_Enabled := Assertions_Enabled_Config; Assume_No_Invalid_Values := Assume_No_Invalid_Values_Config; Check_Float_Overflow := Check_Float_Overflow_Config; Check_Policy_List := Check_Policy_List_Config; Default_SSO := Default_SSO_Config; Dynamic_Elaboration_Checks := Dynamic_Elaboration_Checks_Config; Extensions_Allowed := Extensions_Allowed_Config; External_Name_Exp_Casing := External_Name_Exp_Casing_Config; External_Name_Imp_Casing := External_Name_Imp_Casing_Config; Fast_Math := Fast_Math_Config; Initialize_Scalars := Initialize_Scalars_Config; Optimize_Alignment := Optimize_Alignment_Config; Optimize_Alignment_Local := False; Persistent_BSS_Mode := Persistent_BSS_Mode_Config; Prefix_Exception_Messages := Prefix_Exception_Messages_Config; SPARK_Mode := SPARK_Mode_Config; SPARK_Mode_Pragma := SPARK_Mode_Pragma_Config; Uneval_Old := Uneval_Old_Config; Use_VADS_Size := Use_VADS_Size_Config; Warnings_As_Errors_Count := Warnings_As_Errors_Count_Config; -- Update consistently the value of Init_Or_Norm_Scalars. The value -- of Normalize_Scalars is not saved/restored because once set to -- True its value is never changed. That is, if a compilation unit -- has pragma Normalize_Scalars then it forces that value for all -- with'ed units. Init_Or_Norm_Scalars := Initialize_Scalars or Normalize_Scalars; end if; -- Values set for all units Default_Pool := Default_Pool_Config; Exception_Locations_Suppressed := Exception_Locations_Suppressed_Config; Fast_Math := Fast_Math_Config; Optimize_Alignment := Optimize_Alignment_Config; Polling_Required := Polling_Required_Config; end Set_Opt_Config_Switches; --------------- -- Tree_Read -- --------------- procedure Tree_Read is Tree_Version_String_Len : Nat; Ada_Version_Config_Val : Nat; Ada_Version_Explicit_Config_Val : Nat; Assertions_Enabled_Config_Val : Nat; begin Tree_Read_Int (Tree_ASIS_Version_Number); Tree_Read_Bool (Address_Is_Private); Tree_Read_Bool (Brief_Output); Tree_Read_Bool (GNAT_Mode); Tree_Read_Char (Identifier_Character_Set); Tree_Read_Bool (Ignore_Rep_Clauses); Tree_Read_Bool (Ignore_Style_Checks_Pragmas); Tree_Read_Int (Maximum_File_Name_Length); Tree_Read_Data (Suppress_Options'Address, (Suppress_Options'Size + SU - 1) / SU); Tree_Read_Bool (Verbose_Mode); Tree_Read_Data (Warning_Mode'Address, (Warning_Mode'Size + SU - 1) / SU); Tree_Read_Int (Ada_Version_Config_Val); Tree_Read_Int (Ada_Version_Explicit_Config_Val); Tree_Read_Int (Assertions_Enabled_Config_Val); Tree_Read_Bool (All_Errors_Mode); Tree_Read_Bool (Assertions_Enabled); Tree_Read_Bool (Check_Float_Overflow); Tree_Read_Int (Int (Check_Policy_List)); Tree_Read_Int (Int (Default_Pool)); Tree_Read_Bool (Full_List); Ada_Version_Config := Ada_Version_Type'Val (Ada_Version_Config_Val); Ada_Version_Explicit_Config := Ada_Version_Type'Val (Ada_Version_Explicit_Config_Val); Assertions_Enabled_Config := Boolean'Val (Assertions_Enabled_Config_Val); -- Read version string: we have to get the length first Tree_Read_Int (Tree_Version_String_Len); declare Tmp : String (1 .. Integer (Tree_Version_String_Len)); begin Tree_Read_Data (Tmp'Address, Tree_Version_String_Len); System.Strings.Free (Tree_Version_String); Free (Tree_Version_String); Tree_Version_String := new String'(Tmp); end; Tree_Read_Data (Distribution_Stub_Mode'Address, (Distribution_Stub_Mode'Size + SU - 1) / Storage_Unit); Tree_Read_Bool (Inline_Active); Tree_Read_Bool (Inline_Processing_Required); Tree_Read_Bool (List_Units); Tree_Read_Int (Multiple_Unit_Index); Tree_Read_Bool (Configurable_Run_Time_Mode); Tree_Read_Data (Operating_Mode'Address, (Operating_Mode'Size + SU - 1) / Storage_Unit); Tree_Read_Bool (Suppress_Checks); Tree_Read_Bool (Try_Semantics); Tree_Read_Data (Wide_Character_Encoding_Method'Address, (Wide_Character_Encoding_Method'Size + SU - 1) / SU); Tree_Read_Bool (Upper_Half_Encoding); Tree_Read_Bool (Force_ALI_Tree_File); end Tree_Read; ---------------- -- Tree_Write -- ---------------- procedure Tree_Write is Version_String : String := Gnat_Version_String; begin Tree_Write_Int (ASIS_Version_Number); Tree_Write_Bool (Address_Is_Private); Tree_Write_Bool (Brief_Output); Tree_Write_Bool (GNAT_Mode); Tree_Write_Char (Identifier_Character_Set); Tree_Write_Bool (Ignore_Rep_Clauses); Tree_Write_Bool (Ignore_Style_Checks_Pragmas); Tree_Write_Int (Maximum_File_Name_Length); Tree_Write_Data (Suppress_Options'Address, (Suppress_Options'Size + SU - 1) / SU); Tree_Write_Bool (Verbose_Mode); Tree_Write_Data (Warning_Mode'Address, (Warning_Mode'Size + SU - 1) / Storage_Unit); Tree_Write_Int (Ada_Version_Type'Pos (Ada_Version_Config)); Tree_Write_Int (Ada_Version_Type'Pos (Ada_Version_Explicit_Config)); Tree_Write_Int (Boolean'Pos (Assertions_Enabled_Config)); Tree_Write_Bool (All_Errors_Mode); Tree_Write_Bool (Assertions_Enabled); Tree_Write_Bool (Check_Float_Overflow); Tree_Write_Int (Int (Check_Policy_List)); Tree_Write_Int (Int (Default_Pool)); Tree_Write_Bool (Full_List); Tree_Write_Int (Int (Version_String'Length)); Tree_Write_Data (Version_String'Address, Version_String'Length); Tree_Write_Data (Distribution_Stub_Mode'Address, (Distribution_Stub_Mode'Size + SU - 1) / SU); Tree_Write_Bool (Inline_Active); Tree_Write_Bool (Inline_Processing_Required); Tree_Write_Bool (List_Units); Tree_Write_Int (Multiple_Unit_Index); Tree_Write_Bool (Configurable_Run_Time_Mode); Tree_Write_Data (Operating_Mode'Address, (Operating_Mode'Size + SU - 1) / SU); Tree_Write_Bool (Suppress_Checks); Tree_Write_Bool (Try_Semantics); Tree_Write_Data (Wide_Character_Encoding_Method'Address, (Wide_Character_Encoding_Method'Size + SU - 1) / SU); Tree_Write_Bool (Upper_Half_Encoding); Tree_Write_Bool (Force_ALI_Tree_File); end Tree_Write; end Opt;
-- As input events occur, we just keep them here. Then as a window -- is notified of something, if it's a Troodon app, we will wake it -- up and it can pull whatever inputs it wants. package Events.Inputs is type InputEvent is (MOUSEMOVEMENT, BUTTONDOWN, BUTTONUP, KEYDOWN, KEYUP, QUIT); end Events.Inputs;
generic Capacite : integer; package Arbre_Foret is type T_Abr_Foret is private; type T_Tableau is private; Capacite_Tableau_Compagnon_Maximale : Exception; Compagnon_Existe : Exception; Epoux_Existe : Exception; Pere_Existe : Exception; Mere_Existe : Exception; Cle_Absente : Exception; procedure Initialiser(Abr : out T_Abr_Foret) with Post => Vide(Abr); function Vide (Abr : in T_Abr_Foret) return Boolean; procedure Creer_Minimal (Abr : out T_Abr_Foret; Cle : in integer) with Post => not Vide(Abr); Procedure Ajouter_Pere ( Abr : in out T_Abr_Foret ; Cle : in integer; Cle_Pere : in integer); Procedure Ajouter_Mere ( Abr : in out T_Abr_Foret ; Cle : in integer ; Cle_Mere : in integer); procedure Ajouter_Epoux ( Abr : in out T_Abr_Foret ; Cle : in integer; Cle_Epoux : in integer); procedure Ajouter_Compagnon ( Abr : in out T_Abr_Foret ; Cle : in integer; Cle_Compagnon : in integer); function Existe ( Abr : in T_Abr_Foret ; Cle : in integer) return Boolean; procedure Demis_Soeurs_Freres_Pere ( Abr : in T_Abr_Foret ) ; procedure Afficher_Fils_Pere ( Abr : in T_Abr_Foret ; Cle_Pere : in integer; Cle_Mere : in integer) ; procedure Demis_Soeurs_Freres_Mere ( Abr : in T_Abr_Foret ) ; procedure Afficher_Fils_Mere ( Abr : in T_Abr_Foret ; Cle_Mere : in integer; Cle_Pere : in integer) ; procedure Avoir_Arbre (Abr : in T_Abr_Foret ; Cle : in integer ; Curseur : in out T_Abr_Foret ) with Pre => Existe ( Abr , Cle ); function Existe_Compagnon (TableauCompagnon : in T_Tableau; Cle_Compagnon : in integer) return Boolean; private type T_Cellule; type T_Abr_Foret is access T_Cellule; type T_Tab is array(1..Capacite) of T_Abr_Foret; type T_Tableau is record Taille : integer; Tableau : T_Tab; end record; type T_Cellule is record Cle : integer; Pere : T_Abr_Foret; Mere : T_Abr_Foret; Epoux : T_Abr_Foret; Tableau_Compagnons : T_Tableau; end record; end Arbre_Foret;
-- C52008B.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK THAT A RECORD VARIABLE DECLARED WITH A SPECIFIED -- DISCRIMINANT CONSTRAINT CANNOT HAVE A DISCRIMINANT VALUE ALTERED -- BY ASSIGNMENT. ASSIGNING AN ENTIRE RECORD VALUE WITH A -- DIFFERENT DISCRIMINANT VALUE SHOULD RAISE CONSTRAINT_ERROR AND -- LEAVE THE TARGET VARIABLE UNALTERED. THIS TEST USES NON-STATIC -- DISCRIMINANT VALUES. -- HISTORY: -- ASL 6/25/81 CREATED ORIGINAL TEST -- JRK 11/18/82 -- RJW 8/17/89 ADDED SUBTYPE 'SUBINT'. WITH REPORT; PROCEDURE C52008B IS USE REPORT; TYPE REC1(D1,D2 : INTEGER) IS RECORD COMP1 : STRING(D1..D2); END RECORD; TYPE AR_REC1 IS ARRAY (NATURAL RANGE <>) OF REC1(IDENT_INT(3), IDENT_INT(5)); SUBTYPE SUBINT IS INTEGER RANGE -128 .. 127; TYPE REC2(D1,D2,D3,D4 : SUBINT := 0) IS RECORD COMP1 : STRING(1..D1); COMP2 : STRING(D2..D3); COMP5 : AR_REC1(1..D4); COMP6 : REC1(D3,D4); END RECORD; STR : STRING(IDENT_INT(3)..IDENT_INT(5)) := "ZZZ"; R1A : REC1(IDENT_INT(3),IDENT_INT(5)) := (3,5,STR); R1C : REC1(5,6) := (5,6,COMP1 => (5..6 => 'K')); Q,R : REC2(IDENT_INT(2),IDENT_INT(3),IDENT_INT(5),IDENT_INT(6)); TEMP : REC2(2,3,5,6); W : REC2(1,4,6,8); OK : BOOLEAN := FALSE; BEGIN TEST ("C52008B", "CANNOT ASSIGN RECORD VARIABLE WITH SPECIFIED " & "DISCRIMINANT VALUE A VALUE WITH A DIFFERENT " & "(DYNAMIC) DISCRIMINANT VALUE"); BEGIN R1A := (IDENT_INT(3),5,"XYZ"); R := (IDENT_INT(2),IDENT_INT(3),IDENT_INT(5),IDENT_INT(6), "AB", STR, (1..6 => R1A), R1C); TEMP := R; Q := TEMP; R.COMP1 := "YY"; OK := TRUE; W := R; FAILED ("ASSIGNMENT MADE USING INCORRECT DISCRIMINANT " & "VALUES"); EXCEPTION WHEN CONSTRAINT_ERROR => IF NOT OK OR Q /= TEMP OR R = TEMP OR R = Q OR W.D4 /= 8 THEN FAILED ("LEGITIMATE ASSIGNMENT FAILED"); END IF; WHEN OTHERS => FAILED ("WRONG EXCEPTION"); END; RESULT; END C52008B;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Text_IO; with GL.Types; with Orka.Types; procedure Orka_7_Half is use type GL.Types.Single; Numbers : constant GL.Types.Single_Array := (0.0, 0.5, -0.5, 1.0, -1.0, 0.1, -0.1, 0.0, 0.1234, -0.123456, 10.1234, 20.1234, 50.1234, 100.1234, 1000.1234); Half_Numbers : GL.Types.Half_Array (Numbers'Range); Single_Numbers : GL.Types.Single_Array (Half_Numbers'Range); begin Orka.Types.Convert (Numbers, Half_Numbers); Orka.Types.Convert (Half_Numbers, Single_Numbers); for Number of Numbers loop Ada.Text_IO.Put_Line (GL.Types.Single'Image (Number)); end loop; Ada.Text_IO.Put_Line ("------------"); for Number of Single_Numbers loop Ada.Text_IO.Put_Line (GL.Types.Single'Image (Number)); end loop; end Orka_7_Half;
-- Copyright (C) 2020 Glen Cornell <glen.m.cornell@gmail.com> -- -- 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 3 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. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see -- <http://www.gnu.org/licenses/>. with System; with Aof.Core.Objects; with Aof.Core.Properties; package Aof.Core.Threads is -- pragma Preelaborate; -- This is the public part of the thread object. do not create -- instances of this type. type Thread_Public_Part is limited new Aof.Core.Objects.Object with record Started : Aof.Core.Properties.Booleans.Property; Finished : Aof.Core.Properties.Booleans.Property; end record; type Thread is limited new Thread_Public_Part with private; type Access_Thread is access all Thread'Class; procedure Initialize (This : in out Thread); procedure Start (This : in out Thread; Priority : in System.Any_Priority); procedure Terminate_Thread (This : in out Thread); procedure Run (This : in out Thread); function Current_Thread return Access_Thread; function Is_Finished (This : in Thread) return Boolean; function Is_Running (This : in Thread) return Boolean; function Priority (This : in Thread) return System.Any_Priority; procedure Set_Priority (This : in out Thread; Priority : in System.Any_Priority); private task type Task_Type Is entry Initialize (The_Thread : in Access_Thread); entry Start (The_Priority : in System.Any_Priority); end Task_Type; type Thread is limited new Thread_Public_Part with record Thread : Task_Type; Priority : System.Any_Priority; end record; end Aof.Core.Threads;
with agar.gui.widget.scrollbar; with agar.gui.widget.editable; package agar.gui.widget.textbox is use type c.unsigned; subtype cursor_pos_t is agar.gui.widget.editable.cursor_pos_t; type flags_t is new c.unsigned; TEXTBOX_MULTILINE : constant flags_t := 16#00001#; TEXTBOX_PASSWORD : constant flags_t := 16#00004#; TEXTBOX_ABANDON_FOCUS : constant flags_t := 16#00008#; TEXTBOX_COMBO : constant flags_t := 16#00010#; TEXTBOX_HFILL : constant flags_t := 16#00020#; TEXTBOX_VFILL : constant flags_t := 16#00040#; TEXTBOX_EXPAND : constant flags_t := TEXTBOX_HFILL or TEXTBOX_VFILL; TEXTBOX_READONLY : constant flags_t := 16#00100#; TEXTBOX_INT_ONLY : constant flags_t := 16#00200#; TEXTBOX_FLT_ONLY : constant flags_t := 16#00400#; TEXTBOX_CATCH_TAB : constant flags_t := 16#00800#; TEXTBOX_CURSOR_MOVING : constant flags_t := 16#01000#; TEXTBOX_STATIC : constant flags_t := 16#04000#; TEXTBOX_NOEMACS : constant flags_t := 16#08000#; TEXTBOX_NOWORDSEEK : constant flags_t := 16#10000#; TEXTBOX_NOLATIN1 : constant flags_t := 16#20000#; type textbox_t is limited private; type textbox_access_t is access all textbox_t; pragma convention (c, textbox_access_t); string_max : constant := agar.gui.widget.editable.string_max; -- API function allocate (parent : widget_access_t; flags : flags_t; label : string) return textbox_access_t; pragma inline (allocate); procedure set_static (textbox : textbox_access_t; enable : boolean); pragma inline (set_static); procedure set_password (textbox : textbox_access_t; enable : boolean); pragma inline (set_password); procedure set_float_only (textbox : textbox_access_t; enable : boolean); pragma inline (set_float_only); procedure set_integer_only (textbox : textbox_access_t; enable : boolean); pragma inline (set_integer_only); procedure set_label (textbox : textbox_access_t; text : string); pragma inline (set_label); procedure size_hint (textbox : textbox_access_t; text : string); pragma inline (size_hint); procedure size_hint_pixels (textbox : textbox_access_t; width : positive; height : positive); pragma inline (size_hint_pixels); -- cursor manipulation procedure map_position (textbox : textbox_access_t; x : integer; y : integer; index : out natural; pos : out cursor_pos_t; absolute : boolean); pragma inline (map_position); function move_cursor (textbox : textbox_access_t; x : integer; y : integer; absolute : boolean) return integer; pragma inline (move_cursor); function get_cursor_position (textbox : textbox_access_t) return integer; pragma inline (get_cursor_position); function set_cursor_position (textbox : textbox_access_t; position : integer) return integer; pragma inline (set_cursor_position); -- text manipulation procedure set_string (textbox : textbox_access_t; text : string); pragma inline (set_string); procedure set_string_ucs4 (textbox : textbox_access_t; text : wide_wide_string); pragma inline (set_string_ucs4); procedure clear_string (textbox : textbox_access_t); pragma import (c, clear_string, "agar_gui_widget_textbox_clear_string"); procedure buffer_changed (textbox : textbox_access_t); pragma import (c, buffer_changed, "agar_gui_widget_textbox_buffer_changed"); function get_integer (textbox : textbox_access_t) return integer; pragma inline (get_integer); function get_float (textbox : textbox_access_t) return float; pragma inline (get_float); function get_long_float (textbox : textbox_access_t) return long_float; pragma inline (get_long_float); function widget (textbox : textbox_access_t) return widget_access_t; pragma inline (widget); private type textbox_t is record widget : aliased widget_t; editable : agar.gui.widget.editable.editable_access_t; label_text : cs.chars_ptr; label : c.int; flags : flags_t; box_pad_x : c.int; box_pad_y : c.int; label_pad_left : c.int; label_pad_right : c.int; width_label : c.int; height_label : c.int; horiz_scrollbar : agar.gui.widget.scrollbar.scrollbar_access_t; vert_scrollbar : agar.gui.widget.scrollbar.scrollbar_access_t; r : agar.gui.rect.rect_t; r_label : agar.gui.rect.rect_t; end record; pragma convention (c, textbox_t); end agar.gui.widget.textbox;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- XML Processor -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2014, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Ada.Unchecked_Deallocation; with League.IRIs; with League.Strings.Internals; with Matreshka.Internals.Strings.Operations; with Matreshka.Internals.Unicode.Characters.Latin; with Matreshka.Internals.URI_Utilities; with XML.SAX.Simple_Readers.Callbacks; with XML.SAX.Simple_Readers.Scanner.Actions; with XML.SAX.Simple_Readers.Scanner.Tables; package body XML.SAX.Simple_Readers.Scanner is use type Interfaces.Unsigned_32; use Matreshka.Internals.Unicode; use Matreshka.Internals.Unicode.Characters.Latin; use Matreshka.Internals.Utf16; use Matreshka.Internals.XML; use Matreshka.Internals.XML.Base_Scopes; use Matreshka.Internals.XML.Entity_Tables; use XML.SAX.Simple_Readers.Scanner.Tables; procedure Set_Whitespace_Matched (Self : in out Simple_Reader'Class) with Inline => True; -- Sets "whitespace matched" flag. procedure Free is new Ada.Unchecked_Deallocation (XML.SAX.Input_Sources.SAX_Input_Source'Class, XML.SAX.Input_Sources.SAX_Input_Source_Access); --------------------------- -- Enter_Start_Condition -- --------------------------- procedure Enter_Start_Condition (Self : in out Simple_Reader'Class; State : Interfaces.Unsigned_32) is begin Self.Scanner_State.YY_Start_State := State * 2 + 1; end Enter_Start_Condition; -------------- -- Finalize -- -------------- procedure Finalize (Self : in out Simple_Reader'Class) is use type XML.SAX.Input_Sources.SAX_Input_Source_Access; begin -- Unwind entity stack and release all input sources owned by the -- reader. while not Self.Scanner_Stack.Is_Empty loop if Self.Scanner_State.Source /= null then -- Deallocate input source and replacement text data, because -- it was not yet saved in the entities table. Free (Self.Scanner_State.Source); Matreshka.Internals.Strings.Dereference (Self.Scanner_State.Data); end if; Self.Scanner_State := Self.Scanner_Stack.Last_Element; Self.Scanner_Stack.Delete_Last; end loop; -- Release last token, it can be unused by the parser when fatal error -- occured. Clear (Self.YYLVal); -- Release shared string when scanner's stack is empty, because it is -- buffer for document entity. Matreshka.Internals.Strings.Dereference (Self.Scanner_State.Data); end Finalize; ---------------- -- Initialize -- ---------------- procedure Initialize (Self : in out Simple_Reader'Class) is begin Self.Scanner_State.Start_Condition_Stack.Append (Tables.DOCUMENT_10); end Initialize; ------------------------- -- Pop_Start_Condition -- ------------------------- procedure Pop_Start_Condition (Self : in out Simple_Reader'Class) is begin Enter_Start_Condition (Self, Self.Scanner_State.Start_Condition_Stack.Last_Element); Self.Scanner_State.Start_Condition_Stack.Delete_Last; end Pop_Start_Condition; ------------------------------------ -- Push_And_Enter_Start_Condition -- ------------------------------------ procedure Push_And_Enter_Start_Condition (Self : in out Simple_Reader'Class; Push : Interfaces.Unsigned_32; Enter : Interfaces.Unsigned_32) is begin Self.Scanner_State.Start_Condition_Stack.Append (Push); Self.Scanner_State.YY_Start_State := 1 + 2 * Enter; end Push_And_Enter_Start_Condition; -------------------------------------------- -- Push_Current_And_Enter_Start_Condition -- -------------------------------------------- procedure Push_Current_And_Enter_Start_Condition (Self : in out Simple_Reader'Class; Enter : Interfaces.Unsigned_32) is begin Self.Scanner_State.Start_Condition_Stack.Append (Start_Condition (Self)); Self.Scanner_State.YY_Start_State := 1 + 2 * Enter; end Push_Current_And_Enter_Start_Condition; ----------------- -- Push_Entity -- ----------------- function Push_Entity (Self : in out Simple_Reader'Class; Entity : Matreshka.Internals.XML.Entity_Identifier; In_Document_Type : Boolean; In_Literal : Boolean) return Boolean is use type Matreshka.Internals.Strings.Shared_String_Access; use type League.Strings.Universal_String; Source : XML.SAX.Input_Sources.SAX_Input_Source_Access; Text : Matreshka.Internals.Strings.Shared_String_Access; Last_Match : Boolean; Condition : constant Interfaces.Unsigned_32 := Start_Condition (Self); begin -- Resolve entity when necessary. if not Is_Resolved (Self.Entities, Entity) then Callbacks.Call_Resolve_Entity (Self, Entity, Public_Id (Self.Entities, Entity), Enclosing_Base_URI (Self.Entities, Entity), System_Id (Self.Entities, Entity), Source); Text := Matreshka.Internals.Strings.Shared_Empty'Access; Last_Match := False; if not Self.Continue then Self.Error_Message.Prepend ("unable to resolve external entity: "); Callbacks.Call_Fatal_Error (Self, Self.Error_Message); return False; end if; Set_Is_Resolved (Self.Entities, Entity, True); Set_Entity_Base_URI (Self.Entities, Entity, Matreshka.Internals.URI_Utilities.Directory_Name (Source.System_Id)); case Self.Version is when XML_1_0 => Source.Set_Version (League.Strings.To_Universal_String ("1.0")); when XML_1_1 => Source.Set_Version (League.Strings.To_Universal_String ("1.1")); end case; else Source := null; Text := Replacement_Text (Self.Entities, Entity); Last_Match := True; if Text.Unused = 0 then -- Replacement text is empty string, -- [XML 4.4.8] Included as PE -- -- "Just as with external parsed entities, parameter entities need -- only be included if validating. When a parameter-entity -- reference is recognized in the DTD and included, its -- replacement text MUST be enlarged by the attachment of one -- leading and one following space (#x20) character; the intent is -- to constrain the replacement text of parameter entities to -- contain an integral number of grammatical tokens in the DTD. -- This behavior MUST NOT apply to parameter entity references -- within entity values; these are described in 4.4.5 Included in -- Literal." -- -- Set Whitespace_Matched flag, it is used only while processing -- of DTD, so the place where parameter entity declarations are -- allowed. Self.Whitespace_Matched := True; return True; end if; end if; -- [XML 4.4.8] Included as PE -- -- "Just as with external parsed entities, parameter entities need only -- be included if validating. When a parameter-entity reference is -- recognized in the DTD and included, its replacement text MUST be -- enlarged by the attachment of one leading and one following space -- (#x20) character; the intent is to constrain the replacement text of -- parameter entities to contain an integral number of grammatical -- tokens in the DTD. This behavior MUST NOT apply to parameter entity -- references within entity values; these are described in 4.4.5 -- Included in Literal." -- -- Set Whitespace_Matched flag, it is used only while processing of DTD, -- so the place where parameter entity declarations are allowed. Self.Whitespace_Matched := True; Self.Scanner_Stack.Append (Self.Scanner_State); Self.Scanner_State := (Source => Source, Data => Text, Entity => Entity, In_Literal => In_Literal, Delimiter => 0, others => <>); -- Push base URI into the stack. Entity base URI is used for external -- entities; current base URI is used for internal entities. if Entity_Base_URI (Self.Entities, Entity) = Matreshka.Internals.Strings.Shared_Empty'Access then Matreshka.Internals.XML.Base_Scopes.Push_Scope (Self.Bases); else Matreshka.Internals.XML.Base_Scopes.Push_Scope (Self.Bases, League.IRIs.From_Universal_String (League.Strings.Internals.Create (Entity_Base_URI (Self.Entities, Entity)))); end if; if Last_Match then Self.Scanner_State.YY_Current_Position := First_Position (Self.Entities, Entity); Self.Scanner_State.YY_Current_Index := Integer (First_Position (Self.Entities, Entity)) + 1; if In_Document_Type then -- External subset processed after processing of internal subset -- is completed and scanner returns to DOCTYPE_INT start -- condition; but it must be switched back to -- DOCTYPE_INTSUBSET_10 or DOCTYPE_INTSUBSET_11 start condition. case Self.Version is when XML_1_0 => Enter_Start_Condition (Self, DOCTYPE_INTSUBSET_10); when XML_1_1 => Enter_Start_Condition (Self, DOCTYPE_INTSUBSET_11); end case; else if Condition = DOCUMENT_11 and Is_Internal_General_Entity (Self.Entities, Entity) then -- Character references are resolved when replacement text of -- internal general entity is constructed. In XML 1.1 character -- references can refer to restricted characters which is not -- valid in text, but valid in replacement text. Enter_Start_Condition (Self, DOCUMENT_U11); else Enter_Start_Condition (Self, Condition); end if; end if; else -- Reset scanner to INITIAL state to be able to process text -- declaration at the beginning of the external entity. if In_Document_Type then -- External subset processed after processing of internal subset -- is completed and scanner returns to DOCTYPE_INT start -- condition; but it must be switched back to -- DOCTYPE_INTSUBSET_10 or DOCTYPE_INTSUBSET_11 start condition. case Self.Version is when XML_1_0 => Push_And_Enter_Start_Condition (Self, DOCTYPE_INTSUBSET_10, INITIAL); when XML_1_1 => Push_And_Enter_Start_Condition (Self, DOCTYPE_INTSUBSET_11, INITIAL); end case; else Push_And_Enter_Start_Condition (Self, Condition, INITIAL); end if; end if; return True; end Push_Entity; ------------------------------ -- Reset_Whitespace_Matched -- ------------------------------ procedure Reset_Whitespace_Matched (Self : in out Simple_Reader'Class) is begin Self.Whitespace_Matched := False; end Reset_Whitespace_Matched; --------------------------------------- -- Set_Document_Version_And_Encoding -- --------------------------------------- procedure Set_Document_Version_And_Encoding (Self : in out Simple_Reader'Class; Version : XML_Version; Encoding : League.Strings.Universal_String) is Restart : Boolean; Success : Boolean; End_Of_Source : Boolean; begin Pop_Start_Condition (Self); if Self.Version /= Version then -- [XML1.0 2.8] -- -- "Note: When an XML 1.0 processor encounters a document that -- specifies a 1.x version number other than '1.0', it will process -- it as a 1.0 document. This means that an XML 1.0 processor will -- accept 1.x documents provided they do not use any non-1.0 -- features." -- -- [XML1.1 4.3.4] -- -- "Each entity, including the document entity, can be separately -- declared as XML 1.0 or XML 1.1. The version declaration appearing -- in the document entity determines the version of the document as a -- whole. An XML 1.1 document may invoke XML 1.0 external entities, -- so that otherwise duplicated versions of external entities, -- particularly DTD external subsets, need not be maintained. -- However, in such a case the rules of XML 1.1 are applied to the -- entire document." -- -- So, XML version of the document can be declared only once, in the -- XML declaration at the start of the document entity. All other -- occurrences of version declaration in external subset and -- external entities are ignored. This allows to simplify code of -- the version change subprogram. Self.Version := Version; case Self.Version is when XML_1_0 => Enter_Start_Condition (Self, Tables.DOCUMENT_10); when XML_1_1 => Enter_Start_Condition (Self, Tables.DOCUMENT_11); end case; end if; case Self.Version is when XML_1_0 => Self.Scanner_State.Source.Reset (League.Strings.To_Universal_String ("1.0"), Encoding, Restart, Success); when XML_1_1 => Self.Scanner_State.Source.Reset (League.Strings.To_Universal_String ("1.1"), Encoding, Restart, Success); end case; if not Success then Callbacks.Call_Fatal_Error (Self, League.Strings.To_Universal_String ("invalid or unsupported encoding")); elsif Restart then Matreshka.Internals.Strings.Operations.Reset (Self.Scanner_State.Data); Self.Scanner_State.Source.Next (Self.Scanner_State.Data, End_Of_Source); end if; end Set_Document_Version_And_Encoding; ---------------------------- -- Set_Whitespace_Matched -- ---------------------------- procedure Set_Whitespace_Matched (Self : in out Simple_Reader'Class) is begin Self.Whitespace_Matched := True; end Set_Whitespace_Matched; --------------------- -- Start_Condition -- --------------------- function Start_Condition (Self : Simple_Reader'Class) return Interfaces.Unsigned_32 is begin return (Self.Scanner_State.YY_Start_State - 1) / 2; end Start_Condition; ---------------------- -- YY_Move_Backward -- ---------------------- procedure YY_Move_Backward (Self : in out Simple_Reader'Class) is begin Self.Scanner_State.YY_Current_Position := Self.Scanner_State.YY_Current_Position - 1; Self.Scanner_State.YY_Current_Index := Self.Scanner_State.YY_Current_Index - 1; Self.Scanner_State.YY_Current_Column := Self.Scanner_State.YY_Current_Column - 1; end YY_Move_Backward; ------------- -- YY_Text -- ------------- function YY_Text (Self : Simple_Reader'Class; Trim_Left : Natural := 0; Trim_Right : Natural := 0; Trim_Whitespace : Boolean := False) return Matreshka.Internals.Strings.Shared_String_Access is -- Trailing and leading character as well as whitespace characters -- belongs to BMP and don't require expensive UTF-16 decoding. FP : Utf16_String_Index := Self.Scanner_State.YY_Base_Position + Utf16_String_Index (Trim_Left); FI : Positive := Self.Scanner_State.YY_Base_Index + Trim_Left; LP : constant Utf16_String_Index := Self.Scanner_State.YY_Current_Position - Utf16_String_Index (Trim_Right); LI : constant Positive := Self.Scanner_State.YY_Current_Index - Trim_Right; C : Code_Point; begin if Trim_Whitespace then loop C := Code_Point (Self.Scanner_State.Data.Value (FP)); exit when C /= Space and then C /= Character_Tabulation and then C /= Carriage_Return and then C /= Line_Feed; FP := FP + 1; FI := FI + 1; end loop; end if; return Matreshka.Internals.Strings.Operations.Slice (Self.Scanner_State.Data, FP, LP - FP, LI - FI); end YY_Text; ----------- -- YYLex -- ----------- function YYLex (Self : in out Simple_Reader'Class) return Token is use type XML.SAX.Input_Sources.SAX_Input_Source_Access; type YY_End_Of_Buffer_Actions is (YY_Continue_Scan, -- Continue scanning from the current position. -- It is used to continue processing after pop -- up of entity from the scanner's stack. YY_Report_Entity_End, -- Return end of entity mark. YY_Restart_Scan, -- Restart scanning from the base position. YY_Accept_Last_Match, -- Accept last matched action. YY_End_Of_Chunk, -- End of chunk of data is reached. YY_End_Of_Input); -- End of input is reached. YY_Action : Interfaces.Unsigned_32; YY_C : Interfaces.Unsigned_32; YY_Current_State : Interfaces.Unsigned_32; YY_Current_Code : Code_Point; YY_Last_Accepting_Position : Utf16_String_Index; YY_Last_Accepting_Index : Positive; YY_Last_Accepting_State : Interfaces.Unsigned_32; YY_Last_Accepting_Line : Natural; YY_Last_Accepting_Column : Natural; YY_Last_Accepting_Skip_LF : Boolean; YY_Last_Accepting : Boolean; YY_Next_Position : Utf16_String_Index; YY_Next_Index : Positive; YY_Next_Line : Natural; YY_Next_Column : Natural; YY_Next_Skip_LF : Boolean; YY_Last_Match_Position : Utf16_String_Index; YY_Last_Match_Index : Positive; YY_Last_Match_State : Interfaces.Unsigned_32; YY_Last_Match_Line : Natural; YY_Last_Match_Column : Natural; YY_Last_Match_Skip_LF : Boolean; YY_Last_Match : Boolean; YYLVal : YYSType renames Self.YYLVal; YY_Last : Utf16_String_Index; End_Of_Source : Boolean; YY_End_Of_Buffer_Action : YY_End_Of_Buffer_Actions; YY_Position_Offset : Utf16_String_Index; YY_Index_Offset : Natural; YY_Start_Condition : Interfaces.Unsigned_32; Start_Issued : Boolean; function YY_Text_Internal (Trim_Left : Natural := 0; Trim_Right : Natural := 0; Trim_Whitespace : Boolean := False) return Matreshka.Internals.Strings.Shared_String_Access; ---------------------- -- YY_Text_Internal -- ---------------------- function YY_Text_Internal (Trim_Left : Natural := 0; Trim_Right : Natural := 0; Trim_Whitespace : Boolean := False) return Matreshka.Internals.Strings.Shared_String_Access is -- Trailing and leading character as well as whitespace characters -- belongs to BMP and don't require expensive UTF-16 decoding. FP : Utf16_String_Index := Self.Scanner_State.YY_Base_Position + Utf16_String_Index (Trim_Left); FI : Positive := Self.Scanner_State.YY_Base_Index + Trim_Left; LP : constant Utf16_String_Index := Self.Scanner_State.YY_Current_Position - Utf16_String_Index (Trim_Right); LI : constant Positive := Self.Scanner_State.YY_Current_Index - Trim_Right; C : Code_Point; begin if Trim_Whitespace then loop C := Code_Point (Self.Scanner_State.Data.Value (FP)); exit when C /= Space and then C /= Character_Tabulation and then C /= Carriage_Return and then C /= Line_Feed; FP := FP + 1; FI := FI + 1; end loop; end if; return Matreshka.Internals.Strings.Operations.Slice (Self.Scanner_State.Data, FP, LP - FP, LI - FI); end YY_Text_Internal; begin loop -- Loops until end-of-data is reached. Self.Scanner_State.YY_Base_Position := Self.Scanner_State.YY_Current_Position; Self.Scanner_State.YY_Base_Index := Self.Scanner_State.YY_Current_Index; Self.Scanner_State.YY_Base_Line := Self.Scanner_State.YY_Current_Line; Self.Scanner_State.YY_Base_Column := Self.Scanner_State.YY_Current_Column; Self.Scanner_State.YY_Base_Skip_LF := Self.Scanner_State.YY_Current_Skip_LF; YY_Current_State := Self.Scanner_State.YY_Start_State; YY_Last_Match := False; YY_Last_Accepting := False; loop YY_Next_Position := Self.Scanner_State.YY_Current_Position; YY_Next_Index := Self.Scanner_State.YY_Current_Index; YY_Next_Line := Self.Scanner_State.YY_Current_Line; YY_Next_Column := Self.Scanner_State.YY_Current_Column; YY_Next_Skip_LF := Self.Scanner_State.YY_Current_Skip_LF; if YY_Next_Position < Self.Scanner_State.Data.Unused then Unchecked_Next (Self.Scanner_State.Data.Value, YY_Next_Position, YY_Current_Code); YY_Next_Index := YY_Next_Index + 1; -- Track line/column in entity if YY_Current_Code = Carriage_Return then -- Start of new line. YY_Next_Line := YY_Next_Line + 1; YY_Next_Column := 1; YY_Next_Skip_LF := True; elsif YY_Current_Code = Line_Feed then if YY_Next_Skip_LF then -- Ignore CR after LF. YY_Next_Skip_LF := False; else YY_Next_Line := YY_Next_Line + 1; YY_Next_Column := 1; end if; else -- Move to next column. YY_Next_Column := YY_Next_Column + 1; YY_Next_Skip_LF := False; end if; YY_C := YY_EC_Base (YY_Current_Code / 16#100#) (YY_Current_Code mod 16#100#); else -- End of buffer reached. YY_C := 0; -- Aflex uses character with code point zero to mark end of -- buffer character. This character always has YY_EC zero. YY_Last_Match := YY_Last_Accepting; if YY_Last_Accepting then YY_Last_Match_Position := YY_Last_Accepting_Position; YY_Last_Match_Index := YY_Last_Accepting_Index; YY_Last_Match_State := YY_Last_Accepting_State; YY_Last_Match_Line := YY_Last_Accepting_Line; YY_Last_Match_Column := YY_Last_Accepting_Column; YY_Last_Match_Skip_LF := YY_Last_Accepting_Skip_LF; end if; end if; if YY_Accept (YY_Current_State) /= 0 then -- Accepting state reached, save for possible backtrack. YY_Last_Accepting_Position := Self.Scanner_State.YY_Current_Position; YY_Last_Accepting_Index := Self.Scanner_State.YY_Current_Index; YY_Last_Accepting_Line := Self.Scanner_State.YY_Current_Line; YY_Last_Accepting_Column := Self.Scanner_State.YY_Current_Column; YY_Last_Accepting_Skip_LF := Self.Scanner_State.YY_Current_Skip_LF; YY_Last_Accepting_State := YY_Current_State; YY_Last_Accepting := True; end if; while YY_Chk (YY_Base (YY_Current_State) + YY_C) /= YY_Current_State loop YY_Current_State := YY_Def (YY_Current_State); if YY_Current_State >= YY_First_Template then YY_C := YY_Meta (YY_C); end if; end loop; Self.Scanner_State.YY_Current_Position := YY_Next_Position; Self.Scanner_State.YY_Current_Index := YY_Next_Index; Self.Scanner_State.YY_Current_Line := YY_Next_Line; Self.Scanner_State.YY_Current_Column := YY_Next_Column; Self.Scanner_State.YY_Current_Skip_LF := YY_Next_Skip_LF; YY_Current_State := YY_Nxt (YY_Base (YY_Current_State) + YY_C); exit when YY_Base (YY_Current_State) = YY_Jam_Base; end loop; -- Return back to last accepting state. <<Next_Action>> YY_Action := YY_Accept (YY_Current_State); case YY_Action is when 0 => -- must backtrack if YY_Last_Accepting then Self.Scanner_State.YY_Current_Position := YY_Last_Accepting_Position; Self.Scanner_State.YY_Current_Index := YY_Last_Accepting_Index; Self.Scanner_State.YY_Current_Line := YY_Last_Accepting_Line; Self.Scanner_State.YY_Current_Column := YY_Last_Accepting_Column; Self.Scanner_State.YY_Current_Skip_LF := YY_Last_Accepting_Skip_LF; YY_Current_State := YY_Last_Accepting_State; YY_Last_Accepting := False; goto Next_Action; else raise Program_Error; end if; pragma Style_Checks ("M127"); when 1 => -- Open of XML declaration or text declaration, rules [23], [77]. return Actions.On_Open_Of_XML_Or_Text_Declaration (Self); when 2 => -- Any character except literal "<?xml" means there is no XML declaration -- in this document/external parsed entity. Actions.On_No_XML_Declaration (Self); when 3 => -- Open of processing instruction, rule [16]. Rule [17] is implemented -- implicitly by ordering of open of XMLDecl and open of PI. return Actions.On_Open_Of_Processing_Instruction (Self); when 4 => -- Open tag of document type declaration and name of root element, -- rule [28]. return Actions.On_Open_Of_Document_Type_Declaration (Self); when 5 => -- Open of start tag, rule [40], or empty element, rule [44]. return Actions.On_Open_Of_Start_Tag (Self); when 6 => -- Open of end tag, rule [42]. return Actions.On_Open_Of_End_Tag (Self); when 7 => -- Segment of whitespaces. if Actions.On_Whitespace_In_Document (Self) then return Token_String_Segment; end if; when 8 => -- Segment of character data, rule [14]. return Actions.On_Character_Data (Self); when 9 => -- Segment of character data, rule [14]. return Actions.On_Character_Data (Self); when 10 => -- Segment of character data, rule [14]. return Actions.On_Character_Data (Self); when 11 => -- Start of CDATA section, production [19]. return Actions.On_Open_Of_CDATA (Self); when 12 => -- Start of CDATA section, production [19]. return Actions.On_Open_Of_CDATA (Self); when 13 => -- Start of CDATA section, production [19]. return Actions.On_Open_Of_CDATA (Self); when 14 => -- Text data of CDATA section, production [20]. return Actions.On_CDATA (Self); when 15 => -- Text data of CDATA section, production [20]. return Actions.On_CDATA (Self); when 16 => -- Text data of CDATA section, production [20]. return Actions.On_CDATA (Self); when 17 => -- End of CDATA section, production [21]. return Actions.On_Close_Of_CDATA (Self); when 18 => -- End of CDATA section, production [21]. return Actions.On_Close_Of_CDATA (Self); when 19 => -- End of CDATA section, production [21]. return Actions.On_Close_Of_CDATA (Self); when 20 => -- General entity reference rule [68] in document content. declare Aux : constant Token := Actions.On_General_Entity_Reference_In_Document_Content (Self); begin -- By convention, End_Of_Input means that replacement text of the -- referenced entity is empty and it is not pushed into the scanner -- stack. if Aux /= End_Of_Input then return Aux; end if; end; when 21 => -- [24] VersionInfo return Actions.On_Version_Keyword (Self); when 22 => -- [80] EncodingDecl return Actions.On_Encoding_Keyword (Self); when 23 => -- [32] SDDecl return Actions.On_Standalone_Keyword (Self); when 24 => -- Synthetic rule. XMLDECL_ATTRIBUTE_CHAR is a union of characters allowed -- by [26] VersionNum, [81] EncName, [32] SDDecl. Precise check is -- processed while parsing. return Actions.On_Attribute_Value_In_XML_Declaration (Self); when 25 => -- Close of XML declaration (production [23]) or text declaration -- (production [77]). return Actions.On_Close_Of_XML_Or_Text_Declaration (Self); when 26 => -- Close of processing instruction (rule [16]). return Actions.On_Close_Of_Processing_Instruction (Self, True); when 27 => -- Ignore all whitespaces is followed by processing insturction's name, -- rule [16]. Actions.On_Whitespace_In_Processing_Instruction (Self); when 28 => -- Segment of data and close delimiter of the processing instruction, rule -- [16]. return Actions.On_Close_Of_Processing_Instruction (Self, False); when 29 => -- Segment of data and close delimiter of the processing instruction, rule -- [16]. return Actions.On_Close_Of_Processing_Instruction (Self, False); when 30 => -- Keyword SYSTEM, rule [75]. return Actions.On_System_Keyword_In_Document_Type (Self); when 31 => -- System literal, rule [11], used in rule [75]. return Actions.On_System_Literal (Self); when 32 => -- Productions [82], [83] allows absence of system literal in -- notation declaration. Pop_Start_Condition (Self); if Start_Condition (Self) = NOTATION_DECL then Pop_Start_Condition (Self); end if; return Token_Close; when 33 => -- Keyword PUBLIC, rule [75]. Reset_Whitespace_Matched (Self); Push_And_Enter_Start_Condition (Self, DOCTYPE_INT, EXTERNAL_ID_PUB); return Token_Public; when 34 => -- Public id literal, rule [12], used in rule [75]. return Actions.On_Public_Literal (Self); when 35 => -- Open of internal subset declaration, rule [28]. return Actions.On_Open_Of_Internal_Subset (Self); when 36 => -- Close of internal subset declaration, rule [28]. Enter_Start_Condition (Self, DOCTYPE_INT); return Token_Internal_Subset_Close; when 37 => -- Text of comment, rule [15]. Set_String_Internal (Item => YYLVal, String => YY_Text_Internal (4, 3), Is_Whitespace => False); return Token_Comment; when 38 => -- Text of comment, rule [15]. Set_String_Internal (Item => YYLVal, String => YY_Text_Internal (4, 3), Is_Whitespace => False); return Token_Comment; when 39 => -- Parameter entity reference rule [69] in document type declaration. return Actions.On_Parameter_Entity_Reference_In_Document_Declaration (Self); when 40 => -- Open of entity declaration, rules [71], [72]. Enter_Start_Condition (Self, ENTITY_DECL); Reset_Whitespace_Matched (Self); return Token_Entity_Decl_Open; when 41 => -- Open of element declaration and name of the element, rule [45]. return Actions.On_Open_Of_Element_Declaration (Self); when 42 => -- Open of attribute list declaration, rule [52]. return Actions.On_Open_Of_Attribute_List_Declaration (Self); when 43 => -- Open of notation declaration, production [82]. return Actions.On_Open_Of_Notation_Declaration (Self); when 44 => -- Start of conditional section. return Actions.On_Open_Of_Conditional_Section (Self); when 45 => -- Close of conditional section. return Actions.On_Close_Of_Conditional_Section (Self); when 46 => -- Close of notation declaration, production [82]. Pop_Start_Condition (Self); return Token_Close; when 47 => -- Name in entity declaration, rules [71], [72]. return Actions.On_Name_In_Entity_Declaration (Self); when 48 => -- Percent mark in parameter entity declaration, rule [72]. return Actions.On_Percent_Sign (Self); when 49 => -- Entity value, rule [9]. return Actions.On_Entity_Value_Open_Delimiter (Self); when 50 => -- Entity value as ExternalID, rule [75], used by rules [73], [74]. return Actions.On_System_Keyword_In_Entity_Or_Notation (Self); when 51 => -- Entity value as ExternalID, rule [75], used by rules [73], [74]. -- Notation as ExternalID or Public_ID (productions [75], [82], [83]). Reset_Whitespace_Matched (Self); Push_Current_And_Enter_Start_Condition (Self, EXTERNAL_ID_PUB); return Token_Public; when 52 => -- NDATA keyword, rule [76]. return Actions.On_NDATA (Self); when 53 => -- Name of NDATA, rule [76]. return Actions.On_Name_In_Entity_Declaration_Notation (Self); when 54 => Set_String_Internal (Item => YYLVal, String => YY_Text_Internal, Is_Whitespace => False); return Token_String_Segment; when 55 => Set_String_Internal (Item => YYLVal, String => YY_Text_Internal, Is_Whitespace => False); return Token_String_Segment; when 56 => -- Close of entity value, rule [9]. return Actions.On_Entity_Value_Close_Delimiter (Self); when 57 => -- Decimal form of character reference rule [66] in entity value rule [9]; -- or content of element, rule [43]. return Actions.On_Character_Reference (Self, False); when 58 => -- Decimal form of character reference rule [66] in attribute value, -- rule [10]. if not Actions.On_Character_Reference_In_Attribute_Value (Self, False) then return Error; end if; when 59 => -- Hexadecimal form of character reference rule [66] in entity value rule -- [9] or content of element, rule [43]. return Actions.On_Character_Reference (Self, True); when 60 => -- Hexadecimal form of character reference rule [66] in attribute value, -- rule [10]. if not Actions.On_Character_Reference_In_Attribute_Value (Self, True) then return Error; end if; when 61 => -- General entity reference rule [68] in entity value rule [9]. return Actions.On_General_Entity_Reference_In_Entity_Value (Self); when 62 => -- Parameter entity reference rule [69] in entity value rule [9]. -- -- Processing of parameter entity uses separate scanner's state, thus -- after processing current state is restored automatically. This allows -- to reuse code for three modes: parsing of entity value delimited by -- quotation; parsing of entity value delimited by apostrophe; and -- parsing of parameter entity replacement text when it is referenced -- in any of two form of entity value. if not Actions.On_Parameter_Entity_Reference_In_Entity_Value (Self) then return Error; end if; when 63 => -- Name of the element in element declaration. return Actions.On_Name_In_Element_Declaration (Self); when 64 => -- EMPTY keyword, rule [46]. return Token_Empty; when 65 => -- ANY keyword, rule [46]. return Token_Any; when 66 => -- Open parenthesis, rules [49], [50], [51]. return Actions.On_Open_Parenthesis_In_Content_Declaration (Self); when 67 => -- Close parenthesis, rules [49], [50], [51]. return Actions.On_Close_Parenthesis_In_Content_Declaration (Self); when 68 => -- Question mark in rules [47], [48]. return Actions.On_Question_Mark_In_Content_Declaration (Self); when 69 => -- Asterisk in rules [47], [48], [51]. return Actions.On_Asterisk_In_Content_Declaration (Self); when 70 => -- Plus sign in rules [47], [48]. return Actions.On_Plus_In_Content_Declaration (Self); when 71 => -- Vertical bar in rule [49]. return Token_Vertical_Bar; when 72 => -- Comma in rule [50]. return Token_Comma; when 73 => -- #PCDATA in rule [51]. return Token_Pcdata; when 74 => -- Name in element's children declaration, rules [48], [51]. return Actions.On_Name_In_Element_Declaration_Children (Self); when 75 => -- Close token of entity declaration, rules [71], [72]. -- Close of element declaration, rule [45]. -- Close of attribute list declaration, rule [52]. return Actions.On_Close_Of_Declaration (Self); when 76 => -- Element's name in attribute list declaration, rule [52]. return Actions.On_Element_Name_In_Attribute_List_Declaration (Self); when 77 => -- Name of the attribute, rule [53]. return Actions.On_Attribute_Name_In_Attribute_List_Declaration (Self); when 78 => -- CDATA keyword, rule [55]. return Actions.On_Attribute_Type (Self, Token_Cdata); when 79 => -- ID keyword, rule [56]. return Actions.On_Attribute_Type (Self, Token_Id); when 80 => -- IDREF keyword, rule [56]. return Actions.On_Attribute_Type (Self, Token_Idref); when 81 => -- IDREFS keyword, rule [56]. return Actions.On_Attribute_Type (Self, Token_Idrefs); when 82 => -- ENTITY keyword, rule [56]. return Actions.On_Attribute_Type (Self, Token_Entity); when 83 => -- ENTITIES keyword, rule [56]. return Actions.On_Attribute_Type (Self, Token_Entities); when 84 => -- NMTOKEN keyword, rule [56]. return Actions.On_Attribute_Type (Self, Token_Nmtoken); when 85 => -- NMTOKENS keyword, rule [56]. return Actions.On_Attribute_Type (Self, Token_Nmtokens); when 86 => -- NOTATION keyword, rule [58]. return Actions.On_Attribute_Type (Self, Token_Notation); when 87 => -- #REQUIRED keyword, rule [60]. return Actions.On_Default_Declaration (Self, ATTLIST_DECL, Token_Required); when 88 => -- #IMPLIED keyword, rule [60]. return Actions.On_Default_Declaration (Self, ATTLIST_DECL, Token_Implied); when 89 => -- #FIXED keyword, rule [60]. return Actions.On_Default_Declaration (Self, ATTLIST_TYPE, Token_Fixed); when 90 => -- Open parenthesis, rules [58], [59]. return Actions.On_Open_Parenthesis_In_Notation_Attribute (Self); when 91 => -- Close parenthesis, rules [58], [59]. return Actions.On_Close_Parenthesis_In_Notation_Attribute (Self); when 92 => -- Vertical bar, rules [58], [59]. return Token_Vertical_Bar; when 93 => -- Name in the rule [58]. return Actions.On_Name_In_Attribute_List_Declaration_Notation (Self); when 94 => -- Nmtoken in the rule [59]. Set_String_Internal (Item => YYLVal, String => YY_Text_Internal, Is_Whitespace => False); -- XXX Need to add flag to mark Nmtoken. return Token_Name; when 95 => -- Open delimiter of attribute value, rule [10]. if not Actions.On_Attribute_Value_Open_Delimiter (Self, ATTLIST_DECL) then return Error; end if; when 96 => -- Parameter entity reference rule [69] in attribute declaration. -- Parameter entity reference in element's children declaration, [51]. if not Actions.On_Parameter_Entity_Reference_In_Markup_Declaration (Self) then return Error; end if; when 97 => -- All white spaces from rules [28] are ignored. -- Whitespace before name in rule [76] is ignored. null; when 98 => -- IGNORE directive of the conditional section. Actions.On_Conditional_Section_Directive (Self, False); when 99 => -- INCLUDE directive of the conditional section. Actions.On_Conditional_Section_Directive (Self, True); when 100 => -- Start of content of conditional section. if not Actions.On_Open_Of_Conditional_Section_Content (Self) then return Error; end if; when 101 => -- Content of ignore conditional section. It ends with "]]>" or "<![". null; when 102 => -- Content of ignore conditional section. It ends with "]]>" or "<![". null; when 103 => -- White spaces in entity declaration are not optional, rules [71], [72], -- [75], [76]. -- -- White spaces in start tag, rule [40], are ignored, but white space -- between attribute value and name of the next attribute are must be -- present. -- -- All white spaces from rules [23], [24], [25], [32], [80], [82] are -- ignored, but white space between attribute value and name of the -- next attribute are must be present. -- -- Production [45] requires whitespace after the name and before -- content specification. -- -- Productions [47], [48] don't allow spaces before multiplicity -- indicator. Set_Whitespace_Matched (Self); when 104 => -- Name of the attribute, rule [41]. return Actions.On_Name_In_Element_Start_Tag (Self); when 105 => -- Equal sign as attribute's name value delimiter, rule [25] in rules [41], -- [24], [32], [80]. return Token_Equal; when 106 => -- Close of empty element tag, rule [44]. return Actions.On_Close_Of_Empty_Element_Tag (Self); when 107 => -- Close tag of document type declaration, rule [28]. if Actions.On_Close_Of_Document_Type_Declaration (Self) then return Token_Close; end if; when 108 => -- Close of tag, rule [40]. -- Close tag of document type declaration, rule [28]. return Actions.On_Close_Of_Tag (Self); when 109 => -- Open delimiter of attribute value, rule [10]. Actions.On_Attribute_Value_Open_Delimiter (Self, ELEMENT_START); when 110 => -- Close delimiter of attribute value, rule [10]. if Actions.On_Attribute_Value_Close_Delimiter (Self) then return Token_String_Segment; end if; when 111 => -- Value of attribute, rule [10]. Actions.On_Attribute_Value_Character_Data (Self); when 112 => -- Value of attribute, rule [10]. Actions.On_Attribute_Value_Character_Data (Self); when 113 => -- Less-than sign can't be used in the attribute value. return Actions.On_Less_Than_Sign_In_Attribute_Value (Self); when 114 => -- General entity reference rule [68] in attribute value, rule [10]. if not Actions.On_General_Entity_Reference_In_Attribute_Value (Self) then return Error; end if; when 115 => -- Unexpected character. return Actions.On_Unexpected_Character (Self); pragma Style_Checks ("M79"); -- when YY_END_OF_BUFFER + INITIAL + 1 -- => -- return End_Of_Input; -- when YY_End_Of_Buffer => if Self.Scanner_State.Source /= null then -- Input source is used to retrieve data. if Is_Document_Entity (Self.Entities, Self.Scanner_State.Entity) and Self.Scanner_State.YY_Base_Position /= 0 then -- For document entity, remove already scanned data. -- Construct slice only when we actually need to move -- data. Matreshka.Internals.Strings.Operations.Slice (Self.Scanner_State.Data, Self.Scanner_State.YY_Base_Position, Self.Scanner_State.Data.Unused - Self.Scanner_State.YY_Base_Position, Self.Scanner_State.Data.Length - Self.Scanner_State.YY_Base_Index + 1); YY_Position_Offset := Self.Scanner_State.YY_Base_Position; YY_Index_Offset := Self.Scanner_State.YY_Base_Index - 1; Self.Scanner_State.YY_Base_Position := Self.Scanner_State.YY_Base_Position - YY_Position_Offset; Self.Scanner_State.YY_Base_Index := Self.Scanner_State.YY_Base_Index - YY_Index_Offset; Self.Scanner_State.YY_Current_Position := Self.Scanner_State.YY_Current_Position - YY_Position_Offset; Self.Scanner_State.YY_Current_Index := Self.Scanner_State.YY_Current_Index - YY_Index_Offset; if YY_Last_Match then YY_Last_Match_Position := YY_Last_Match_Position - YY_Position_Offset; YY_Last_Match_Index := YY_Last_Match_Index - YY_Index_Offset; end if; end if; -- Obtain next portion of data from the input source. YY_Last := Self.Scanner_State.Data.Unused; Self.Scanner_State.Source.Next (Self.Scanner_State.Data, End_Of_Source); YY_End_Of_Buffer_Action := YY_Restart_Scan; if YY_Last = Self.Scanner_State.Data.Unused then -- There is no new data retrieved, handle end of source -- state. It is possible to not reach end of source and -- retrieve no new data at the same time, for example -- when source data is mailformed and decoder unable to -- convert data. The same situtation is possible when -- some kind of filter is inserted between input source -- and actual stream (SSL/TLS encription, for example). if End_Of_Source then -- Replacement text of the entity is loaded from input -- source and need to be stored in the entities table, -- except replacement text of the document entity. -- Input source can be deallocated. if not Is_Document_Entity (Self.Entities, Self.Scanner_State.Entity) then Set_Replacement_Text (Self.Entities, Self.Scanner_State.Entity, Self.Scanner_State.Data); Free (Self.Scanner_State.Source); -- XXX Input source should not be deallocated, it -- can be needed later to reread entity when XML -- version (document entity only) or encoding is -- changed. else Self.Scanner_State.Source := null; -- Input source of document entity is managed by -- application. end if; elsif Self.Scanner_State.Incremental then YY_End_Of_Buffer_Action := YY_End_Of_Chunk; end if; end if; else -- Input source is not used, complete replacement text of -- the entity is in the scanner's buffer. This covers two -- cases: (1) entity is internal or predefined entity, and -- (2) text of the entity is loaded completely. if Self.Scanner_State.Data.Unused /= Self.Scanner_State.YY_Base_Position then -- Continue processing till end of buffer will be -- reached. YY_End_Of_Buffer_Action := YY_Accept_Last_Match; else -- Replacement text of the entity is completely scanned, -- pop scanner's entity stack. When scanner's stack is -- empty returns End_Of_Input token. if not Self.Scanner_Stack.Is_Empty then if Is_Parameter_Entity (Self.Entities, Self.Scanner_State.Entity) then -- For parameter entities start condition need to -- be propagated to previous state, otherwise -- scanner can start from the wrong condition. -- For non-parameter entities it is not needed, -- because their processing doesn't use stack of -- start conditions. YY_Start_Condition := Start_Condition (Self); -- Save flag whether or not Token_Entity_Start was -- issued. Start_Issued := Self.Scanner_State.Start_Issued; -- When entity's replacement text is empty and -- there are no text declaration, then scanner is -- in the initial state and actual state must be -- retrieved from the state stack. if YY_Start_Condition = INITIAL then Pop_Start_Condition (Self); YY_Start_Condition := Start_Condition (Self); end if; Free (Self.Scanner_State.Source); Self.Scanner_State := Self.Scanner_Stack.Last_Element; Self.Scanner_Stack.Delete_Last; Pop_Scope (Self.Bases); Enter_Start_Condition (Self, YY_Start_Condition); -- [XML 4.4.8] Included as PE -- -- "Just as with external parsed entities, -- parameter entities need only be included if -- validating. When a parameter-entity reference is -- recognized in the DTD and included, its -- replacement text MUST be enlarged by the -- attachment of one leading and one following -- space (#x20) character; the intent is to -- constrain the replacement text of parameter -- entities to contain an integral number of -- grammatical tokens in the DTD. This behavior -- MUST NOT apply to parameter entity references -- within entity values; these are described in -- 4.4.5 Included in Literal." -- -- Set Whitespace_Matched flag, it is used only -- while processing of DTD, so the place where -- parameter entity declarations are allowed. Self.Whitespace_Matched := True; -- [XML WFC: PE Between Declarations] -- -- "The replacement text of a parameter entity -- reference in a DeclSep MUST match the production -- extSubsetDecl." -- -- To check this constraint special rule is added -- in parser. To pass this rule Token_Entity_End -- must be returned when handling of parameter -- entity reference between markup declaration is -- completed. if Start_Issued then YY_End_Of_Buffer_Action := YY_Report_Entity_End; else YY_End_Of_Buffer_Action := YY_Continue_Scan; end if; elsif Self.In_Document_Content and not Self.Scanner_State.In_Literal then -- For entity references in the document content -- we need to track start/end of entity. Free (Self.Scanner_State.Source); Self.Scanner_State := Self.Scanner_Stack.Last_Element; Self.Scanner_Stack.Delete_Last; Pop_Scope (Self.Bases); YY_End_Of_Buffer_Action := YY_Report_Entity_End; else Free (Self.Scanner_State.Source); Self.Scanner_State := Self.Scanner_Stack.Last_Element; Self.Scanner_Stack.Delete_Last; Pop_Scope (Self.Bases); YY_End_Of_Buffer_Action := YY_Continue_Scan; end if; else YY_End_Of_Buffer_Action := YY_End_Of_Input; end if; end if; end if; case YY_End_Of_Buffer_Action is when YY_Continue_Scan => null; when YY_Report_Entity_End => return Token_Entity_End; when YY_Restart_Scan | YY_End_Of_Chunk => -- Back current position to base position. Self.Scanner_State.YY_Current_Position := Self.Scanner_State.YY_Base_Position; Self.Scanner_State.YY_Current_Index := Self.Scanner_State.YY_Base_Index; Self.Scanner_State.YY_Current_Line := Self.Scanner_State.YY_Base_Line; Self.Scanner_State.YY_Current_Column := Self.Scanner_State.YY_Base_Column; Self.Scanner_State.YY_Current_Skip_LF := Self.Scanner_State.YY_Base_Skip_LF; if YY_End_Of_Buffer_Action = YY_End_Of_Chunk then return End_Of_Chunk; end if; when YY_Accept_Last_Match => -- Replace current position to last matched position and -- process matched action. -- XXX: Other cases handle line/column numbers and -- "skip LF" flag also, should they be handled here? if YY_Last_Match then Self.Scanner_State.YY_Current_Position := YY_Last_Match_Position; Self.Scanner_State.YY_Current_Index := YY_Last_Match_Index; Self.Scanner_State.YY_Current_Line := YY_Last_Match_Line; Self.Scanner_State.YY_Current_Column := YY_Last_Match_Column; Self.Scanner_State.YY_Current_Skip_LF := YY_Last_Match_Skip_LF; YY_Current_State := YY_Last_Match_State; YY_Last_Match := False; else raise Program_Error; end if; goto Next_Action; when YY_End_Of_Input => return End_Of_Input; end case; when others => raise Program_Error with "Unhandled action" & Interfaces.Unsigned_32'Image (YY_Action) & " in scanner"; end case; end loop; -- end of loop waiting for end of file end YYLex; end XML.SAX.Simple_Readers.Scanner;
------------------------------------------------------------------------------ -- -- -- Simple HTTP -- -- -- -- Basic HTTP 1.1 support for API endpoints -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2021, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Richard Wai (ANNEXI-STRAYLINE) -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- -- -- * Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Ada.TexT_IO; with Simple_HTTP.RFC_3986; with Simple_HTTP.RFC_7230_7231; separate (Simple_HTTP.HTTP_Message_Processor) package body Parsers is package TIO renames Ada.Text_IO; use type Ada.Calendar.Time; CR : Character renames RFC_7230_7231.CR; LF : Character renames RFC_7230_7231.LF; CRLF: String renames RFC_7230_7231.CRLF; -- -- Utilities -- ------------------------------- -- Fetch_Skipping_Whitespace -- ------------------------------- -- Only reads up to Limit characters. -- Catches illegal CR/LF combinations -- All CRs must be followed by LF. -- Exits if CRLF is encountered, setting Got_CRLF to True. -- Status will be set to OK if no issue was encountered, or to -- Timeout or Bad_Input procedure Fetch_Skipping_Whitespace (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Deadline: in Ada.Calendar.Time; C : out Character; Got_CRLF: out Boolean; Status : out HTTP_Message_Status) with Post => (if Got_CRLF then C = LF else (Status = OK) = (not RFC_7230_7231.Is_Whitespace (C))) is use RFC_7230_7231; use type Ada.Calendar.Time; Last_Is_CR: Boolean := False; LWS_Count: Natural := 0; begin Status := OK; Got_CRLF := False; loop if Ada.Calendar.Clock > Deadline then Status := Timeout; return; end if; Character'Read (Stream, C); if (Last_Is_CR and then C /= LF) or else C = LF then -- CR should only appear immediately preceeding LF. Status := Bad_Input; return; elsif Last_Is_CR then pragma Assert (C = LF); -- Implied by the first if statement Got_CRLF := True; return; end if; exit when not Is_Whitespace (C); Last_Is_CR := (C = CR); LWS_Count := LWS_Count + 1; if LWS_Count > Whitespace_Limit then Status := Bad_Input; return; end if; end loop; end Fetch_Skipping_Whitespace; ----------------------- -- Read_HTTP_Version -- ----------------------- -- Parses an expected HTTP_Version procedure Read_HTTP_Version (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Status : out HTTP_Message_Status; Deadline: in Ada.Calendar.Time) with Post => Status in OK | Bad_Input | Bad_Version is use RFC_7230_7231; use type Ada.Calendar.Time; Expected_Version: constant String (1 .. 8) := "HTTP/1.1"; Version_Buffer : String (Expected_Version'Range); Version_OK : Boolean := False; begin Status := Bad_Input; -- First is the HTTP-Version part. We will accept any version, but -- if it is not 1.1, we will report a non-OK status for C of Version_Buffer loop Character'Read (Stream, C); if Ada.Calendar.Clock > Deadline then Status := Timeout; return; end if; end loop; if Version_Buffer /= Expected_Version then if Version_Buffer (1 .. 5) /= Expected_Version (1 .. 5) or else not Is_DIGIT (Version_Buffer (6)) or else not Is_DIGIT (Version_Buffer (8)) or else Version_Buffer (7) /= '.' then -- The format itself is wrong Status := Bad_Input; return; else -- This version is not recognized. Note and continue. Status := Bad_Version; end if; else Status := OK; end if; end Read_HTTP_Version; ------------------------- -- Read_Request_Method -- ------------------------- procedure Read_Request_Method (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Method : out RFC_7230_7231.Request_Method; Status : out HTTP_Message_Status; Deadline: in Ada.Calendar.Time) is use RFC_7230_7231; Method_Buffer: String (1 .. Request_Method_Max_Length + 1); Method_Mark : Positive := Method_Buffer'First; begin Method := OPTIONS; -- A generic method default to avoid warnings for not setting -- Method loop if Ada.Calendar.Clock > Deadline then Status := Timeout; return; end if; Character'Read (Stream, Method_Buffer(Method_Mark)); exit when Method_Buffer(Method_Mark) = SP; -- RFC 7230 says the method ends specifically with a space if Method_Buffer(Method_Mark) in CR | LF then Status := Bad_Input; return; elsif Method_Mark = Method_Buffer'Last then Status := Bad_Method; return; end if; Method_Mark := Method_Mark + 1; end loop; pragma Assert (Is_Whitespace (Method_Buffer(Method_Mark))); if Method_Mark <= Method_Buffer'First then Status := Bad_Method; return; else Method_Mark := Method_Mark - 1; end if; begin Method := Request_Method'Value (Method_Buffer (Method_Buffer'First .. Method_Mark)); exception when others => Status := Bad_Method; return; end; Status := OK; end Read_Request_Method; -- -- Implementation -- ----------------------- -- Read_Request_Line -- ----------------------- procedure Read_Request_Line (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Method : out RFC_7230_7231.Request_Method; URI : out Path_Strings.Bounded_String; Status : out HTTP_Message_Status; Deadline: in Ada.Calendar.Time) is use Path_Strings; Buffer: Character; In_Fragment: Boolean := False; Fragment_Ghost: Natural := 0; begin -- RFC 7230 states: -- request-line = method SP request-target SP HTTP-version CRLF -- -- We will adhere to this strictly. Read_Request_Method (Stream, Method, Status, Deadline); if Status /= OK then return; end if; URI := Path_Strings.Null_Bounded_String; -- We've already read-in the SP part that follows method. The next -- part is to read-in the URI until we see a space, but we'll also -- do a cursary verification the content as we go (not a semantic check). -- -- If we encounter a fragment, we will continue to verify it, but the -- fragment will not be added to the URI. loop if Ada.Calendar.Clock > Deadline then Status := Timeout; return; elsif Length (URI) = Path_Strings.Max_Length then Status := URI_Too_Long; return; end if; Character'Read (Stream, Buffer); exit when Buffer = RFC_7230_7231.SP; if (not RFC_3986.Is_unreserved (Buffer)) and then (not RFC_3986.Is_reserved (Buffer)) then Status := Bad_URI; return; elsif In_Fragment then if Fragment_Ghost >= Path_Strings.Max_Length then Status := URI_Too_Long; return; end if; Fragment_Ghost := Fragment_Ghost + 1; elsif Buffer = '#' then In_Fragment := True; Fragment_Ghost := Length (URI) + 1; -- We want to apply the same length restriction to all URIs, -- even if we discard fragments else Append (Source => URI, New_Item => Buffer); end if; end loop; if Length (URI) = 0 then Status := Bad_URI; return; end if; if Ada.Calendar.Clock > Deadline then Status := Timeout; return; end if; -- HTTP version. This shall be followed immediately with CRLF Read_HTTP_Version (Stream, Status, Deadline); if Status not in OK | Bad_Version then return; end if; if Character'Input (Stream) /= CR then Status := Bad_Input; return; end if; if Ada.Calendar.Clock > Deadline then Status := Timeout; return; end if; if Character'Input (Stream) /= LF then Status := Bad_Input; return; end if; -- If we got this far, it seems to check-out. Status should be OK from -- the original call to Read_Request_Method, or Bad_Version if the -- http-version line was not indicating 1.1 pragma Assert (Status in OK | Bad_Version); end Read_Request_Line; ---------------------- -- Read_Status_Line -- ---------------------- procedure Read_Status_Line (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Code : out RFC_7230_7231.Response_Status; Phrase : out Phrase_Strings.Bounded_String; Status : out HTTP_Message_Status; Deadline: in Ada.Calendar.Time) is use RFC_7230_7231; Status_Code_Buffer: String (1 .. 3); Version_OK: Boolean; begin -- Avoid warnings for out parameters by setting some sane "defaults" Code := 400; -- "Bad Request"; Phrase := Phrase_Strings.Null_Bounded_String; -- http-version + SP Read_HTTP_Version (Stream, Status, Deadline); Version_OK := (Status = OK); if Status not in OK | Bad_Version then return; elsif Character'Input (Stream) /= RFC_7230_7231.SP then Status := Bad_Input; return; elsif Ada.Calendar.Clock > Deadline then Status := Timeout; return; end if; -- Next is the status code. RFC 7230 specifies that the status code is -- always exactly 3 digits. for C of Status_Code_Buffer loop Character'Read (Stream, C); if Ada.Calendar.Clock > Deadline then Status := Timeout; return; elsif not Is_DIGIT (C) then Status := Bad_Status; return; end if; end loop; begin Code := Response_Status'Value (Status_Code_Buffer); exception when others => Status := Bad_Status; return; end; -- RFC 7230-3.1.2 says that clients "SHOULD" ignore the reason-phrase -- content - so we won't actually require anything to be there, but -- if there is something, we'll still verify the content Phrase := Phrase_Strings.Null_Bounded_String; declare C: Character; Started: Boolean := False; begin loop Character'Read (Stream, C); if Ada.Calendar.Clock > Deadline then Status := Timeout; return; elsif C = CR then -- LF must follow. Character'Read (Stream, C); if C = LF then exit; else Status := Bad_Status; return; end if; elsif not Started and then C = SP then -- We don't want to include the first space following the -- status-code to be included in the reason phrase, however -- pretty much everything else is Started := True; elsif not Is_VCHAR (C) and then C not in HT | SP and then not Is_obs_text (C) then -- Invalid content according to RFC 7230-3.1.2 Status := Bad_Status; return; elsif Phrase_Strings.Length (Phrase) = Phrase_Strings.Max_Length then -- Out of room Status := Bad_Status; return; else -- Checks-out Phrase_Strings.Append (Source => Phrase, New_Item => C); end if; end loop; end; pragma Assert (Status = OK); if not Version_OK then Status := Bad_Version; end if; end Read_Status_Line; ------------------ -- Load_Headers -- ------------------ procedure Load_Headers (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Target : in out Header_Set; Status : out HTTP_Message_Status; Deadline: in Ada.Calendar.Time) is use RFC_7230_7231; use type Ada.Containers.Count_Type; procedure Load_One_Header (Lead_Character: Character) is Buffer : Character; Got_CRLF : Boolean := True; Last_Was_Whitespace: Boolean := False; New_Header: HTTP_Header; Field_In: Field_Strings.Bounded_String renames New_Header.Field; Value_In: Value_Strings.Bounded_String renames New_Header.Value; begin -- Load the Field Buffer := Lead_Character; while Buffer not in ':' loop if Field_Strings.Length (Field_In) = Field_Strings.Max_Length then Status := Header_Field_Too_Long; return; elsif not Is_Token (Buffer) then Status := Bad_Header; return; else Field_Strings.Append (Source => Field_In, New_Item => Buffer); end if; Character'Read (Stream, Buffer); if Ada.Calendar.Clock > Deadline then Status := Timeout; return; end if; end loop; if Field_Strings.Length (Field_In) = 0 then -- This would indicate that there was no field name, which of -- course is not legal Status := Bad_Header; return; end if; -- Now the field value can be separated by "optional whitespace -- (OWS)", which could be any amount of whitespace, but not a CR/LF Fetch_Skipping_Whitespace (Stream => Stream, Deadline => Deadline, C => Buffer, Got_CRLF => Got_CRLF, Status => Status); if Status /= OK then return; elsif Got_CRLF then -- This would mean no value Status := Bad_Header; return; end if; -- Load the value loop if Buffer = CR then Character'Read (Stream, Buffer); if Buffer = LF then exit; else Status := Bad_Header; return; end if; elsif Value_Strings.Length (Value_In) = Value_Strings.Max_Length then Status := Header_Value_Too_Long; return; elsif Buffer in SP | HT then if Last_Was_Whitespace then -- RFC 7230 3.2 only allows a single space/tab Status := Bad_Header; return; else Last_Was_Whitespace := True; end if; elsif Is_VCHAR (Buffer) or else Is_obs_text (Buffer) then -- This is fine Last_Was_Whitespace := False; end if; Value_Strings.Append (Source => Value_In, New_Item => Buffer); Character'Read (Stream, Buffer); if Ada.Calendar.Clock > Deadline then Status := Timeout; return; end if; end loop; -- We should now have a valid header which we can then pass to -- the specialed Internal_Add_Header subprogram, which will take -- care of the rest Internal_Add_Header (Target => Target, Header => New_Header, Status => Status); end Load_One_Header; begin Status := OK; while Status = OK loop declare Lead: constant Character := Character'Input (Stream); begin exit when Lead = CR and then Character'Input (Stream) = LF; Load_One_Header (Lead_Character => Lead); end; if Ada.Calendar.Clock > Deadline then Status := Timeout; return; end if; end loop; end Load_Headers; end Parsers;
----------------------------------------------------------------------- -- measures -- Example of Runtime Benchmark -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Util.Measures; -- -- This example performs several measures and dumps the result. -- The result produced by <b>Util.Measures.Write</b> looks like: -- -- <measures title="Example of measures"> -- <time count="1000" time="406.000000000us" title="Empty"/> -- <time count="2" time="34.000000000us" title="Ada.Text_IO.Put_Line"/> -- <time count="1" time="413.000000000us" -- title="No tracking Empty procedure called 1000 times"/> -- <time count="1" time="1.960000000ms" -- title="Tracking Empty procedure called 1000 times"/> -- </measures> -- -- 'Empty' is called 1000 times for a total time of 406us (or 406ns per call). procedure Measures is procedure Print; procedure Empty; Perf : Util.Measures.Measure_Set; procedure Print is S : Util.Measures.Stamp; begin Ada.Text_IO.Put_Line ("Print test benchmark"); Util.Measures.Report (Perf, S, "Ada.Text_IO.Put_Line"); end Print; procedure Empty is S : Util.Measures.Stamp; begin Util.Measures.Report (Perf, S, "Empty"); end Empty; begin Print; Print; -- Measure time for calling 'Empty' 1000 times declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Empty; end loop; Util.Measures.Report (Perf, S, "Tracking Empty procedure called 1000 times"); end; -- Disable measures (the next calls will not be counted) Util.Measures.Disable (Perf); Print; Print; -- Measure time for calling 'Empty' 1000 times with performance tracking OFF. declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Empty; end loop; -- Enable measures again to track Util.Measures.Enable (Perf); Util.Measures.Report (Perf, S, "No tracking Empty procedure called 1000 times"); end; -- Dump the result Util.Measures.Write (Perf, "Example of measures", Ada.Text_IO.Standard_Output); end Measures;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Containers.Vectors; with Program.Compilation_Unit_Vectors; package Program.Units.Vectors is pragma Preelaborate; type Unit_Vector is limited new Program.Compilation_Unit_Vectors.Compilation_Unit_Vector with private; procedure Clear (Self : in out Unit_Vector); procedure Append (Self : in out Unit_Vector; Value : not null Program.Compilation_Units.Compilation_Unit_Access); private package Unit_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Program.Compilation_Units.Compilation_Unit_Access, "=" => Program.Compilation_Units."="); type Unit_Vector is limited new Program.Compilation_Unit_Vectors.Compilation_Unit_Vector with record Data : Unit_Vectors.Vector; end record; overriding function Get_Length (Self : Unit_Vector) return Positive; overriding function Element (Self : Unit_Vector; Index : Positive) return not null Program.Compilation_Units.Compilation_Unit_Access; overriding function Find_Unit (Self : Unit_Vector; Name : Text) return Program.Compilation_Units.Compilation_Unit_Access; end Program.Units.Vectors;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . I N I T -- -- -- -- S p e c -- -- -- -- Copyright (C) 2003-2021, 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. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by AdaCore. -- -- -- ------------------------------------------------------------------------------ -- This unit contains initialization circuits that are system dependent -- This package is for use with configurable runtimes, and replaces init.c pragma Restrictions (No_Elaboration_Code); -- The procedure Install_Handler is called by the binder generated file before -- any elaboration code, so we use the No_Elaboration_Code restriction to be -- enfore full static preelaboration. package System.Init is pragma Preelaborate; procedure Install_Handler; pragma Export (C, Install_Handler, "__gnat_install_handler"); -- Install signal handlers. This procedure is called by Runtime_Initialize, -- but it may also be called by the tasking runtime when a task is created. procedure Runtime_Initialize (Install_Handler : Integer); pragma Export (C, Runtime_Initialize, "__gnat_runtime_initialize"); -- This procedure is called by adainit before the elaboration of other -- units. It usually installs handler for the synchronous signals. The C -- profile here is what is expected by the binder-generated main. procedure Runtime_Finalize; pragma Export (C, Runtime_Finalize, "__gnat_runtime_finalize"); -- This procedure is called by adafinal. private ----------------------------- -- Binder Generated Values -- ----------------------------- Gl_Leap_Seconds_Support : Integer := 0; pragma Export (C, Gl_Leap_Seconds_Support, "__gl_leap_seconds_support"); Gl_Time_Slice_Val : Integer := -1; pragma Export (C, Gl_Time_Slice_Val, "__gl_time_slice_val"); Gl_Wc_Encoding : Character := 'n'; pragma Export (C, Gl_Wc_Encoding, "__gl_wc_encoding"); Gl_Locking_Policy : Character := ' '; pragma Export (C, Gl_Locking_Policy, "__gl_locking_policy"); Gl_Queuing_Policy : Character := ' '; pragma Export (C, Gl_Queuing_Policy, "__gl_queuing_policy"); Gl_Task_Dispatching_Policy : Character := ' '; pragma Export (C, Gl_Task_Dispatching_Policy, "__gl_task_dispatching_policy"); Gl_Priority_Specific_Dispatching : Address := Null_Address; pragma Export (C, Gl_Priority_Specific_Dispatching, "__gl_priority_specific_dispatching"); Gl_Num_Specific_Dispatching : Integer := 0; pragma Export (C, Gl_Num_Specific_Dispatching, "__gl_num_specific_dispatching"); Gl_Restrictions : Address := Null_Address; pragma Export (C, Gl_Restrictions, "__gl_restrictions"); Gl_Interrupt_States : Address := Null_Address; pragma Export (C, Gl_Interrupt_States, "__gl_interrupt_states"); Gl_Num_Interrupt_States : Integer := 0; pragma Export (C, Gl_Num_Interrupt_States, "__gl_num_interrupt_states"); Gl_Unreserve_All_Interrupts : Integer := 0; pragma Export (C, Gl_Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts"); Gl_Exception_Tracebacks : Integer := 0; pragma Export (C, Gl_Exception_Tracebacks, "__gl_exception_tracebacks"); Gl_Exception_Tracebacks_Symbolic : Integer := 0; pragma Export (C, Gl_Exception_Tracebacks_Symbolic, "__gl_exception_tracebacks_symbolic"); Gl_Detect_Blocking : Integer := 0; pragma Export (C, Gl_Detect_Blocking, "__gl_detect_blocking"); Gl_Default_Stack_Size : Integer := 0; pragma Export (C, Gl_Default_Stack_Size, "__gl_default_stack_size"); Gl_Bind_Env_Addr : Address := Null_Address; pragma Export (C, Gl_Bind_Env_Addr, "__gl_bind_env_addr"); Gl_XDR_Stream : Integer := 0; pragma Export (C, Gl_XDR_Stream, "__gl_xdr_stream"); Gl_Time_T_is_32_Bits : Integer := 0; pragma Export (C, Gl_Time_T_is_32_Bits, "__gl_time_t_is_32_bits"); -- The following two variables are deliberately commented out. They are -- referenced by the binder generated file, but they cannot be shared among -- different versions of System.Init. The reason is that the ravenscar -- version of System.Tasking (s-taskin-raven.adb) redefines these variables -- because the ravenscar/sfp runtime doesn't use System.Init, while the -- ravenscar/full runtime does. -- Gl_Main_Priority : Integer := -1; -- pragma Export (C, Gl_Main_Priority, "__gl_main_priority"); -- Gl_Main_CPU : Integer := -1; -- pragma Export (C, Gl_Main_CPU, "__gl_main_cpu"); end System.Init;
-- C45651A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- FOR FIXED POINT TYPES, CHECK: -- (A) FOR MODEL NUMBERS A >= 0.0, THAT ABS A = A. -- (B) FOR MODEL NUMBERS A <= 0.0. THAT ABS A = -A. -- (C) FOR NON-MODEL NUMBERS A > 0.0, THAT ABS A VALUES ARE -- WITHIN THE APPROPRIATE MODEL INTERVAL. -- (D) FOR NON-MODEL NUMBERS A < 0.0, THAT ABS A VALUES ARE -- WITHIN THE APPROPRIATE MODEL INTERVAL. -- CASE A: BASIC TYPES THAT FIT THE CHARACTERISTICS OF -- DURATION'BASE. -- HISTORY: -- WRG 9/11/86 -- PWB 3/31/88 CHANGED RANGE FOR MEMBERSHIP TEST INVOLVING -- ABS (DECIMAL_M4'FIRST + DECIMAL_M4'SMALL / 2). -- RJW 8/21/89 REMOVED CHECKS INVOLVING HARD-CODED FIXED-POINT -- UPPER BOUNDS WHICH WERE INCORRECT FOR SOME -- IMPLEMENTATIONS. REVISED HEADER. -- PWN 02/02/95 REMOVED INCONSISTENCIES WITH ADA 9X. -- KAS 11/14/95 REMOVED CASES THAT DEPEND ON SPECIFIC VALUE FOR 'SMALL -- TMB 11/19/94 REMOVED CASES RELATING TO 3.5.9(8) RULES - SMALL -- MAY BE LESS THAN OR EQUAL TO DELTA FOR FIXED POINT. WITH REPORT; USE REPORT; PROCEDURE C45651A IS -- THE NAME OF EACH TYPE OR SUBTYPE ENDS WITH THAT TYPE'S -- 'MANTISSA VALUE. BEGIN TEST ("C45651A", "CHECK THAT, FOR FIXED POINT TYPES, THE ABS " & "OPERATOR PRODUCES CORRECT RESULTS - BASIC " & "TYPES"); ------------------------------------------------------------------- A: DECLARE TYPE LIKE_DURATION_M23 IS DELTA 0.020 RANGE -86_400.0 .. 86_400.0; NON_MODEL_CONST : CONSTANT := 2.0 / 3; NON_MODEL_VAR : LIKE_DURATION_M23 := 0.0; SMALL, MAX, MIN, ZERO : LIKE_DURATION_M23 := 0.5; X : LIKE_DURATION_M23 := 1.0; BEGIN -- INITIALIZE "CONSTANTS": IF EQUAL (3, 3) THEN SMALL := LIKE_DURATION_M23'SMALL; MAX := LIKE_DURATION_M23'LAST; MIN := LIKE_DURATION_M23'FIRST; ZERO := 0.0; NON_MODEL_VAR := NON_MODEL_CONST; END IF; -- (A) IF EQUAL (3, 3) THEN X := SMALL; END IF; IF ABS X /= SMALL OR X /= ABS LIKE_DURATION_M23'SMALL THEN FAILED ("ABS (1.0 / 64) /= (1.0 / 64)"); END IF; IF EQUAL (3, 3) THEN X := MAX; END IF; IF ABS X /= MAX OR X /= ABS LIKE_DURATION_M23'LAST THEN FAILED ("ABS 86_400.0 /= 86_400.0"); END IF; -- (B) IF EQUAL (3, 3) THEN X := -SMALL; END IF; IF ABS X /= SMALL OR ABS (-LIKE_DURATION_M23'SMALL) /= SMALL THEN FAILED ("ABS -(1.0 / 64) /= (1.0 / 64)"); END IF; IF EQUAL (3, 3) THEN X := MIN; END IF; IF ABS X /= MAX OR ABS LIKE_DURATION_M23'FIRST /= MAX THEN FAILED ("ABS -86_400.0 /= 86_400.0"); END IF; -- (A) AND (B) IF EQUAL (3, 3) THEN X := 0.0; END IF; IF "ABS" (RIGHT => X) /= ZERO OR X /= ABS 0.0 THEN FAILED ("ABS 0.0 /= 0.0 -- (LIKE_DURATION_M23)"); END IF; -- CHECK THAT VALUE OF NON_MODEL_VAR IS IN THE RANGE -- 42 * 'SMALL .. 43 * 'SMALL: IF NON_MODEL_VAR NOT IN 0.65625 .. 0.671875 THEN FAILED ("VALUE OF NON_MODEL_VAR NOT IN CORRECT RANGE " & "- A"); END IF; -- (C) IF ABS NON_MODEL_VAR NOT IN 0.65625 .. 0.671875 OR ABS LIKE_DURATION_M23'(NON_MODEL_CONST) NOT IN 0.65625 .. 0.671875 THEN FAILED ("ABS (2.0 / 3) NOT IN CORRECT RANGE - A"); END IF; IF EQUAL (3, 3) THEN X := 86_399.992_187_5; -- LIKE_DURATION_M23'LAST - -- 1.0 / 128. END IF; IF ABS X NOT IN 86_399.984_375 .. 86_400.0 OR ABS (LIKE_DURATION_M23'LAST - LIKE_DURATION_M23'SMALL / 2) NOT IN 86_399.984_375 .. 86_400.0 THEN FAILED ("ABS (LIKE_DURATION_M23'LAST - " & "LIKE_DURATION_M23'SMALL / 2) NOT IN CORRECT " & "RANGE"); END IF; -- (D) IF EQUAL (3, 3) THEN X := -NON_MODEL_CONST; END IF; IF ABS X NOT IN 0.65625 .. 0.671875 OR ABS (-LIKE_DURATION_M23'(NON_MODEL_CONST)) NOT IN 0.65625 .. 0.671875 THEN FAILED ("ABS (-2.0 / 3) NOT IN CORRECT RANGE - A"); END IF; IF EQUAL (3, 3) THEN X := -86_399.992_187_5; -- LIKE_DURATION_M23'FIRST + -- 1.0 / 128. END IF; IF ABS X NOT IN 86_399.984_375 .. 86_400.0 OR ABS (LIKE_DURATION_M23'FIRST + LIKE_DURATION_M23'SMALL / 2) NOT IN 86_399.984_375 .. 86_400.0 THEN FAILED ("ABS (LIKE_DURATION_M23'FIRST +" & "LIKE_DURATION_M23'SMALL / 2) NOT IN CORRECT " & "RANGE"); END IF; END A; ------------------------------------------------------------------- B: DECLARE TYPE DECIMAL_M4 IS DELTA 100.0 RANGE -1000.0 .. 1000.0; NON_MODEL_CONST : CONSTANT := 2.0 / 3; NON_MODEL_VAR : DECIMAL_M4 := 0.0; SMALL, MAX, MIN, ZERO : DECIMAL_M4 := 128.0; X : DECIMAL_M4 := 0.0; BEGIN -- INITIALIZE "CONSTANTS": IF EQUAL (3, 3) THEN SMALL := DECIMAL_M4'SMALL; ZERO := 0.0; NON_MODEL_VAR := NON_MODEL_CONST; END IF; -- (A) IF EQUAL (3, 3) THEN X := SMALL; END IF; IF ABS X /= SMALL OR X /= ABS DECIMAL_M4'SMALL THEN FAILED ("ABS 64.0 /= 64.0"); END IF; -- (B) IF EQUAL (3, 3) THEN X := -SMALL; END IF; IF ABS X /= SMALL OR ABS (-DECIMAL_M4'SMALL) /= SMALL THEN FAILED ("ABS -64.0 /= 64.0"); END IF; -- (A) AND (B) IF EQUAL (3, 3) THEN X := 0.0; END IF; IF ABS X /= ZERO OR X /= ABS 0.0 THEN FAILED ("ABS 0.0 /= 0.0 -- (DECIMAL_M4)"); END IF; -- CHECK THE VALUE OF NON_MODEL_VAR: IF NON_MODEL_VAR NOT IN 0.0 .. 64.0 THEN FAILED ("VALUE OF NON_MODEL_VAR NOT IN CORRECT RANGE " & "- B"); END IF; -- (C) IF ABS NON_MODEL_VAR NOT IN 0.0 .. 64.0 OR ABS DECIMAL_M4'(NON_MODEL_CONST) NOT IN 0.0 .. 64.0 THEN FAILED ("ABS (2.0 / 3) NOT IN CORRECT RANGE - B"); END IF; IF EQUAL (3, 3) THEN X := 37.0; -- INTERVAL IS 0.0 .. 64.0. END IF; IF EQUAL (3, 3) THEN X := 928.0; END IF; -- (D) IF EQUAL (3, 3) THEN X := -NON_MODEL_CONST; END IF; IF ABS X NOT IN 0.0 .. 64.0 OR ABS (-DECIMAL_M4'(NON_MODEL_CONST)) NOT IN 0.0 .. 64.0 THEN FAILED ("ABS -(2.0 / 3) NOT IN CORRECT RANGE - B"); END IF; IF EQUAL (3, 3) THEN X := -37.0; -- INTERVAL IS -SMALL .. 0.0. END IF; IF EQUAL (3, 3) THEN X := -928.0; END IF; END B; ------------------------------------------------------------------- RESULT; END C45651A;
with System; with Interfaces.C; package STB.Image is function Load (Filename : String; X, Y, Channels_In_File : out Interfaces.C.int; Desired_Channels : Interfaces.C.int) return System.Address; function Write_PNG (Filename : String; W, H, Channels : Interfaces.C.int; Data : System.Address; Len : Interfaces.C.int) return Interfaces.C.int; end STB.Image;
------------------------------------------------------------------------------ -- -- -- GNAT RUNTIME COMPONENTS -- -- -- -- A D A . S T R I N G S . W I D E _ B O U N D E D -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Strings.Wide_Maps; use Ada.Strings.Wide_Maps; with Ada.Strings.Wide_Search; package body Ada.Strings.Wide_Bounded is package body Generic_Bounded_Length is --------- -- "&" -- --------- function "&" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; Rlen : constant Length_Range := Right.Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen > Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Nlen; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Nlen) := Right.Data (1 .. Rlen); end if; return Result; end "&"; function "&" (Left : in Bounded_Wide_String; Right : in Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; Nlen : constant Natural := Llen + Right'Length; begin if Nlen > Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Nlen; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Nlen) := Right; end if; return Result; end "&"; function "&" (Left : in Wide_String; Right : in Bounded_Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left'Length; Rlen : constant Length_Range := Right.Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen > Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Nlen; Result.Data (1 .. Llen) := Left; Result.Data (Llen + 1 .. Nlen) := Right.Data (1 .. Rlen); end if; return Result; end "&"; function "&" (Left : in Bounded_Wide_String; Right : in Wide_Character) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; begin if Llen = Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Llen + 1; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Result.Length) := Right; end if; return Result; end "&"; function "&" (Left : in Wide_Character; Right : in Bounded_Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Rlen : Length_Range := Right.Length; begin if Rlen = Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Rlen + 1; Result.Data (1) := Left; Result.Data (2 .. Result.Length) := Right.Data (1 .. Rlen); end if; return Result; end "&"; --------- -- "*" -- --------- function "*" (Left : in Natural; Right : in Wide_Character) return Bounded_Wide_String is Result : Bounded_Wide_String; begin if Left > Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Left; for J in 1 .. Left loop Result.Data (J) := Right; end loop; end if; return Result; end "*"; function "*" (Left : in Natural; Right : in Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Pos : Positive := 1; Rlen : constant Natural := Right'Length; Nlen : constant Natural := Left * Rlen; begin if Nlen > Max_Length then raise Ada.Strings.Index_Error; else Result.Length := Nlen; if Nlen > 0 then for J in 1 .. Left loop Result.Data (Pos .. Pos + Rlen - 1) := Right; Pos := Pos + Rlen; end loop; end if; end if; return Result; end "*"; function "*" (Left : in Natural; Right : in Bounded_Wide_String) return Bounded_Wide_String is Result : Bounded_Wide_String; Pos : Positive := 1; Rlen : constant Length_Range := Right.Length; Nlen : constant Natural := Left * Rlen; begin if Nlen > Max_Length then raise Ada.Strings.Length_Error; else Result.Length := Nlen; if Nlen > 0 then for J in 1 .. Left loop Result.Data (Pos .. Pos + Rlen - 1) := Right.Data (1 .. Rlen); Pos := Pos + Rlen; end loop; end if; end if; return Result; end "*"; --------- -- "<" -- --------- function "<" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) < Right.Data (1 .. Right.Length); end "<"; function "<" (Left : in Bounded_Wide_String; Right : in Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) < Right; end "<"; function "<" (Left : in Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left < Right.Data (1 .. Right.Length); end "<"; ---------- -- "<=" -- ---------- function "<=" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) <= Right.Data (1 .. Right.Length); end "<="; function "<=" (Left : in Bounded_Wide_String; Right : in Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) <= Right; end "<="; function "<=" (Left : in Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left <= Right.Data (1 .. Right.Length); end "<="; --------- -- "=" -- --------- function "=" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left.Length = Right.Length and then Left.Data (1 .. Left.Length) = Right.Data (1 .. Right.Length); end "="; function "=" (Left : in Bounded_Wide_String; Right : in Wide_String) return Boolean is begin return Left.Length = Right'Length and then Left.Data (1 .. Left.Length) = Right; end "="; function "=" (Left : in Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left'Length = Right.Length and then Left = Right.Data (1 .. Right.Length); end "="; --------- -- ">" -- --------- function ">" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) > Right.Data (1 .. Right.Length); end ">"; function ">" (Left : in Bounded_Wide_String; Right : in Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) > Right; end ">"; function ">" (Left : in Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left > Right.Data (1 .. Right.Length); end ">"; ---------- -- ">=" -- ---------- function ">=" (Left : in Bounded_Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) >= Right.Data (1 .. Right.Length); end ">="; function ">=" (Left : in Bounded_Wide_String; Right : in Wide_String) return Boolean is begin return Left.Data (1 .. Left.Length) >= Right; end ">="; function ">=" (Left : in Wide_String; Right : in Bounded_Wide_String) return Boolean is begin return Left >= Right.Data (1 .. Right.Length); end ">="; ------------ -- Append -- ------------ -- Case of Bounded_Wide_String and Bounded_Wide_String function Append (Left, Right : in Bounded_Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; Rlen : constant Length_Range := Right.Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen <= Max_Length then Result.Length := Nlen; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Nlen) := Right.Data (1 .. Rlen); else Result.Length := Max_Length; case Drop is when Strings.Right => if Llen >= Max_Length then -- only case is Llen = Max_Length Result.Data := Right.Data; else Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Max_Length) := Right.Data (1 .. Max_Length - Llen); end if; when Strings.Left => if Rlen >= Max_Length then -- only case is Rlen = Max_Length Result.Data := Right.Data; else Result.Data (1 .. Max_Length - Rlen) := Left.Data (Llen - (Max_Length - Rlen - 1) .. Llen); Result.Data (Max_Length - Rlen + 1 .. Max_Length) := Right.Data (1 .. Rlen); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Append; procedure Append (Source : in out Bounded_Wide_String; New_Item : in Bounded_Wide_String; Drop : in Truncation := Error) is Llen : constant Length_Range := Source.Length; Rlen : constant Length_Range := New_Item.Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen <= Max_Length then Source.Length := Nlen; Source.Data (Llen + 1 .. Nlen) := New_Item.Data (1 .. Rlen); else Source.Length := Max_Length; case Drop is when Strings.Right => if Llen < Max_Length then Source.Data (Llen + 1 .. Max_Length) := New_Item.Data (1 .. Max_Length - Llen); end if; when Strings.Left => if Rlen >= Max_Length then -- only case is Rlen = Max_Length Source.Data := New_Item.Data; else Source.Data (1 .. Max_Length - Rlen) := Source.Data (Llen - (Max_Length - Rlen - 1) .. Llen); Source.Data (Max_Length - Rlen + 1 .. Max_Length) := New_Item.Data (1 .. Rlen); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Append; -- Case of Bounded_Wide_String and Wide_String function Append (Left : in Bounded_Wide_String; Right : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; Rlen : constant Length_Range := Right'Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen <= Max_Length then Result.Length := Nlen; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Nlen) := Right; else Result.Length := Max_Length; case Drop is when Strings.Right => if Llen >= Max_Length then -- only case is Llen = Max_Length Result.Data := Left.Data; else Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1 .. Max_Length) := Right (Right'First .. Right'First - 1 + Max_Length - Llen); end if; when Strings.Left => if Rlen >= Max_Length then Result.Data (1 .. Max_Length) := Right (Right'Last - (Max_Length - 1) .. Right'Last); else Result.Data (1 .. Max_Length - Rlen) := Left.Data (Llen - (Max_Length - Rlen - 1) .. Llen); Result.Data (Max_Length - Rlen + 1 .. Max_Length) := Right; end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Append; procedure Append (Source : in out Bounded_Wide_String; New_Item : in Wide_String; Drop : in Truncation := Error) is Llen : constant Length_Range := Source.Length; Rlen : constant Length_Range := New_Item'Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen <= Max_Length then Source.Length := Nlen; Source.Data (Llen + 1 .. Nlen) := New_Item; else Source.Length := Max_Length; case Drop is when Strings.Right => if Llen < Max_Length then Source.Data (Llen + 1 .. Max_Length) := New_Item (New_Item'First .. New_Item'First - 1 + Max_Length - Llen); end if; when Strings.Left => if Rlen >= Max_Length then Source.Data (1 .. Max_Length) := New_Item (New_Item'Last - (Max_Length - 1) .. New_Item'Last); else Source.Data (1 .. Max_Length - Rlen) := Source.Data (Llen - (Max_Length - Rlen - 1) .. Llen); Source.Data (Max_Length - Rlen + 1 .. Max_Length) := New_Item; end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Append; -- Case of Wide_String and Bounded_Wide_String function Append (Left : in Wide_String; Right : in Bounded_Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left'Length; Rlen : constant Length_Range := Right.Length; Nlen : constant Natural := Llen + Rlen; begin if Nlen <= Max_Length then Result.Length := Nlen; Result.Data (1 .. Llen) := Left; Result.Data (Llen + 1 .. Llen + Rlen) := Right.Data (1 .. Rlen); else Result.Length := Max_Length; case Drop is when Strings.Right => if Llen >= Max_Length then Result.Data (1 .. Max_Length) := Left (Left'First .. Left'First + (Max_Length - 1)); else Result.Data (1 .. Llen) := Left; Result.Data (Llen + 1 .. Max_Length) := Right.Data (1 .. Max_Length - Llen); end if; when Strings.Left => if Rlen >= Max_Length then Result.Data (1 .. Max_Length) := Right.Data (Rlen - (Max_Length - 1) .. Rlen); else Result.Data (1 .. Max_Length - Rlen) := Left (Left'Last - (Max_Length - Rlen - 1) .. Left'Last); Result.Data (Max_Length - Rlen + 1 .. Max_Length) := Right.Data (1 .. Rlen); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Append; -- Case of Bounded_Wide_String and Wide_Character function Append (Left : in Bounded_Wide_String; Right : in Wide_Character; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Llen : constant Length_Range := Left.Length; begin if Llen < Max_Length then Result.Length := Llen + 1; Result.Data (1 .. Llen) := Left.Data (1 .. Llen); Result.Data (Llen + 1) := Right; return Result; else case Drop is when Strings.Right => return Left; when Strings.Left => Result.Length := Max_Length; Result.Data (1 .. Max_Length - 1) := Left.Data (2 .. Max_Length); Result.Data (Max_Length) := Right; return Result; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Append; procedure Append (Source : in out Bounded_Wide_String; New_Item : in Wide_Character; Drop : in Truncation := Error) is Llen : constant Length_Range := Source.Length; begin if Llen < Max_Length then Source.Length := Llen + 1; Source.Data (Llen + 1) := New_Item; else Source.Length := Max_Length; case Drop is when Strings.Right => null; when Strings.Left => Source.Data (1 .. Max_Length - 1) := Source.Data (2 .. Max_Length); Source.Data (Max_Length) := New_Item; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Append; -- Case of Wide_Character and Bounded_Wide_String function Append (Left : in Wide_Character; Right : in Bounded_Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Rlen : constant Length_Range := Right.Length; begin if Rlen < Max_Length then Result.Length := Rlen + 1; Result.Data (1) := Left; Result.Data (2 .. Rlen + 1) := Right.Data (1 .. Rlen); return Result; else case Drop is when Strings.Right => Result.Length := Max_Length; Result.Data (1) := Left; Result.Data (2 .. Max_Length) := Right.Data (1 .. Max_Length - 1); return Result; when Strings.Left => return Right; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Append; ----------- -- Count -- ----------- function Count (Source : in Bounded_Wide_String; Pattern : in Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity) return Natural is begin return Wide_Search.Count (Source.Data (1 .. Source.Length), Pattern, Mapping); end Count; function Count (Source : in Bounded_Wide_String; Pattern : in Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping_Function) return Natural is begin return Wide_Search.Count (Source.Data (1 .. Source.Length), Pattern, Mapping); end Count; function Count (Source : in Bounded_Wide_String; Set : in Wide_Maps.Wide_Character_Set) return Natural is begin return Wide_Search.Count (Source.Data (1 .. Source.Length), Set); end Count; ------------ -- Delete -- ------------ function Delete (Source : in Bounded_Wide_String; From : in Positive; Through : in Natural) return Bounded_Wide_String is Slen : constant Natural := Source.Length; Num_Delete : constant Integer := Through - From + 1; Result : Bounded_Wide_String; begin if Num_Delete <= 0 then return Source; elsif From > Slen + 1 then raise Ada.Strings.Index_Error; elsif Through >= Slen then Result.Length := From - 1; Result.Data (1 .. From - 1) := Source.Data (1 .. From - 1); return Result; else Result.Length := Slen - Num_Delete; Result.Data (1 .. From - 1) := Source.Data (1 .. From - 1); Result.Data (From .. Result.Length) := Source.Data (Through + 1 .. Slen); return Result; end if; end Delete; procedure Delete (Source : in out Bounded_Wide_String; From : in Positive; Through : in Natural) is Slen : constant Natural := Source.Length; Num_Delete : constant Integer := Through - From + 1; begin if Num_Delete <= 0 then return; elsif From > Slen + 1 then raise Ada.Strings.Index_Error; elsif Through >= Slen then Source.Length := From - 1; else Source.Length := Slen - Num_Delete; Source.Data (From .. Source.Length) := Source.Data (Through + 1 .. Slen); end if; end Delete; ------------- -- Element -- ------------- function Element (Source : in Bounded_Wide_String; Index : in Positive) return Wide_Character is begin if Index in 1 .. Source.Length then return Source.Data (Index); else raise Strings.Index_Error; end if; end Element; ---------------- -- Find_Token -- ---------------- procedure Find_Token (Source : in Bounded_Wide_String; Set : in Wide_Maps.Wide_Character_Set; Test : in Strings.Membership; First : out Positive; Last : out Natural) is begin Wide_Search.Find_Token (Source.Data (1 .. Source.Length), Set, Test, First, Last); end Find_Token; ---------- -- Head -- ---------- function Head (Source : in Bounded_Wide_String; Count : in Natural; Pad : in Wide_Character := Wide_Space; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Slen : constant Natural := Source.Length; Npad : constant Integer := Count - Slen; begin if Npad <= 0 then Result.Length := Count; Result.Data (1 .. Count) := Source.Data (1 .. Count); elsif Count <= Max_Length then Result.Length := Count; Result.Data (1 .. Slen) := Source.Data (1 .. Slen); Result.Data (Slen + 1 .. Count) := (others => Pad); else Result.Length := Max_Length; case Drop is when Strings.Right => Result.Data (1 .. Slen) := Source.Data (1 .. Slen); Result.Data (Slen + 1 .. Max_Length) := (others => Pad); when Strings.Left => if Npad >= Max_Length then Result.Data := (others => Pad); else Result.Data (1 .. Max_Length - Npad) := Source.Data (Count - Max_Length + 1 .. Slen); Result.Data (Max_Length - Npad + 1 .. Max_Length) := (others => Pad); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Head; procedure Head (Source : in out Bounded_Wide_String; Count : in Natural; Pad : in Wide_Character := Wide_Space; Drop : in Truncation := Error) is Slen : constant Natural := Source.Length; Npad : constant Integer := Count - Slen; Temp : Wide_String (1 .. Max_Length); begin if Npad <= 0 then Source.Length := Count; elsif Count <= Max_Length then Source.Length := Count; Source.Data (Slen + 1 .. Count) := (others => Pad); else Source.Length := Max_Length; case Drop is when Strings.Right => Source.Data (Slen + 1 .. Max_Length) := (others => Pad); when Strings.Left => if Npad > Max_Length then Source.Data := (others => Pad); else Temp := Source.Data; Source.Data (1 .. Max_Length - Npad) := Temp (Count - Max_Length + 1 .. Slen); for J in Max_Length - Npad + 1 .. Max_Length loop Source.Data (J) := Pad; end loop; end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Head; ----------- -- Index -- ----------- function Index (Source : in Bounded_Wide_String; Pattern : in Wide_String; Going : in Strings.Direction := Strings.Forward; Mapping : in Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity) return Natural is begin return Wide_Search.Index (Source.Data (1 .. Source.Length), Pattern, Going, Mapping); end Index; function Index (Source : in Bounded_Wide_String; Pattern : in Wide_String; Going : in Direction := Forward; Mapping : in Wide_Maps.Wide_Character_Mapping_Function) return Natural is begin return Wide_Search.Index (Source.Data (1 .. Source.Length), Pattern, Going, Mapping); end Index; function Index (Source : in Bounded_Wide_String; Set : in Wide_Maps.Wide_Character_Set; Test : in Strings.Membership := Strings.Inside; Going : in Strings.Direction := Strings.Forward) return Natural is begin return Wide_Search.Index (Source.Data (1 .. Source.Length), Set, Test, Going); end Index; --------------------- -- Index_Non_Blank -- --------------------- function Index_Non_Blank (Source : in Bounded_Wide_String; Going : in Strings.Direction := Strings.Forward) return Natural is begin return Wide_Search.Index_Non_Blank (Source.Data (1 .. Source.Length), Going); end Index_Non_Blank; ------------ -- Insert -- ------------ function Insert (Source : in Bounded_Wide_String; Before : in Positive; New_Item : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Slen : constant Natural := Source.Length; Nlen : constant Natural := New_Item'Length; Tlen : constant Natural := Slen + Nlen; Blen : constant Natural := Before - 1; Alen : constant Integer := Slen - Blen; Droplen : constant Integer := Tlen - Max_Length; Result : Bounded_Wide_String; -- Tlen is the length of the total string before possible truncation. -- Blen, Alen are the lengths of the before and after pieces of the -- source string. begin if Alen < 0 then raise Ada.Strings.Index_Error; elsif Droplen <= 0 then Result.Length := Tlen; Result.Data (1 .. Blen) := Source.Data (1 .. Blen); Result.Data (Before .. Before + Nlen - 1) := New_Item; Result.Data (Before + Nlen .. Tlen) := Source.Data (Before .. Slen); else Result.Length := Max_Length; case Drop is when Strings.Right => Result.Data (1 .. Blen) := Source.Data (1 .. Blen); if Droplen > Alen then Result.Data (Before .. Max_Length) := New_Item (New_Item'First .. New_Item'First + Max_Length - Before); else Result.Data (Before .. Before + Nlen - 1) := New_Item; Result.Data (Before + Nlen .. Max_Length) := Source.Data (Before .. Slen - Droplen); end if; when Strings.Left => Result.Data (Max_Length - (Alen - 1) .. Max_Length) := Source.Data (Before .. Slen); if Droplen >= Blen then Result.Data (1 .. Max_Length - Alen) := New_Item (New_Item'Last - (Max_Length - Alen) + 1 .. New_Item'Last); else Result.Data (Blen - Droplen + 1 .. Max_Length - Alen) := New_Item; Result.Data (1 .. Blen - Droplen) := Source.Data (Droplen + 1 .. Blen); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Insert; procedure Insert (Source : in out Bounded_Wide_String; Before : in Positive; New_Item : in Wide_String; Drop : in Strings.Truncation := Strings.Error) is begin -- We do a double copy here because this is one of the situations -- in which we move data to the right, and at least at the moment, -- GNAT is not handling such cases correctly ??? Source := Insert (Source, Before, New_Item, Drop); end Insert; ------------ -- Length -- ------------ function Length (Source : in Bounded_Wide_String) return Length_Range is begin return Source.Length; end Length; --------------- -- Overwrite -- --------------- function Overwrite (Source : in Bounded_Wide_String; Position : in Positive; New_Item : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Endpos : constant Natural := Position + New_Item'Length - 1; Slen : constant Natural := Source.Length; Droplen : Natural; begin if Position > Slen + 1 then raise Ada.Strings.Index_Error; elsif New_Item'Length = 0 then return Source; elsif Endpos <= Slen then Result.Length := Source.Length; Result.Data (1 .. Slen) := Source.Data (1 .. Slen); Result.Data (Position .. Endpos) := New_Item; return Result; elsif Endpos <= Max_Length then Result.Length := Endpos; Result.Data (1 .. Position - 1) := Source.Data (1 .. Position - 1); Result.Data (Position .. Endpos) := New_Item; return Result; else Result.Length := Max_Length; Droplen := Endpos - Max_Length; case Drop is when Strings.Right => Result.Data (1 .. Position - 1) := Source.Data (1 .. Position - 1); Result.Data (Position .. Max_Length) := New_Item (New_Item'First .. New_Item'Last - Droplen); return Result; when Strings.Left => if New_Item'Length >= Max_Length then Result.Data (1 .. Max_Length) := New_Item (New_Item'Last - Max_Length + 1 .. New_Item'Last); return Result; else Result.Data (1 .. Max_Length - New_Item'Length) := Source.Data (Droplen + 1 .. Position - 1); Result.Data (Max_Length - New_Item'Length + 1 .. Max_Length) := New_Item; return Result; end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Overwrite; procedure Overwrite (Source : in out Bounded_Wide_String; Position : in Positive; New_Item : in Wide_String; Drop : in Strings.Truncation := Strings.Error) is Endpos : constant Positive := Position + New_Item'Length - 1; Slen : constant Natural := Source.Length; Droplen : Natural; begin if Position > Slen + 1 then raise Ada.Strings.Index_Error; elsif Endpos <= Slen then Source.Data (Position .. Endpos) := New_Item; elsif Endpos <= Max_Length then Source.Data (Position .. Endpos) := New_Item; Source.Length := Endpos; else Source.Length := Max_Length; Droplen := Endpos - Max_Length; case Drop is when Strings.Right => Source.Data (Position .. Max_Length) := New_Item (New_Item'First .. New_Item'Last - Droplen); when Strings.Left => if New_Item'Length > Max_Length then Source.Data (1 .. Max_Length) := New_Item (New_Item'Last - Max_Length + 1 .. New_Item'Last); else Source.Data (1 .. Max_Length - New_Item'Length) := Source.Data (Droplen + 1 .. Position - 1); Source.Data (Max_Length - New_Item'Length + 1 .. Max_Length) := New_Item; end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Overwrite; --------------------- -- Replace_Element -- --------------------- procedure Replace_Element (Source : in out Bounded_Wide_String; Index : in Positive; By : in Wide_Character) is begin if Index <= Source.Length then Source.Data (Index) := By; else raise Ada.Strings.Index_Error; end if; end Replace_Element; ------------------- -- Replace_Slice -- ------------------- function Replace_Slice (Source : in Bounded_Wide_String; Low : in Positive; High : in Natural; By : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Slen : constant Natural := Source.Length; begin if Low > Slen + 1 then raise Strings.Index_Error; elsif High < Low then return Insert (Source, Low, By, Drop); else declare Blen : constant Natural := Natural'Max (0, Low - 1); Alen : constant Natural := Natural'Max (0, Slen - High); Tlen : constant Natural := Blen + By'Length + Alen; Droplen : constant Integer := Tlen - Max_Length; Result : Bounded_Wide_String; -- Tlen is the total length of the result string before any -- truncation. Blen and Alen are the lengths of the pieces -- of the original string that end up in the result string -- before and after the replaced slice. begin if Droplen <= 0 then Result.Length := Tlen; Result.Data (1 .. Blen) := Source.Data (1 .. Blen); Result.Data (Low .. Low + By'Length - 1) := By; Result.Data (Low + By'Length .. Tlen) := Source.Data (High + 1 .. Slen); else Result.Length := Max_Length; case Drop is when Strings.Right => Result.Data (1 .. Blen) := Source.Data (1 .. Blen); if Droplen > Alen then Result.Data (Low .. Max_Length) := By (By'First .. By'First + Max_Length - Low); else Result.Data (Low .. Low + By'Length - 1) := By; Result.Data (Low + By'Length .. Max_Length) := Source.Data (High + 1 .. Slen - Droplen); end if; when Strings.Left => Result.Data (Max_Length - (Alen - 1) .. Max_Length) := Source.Data (High + 1 .. Slen); if Droplen >= Blen then Result.Data (1 .. Max_Length - Alen) := By (By'Last - (Max_Length - Alen) + 1 .. By'Last); else Result.Data (Blen - Droplen + 1 .. Max_Length - Alen) := By; Result.Data (1 .. Blen - Droplen) := Source.Data (Droplen + 1 .. Blen); end if; when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end; end if; end Replace_Slice; procedure Replace_Slice (Source : in out Bounded_Wide_String; Low : in Positive; High : in Natural; By : in Wide_String; Drop : in Strings.Truncation := Strings.Error) is begin -- We do a double copy here because this is one of the situations -- in which we move data to the right, and at least at the moment, -- GNAT is not handling such cases correctly ??? Source := Replace_Slice (Source, Low, High, By, Drop); end Replace_Slice; --------------- -- Replicate -- --------------- function Replicate (Count : in Natural; Item : in Wide_Character; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; begin if Count <= Max_Length then Result.Length := Count; elsif Drop = Strings.Error then raise Ada.Strings.Length_Error; else Result.Length := Max_Length; end if; Result.Data (1 .. Result.Length) := (others => Item); return Result; end Replicate; function Replicate (Count : in Natural; Item : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Length : constant Integer := Count * Item'Length; Result : Bounded_Wide_String; Indx : Positive; begin if Length <= Max_Length then Result.Length := Length; if Length > 0 then Indx := 1; for J in 1 .. Count loop Result.Data (Indx .. Indx + Item'Length - 1) := Item; Indx := Indx + Item'Length; end loop; end if; else Result.Length := Max_Length; case Drop is when Strings.Right => Indx := 1; while Indx + Item'Length <= Max_Length + 1 loop Result.Data (Indx .. Indx + Item'Length - 1) := Item; Indx := Indx + Item'Length; end loop; Result.Data (Indx .. Max_Length) := Item (Item'First .. Item'First + Max_Length - Indx); when Strings.Left => Indx := Max_Length; while Indx - Item'Length >= 1 loop Result.Data (Indx - (Item'Length - 1) .. Indx) := Item; Indx := Indx - Item'Length; end loop; Result.Data (1 .. Indx) := Item (Item'Last - Indx + 1 .. Item'Last); when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Replicate; function Replicate (Count : in Natural; Item : in Bounded_Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is begin return Replicate (Count, Item.Data (1 .. Item.Length), Drop); end Replicate; ----------- -- Slice -- ----------- function Slice (Source : Bounded_Wide_String; Low : Positive; High : Natural) return Wide_String is begin -- Note: test of High > Length is in accordance with AI95-00128 if Low > Source.Length + 1 or else High > Source.Length then raise Index_Error; else declare Result : Wide_String (1 .. High - Low + 1); begin Result := Source.Data (Low .. High); return Result; end; end if; end Slice; ---------- -- Tail -- ---------- function Tail (Source : in Bounded_Wide_String; Count : in Natural; Pad : in Wide_Character := Wide_Space; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Result : Bounded_Wide_String; Slen : constant Natural := Source.Length; Npad : constant Integer := Count - Slen; begin if Npad <= 0 then Result.Length := Count; Result.Data (1 .. Count) := Source.Data (Slen - (Count - 1) .. Slen); elsif Count <= Max_Length then Result.Length := Count; Result.Data (1 .. Npad) := (others => Pad); Result.Data (Npad + 1 .. Count) := Source.Data (1 .. Slen); else Result.Length := Max_Length; case Drop is when Strings.Right => if Npad >= Max_Length then Result.Data := (others => Pad); else Result.Data (1 .. Npad) := (others => Pad); Result.Data (Npad + 1 .. Max_Length) := Source.Data (1 .. Max_Length - Npad); end if; when Strings.Left => Result.Data (1 .. Max_Length - Slen) := (others => Pad); Result.Data (Max_Length - Slen + 1 .. Max_Length) := Source.Data (1 .. Slen); when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end Tail; procedure Tail (Source : in out Bounded_Wide_String; Count : in Natural; Pad : in Wide_Character := Wide_Space; Drop : in Truncation := Error) is Slen : constant Natural := Source.Length; Npad : constant Integer := Count - Slen; Temp : Wide_String (1 .. Max_Length) := Source.Data; begin if Npad <= 0 then Source.Length := Count; Source.Data (1 .. Count) := Temp (Slen - (Count - 1) .. Slen); elsif Count <= Max_Length then Source.Length := Count; Source.Data (1 .. Npad) := (others => Pad); Source.Data (Npad + 1 .. Count) := Temp (1 .. Slen); else Source.Length := Max_Length; case Drop is when Strings.Right => if Npad >= Max_Length then Source.Data := (others => Pad); else Source.Data (1 .. Npad) := (others => Pad); Source.Data (Npad + 1 .. Max_Length) := Temp (1 .. Max_Length - Npad); end if; when Strings.Left => for J in 1 .. Max_Length - Slen loop Source.Data (J) := Pad; end loop; Source.Data (Max_Length - Slen + 1 .. Max_Length) := Temp (1 .. Slen); when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; end Tail; ---------------------------- -- To_Bounded_Wide_String -- ---------------------------- function To_Bounded_Wide_String (Source : in Wide_String; Drop : in Strings.Truncation := Strings.Error) return Bounded_Wide_String is Slen : constant Natural := Source'Length; Result : Bounded_Wide_String; begin if Slen <= Max_Length then Result.Length := Slen; Result.Data (1 .. Slen) := Source; else case Drop is when Strings.Right => Result.Length := Max_Length; Result.Data (1 .. Max_Length) := Source (Source'First .. Source'First - 1 + Max_Length); when Strings.Left => Result.Length := Max_Length; Result.Data (1 .. Max_Length) := Source (Source'Last - (Max_Length - 1) .. Source'Last); when Strings.Error => raise Ada.Strings.Length_Error; end case; end if; return Result; end To_Bounded_Wide_String; -------------------- -- To_Wide_String -- -------------------- function To_Wide_String (Source : in Bounded_Wide_String) return Wide_String is begin return Source.Data (1 .. Source.Length); end To_Wide_String; --------------- -- Translate -- --------------- function Translate (Source : in Bounded_Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping) return Bounded_Wide_String is Result : Bounded_Wide_String; begin Result.Length := Source.Length; for J in 1 .. Source.Length loop Result.Data (J) := Value (Mapping, Source.Data (J)); end loop; return Result; end Translate; procedure Translate (Source : in out Bounded_Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping) is begin for J in 1 .. Source.Length loop Source.Data (J) := Value (Mapping, Source.Data (J)); end loop; end Translate; function Translate (Source : in Bounded_Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping_Function) return Bounded_Wide_String is Result : Bounded_Wide_String; begin Result.Length := Source.Length; for J in 1 .. Source.Length loop Result.Data (J) := Mapping.all (Source.Data (J)); end loop; return Result; end Translate; procedure Translate (Source : in out Bounded_Wide_String; Mapping : in Wide_Maps.Wide_Character_Mapping_Function) is begin for J in 1 .. Source.Length loop Source.Data (J) := Mapping.all (Source.Data (J)); end loop; end Translate; ---------- -- Trim -- ---------- function Trim (Source : in Bounded_Wide_String; Side : in Trim_End) return Bounded_Wide_String is Result : Bounded_Wide_String; Last : Natural := Source.Length; First : Positive := 1; begin if Side = Left or else Side = Both then while First <= Last and then Source.Data (First) = ' ' loop First := First + 1; end loop; end if; if Side = Right or else Side = Both then while Last >= First and then Source.Data (Last) = ' ' loop Last := Last - 1; end loop; end if; Result.Length := Last - First + 1; Result.Data (1 .. Result.Length) := Source.Data (First .. Last); return Result; end Trim; procedure Trim (Source : in out Bounded_Wide_String; Side : in Trim_End) is Last : Length_Range := Source.Length; First : Positive := 1; Temp : Wide_String (1 .. Max_Length); begin Temp (1 .. Last) := Source.Data (1 .. Last); if Side = Left or else Side = Both then while First <= Last and then Temp (First) = ' ' loop First := First + 1; end loop; end if; if Side = Right or else Side = Both then while Last >= First and then Temp (Last) = ' ' loop Last := Last - 1; end loop; end if; Source.Length := Last - First + 1; Source.Data (1 .. Source.Length) := Temp (First .. Last); end Trim; function Trim (Source : in Bounded_Wide_String; Left : in Wide_Maps.Wide_Character_Set; Right : in Wide_Maps.Wide_Character_Set) return Bounded_Wide_String is Result : Bounded_Wide_String; begin for First in 1 .. Source.Length loop if not Is_In (Source.Data (First), Left) then for Last in reverse First .. Source.Length loop if not Is_In (Source.Data (Last), Right) then Result.Length := Last - First + 1; Result.Data (1 .. Result.Length) := Source.Data (First .. Last); return Result; end if; end loop; end if; end loop; Result.Length := 0; return Result; end Trim; procedure Trim (Source : in out Bounded_Wide_String; Left : in Wide_Maps.Wide_Character_Set; Right : in Wide_Maps.Wide_Character_Set) is begin for First in 1 .. Source.Length loop if not Is_In (Source.Data (First), Left) then for Last in reverse First .. Source.Length loop if not Is_In (Source.Data (Last), Right) then if First = 1 then Source.Length := Last; return; else Source.Length := Last - First + 1; Source.Data (1 .. Source.Length) := Source.Data (First .. Last); return; end if; end if; end loop; Source.Length := 0; return; end if; end loop; Source.Length := 0; end Trim; end Generic_Bounded_Length; end Ada.Strings.Wide_Bounded;
pragma Style_Checks (Off); -- This spec has been automatically generated from STM32H743x.svd pragma Restrictions (No_Elaboration_Code); with HAL; with System; package STM32_SVD.DMA2D is pragma Preelaborate; --------------- -- Registers -- --------------- subtype CR_MODE_Field is HAL.UInt2; -- DMA2D control register type CR_Register is record -- Start This bit can be used to launch the DMA2D according to the -- parameters loaded in the various configuration registers START : Boolean := False; -- Suspend This bit can be used to suspend the current transfer. This -- bit is set and reset by software. It is automatically reset by -- hardware when the START bit is reset. SUSP : Boolean := False; -- Abort This bit can be used to abort the current transfer. This bit is -- set by software and is automatically reset by hardware when the START -- bit is reset. ABORT_k : Boolean := False; -- unspecified Reserved_3_7 : HAL.UInt5 := 16#0#; -- Transfer error interrupt enable This bit is set and cleared by -- software. TEIE : Boolean := False; -- Transfer complete interrupt enable This bit is set and cleared by -- software. TCIE : Boolean := False; -- Transfer watermark interrupt enable This bit is set and cleared by -- software. TWIE : Boolean := False; -- CLUT access error interrupt enable This bit is set and cleared by -- software. CAEIE : Boolean := False; -- CLUT transfer complete interrupt enable This bit is set and cleared -- by software. CTCIE : Boolean := False; -- Configuration Error Interrupt Enable This bit is set and cleared by -- software. CEIE : Boolean := False; -- unspecified Reserved_14_15 : HAL.UInt2 := 16#0#; -- DMA2D mode This bit is set and cleared by software. It cannot be -- modified while a transfer is ongoing. MODE : CR_MODE_Field := 16#0#; -- unspecified Reserved_18_31 : HAL.UInt14 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for CR_Register use record START at 0 range 0 .. 0; SUSP at 0 range 1 .. 1; ABORT_k at 0 range 2 .. 2; Reserved_3_7 at 0 range 3 .. 7; TEIE at 0 range 8 .. 8; TCIE at 0 range 9 .. 9; TWIE at 0 range 10 .. 10; CAEIE at 0 range 11 .. 11; CTCIE at 0 range 12 .. 12; CEIE at 0 range 13 .. 13; Reserved_14_15 at 0 range 14 .. 15; MODE at 0 range 16 .. 17; Reserved_18_31 at 0 range 18 .. 31; end record; -- DMA2D Interrupt Status Register type ISR_Register is record -- Read-only. Transfer error interrupt flag This bit is set when an -- error occurs during a DMA transfer (data transfer or automatic CLUT -- loading). TEIF : Boolean; -- Read-only. Transfer complete interrupt flag This bit is set when a -- DMA2D transfer operation is complete (data transfer only). TCIF : Boolean; -- Read-only. Transfer watermark interrupt flag This bit is set when the -- last pixel of the watermarked line has been transferred. TWIF : Boolean; -- Read-only. CLUT access error interrupt flag This bit is set when the -- CPU accesses the CLUT while the CLUT is being automatically copied -- from a system memory to the internal DMA2D. CAEIF : Boolean; -- Read-only. CLUT transfer complete interrupt flag This bit is set when -- the CLUT copy from a system memory area to the internal DMA2D memory -- is complete. CTCIF : Boolean; -- Read-only. Configuration error interrupt flag This bit is set when -- the START bit of DMA2D_CR, DMA2DFGPFCCR or DMA2D_BGPFCCR is set and a -- wrong configuration has been programmed. CEIF : Boolean; -- unspecified Reserved_6_31 : HAL.UInt26; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for ISR_Register use record TEIF at 0 range 0 .. 0; TCIF at 0 range 1 .. 1; TWIF at 0 range 2 .. 2; CAEIF at 0 range 3 .. 3; CTCIF at 0 range 4 .. 4; CEIF at 0 range 5 .. 5; Reserved_6_31 at 0 range 6 .. 31; end record; -- DMA2D interrupt flag clear register type IFCR_Register is record -- Clear Transfer error interrupt flag Programming this bit to 1 clears -- the TEIF flag in the DMA2D_ISR register CTEIF : Boolean := False; -- Clear transfer complete interrupt flag Programming this bit to 1 -- clears the TCIF flag in the DMA2D_ISR register CTCIF : Boolean := False; -- Clear transfer watermark interrupt flag Programming this bit to 1 -- clears the TWIF flag in the DMA2D_ISR register CTWIF : Boolean := False; -- Clear CLUT access error interrupt flag Programming this bit to 1 -- clears the CAEIF flag in the DMA2D_ISR register CAECIF : Boolean := False; -- Clear CLUT transfer complete interrupt flag Programming this bit to 1 -- clears the CTCIF flag in the DMA2D_ISR register CCTCIF : Boolean := False; -- Clear configuration error interrupt flag Programming this bit to 1 -- clears the CEIF flag in the DMA2D_ISR register CCEIF : Boolean := False; -- unspecified Reserved_6_31 : HAL.UInt26 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for IFCR_Register use record CTEIF at 0 range 0 .. 0; CTCIF at 0 range 1 .. 1; CTWIF at 0 range 2 .. 2; CAECIF at 0 range 3 .. 3; CCTCIF at 0 range 4 .. 4; CCEIF at 0 range 5 .. 5; Reserved_6_31 at 0 range 6 .. 31; end record; subtype FGOR_LO_Field is HAL.UInt14; -- DMA2D foreground offset register type FGOR_Register is record -- Line offset Line offset used for the foreground expressed in pixel. -- This value is used to generate the address. It is added at the end of -- each line to determine the starting address of the next line. These -- bits can only be written when data transfers are disabled. Once a -- data transfer has started, they become read-only. If the image format -- is 4-bit per pixel, the line offset must be even. LO : FGOR_LO_Field := 16#0#; -- unspecified Reserved_14_31 : HAL.UInt18 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for FGOR_Register use record LO at 0 range 0 .. 13; Reserved_14_31 at 0 range 14 .. 31; end record; subtype BGOR_LO_Field is HAL.UInt14; -- DMA2D background offset register type BGOR_Register is record -- Line offset Line offset used for the background image (expressed in -- pixel). This value is used for the address generation. It is added at -- the end of each line to determine the starting address of the next -- line. These bits can only be written when data transfers are -- disabled. Once data transfer has started, they become read-only. If -- the image format is 4-bit per pixel, the line offset must be even. LO : BGOR_LO_Field := 16#0#; -- unspecified Reserved_14_31 : HAL.UInt18 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for BGOR_Register use record LO at 0 range 0 .. 13; Reserved_14_31 at 0 range 14 .. 31; end record; subtype FGPFCCR_CM_Field is HAL.UInt4; subtype FGPFCCR_CS_Field is HAL.UInt8; subtype FGPFCCR_AM_Field is HAL.UInt2; subtype FGPFCCR_CSS_Field is HAL.UInt2; subtype FGPFCCR_ALPHA_Field is HAL.UInt8; -- DMA2D foreground PFC control register type FGPFCCR_Register is record -- Color mode These bits defines the color format of the foreground -- image. They can only be written when data transfers are disabled. -- Once the transfer has started, they are read-only. others: -- meaningless CM : FGPFCCR_CM_Field := 16#0#; -- CLUT color mode This bit defines the color format of the CLUT. It can -- only be written when the transfer is disabled. Once the CLUT transfer -- has started, this bit is read-only. CCM : Boolean := False; -- Start This bit can be set to start the automatic loading of the CLUT. -- It is automatically reset: ** at the end of the transfer ** when the -- transfer is aborted by the user application by setting the ABORT bit -- in DMA2D_CR ** when a transfer error occurs ** when the transfer has -- not started due to a configuration error or another transfer -- operation already ongoing (data transfer or automatic background CLUT -- transfer). START : Boolean := False; -- unspecified Reserved_6_7 : HAL.UInt2 := 16#0#; -- CLUT size These bits define the size of the CLUT used for the -- foreground image. Once the CLUT transfer has started, this field is -- read-only. The number of CLUT entries is equal to CS[7:0] + 1. CS : FGPFCCR_CS_Field := 16#0#; -- Alpha mode These bits select the alpha channel value to be used for -- the foreground image. They can only be written data the transfer are -- disabled. Once the transfer has started, they become read-only. other -- configurations are meaningless AM : FGPFCCR_AM_Field := 16#0#; -- Chroma Sub-Sampling These bits define the chroma sub-sampling mode -- for YCbCr color mode. Once the transfer has started, these bits are -- read-only. others: meaningless CSS : FGPFCCR_CSS_Field := 16#0#; -- Alpha Inverted This bit inverts the alpha value. Once the transfer -- has started, this bit is read-only. AI : Boolean := False; -- Red Blue Swap This bit allows to swap the R &amp; B to support BGR or -- ABGR color formats. Once the transfer has started, this bit is -- read-only. RBS : Boolean := False; -- unspecified Reserved_22_23 : HAL.UInt2 := 16#0#; -- Alpha value These bits define a fixed alpha channel value which can -- replace the original alpha value or be multiplied by the original -- alpha value according to the alpha mode selected through the AM[1:0] -- bits. These bits can only be written when data transfers are -- disabled. Once a transfer has started, they become read-only. ALPHA : FGPFCCR_ALPHA_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for FGPFCCR_Register use record CM at 0 range 0 .. 3; CCM at 0 range 4 .. 4; START at 0 range 5 .. 5; Reserved_6_7 at 0 range 6 .. 7; CS at 0 range 8 .. 15; AM at 0 range 16 .. 17; CSS at 0 range 18 .. 19; AI at 0 range 20 .. 20; RBS at 0 range 21 .. 21; Reserved_22_23 at 0 range 22 .. 23; ALPHA at 0 range 24 .. 31; end record; subtype FGCOLR_BLUE_Field is HAL.UInt8; subtype FGCOLR_GREEN_Field is HAL.UInt8; subtype FGCOLR_RED_Field is HAL.UInt8; -- DMA2D foreground color register type FGCOLR_Register is record -- Blue Value These bits defines the blue value for the A4 or A8 mode of -- the foreground image. They can only be written when data transfers -- are disabled. Once the transfer has started, They are read-only. BLUE : FGCOLR_BLUE_Field := 16#0#; -- Green Value These bits defines the green value for the A4 or A8 mode -- of the foreground image. They can only be written when data transfers -- are disabled. Once the transfer has started, They are read-only. GREEN : FGCOLR_GREEN_Field := 16#0#; -- Red Value These bits defines the red value for the A4 or A8 mode of -- the foreground image. They can only be written when data transfers -- are disabled. Once the transfer has started, they are read-only. RED : FGCOLR_RED_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for FGCOLR_Register use record BLUE at 0 range 0 .. 7; GREEN at 0 range 8 .. 15; RED at 0 range 16 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype BGPFCCR_CM_Field is HAL.UInt4; subtype BGPFCCR_CS_Field is HAL.UInt8; subtype BGPFCCR_AM_Field is HAL.UInt2; subtype BGPFCCR_ALPHA_Field is HAL.UInt8; -- DMA2D background PFC control register type BGPFCCR_Register is record -- Color mode These bits define the color format of the foreground -- image. These bits can only be written when data transfers are -- disabled. Once the transfer has started, they are read-only. others: -- meaningless CM : BGPFCCR_CM_Field := 16#0#; -- CLUT Color mode These bits define the color format of the CLUT. This -- register can only be written when the transfer is disabled. Once the -- CLUT transfer has started, this bit is read-only. CCM : Boolean := False; -- Start This bit is set to start the automatic loading of the CLUT. -- This bit is automatically reset: ** at the end of the transfer ** -- when the transfer is aborted by the user application by setting the -- ABORT bit in the DMA2D_CR ** when a transfer error occurs ** when the -- transfer has not started due to a configuration error or another -- transfer operation already on going (data transfer or automatic -- BackGround CLUT transfer). START : Boolean := False; -- unspecified Reserved_6_7 : HAL.UInt2 := 16#0#; -- CLUT size These bits define the size of the CLUT used for the BG. -- Once the CLUT transfer has started, this field is read-only. The -- number of CLUT entries is equal to CS[7:0] + 1. CS : BGPFCCR_CS_Field := 16#0#; -- Alpha mode These bits define which alpha channel value to be used for -- the background image. These bits can only be written when data -- transfers are disabled. Once the transfer has started, they are -- read-only. others: meaningless AM : BGPFCCR_AM_Field := 16#0#; -- unspecified Reserved_18_19 : HAL.UInt2 := 16#0#; -- Alpha Inverted This bit inverts the alpha value. Once the transfer -- has started, this bit is read-only. AI : Boolean := False; -- Red Blue Swap This bit allows to swap the R &amp; B to support BGR or -- ABGR color formats. Once the transfer has started, this bit is -- read-only. RBS : Boolean := False; -- unspecified Reserved_22_23 : HAL.UInt2 := 16#0#; -- Alpha value These bits define a fixed alpha channel value which can -- replace the original alpha value or be multiplied with the original -- alpha value according to the alpha mode selected with bits AM[1: 0]. -- These bits can only be written when data transfers are disabled. Once -- the transfer has started, they are read-only. ALPHA : BGPFCCR_ALPHA_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for BGPFCCR_Register use record CM at 0 range 0 .. 3; CCM at 0 range 4 .. 4; START at 0 range 5 .. 5; Reserved_6_7 at 0 range 6 .. 7; CS at 0 range 8 .. 15; AM at 0 range 16 .. 17; Reserved_18_19 at 0 range 18 .. 19; AI at 0 range 20 .. 20; RBS at 0 range 21 .. 21; Reserved_22_23 at 0 range 22 .. 23; ALPHA at 0 range 24 .. 31; end record; subtype BGCOLR_BLUE_Field is HAL.UInt8; subtype BGCOLR_GREEN_Field is HAL.UInt8; subtype BGCOLR_RED_Field is HAL.UInt8; -- DMA2D background color register type BGCOLR_Register is record -- Blue Value These bits define the blue value for the A4 or A8 mode of -- the background. These bits can only be written when data transfers -- are disabled. Once the transfer has started, they are read-only. BLUE : BGCOLR_BLUE_Field := 16#0#; -- Green Value These bits define the green value for the A4 or A8 mode -- of the background. These bits can only be written when data transfers -- are disabled. Once the transfer has started, they are read-only. GREEN : BGCOLR_GREEN_Field := 16#0#; -- Red Value These bits define the red value for the A4 or A8 mode of -- the background. These bits can only be written when data transfers -- are disabled. Once the transfer has started, they are read-only. RED : BGCOLR_RED_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for BGCOLR_Register use record BLUE at 0 range 0 .. 7; GREEN at 0 range 8 .. 15; RED at 0 range 16 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype OPFCCR_CM_Field is HAL.UInt3; -- DMA2D output PFC control register type OPFCCR_Register is record -- Color mode These bits define the color format of the output image. -- These bits can only be written when data transfers are disabled. Once -- the transfer has started, they are read-only. others: meaningless CM : OPFCCR_CM_Field := 16#0#; -- unspecified Reserved_3_19 : HAL.UInt17 := 16#0#; -- Alpha Inverted This bit inverts the alpha value. Once the transfer -- has started, this bit is read-only. AI : Boolean := False; -- Red Blue Swap This bit allows to swap the R &amp; B to support BGR or -- ABGR color formats. Once the transfer has started, this bit is -- read-only. RBS : Boolean := False; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OPFCCR_Register use record CM at 0 range 0 .. 2; Reserved_3_19 at 0 range 3 .. 19; AI at 0 range 20 .. 20; RBS at 0 range 21 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; subtype OCOLR_BLUE_Field is HAL.UInt8; subtype OCOLR_GREEN_Field is HAL.UInt8; subtype OCOLR_RED_Field is HAL.UInt8; subtype OCOLR_ALPHA_Field is HAL.UInt8; -- DMA2D output color register type OCOLR_Register is record -- Blue Value These bits define the blue value of the output image. -- These bits can only be written when data transfers are disabled. Once -- the transfer has started, they are read-only. BLUE : OCOLR_BLUE_Field := 16#0#; -- Green Value These bits define the green value of the output image. -- These bits can only be written when data transfers are disabled. Once -- the transfer has started, they are read-only. GREEN : OCOLR_GREEN_Field := 16#0#; -- Red Value These bits define the red value of the output image. These -- bits can only be written when data transfers are disabled. Once the -- transfer has started, they are read-only. RED : OCOLR_RED_Field := 16#0#; -- Alpha Channel Value These bits define the alpha channel of the output -- color. These bits can only be written when data transfers are -- disabled. Once the transfer has started, they are read-only. ALPHA : OCOLR_ALPHA_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OCOLR_Register use record BLUE at 0 range 0 .. 7; GREEN at 0 range 8 .. 15; RED at 0 range 16 .. 23; ALPHA at 0 range 24 .. 31; end record; subtype OOR_LO_Field is HAL.UInt14; -- DMA2D output offset register type OOR_Register is record -- Line Offset Line offset used for the output (expressed in pixels). -- This value is used for the address generation. It is added at the end -- of each line to determine the starting address of the next line. -- These bits can only be written when data transfers are disabled. Once -- the transfer has started, they are read-only. LO : OOR_LO_Field := 16#0#; -- unspecified Reserved_14_31 : HAL.UInt18 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for OOR_Register use record LO at 0 range 0 .. 13; Reserved_14_31 at 0 range 14 .. 31; end record; subtype NLR_NL_Field is HAL.UInt16; subtype NLR_PL_Field is HAL.UInt14; -- DMA2D number of line register type NLR_Register is record -- Number of lines Number of lines of the area to be transferred. These -- bits can only be written when data transfers are disabled. Once the -- transfer has started, they are read-only. NL : NLR_NL_Field := 16#0#; -- Pixel per lines Number of pixels per lines of the area to be -- transferred. These bits can only be written when data transfers are -- disabled. Once the transfer has started, they are read-only. If any -- of the input image format is 4-bit per pixel, pixel per lines must be -- even. PL : NLR_PL_Field := 16#0#; -- unspecified Reserved_30_31 : HAL.UInt2 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for NLR_Register use record NL at 0 range 0 .. 15; PL at 0 range 16 .. 29; Reserved_30_31 at 0 range 30 .. 31; end record; subtype LWR_LW_Field is HAL.UInt16; -- DMA2D line watermark register type LWR_Register is record -- Line watermark These bits allow to configure the line watermark for -- interrupt generation. An interrupt is raised when the last pixel of -- the watermarked line has been transferred. These bits can only be -- written when data transfers are disabled. Once the transfer has -- started, they are read-only. LW : LWR_LW_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for LWR_Register use record LW at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype AMTCR_DT_Field is HAL.UInt8; -- DMA2D AXI master timer configuration register type AMTCR_Register is record -- Enable Enables the dead time functionality. EN : Boolean := False; -- unspecified Reserved_1_7 : HAL.UInt7 := 16#0#; -- Dead Time Dead time value in the AXI clock cycle inserted between two -- consecutive accesses on the AXI master port. These bits represent the -- minimum guaranteed number of cycles between two consecutive AXI -- accesses. DT : AMTCR_DT_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for AMTCR_Register use record EN at 0 range 0 .. 0; Reserved_1_7 at 0 range 1 .. 7; DT at 0 range 8 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- DMA2D type DMA2D_Peripheral is record -- DMA2D control register CR : aliased CR_Register; -- DMA2D Interrupt Status Register ISR : aliased ISR_Register; -- DMA2D interrupt flag clear register IFCR : aliased IFCR_Register; -- DMA2D foreground memory address register FGMAR : aliased HAL.UInt32; -- DMA2D foreground offset register FGOR : aliased FGOR_Register; -- DMA2D background memory address register BGMAR : aliased HAL.UInt32; -- DMA2D background offset register BGOR : aliased BGOR_Register; -- DMA2D foreground PFC control register FGPFCCR : aliased FGPFCCR_Register; -- DMA2D foreground color register FGCOLR : aliased FGCOLR_Register; -- DMA2D background PFC control register BGPFCCR : aliased BGPFCCR_Register; -- DMA2D background color register BGCOLR : aliased BGCOLR_Register; -- DMA2D foreground CLUT memory address register FGCMAR : aliased HAL.UInt32; -- DMA2D background CLUT memory address register BGCMAR : aliased HAL.UInt32; -- DMA2D output PFC control register OPFCCR : aliased OPFCCR_Register; -- DMA2D output color register OCOLR : aliased OCOLR_Register; -- DMA2D output memory address register OMAR : aliased HAL.UInt32; -- DMA2D output offset register OOR : aliased OOR_Register; -- DMA2D number of line register NLR : aliased NLR_Register; -- DMA2D line watermark register LWR : aliased LWR_Register; -- DMA2D AXI master timer configuration register AMTCR : aliased AMTCR_Register; end record with Volatile; for DMA2D_Peripheral use record CR at 16#0# range 0 .. 31; ISR at 16#4# range 0 .. 31; IFCR at 16#8# range 0 .. 31; FGMAR at 16#C# range 0 .. 31; FGOR at 16#10# range 0 .. 31; BGMAR at 16#14# range 0 .. 31; BGOR at 16#18# range 0 .. 31; FGPFCCR at 16#1C# range 0 .. 31; FGCOLR at 16#20# range 0 .. 31; BGPFCCR at 16#24# range 0 .. 31; BGCOLR at 16#28# range 0 .. 31; FGCMAR at 16#2C# range 0 .. 31; BGCMAR at 16#30# range 0 .. 31; OPFCCR at 16#34# range 0 .. 31; OCOLR at 16#38# range 0 .. 31; OMAR at 16#3C# range 0 .. 31; OOR at 16#40# range 0 .. 31; NLR at 16#44# range 0 .. 31; LWR at 16#48# range 0 .. 31; AMTCR at 16#4C# range 0 .. 31; end record; -- DMA2D DMA2D_Periph : aliased DMA2D_Peripheral with Import, Address => DMA2D_Base; end STM32_SVD.DMA2D;
-- package pc_1_coeff_17 -- -- Predictor_Rule : Integration_Rule renames Predictor_32_17; -- -- Corrector_Rule : Integration_Rule renames Corrector_33_17; -- -- Final_Step_Corrector : Real renames Final_Step_Corrector_33_17; -- generic type Real is digits <>; package pc_1_coeff_17 is subtype PC_Rule_Range is Integer range 0..31; type Integration_Rule is array(PC_Rule_Range) of Real; Extrap_Factor: constant Real := 1.0 / 15.8; Predictor_32_17 : constant Integration_Rule := ( -1.62472980947547285227912948691595204E-1 , 1.51846575484458773430336413812753196E+0 , -5.68313970441214142340495425745202565E+0 , 1.00050734670521388742024808461071612E+1 , -5.61854336297953874414035267260123444E+0 , -6.41511270402391939529842383747530560E+0 , 6.59402419366119591267336173438292271E+0 , 6.73389647814116072687447173034733748E+0 , -4.86700881396898624573986118676698199E+0 , -8.64478706711790617969744057119346501E+0 , 6.63950727514010549784482933422989055E-1 , 9.20584617745705343258283037112855880E+0 , 5.19291395136070380968021848017215355E+0 , -5.96875633034033333049422865420452374E+0 , -9.72525166371917802502970850620895075E+0 , -9.95483190234079632968918740363838844E-1 , 9.52700922317356348545779899395211586E+0 , 8.36629002979632377094330540813030109E+0 , -3.85140687351134092395168103549558921E+0 , -1.19484970796233066876477705100278548E+1 , -4.44168726638781250188880979736295583E+0 , 1.01593092041960707363001655682217274E+1 , 1.14434446021422622131134674483204015E+1 , -5.04683008000810008640273594832825778E+0 , -1.56394540669719939074019577890952650E+1 , 4.58226091321959434664888304431326364E-1 , 1.90978849948879625945213856074456873E+1 , -1.62929715322749462770004952327020878E+0 , -2.47069184123582886764830758984010759E+1 , 2.64970064547578370104165815171826716E+1 , -1.32754569867641443423432949584113725E+1 , 4.15676238628928173030237375397761510E+0 ); Predictor_32_extrap_to_17 : constant Integration_Rule := ( 1.36170338100944228833244474089595536E-1 , -1.43627006830559893033227429680231347E+0 , 6.25426101053819487878676687905366217E+0 , -1.37007265543019152786589106916978149E+1 , 1.30180684411558539611462169446664638E+1 , 3.37161992934220452136765391206638380E+0 , -1.44967104901233064320465797867265537E+1 , -2.32976036259699042473128857293279032E+0 , 1.60135143422803149804126763227308538E+1 , 6.09415040781672732848112078705410452E+0 , -1.67176567383205210974706254692379378E+1 , -1.24784473750736143913368532411975415E+1 , 1.33560980157391979480655078492820117E+1 , 1.88295870130376820754771101489794362E+1 , -4.21972488741453009458242453116599415E+0 , -2.16905844193546925713292133005795100E+1 , -8.54977852575513347873329401429507024E+0 , 1.83162714746860914505261967956328830E+1 , 2.03691056825979617972191189828938736E+1 , -9.48894410534496198964999690653173315E+0 , -2.69829180340256333702722180576512020E+1 , -1.05463051869620197709087430018367894E+0 , 2.73423581859878178943934360569196619E+1 , 1.00399919777284775215768531822227871E+1 , -2.52328248015840951873717383878101787E+1 , -1.55533819955664366838517778040311197E+1 , 2.76995237685588538548398240808673052E+1 , 1.34928731717967644615465425025854988E+1 , -4.47413113609792192188253274754918855E+1 , 3.67681104676958786532390848303135661E+1 , -1.58467700133578032514837230255466989E+1 , 4.41873602373768882185576611252393568E+0 ); Corrector_33_17 : constant Integration_Rule := ( 4.98168398855966025659830340469982468E-3 , -4.51613208728487145714279319138577943E-2 , 1.62172454961820758387144902609866889E-1 , -2.66736718543866567001890246179627645E-1 , 1.17456847072785594212726095808335063E-1 , 1.96866047179146830607213954647420838E-1 , -1.36406446406406306686104779385869613E-1 , -2.10316570120453320678394972110799891E-1 , 7.08775822889284787661100350119805011E-2 , 2.42273511266352912579478510626232678E-1 , 6.07880076103313559217517180111815585E-2 , -2.08884152342191241654946666209678123E-1 , -2.06927786051030923340239805288218292E-1 , 6.27988202459660113353878599356576194E-2 , 2.64368799640054028698998748639507920E-1 , 1.46893121647767128072743038831631258E-1 , -1.58366061762764557700156430430808771E-1 , -2.87895985515915602425491040068879095E-1 , -6.97454945893382033173477264815729488E-2 , 2.53738018963797141239773267604182993E-1 , 2.80867798494825232899917918565546520E-1 , -6.06446297592698498469263002734874671E-2 , -3.58323214027075377289296944856532071E-1 , -1.78281079905509944614996373606226778E-1 , 3.01776031852680498634277131438819591E-1 , 3.68005656150613531276021055250876534E-1 , -2.15472206527322468891573729855813413E-1 , -5.07830439816322016584924426165303395E-1 , 2.84771043627340798318221042098526303E-1 , 5.99446533852551009537456116171727083E-1 , -1.00303000540072804419740748556957105E+0 , 1.20147256716041481639865238776711029E+0 ); Final_Step_Corrector_33_17 : constant Real := 2.94467585637107351658652771972942886E-1; Predictor_31_17 : constant Integration_Rule := ( 0.0, -1.66288025996788291979014146692279247E-1 , 1.61314625598600037148364551586909605E+0 , -6.34652284483809191615748750922343187E+0 , 1.20925290950580058969215358176485194E+1 , -8.55543001730046005814737604555588414E+0 , -6.03856653603814841772670915680964009E+0 , 9.87411753435123356567413853432060800E+0 , 5.84792178429449472740424201798429506E+0 , -8.79080704693799352277751159942444752E+0 , -8.68433491492276051348785151885634521E+0 , 5.23249514341292630582386320899518599E+0 , 1.15501269956505581429385972255865776E+1 , 1.19015803599446214851405436363081260E+0 , -1.12735863726613656709402177491395534E+1 , -8.58724535293452427603673411259105530E+0 , 6.11779894831184736325921309026516388E+0 , 1.33143757032492108804679352846582872E+1 , 2.54498194351809454946350642124060281E+0 , -1.26899547687530867831866333263973675E+1 , -1.10392955600528269217184624438165837E+1 , 7.22114406303264771332361646862478847E+0 , 1.64284437998856731324743466498097621E+1 , -5.67080726395450006591274670119935468E-2 , -1.90090554969964743313479857481245026E+1 , -5.16273643185844088179660001589396301E+0 , 2.25693367707791379806394135476958962E+1 , 3.23942573862421619313560030459267391E+0 , -3.16177593803619854016308619241162746E+1 , 3.01300772494106219311088419792550374E+1 , -1.41999300670040827526500215273680735E+1 , 4.25214182773744383761004386084408864E+0 ); Corrector_33_extrap_to_18 : constant Integration_Rule := ( 4.64957172265568290617642035306327849E-3 , -5.32364345477780197326227382703065444E-2 , 2.58904041696766065932598884556662776E-1 , -6.72055793630148256966630050895269478E-1 , 9.15794996938466947765310910581055406E-1 , -3.86620357119493628669435032828971106E-1 , -5.29883785715189114108400207057360403E-1 , 4.61979036844325805108905000116698707E-1 , 4.56013862422632895360734280356379472E-1 , -3.59931859280603516471244037106034340E-1 , -5.22220187225208102066130902592553281E-1 , 1.53874467374816594859432240887279253E-1 , 5.76875866062408347780792620531227060E-1 , 1.37956101295865753817956167030461936E-1 , -5.04828211846707284644976890397154485E-1 , -4.35382776657718965561179636154178742E-1 , 2.60044938908876237049241916677437476E-1 , 6.18922127068426163141800392336135070E-1 , 1.04569667951157313542505041254343853E-1 , -6.09174833550661787094532384167567230E-1 , -4.73809758741684910775201463003244463E-1 , 4.24807949760191321053725822758113827E-1 , 7.60794586900441190078935262601197249E-1 , -1.70176212754445615018762081075796958E-1 , -9.85612736737263156756894612628934325E-1 , -7.10483049990096277149603714051640309E-4 , 1.30351505862644156114775006541164752E+0 , -2.58013361253619469261814185766801641E-1 , -1.84206431797194761511067211764574917E+0 , 2.56815524822308907107299393885690785E+0 , -1.88282334284095169147611053155693178E+0 , 1.40485051786555008449720031230200151E+0 ); Final_Step_Corrector_33_extrap_to_18 : constant Real := 2.74836413261300194882473461828327737E-1; Corrector_33_18 : constant Integration_Rule := ( -4.29063799602363300332554290338226295E-3 , 4.38930332480966809796959379076409981E-2 , -1.84407586326769458272582523016445115E-1 , 3.86018410068741543924126535404563539E-1 , -3.39672522737244306236877595500955353E-1 , -1.15641698427106085154098431312500252E-1 , 3.67714580948230418726334597592131207E-1 , 8.51130013530862502298476133473910856E-2 , -3.54666284501439138817890595269239766E-1 , -1.81416311108832538094079171518532074E-1 , 2.88833826526463644786676422021725394E-1 , 3.22344332863848596675379797234396480E-1 , -1.21000123850099483378649506353159374E-1 , -4.05936344466723412585600990426609324E-1 , -1.33568166316278517562718545082911589E-1 , 3.36386586562306821405499326466245392E-1 , 3.72313509686552044866666445265398842E-1 , -9.84025206013759090927347524342649613E-2 , -4.67682460545670749579065020203992459E-1 , -2.14997145748892282681215582758083950E-1 , 3.66795460695756672861508217500605439E-1 , 4.70583855446769988483400163170587136E-1 , -1.30277395110943088424372240845988236E-1 , -6.01970902280695395288554055750991530E-1 , -1.23767834937687118949723498842400676E-1 , 6.63435227624153102184263640709067511E-1 , 2.88648820827314256520865647122187408E-1 , -8.20338185422574932346236812125224486E-1 , -1.72358326182689102131382649210764114E-1 , 1.25220166246515912046347289775591826E+0 , -1.34961004668931826085713491119588305E+0 , 1.29052692128136021194977625758860908E+0 ); Final_Step_Corrector_33_18 : constant Real := 2.85195263652524058398728925664860798E-1; Predictor_Rule : Integration_Rule renames Predictor_31_17; --Predictor_Rule : Integration_Rule renames Predictor_32_extrap_to_17; Corrector_Rule : Integration_Rule renames Corrector_33_17; --Corrector_Rule : Integration_Rule renames Corrector_33_extrap_to_18; Final_Step_Corrector : Real renames Final_Step_Corrector_33_17; --Final_Step_Corrector : Real renames Final_Step_Corrector_33_extrap_to_18; end pc_1_coeff_17;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Program.Elements; package Program.Nodes is pragma Preelaborate; type Node is abstract limited new Program.Elements.Element with private; private type Node is abstract limited new Program.Elements.Element with record Enclosing_Element : Program.Elements.Element_Access; end record; procedure Set_Enclosing_Element (Self : access Program.Elements.Element'Class; Value : access Program.Elements.Element'Class); overriding function Enclosing_Element (Self : Node) return Program.Elements.Element_Access; overriding function Is_Part_Of_Implicit (Self : Node) return Boolean; overriding function Is_Part_Of_Inherited (Self : Node) return Boolean; overriding function Is_Part_Of_Instance (Self : Node) return Boolean; overriding function Is_Pragma_Element (Self : Node) return Boolean; overriding function Is_Defining_Name_Element (Self : Node) return Boolean; overriding function Is_Defining_Identifier_Element (Self : Node) return Boolean; overriding function Is_Defining_Character_Literal_Element (Self : Node) return Boolean; overriding function Is_Defining_Operator_Symbol_Element (Self : Node) return Boolean; overriding function Is_Defining_Expanded_Name_Element (Self : Node) return Boolean; overriding function Is_Declaration_Element (Self : Node) return Boolean; overriding function Is_Type_Declaration_Element (Self : Node) return Boolean; overriding function Is_Task_Type_Declaration_Element (Self : Node) return Boolean; overriding function Is_Protected_Type_Declaration_Element (Self : Node) return Boolean; overriding function Is_Subtype_Declaration_Element (Self : Node) return Boolean; overriding function Is_Object_Declaration_Element (Self : Node) return Boolean; overriding function Is_Single_Task_Declaration_Element (Self : Node) return Boolean; overriding function Is_Single_Protected_Declaration_Element (Self : Node) return Boolean; overriding function Is_Number_Declaration_Element (Self : Node) return Boolean; overriding function Is_Enumeration_Literal_Specification_Element (Self : Node) return Boolean; overriding function Is_Discriminant_Specification_Element (Self : Node) return Boolean; overriding function Is_Component_Declaration_Element (Self : Node) return Boolean; overriding function Is_Loop_Parameter_Specification_Element (Self : Node) return Boolean; overriding function Is_Generalized_Iterator_Specification_Element (Self : Node) return Boolean; overriding function Is_Element_Iterator_Specification_Element (Self : Node) return Boolean; overriding function Is_Procedure_Declaration_Element (Self : Node) return Boolean; overriding function Is_Function_Declaration_Element (Self : Node) return Boolean; overriding function Is_Parameter_Specification_Element (Self : Node) return Boolean; overriding function Is_Procedure_Body_Declaration_Element (Self : Node) return Boolean; overriding function Is_Function_Body_Declaration_Element (Self : Node) return Boolean; overriding function Is_Return_Object_Specification_Element (Self : Node) return Boolean; overriding function Is_Package_Declaration_Element (Self : Node) return Boolean; overriding function Is_Package_Body_Declaration_Element (Self : Node) return Boolean; overriding function Is_Object_Renaming_Declaration_Element (Self : Node) return Boolean; overriding function Is_Exception_Renaming_Declaration_Element (Self : Node) return Boolean; overriding function Is_Procedure_Renaming_Declaration_Element (Self : Node) return Boolean; overriding function Is_Function_Renaming_Declaration_Element (Self : Node) return Boolean; overriding function Is_Package_Renaming_Declaration_Element (Self : Node) return Boolean; overriding function Is_Generic_Package_Renaming_Declaration_Element (Self : Node) return Boolean; overriding function Is_Generic_Procedure_Renaming_Declaration_Element (Self : Node) return Boolean; overriding function Is_Generic_Function_Renaming_Declaration_Element (Self : Node) return Boolean; overriding function Is_Task_Body_Declaration_Element (Self : Node) return Boolean; overriding function Is_Protected_Body_Declaration_Element (Self : Node) return Boolean; overriding function Is_Entry_Declaration_Element (Self : Node) return Boolean; overriding function Is_Entry_Body_Declaration_Element (Self : Node) return Boolean; overriding function Is_Entry_Index_Specification_Element (Self : Node) return Boolean; overriding function Is_Procedure_Body_Stub_Element (Self : Node) return Boolean; overriding function Is_Function_Body_Stub_Element (Self : Node) return Boolean; overriding function Is_Package_Body_Stub_Element (Self : Node) return Boolean; overriding function Is_Task_Body_Stub_Element (Self : Node) return Boolean; overriding function Is_Protected_Body_Stub_Element (Self : Node) return Boolean; overriding function Is_Exception_Declaration_Element (Self : Node) return Boolean; overriding function Is_Choice_Parameter_Specification_Element (Self : Node) return Boolean; overriding function Is_Generic_Package_Declaration_Element (Self : Node) return Boolean; overriding function Is_Generic_Procedure_Declaration_Element (Self : Node) return Boolean; overriding function Is_Generic_Function_Declaration_Element (Self : Node) return Boolean; overriding function Is_Package_Instantiation_Element (Self : Node) return Boolean; overriding function Is_Procedure_Instantiation_Element (Self : Node) return Boolean; overriding function Is_Function_Instantiation_Element (Self : Node) return Boolean; overriding function Is_Formal_Object_Declaration_Element (Self : Node) return Boolean; overriding function Is_Formal_Type_Declaration_Element (Self : Node) return Boolean; overriding function Is_Formal_Procedure_Declaration_Element (Self : Node) return Boolean; overriding function Is_Formal_Function_Declaration_Element (Self : Node) return Boolean; overriding function Is_Formal_Package_Declaration_Element (Self : Node) return Boolean; overriding function Is_Definition_Element (Self : Node) return Boolean; overriding function Is_Type_Definition_Element (Self : Node) return Boolean; overriding function Is_Subtype_Indication_Element (Self : Node) return Boolean; overriding function Is_Constraint_Element (Self : Node) return Boolean; overriding function Is_Component_Definition_Element (Self : Node) return Boolean; overriding function Is_Discrete_Range_Element (Self : Node) return Boolean; overriding function Is_Discrete_Subtype_Indication_Element (Self : Node) return Boolean; overriding function Is_Discrete_Range_Attribute_Reference_Element (Self : Node) return Boolean; overriding function Is_Discrete_Simple_Expression_Range_Element (Self : Node) return Boolean; overriding function Is_Unknown_Discriminant_Part_Element (Self : Node) return Boolean; overriding function Is_Known_Discriminant_Part_Element (Self : Node) return Boolean; overriding function Is_Record_Definition_Element (Self : Node) return Boolean; overriding function Is_Null_Component_Element (Self : Node) return Boolean; overriding function Is_Variant_Part_Element (Self : Node) return Boolean; overriding function Is_Variant_Element (Self : Node) return Boolean; overriding function Is_Others_Choice_Element (Self : Node) return Boolean; overriding function Is_Anonymous_Access_Definition_Element (Self : Node) return Boolean; overriding function Is_Anonymous_Access_To_Object_Element (Self : Node) return Boolean; overriding function Is_Anonymous_Access_To_Procedure_Element (Self : Node) return Boolean; overriding function Is_Anonymous_Access_To_Function_Element (Self : Node) return Boolean; overriding function Is_Private_Type_Definition_Element (Self : Node) return Boolean; overriding function Is_Private_Extension_Definition_Element (Self : Node) return Boolean; overriding function Is_Incomplete_Type_Definition_Element (Self : Node) return Boolean; overriding function Is_Task_Definition_Element (Self : Node) return Boolean; overriding function Is_Protected_Definition_Element (Self : Node) return Boolean; overriding function Is_Formal_Type_Definition_Element (Self : Node) return Boolean; overriding function Is_Aspect_Specification_Element (Self : Node) return Boolean; overriding function Is_Real_Range_Specification_Element (Self : Node) return Boolean; overriding function Is_Expression_Element (Self : Node) return Boolean; overriding function Is_Numeric_Literal_Element (Self : Node) return Boolean; overriding function Is_String_Literal_Element (Self : Node) return Boolean; overriding function Is_Identifier_Element (Self : Node) return Boolean; overriding function Is_Operator_Symbol_Element (Self : Node) return Boolean; overriding function Is_Character_Literal_Element (Self : Node) return Boolean; overriding function Is_Explicit_Dereference_Element (Self : Node) return Boolean; overriding function Is_Function_Call_Element (Self : Node) return Boolean; overriding function Is_Infix_Operator_Element (Self : Node) return Boolean; overriding function Is_Indexed_Component_Element (Self : Node) return Boolean; overriding function Is_Slice_Element (Self : Node) return Boolean; overriding function Is_Selected_Component_Element (Self : Node) return Boolean; overriding function Is_Attribute_Reference_Element (Self : Node) return Boolean; overriding function Is_Record_Aggregate_Element (Self : Node) return Boolean; overriding function Is_Extension_Aggregate_Element (Self : Node) return Boolean; overriding function Is_Array_Aggregate_Element (Self : Node) return Boolean; overriding function Is_Short_Circuit_Operation_Element (Self : Node) return Boolean; overriding function Is_Membership_Test_Element (Self : Node) return Boolean; overriding function Is_Null_Literal_Element (Self : Node) return Boolean; overriding function Is_Parenthesized_Expression_Element (Self : Node) return Boolean; overriding function Is_Raise_Expression_Element (Self : Node) return Boolean; overriding function Is_Type_Conversion_Element (Self : Node) return Boolean; overriding function Is_Qualified_Expression_Element (Self : Node) return Boolean; overriding function Is_Allocator_Element (Self : Node) return Boolean; overriding function Is_Case_Expression_Element (Self : Node) return Boolean; overriding function Is_If_Expression_Element (Self : Node) return Boolean; overriding function Is_Quantified_Expression_Element (Self : Node) return Boolean; overriding function Is_Association_Element (Self : Node) return Boolean; overriding function Is_Discriminant_Association_Element (Self : Node) return Boolean; overriding function Is_Record_Component_Association_Element (Self : Node) return Boolean; overriding function Is_Array_Component_Association_Element (Self : Node) return Boolean; overriding function Is_Parameter_Association_Element (Self : Node) return Boolean; overriding function Is_Formal_Package_Association_Element (Self : Node) return Boolean; overriding function Is_Statement_Element (Self : Node) return Boolean; overriding function Is_Null_Statement_Element (Self : Node) return Boolean; overriding function Is_Assignment_Statement_Element (Self : Node) return Boolean; overriding function Is_If_Statement_Element (Self : Node) return Boolean; overriding function Is_Case_Statement_Element (Self : Node) return Boolean; overriding function Is_Loop_Statement_Element (Self : Node) return Boolean; overriding function Is_While_Loop_Statement_Element (Self : Node) return Boolean; overriding function Is_For_Loop_Statement_Element (Self : Node) return Boolean; overriding function Is_Block_Statement_Element (Self : Node) return Boolean; overriding function Is_Exit_Statement_Element (Self : Node) return Boolean; overriding function Is_Goto_Statement_Element (Self : Node) return Boolean; overriding function Is_Call_Statement_Element (Self : Node) return Boolean; overriding function Is_Simple_Return_Statement_Element (Self : Node) return Boolean; overriding function Is_Extended_Return_Statement_Element (Self : Node) return Boolean; overriding function Is_Accept_Statement_Element (Self : Node) return Boolean; overriding function Is_Requeue_Statement_Element (Self : Node) return Boolean; overriding function Is_Delay_Statement_Element (Self : Node) return Boolean; overriding function Is_Terminate_Alternative_Statement_Element (Self : Node) return Boolean; overriding function Is_Select_Statement_Element (Self : Node) return Boolean; overriding function Is_Abort_Statement_Element (Self : Node) return Boolean; overriding function Is_Raise_Statement_Element (Self : Node) return Boolean; overriding function Is_Code_Statement_Element (Self : Node) return Boolean; overriding function Is_Path_Element (Self : Node) return Boolean; overriding function Is_Elsif_Path_Element (Self : Node) return Boolean; overriding function Is_Case_Path_Element (Self : Node) return Boolean; overriding function Is_Select_Path_Element (Self : Node) return Boolean; overriding function Is_Case_Expression_Path_Element (Self : Node) return Boolean; overriding function Is_Elsif_Expression_Path_Element (Self : Node) return Boolean; overriding function Is_Clause_Element (Self : Node) return Boolean; overriding function Is_Use_Clause_Element (Self : Node) return Boolean; overriding function Is_With_Clause_Element (Self : Node) return Boolean; overriding function Is_Representation_Clause_Element (Self : Node) return Boolean; overriding function Is_Component_Clause_Element (Self : Node) return Boolean; overriding function Is_Derived_Type_Element (Self : Node) return Boolean; overriding function Is_Derived_Record_Extension_Element (Self : Node) return Boolean; overriding function Is_Enumeration_Type_Element (Self : Node) return Boolean; overriding function Is_Signed_Integer_Type_Element (Self : Node) return Boolean; overriding function Is_Modular_Type_Element (Self : Node) return Boolean; overriding function Is_Root_Type_Element (Self : Node) return Boolean; overriding function Is_Floating_Point_Type_Element (Self : Node) return Boolean; overriding function Is_Ordinary_Fixed_Point_Type_Element (Self : Node) return Boolean; overriding function Is_Decimal_Fixed_Point_Type_Element (Self : Node) return Boolean; overriding function Is_Unconstrained_Array_Type_Element (Self : Node) return Boolean; overriding function Is_Constrained_Array_Type_Element (Self : Node) return Boolean; overriding function Is_Record_Type_Element (Self : Node) return Boolean; overriding function Is_Interface_Type_Element (Self : Node) return Boolean; overriding function Is_Object_Access_Type_Element (Self : Node) return Boolean; overriding function Is_Procedure_Access_Type_Element (Self : Node) return Boolean; overriding function Is_Function_Access_Type_Element (Self : Node) return Boolean; overriding function Is_Formal_Private_Type_Definition_Element (Self : Node) return Boolean; overriding function Is_Formal_Derived_Type_Definition_Element (Self : Node) return Boolean; overriding function Is_Formal_Discrete_Type_Definition_Element (Self : Node) return Boolean; overriding function Is_Formal_Signed_Integer_Type_Definition_Element (Self : Node) return Boolean; overriding function Is_Formal_Modular_Type_Definition_Element (Self : Node) return Boolean; overriding function Is_Formal_Floating_Point_Definition_Element (Self : Node) return Boolean; overriding function Is_Formal_Ordinary_Fixed_Point_Definition_Element (Self : Node) return Boolean; overriding function Is_Formal_Decimal_Fixed_Point_Definition_Element (Self : Node) return Boolean; overriding function Is_Formal_Unconstrained_Array_Type_Element (Self : Node) return Boolean; overriding function Is_Formal_Constrained_Array_Type_Element (Self : Node) return Boolean; overriding function Is_Formal_Access_Type_Element (Self : Node) return Boolean; overriding function Is_Formal_Object_Access_Type_Element (Self : Node) return Boolean; overriding function Is_Formal_Procedure_Access_Type_Element (Self : Node) return Boolean; overriding function Is_Formal_Function_Access_Type_Element (Self : Node) return Boolean; overriding function Is_Formal_Interface_Type_Element (Self : Node) return Boolean; overriding function Is_Access_Type_Element (Self : Node) return Boolean; overriding function Is_Range_Attribute_Reference_Element (Self : Node) return Boolean; overriding function Is_Simple_Expression_Range_Element (Self : Node) return Boolean; overriding function Is_Digits_Constraint_Element (Self : Node) return Boolean; overriding function Is_Delta_Constraint_Element (Self : Node) return Boolean; overriding function Is_Index_Constraint_Element (Self : Node) return Boolean; overriding function Is_Discriminant_Constraint_Element (Self : Node) return Boolean; overriding function Is_Attribute_Definition_Clause_Element (Self : Node) return Boolean; overriding function Is_Enumeration_Representation_Clause_Element (Self : Node) return Boolean; overriding function Is_Record_Representation_Clause_Element (Self : Node) return Boolean; overriding function Is_At_Clause_Element (Self : Node) return Boolean; overriding function Is_Exception_Handler_Element (Self : Node) return Boolean; end Program.Nodes;
package OCONST2 is type u8 is mod 2**8; type Base is record i1 : Integer; end Record; type R is record u : u8; b : Base; end record; for R use record u at 0 range 0 .. 7; b at 1 range 0 .. 31; -- aligned SImode bitfield end record; My_R : constant R := (u=>1, b=>(i1=>2)); procedure check (arg : R); end;
package RTCH.Maths.Tuples with Pure is type Tuple is record X : Float; Y : Float; Z : Float; W : Float; end record; function "+" (Left, Right : in Tuple) return Tuple is (Tuple'(X => Left.X + Right.X, Y => Left.Y + Right.Y, Z => Left.Z + Right.Z, W => Left.W + Right.W)); function "-" (Right : in Tuple) return Tuple is (Tuple'(X => -Right.X, Y => -Right.Y, Z => -Right.Z, W => -Right.W)); function "*" (Left : in Tuple; Right : in Float) return Tuple is (Tuple'(X => Left.X * Right, Y => Left.Y * Right, Z => Left.Z * Right, W => Left.W * Right)); function "/" (Left : in Tuple; Right : in Float) return Tuple is (Tuple'(X => Left.X / Right, Y => Left.Y / Right, Z => Left.Z / Right, W => Left.W / Right)); function Is_Point (T : in Tuple) return Boolean is (T.W = 1.0); function Is_Vector (T : in Tuple) return Boolean is (T.W = 0.0); end RTCH.Maths.Tuples;
with Ada.Finalization; with Ada.Streams; with Ada.Strings.Unbounded; with Interfaces; with kv.avm.Instructions; with kv.avm.Tuples; with kv.avm.Actor_References; with kv.avm.references; package kv.avm.Registers is Unimplemented_Error : exception; subtype String_Type is Ada.Strings.Unbounded.Unbounded_String; function "+"(S : String) return String_Type; function "+"(U : String_Type) return String; type Data_Kind is (Unset, Signed_Integer, Unsigned_Integer, Floatingpoint, Bit_Or_Boolean, Tuple, Tuple_Map, Immutable_String, Actor_Reference, -- A reference to an actor instance (can't be used to create a new actor) Actor_Definition, -- The type of actor being created (and constructor message definition) Message_Definition, Future, Tuple_Definition); for Data_Kind'SIZE use 4; type Signature_Type is array (positive range <>) of Data_Kind; type Signature_Access is access Signature_Type; function Signature(Format : in Data_Kind) return Character; function Format(Signature : in Character) return Data_Kind; -- Will return Unset for unrecognized signatures function Signature_To_String(Signature : in Signature_Type) return String; function String_To_Signature(Signature : in String) return Signature_Type; type Constant_String_Access is access constant String; -- This is a variant record so that it is a constrained type and can be used -- in an array. -- type Register_Type(format : Data_Kind := Unset) is record case format is when Signed_Integer => Signed_Value : Interfaces.Integer_64; when Unsigned_Integer => Unsigned_Value : Interfaces.Unsigned_64; when Bit_Or_Boolean => Bit : boolean; when Floatingpoint => Value : Interfaces.IEEE_Float_64; when Tuple => Folded_Tuple : kv.avm.Tuples.Tuple_Type; when Tuple_Map => Map : kv.avm.Tuples.Map_Type; when Actor_Reference => Instance : kv.avm.Actor_References.Actor_Reference_Type; when Actor_Definition => Actor_Kind : String_Type; when Immutable_String => The_String : String_Type; when Future => ID : Interfaces.Unsigned_32; when Message_Definition => Message_Name : String_Type; Send_Count : Interfaces.Unsigned_32; -- how many elements are in the message tuple Reply_Count : Interfaces.Unsigned_32; -- how many elements are in the reply tuple --TODO Add tuple profiles when others => null; end case; end record; function Reg_Img(Reg : Register_Type) return String; procedure Register_Write(Stream : not null access Ada.Streams.Root_Stream_Type'CLASS; Item : in Register_Type); for Register_Type'WRITE use Register_Write; procedure Register_Read(Stream : not null access Ada.Streams.Root_Stream_Type'CLASS; Item : out Register_Type); for Register_Type'READ use Register_Read; function Bool(B : Boolean) return String; function Make_Tuple_Map(Value : kv.avm.references.Reference_Array_Type) return Register_Type; function String_To_Tuple_Map(Token : String) return Register_Type; function Make_S(Value : Interfaces.Integer_64) return Register_Type; function Make_U(Value : Interfaces.Unsigned_64) return Register_Type; function Make_String(Value : String) return Register_Type; function Make_Tuple(Value : kv.avm.Tuples.Tuple_Type) return Register_Type; function Make_Ref(Value : kv.avm.Actor_References.Actor_Reference_Type) return Register_Type; end kv.avm.Registers;
-- 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.Containers.Hashed_Maps; use Ada.Containers; with Ada.Strings.Unbounded.Hash; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with DOM.Readers; use DOM.Readers; with ShipModules; use ShipModules; with Game; use Game; with Ships; use Ships; -- ****h* Crafts/Crafts -- FUNCTION -- Provide code for crafting -- SOURCE package Crafts is -- **** -- ****s* Crafts/Crafts.Craft_Data -- FUNCTION -- Data structure for recipes -- PARAMETERS -- MaterialTypes - Types of material needed for recipe -- MaterialAmounts - Amounts of material needed for recipe -- ResultIndex - Prototype index of crafted item -- ResultAmount - Amount of products -- Workplace - Ship module needed for crafting -- Skill - Skill used in crafting item -- Time - Minutes needed for finish recipe -- Difficulty - How difficult is recipe to discover -- Tool - Type of tool used to craft item -- Reputation - Minimal reputation in base needed to buy that recipe -- ToolQuality - Minimal quality of tool needed to craft that recipe -- SOURCE type Craft_Data is record MaterialTypes: UnboundedString_Container.Vector; MaterialAmounts: Positive_Container.Vector; ResultIndex: Unbounded_String; ResultAmount: Natural := 0; Workplace: ModuleType; Skill: SkillsData_Container.Extended_Index; Time: Positive := 1; Difficulty: Positive := 1; Tool: Unbounded_String; Reputation: Reputation_Range; ToolQuality: Positive := 1; end record; -- **** -- ****t* Crafts/Crafts.Recipes_Container -- SOURCE package Recipes_Container is new Hashed_Maps (Unbounded_String, Craft_Data, Ada.Strings.Unbounded.Hash, "="); -- **** -- ****v* Crafts/Crafts.Recipes_List -- FUNCTION -- List of recipes available in game -- SOURCE Recipes_List: Recipes_Container.Map; -- **** -- ****v* Crafts/Crafts.Known_Recipes -- FUNCTION -- List of all know by player recipes -- SOURCE Known_Recipes: UnboundedString_Container.Vector; -- **** -- ****e* Crafts/Crafts.Crafting_No_Materials -- FUNCTION -- Raised when no materials needed for selected recipe -- SOURCE Crafting_No_Materials: exception; -- **** -- ****e* Crafts/Crafts.Crafting_No_Tools -- FUNCTION -- Raised when no tool needed for selected recipe -- SOURCE Crafting_No_Tools: exception; -- **** -- ****e* Crafts/Crafts.Crafting_No_Workshop -- FUNCTION -- Raised when no workshop needed for selected recipe -- SOURCE Crafting_No_Workshop: exception; -- **** -- ****f* Crafts/Crafts.LoadRecipes -- FUNCTION -- Load recipes from files -- PARAMETERS -- Reader - XML reader from which recipes will be read -- SOURCE procedure LoadRecipes(Reader: Tree_Reader); -- **** -- ****f* Crafts/Crafts.Manufacturing -- FUNCTION -- Craft selected items -- PARAMETERS -- Minutes - How many in game minutes passed -- SOURCE procedure Manufacturing(Minutes: Positive) with Test_Case => (Name => "Test_Manufacturing", Mode => Robustness); -- **** -- ****f* Crafts/Crafts.SetRecipeData -- FUNCTION -- Set crafting data for selected recipe -- PARAMETERS -- RecipeIndex - Index of recipe from Recipes_List or full name of recipe -- for deconstructing -- RESULT -- Crafting data for selected recipe -- SOURCE function SetRecipeData(RecipeIndex: Unbounded_String) return Craft_Data; -- **** -- ****f* Crafts/Crafts.CheckRecipe -- FUNCTION -- Check if player have all requirements for selected recipe -- PARAMETERS -- RecipeIndex - Index of the prototype recipe to check or if deconstruct -- existing item, "Study " + item name. -- RESULT -- Max amount of items which can be craft -- SOURCE function CheckRecipe(RecipeIndex: Unbounded_String) return Positive with Pre => RecipeIndex /= Null_Unbounded_String, Test_Case => (Name => "Test_CheckRecipe", Mode => Nominal); -- **** -- ****f* Crafts/Crafts.SetRecipe -- FUNCTION -- Set crafting recipe for selected workshop -- PARAMETERS -- Workshop - Index of player ship module (workplace) to which -- selected recipe will be set -- Amount - How many times the recipe will be crafted -- RecipeIndex - Index of the prototype recipe to check or if deconstruct -- existing item, "Study " + item name. -- SOURCE procedure SetRecipe (Workshop, Amount: Positive; RecipeIndex: Unbounded_String) with Pre => (Workshop <= Player_Ship.Modules.Last_Index and RecipeIndex /= Null_Unbounded_String), Test_Case => (Name => "Test_SetRecipe", Mode => Nominal); -- **** end Crafts;
package body agar.gui.unit is package cbinds is function find (key : cs.chars_ptr) return unit_const_access_t; pragma import (c, find, "AG_FindUnit"); function best (unit_group : unit_const_access_t; n : c.double) return unit_const_access_t; pragma import (c, best, "AG_BestUnit"); function unit_to_base (n : c.double; unit_group : unit_const_access_t) return c.double; pragma import (c, unit_to_base, "agar_unit2base"); function base_to_unit (n : c.double; unit_group : unit_const_access_t) return c.double; pragma import (c, base_to_unit, "agar_base2unit"); function unit_to_unit (n : c.double; unit_from : unit_const_access_t; unit_to : unit_const_access_t) return c.double; pragma import (c, unit_to_unit, "agar_unit2unit"); end cbinds; function find (key : string) return unit_const_access_t is ca_key : aliased c.char_array := c.to_c (key); begin return cbinds.find (cs.to_chars_ptr (ca_key'unchecked_access)); end find; function best (unit_group : unit_const_access_t; n : long_float) return unit_const_access_t is begin return cbinds.best (unit_group, c.double (n)); end best; function abbreviation (unit : unit_const_access_t) return string is begin return cs.value (abbreviation (unit)); end abbreviation; function unit_to_base (n : long_float; unit_group : unit_const_access_t) return long_float is ret : constant c.double := cbinds.unit_to_base (c.double (n), unit_group); begin return long_float (ret); end unit_to_base; function base_to_unit (n : long_float; unit_group : unit_const_access_t) return long_float is ret : constant c.double := cbinds.base_to_unit (c.double (n), unit_group); begin return long_float (ret); end base_to_unit; function unit_to_unit (n : long_float; unit_from : unit_const_access_t; unit_to : unit_const_access_t) return long_float is ret : constant c.double := cbinds.unit_to_unit (c.double (n), unit_from, unit_to); begin return long_float (ret); end unit_to_unit; end agar.gui.unit;
with Ada.Text_IO; use Ada.Text_IO; procedure Test is x: integer := 2147483648; begin Put('a'); end;
with utils, ada.text_io, ada.Float_Text_IO, ada.Integer_Text_IO; use utils, ada.text_io, ada.Float_Text_IO, ada.Integer_Text_IO; package montecarlo is --E/ cards : T_set --E/S/ sample : T_set --Necessite : Table ne contient pas plus de 5 cartes --Entraine : Genere 50 000 jeux en completant le jeu existant (donne par -- la main et les cartes communes revelees) avec des cartes aleatoires function initSample(sample : in out T_Set; hand : in T_set; table : in T_set) return Integer; --E/ hand, table : T_set --Necessite : hand contient 2 cartes et table contient 1 a 4 cartes --S/ chance de gain : float --Entraine : Calcule la porbabilte de gagner avec la methode de Monte Carlo function chancesOfWinning(hand : T_set; table : T_set) return float; --E/ max : integer --Necessite : none --S/ card : T_carte --Entraine : Renvoie une carte aleatoire function randomCard(max : in Integer) return T_card; end montecarlo;
with System.Address_To_Access_Conversions; package body zlib.Streams is generic with procedure Deflate_Or_Inflate ( Stream : in out zlib.Stream; In_Item : in Ada.Streams.Stream_Element_Array; In_Last : out Ada.Streams.Stream_Element_Offset; Out_Item : out Ada.Streams.Stream_Element_Array; Out_Last : out Ada.Streams.Stream_Element_Offset; Finish : in Boolean; Finished : out Boolean); procedure Generic_Finish ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Object : in out zlib.Stream); procedure Generic_Finish ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Object : in out zlib.Stream) is Dummy_In_Item : Ada.Streams.Stream_Element_Array (1 .. 0); Dummy_In_Used : Ada.Streams.Stream_Element_Offset; Out_Item : Ada.Streams.Stream_Element_Array (1 .. 2 ** 15); Out_Last : Ada.Streams.Stream_Element_Offset; Finished : Boolean; begin loop Deflate_Or_Inflate ( Object, Dummy_In_Item, Dummy_In_Used, Out_Item, Out_Last, True, Finished); Ada.Streams.Write (Stream.all, Out_Item (Out_Item'First .. Out_Last)); exit when Finished; end loop; end Generic_Finish; generic with procedure Deflate_Or_Inflate ( Stream : in out zlib.Stream; In_Item : in Ada.Streams.Stream_Element_Array; In_Last : out Ada.Streams.Stream_Element_Offset; Out_Item : out Ada.Streams.Stream_Element_Array; Out_Last : out Ada.Streams.Stream_Element_Offset; Finish : in Boolean; Finished : out Boolean); procedure Generic_Read ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Object : in out zlib.Stream; Reading_In_First : in out Ada.Streams.Stream_Element_Offset; Reading_In_Last : in out Ada.Streams.Stream_Element_Offset; Reading_In_Buffer : in out Ada.Streams.Stream_Element_Array); procedure Generic_Read ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Object : in out zlib.Stream; Reading_In_First : in out Ada.Streams.Stream_Element_Offset; Reading_In_Last : in out Ada.Streams.Stream_Element_Offset; Reading_In_Buffer : in out Ada.Streams.Stream_Element_Array) is begin if Controlled.Reference (Object).Stream_End then Last := Item'First - 1; else declare In_Used : Ada.Streams.Stream_Element_Offset; Out_First : Ada.Streams.Stream_Element_Offset := Item'First; Finish : Boolean := False; Finished : Boolean; begin loop if Reading_In_First > Reading_In_Last then Reading_In_First := Reading_In_Buffer'First; begin Ada.Streams.Read (Stream.all, Reading_In_Buffer, Reading_In_Last); exception when End_Error => Reading_In_Last := Reading_In_First - 1; end; if Reading_In_Last < Reading_In_Buffer'First then Finish := True; end if; end if; Deflate_Or_Inflate ( Object, Reading_In_Buffer (Reading_In_First .. Reading_In_Last), In_Used, Item (Out_First .. Item'Last), Last, Finish, Finished); Reading_In_First := In_Used + 1; exit when Finished or else Last >= Item'Last; Out_First := Last + 1; end loop; end; end if; if Last = Item'First - 1 then raise End_Error; end if; end Generic_Read; generic with procedure Deflate_Or_Inflate ( Stream : in out zlib.Stream; In_Item : in Ada.Streams.Stream_Element_Array; In_Last : out Ada.Streams.Stream_Element_Offset; Out_Item : out Ada.Streams.Stream_Element_Array; Out_Last : out Ada.Streams.Stream_Element_Offset; Finish : in Boolean; Finished : out Boolean); procedure Generic_Write ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : in Ada.Streams.Stream_Element_Array; Object : in out zlib.Stream); procedure Generic_Write ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : in Ada.Streams.Stream_Element_Array; Object : in out zlib.Stream) is begin if Item'First <= Item'Last then declare In_First : Ada.Streams.Stream_Element_Offset := Item'First; In_Used : Ada.Streams.Stream_Element_Offset; Out_Item : Ada.Streams.Stream_Element_Array (1 .. 2 ** 15); Out_Last : Ada.Streams.Stream_Element_Offset; Finished : Boolean; begin loop Deflate_Or_Inflate ( Object, Item (In_First .. Item'Last), In_Used, Out_Item, Out_Last, False, Finished); Ada.Streams.Write (Stream.all, Out_Item (Out_Item'First .. Out_Last)); exit when Finished or else In_Used >= Item'Last; In_First := In_Used + 1; end loop; end; end if; end Generic_Write; -- only writing with deflation function Open ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Level : Compression_Level := Default_Compression; Method : Compression_Method := Deflated; Window_Bits : zlib.Window_Bits := Default_Window_Bits; Header : Deflation_Header := Default; Memory_Level : zlib.Memory_Level := Default_Memory_Level; Strategy : zlib.Strategy := Default_Strategy) return Out_Type is package Conv is new System.Address_To_Access_Conversions (Ada.Streams.Root_Stream_Type'Class); begin return (Ada.Streams.Root_Stream_Type with Variable_View => <>, -- default value Stream => Conv.To_Address (Conv.Object_Pointer (Stream)), Deflator => Deflate_Init ( Level => Level, Method => Method, Window_Bits => Window_Bits, Header => Header, Memory_Level => Memory_Level, Strategy => Strategy)); end Open; procedure Close (Object : in out Out_Type) is pragma Check (Dynamic_Predicate, Check => Is_Open (Object) or else raise Status_Error); begin Close (Object.Deflator); end Close; function Is_Open (Object : Out_Type) return Boolean is begin return Is_Open (Object.Deflator); end Is_Open; function Stream ( Object : in out Out_Type) return not null access Ada.Streams.Root_Stream_Type'Class is pragma Check (Dynamic_Predicate, Check => Is_Open (Object) or else raise Status_Error); begin return Object.Variable_View; end Stream; procedure Finish ( Object : in out Out_Type) is pragma Check (Dynamic_Predicate, Check => Is_Open (Object) or else raise Status_Error); package Conv is new System.Address_To_Access_Conversions (Ada.Streams.Root_Stream_Type'Class); procedure Deflating_Finish is new Generic_Finish (Deflate); begin Deflating_Finish (Conv.To_Pointer (Object.Stream), Object.Deflator); end Finish; overriding procedure Read ( Object : in out Out_Type; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is pragma Check (Dynamic_Predicate, Check => Boolean'(raise Mode_Error)); begin raise Program_Error; -- exclusive use for writing end Read; overriding procedure Write ( Object : in out Out_Type; Item : in Ada.Streams.Stream_Element_Array) is package Conv is new System.Address_To_Access_Conversions (Ada.Streams.Root_Stream_Type'Class); procedure Deflating_Write is new Generic_Write (Deflate); begin Deflating_Write (Conv.To_Pointer (Object.Stream), Item, Object.Deflator); end Write; -- only reading with inflation function Open ( Stream : not null access Ada.Streams.Root_Stream_Type'Class; Window_Bits : zlib.Window_Bits := Default_Window_Bits; Header : Inflation_Header := Auto; Buffer_Length : Ada.Streams.Stream_Element_Count := Default_Buffer_Length) return In_Type is package Conv is new System.Address_To_Access_Conversions (Ada.Streams.Root_Stream_Type'Class); begin return (Ada.Streams.Root_Stream_Type with Variable_View => <>, -- default value Buffer_Length => Buffer_Length, Stream => Conv.To_Address (Conv.Object_Pointer (Stream)), Inflator => Inflate_Init (Window_Bits => Window_Bits, Header => Header), In_Buffer => <>, In_First => 0, In_Last => -1); end Open; procedure Close (Object : in out In_Type) is pragma Check (Dynamic_Predicate, Check => Is_Open (Object) or else raise Status_Error); begin Close (Object.Inflator); end Close; function Is_Open (Object : In_Type) return Boolean is begin return Is_Open (Object.Inflator); end Is_Open; function Stream ( Object : in out In_Type) return not null access Ada.Streams.Root_Stream_Type'Class is pragma Check (Dynamic_Predicate, Check => Is_Open (Object) or else raise Status_Error); begin return Object.Variable_View; end Stream; overriding procedure Read ( Object : in out In_Type; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is package Conv is new System.Address_To_Access_Conversions (Ada.Streams.Root_Stream_Type'Class); procedure Deflating_Read is new Generic_Read (Inflate); begin Deflating_Read ( Conv.To_Pointer (Object.Stream), Item, Last, Object.Inflator, Object.In_First, Object.In_Last, Object.In_Buffer); end Read; overriding procedure Write ( Object : in out In_Type; Item : in Ada.Streams.Stream_Element_Array) is pragma Check (Dynamic_Predicate, Check => Boolean'(raise Mode_Error)); begin raise Program_Error; -- exclusive use for reading end Write; -- compatibility procedure Create ( Stream : in out Stream_Type'Class; Mode : in Stream_Mode; Back : access Ada.Streams.Root_Stream_Type'Class; Back_Compressed : in Boolean; Level : in Compression_Level := Default_Compression; Strategy : in Strategy_Type := Default_Strategy; Header : in Header_Type := Default) is pragma Check (Dynamic_Predicate, Check => not Is_Open (Stream) or else raise Status_Error); package Conv is new System.Address_To_Access_Conversions (Ada.Streams.Root_Stream_Type'Class); begin Stream.Direction := Mode; Stream.Target := Conv.To_Address (Conv.Object_Pointer (Back)); Stream.In_First := 0; Stream.In_Last := -1; if (Mode = Out_Stream) = Back_Compressed then Deflate_Init ( Stream.Raw, Level => Level, Header => Header, Strategy => Strategy); else Inflate_Init (Stream.Raw, Header => Header); end if; end Create; procedure Close (Object : in out Stream_Type'Class) is pragma Check (Dynamic_Predicate, Check => Is_Open (Object) or else raise Status_Error); begin Close (Object.Raw); end Close; function Is_Open (Object : Stream_Type'Class) return Boolean is begin return Is_Open (Object.Raw); end Is_Open; procedure Flush (Stream : in out Stream_Type'Class; Mode : in Flush_Mode) is pragma Check (Dynamic_Predicate, Check => Is_Open (Stream) or else raise Status_Error); package Conv is new System.Address_To_Access_Conversions (Ada.Streams.Root_Stream_Type'Class); begin if Mode then declare procedure DI_Finish is new Generic_Finish (Deflate_Or_Inflate); begin DI_Finish (Conv.To_Pointer (Stream.Target), Stream.Raw); end; end if; end Flush; function Read_Total_In (Stream : Stream_Type'Class) return Count is begin return Total_In (Stream.Raw); end Read_Total_In; function Read_Total_Out (Stream : Stream_Type'Class) return Count is begin return Total_Out (Stream.Raw); end Read_Total_Out; function Write_Total_In (Stream : Stream_Type'Class) return Count renames Read_Total_Out; function Write_Total_Out (Stream : Stream_Type'Class) return Count renames Read_Total_Out; overriding procedure Read ( Object : in out Stream_Type; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is pragma Check (Dynamic_Predicate, Check => Is_Open (Object) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Object.Direction = In_Stream or else raise Mode_Error); package Conv is new System.Address_To_Access_Conversions (Ada.Streams.Root_Stream_Type'Class); procedure DI_Read is new Generic_Read (Deflate_Or_Inflate); begin DI_Read ( Conv.To_Pointer (Object.Target), Item, Last, Object.Raw, Object.In_First, Object.In_Last, Object.In_Buffer); end Read; overriding procedure Write ( Object : in out Stream_Type; Item : in Ada.Streams.Stream_Element_Array) is pragma Check (Dynamic_Predicate, Check => Is_Open (Object) or else raise Status_Error); pragma Check (Dynamic_Predicate, Check => Object.Direction = Out_Stream or else raise Mode_Error); package Conv is new System.Address_To_Access_Conversions (Ada.Streams.Root_Stream_Type'Class); procedure DI_Write is new Generic_Write (Deflate_Or_Inflate); begin DI_Write (Conv.To_Pointer (Object.Target), Item, Object.Raw); end Write; end zlib.Streams;
with CLIC.Subcommand; private with Ada.Text_IO; private with GNAT.OS_Lib; private with CLIC.Subcommand.Instance; private with CLIC.TTY; private with FSmaker.Target; package FSmaker.Commands is procedure Set_Global_Switches (Config : in out CLIC.Subcommand.Switches_Configuration); procedure Execute; function Format return String; function Image_Path return String; function Verbose return Boolean; function Debug return Boolean; type Command is abstract new CLIC.Subcommand.Command with private; function Switch_Parsing (This : Command) return CLIC.Subcommand.Switch_Parsing_Kind is (CLIC.Subcommand.Parse_All); procedure Setup_Image (This : in out Command; To_Format : Boolean := False); procedure Close_Image (This : in out Command); procedure Success (This : in out Command); procedure Failure (This : in out Command; Msg : String) with No_Return; procedure Usage_Error (This : in out Command; Msg : String) with No_Return; private Sw_Format : aliased GNAT.OS_Lib.String_Access; Sw_Image : aliased GNAT.OS_Lib.String_Access; Sw_Verbose : aliased Boolean; Sw_Debug : aliased Boolean; function Format return String is (if GNAT.OS_Lib."=" (Sw_Format, null) then "" else Sw_Format.all); function Image_Path return String is (if GNAT.OS_Lib."=" (Sw_Image, null) then "" else Sw_Image.all); function Verbose return Boolean is (Sw_Verbose); function Debug return Boolean is (Sw_Debug); procedure Put_Error (Str : String); package Sub_Cmd is new CLIC.Subcommand.Instance (Main_Command_Name => "fsmaker", Version => "0.1.0-dev", Set_Global_Switches => Set_Global_Switches, Put => Ada.Text_IO.Put, Put_Line => Ada.Text_IO.Put_Line, Put_Error => Put_Error, Error_Exit => GNAT.OS_Lib.OS_Exit, TTY_Chapter => CLIC.TTY.Info, TTY_Description => CLIC.TTY.Description, TTY_Version => CLIC.TTY.Version, TTY_Underline => CLIC.TTY.Underline, TTY_Emph => CLIC.TTY.Emph); type Command is abstract new CLIC.Subcommand.Command with record FD : GNAT.OS_Lib.File_Descriptor; Target : FSmaker.Target.Any_Filesystem_Ref := null; end record; end FSmaker.Commands;
pragma License (Unrestricted); -- Ada 2012 private with Ada.Containers.Copy_On_Write; private with Ada.Finalization; private with Ada.Streams; generic type Element_Type (<>) is private; with function "=" (Left, Right : Element_Type) return Boolean is <>; package Ada.Containers.Indefinite_Holders is pragma Preelaborate; pragma Remote_Types; type Holder is tagged private; pragma Preelaborable_Initialization (Holder); -- modified -- Empty_Holder : constant Holder; function Empty_Holder return Holder; overriding function "=" (Left, Right : Holder) return Boolean; function To_Holder (New_Item : Element_Type) return Holder; function Is_Empty (Container : Holder) return Boolean; procedure Clear (Container : in out Holder); -- modified function Element (Container : Holder'Class) -- not primitive return Element_Type; procedure Replace_Element ( Container : in out Holder; New_Item : Element_Type); -- modified procedure Query_Element ( Container : Holder'Class; -- not primitive Process : not null access procedure (Element : Element_Type)); -- modified procedure Update_Element ( Container : in out Holder'Class; -- not primitive Process : not null access procedure (Element : in out Element_Type)); type Constant_Reference_Type ( Element : not null access constant Element_Type) is private with Implicit_Dereference => Element; type Reference_Type (Element : not null access Element_Type) is private with Implicit_Dereference => Element; function Constant_Reference (Container : aliased Holder) return Constant_Reference_Type; function Reference (Container : aliased in out Holder) return Reference_Type; procedure Assign (Target : in out Holder; Source : Holder); function Copy (Source : Holder) return Holder; procedure Move (Target : in out Holder; Source : in out Holder); private type Element_Access is access Element_Type; type Data is limited record Super : aliased Copy_On_Write.Data; Element : Element_Access; end record; pragma Suppress_Initialization (Data); type Data_Access is access all Data; type Holder is new Finalization.Controlled with record Super : aliased Copy_On_Write.Container; end record; overriding procedure Adjust (Object : in out Holder); overriding procedure Finalize (Object : in out Holder) renames Clear; type Constant_Reference_Type ( Element : not null access constant Element_Type) is null record; type Reference_Type (Element : not null access Element_Type) is null record; package Streaming is procedure Read ( Stream : not null access Streams.Root_Stream_Type'Class; Item : out Holder); procedure Write ( Stream : not null access Streams.Root_Stream_Type'Class; Item : Holder); procedure Missing_Read ( Stream : access Streams.Root_Stream_Type'Class; Item : out Constant_Reference_Type) with Import, Convention => Ada, External_Name => "__drake_program_error"; procedure Missing_Write ( Stream : access Streams.Root_Stream_Type'Class; Item : Constant_Reference_Type) with Import, Convention => Ada, External_Name => "__drake_program_error"; procedure Missing_Read ( Stream : access Streams.Root_Stream_Type'Class; Item : out Reference_Type) with Import, Convention => Ada, External_Name => "__drake_program_error"; procedure Missing_Write ( Stream : access Streams.Root_Stream_Type'Class; Item : Reference_Type) with Import, Convention => Ada, External_Name => "__drake_program_error"; end Streaming; for Holder'Read use Streaming.Read; for Holder'Write use Streaming.Write; for Constant_Reference_Type'Read use Streaming.Missing_Read; for Constant_Reference_Type'Write use Streaming.Missing_Write; for Reference_Type'Read use Streaming.Missing_Read; for Reference_Type'Write use Streaming.Missing_Write; end Ada.Containers.Indefinite_Holders;
with SDA_Exceptions; use SDA_Exceptions; -- Définition de structures de données associatives sous forme d'une liste -- chaînée associative (LCA). generic type T_Cle is private; type T_Donnee is private; package LCA is type T_LCA is private; -- Initialiser une Sda. La Sda est vide. procedure Initialiser(Sda: out T_LCA) with Post => Est_Vide (Sda); -- Est-ce qu'une Sda est vide ? function Est_Vide (Sda : T_LCA) return Boolean; -- Obtenir le nombre d'éléments d'une Sda. function Taille (Sda : in T_LCA) return Integer with Post => Taille'Result >= 0 and (Taille'Result = 0) = Est_Vide (Sda); -- Enregistrer une Donnée associée à une Clé dans une Sda. -- Si la clé est déjà présente dans la Sda, sa donnée est changée. procedure Enregistrer (Sda : in out T_LCA ; Cle : in T_Cle ; Donnee : in T_Donnee) with Post => Cle_Presente (Sda, Cle) and then (La_Donnee (Sda, Cle) = Donnee) -- donnée insérée -- and then (if not (Cle_Presente (Sda, Cle)'Old) then Taille (Sda) = Taille (Sda)'Old) -- and then (if Cle_Presente (Sda, Cle)'Old then Taille (Sda) = Taille (Sda)'Old + 1) ; -- Supprimer la Donnée associée à une Clé dans une Sda. -- Exception : Cle_Absente_Exception si Clé n'est pas utilisée dans la Sda procedure Supprimer (Sda : in out T_LCA ; Cle : in T_Cle) with Post => Taille (Sda) = Taille (Sda)'Old - 1 -- un élément de moins and not Cle_Presente (Sda, Cle); -- la clé a été supprimée -- Savoir si une Clé est présente dans une Sda. function Cle_Presente (Sda : in T_LCA ; Cle : in T_Cle) return Boolean; -- Obtenir la donnée associée à une Cle dans la Sda. -- Exception : Cle_Absente_Exception si Clé n'est pas utilisée dans l'Sda function La_Donnee (Sda : in T_LCA ; Cle : in T_Cle) return T_Donnee; -- Supprimer tous les éléments d'une Sda. procedure Vider (Sda : in out T_LCA) with Post => Est_Vide (Sda); -- Appliquer un traitement (Traiter) pour chaque couple d'une Sda. generic with procedure Traiter (Cle : in T_Cle; Donnee: in T_Donnee); procedure Pour_Chaque (Sda : in T_LCA); private type T_Cellule; type T_LCA is access T_Cellule; type T_Cellule is record Cle : T_Cle; Donnee : T_Donnee; Suivant : T_LCA; end record; end LCA;
with ada.text_io; package body keyevent_callbacks is package io renames ada.text_io; procedure keydown (event : gui_event.event_access_t) is keyint : constant integer := gui_event.get_integer (event, 1); modint : constant integer := gui_event.get_integer (event, 2); keystr : constant string := integer'image (keyint); modstr : constant string := integer'image (modint); begin io.put_line ("keyevent: keydown key=" & keystr & " mod=" & modstr); end keydown; procedure keyup (event : gui_event.event_access_t) is begin io.put_line ("keyevent: keyup"); end keyup; procedure quit (event : gui_event.event_access_t) is begin io.put_line ("keyevent: exiting"); agar.core.quit; end quit; end keyevent_callbacks;
package Courbes.Droites is use Liste_Points; type Droite is new Courbe with private; -- Crée une droite function Ctor_Droite (Debut, Fin : Point2D) return Droite; -- Obtient un point d'une droite overriding function Obtenir_Point(Self : Droite; X : Coordonnee_Normalisee) return Point2D; overriding procedure Accepter (Self : Droite; Visiteur : Courbes.Visiteurs.Visiteur_Courbe'Class); private type Droite is new Courbe with record -- Longueur de la droite Longueur : Float; -- Vecteur normal Vecteur_Directeur : Point2D; end record; end Courbes.Droites;
package body Inline13_Pkg is function Padded (Value : T) return Padded_T is begin return Padded_T(Value); end Padded; end Inline13_Pkg;
----------------------------------------------------------------------- -- awa-questions-tests -- Unit tests for questions module -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Questions.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Questions.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load_List (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load (missing)", Test_Missing_Page'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save (answer)", Test_Answer_Question'Access); end Add_Tests; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/list.html", "question-list.html"); ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply, "Questions list page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/questions/tags/tag", "question-list-tagged.html"); ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply, "Questions tag page is invalid"); if Page'Length > 0 then ASF.Tests.Do_Get (Request, Reply, "/questions/view/" & Page, "question-page-" & Page & ".html"); ASF.Tests.Assert_Contains (T, Title, Reply, "Question page " & Page & " is invalid"); ASF.Tests.Assert_Matches (T, ".input type=.hidden. name=.question-id. " & "value=.[0-9]+. id=.question-id.../input", Reply, "Question page " & Page & " is invalid"); end if; end Verify_Anonymous; -- ------------------------------ -- Verify that the question list contains the given question. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Id : in String; Title : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/list.html", "question-list-recent.html"); ASF.Tests.Assert_Contains (T, "Questions", Reply, "List of questions page is invalid"); ASF.Tests.Assert_Contains (T, "/questions/view/" & Id, Reply, "List of questions page does not reference the page"); ASF.Tests.Assert_Contains (T, Title, Reply, "List of questions page does not contain the question"); end Verify_List_Contains; -- ------------------------------ -- Test access to the question as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of question by simulating web requests. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is procedure Create_Question (Title : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; procedure Create_Question (Title : in String) is begin Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("title", Title); Request.Set_Parameter ("text", "# Main title" & ASCII.LF & "* The question content." & ASCII.LF & "* Second item." & ASCII.LF); Request.Set_Parameter ("save", "1"); ASF.Tests.Do_Post (Request, Reply, "/questions/ask.html", "questions-ask.html"); T.Question_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/questions/view/"); Util.Tests.Assert_Matches (T, "[0-9]+$", To_String (T.Question_Ident), "Invalid redirect after question creation"); -- Remove the 'question' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("question"); end Create_Question; begin AWA.Tests.Helpers.Users.Login ("test-question@test.com", Request); Create_Question ("Question 1 page title1"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 1 page title1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 1 page title1"); Create_Question ("Question 2 page title2"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 2 page title2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 2 page title2"); Create_Question ("Question 3 page title3"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 3 page title3"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 3 page title3"); end Test_Create_Question; -- ------------------------------ -- Test getting a wiki page which does not exist. -- ------------------------------ procedure Test_Missing_Page (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/view.html?id=12345678", "question-page-missing.html"); ASF.Tests.Assert_Matches (T, "<title>Question not found</title>", Reply, "Question page title '12345678' is invalid", ASF.Responses.SC_NOT_FOUND); ASF.Tests.Assert_Matches (T, "question.*removed", Reply, "Question page content '12345678' is invalid", ASF.Responses.SC_NOT_FOUND); end Test_Missing_Page; -- ------------------------------ -- Test answer of question by simulating web requests. -- ------------------------------ procedure Test_Answer_Question (T : in out Test) is procedure Create_Answer (Content : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; procedure Create_Answer (Content : in String) is begin Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("question-id", To_String (T.Question_Ident)); Request.Set_Parameter ("answer-id", ""); Request.Set_Parameter ("text", Content); Request.Set_Parameter ("save", "1"); ASF.Tests.Do_Post (Request, Reply, "/questions/forms/answer-form.html", "questions-answer.html"); ASF.Tests.Assert_Contains (T, "/questions/view/" & To_String (T.Question_Ident), Reply, "Answer response is invalid"); -- Remove the 'question' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("answer"); end Create_Answer; begin AWA.Tests.Helpers.Users.Login ("test-answer@test.com", Request); Create_Answer ("Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); Create_Answer ("Answer content 2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 2"); Create_Answer ("Answer content 3"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 3"); end Test_Answer_Question; end AWA.Questions.Tests;
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 euler32 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; -- --We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; --for example, the 5-digit number, 15234, is 1 through 5 pandigital. -- --The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, --and product is 1 through 9 pandigital. -- --Find the sum of all products whose multiplicand/multiplier/product identity can be written as a --1 through 9 pandigital. -- --HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. -- -- --(a * 10 + b) ( c * 100 + d * 10 + e) = -- a * c * 1000 + -- a * d * 100 + -- a * e * 10 + -- b * c * 100 + -- b * d * 10 + -- b * e -- => b != e != b * e % 10 ET -- a != d != (b * e / 10 + b * d + a * e ) % 10 -- type f is Array (Integer range <>) of Boolean; type f_PTR is access f; function okdigits(ok : in f_PTR; n : in Integer) return Boolean is o : Boolean; digit : Integer; begin if n = 0 then return TRUE; else digit := n rem 10; if ok(digit) then ok(digit) := FALSE; o := okdigits(ok, n / 10); ok(digit) := TRUE; return o; else return FALSE; end if; end if; end; product2 : Integer; product : Integer; counted : f_PTR; count : Integer; be : Integer; allowed : f_PTR; begin count := 0; allowed := new f (0..9); for i in integer range 0..9 loop allowed(i) := i /= 0; end loop; counted := new f (0..99999); for j in integer range 0..99999 loop counted(j) := FALSE; end loop; for e in integer range 1..9 loop allowed(e) := FALSE; for b in integer range 1..9 loop if allowed(b) then allowed(b) := FALSE; be := b * e rem 10; if allowed(be) then allowed(be) := FALSE; for a in integer range 1..9 loop if allowed(a) then allowed(a) := FALSE; for c in integer range 1..9 loop if allowed(c) then allowed(c) := FALSE; for d in integer range 1..9 loop if allowed(d) then allowed(d) := FALSE; -- 2 * 3 digits product := (a * 10 + b) * (c * 100 + d * 10 + e); if not counted(product) and then okdigits(allowed, product / 10) then counted(product) := TRUE; count := count + product; PInt(product); PString(new char_array'( To_C(" "))); end if; -- 1 * 4 digits product2 := b * (a * 1000 + c * 100 + d * 10 + e); if not counted(product2) and then okdigits(allowed, product2 / 10) then counted(product2) := TRUE; count := count + product2; PInt(product2); PString(new char_array'( To_C(" "))); end if; allowed(d) := TRUE; end if; end loop; allowed(c) := TRUE; end if; end loop; allowed(a) := TRUE; end if; end loop; allowed(be) := TRUE; end if; allowed(b) := TRUE; end if; end loop; allowed(e) := TRUE; end loop; PInt(count); PString(new char_array'( To_C("" & Character'Val(10)))); end;
-- ___ _ ___ _ _ -- -- / __| |/ (_) | | Common SKilL implementation -- -- \__ \ ' <| | | |__ skills vector container implementation -- -- |___/_|\_\_|_|____| by: Dennis Przytarski, Timm Felden -- -- -- pragma Ada_2012; with Ada.Unchecked_Deallocation; package body Skill.Containers.Vectors is function Empty_Vector return Vector is begin return new Vector_T' (Data => new Element_Array_T (Index_Type'First .. Index_Type'First + 4), Next_Index => Index_Type'First); end Empty_Vector; procedure Free (This : access Vector_T) is type V is access all Vector_T; procedure Delete is new Ada.Unchecked_Deallocation (Element_Array_T, Element_Array_Access); procedure Delete is new Ada.Unchecked_Deallocation (Vector_T, V); D : Element_Array_Access := Element_Array_Access (This.Data); T : V := V (This); begin Delete (D); Delete (T); end Free; procedure Foreach (This : not null access Vector_T'Class; F : not null access procedure (I : Element_Type)) is begin for I in Index_Type'First .. Index_Type (This.Next_Index) - 1 loop F (This.Data (I)); end loop; end Foreach; procedure Append (This : not null access Vector_T'Class; New_Element : Element_Type) is begin -- if not (Index_Type (This.Next_Index) < This.Data'Last) then This.Ensure_Index (Index_Type (This.Next_Index)); -- end if; This.Append_Unsafe (New_Element); end Append; procedure Append_Unsafe (This : not null access Vector_T'Class; New_Element : Element_Type) is begin This.Data (Index_Type (This.Next_Index)) := New_Element; This.Next_Index := This.Next_Index + 1; end Append_Unsafe; procedure Append_All (This : access Vector_T'Class; Other : Vector) is begin if Other.Is_Empty then return; end if; This.Ensure_Index (Index_Base (This.Next_Index) + Index_Base (Other.Length)); for I in Index_Type'First .. Other.Next_Index - 1 loop This.Append_Unsafe (Other.Data (I)); end loop; end Append_All; procedure Prepend_All (This : access Vector_T'Class; Other : Vector) is I : Index_Type; Other_Length : Index_Type; begin if Other.Is_Empty then return; end if; Other_Length := Index_Type (Other.Length); I := Index_Base (This.Next_Index) + Index_Base (Other_Length); This.Ensure_Index (I); This.Next_Index := I; -- move elements from the back, so we can do it in one iteration loop I := I - 1; if I - Other_Length >= Index_Type'First then This.Data (I) := This.Data (I - Other_Length); else This.Data (I) := Other.Data (I); end if; exit when I = Index_Type'First; end loop; end Prepend_All; procedure Append_Undefined (This : access Vector_T'Class; Count : Natural) is I : Index_Type; begin if 0 = Count then return; end if; I := Index_Base (This.Next_Index) + Index_Base (Count); This.Ensure_Index (I); This.Next_Index := I; -- no move required end Append_Undefined; procedure Prepend_Undefined (This : access Vector_T'Class; Count : Natural) is I : Index_Type; begin if 0 = Count then return; end if; I := Index_Base (This.Next_Index) + Index_Base (Count); This.Ensure_Index (I); This.Next_Index := I; -- move elements from the back, so we can do it in one iteration while I - Index_Type (Count) > Index_Type'First loop I := I - 1; This.Data (I) := This.Data (I - Index_Type (Count)); end loop; end Prepend_Undefined; function Pop (This : access Vector_T'Class) return Element_Type is begin This.Next_Index := This.Next_Index - 1; return This.Data (Index_Type (This.Next_Index)); end Pop; function Element (This : access Vector_T'Class; Index : Index_Type) return Element_Type is begin if (Index < Index_Type (This.Next_Index)) then return This.Data (Index); else raise Constraint_Error with "index check failed: " & Integer'Image (Integer (Index)) & " >= " & Integer'Image (Integer (Index_Type (This.Next_Index))); end if; end Element; function Last_Element (This : access Vector_T'Class) return Element_Type is begin if Index_Type'First /= This.Next_Index then return This.Data (This.Next_Index - 1); else raise Constraint_Error with "empty vector has no last element"; end if; end Last_Element; -- returns the first element in the vector or raises constraint error if empty function First_Element (This : access Vector_T'Class) return Element_Type is (This.Data (Index_Type'First)); procedure Ensure_Index (This : access Vector_T'Class; New_Index : Index_Type) is procedure Delete is new Ada.Unchecked_Deallocation (Element_Array_T, Element_Array_Access); begin if New_Index < This.Data'Last then return; end if; declare New_Size : Index_Type'Base := 2 * This.Data'Length; begin if New_Index - Index_Type'First > New_Size then New_Size := 1 + New_Index - Index_Type'First; end if; New_Size := New_Size + Index_Type'First; declare New_Container : Element_Array := new Element_Array_T (Index_Type'First .. New_Size); D : Element_Array_Access := Element_Array_Access (This.Data); begin New_Container (Index_Type'First .. This.Data'Last) := This.Data (Index_Type'First .. This.Data'Last); This.Data := New_Container; Delete (D); end; end; end Ensure_Index; procedure Ensure_Allocation (This : access Vector_T'Class; New_Index : Index_Type) is begin This.Ensure_Index (New_Index); This.Next_Index := Index_Base (New_Index + 1); end Ensure_Allocation; function Length (This : access Vector_T'Class) return Natural is begin return Natural (Index_Type (This.Next_Index) - Index_Type'First); end Length; function Is_Empty (This : access Vector_T'Class) return Boolean is (Index_Type'First = Index_Type (This.Next_Index)); procedure Clear (This : access Vector_T'Class) is begin This.Next_Index := Index_Type'First; end Clear; procedure Replace_Element (This : access Vector_T'Class; Index : Index_Type; Element : Element_Type) is begin This.Data (Index) := Element; end Replace_Element; function Check_Index (This : access Vector_T'Class; Index : Index_Type) return Boolean is (Index < Index_Type (This.Next_Index)); end Skill.Containers.Vectors;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == OAuth == -- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization -- framework as defined by the IETF working group. -- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26 package Security.OAuth is -- OAuth 2.0: Section 10.2.2. Initial Registry Contents -- RFC 6749: 11.2.2. Initial Registry Contents Client_Id : constant String := "client_id"; Client_Secret : constant String := "client_secret"; Response_Type : constant String := "response_type"; Redirect_Uri : constant String := "redirect_uri"; Scope : constant String := "scope"; State : constant String := "state"; Code : constant String := "code"; Error_Description : constant String := "error_description"; Error_Uri : constant String := "error_uri"; Grant_Type : constant String := "grant_type"; Access_Token : constant String := "access_token"; Token_Type : constant String := "token_type"; Expires_In : constant String := "expires_in"; Username : constant String := "username"; Password : constant String := "password"; Refresh_Token : constant String := "refresh_token"; end Security.OAuth;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.Mappers; with GNAT.Regexp; with Security.Contexts; -- == URL Security Policy == -- The `Security.Policies.Urls` implements a security policy intended to be used -- in web servers. It allows to protect an URL by defining permissions that must be granted -- for a user to get access to the URL. A typical example is a web server that has a set of -- administration pages, these pages should be accessed by users having some admin permission. -- -- === Policy creation === -- An instance of the `URL_Policy` must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission `create-workspace` or `admin`. -- These two permissions are checked according to another security policy. -- The XML configuration can define several `url-policy`. They are checked in -- the order defined in the XML. In other words, the first `url-policy` that matches -- the URL is used to verify the permission. -- -- The `url-policy` definition can contain several `permission`. -- The first permission that is granted gives access to the URL. -- -- === Checking for permission === -- To check a URL permission, you must declare a `URL_Permission` object with the URL. -- -- URL : constant String := ...; -- Perm : constant Policies.URLs.URL_Permission (URL'Length) -- := URL_Permission '(Len => URI'Length, URL => URL); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.URLs is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URL Permission -- ------------------------------ -- Represents a permission to access a given URL. type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URL : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Mapper : in out Util.Serialize.Mappers.Processing); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); package Atomic_Rules_Ref is new Rules_Ref.IR.Atomic; type Rules_Ref_Access is access Atomic_Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.URLs;
----------------------------------------------------------------------- -- util-stacks -- Simple stack -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Stacks is procedure Free is new Ada.Unchecked_Deallocation (Element_Type_Array, Element_Type_Array_Access); -- ------------------------------ -- Get access to the current stack element. -- ------------------------------ function Current (Container : in Stack) return Element_Type_Access is begin return Container.Current; end Current; -- ------------------------------ -- Push an element on top of the stack making the new element the current one. -- ------------------------------ procedure Push (Container : in out Stack) is begin if Container.Stack = null then Container.Stack := new Element_Type_Array (1 .. 100); Container.Pos := Container.Stack'First; elsif Container.Pos = Container.Stack'Last then declare Old : Element_Type_Array_Access := Container.Stack; begin Container.Stack := new Element_Type_Array (1 .. Old'Last + 100); Container.Stack (1 .. Old'Last) := Old (1 .. Old'Last); Free (Old); end; end if; if Container.Pos /= Container.Stack'First then Container.Stack (Container.Pos + 1) := Container.Stack (Container.Pos); end if; Container.Pos := Container.Pos + 1; Container.Current := Container.Stack (Container.Pos)'Access; end Push; -- ------------------------------ -- Pop the top element. -- ------------------------------ procedure Pop (Container : in out Stack) is begin Container.Pos := Container.Pos - 1; Container.Current := Container.Stack (Container.Pos)'Access; end Pop; -- ------------------------------ -- Clear the stack. -- ------------------------------ procedure Clear (Container : in out Stack) is begin if Container.Stack /= null then Container.Pos := Container.Stack'First; end if; Container.Current := null; end Clear; -- ------------------------------ -- Release the stack -- ------------------------------ overriding procedure Finalize (Obj : in out Stack) is begin Free (Obj.Stack); end Finalize; end Util.Stacks;
----------------------------------------------------------------------- -- gen-artifacts-xmi -- UML-XMI artifact for Code Generator -- Copyright (C) 2012, 2013, 2014, 2015, 2016, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Strings.Fixed; with Gen.Configs; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Enums; with Gen.Model.Mappings; with Gen.Model.Beans; with Gen.Model.Operations; with Gen.Model.Stypes; with Util.Log.Loggers; with Util.Strings; with Util.Files; with Util.Beans; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Buffered; package body Gen.Artifacts.XMI is use Ada.Strings.Unbounded; use Gen.Model; use Gen.Configs; package UBO renames Util.Beans.Objects; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.XMI"); -- Get the visibility from the XMI visibility value. function Get_Visibility (Value : in UBO.Object) return Model.XMI.Visibility_Type; -- Get the changeability from the XMI visibility value. function Get_Changeability (Value : in UBO.Object) return Model.XMI.Changeability_Type; -- Get the parameter kind from the XMI parameter kind value. function Get_Parameter_Type (Value : in UBO.Object) return Model.XMI.Parameter_Type; procedure Iterate_For_Table is new Gen.Model.XMI.Iterate_Elements (T => Gen.Model.Tables.Table_Definition'Class); procedure Iterate_For_Bean is new Gen.Model.XMI.Iterate_Elements (T => Gen.Model.Beans.Bean_Definition'Class); procedure Iterate_For_Package is new Gen.Model.XMI.Iterate_Elements (T => Gen.Model.Packages.Package_Definition'Class); procedure Iterate_For_Enum is new Gen.Model.XMI.Iterate_Elements (T => Gen.Model.Enums.Enum_Definition'Class); procedure Iterate_For_Operation is new Gen.Model.XMI.Iterate_Elements (T => Gen.Model.Operations.Operation_Definition'Class); function Find_Stereotype is new Gen.Model.XMI.Find_Element (Element_Type => Model.XMI.Stereotype_Element, Element_Type_Access => Model.XMI.Stereotype_Element_Access); function Find_Tag_Definition is new Gen.Model.XMI.Find_Element (Element_Type => Model.XMI.Tag_Definition_Element, Element_Type_Access => Model.XMI.Tag_Definition_Element_Access); type XMI_Fields is (FIELD_NAME, FIELD_ID, FIELD_ID_REF, FIELD_VALUE, FIELD_HREF, FIELD_CLASS_NAME, FIELD_CLASS_ID, FIELD_STEREOTYPE, FIELD_STEREOTYPE_NAME, FIELD_STEREOTYPE_ID, FIELD_STEREOTYPE_HREF, FIELD_ATTRIBUTE_NAME, FIELD_ATTRIBUTE_ID, FIELD_ATTRIBUTE_VISIBILITY, FIELD_ATTRIBUTE_CHANGEABILITY, FIELD_ATTRIBUTE_INITIAL_VALUE, FIELD_ATTRIBUTE, FIELD_MULTIPLICITY_UPPER, FIELD_MULTIPLICITY_LOWER, FIELD_PACKAGE_ID, FIELD_PACKAGE_NAME, FIELD_PACKAGE_END, FIELD_CLASS_VISIBILITY, FIELD_DATA_TYPE, FIELD_DATA_TYPE_NAME, FIELD_DATA_TYPE_HREF, FIELD_CLASS_END, FIELD_ASSOCIATION_NAME, FIELD_ASSOCIATION_ID, FIELD_ASSOCIATION, FIELD_ASSOCIATION_CLASS_ID, FIELD_CLASSIFIER_HREF, FIELD_GENERALIZATION_ID, FIELD_GENERALIZATION_CHILD_ID, FIELD_GENERALIZATION_PARENT_ID, FIELD_GENERALIZATION_END, FIELD_ASSOCIATION_END_ID, FIELD_ASSOCIATION_END_NAME, FIELD_ASSOCIATION_END_VISIBILITY, FIELD_ASSOCIATION_END_NAVIGABLE, FIELD_ASSOCIATION_END, FIELD_OPERATION_ID, FIELD_OPERATION_NAME, FIELD_OPERATION_END, FIELD_PARAMETER_ID, FIELD_PARAMETER_NAME, FIELD_PARAMETER_KIND, FIELD_PARAMETER_END, FIELD_COMMENT, FIELD_COMMENT_ID, FIELD_TAG_DEFINITION, FIELD_TAG_DEFINITION_ID, FIELD_TAG_DEFINITION_NAME, FIELD_TAGGED_ID, FIELD_TAGGED_VALUE, FIELD_ENUMERATION, FIELD_ENUMERATION_LITERAL, FIELD_ENUMERATION_LITERAL_END, FIELD_ENUMERATION_HREF); type XMI_Info is record Model : Gen.Model.XMI.Model_Map_Access; Default_Type : UString; File : UString; Parser : access Util.Serialize.IO.XML.Parser'Class; Profiles : access Util.Strings.Sets.Set; Is_Profile : Boolean := False; Class_Element : Gen.Model.XMI.Class_Element_Access; Class_Name : UBO.Object; Class_Visibility : Gen.Model.XMI.Visibility_Type := Gen.Model.XMI.VISIBILITY_PUBLIC; Class_Id : UBO.Object; -- UML Generalization. Child_Id : UBO.Object; Parent_Id : UBO.Object; Generalization_Id : UBO.Object; Generalization : Gen.Model.XMI.Generalization_Element_Access; Package_Element : Gen.Model.XMI.Package_Element_Access; Package_Id : UBO.Object; Attr_Id : UBO.Object; Attr_Element : Gen.Model.XMI.Attribute_Element_Access; Attr_Visibility : Gen.Model.XMI.Visibility_Type := Gen.Model.XMI.VISIBILITY_PUBLIC; Attr_Changeability : Gen.Model.XMI.Changeability_Type := Gen.Model.XMI.CHANGEABILITY_CHANGEABLE; Attr_Value : UBO.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 0; Association : Gen.Model.XMI.Association_Element_Access; Assos_End_Element : Gen.Model.XMI.Association_End_Element_Access; Assos_End_Name : UBO.Object; Assos_End_Visibility : Gen.Model.XMI.Visibility_Type := Gen.Model.XMI.VISIBILITY_PUBLIC; Assos_End_Navigable : Boolean := False; Operation_Id : UBO.Object; Operation : Gen.Model.XMI.Operation_Element_Access; Parameter : Gen.Model.XMI.Parameter_Element_Access; Parameter_Type : Gen.Model.XMI.Parameter_Type; Name : UBO.Object; Id : UBO.Object; Ref_Id : UBO.Object; Value : UBO.Object; Href : UBO.Object; Tag_Name : UBO.Object; Tagged_Id : UBO.Object; Association_Id : UBO.Object; Stereotype_Id : UBO.Object; Data_Type : Gen.Model.XMI.Data_Type_Element_Access; Enumeration : Gen.Model.XMI.Enum_Element_Access; Enumeration_Literal : Gen.Model.XMI.Literal_Element_Access; Tag_Definition : Gen.Model.XMI.Tag_Definition_Element_Access; Stereotype : Gen.Model.XMI.Stereotype_Element_Access; Tagged_Value : Gen.Model.XMI.Tagged_Value_Element_Access; Comment : Gen.Model.XMI.Comment_Element_Access; Has_Package_Id : Boolean := False; Has_Package_Name : Boolean := False; end record; type XMI_Access is access all XMI_Info; procedure Add_Tagged_Value (P : in out XMI_Info); procedure Set_Member (P : in out XMI_Info; Field : in XMI_Fields; Value : in UBO.Object); -- Set the package name and or XMI id. procedure Set_Package (P : in out XMI_Info; Name : in UBO.Object; Id : in UBO.Object); use type Gen.Model.XMI.Model_Element_Access; use type Gen.Model.XMI.Attribute_Element_Access; use type Gen.Model.XMI.Class_Element_Access; use type Gen.Model.XMI.Package_Element_Access; use type Gen.Model.XMI.Tag_Definition_Element_Access; use type Gen.Model.XMI.Association_End_Element_Access; use type Gen.Model.XMI.Stereotype_Element_Access; use type Gen.Model.XMI.Enum_Element_Access; use type Gen.Model.XMI.Literal_Element_Access; use type Gen.Model.XMI.Comment_Element_Access; use type Gen.Model.XMI.Operation_Element_Access; use type Gen.Model.XMI.Association_Element_Access; use type Gen.Model.XMI.Ref_Type_Element_Access; use type Gen.Model.XMI.Data_Type_Element_Access; -- ------------------------------ -- Get the visibility from the XMI visibility value. -- ------------------------------ function Get_Visibility (Value : in UBO.Object) return Model.XMI.Visibility_Type is S : constant String := UBO.To_String (Value); begin if S = "public" then return Model.XMI.VISIBILITY_PUBLIC; elsif S = "package" then return Model.XMI.VISIBILITY_PACKAGE; elsif S = "protected" then return Model.XMI.VISIBILITY_PROTECTED; elsif S = "private" then return Model.XMI.VISIBILITY_PRIVATE; else return Model.XMI.VISIBILITY_PUBLIC; end if; end Get_Visibility; -- ------------------------------ -- Get the changeability from the XMI visibility value. -- ------------------------------ function Get_Changeability (Value : in UBO.Object) return Model.XMI.Changeability_Type is S : constant String := UBO.To_String (Value); begin if S = "frozen" then return Model.XMI.CHANGEABILITY_FROZEN; elsif S = "changeable" then return Model.XMI.CHANGEABILITY_CHANGEABLE; elsif S = "addOnly" then return Model.XMI.CHANGEABILITY_INSERT; else return Model.XMI.CHANGEABILITY_CHANGEABLE; end if; end Get_Changeability; -- ------------------------------ -- Get the parameter kind from the XMI parameter kind value. -- ------------------------------ function Get_Parameter_Type (Value : in UBO.Object) return Model.XMI.Parameter_Type is S : constant String := UBO.To_String (Value); begin if S = "return" then return Model.XMI.PARAM_RETURN; elsif S = "in" then return Model.XMI.PARAM_IN; elsif S = "out" then return Model.XMI.PARAM_OUT; elsif S = "inout" then return Model.XMI.PARAM_INOUT; else return Model.XMI.PARAM_INOUT; end if; end Get_Parameter_Type; procedure Add_Tagged_Value (P : in out XMI_Info) is Id : constant UString := UBO.To_Unbounded_String (P.Tagged_Id); Value : constant UString := UBO.To_Unbounded_String (P.Value); Tagged_Value : constant Model.XMI.Tagged_Value_Element_Access := new Model.XMI.Tagged_Value_Element (P.Model); begin Log.Info ("Add tag {0} - {1}", Id, To_String (Value)); Tagged_Value.Value := Value; if not UBO.Is_Null (P.Ref_Id) then Tagged_Value.Set_Reference_Id (UBO.To_String (P.Ref_Id), P.Profiles.all); P.Ref_Id := UBO.Null_Object; else Tagged_Value.Set_Reference_Id (UBO.To_String (P.Href), P.Profiles.all); P.Href := UBO.Null_Object; end if; Tagged_Value.XMI_Id := Id; P.Model.Insert (Tagged_Value.XMI_Id, Tagged_Value.all'Access); -- Insert the tag value into the current element. if P.Data_Type /= null then P.Data_Type.Tagged_Values.Append (Tagged_Value.all'Access); elsif P.Assos_End_Element /= null then P.Assos_End_Element.Tagged_Values.Append (Tagged_Value.all'Access); elsif P.Association /= null then P.Association.Tagged_Values.Append (Tagged_Value.all'Access); elsif P.Attr_Element /= null then P.Attr_Element.Tagged_Values.Append (Tagged_Value.all'Access); elsif P.Class_Element /= null then Log.Info ("Adding in {0}", To_String (P.Class_Element.Name)); P.Class_Element.Tagged_Values.Append (Tagged_Value.all'Access); elsif P.Enumeration_Literal /= null then P.Enumeration_Literal.Tagged_Values.Append (Tagged_Value.all'Access); elsif P.Enumeration /= null then P.Enumeration.Tagged_Values.Append (Tagged_Value.all'Access); elsif P.Package_Element /= null then P.Package_Element.Tagged_Values.Append (Tagged_Value.all'Access); elsif P.Tag_Definition /= null then P.Tag_Definition.Tagged_Values.Append (Tagged_Value.all'Access); else Log.Info ("Tagged value {0} ignored", Id); end if; end Add_Tagged_Value; -- ------------------------------ -- Set the package name and or XMI id. -- ------------------------------ procedure Set_Package (P : in out XMI_Info; Name : in UBO.Object; Id : in UBO.Object) is Parent : constant Gen.Model.XMI.Package_Element_Access := P.Package_Element; begin -- This is a new nested package, create it. if Parent /= null and P.Has_Package_Name and P.Has_Package_Id then P.Package_Element := null; end if; if P.Package_Element = null then P.Package_Element := new Gen.Model.XMI.Package_Element (P.Model); P.Package_Element.Set_Location (P.Parser.Get_Location); P.Package_Element.Is_Profile := P.Is_Profile; if Parent /= null then P.Package_Element.Parent := Parent.all'Access; else P.Package_Element.Parent := null; end if; P.Has_Package_Name := False; P.Has_Package_Id := False; end if; if not UBO.Is_Null (Id) then P.Package_Element.Set_XMI_Id (Id); P.Model.Include (P.Package_Element.XMI_Id, P.Package_Element.all'Access); P.Has_Package_Id := True; end if; if not UBO.Is_Null (Name) then P.Package_Element.Set_Name (Name); P.Has_Package_Name := True; end if; end Set_Package; procedure Set_Member (P : in out XMI_Info; Field : in XMI_Fields; Value : in UBO.Object) is begin case Field is when FIELD_NAME => P.Name := Value; when FIELD_ID => P.Id := Value; P.Ref_Id := UBO.Null_Object; P.Href := UBO.Null_Object; when FIELD_ID_REF => P.Ref_Id := Value; when FIELD_VALUE => P.Value := Value; when FIELD_HREF => P.Href := Value; when FIELD_MULTIPLICITY_LOWER => P.Multiplicity_Lower := UBO.To_Integer (Value); when FIELD_MULTIPLICITY_UPPER => P.Multiplicity_Upper := UBO.To_Integer (Value); when FIELD_CLASS_NAME => P.Class_Element := new Gen.Model.XMI.Class_Element (P.Model); P.Class_Element.Set_Name (Value); P.Class_Element.Set_Location (To_String (P.File) & P.Parser.Get_Location); P.Ref_Id := UBO.Null_Object; P.Href := UBO.Null_Object; when FIELD_CLASS_VISIBILITY => P.Class_Visibility := Get_Visibility (Value); when FIELD_CLASS_ID => P.Class_Id := Value; when FIELD_CLASS_END => if P.Class_Element /= null then P.Class_Element.XMI_Id := UBO.To_Unbounded_String (P.Class_Id); P.Class_Element.Visibility := P.Class_Visibility; Log.Info ("Adding class {0} - {1}", P.Class_Element.XMI_Id, To_String (P.Class_Element.Name)); P.Model.Insert (P.Class_Element.XMI_Id, P.Class_Element.all'Access); if P.Package_Element /= null then P.Package_Element.Classes.Append (P.Class_Element.all'Access); P.Package_Element.Elements.Append (P.Class_Element.all'Access); P.Class_Element.Parent := P.Package_Element.all'Access; end if; P.Class_Element := null; P.Class_Visibility := Gen.Model.XMI.VISIBILITY_PUBLIC; end if; when FIELD_GENERALIZATION_CHILD_ID => P.Child_Id := Value; when FIELD_GENERALIZATION_PARENT_ID => P.Parent_Id := Value; when FIELD_GENERALIZATION_ID => P.Generalization_Id := Value; when FIELD_GENERALIZATION_END => if not UBO.Is_Null (P.Child_Id) and not UBO.Is_Null (P.Parent_Id) and not UBO.Is_Null (P.Generalization_Id) then P.Generalization := new Gen.Model.XMI.Generalization_Element (P.Model); P.Generalization.Set_XMI_Id (P.Generalization_Id); P.Model.Insert (P.Generalization.XMI_Id, P.Generalization.all'Access); P.Generalization.Set_Reference_Id (UBO.To_String (P.Parent_Id), P.Profiles.all); P.Generalization.Child_Id := UBO.To_Unbounded_String (P.Child_Id); end if; P.Child_Id := UBO.Null_Object; P.Generalization_Id := UBO.Null_Object; P.Parent_Id := UBO.Null_Object; when FIELD_OPERATION_ID => P.Operation_Id := Value; when FIELD_ATTRIBUTE_ID | FIELD_PARAMETER_ID => P.Attr_Id := Value; when FIELD_ATTRIBUTE_VISIBILITY => P.Attr_Visibility := Get_Visibility (Value); when FIELD_ATTRIBUTE_CHANGEABILITY => P.Attr_Changeability := Get_Changeability (Value); when FIELD_ATTRIBUTE_NAME => P.Attr_Element := new Gen.Model.XMI.Attribute_Element (P.Model); P.Attr_Element.Set_Name (Value); P.Attr_Element.Set_Location (To_String (P.File) & P.Parser.Get_Location); when FIELD_ATTRIBUTE_INITIAL_VALUE => P.Attr_Value := Value; when FIELD_ATTRIBUTE => P.Attr_Element.Set_XMI_Id (P.Attr_Id); P.Attr_Element.Visibility := P.Attr_Visibility; P.Attr_Element.Changeability := P.Attr_Changeability; P.Attr_Element.Multiplicity_Lower := P.Multiplicity_Lower; P.Attr_Element.Multiplicity_Upper := P.Multiplicity_Upper; P.Attr_Element.Initial_Value := P.Attr_Value; -- Prepare for next attribute. P.Attr_Visibility := Gen.Model.XMI.VISIBILITY_PUBLIC; P.Attr_Changeability := Gen.Model.XMI.CHANGEABILITY_CHANGEABLE; P.Multiplicity_Lower := 0; P.Multiplicity_Upper := 0; -- Sanity check and add this attribute to the class. if P.Class_Element /= null then P.Model.Insert (P.Attr_Element.XMI_Id, P.Attr_Element.all'Access); P.Attr_Element.Parent := P.Class_Element.all'Access; P.Class_Element.Elements.Append (P.Attr_Element.all'Access); P.Class_Element.Attributes.Append (P.Attr_Element.all'Access); if Length (P.Attr_Element.Ref_Id) = 0 then P.Attr_Element.Ref_Id := P.Default_Type; declare Msg : constant String := "attribute '" & To_String (P.Attr_Element.Name) & "' in table '" & To_String (P.Class_Element.Name) & "' has no type."; begin P.Attr_Element := null; raise Util.Serialize.Mappers.Field_Error with Msg; end; end if; end if; P.Attr_Element := null; when FIELD_OPERATION_NAME => P.Operation := new Gen.Model.XMI.Operation_Element (P.Model); P.Operation.Set_Name (Value); P.Operation.Set_Location (To_String (P.File) & P.Parser.Get_Location); when FIELD_PARAMETER_NAME => P.Attr_Element := new Gen.Model.XMI.Attribute_Element (P.Model); P.Attr_Element.Set_Name (Value); P.Attr_Element.Set_Location (To_String (P.File) & P.Parser.Get_Location); when FIELD_PARAMETER_KIND => P.Parameter_Type := Get_Parameter_Type (Value); when FIELD_PARAMETER_END => if P.Attr_Element /= null and P.Operation /= null then P.Attr_Element.Set_XMI_Id (P.Attr_Id); P.Operation.Elements.Append (P.Attr_Element.all'Access); P.Model.Insert (P.Attr_Element.XMI_Id, P.Attr_Element.all'Access); end if; P.Attr_Element := null; when FIELD_OPERATION_END => if P.Operation /= null and P.Class_Element /= null then P.Operation.Set_XMI_Id (P.Operation_Id); P.Model.Insert (P.Operation.XMI_Id, P.Operation.all'Access); P.Class_Element.Operations.Append (P.Operation.all'Access); end if; P.Operation := null; -- Extract an association. when FIELD_ASSOCIATION_ID => P.Association_Id := Value; when FIELD_ASSOCIATION_NAME => P.Association := new Gen.Model.XMI.Association_Element (P.Model); P.Association.Set_Name (Value); P.Association.Set_Location (To_String (P.File) & P.Parser.Get_Location); when FIELD_ASSOCIATION_END_NAME => P.Assos_End_Name := Value; when FIELD_ASSOCIATION_END_VISIBILITY => P.Assos_End_Visibility := Get_Visibility (Value); when FIELD_ASSOCIATION_END_NAVIGABLE => P.Assos_End_Navigable := UBO.To_Boolean (Value); when FIELD_ASSOCIATION_END_ID => P.Assos_End_Element := new Gen.Model.XMI.Association_End_Element (P.Model); P.Assos_End_Element.Set_XMI_Id (Value); P.Assos_End_Element.Set_Location (To_String (P.File) & P.Parser.Get_Location); P.Model.Include (P.Assos_End_Element.XMI_Id, P.Assos_End_Element.all'Access); when FIELD_ASSOCIATION_CLASS_ID => if P.Assos_End_Element /= null then P.Assos_End_Element.Set_Reference_Id (UBO.To_String (Value), P.Profiles.all); end if; when FIELD_ASSOCIATION_END => if P.Assos_End_Element /= null and P.Association /= null then P.Assos_End_Element.Set_Name (P.Assos_End_Name); P.Assos_End_Element.Visibility := P.Assos_End_Visibility; P.Assos_End_Element.Navigable := P.Assos_End_Navigable; P.Assos_End_Element.Multiplicity_Lower := P.Multiplicity_Lower; P.Assos_End_Element.Multiplicity_Upper := P.Multiplicity_Upper; P.Assos_End_Element.Parent := P.Association.all'Access; -- Keep the association if the target class is specified. -- We ignore association to a UML Component for example. if Length (P.Assos_End_Element.Ref_Id) > 0 then P.Association.Connections.Append (P.Assos_End_Element.all'Access); else Log.Info ("Association end {0} ignored", P.Assos_End_Element.Name); end if; end if; P.Multiplicity_Lower := 0; P.Multiplicity_Upper := 0; P.Assos_End_Name := UBO.Null_Object; P.Assos_End_Navigable := False; if P.Association = null then raise Util.Serialize.Mappers.Field_Error with "invalid association"; end if; P.Assos_End_Element := null; when FIELD_ASSOCIATION => if P.Association /= null then P.Association.Set_XMI_Id (P.Association_Id); P.Model.Include (P.Association.XMI_Id, P.Association.all'Access); if P.Package_Element /= null then P.Package_Element.Associations.Append (P.Association.all'Access); end if; end if; P.Association := null; when FIELD_PACKAGE_ID => Set_Package (P, UBO.Null_Object, Value); when FIELD_PACKAGE_NAME => Set_Package (P, Value, UBO.Null_Object); when FIELD_PACKAGE_END => if P.Package_Element /= null then if P.Package_Element.Parent /= null then P.Package_Element := Gen.Model.XMI.Package_Element (P.Package_Element.Parent.all)'Access; else P.Package_Element := null; end if; end if; when FIELD_TAGGED_ID => P.Tagged_Id := Value; -- Tagged value associated with an attribute, operation, class, package. when FIELD_TAGGED_VALUE => Add_Tagged_Value (P); -- Data type mapping. when FIELD_DATA_TYPE_NAME => P.Data_Type := new Gen.Model.XMI.Data_Type_Element (P.Model); P.Data_Type.Set_Name (Value); P.Data_Type.Set_Location (To_String (P.File) & P.Parser.Get_Location); P.Data_Type.XMI_Id := UBO.To_Unbounded_String (P.Id); P.Ref_Id := UBO.Null_Object; P.Href := UBO.Null_Object; when FIELD_DATA_TYPE => if P.Attr_Element = null and P.Operation = null and UBO.Is_Null (P.Generalization_Id) and P.Data_Type /= null then if P.Package_Element /= null and not P.Is_Profile then P.Data_Type.Parent := P.Package_Element.all'Access; end if; P.Model.Insert (P.Data_Type.XMI_Id, P.Data_Type.all'Access); if P.Package_Element /= null and not P.Is_Profile then P.Package_Element.Types.Append (P.Data_Type.all'Access); end if; end if; P.Data_Type := null; when FIELD_DATA_TYPE_HREF | FIELD_ENUMERATION_HREF | FIELD_CLASSIFIER_HREF => if P.Attr_Element /= null then P.Attr_Element.Set_Reference_Id (UBO.To_String (Value), P.Profiles.all); Log.Debug ("Attribute {0} has type {1}", P.Attr_Element.Name, P.Attr_Element.Ref_Id); end if; -- Enumeration mapping. when FIELD_ENUMERATION => P.Enumeration := new Gen.Model.XMI.Enum_Element (P.Model); P.Enumeration.Set_Name (Value); P.Enumeration.Set_Location (To_String (P.File) & P.Parser.Get_Location); P.Enumeration.XMI_Id := UBO.To_Unbounded_String (P.Id); if P.Package_Element /= null then P.Enumeration.Parent := P.Package_Element.all'Access; end if; P.Model.Insert (P.Enumeration.XMI_Id, P.Enumeration.all'Access); Log.Info ("Adding enumeration {0}", P.Enumeration.Name); if P.Package_Element /= null then P.Package_Element.Enums.Append (P.Enumeration.all'Access); end if; when FIELD_ENUMERATION_LITERAL => P.Enumeration.Add_Literal (Value, P.Name, P.Enumeration_Literal); when FIELD_ENUMERATION_LITERAL_END => P.Enumeration_Literal.Set_Name (P.Name); P.Enumeration_Literal := null; when FIELD_STEREOTYPE_NAME => P.Stereotype := new Gen.Model.XMI.Stereotype_Element (P.Model); P.Stereotype.Set_Name (Value); P.Stereotype.Set_Location (To_String (P.File) & P.Parser.Get_Location); when FIELD_STEREOTYPE_ID => P.Stereotype_Id := Value; -- Stereotype mapping. when FIELD_STEREOTYPE => if not UBO.Is_Null (P.Stereotype_Id) and P.Stereotype /= null then P.Stereotype.XMI_Id := UBO.To_Unbounded_String (P.Stereotype_Id); P.Model.Insert (P.Stereotype.XMI_Id, P.Stereotype.all'Access); if P.Class_Element /= null then P.Class_Element.Elements.Append (P.Stereotype.all'Access); elsif P.Package_Element /= null then P.Package_Element.Elements.Append (P.Stereotype.all'Access); end if; P.Stereotype := null; end if; when FIELD_STEREOTYPE_HREF => declare S : constant Gen.Model.XMI.Ref_Type_Element_Access := new Gen.Model.XMI.Ref_Type_Element (P.Model); begin S.Set_Location (To_String (P.File) & P.Parser.Get_Location); S.Set_Reference_Id (UBO.To_String (Value), P.Profiles.all); if P.Enumeration_Literal /= null then P.Enumeration_Literal.Stereotypes.Append (S.all'Access); elsif P.Assos_End_Element /= null then Log.Info ("Stereotype {0} added", UBO.To_String (Value)); P.Assos_End_Element.Stereotypes.Append (S.all'Access); elsif P.Association /= null then P.Association.Stereotypes.Append (S.all'Access); elsif P.Attr_Element /= null then P.Attr_Element.Stereotypes.Append (S.all'Access); elsif P.Class_Element /= null then P.Class_Element.Stereotypes.Append (S.all'Access); elsif P.Package_Element /= null then P.Package_Element.Stereotypes.Append (S.all'Access); else Log.Info ("Stereotype {0} ignored", UBO.To_String (Value)); end if; end; -- Tag definition mapping. when FIELD_TAG_DEFINITION_NAME => P.Tag_Name := Value; when FIELD_TAG_DEFINITION_ID => P.Tag_Definition := new Gen.Model.XMI.Tag_Definition_Element (P.Model); P.Tag_Definition.Set_XMI_Id (Value); P.Tag_Definition.Set_Location (To_String (P.File) & P.Parser.Get_Location); P.Model.Insert (P.Tag_Definition.XMI_Id, P.Tag_Definition.all'Access); when FIELD_TAG_DEFINITION => P.Tag_Definition.Set_Name (P.Tag_Name); Log.Info ("Adding tag definition {0}", P.Tag_Definition.Name); if P.Stereotype /= null then P.Stereotype.Elements.Append (P.Tag_Definition.all'Access); elsif P.Package_Element /= null then P.Package_Element.Elements.Append (P.Tag_Definition.all'Access); end if; P.Tag_Definition := null; when FIELD_COMMENT_ID => P.Comment := new Gen.Model.XMI.Comment_Element (P.Model); P.Comment.Set_Location (To_String (P.File) & P.Parser.Get_Location); P.Comment.XMI_Id := UBO.To_Unbounded_String (Value); P.Ref_Id := UBO.Null_Object; -- Comment mapping. when FIELD_COMMENT => if P.Comment /= null then P.Comment.Text := UBO.To_Unbounded_String (P.Value); P.Comment.Ref_Id := UBO.To_Unbounded_String (P.Ref_Id); P.Model.Insert (P.Comment.XMI_Id, P.Comment.all'Access); end if; P.Ref_Id := UBO.Null_Object; P.Comment := null; end case; exception when Util.Serialize.Mappers.Field_Error => raise; when E : others => Log.Error ("Extraction of field {0} with value '{1}' failed", XMI_Fields'Image (Field), UBO.To_String (Value)); Log.Error ("Cause", E); raise; end Set_Member; package XMI_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => XMI_Info, Element_Type_Access => XMI_Access, Fields => XMI_Fields, Set_Member => Set_Member); XMI_Mapping : aliased XMI_Mapper.Mapper; -- ------------------------------ -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. -- ------------------------------ procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is begin Log.Debug ("Initializing query artifact for the configuration"); Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class) is pragma Unreferenced (Project); -- Collect the enum literal for the enum definition. procedure Prepare_Enum_Literal (Enum : in out Gen.Model.Enums.Enum_Definition'Class; Item : in Gen.Model.XMI.Model_Element_Access); -- Register the enum in the model for the generation. procedure Prepare_Enum (Pkg : in out Gen.Model.Packages.Package_Definition'Class; Item : in Gen.Model.XMI.Model_Element_Access); use Gen.Model.XMI; use Gen.Model.Tables; use Gen.Model.Beans; -- Register the attribute in the table procedure Prepare_Attribute (Table : in out Gen.Model.Tables.Table_Definition'Class; Column : in Model_Element_Access); -- Register the attribute in the bean definition. procedure Prepare_Attribute (Bean : in out Gen.Model.Beans.Bean_Definition'Class; Column : in Model_Element_Access); -- Identify the UML association and create an entry for it in the table. procedure Prepare_Association (Table : in out Gen.Model.Tables.Table_Definition'Class; Node : in Model_Element_Access); procedure Prepare_Parameter (Operation : in out Gen.Model.Operations.Operation_Definition'Class; Node : in Model_Element_Access); -- Identify the UML operation and create an entry for it in the table. procedure Prepare_Operation (Table : in out Gen.Model.Tables.Table_Definition'Class; Node : in Model_Element_Access); -- Prepare a UML/XMI class: -- o if the class has the <<Dynamo.ADO.table>> stereotype, create a table definition. -- o if the class has the <<Dynamo.AWA.bean>> stereotype, create a bean procedure Prepare_Class (Pkg : in out Gen.Model.Packages.Package_Definition'Class; Item : in Gen.Model.XMI.Model_Element_Access); procedure Prepare_Type (Pkg : in out Gen.Model.Packages.Package_Definition'Class; Item : in Gen.Model.XMI.Model_Element_Access); -- Scan the package for the model generation. procedure Prepare_Package (Id : in UString; Item : in Gen.Model.XMI.Model_Element_Access); procedure Prepare_Model (Key : in UString; Model : in out Gen.Model.XMI.Model_Map.Map); procedure Prepare_Profile (Id : in UString; Item : in Gen.Model.XMI.Model_Element_Access); -- ------------------------------ -- Register the attribute in the table -- ------------------------------ procedure Prepare_Attribute (Table : in out Gen.Model.Tables.Table_Definition'Class; Column : in Model_Element_Access) is use Util.Beans.Objects; Msg : constant String := Column.Get_Error_Message; Sql : constant String := Column.Find_Tag_Value (Handler.Sql_Type_Tag, ""); Len : constant String := Column.Find_Tag_Value (Handler.Sql_Length_Tag, ""); C : Column_Definition_Access; begin Log.Info ("Prepare class attribute {0}", Column.Name); if Msg'Length /= 0 then Context.Error (Column.Get_Location & ": " & Msg); end if; Table.Add_Column (Column.Name, C); C.Set_Comment (Column.Get_Comment); C.Set_Location (Column.Get_Location); if Column.all in Attribute_Element'Class then declare Attr : constant Attribute_Element_Access := Attribute_Element'Class (Column.all)'Access; begin if Attr.Data_Type /= null then C.Set_Type (Attr.Data_Type.Get_Qualified_Name); end if; C.Not_Null := Attr.Multiplicity_Lower > 0; C.Is_Key := Column.Has_Stereotype (Handler.PK_Stereotype); C.Is_Version := Column.Has_Stereotype (Handler.Version_Stereotype); C.Is_Auditable := Column.Has_Stereotype (Handler.Auditable_Stereotype); C.Is_Updated := Attr.Changeability /= CHANGEABILITY_FROZEN; C.Is_Inserted := True; -- Attr.Changeability = CHANGEABILITY_INSERT; C.Sql_Type := To_UString (Sql); if Column.Has_Stereotype (Handler.Not_Null_Stereotype) then C.Not_Null := True; end if; if Column.Has_Stereotype (Handler.Nullable_Stereotype) then C.Not_Null := False; end if; if C.Is_Version then C.Not_Null := True; end if; if C.Is_Key then C.Generator := To_Object (Column.Find_Tag_Value (Handler.Generator_Tag, "")); end if; if Len'Length > 0 then C.Set_Sql_Length (Len, Context); end if; end; end if; end Prepare_Attribute; -- ------------------------------ -- Register the attribute in the bean definition. -- ------------------------------ procedure Prepare_Attribute (Bean : in out Gen.Model.Beans.Bean_Definition'Class; Column : in Model_Element_Access) is Msg : constant String := Column.Get_Error_Message; C : Column_Definition_Access; begin Log.Info ("Prepare class attribute {0}", Column.Name); if Msg'Length /= 0 then Context.Error (Column.Get_Location & ": " & Msg); end if; Bean.Add_Attribute (Column.Name, C); C.Set_Comment (Column.Get_Comment); C.Set_Location (Column.Get_Location); if Column.all in Attribute_Element'Class then declare Attr : constant Attribute_Element_Access := Attribute_Element'Class (Column.all)'Access; begin if Attr.Data_Type /= null then C.Set_Type (To_String (Attr.Data_Type.Name)); end if; C.Not_Null := Attr.Multiplicity_Lower > 0; end; end if; end Prepare_Attribute; -- ------------------------------ -- Identify the UML association and create an entry for it in the table. -- ------------------------------ procedure Prepare_Association (Table : in out Gen.Model.Tables.Table_Definition'Class; Node : in Model_Element_Access) is A : Association_Definition_Access; Assoc : constant Association_End_Element_Access := Association_End_Element'Class (Node.all)'Access; Msg : constant String := Node.Get_Error_Message; begin Log.Info ("Prepare class association {0}", Assoc.Name); if Msg'Length /= 0 then Context.Error (Assoc.Get_Location & ": " & Msg); end if; if Assoc.Multiplicity_Upper /= 1 then Context.Error (Assoc.Get_Location & ": multiple association '{0}' for table '{1}' is not supported.", To_String (Assoc.Name), Table.Get_Name); else Table.Add_Association (Assoc.Name, A); A.Set_Comment (Assoc.Get_Comment); A.Set_Location (Assoc.Get_Location); A.Set_Type (Assoc.Source_Element.Get_Qualified_Name); A.Not_Null := Assoc.Multiplicity_Lower > 0; -- If the <<use foreign key>> stereotype is set on the association, to not use -- the Ada tagged object but create an attribute using the foreign key type. A.Use_Foreign_Key_Type := Node.Parent.Has_Stereotype (Handler.Use_FK_Stereotype); A.Is_Key := Node.Has_Stereotype (Handler.PK_Stereotype); if A.Use_Foreign_Key_Type then Log.Info ("Association {0} type is using foreign key", Assoc.Name); end if; end if; end Prepare_Association; procedure Prepare_Parameter (Operation : in out Gen.Model.Operations.Operation_Definition'Class; Node : in Model_Element_Access) is Param : constant Attribute_Element_Access := Attribute_Element'Class (Node.all)'Access; P : Gen.Model.Operations.Parameter_Definition_Access; begin if Param.Data_Type /= null then Log.Info ("Prepare operation parameter {0} : {1}", Param.Name, Param.Data_Type.Get_Qualified_Name); Operation.Add_Parameter (Param.Name, To_UString (Param.Data_Type.Get_Qualified_Name), P); end if; end Prepare_Parameter; -- ------------------------------ -- Identify the UML operation and create an entry for it in the table. -- ------------------------------ procedure Prepare_Operation (Table : in out Gen.Model.Tables.Table_Definition'Class; Node : in Model_Element_Access) is Op : constant Operation_Element_Access := Operation_Element'Class (Node.all)'Access; Msg : constant String := Node.Get_Error_Message; Operation : Gen.Model.Operations.Operation_Definition_Access; begin Log.Info ("Prepare class operation {0}", Op.Name); if Msg'Length /= 0 then Context.Error (Op.Get_Location & ": " & Msg); end if; Table.Add_Operation (Op.Name, Operation); Operation.Set_Location (Op.Get_Location); Operation.Set_Comment (Op.Get_Comment); Iterate_For_Operation (Operation.all, Op.Elements, Prepare_Parameter'Access); end Prepare_Operation; -- ------------------------------ -- Prepare a UML/XMI class: -- o if the class has the <<Dynamo.ADO.table>> stereotype, create a table definition. -- o if the class has the <<Dynamo.AWA.bean>> stereotype, create a bean -- ------------------------------ procedure Prepare_Class (Pkg : in out Gen.Model.Packages.Package_Definition'Class; Item : in Gen.Model.XMI.Model_Element_Access) is Class : constant Class_Element_Access := Class_Element'Class (Item.all)'Access; Name : constant UString := Gen.Utils.Qualify_Name (Pkg.Name, Class.Name); begin Log.Info ("Prepare class {0}", Name); if Item.Has_Stereotype (Handler.Table_Stereotype) then Log.Debug ("Class {0} recognized as a database table", Name); declare Table : constant Table_Definition_Access := Gen.Model.Tables.Create_Table (Name); Has_List : constant String := Item.Find_Tag_Value (Handler.Has_List_Tag, "true"); T_Name : constant String := Item.Find_Tag_Value (Handler.Table_Name_Tag, ""); begin Log.Info ("Has list: {0}", Has_List); Table.Set_Comment (Item.Get_Comment); Table.Set_Location (Item.Get_Location); Model.Register_Table (Table); Table.Has_List := Has_List = "true"; Table.Is_Serializable := Item.Has_Stereotype (Handler.Serialize_Stereotype); if T_Name'Length /= 0 then Log.Info ("Using table name {0}", Name); Table.Table_Name := To_UString (T_Name); end if; Iterate_For_Table (Table.all, Class.Attributes, Prepare_Attribute'Access); Iterate_For_Table (Table.all, Class.Associations, Prepare_Association'Access); end; elsif Item.Has_Stereotype (Handler.Bean_Stereotype) or Item.Has_Stereotype (Handler.Limited_Bean_Stereotype) then Log.Debug ("Class {0} recognized as a bean", Name); declare Bean : constant Bean_Definition_Access := Gen.Model.Beans.Create_Bean (Name); begin Model.Register_Bean (Bean); Bean.Set_Comment (Item.Get_Comment); Bean.Set_Location (Item.Get_Location); Bean.Target := Name; Bean.Is_Limited := Item.Has_Stereotype (Handler.Limited_Bean_Stereotype); Bean.Is_Serializable := Item.Has_Stereotype (Handler.Serialize_Stereotype); if Class.Parent_Class /= null then Log.Info ("Bean {0} inherit from {1}", Name, To_String (Class.Parent_Class.Name)); Bean.Parent_Name := To_UString (Class.Parent_Class.Get_Qualified_Name); end if; Iterate_For_Bean (Bean.all, Class.Attributes, Prepare_Attribute'Access); Iterate_For_Table (Bean.all, Class.Associations, Prepare_Association'Access); Iterate_For_Table (Bean.all, Class.Operations, Prepare_Operation'Access); end; else Log.Info ("UML class {0} not generated: no <<Bean>> and no <<Table>> stereotype", To_String (Name)); end if; exception when E : others => Log.Error ("Exception", E); end Prepare_Class; -- ------------------------------ -- Collect the enum literal for the enum definition. -- ------------------------------ procedure Prepare_Enum_Literal (Enum : in out Gen.Model.Enums.Enum_Definition'Class; Item : in Gen.Model.XMI.Model_Element_Access) is Literal : Gen.Model.Enums.Value_Definition_Access; Value : constant String := Item.Find_Tag_Value (Handler.Literal_Tag, ""); begin Log.Info ("Prepare enum literal {0}", Item.Name); Enum.Add_Value (To_String (Item.Name), Literal); if Value'Length > 0 then begin Literal.Number := Natural'Value (Value); exception when others => Context.Error (Item.Get_Location & ": value '{0}' for enum literal '{1}' must be a number", Value, To_String (Item.Name)); end; end if; end Prepare_Enum_Literal; -- ------------------------------ -- Register the enum in the model for the generation. -- ------------------------------ procedure Prepare_Type (Pkg : in out Gen.Model.Packages.Package_Definition'Class; Item : in Gen.Model.XMI.Model_Element_Access) is Data_Type : constant Data_Type_Element_Access := Data_Type_Element'Class (Item.all)'Access; Name : constant String := Data_Type.Get_Qualified_Name; Msg : constant String := Data_Type.Get_Error_Message; Sql : constant String := Data_Type.Find_Tag_Value (Handler.Sql_Type_Tag, ""); Stype : Gen.Model.Stypes.Stype_Definition_Access; begin Log.Info ("Prepare data type {0} - {1}", Name, Sql); if Msg'Length > 0 then Context.Error (Item.Get_Location & ": " & Msg); end if; if Data_Type.Parent_Type /= null then Stype := Gen.Model.Stypes.Create_Stype (To_UString (Name), To_UString (Data_Type.Parent_Type.Get_Qualified_Name)); else Stype := Gen.Model.Stypes.Create_Stype (To_UString (Name), Null_Unbounded_String); end if; Stype.Set_Comment (Item.Get_Comment); Stype.Set_Location (Item.Get_Location); Stype.Sql_Type := To_UString (Sql); Model.Register_Stype (Stype); exception when Gen.Model.Name_Exist => -- Ignore the Name_Exist exception for pre-defined package -- because the type is already defined through a XML mapping definition. if not Pkg.Is_Predefined then raise; end if; end Prepare_Type; -- ------------------------------ -- Register the enum in the model for the generation. -- ------------------------------ procedure Prepare_Enum (Pkg : in out Gen.Model.Packages.Package_Definition'Class; Item : in Gen.Model.XMI.Model_Element_Access) is pragma Unreferenced (Pkg); Name : constant String := Item.Get_Qualified_Name; Msg : constant String := Item.Get_Error_Message; Enum : Gen.Model.Enums.Enum_Definition_Access; Sql : constant String := Item.Find_Tag_Value (Handler.Sql_Type_Tag, ""); begin Log.Info ("Prepare enum {0}", Name); if Msg'Length > 0 then Context.Error (Item.Get_Location & ": " & Msg); end if; Enum := Gen.Model.Enums.Create_Enum (To_UString (Name)); Enum.Set_Comment (Item.Get_Comment); Enum.Set_Location (Item.Get_Location); Enum.Sql_Type := To_UString (Sql); Model.Register_Enum (Enum); Iterate_For_Enum (Enum.all, Item.Elements, Prepare_Enum_Literal'Access); end Prepare_Enum; -- ------------------------------ -- Scan the package for the model generation. -- ------------------------------ procedure Prepare_Package (Id : in UString; Item : in Gen.Model.XMI.Model_Element_Access) is pragma Unreferenced (Id); Pkg : constant Package_Element_Access := Package_Element'Class (Item.all)'Access; Name : constant String := Pkg.Get_Qualified_Name; P : Gen.Model.Packages.Package_Definition_Access; begin if Pkg.Is_Profile then return; end if; Log.Info ("Prepare package {0}", Name); Model.Register_Package (To_UString (Name), P); if Item.Has_Stereotype (Handler.Data_Model_Stereotype) then Log.Info ("Package {0} has the <<DataModel>> stereotype", Name); else Log.Info ("Package {0} does not have the <<DataModel>> stereotype.", Name); -- Do not generate packages that don't have the <<DataModel>> stereotype. -- But still get their UML definition so that we can use their classes. P.Set_Predefined; end if; P.Set_Comment (Pkg.Get_Comment); Iterate_For_Package (P.all, Pkg.Types, Prepare_Type'Access); Iterate_For_Package (P.all, Pkg.Enums, Prepare_Enum'Access); Iterate_For_Package (P.all, Pkg.Classes, Prepare_Class'Access); end Prepare_Package; -- ------------------------------ -- Scan the profile packages for the model generation. -- ------------------------------ procedure Prepare_Profile (Id : in UString; Item : in Gen.Model.XMI.Model_Element_Access) is pragma Unreferenced (Id); Pkg : constant Package_Element_Access := Package_Element'Class (Item.all)'Access; Name : constant String := Pkg.Get_Qualified_Name; P : Gen.Model.Packages.Package_Definition_Access; begin if not Pkg.Is_Profile then return; end if; Log.Info ("Prepare profile package {0}", Name); Model.Register_Package (To_UString (Name), P); P.Set_Predefined; P.Set_Comment (Pkg.Get_Comment); -- Iterate_For_Package (P.all, Pkg.Types, Prepare_Type'Access); Iterate_For_Package (P.all, Pkg.Enums, Prepare_Enum'Access); Iterate_For_Package (P.all, Pkg.Classes, Prepare_Class'Access); end Prepare_Profile; procedure Prepare_Model (Key : in UString; Model : in out Gen.Model.XMI.Model_Map.Map) is begin Log.Info ("Preparing model {0}", Key); Gen.Model.XMI.Iterate (Model => Model, On => Gen.Model.XMI.XMI_PACKAGE, Process => Prepare_Package'Access); end Prepare_Model; Iter : Gen.Model.XMI.UML_Model_Map.Cursor := Handler.Nodes.First; begin Log.Debug ("Preparing the XMI model for generation"); Gen.Model.XMI.Reconcile (Handler.Nodes, Context.Get_Parameter (Gen.Configs.GEN_DEBUG_ENABLE)); -- Get the Dynamo stereotype definitions. Handler.Table_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME); Handler.PK_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "ADO.PK", Gen.Model.XMI.BY_NAME); Handler.FK_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "ADO.FK", Gen.Model.XMI.BY_NAME); Handler.Version_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "ADO.Version", Gen.Model.XMI.BY_NAME); Handler.Nullable_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "ADO.Nullable", Gen.Model.XMI.BY_NAME); Handler.Not_Null_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "ADO.Not Null", Gen.Model.XMI.BY_NAME); Handler.Data_Model_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "ADO.DataModel", Gen.Model.XMI.BY_NAME); Handler.Use_FK_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "ADO.use foreign key", Gen.Model.XMI.BY_NAME); Handler.Auditable_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "ADO.Auditable", Gen.Model.XMI.BY_NAME); Handler.Bean_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "AWA.Bean", Gen.Model.XMI.BY_NAME); Handler.Limited_Bean_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "AWA.Limited_Bean", Gen.Model.XMI.BY_NAME); Handler.Serialize_Stereotype := Find_Stereotype (Handler.Nodes, "Dynamo.xmi", "ASF.Serializable", Gen.Model.XMI.BY_NAME); Handler.Has_List_Tag := Find_Tag_Definition (Handler.Nodes, "Dynamo.xmi", "ADO.Table.@dynamo.table.hasList", Gen.Model.XMI.BY_NAME); Handler.Table_Name_Tag := Find_Tag_Definition (Handler.Nodes, "Dynamo.xmi", "ADO.Table.@dynamo.table.name", Gen.Model.XMI.BY_NAME); Handler.Sql_Type_Tag := Find_Tag_Definition (Handler.Nodes, "Dynamo.xmi", "ADO.@dynamo.sql.type", Gen.Model.XMI.BY_NAME); Handler.Sql_Length_Tag := Find_Tag_Definition (Handler.Nodes, "Dynamo.xmi", "ADO.@dynamo.sql.length", Gen.Model.XMI.BY_NAME); Handler.Generator_Tag := Find_Tag_Definition (Handler.Nodes, "Dynamo.xmi", "ADO.PK.@dynamo.pk.generator", Gen.Model.XMI.BY_NAME); Handler.Literal_Tag := Find_Tag_Definition (Handler.Nodes, "Dynamo.xmi", "ADO.Literal.@dynamo.literal", Gen.Model.XMI.BY_NAME); for Model of Handler.Nodes loop Gen.Model.XMI.Iterate (Model => Model, On => Gen.Model.XMI.XMI_PACKAGE, Process => Prepare_Profile'Access); end loop; while Gen.Model.XMI.UML_Model_Map.Has_Element (Iter) loop Handler.Nodes.Update_Element (Iter, Prepare_Model'Access); Gen.Model.XMI.UML_Model_Map.Next (Iter); end loop; if Model.Has_Packages then Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); end if; end Prepare; -- ------------------------------ -- Read the UML profiles that are referenced by the current models. -- The UML profiles are installed in the UML config directory for dynamo's installation. -- ------------------------------ procedure Read_Profiles (Handler : in out Artifact; Context : in out Generator'Class) is Path : constant String := Context.Get_Parameter (Gen.Configs.GEN_UML_DIR); Iter : Util.Strings.Sets.Cursor := Handler.Profiles.First; begin while Util.Strings.Sets.Has_Element (Iter) loop declare Profile : constant String := Util.Strings.Sets.Element (Iter); begin if not Handler.Nodes.Contains (To_UString (Profile)) then Log.Info ("Reading the UML profile {0}", Profile); -- We have a profile, load the UML model. Handler.Read_Model (Util.Files.Compose (Path, Profile), Context, True); -- Verify that we have the model, report an error and remove it from the profiles. if not Handler.Nodes.Contains (To_UString (Profile)) then Context.Error ("UML profile {0} was not found", Profile); Handler.Profiles.Delete (Profile); end if; -- And start again from the beginning since new profiles could be necessary. Iter := Handler.Profiles.First; else Util.Strings.Sets.Next (Iter); end if; end; end loop; end Read_Profiles; -- ------------------------------ -- Read the UML/XMI model file. -- ------------------------------ procedure Read_Model (Handler : in out Artifact; File : in String; Context : in out Generator'Class; Is_Predefined : in Boolean := False) is procedure Read (Key : in UString; Model : in out Gen.Model.XMI.Model_Map.Map); procedure Read (Key : in UString; Model : in out Gen.Model.XMI.Model_Map.Map) is pragma Unreferenced (Key); N : constant Natural := Util.Strings.Rindex (File, '.'); Name : constant String := Ada.Directories.Base_Name (File); type Parser is new Util.Serialize.IO.XML.Parser with null record; -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. overriding procedure Error (Handler : in out Parser; Message : in String); -- ------------------------------ -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. -- ------------------------------ overriding procedure Error (Handler : in out Parser; Message : in String) is begin if Ada.Strings.Fixed.Index (Message, "Invalid absolute IRI") > 0 and then Ada.Strings.Fixed.Index (Message, "org.omg.xmi.namespace.UML") > 0 then return; end if; Context.Error ("{0}: {1}", Name & ".xmi" & Parser'Class (Handler).Get_Location, Message); end Error; Reader : aliased Parser; Mapper : Util.Serialize.Mappers.Processing; Info : aliased XMI_Info; Def_Type : constant String := Context.Get_Parameter (Gen.Configs.GEN_UML_DEFAULT_TYPE); begin Info.Model := Model'Unchecked_Access; Info.Parser := Reader'Unchecked_Access; Info.Profiles := Handler.Profiles'Unchecked_Access; Info.File := To_UString (Name & ".xmi"); Info.Default_Type := To_UString (Def_Type); Info.Is_Profile := Is_Predefined; Mapper.Add_Mapping ("XMI", XMI_Mapping'Access); if Context.Get_Parameter (Gen.Configs.GEN_DEBUG_ENABLE) then Mapper.Dump (Log); end if; XMI_Mapper.Set_Context (Mapper, Info'Unchecked_Access); if N > 0 and then File (N .. File'Last) = ".zargo" then declare Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; begin Pipe.Open ("unzip -cq " & File & " " & Name & ".xmi", Util.Processes.READ); Buffer.Initialize (Pipe'Unchecked_Access, 4096); Reader.Parse (Buffer, Mapper); Pipe.Close; end; else Reader.Parse (File, Mapper); end if; end Read; UML : Gen.Model.XMI.Model_Map.Map; Name : constant UString := To_UString (Ada.Directories.Simple_Name (File)); begin Log.Info ("Reading XMI {0}", File); Handler.Initialized := True; Handler.Nodes.Include (Name, UML); Handler.Nodes.Update_Element (Handler.Nodes.Find (Name), Read'Access); Handler.Read_Profiles (Context); end Read_Model; begin -- Define the XMI mapping. XMI_Mapping.Add_Mapping ("**/Package/@name", FIELD_PACKAGE_NAME); XMI_Mapping.Add_Mapping ("**/Package/@xmi.id", FIELD_PACKAGE_ID); XMI_Mapping.Add_Mapping ("**/Package", FIELD_PACKAGE_END); XMI_Mapping.Add_Mapping ("**/Class/@name", FIELD_CLASS_NAME); XMI_Mapping.Add_Mapping ("**/Class/@xmi.id", FIELD_CLASS_ID); XMI_Mapping.Add_Mapping ("**/Class/@visibility", FIELD_CLASS_VISIBILITY); XMI_Mapping.Add_Mapping ("**/Class", FIELD_CLASS_END); -- Generalization (limited to single inheritance). XMI_Mapping.Add_Mapping ("**/Generalization/@xmi.idref", FIELD_GENERALIZATION_ID); XMI_Mapping.Add_Mapping ("**/Generalization/@xmi.href", FIELD_GENERALIZATION_ID); XMI_Mapping.Add_Mapping ("**/Generalization/@xmi.id", FIELD_GENERALIZATION_ID); XMI_Mapping.Add_Mapping ("**/Generalization/Generalization.child/Class/@xmi.idref", FIELD_GENERALIZATION_CHILD_ID); XMI_Mapping.Add_Mapping ("**/Generalization/Generalization.parent/Class/@xmi.idref", FIELD_GENERALIZATION_PARENT_ID); XMI_Mapping.Add_Mapping ("**/Generalization/Generalization.child/DataType/@xmi.idref", FIELD_GENERALIZATION_CHILD_ID); XMI_Mapping.Add_Mapping ("**/Generalization/Generalization.parent/DataType/@xmi.idref", FIELD_GENERALIZATION_PARENT_ID); XMI_Mapping.Add_Mapping ("**/Generalization/Generalization.parent/DataType/@href", FIELD_GENERALIZATION_PARENT_ID); XMI_Mapping.Add_Mapping ("**/Generalization", FIELD_GENERALIZATION_END); -- Class attribute mapping. XMI_Mapping.Add_Mapping ("**/Attribute/@name", FIELD_ATTRIBUTE_NAME); XMI_Mapping.Add_Mapping ("**/Attribute/@xmi.id", FIELD_ATTRIBUTE_ID); XMI_Mapping.Add_Mapping ("**/Attribute/@visibility", FIELD_ATTRIBUTE_VISIBILITY); XMI_Mapping.Add_Mapping ("**/Attribute/@changeability", FIELD_ATTRIBUTE_CHANGEABILITY); XMI_Mapping.Add_Mapping ("**/Attribute.initialValue/Expression/@body", FIELD_ATTRIBUTE_INITIAL_VALUE); XMI_Mapping.Add_Mapping ("**/Attribute", FIELD_ATTRIBUTE); -- Field multiplicity. XMI_Mapping.Add_Mapping ("**/MultiplicityRange/@lower", FIELD_MULTIPLICITY_LOWER); XMI_Mapping.Add_Mapping ("**/MultiplicityRange/@upper", FIELD_MULTIPLICITY_UPPER); -- Operation mapping. XMI_Mapping.Add_Mapping ("**/Operation/@name", FIELD_OPERATION_NAME); XMI_Mapping.Add_Mapping ("**/Operation/@xmi.id", FIELD_OPERATION_ID); XMI_Mapping.Add_Mapping ("**/Operation", FIELD_OPERATION_END); XMI_Mapping.Add_Mapping ("**/Parameter/@xmi.id", FIELD_PARAMETER_ID); XMI_Mapping.Add_Mapping ("**/Parameter/@name", FIELD_PARAMETER_NAME); XMI_Mapping.Add_Mapping ("**/Parameter/@kind", FIELD_PARAMETER_KIND); XMI_Mapping.Add_Mapping ("**/Parameter", FIELD_PARAMETER_END); XMI_Mapping.Add_Mapping ("**/Parameter/Parameter.type/Class/@xmi.idref", FIELD_CLASSIFIER_HREF); XMI_Mapping.Add_Mapping ("**/Parameter/Parameter.type/Class/@xmi.href", FIELD_CLASSIFIER_HREF); XMI_Mapping.Add_Mapping ("**/Parameter/Parameter.type/Class/@href", FIELD_CLASSIFIER_HREF); XMI_Mapping.Add_Mapping ("**/Parameter/Parameter.type/DataType/@xmi.href", FIELD_CLASSIFIER_HREF); XMI_Mapping.Add_Mapping ("**/Parameter/Parameter.type/DataType/@href", FIELD_CLASSIFIER_HREF); -- Association mapping. XMI_Mapping.Add_Mapping ("**/Association/@name", FIELD_ASSOCIATION_NAME); XMI_Mapping.Add_Mapping ("**/Association/@xmi.id", FIELD_ASSOCIATION_ID); XMI_Mapping.Add_Mapping ("**/Association", FIELD_ASSOCIATION); -- Association end mapping. XMI_Mapping.Add_Mapping ("**/AssociationEnd/@name", FIELD_ASSOCIATION_END_NAME); XMI_Mapping.Add_Mapping ("**/AssociationEnd/@xmi.id", FIELD_ASSOCIATION_END_ID); XMI_Mapping.Add_Mapping ("**/AssociationEnd/@visibility", FIELD_ASSOCIATION_END_VISIBILITY); XMI_Mapping.Add_Mapping ("**/AssociationEnd/@isNavigable", FIELD_ASSOCIATION_END_NAVIGABLE); XMI_Mapping.Add_Mapping ("**/AssociationEnd", FIELD_ASSOCIATION_END); XMI_Mapping.Add_Mapping ("**/AssociationEnd.participant/Class/@xmi.idref", FIELD_ASSOCIATION_CLASS_ID); XMI_Mapping.Add_Mapping ("**/AssociationEnd.participant/Class/@href", FIELD_ASSOCIATION_CLASS_ID); -- Comment mapping. XMI_Mapping.Add_Mapping ("**/Comment/@xmi.id", FIELD_COMMENT_ID); XMI_Mapping.Add_Mapping ("**/Comment/@body", FIELD_VALUE); XMI_Mapping.Add_Mapping ("**/Comment/Comment.annotatedElement/Class/@xmi.idref", FIELD_ID_REF); XMI_Mapping.Add_Mapping ("**/Comment/Comment.annotatedElement/Attribute/@xmi.idref", FIELD_ID_REF); XMI_Mapping.Add_Mapping ("**/Comment/Comment.annotatedElement/Enumeration/@xmi.idref", FIELD_ID_REF); XMI_Mapping.Add_Mapping ("**/Comment/Comment.annotatedElement/AssociationEnd/@xmi.idref", FIELD_ID_REF); XMI_Mapping.Add_Mapping ("**/Comment", FIELD_COMMENT); -- Tagged value mapping. XMI_Mapping.Add_Mapping ("**/TaggedValue/@xmi.id", FIELD_TAGGED_ID); XMI_Mapping.Add_Mapping ("**/TaggedValue/TaggedValue.dataValue", FIELD_VALUE); XMI_Mapping.Add_Mapping ("**/TaggedValue/TaggedValue.type/@xmi.idref", FIELD_ID_REF); XMI_Mapping.Add_Mapping ("**/TaggedValue/TaggedValue.type/TagDefinition/@xmi.idref", FIELD_ID_REF); XMI_Mapping.Add_Mapping ("**/TaggedValue/TaggedValue.type/TagDefinition/@href", FIELD_HREF); XMI_Mapping.Add_Mapping ("**/TaggedValue", FIELD_TAGGED_VALUE); -- Tag definition mapping. XMI_Mapping.Add_Mapping ("**/TagDefinition/@xmi.id", FIELD_TAG_DEFINITION_ID); XMI_Mapping.Add_Mapping ("**/TagDefinition/@name", FIELD_TAG_DEFINITION_NAME); XMI_Mapping.Add_Mapping ("**/TagDefinition", FIELD_TAG_DEFINITION); -- Stereotype mapping. XMI_Mapping.Add_Mapping ("**/Stereotype/@href", FIELD_STEREOTYPE_HREF); XMI_Mapping.Add_Mapping ("**/Stereotype/@xmi.id", FIELD_STEREOTYPE_ID); XMI_Mapping.Add_Mapping ("**/Stereotype/@name", FIELD_STEREOTYPE_NAME); XMI_Mapping.Add_Mapping ("**/Stereotype", FIELD_STEREOTYPE); -- Enumeration mapping. XMI_Mapping.Add_Mapping ("**/Enumeration/@xmi.id", FIELD_ID); XMI_Mapping.Add_Mapping ("**/Enumeration/@name", FIELD_ENUMERATION); XMI_Mapping.Add_Mapping ("**/Enumeration/Enumeration.literal/EnumerationLiteral/@xmi.id", FIELD_ENUMERATION_LITERAL); XMI_Mapping.Add_Mapping ("**/Enumeration/Enumeration.literal/EnumerationLiteral/@name", FIELD_NAME); XMI_Mapping.Add_Mapping ("**/Enumeration/Enumeration.literal/EnumerationLiteral", FIELD_ENUMERATION_LITERAL_END); XMI_Mapping.Add_Mapping ("**/Enumeration/@href", FIELD_ENUMERATION_HREF); XMI_Mapping.Add_Mapping ("**/Enumeration/@xmi.idref", FIELD_ENUMERATION_HREF); XMI_Mapping.Add_Mapping ("**/Classifier/@xmi.idref", FIELD_CLASSIFIER_HREF); XMI_Mapping.Add_Mapping ("**/Classifier/@href", FIELD_CLASSIFIER_HREF); XMI_Mapping.Add_Mapping ("**/Dependency.client/Class/@xmi.idref", FIELD_CLASSIFIER_HREF); XMI_Mapping.Add_Mapping ("**/Dependency.supplier/Class/@xmi.idref", FIELD_CLASSIFIER_HREF); -- Data type mapping. XMI_Mapping.Add_Mapping ("**/DataType/@xmi.id", FIELD_ID); XMI_Mapping.Add_Mapping ("**/DataType/@name", FIELD_DATA_TYPE_NAME); XMI_Mapping.Add_Mapping ("**/DataType", FIELD_DATA_TYPE); XMI_Mapping.Add_Mapping ("**/DataType/@href", FIELD_DATA_TYPE_HREF); XMI_Mapping.Add_Mapping ("**/DataType/@xmi.idref", FIELD_DATA_TYPE_HREF); XMI_Mapping.Add_Mapping ("**/StructuralFeature.type/Class/@xmi.idref", FIELD_DATA_TYPE_HREF); end Gen.Artifacts.XMI;
package openGL.Frustum -- -- Provide frustum operations. -- is type Plane_Id is (Left, Right, High, Low, Near, Far); type Plane_array is array (Plane_Id) of openGL.Geometry_3d.Plane; procedure normalise (Planes : in out Plane_array); end openGL.Frustum;
-- Based on AdaCore's Ada Drivers Library, -- see https://github.com/AdaCore/Ada_Drivers_Library, -- checkout 93b5f269341f970698af18f9182fac82a0be66c3. -- Copyright (C) Adacore -- -- Tailored to StratoX project. -- Author: Martin Becker (becker@rcs.ei.tum.de) with STM32_SVD.RCC; use STM32_SVD.RCC; package body Media_Reader.SDCard.Config is ------------------------- -- Enable_Clock_Device -- ------------------------- procedure Enable_Clock_Device is begin RCC_Periph.APB2ENR.SDIOEN := True; end Enable_Clock_Device; ------------------ -- Reset_Device -- ------------------ procedure Reset_Device is begin RCC_Periph.APB2RSTR.SDIORST := True; -- FIXME: need some minimum time here? RCC_Periph.APB2RSTR.SDIORST := False; end Reset_Device; end Media_Reader.SDCard.Config;
-- part of AdaYaml, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" package body Yaml.Destination.Text_IO is function As_Destination (File : Ada.Text_IO.File_Access) return Pointer is (new Instance'(Ada.Finalization.Limited_Controlled with File_Pointer => File)); procedure Write_Data (D : in out Instance; Buffer : String) is begin Ada.Text_IO.Put (D.File_Pointer.all, Buffer); end Write_Data; end Yaml.Destination.Text_IO;
package body ACO.Nodes is overriding procedure On_Event (This : in out Tick_Subscriber; Data : in ACO.Events.Handler_Event_Data) is begin This.Node_Ref.Periodic_Actions (T_Now => Data.Current_Time); This.Node_Ref.Od.Events.Process; end On_Event; overriding procedure On_Event (This : in out Message_Subscriber; Data : in ACO.Events.Handler_Event_Data) is begin This.Node_Ref.On_Message_Dispatch (Msg => Data.Msg); end On_Event; overriding procedure Initialize (This : in out Node_Base) is begin This.Handler.Events.Handler_Events.Attach (Subscriber => This.Periodic_Action_Indication'Unchecked_Access); This.Handler.Events.Handler_Events.Attach (Subscriber => This.New_Message_Indication'Unchecked_Access); end Initialize; overriding procedure Finalize (This : in out Node_Base) is begin This.Handler.Events.Handler_Events.Detach (Subscriber => This.Periodic_Action_Indication'Unchecked_Access); This.Handler.Events.Handler_Events.Detach (Subscriber => This.New_Message_Indication'Unchecked_Access); end Finalize; end ACO.Nodes;
-- -- Uwe R. Zimmer, Australia, July 2011 -- generic type Element is private; type Buffer_Index is mod <>; package Generic_Realtime_Buffer is pragma Elaborate_Body; type Realtime_Buffer is private; procedure Put (B : in out Realtime_Buffer; Item : Element); procedure Get (B : in out Realtime_Buffer; Item : out Element); function Element_Available (B : Realtime_Buffer) return Boolean; Calling_Get_On_Empty_Buffer : exception; private type No_Of_Elements is new Natural range 0 .. Natural (Buffer_Index'Last) + 1; type Buffer_Array is array (Buffer_Index) of Element; type Realtime_Buffer is record Write_To, Read_From : Buffer_Index := Buffer_Index'First; Elements_In_Buffer : No_Of_Elements := 0; Buffer : Buffer_Array; end record; end Generic_Realtime_Buffer;
-- Copyright (c) 2021 Devin Hill -- zlib License -- see LICENSE for details. with Ada.Unchecked_Conversion; with System; use type System.Address; package body GBA.Display.Objects is type Shape_Scale is record Scale : OBJ_Scale; Shape : OBJ_Shape; end record with Size => 4; for Shape_Scale use record Scale at 0 range 0 .. 1; Shape at 0 range 2 .. 3; end record; function Cast is new Ada.Unchecked_Conversion (Shape_Scale, OBJ_Size); function Cast is new Ada.Unchecked_Conversion (OBJ_Size, Shape_Scale); function As_Size (Shape : OBJ_Shape; Scale : OBJ_Scale) return OBJ_Size is Shape_And_Scale : Shape_Scale := (Shape => Shape, Scale => Scale); begin return Cast (Shape_And_Scale); end; procedure As_Shape_And_Scale (Size : OBJ_Size; Shape : out OBJ_Shape; Scale : out OBJ_Scale) is Shape_And_Scale : Shape_Scale := Cast (Size); begin Shape := Shape_And_Scale.Shape; Scale := Shape_And_Scale.Scale; end; function Affine_Transform_Address (Ix : OBJ_Affine_Transform_Index) return Address is ( OAM_Address'First + 6 + 32 * Address (Ix) ); function Attributes_Of_Object (ID : OBJ_ID) return OAM_Attributes_Ptr is Attributes : Volatile_OBJ_Attributes renames Object_Attribute_Memory (Integer (ID)).Attributes; begin return Attributes'Unchecked_Access; end; function Attributes_Of_Object (ID : OBJ_ID) return OBJ_Attributes is Attributes : Volatile_OBJ_Attributes renames Object_Attribute_Memory (Integer (ID)).Attributes; begin return OBJ_Attributes (Attributes); end; procedure Set_Object_Attributes (ID : OBJ_ID; Attributes : OBJ_Attributes) is Curr_Attributes : Volatile_OBJ_Attributes renames Object_Attribute_Memory (Integer (ID)).Attributes; begin Curr_Attributes := Volatile_OBJ_Attributes (Attributes); end; end GBA.Display.Objects;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . L I B M -- -- -- -- S p e c -- -- -- -- Copyright (C) 2014-2021, 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. -- -- -- -- -- -- -- -- -- -- -- -- 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 is the Ada Cert Math specific version of s-libm.ads with Ada.Numerics; package System.Libm is pragma Pure; Ln_2 : constant := 0.69314_71805_59945_30941_72321_21458_17656_80755; Ln_3 : constant := 1.09861_22886_68109_69139_52452_36922_52570_46475; Half_Ln_2 : constant := Ln_2 / 2.0; Inv_Ln_2 : constant := 1.0 / Ln_2; Half_Pi : constant := Ada.Numerics.Pi / 2.0; Third_Pi : constant := Ada.Numerics.Pi / 3.0; Quarter_Pi : constant := Ada.Numerics.Pi / 4.0; Sixth_Pi : constant := Ada.Numerics.Pi / 6.0; Max_Red_Trig_Arg : constant := 0.26 * Ada.Numerics.Pi; -- This constant representing the maximum absolute value of the reduced -- argument of the approximation functions for Sin, Cos and Tan. A value -- slightly larger than Pi / 4 is used. The reduction doesn't reduce to -- an interval strictly within +-Pi / 4, as that would complicate the -- reduction code. One_Over_Pi : constant := 1.0 / Ada.Numerics.Pi; Two_Over_Pi : constant := 2.0 / Ada.Numerics.Pi; Sqrt_2 : constant := 1.41421_35623_73095_04880_16887_24209_69807_85696; Sqrt_3 : constant := 1.73205_08075_68877_29352_74463_41505_87236_69428; Root16_Half : constant := 0.95760_32806_98573_64693_63056_35147_91544; -- Sixteenth root of 0.5 Sqrt_Half : constant := 0.70710_67811_86547_52440_08443_62105; subtype Quadrant is Integer range 0 .. 3; generic type T is digits <>; with function Sqrt (X : T) return T is <>; with function Approx_Asin (X : T) return T is <>; function Generic_Acos (X : T) return T; generic type T is digits <>; with function Approx_Atan (X : T) return T is <>; with function Infinity return T is <>; function Generic_Atan2 (Y, X : T) return T; generic type T is digits <>; procedure Generic_Pow_Special_Cases (Left : T; Right : T; Is_Special : out Boolean; Negate : out Boolean; Result : out T); generic type T is private; Mantissa : Positive; with function "-" (X : T) return T is <>; with function "+" (X, Y : T) return T is <>; with function "-" (X, Y : T) return T is <>; with function "*" (X, Y : T) return T is <>; with function "/" (X, Y : T) return T is <>; with function "<=" (X, Y : T) return Boolean is <>; with function "abs" (X : T) return T is <>; with function Exact (X : Long_Long_Float) return T is <>; with function Maximum_Relative_Error (X : T) return Float is <>; with function Sqrt (X : T) return T is <>; package Generic_Approximations is Epsilon : constant Float := 2.0**(1 - Mantissa); -- The approximations in this package will work well for single -- precision floating point types. function Approx_Asin (X : T) return T with Pre => abs X <= Exact (0.25), Post => abs Approx_Asin'Result <= Exact (Half_Pi); -- @llr Approx_Asin -- The Approx_Asin function shallapproximate the mathematical function -- arcsin (sqrt (x)) / sqrt (x) - 1.0 on -0.25 .. 0.25. -- -- Ada accuracy requirements: -- The approximation MRE shall be XXX T'Model_Epsilon. function Approx_Atan (X : T) return T with Pre => abs X <= Exact (Sqrt_3), Post => abs (Approx_Atan'Result) <= Exact (Half_Pi) and then Maximum_Relative_Error (Approx_Atan'Result) <= 2.0 * Epsilon; -- @llr Approx_Atan -- The Approx_Atan approximates the mathematical inverse tangent on -- -Sqrt (3) .. Sqrt (3) -- -- Accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Approx_Cos (X : T) return T with Pre => abs (X) <= Exact (Max_Red_Trig_Arg), Post => abs (Approx_Cos'Result) <= Exact (1.0) and then Maximum_Relative_Error (Approx_Cos'Result) <= 2.0 * Epsilon; -- @llr Approx_Cos -- The Approx_Cos approximates the mathematical cosine on -- -0.26 * Pi .. 0.26 * Pi -- -- Accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Approx_Exp (X : T) return T with Pre => abs (X) <= Exact (Ln_2 / 2.0), Post => Exact (0.0) <= Approx_Exp'Result and then Maximum_Relative_Error (Approx_Exp'Result) <= 2.0 * Epsilon; -- @llr Approx_Exp -- The Approx_Exp function approximates the mathematical exponent on -- -Ln (2.0) / 2.0 .. Ln (2.0) / 2.0 -- -- Accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Approx_Exp2 (X : T) return T with Pre => abs (X) <= Exact (Ln_2 / 2.0), Post => Exact (0.0) <= Approx_Exp2'Result and then Maximum_Relative_Error (Approx_Exp2'Result) <= 2.0 * Epsilon; -- @llr Approx_Exp2 -- The Approx_Exp2 function approximates the mathematical function -- (x-> 2.0 ** x) on -Ln (2.0) / 2.0 .. Ln (2.0) / 2.0 -- -- Accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Approx_Log (X : T) return T with Pre => Exact (Sqrt_2 / 2.0) <= X and then X <= Exact (Sqrt_2), Post => Maximum_Relative_Error (Approx_Log'Result) <= 2.0 * Epsilon; -- @llr Approx_Log -- The Approx_Log function approximates the mathematical logarithm on -- Sqrt (2.0) /2.0 .. Sqrt (2.0) -- -- Accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Approx_Power_Log (X : T) return T; -- @llr Approx_Power_Log -- The Approx_Power_Log approximates the function -- (x -> Log ((x-1) / (x+1), base => 2)) on the interval -- TODO -- -- Accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Approx_Sin (X : T) return T with Pre => (abs X) <= Exact (Max_Red_Trig_Arg), Post => abs Approx_Sin'Result <= Exact (1.0) and then Maximum_Relative_Error (Approx_Sin'Result) <= 2.0 * Epsilon; -- @llr Approx_Sin -- The Approx_Sin function approximates the mathematical sine on -- -0.26 * Pi .. 0.26 * Pi -- -- Ada accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Approx_Sinh (X : T) return T with Pre => True, -- The original X >= 0.0 and X <= 1.0, fails ??? Post => abs Approx_Sinh'Result <= Exact ((Ada.Numerics.e - 1.0 / Ada.Numerics.e) / 2.0) and then Maximum_Relative_Error (Approx_Sinh'Result) <= 2.0 * Epsilon; -- @llr Approx_Sinh -- The Approx_Sinh function approximates the mathematical hyperbolic -- sine on XXX -- -- Accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Approx_Tan (X : T) return T with Pre => abs X <= Exact (Max_Red_Trig_Arg), Post => Maximum_Relative_Error (Approx_Tan'Result) <= 2.0 * Epsilon; -- @llr Approx_Tan -- The Approx_Tan function approximates the mathematical tangent on -- -0.26 * Pi .. 0.26 * Pi -- -- Accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Approx_Cot (X : T) return T with Pre => abs X <= Exact (Max_Red_Trig_Arg), Post => Maximum_Relative_Error (Approx_Cot'Result) <= 2.0 * Epsilon; -- @llr Approx_Cot -- The Approx_Cot function approximates the mathematical cotangent on -- -0.26 * Pi .. 0.26 * Pi -- -- Accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Approx_Tanh (X : T) return T with Pre => Exact (0.0) <= X and then X <= Exact (Ln_3 / 2.0), Post => abs (Approx_Tanh'Result) <= Exact (Half_Pi) and then Maximum_Relative_Error (Approx_Tanh'Result) <= 2.0 * Epsilon; -- @llr Approx_Tanh -- The Approx_Tanh function approximates the mathematical hyperbolic -- tangent on 0.0 .. Ln (3.0) / 2.0 -- -- Accuracy requirements: -- The approximation MRE is XXX T'Model_Epsilon function Asin (X : T) return T with Pre => abs X <= Exact (1.0), Post => Maximum_Relative_Error (Asin'Result) <= 400.0 * Epsilon; -- @llr Asin -- The Asin function has a maximum relative error of 2 epsilon. end Generic_Approximations; end System.Libm;
-- { dg-do compile } package Import_Abstract is type T1 is abstract tagged null record; procedure p1(X : T1) is abstract; pragma Import (Ada, p1); -- { dg-error "cannot import abstract subprogram" } end Import_Abstract;
-- { dg-do compile } procedure Bad_Array is A1 : array(Character range <> ) of Character := ( 'a', 'b', 'c' ); begin null; end Bad_Array;
procedure Named_Block is begin TheBlock: declare type IntArray is array(1..2) of Integer; ia : IntArray := (others => 0); begin null; end TheBlock; end Named_Block;
with Ada.Text_IO; package body Fibonacci is function Has_Element (Pos : Fibo_Cur) return Boolean is (Pos.Cur <= Natural'Last - Pos.Prev and Pos.Prev > 0); overriding function First (O : Fibo_Forward) return Fibo_Cur is ((Cur => 1, Prev => 1)); overriding function Next (O : Fibo_Forward; Pos : Fibo_Cur) return Fibo_Cur is ((Cur => Pos.Cur + Pos.Prev, Prev => Pos.Cur)); overriding function First (O : Fibo_Reversible) return Fibo_Cur is ((Cur => 1, Prev => 1)); overriding function Next (O : Fibo_Reversible; Pos : Fibo_Cur) return Fibo_Cur is ((Cur => Pos.Cur + Pos.Prev, Prev => Pos.Cur)); overriding function Last (O : Fibo_Reversible) return Fibo_Cur is ((Cur => 1134903170, Prev => 701408733)); overriding function Previous (O : Fibo_Reversible; Pos : Fibo_Cur) return Fibo_Cur is ((Cur => Pos.Prev, Prev => Pos.Cur - Pos.Prev)); function Element (C : Fibo_Cur) return Natural is (C.Cur); function Element (V : Fibo_Type'Class) return Natural is (V.Value); function Element_Value (C : Fibo_List; P : Fibo_Cur) return Fibo_Type'Class is (Fibo_Type'(Value => P.Cur, Cursor => P)); function Iterate (C : Fibo_List) return Fibo.Forward_Iterator'Class is (Fibo_Forward'(Value => 1, Cursor => (Cur => 1, Prev => 1))); procedure Put_Line (O : Fibo_Type'Class) is begin Ada.Text_IO.Put_Line (Natural'Image (Element (O))); end; end Fibonacci;
-- -- Copyright (C) 2014-2017 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 GNAT.Source_Info; with HW.Debug; with HW.GFX.GMA.Config; with HW.GFX.GMA.Registers; with HW.GFX.GMA.Power_And_Clocks_Haswell; with HW.GFX.GMA.DDI_Phy; use HW.GFX.GMA.Registers; package body HW.GFX.GMA.Power_And_Clocks is type Power_Domain is (PW1, PW2, DDI_A, DDI_BC); subtype Power_Well is Power_Domain range PW1 .. PW2; subtype Dynamic_Domain is Power_Domain range PW2 .. DDI_BC; subtype DDI_Domain is Dynamic_Domain range DDI_A .. DDI_BC; type DDI_Phy_Array is array (DDI_Domain) of DDI_Phy.T; Phy : constant DDI_Phy_Array := (DDI_A => DDI_Phy.A, DDI_BC => DDI_Phy.BC); NDE_RSTWRN_OPT_RST_PCH_Handshake_En : constant := 1 * 2 ** 4; FUSE_STATUS_DOWNLOAD_STATUS : constant := 1 * 2 ** 31; FUSE_STATUS_PG0_DIST_STATUS : constant := 1 * 2 ** 27; type Power_Well_Values is array (Power_Well) of Word32; PWR_WELL_CTL_POWER_REQUEST : constant Power_Well_Values := (PW1 => 1 * 2 ** 29, PW2 => 1 * 2 ** 31); PWR_WELL_CTL_POWER_STATE : constant Power_Well_Values := (PW1 => 1 * 2 ** 28, PW2 => 1 * 2 ** 30); FUSE_STATUS_PGx_DIST_STATUS : constant Power_Well_Values := (PW1 => 1 * 2 ** 26, PW2 => 1 * 2 ** 25); DBUF_CTL_DBUF_POWER_REQUEST : constant := 1 * 2 ** 31; DBUF_CTL_DBUF_POWER_STATE : constant := 1 * 2 ** 30; ---------------------------------------------------------------------------- BXT_DE_PLL_RATIO_MASK : constant := 16#ff#; BXT_DE_PLL_PLL_ENABLE : constant := 1 * 2 ** 31; BXT_DE_PLL_PLL_LOCK : constant := 1 * 2 ** 30; CDCLK_CD2X_DIV_SEL_MASK : constant := 3 * 2 ** 22; CDCLK_CD2X_DIV_SEL_1 : constant := 0 * 2 ** 22; CDCLK_CD2X_DIV_SEL_1_5 : constant := 1 * 2 ** 22; CDCLK_CD2X_DIV_SEL_2 : constant := 2 * 2 ** 22; CDCLK_CD2X_DIV_SEL_4 : constant := 3 * 2 ** 22; CDCLK_CD2X_PIPE_NONE : constant := 3 * 2 ** 20; CDCLK_CD2X_SSA_PRECHARGE_ENABLE : constant := 1 * 2 ** 16; CDCLK_CTL_CD_FREQ_DECIMAL_MASK : constant := 16#7ff#; function CDCLK_CTL_CD_FREQ_DECIMAL (Freq : Frequency_Type) return Word32 is begin return Word32 (2 * (Freq / 1_000_000 - 1)); end CDCLK_CTL_CD_FREQ_DECIMAL; BXT_PCODE_CDCLK_CONTROL : constant := 16#17#; BXT_CDCLK_PREPARE_FOR_CHANGE : constant := 16#8000_0000#; ---------------------------------------------------------------------------- procedure PW_Off (PD : Power_Well) is Ctl1, Ctl2, Ctl3, Ctl4 : Word32; begin pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity)); Read (PWR_WELL_CTL_BIOS, Ctl1); Read (PWR_WELL_CTL_DRIVER, Ctl2); Read (PWR_WELL_CTL_KVMR, Ctl3); Read (PWR_WELL_CTL_DEBUG, Ctl4); pragma Debug (Posting_Read (PWR_WELL_CTL5)); -- Result for debugging only pragma Debug (Posting_Read (PWR_WELL_CTL6)); -- Result for debugging only if ((Ctl1 or Ctl2 or Ctl3 or Ctl4) and PWR_WELL_CTL_POWER_REQUEST (PD)) /= 0 then Wait_Set_Mask (PWR_WELL_CTL_DRIVER, PWR_WELL_CTL_POWER_STATE (PD)); end if; if (Ctl1 and PWR_WELL_CTL_POWER_REQUEST (PD)) /= 0 then Unset_Mask (PWR_WELL_CTL_BIOS, PWR_WELL_CTL_POWER_REQUEST (PD)); end if; if (Ctl2 and PWR_WELL_CTL_POWER_REQUEST (PD)) /= 0 then Unset_Mask (PWR_WELL_CTL_DRIVER, PWR_WELL_CTL_POWER_REQUEST (PD)); end if; end PW_Off; procedure PW_On (PD : Power_Well) with Pre => True is Ctl1, Ctl2, Ctl3, Ctl4 : Word32; begin pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity)); Read (PWR_WELL_CTL_BIOS, Ctl1); Read (PWR_WELL_CTL_DRIVER, Ctl2); Read (PWR_WELL_CTL_KVMR, Ctl3); Read (PWR_WELL_CTL_DEBUG, Ctl4); pragma Debug (Posting_Read (PWR_WELL_CTL5)); -- Result for debugging only pragma Debug (Posting_Read (PWR_WELL_CTL6)); -- Result for debugging only if ((Ctl1 or Ctl2 or Ctl3 or Ctl4) and PWR_WELL_CTL_POWER_REQUEST (PD)) = 0 then Wait_Unset_Mask (PWR_WELL_CTL_DRIVER, PWR_WELL_CTL_POWER_STATE (PD)); end if; if (Ctl2 and PWR_WELL_CTL_POWER_REQUEST (PD)) = 0 then Set_Mask (PWR_WELL_CTL_DRIVER, PWR_WELL_CTL_POWER_REQUEST (PD)); Wait_Set_Mask (PWR_WELL_CTL_DRIVER, PWR_WELL_CTL_POWER_STATE (PD)); Wait_Set_Mask (FUSE_STATUS, FUSE_STATUS_PGx_DIST_STATUS (PD)); end if; end PW_On; procedure PD_On (PD : Power_Domain) is begin if PD in Power_Well then PW_On (PD); else DDI_Phy.Power_On (Phy (PD)); end if; end PD_On; procedure PD_Off (PD : Power_Domain) is begin if PD in Power_Well then PW_Off (PD); else DDI_Phy.Power_Off (Phy (PD)); end if; end PD_Off; function Need_PD (PD : Dynamic_Domain; Configs : Pipe_Configs) return Boolean is begin return (case PD is when DDI_A => Configs (Primary).Port = Internal or Configs (Secondary).Port = Internal or Configs (Tertiary).Port = Internal, when DDI_BC => Configs (Primary).Port = HDMI1 or Configs (Primary).Port = DP1 or Configs (Secondary).Port = HDMI1 or Configs (Secondary).Port = DP1 or Configs (Tertiary).Port = HDMI1 or Configs (Tertiary).Port = DP1 or Configs (Primary).Port = HDMI2 or Configs (Primary).Port = DP2 or Configs (Secondary).Port = HDMI2 or Configs (Secondary).Port = DP2 or Configs (Tertiary).Port = HDMI2 or Configs (Tertiary).Port = DP2, when PW2 => (Configs (Primary).Port /= Disabled and Configs (Primary).Port /= Internal) or Configs (Secondary).Port /= Disabled or Configs (Tertiary).Port /= Disabled); end Need_PD; procedure Power_Set_To (Configs : Pipe_Configs) is begin for PD in reverse Dynamic_Domain loop if not Need_PD (PD, Configs) then PD_Off (PD); end if; end loop; for PD in Dynamic_Domain loop if Need_PD (PD, Configs) then PD_On (PD); end if; end loop; end Power_Set_To; procedure Power_Up (Old_Configs, New_Configs : Pipe_Configs) is begin for PD in Dynamic_Domain loop if not Need_PD (PD, Old_Configs) and Need_PD (PD, New_Configs) then PD_On (PD); end if; end loop; end Power_Up; procedure Power_Down (Old_Configs, Tmp_Configs, New_Configs : Pipe_Configs) is begin for PD in reverse Dynamic_Domain loop if (Need_PD (PD, Old_Configs) or Need_PD (PD, Tmp_Configs)) and not Need_PD (PD, New_Configs) then PD_Off (PD); end if; end loop; end Power_Down; ---------------------------------------------------------------------------- CDClk_Ref : constant := 19_200_000; procedure Set_CDClk (Freq : Frequency_Type) with Pre => Freq = CDClk_Ref or Freq = 144_000_000 or Freq = 288_000_000 or Freq = 384_000_000 or Freq = 576_000_000 or Freq = 624_000_000 is VCO : constant Int64 := CDClk_Ref * (if Freq = CDClk_Ref then 0 elsif Freq = 624_000_000 then 65 else 60); CDCLK_CD2X_Div_Sel : constant Word32 := (case VCO / Freq is -- CDClk = VCO / 2 / Div when 2 => CDCLK_CD2X_DIV_SEL_1, when 3 => CDCLK_CD2X_DIV_SEL_1_5, when 4 => CDCLK_CD2X_DIV_SEL_2, when 8 => CDCLK_CD2X_DIV_SEL_4, when others => CDCLK_CD2X_DIV_SEL_1); -- for CDClk = CDClk_Ref CDCLK_CD2X_SSA_Precharge : constant Word32 := (if Freq >= 500_000_000 then CDCLK_CD2X_SSA_PRECHARGE_ENABLE else 0); begin Power_And_Clocks_Haswell.GT_Mailbox_Write (MBox => BXT_PCODE_CDCLK_CONTROL, Value => BXT_CDCLK_PREPARE_FOR_CHANGE); Write (Register => BXT_DE_PLL_ENABLE, Value => 16#0000_0000#); Wait_Unset_Mask (Register => BXT_DE_PLL_ENABLE, Mask => BXT_DE_PLL_PLL_LOCK, TOut_MS => 1); -- 200us Unset_And_Set_Mask (Register => BXT_DE_PLL_CTL, Mask_Unset => BXT_DE_PLL_RATIO_MASK, Mask_Set => Word32 (VCO / CDClk_Ref)); Write (Register => BXT_DE_PLL_ENABLE, Value => BXT_DE_PLL_PLL_ENABLE); Wait_Set_Mask (Register => BXT_DE_PLL_ENABLE, Mask => BXT_DE_PLL_PLL_LOCK, TOut_MS => 1); -- 200us Write (Register => CDCLK_CTL, Value => CDCLK_CD2X_Div_Sel or CDCLK_CD2X_PIPE_NONE or CDCLK_CD2X_SSA_Precharge or CDCLK_CTL_CD_FREQ_DECIMAL (Freq)); Power_And_Clocks_Haswell.GT_Mailbox_Write (MBox => BXT_PCODE_CDCLK_CONTROL, Value => Word32 ((Freq + (25_000_000 - 1)) / 25_000_000)); end Set_CDClk; ---------------------------------------------------------------------------- procedure Pre_All_Off is begin pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity)); Power_And_Clocks_Haswell.PSR_Off; end Pre_All_Off; procedure Post_All_Off is begin pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity)); for PD in reverse Dynamic_Domain loop PD_Off (PD); end loop; Unset_Mask (DBUF_CTL, DBUF_CTL_DBUF_POWER_REQUEST); Wait_Unset_Mask (DBUF_CTL, DBUF_CTL_DBUF_POWER_STATE); -- Linux' i915 never keeps the PLL disabled but runs it -- at a "ratio" of 0 with CDClk at its reference clock. Set_CDClk (CDClk_Ref); PW_Off (PW1); end Post_All_Off; procedure Initialize is begin pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity)); -- no PCH for Broxton Unset_Mask (NDE_RSTWRN_OPT, NDE_RSTWRN_OPT_RST_PCH_Handshake_En); Wait_Set_Mask (FUSE_STATUS, FUSE_STATUS_PG0_DIST_STATUS); PW_On (PW1); Set_CDClk (Config.Default_CDClk_Freq); Set_Mask (DBUF_CTL, DBUF_CTL_DBUF_POWER_REQUEST); Wait_Set_Mask (DBUF_CTL, DBUF_CTL_DBUF_POWER_STATE); Config.Raw_Clock := Config.Default_RawClk_Freq; end Initialize; end HW.GFX.GMA.Power_And_Clocks;
-- Test QR least squares equation solving real valued *square* matrices. with Ada.Numerics.Generic_elementary_functions; with Givens_QR; with Test_Matrices; With Text_IO; use Text_IO; procedure givens_qr_tst_2 is type Real is digits 15; subtype Index is Integer range 1..191; Start_Index : constant Index := Index'First + 0; Max_Index : constant Index := Index'Last - 0; subtype Row_Index is Index; subtype Col_Index is Index; Starting_Row : constant Row_Index := Start_Index; Starting_Col : constant Col_Index := Start_Index; Final_Row : constant Row_Index := Max_Index; Final_Col : constant Col_Index := Max_Index; type Matrix is array(Row_Index, Col_Index) of Real; type Matrix_inv is array(Col_Index, Row_Index) of Real; -- For inverses of A : Matrix; has shape of A_transpose. --pragma Convention (Fortran, Matrix); --No! This QR prefers Ada convention. package math is new Ada.Numerics.Generic_Elementary_Functions (Real); use math; package QR is new Givens_QR (Real => Real, R_Index => Index, C_Index => Index, A_Matrix => Matrix); use QR; -- QR exports Row_Vector and Col_Vector package Make_Square_Matrix is new Test_Matrices (Real, Index, Matrix); use Make_Square_Matrix; package rio is new Float_IO(Real); use rio; --subtype Longer_Real is Real; -- general case, and for best speed --type Longer_Real is digits 18; -- 18 ok on intel, rarely useful Min_Real :constant Real := 2.0 ** (Real'Machine_Emin/2 + Real'Machine_Emin/4); Zero : constant Real := +0.0; One : constant Real := +1.0; Two : constant Real := +2.0; -- Used by Frobenius_Norm and by Get_Err in reassembled A -------------------- -- Frobenius_Norm -- -------------------- function Frobenius_Norm (A : in Matrix) --Final_Row : in Index; --Final_Col : in Index; --Starting_Row : in Index; --Starting_Col : in Index) return Real is Max_A_Val : Real := Zero; Sum, Scaling, tmp : Real := Zero; begin Max_A_Val := Zero; for Row in Starting_Row .. Final_Row loop for Col in Starting_Col .. Final_Col loop if Max_A_Val < Abs A(Row, Col) then Max_A_Val := Abs A(Row, Col); end if; end loop; end loop; Max_A_Val := Max_A_Val + Two ** (Real'Machine_Emin + 4); Scaling := One / Max_A_Val; Sum := Zero; for Row in Starting_Row .. Final_Row loop for Col in Starting_Col .. Final_Col loop tmp := Scaling * A(Row, Col); Sum := Sum + tmp * tmp; end loop; end loop; return Sqrt (Sum) * Max_A_Val; end Frobenius_Norm; ------------ -- Invert -- ------------ -- Get Inverse of the Matrix: procedure Get_Inverse (R : in Matrix; Q : in Q_Matrix; Scale : in Col_Vector; Permute : in Permutation; A_inverse : out Matrix_inv) -- shape is A_transpose is Solution_Row_Vector : Row_Vector; -- X Unit_Col_Vector : Col_Vector := (others => 0.0); -- B -- We are going to solve for X in A*X = B Final_Row : Row_Index renames Q.Final_Row; Final_Col : Col_Index renames Q.Final_Col; Starting_Row : Row_Index renames Q.Starting_Row; Starting_Col : Col_Index renames Q.Starting_Col; begin A_inverse := (others => (others => Zero)); --new_line; --for i in Starting_Row_Col..Max_Row_Col loop --put(R(i,i)); --end loop; for i in Starting_Row .. Final_Row loop if i > Starting_Row then Unit_Col_Vector(i-1) := 0.0; end if; Unit_Col_Vector(i) := 1.0; -- Make all possible unit Col vectors: (Final_Row-Starting_Row+1) of them QR_Solve (X => Solution_Row_Vector, B => Unit_Col_Vector, R => R, Q => Q, Row_Scalings => Scale, Col_Permutation => Permute); -- Solve equ. A*Solution_Row_Vector = Unit_Col_Vector (for Solution_Row...). -- Q contains the Starting_Row, Final_Row, Starting_Col, etc. for j in Starting_Col .. Final_Col loop A_Inverse (j,i) := Solution_Row_Vector(j); end loop; -- All vectors you multiply by A must be Row_Vectors, -- So the cols of A_inv are Row_Vectors. end loop; end Get_Inverse; procedure Get_Err_in_Least_Squares_A (A : in Matrix; R : in Matrix; Q : in Q_Matrix; Scale : in Col_Vector; Permute : in Permutation; Err_in_Least_Squ_A : out Real; Condition_Number_of_Least_Squ_A : out Real; Condition_Number_of_A : out Real) is Max_Diag_Val_of_R : constant Real := Abs R(Starting_Col, Starting_Row); Min_Allowed_Diag_Val_of_R : constant Real := Max_Diag_Val_of_R * Default_Singularity_Cutoff; Min_Diag_Val_of_Least_Squ_R : Real; Least_Squares_Truncated_Final_Row : Row_Index := Final_Row; -- essential init Product_Vector, Col_of_R : Col_Vector := (others => Zero); Row : Row_Index; Err_Matrix : Matrix := (others => (others => Zero)); Final_Row : Row_Index renames Q.Final_Row; Final_Col : Col_Index renames Q.Final_Col; Starting_Row : Row_Index renames Q.Starting_Row; Starting_Col : Col_Index renames Q.Starting_Col; begin -- The Columns of R have been permuted; unpermute before comparison of A with Q*R -- The Columns of R have been scaled. Before comparison of A with Q*R -- Must unscale each col of R by multiplying them with 1/Scale(Row). Row := Starting_Row; Find_Truncated_Final_Row: for Col in Starting_Col .. Final_Col loop Min_Diag_Val_of_Least_Squ_R := Abs R(Row, Col); if Min_Diag_Val_of_Least_Squ_R < Min_Allowed_Diag_Val_of_R then Least_Squares_Truncated_Final_Row := Row - 1; Min_Diag_Val_of_Least_Squ_R := Abs R(Row-1, Col-1); exit Find_Truncated_Final_Row; end if; if Row < Final_Row then Row := Row + 1; end if; end loop Find_Truncated_Final_Row; for Col in Starting_Col .. Final_Col loop Col_of_R := (others => Zero); for Row in Starting_Row .. Least_Squares_Truncated_Final_Row loop Col_of_R(Row) := R(Row, Col); end loop; Product_Vector := Q_x_Col_Vector (Q, Col_of_R); for Row in Starting_Row .. Final_Row loop Err_Matrix(Row, Col) := Abs (A(Row, Permute(Col)) - --Product_Vector(Row) / (Scale(Permute(Col)) + Min_Real)); Product_Vector(Row) / (Scale(Row) + Min_Real)); end loop; end loop; -- Froebenius norm fractional error = ||Err_Matrix|| / ||A|| Err_in_Least_Squ_A := Frobenius_Norm (Err_Matrix) / (Frobenius_Norm (A) + Min_Real); Condition_Number_of_Least_Squ_A := Max_Diag_Val_of_R / (Min_Diag_Val_of_Least_Squ_R + Min_Real); Condition_Number_of_A := Max_Diag_Val_of_R / (Abs R(Final_Row, Final_Col) + Min_Real); end Get_Err_in_Least_Squares_A; ----------- -- Pause -- ----------- procedure Pause (s0,s1,s2,s3,s4,s5,s6,s7,s8,s9 : String := "") is Continue : Character := ' '; begin new_line; if S0 /= "" then put_line (S0); end if; if S1 /= "" then put_line (S1); end if; if S2 /= "" then put_line (S2); end if; if S3 /= "" then put_line (S3); end if; if S4 /= "" then put_line (S4); end if; if S5 /= "" then put_line (S5); end if; if S6 /= "" then put_line (S6); end if; if S7 /= "" then put_line (S7); end if; if S8 /= "" then put_line (S8); end if; if S9 /= "" then put_line (S9); end if; new_line; begin put ("Type a character to continue: "); get_immediate (Continue); exception when others => null; end; end pause; ------------------------- -- Print_Err_in_LSQ_A -- ------------------------- procedure Print_Err_in_LSQ_A (Chosen_Matrix : Matrix_id) is A_inv : Matrix_inv; A, R : Matrix; Q : Q_Matrix; Scale : Col_Vector; Permute : Permutation; Err_in_Least_Squ_A, Condition_Number_of_Least_Squ_A, Condition_Number_of_A : Real; begin Init_Matrix (A, Chosen_Matrix, Start_Index, Max_Index); R := A; -- leave A unmolested; R will be returned as upper rt. triangular QR_Decompose (A => R, -- input matrix A, but call it R. Q => Q, Row_Scalings => Scale, Col_Permutation => Permute, Final_Row => Final_Row, Final_Col => Final_Col, Starting_Row => Starting_Row, Starting_Col => Starting_Col); --new_line; --for Row in Starting_Row .. Final_Row loop --put (R(Row, Col_Index (Starting_Col + Row - Starting_Row))); --end loop; Get_Inverse (R, Q, Scale, Permute, A_inv); Get_Err_in_Least_Squares_A (A, R, Q, Scale, Permute, Err_in_Least_Squ_A, Condition_Number_of_Least_Squ_A, Condition_Number_of_A); new_line; put ("For matrix A of type "); put(Matrix_id'Image(Chosen_Matrix)); put(":"); new_line; put(" Estimate (usually low) of condition number of original A ="); put(Condition_Number_of_A); new_line; put(" Estimate (usually low) of condition number of least squares A ="); put(Condition_Number_of_Least_Squ_A); new_line; put(" How much A changed in taking least squares: ||A - A_ls||/||A|| ="); put(Err_in_Least_Squ_A); new_line; end Print_Err_in_LSQ_A; begin Pause( "The following test demonstrates least squares equation solving using QR", "decomposition of A. Least squares happens naturally in QR, because in", "obtaining A = Q*R we have written the columns of A as linear combinations", "of a complete set of orthonormal vectors (the Cols of Q). If you zero out", "one or more of the Cols of Q, and recalculate A = Q*R, then you have a", "least squares approximation of the columns of A in the basis spanned by the", "remaining cols of Q. For lack of a better term, let's call this the least", "squares A. We do this below explicitly. The idea is to show that you get a", "least squares version of A that differs from A by only 1 part in (say) 10**11,", "but has vastly better properties in equation solving (lower condition number)." ); Pause( "Below we print condition numbers of the original A, and the least squares A.", "The condition numbers are estimates obtained from the diagonal elements of R.", "They are rough estimates (you need SVD for accurate values), but are ok for", "the present demonstration. The condition number of the least squares A is", "that of the reduced rank matrix used in least squares equation solving.", "(And they are condition numbers of column scaled matrices, not the raw", "matrices emitted by package Matrix_Sampler. SVD uses the raw matrices.)" ); Print_Err_in_LSQ_A (Chosen_Matrix => KAHAN); Pause( "We started with an ideal case: A is nearly singular (condition number > 10**18).", "You would need 23 digit arithmetic to get solutions correct to 4 digits. The", "least squares A is well-conditioned (condition number ~ 8), and notice we", "only had to change A by 2 parts in 10**16 to get a well-conditioned matrix." ); Print_Err_in_LSQ_A (Chosen_Matrix => RANDOM_32_bit); Pause( "All the elements in Random are generated by a random num generator. Its", "condition number should be considered typical. It is not ill-conditioned,", "and it was not modified by the least squares process. Least squares fitting,", "only occurs when condition number exceeds some threshold (here about 10**11)." ); Print_Err_in_LSQ_A (Chosen_Matrix => Hilbert); Pause( "Hilbert's matrix is a worst case matrix. The condition number exceeds 10**11", "so least squares is performed. The distance between A and least squares A", "is now significant, (the maximum likely to be observed). The decrease in", "condition number is as predicted, but not as good as some other cases." ); Print_Err_in_LSQ_A (Chosen_Matrix => Pascal); Pause( "Pascal's matrix is another worst case. The condition number exceeds 10**11", "so the matrix is modified. The difference between A and the least squares A", "is now significant, (the maximum likely to be observed). The decrease in", "condition number is as predicted, but not as good as some other cases." ); Pause( "We now run through all the matrices in the test suite. Most are singular,", "ill-conditioned, badly scaled, or several of the above. The least squares", "process described above is the default, because when the matrix is singular", "(infinite condition number, or 2**231 here) then it is the only practical", "choice. Badly behaved matrices are likely to occur sporadically in most", "problem domains, but in some problem domains they are the norm." ); for Chosen_Matrix in Matrix_id loop Print_Err_in_LSQ_A (Chosen_Matrix); end loop; end;
with BMP_Fonts; with HAL.Bitmap; use HAL.Bitmap; with HAL.Framebuffer; use HAL.Framebuffer; with Inputs; use Inputs; with LCD_Std_Out; with STM32.Board; use STM32.Board; with Interfaces; use Interfaces; package body Gfx is procedure Init_Draw is begin -- Initialize LCD Display.Initialize; Display.Initialize_Layer(1, ARGB_8888); Display.Initialize_Layer(2, ARGB_8888); Display.Set_Orientation(Landscape); -- Set Background color LCD_Std_Out.Set_Font (BMP_Fonts.Font8x8); LCD_Std_Out.Current_Background_Color := Black; Clear_Layer(1); Clear_Layer(2); -- Apply color LCD_Std_Out.Clear_Screen; end Init_Draw; procedure Draw_Keyboard(Mem : Memory) is begin for Y in Layout_Array'Range(1) loop for X in Layout_Array'Range(2) loop Draw_Key(Mem, X, Y); end loop; end loop; Display.Update_Layer(1, False); end Draw_Keyboard; procedure Draw_Key(Mem : Memory; X : Integer; Y : Integer) is Nibble : Byte; begin for I in 0 .. 4 loop Nibble := Shift_Right(Mem(Word(5 * Layout(Y, X) + I)), 4); for J in 0 .. 3 loop if (Shift_Right(Nibble, 3 - J) and 1) = 1 then Draw_Key_Pixel(X * 40 + J * 3 + 16, 160 + 40 * Y + I * 3 + 12); end if; end loop; end loop; end Draw_Key; procedure Draw_Key_Pixel(X : Integer; Y : Integer) is Pt : constant Point := (X, Y); Rct : constant Rect := (Pt, 3, 3); begin Display.Hidden_Buffer(1).Set_Source(White); Display.Hidden_Buffer(1).Fill_Rect(Rct); end Draw_Key_Pixel; procedure Draw_Pixel(X : Integer; Y : Integer; Pixel : Boolean) is Color : constant Bitmap_Color := (if Pixel then White else Transparent); Pt : constant Point := (X * 5, Y * 5); Rct : constant Rect := (Pt, 5, 5); begin Display.Hidden_Buffer(2).Set_Source(Color); Display.Hidden_Buffer(2).Fill_Rect(Rct); end Draw_Pixel; procedure Clear_Layer(Layer : Integer) is begin Display.Hidden_Buffer(Layer).Set_Source(Transparent); Display.Hidden_Buffer(Layer).Fill; Display.Hidden_Buffer(Layer).Set_Source(White); end Clear_Layer; end Gfx;
with Ada.Unchecked_Deallocation; package body pointers is function New_Ptr (Base_Class : Base_Class_Accessor) return pointer is begin return pointer' (Ada.Finalization.Controlled with Pointer => Base_Class); end New_Ptr; function Deref (Ptr : pointer) return Base_Class_Accessor is begin return Ptr.Pointer; end Deref; overriding procedure Adjust (Object : in out pointer) is begin if Object.Pointer /= null then Object.Pointer.Ref_Count := Object.Pointer.Ref_Count + 1; end if; end Adjust; procedure Free is new Ada.Unchecked_Deallocation (Base_Class'Class, Base_Class_Accessor); overriding procedure Finalize (Object : in out pointer) is begin if Object.Pointer /= null then if Object.Pointer.Ref_Count > 0 then Object.Pointer.Ref_Count := Object.Pointer.Ref_Count - 1; if Object.Pointer.Ref_Count = 0 then Free (Object.Pointer); end if; end if; end if; end Finalize; function Is_Null (Ptr : pinter) return Boolean is begin return Ptr = Null_pointer; end Is_Null; end pointers;
with openGL.Camera, ada.Characters.latin_1; package openGL.Dolly -- -- A utility which moves a camera via the keyboard. -- is type Item (Camera : openGL.Camera.view) is tagged private; procedure Speed_is (Self : in out Item; Now : in Real); procedure evolve (Self : in out Item); function quit_Requested (Self : in Item) return Boolean; procedure get_last_Character (Self : in out Item; the_Character : out Character; Available : out Boolean); private type Item (Camera : openGL.Camera.view) is tagged record quit_Requested : Boolean := False; last_Character : Character := ada.Characters.Latin_1.NUL; Speed : Real := 1.0; end record; end openGL.Dolly;
package body agar.gui.widget.pixmap is use type c.int; package cbinds is function allocate (parent : widget_access_t; flags : flags_t; width : c.int; height : c.int) return pixmap_access_t; pragma import (c, allocate, "AG_PixmapNew"); function add_surface (pixmap : pixmap_access_t; surface : agar.gui.surface.surface_access_t) return c.int; pragma import (c, add_surface, "AG_PixmapAddSurface"); function add_surface_copy (pixmap : pixmap_access_t; surface : agar.gui.surface.surface_access_t) return c.int; pragma import (c, add_surface_copy, "AG_PixmapAddSurfaceCopy"); function add_surface_scaled (pixmap : pixmap_access_t; surface : agar.gui.surface.surface_access_t; width : c.int; height : c.int) return c.int; pragma import (c, add_surface_scaled, "AG_PixmapAddSurfaceScaled"); function from_surface_scaled (parent : widget_access_t; flags : flags_t; source : agar.gui.surface.surface_access_t; width : c.int; height : c.int) return pixmap_access_t; pragma import (c, from_surface_scaled, "AG_PixmapFromSurfaceScaled"); function from_bitmap (parent : widget_access_t; path : cs.chars_ptr) return pixmap_access_t; pragma import (c, from_bitmap, "AG_PixmapFromBMP"); -- function from_xcf -- (parent : widget_access_t; -- path : cs.chars_ptr) return pixmap_access_t; -- pragma import (c, from_xcf, "AG_PixmapFromXCF"); end cbinds; function allocate (parent : widget_access_t; flags : flags_t; width : positive; height : positive) return pixmap_access_t is begin return cbinds.allocate (parent => parent, flags => flags, width => c.int (width), height => c.int (height)); end allocate; function from_surface_scaled (parent : widget_access_t; flags : flags_t; source : agar.gui.surface.surface_access_t; width : positive; height : positive) return pixmap_access_t is begin return cbinds.from_surface_scaled (parent => parent, flags => flags, source => source, width => c.int (width), height => c.int (height)); end from_surface_scaled; function from_bitmap (parent : widget_access_t; path : string) return pixmap_access_t is c_path : aliased c.char_array := c.to_c (path); begin return cbinds.from_bitmap (parent => parent, path => cs.to_chars_ptr (c_path'unchecked_access)); end from_bitmap; -- function from_xcf -- (parent : widget_access_t; -- path : string) return pixmap_access_t -- is -- c_path : aliased c.char_array := c.to_c (path); -- begin -- return cbinds.from_xcf -- (parent => parent, -- path => cs.to_chars_ptr (c_path'unchecked_access)); -- end from_xcf; function add_surface (pixmap : pixmap_access_t; surface : agar.gui.surface.surface_access_t) return boolean is begin return cbinds.add_surface (pixmap => pixmap, surface => surface) = 0; end add_surface; function add_surface_copy (pixmap : pixmap_access_t; surface : agar.gui.surface.surface_access_t) return boolean is begin return cbinds.add_surface_copy (pixmap => pixmap, surface => surface) = 0; end add_surface_copy; function add_surface_scaled (pixmap : pixmap_access_t; surface : agar.gui.surface.surface_access_t; width : positive; height : positive) return boolean is begin return cbinds.add_surface_scaled (pixmap => pixmap, surface => surface, width => c.int (width), height => c.int (height)) = 0; end add_surface_scaled; function widget (pixmap : pixmap_access_t) return widget_access_t is begin return pixmap.widget'access; end widget; end agar.gui.widget.pixmap;
package body Bluetooth_Low_Energy is --------------- -- Make_UUID -- --------------- function Make_UUID (UUID : UInt16) return BLE_UUID is begin return (Kind => UUID_16bits, UUID_16 => UUID); end Make_UUID; --------------- -- Make_UUID -- --------------- function Make_UUID (UUID : UInt32) return BLE_UUID is begin return (Kind => UUID_32bits, UUID_32 => UUID); end Make_UUID; --------------- -- Make_UUID -- --------------- function Make_UUID (UUID : BLE_16UInt8s_UUID) return BLE_UUID is begin return (Kind => UUID_16UInt8s, UUID_16_UInt8s => UUID); end Make_UUID; end Bluetooth_Low_Energy;
package Multidimensional_Array is subtype WorkWeek is Natural range 1 .. 5; subtype WorkHours is Natural range 1 .. 8; type FullTime is array(WorkWeek, WorkHours) of Boolean; type PartTime is array(WorkWeek range<>, WorkHours range<>) of Boolean; type Afternoons is new PartTime(1..5, 5..8); procedure test(f: FullTime; p : PartTime; a : Afternoons); end Multidimensional_Array;
with Libadalang.Analysis; with Libadalang.Rewriting; with Libadalang.Common; package Offmt_Lib.Rewrite is package LAL renames Libadalang.Analysis; package LALCO renames Libadalang.Common; package LALRW renames Libadalang.Rewriting; procedure Rewrite_Log_Call (RH : LALRW.Rewriting_Handle; Node : LAL.Call_Stmt'Class; T : Trace); end Offmt_Lib.Rewrite;
-- Swagger Petstore -- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters. -- ------------ EDIT NOTE ------------ -- This file was generated with swagger-codegen. You can modify it to implement -- the server. After you modify this file, you should add the following line -- to the .swagger-codegen-ignore file: -- -- src/samples-petstore.ads -- -- Then, you can drop this edit note comment. -- ------------ EDIT NOTE ------------ package Samples is end Samples;
pragma License (Unrestricted); package Interfaces is pragma Pure; type Integer_8 is range -(2 ** 7) .. 2 ** 7 - 1; -- 2's complement for Integer_8'Size use 8; type Integer_16 is range -(2 ** 15) .. 2 ** 15 - 1; for Integer_16'Size use 16; type Integer_32 is range -(2 ** 31) .. 2 ** 31 - 1; for Integer_32'Size use 32; type Integer_64 is range -(2 ** 63) .. 2 ** 63 - 1; for Integer_64'Size use 64; type Unsigned_8 is mod 2 ** 8; for Unsigned_8'Size use 8; type Unsigned_16 is mod 2 ** 16; for Unsigned_16'Size use 16; type Unsigned_32 is mod 2 ** 32; for Unsigned_32'Size use 32; type Unsigned_64 is mod 2 ** 64; for Unsigned_64'Size use 64; -- function Shift_Left (Value : Unsigned_n; Amount : Natural) -- return Unsigned_n; -- function Shift_Right (Value : Unsigned_n; Amount : Natural) -- return Unsigned_n; -- function Shift_Right_Arithmetic (Value : Unsigned_n; Amount : Natural) -- return Unsigned_n; -- function Rotate_Left (Value : Unsigned_n; Amount : Natural) -- return Unsigned_n; -- function Rotate_Right (Value : Unsigned_n; Amount : Natural) -- return Unsigned_n; -- ... pragma Provide_Shift_Operators (Unsigned_8); pragma Provide_Shift_Operators (Unsigned_16); pragma Provide_Shift_Operators (Unsigned_32); pragma Provide_Shift_Operators (Unsigned_64); end Interfaces;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2012 Felix Krause <contact@flyx.org> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with GL.Algebra; with Orka; package GL.Types is pragma Pure; -- These are the types you can and should use with OpenGL functions -- (particularly when dealing with buffer objects). -- Types that are only used internally, but may be needed when interfacing -- with OpenGL-related library APIs can be found in GL.Low_Level. subtype UInt64 is Orka.Unsigned_64; -- Signed integer types type Byte is new C.signed_char; subtype Short is Orka.Integer_16; subtype Int is Orka.Integer_32; subtype Long is Orka.Integer_64; subtype Size is Int range 0 .. Int'Last; subtype Long_Size is Long range 0 .. Long'Last; subtype Positive_Size is Size range 1 .. Size'Last; -- Unsigned integer types type UByte is new C.unsigned_char; type UShort is new C.unsigned_short; type UInt is new C.unsigned; -- Floating point types ("Single" is used to avoid conflicts with Float) subtype Half is Orka.Float_16; subtype Single is Orka.Float_32; subtype Double is Orka.Float_64; subtype Normalized_Single is Single range 0.0 .. 1.0; -- Array types type Byte_Array is array (Size range <>) of aliased Byte; type Short_Array is array (Size range <>) of aliased Short; type Int_Array is array (Size range <>) of aliased Int; type UByte_Array is array (Size range <>) of aliased UByte; type UShort_Array is array (Size range <>) of aliased UShort; type UInt_Array is array (Size range <>) of aliased UInt; type Half_Array is array (Size range <>) of aliased Half; type Single_Array is array (Size range <>) of aliased Single; type Double_Array is array (Size range <>) of aliased Double; type Size_Array is array (Size range <>) of aliased Size; pragma Convention (C, Byte_Array); pragma Convention (C, Short_Array); pragma Convention (C, Int_Array); pragma Convention (C, UByte_Array); pragma Convention (C, UShort_Array); pragma Convention (C, UInt_Array); pragma Convention (C, Half_Array); pragma Convention (C, Single_Array); pragma Convention (C, Double_Array); pragma Convention (C, Size_Array); -- Type descriptors type Numeric_Type is (Byte_Type, UByte_Type, Short_Type, UShort_Type, Int_Type, UInt_Type, Single_Type, Double_Type, Half_Type); type Index_Type is (UShort_Type, UInt_Type); type Connection_Mode is (Points, Lines, Line_Strip, Triangles, Triangle_Strip, Lines_Adjacency, Line_Strip_Adjacency, Triangles_Adjacency, Triangle_Strip_Adjacency, Patches); type Compare_Function is (Never, Less, Equal, LEqual, Greater, Not_Equal, GEqual, Always); subtype Component_Count is Int range 1 .. 4; -- Counts the number of components for vertex attributes subtype Byte_Count is Int range 1 .. 4 with Static_Predicate => Byte_Count in 1 | 2 | 4; -- Number of bytes of a component package Bytes is new GL.Algebra (Element_Type => Byte, Index_Type => Size); package Shorts is new GL.Algebra (Element_Type => Short, Index_Type => Size); package Ints is new GL.Algebra (Element_Type => Int, Index_Type => Size); package Longs is new GL.Algebra (Element_Type => Long, Index_Type => Size); package UBytes is new GL.Algebra (Element_Type => UByte, Index_Type => Size); package UShorts is new GL.Algebra (Element_Type => UShort, Index_Type => Size); package UInts is new GL.Algebra (Element_Type => UInt, Index_Type => Size); package Singles is new GL.Algebra (Element_Type => Single, Index_Type => Size); package Doubles is new GL.Algebra (Element_Type => Double, Index_Type => Size); private for Numeric_Type use (Byte_Type => 16#1400#, UByte_Type => 16#1401#, Short_Type => 16#1402#, UShort_Type => 16#1403#, Int_Type => 16#1404#, UInt_Type => 16#1405#, Single_Type => 16#1406#, Double_Type => 16#140A#, Half_Type => 16#140B#); for Numeric_Type'Size use UInt'Size; for Index_Type use (UShort_Type => 16#1403#, UInt_Type => 16#1405#); for Index_Type'Size use UInt'Size; for Connection_Mode use (Points => 16#0000#, Lines => 16#0001#, Line_Strip => 16#0003#, Triangles => 16#0004#, Triangle_Strip => 16#0005#, Lines_Adjacency => 16#000A#, Line_Strip_Adjacency => 16#000B#, Triangles_Adjacency => 16#000C#, Triangle_Strip_Adjacency => 16#000D#, Patches => 16#000E#); for Connection_Mode'Size use UInt'Size; for Compare_Function use (Never => 16#0200#, Less => 16#0201#, Equal => 16#0202#, LEqual => 16#0203#, Greater => 16#0204#, Not_Equal => 16#0205#, GEqual => 16#0206#, Always => 16#0207#); for Compare_Function'Size use UInt'Size; end GL.Types;
-- -- 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. -- -- pragma Restrictions (No_Elaboration_Code); with ada.unchecked_conversion; package m4.cpu with spark_mode => on is ------------- -- Globals -- ------------- EXC_THREAD_MODE : constant unsigned_32 := 16#FFFF_FFFD#; EXC_KERN_MODE : constant unsigned_32 := 16#FFFF_FFF9#; EXC_HANDLER_MODE : constant unsigned_32 := 16#FFFF_FFF1#; --------------- -- Registers -- --------------- -- -- CONTROL register -- type t_SPSEL is (MSP, PSP) with size => 1; for t_SPSEL use (MSP => 0, PSP => 1); type t_PRIV is (PRIVILEGED, UNPRIVILEGED) with size => 1; for t_PRIV use (PRIVILEGED => 0, UNPRIVILEGED => 1); type t_control_register is record nPRIV : t_PRIV; -- Thread mode is privileged (0), unprivileged (1) SPSEL : t_SPSEL; -- Current stack pointer end record with size => 32; for t_control_register use record nPRIV at 0 range 0 .. 0; SPSEL at 0 range 1 .. 1; end record; -- -- PSR register that aggregates (A)(I)(E)PSR registers -- type t_PSR_register is record ISR_NUMBER : unsigned_8; ICI_IT_lo : bits_6; GE : bits_4; Thumb : bit; ICI_IT_hi : bits_2; DSP_overflow : bit; -- Q Overflow : bit; -- V Carry : bit; Zero : bit; Negative : bit; end record with size => 32; for t_PSR_register use record ISR_NUMBER at 0 range 0 .. 7; ICI_IT_lo at 0 range 10 .. 15; GE at 0 range 16 .. 19; Thumb at 0 range 24 .. 24; ICI_IT_hi at 0 range 25 .. 26; DSP_overflow at 0 range 27 .. 27; Overflow at 0 range 28 .. 28; Carry at 0 range 29 .. 29; Zero at 0 range 30 .. 30; Negative at 0 range 31 .. 31; end record; function to_unsigned_32 is new ada.unchecked_conversion (t_PSR_register, unsigned_32); -- -- APSR register -- type t_APSR_register is record GE : bits_4; DSP_overflow : bit; Overflow : bit; Carry : bit; Zero : bit; Negative : bit; end record with size => 32; for t_APSR_register use record GE at 0 range 16 .. 19; DSP_overflow at 0 range 27 .. 27; Overflow at 0 range 28 .. 28; Carry at 0 range 29 .. 29; Zero at 0 range 30 .. 30; Negative at 0 range 31 .. 31; end record; function to_PSR_register is new ada.unchecked_conversion (t_APSR_register, t_PSR_register); -- -- IPSR register -- type t_IPSR_register is record ISR_NUMBER : unsigned_8; end record with size => 32; function to_PSR_register is new ada.unchecked_conversion (t_IPSR_register, t_PSR_register); -- -- EPSR register -- type t_EPSR_register is record ICI_IT_lo : bits_6; Thumb : bit; ICI_IT_hi : bits_2; end record with size => 32; for t_EPSR_register use record ICI_IT_lo at 0 range 10 .. 15; Thumb at 0 range 24 .. 24; ICI_IT_hi at 0 range 25 .. 26; end record; function to_PSR_register is new ada.unchecked_conversion (t_EPSR_register, t_PSR_register); --------------- -- Functions -- --------------- -- Enable IRQs by clearing the I-bit in the CPSR. -- (privileged mode) procedure enable_irq with inline; -- Disable IRQs by setting the I-bit in the CPSR. -- (privileged mode) procedure disable_irq with inline; -- Get the Control register. function get_control_register return t_control_register with inline; -- Set the Control register. procedure set_control_register (cr : in t_control_register) with inline; -- Get the IPSR register. function get_ipsr_register return t_IPSR_register with inline; -- Get the APSR register. function get_apsr_register return t_APSR_register with inline; -- Get the EPSR register. function get_epsr_register return t_EPSR_register with inline; -- Get the LR register function get_lr_register return unsigned_32 with inline; -- Get the process stack pointer (PSP) function get_psp_register return system_address with inline; -- Set the process stack pointer (PSP) procedure set_psp_register (addr : in system_address) with inline; -- Get the main stack pointer (MSP) function get_msp_register return system_address with inline; -- Set the main stack pointer (MSP) procedure set_msp_register (addr : system_address) with inline; -- Get the priority mask value function get_primask_register return unsigned_32 with inline; -- Set the priority mask value procedure set_primask_register (mask : in unsigned_32) with inline; end m4.cpu;
with Math_2D.Types; with Math_2D.Points; with Math_2D.Vectors; generic with package Types is new Math_2D.Types (<>); with package Vectors is new Math_2D.Vectors (Types); with package Points is new Math_2D.Points (Types => Types, Vectors => Vectors); package Math_2D.Triangles is function Area (Triangle : in Types.Triangle_t) return Types.Real_Type'Base; function Orthocenter (Triangle : in Types.Triangle_t) return Types.Point_t; function Perimeter (Triangle : in Types.Triangle_t) return Types.Real_Type'Base; function Point_Is_Inside (Triangle : in Types.Triangle_t; Point : in Types.Point_t) return Boolean; end Math_2D.Triangles;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . W I D E _ W I D E _ C H A R A C T E R S . H A N D L I N G -- -- -- -- B o d y -- -- -- -- Copyright (C) 2010-2019, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.Wide_Wide_Characters.Unicode; use Ada.Wide_Wide_Characters.Unicode; package body Ada.Wide_Wide_Characters.Handling is --------------------- -- Is_Alphanumeric -- --------------------- function Is_Alphanumeric (Item : Wide_Wide_Character) return Boolean is begin return Is_Letter (Item) or else Is_Digit (Item); end Is_Alphanumeric; ---------------- -- Is_Control -- ---------------- function Is_Control (Item : Wide_Wide_Character) return Boolean is begin return Get_Category (Item) = Cc; end Is_Control; -------------- -- Is_Digit -- -------------- function Is_Digit (Item : Wide_Wide_Character) return Boolean renames Ada.Wide_Wide_Characters.Unicode.Is_Digit; ---------------- -- Is_Graphic -- ---------------- function Is_Graphic (Item : Wide_Wide_Character) return Boolean is begin return not Is_Non_Graphic (Item); end Is_Graphic; -------------------------- -- Is_Hexadecimal_Digit -- -------------------------- function Is_Hexadecimal_Digit (Item : Wide_Wide_Character) return Boolean is begin return Is_Digit (Item) or else Item in 'A' .. 'F' or else Item in 'a' .. 'f'; end Is_Hexadecimal_Digit; --------------- -- Is_Letter -- --------------- function Is_Letter (Item : Wide_Wide_Character) return Boolean renames Ada.Wide_Wide_Characters.Unicode.Is_Letter; ------------------------ -- Is_Line_Terminator -- ------------------------ function Is_Line_Terminator (Item : Wide_Wide_Character) return Boolean renames Ada.Wide_Wide_Characters.Unicode.Is_Line_Terminator; -------------- -- Is_Lower -- -------------- function Is_Lower (Item : Wide_Wide_Character) return Boolean is begin return Get_Category (Item) = Ll; end Is_Lower; ------------- -- Is_Mark -- ------------- function Is_Mark (Item : Wide_Wide_Character) return Boolean renames Ada.Wide_Wide_Characters.Unicode.Is_Mark; --------------------- -- Is_Other_Format -- --------------------- function Is_Other_Format (Item : Wide_Wide_Character) return Boolean renames Ada.Wide_Wide_Characters.Unicode.Is_Other; ------------------------------ -- Is_Punctuation_Connector -- ------------------------------ function Is_Punctuation_Connector (Item : Wide_Wide_Character) return Boolean renames Ada.Wide_Wide_Characters.Unicode.Is_Punctuation; -------------- -- Is_Space -- -------------- function Is_Space (Item : Wide_Wide_Character) return Boolean renames Ada.Wide_Wide_Characters.Unicode.Is_Space; ---------------- -- Is_Special -- ---------------- function Is_Special (Item : Wide_Wide_Character) return Boolean is begin return Is_Graphic (Item) and then not Is_Alphanumeric (Item); end Is_Special; -------------- -- Is_Upper -- -------------- function Is_Upper (Item : Wide_Wide_Character) return Boolean is begin return Get_Category (Item) = Lu; end Is_Upper; -------------- -- To_Lower -- -------------- function To_Lower (Item : Wide_Wide_Character) return Wide_Wide_Character renames Ada.Wide_Wide_Characters.Unicode.To_Lower_Case; function To_Lower (Item : Wide_Wide_String) return Wide_Wide_String is Result : Wide_Wide_String (Item'Range); begin for J in Result'Range loop Result (J) := To_Lower (Item (J)); end loop; return Result; end To_Lower; -------------- -- To_Upper -- -------------- function To_Upper (Item : Wide_Wide_Character) return Wide_Wide_Character renames Ada.Wide_Wide_Characters.Unicode.To_Upper_Case; function To_Upper (Item : Wide_Wide_String) return Wide_Wide_String is Result : Wide_Wide_String (Item'Range); begin for J in Result'Range loop Result (J) := To_Upper (Item (J)); end loop; return Result; end To_Upper; end Ada.Wide_Wide_Characters.Handling;
with Ada.Containers.Indefinite_Vectors; package body Mode is -- map Count to Elements package Count_Vectors is new Ada.Containers.Indefinite_Vectors (Element_Type => Element_Array, Index_Type => Positive); procedure Add (To : in out Count_Vectors.Vector; Item : Element_Type) is use type Count_Vectors.Cursor; Position : Count_Vectors.Cursor := To.First; Found : Boolean := False; begin while not Found and then Position /= Count_Vectors.No_Element loop declare Elements : Element_Array := Count_Vectors.Element (Position); begin for I in Elements'Range loop if Elements (I) = Item then Found := True; end if; end loop; end; if not Found then Position := Count_Vectors.Next (Position); end if; end loop; if Position /= Count_Vectors.No_Element then -- element found, remove it and insert to next count declare New_Position : Count_Vectors.Cursor := Count_Vectors.Next (Position); begin -- remove from old position declare Old_Elements : Element_Array := Count_Vectors.Element (Position); New_Elements : Element_Array (1 .. Old_Elements'Length - 1); New_Index : Positive := New_Elements'First; begin for I in Old_Elements'Range loop if Old_Elements (I) /= Item then New_Elements (New_Index) := Old_Elements (I); New_Index := New_Index + 1; end if; end loop; To.Replace_Element (Position, New_Elements); end; -- new position not already there? if New_Position = Count_Vectors.No_Element then declare New_Array : Element_Array (1 .. 1) := (1 => Item); begin To.Append (New_Array); end; else -- add to new position declare Old_Elements : Element_Array := Count_Vectors.Element (New_Position); New_Elements : Element_Array (1 .. Old_Elements'Length + 1); begin New_Elements (1 .. Old_Elements'Length) := Old_Elements; New_Elements (New_Elements'Last) := Item; To.Replace_Element (New_Position, New_Elements); end; end if; end; else -- element not found, add to count 1 Position := To.First; if Position = Count_Vectors.No_Element then declare New_Array : Element_Array (1 .. 1) := (1 => Item); begin To.Append (New_Array); end; else declare Old_Elements : Element_Array := Count_Vectors.Element (Position); New_Elements : Element_Array (1 .. Old_Elements'Length + 1); begin New_Elements (1 .. Old_Elements'Length) := Old_Elements; New_Elements (New_Elements'Last) := Item; To.Replace_Element (Position, New_Elements); end; end if; end if; end Add; function Get_Mode (Set : Element_Array) return Element_Array is Counts : Count_Vectors.Vector; begin for I in Set'Range loop Add (Counts, Set (I)); end loop; return Counts.Last_Element; end Get_Mode; end Mode;
-- SPDX-License-Identifier: MIT -- -- Copyright (c) 2016 - 2018 Gautier de Montmollin -- SWITZERLAND -- -- The copyright holder is only the maintainer of the Ada version; -- authors of the C code and those of the algorithm are cited below. -- -- 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. -- Length_limited_Huffman_code_lengths -- ----------------------------------- -- -- This algorithm builds optimal Huffman codes for a given alphabet -- and occurrence counts (frequencies) of this alphabet. These occurrences -- are supposed to have been counted in a message to be sent in a -- compressed form using the Huffman codes. As output, only the bit lengths -- of the Huffman codes are given; the Huffman codes themselves are built -- with these bit lengths when the message actually needs to be sent. -- -- Pure Ada 95+ code, 100% portable: OS-, CPU- and compiler- independent. -- Author: lode.vandevenne [*] gmail [*] com (Lode Vandevenne) -- Author: jyrki.alakuijala [*] gmail [*] com (Jyrki Alakuijala) -- -- Bounded package merge algorithm, based on the paper -- "A Fast and Space-Economical Algorithm for Length-Limited Coding -- Jyrki Katajainen, Alistair Moffat, Andrew Turpin". -- -- Translated by G. de Montmollin to Ada from katajainen.c (Zopfli project), 7-Feb-2016 -- Translation notes in procedure's body. private generic type Alphabet is (<>); -- Any discrete type -- Count_Type is an integer type large enough for counting -- and indexing. See body for actual bounds. type Count_Type is range <>; type Count_Array is array (Alphabet) of Count_Type; type Length_Array is array (Alphabet) of Natural; Max_Bits : Positive; -- Length limit in Huffman codes procedure DCF.Length_Limited_Huffman_Code_Lengths (Frequencies : in Count_Array; Bit_Lengths : out Length_Array); pragma Preelaborate (DCF.Length_Limited_Huffman_Code_Lengths);
-- File: Hello.adb -- Name: Andrew Albanese -- Date: 1/20/2018 with Ada.Text_IO; use Ada.Text_IO; PROCEDURE Hello IS BEGIN Put("Hi"); end Hello;
with GID, ada.Calendar; package body openGL.Images is function fetch_Image (Stream : in Ada.Streams.Stream_IO.Stream_Access; try_TGA : in Boolean) return openGL.Image is the_GID_Image : GID.Image_descriptor; next_Frame : Ada.Calendar.Day_Duration := 0.0; begin GID.Load_image_header (the_GID_Image, Stream.all, try_TGA); declare Image_Width : constant Positive := GID.Pixel_Width (the_GID_Image); Image_Height : constant Positive := GID.Pixel_height (the_GID_Image); the_Image : openGL.Image (1 .. Index_t (Image_Height), 1 .. Index_t (Image_Width)); procedure Load_raw_image is subtype Primary_color_range is GL.glUByte; Row, Col : Index_t; procedure set_X_Y (x, y : Natural) is begin Col := Index_t (X + 1); Row := Index_t (Y + 1); end set_X_Y; procedure put_Pixel (Red, Green, Blue : primary_Color_Range; Alpha : primary_Color_Range) is use type GL.glUByte, Real; pragma Warnings (Off, Alpha); -- Alpha is just ignored. begin the_Image (Row, Col) := (Red, Green, Blue); if Col = Index_t (Image_Width) then -- GID requires us to look to next pixel on the right for next time. Row := Row + 1; Col := 1; else Col := Col + 1; end if; end put_Pixel; procedure Feedback (Percents : Natural) is null; procedure Load_image is new GID.load_Image_contents (primary_Color_Range, set_X_Y, put_Pixel, Feedback, GID.fast); begin load_Image (the_GID_Image, next_Frame); end load_raw_Image; begin load_raw_Image; return the_Image; end; end fetch_Image; end openGL.Images;
with Ada.Containers.Vectors; package EU_Projects.Identifiers.Full is use type Ada.Containers.Count_Type; type Segment_Index is range 1 .. Integer'Last; type Full_ID is private; Empty_Path : constant Full_ID; function "=" (X, Y : Full_ID) return Boolean; function "<" (X, Y : Full_ID) return Boolean; -- A valid path has a syntax similar to an identifier, with the -- following exceptions -- -- * It can have also dots '.' -- * It cannot end with a dot -- * After a dot a letter must follow function Is_Valid_Path (X : String) return Boolean is ( (X'Length > 0) and then (Is_Letter (X (X'First)) and Is_Alphanumeric (X (X'Last))) and then (for all I in X'Range => (Is_Alphanumeric (X (I)) or else (X (I) = '_' and then Is_Alphanumeric (X (I + 1))) or else (X (I) = '.' and then Is_Letter (X (I + 1))))) -- Note : in the condition above I+1 is always well defined since -- if X(X'Last) is alphanumeric, the last two tests are cutted -- away by the "or else" after Is_Alphanumeric (X (I)), otherwise -- if X(X'Last) is not alphanumeric, the "for all" will not checked -- at all because of the preceding "and then" ); function Parse (X : String) return Full_ID with Pre => Is_Valid_Path (X); function Image (X : Full_ID) return String; function Length (Item : Full_ID) return Ada.Containers.Count_Type; function Segment (Item : Full_ID; Index : Segment_Index) return Identifier; function First (Item : Full_ID) return Identifier with Pre => Length (Item) /= 0; function Last (Item : Full_ID) return Identifier with Pre => Length (Item) /= 0; function Header (Item : Full_ID) return Full_ID with Pre => Length (Item) /= 0, Post => Length (Header'Result) = Length (Item)-1; function Trailer (Item : Full_ID) return Full_ID with Pre => Length (Item) /= 0, Post => Length (Trailer'Result) = Length (Item)-1; type Resolver_Type is limited interface; function Find (Resolver : Resolver_Type; What : Full_ID) return Boolean is abstract; function Resolve (Item : Full_ID; Prefix : Full_ID; Resolver : Resolver_Type'Class) return Full_ID; private package ID_Vectors is new Ada.Containers.Vectors (Index_Type => Segment_Index, Element_Type => Identifier); type Full_ID is record Segments : ID_Vectors.Vector; end record; Empty_Path : constant Full_ID := Full_ID'(Segments => ID_Vectors.Empty_Vector); function Length (Item : Full_ID) return Ada.Containers.Count_Type is (Item.Segments.Length); function Segment (Item : Full_ID; Index : Segment_Index) return Identifier is (Item.Segments.Element (Index)); function First (Item : Full_ID) return Identifier is (Item.Segments.First_Element); function Last (Item : Full_ID) return Identifier is (Item.Segments.Last_Element); function "=" (X, Y : Full_ID) return Boolean is (ID_Vectors."="(X.Segments, Y.Segments)); end EU_Projects.Identifiers.Full;
------------------------------------------------------------------------------ -- 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. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.Interpreter_Loop; with Natools.Static_Maps.S_Expressions.Templates.Integers; package body Natools.S_Expressions.Templates.Generic_Integers is package Commands renames Natools.Static_Maps.S_Expressions.Templates.Integers; function Create (Data : Atom) return Atom_Refs.Immutable_Reference renames Atom_Ref_Constructors.Create; procedure Insert_Image (State : in out Format; Context : in Meaningless_Type; Image : in Atom); procedure Update_Image (State : in out Format; Context : in Meaningless_Type; Name : in Atom; Arguments : in out Lockable.Descriptor'Class); procedure Update_Format (State : in out Format; Context : in Meaningless_Type; Name : in Atom; Arguments : in out Lockable.Descriptor'Class); ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Insert_Image (State : in out Format; Context : in Meaningless_Type; Image : in Atom) is pragma Unreferenced (Context); begin State.Append_Image (Image); end Insert_Image; procedure Update_Image (State : in out Format; Context : in Meaningless_Type; Name : in Atom; Arguments : in out Lockable.Descriptor'Class) is pragma Unreferenced (Context); Value : T; begin begin Value := T'Value (To_String (Name)); exception when Constraint_Error => return; end; case Arguments.Current_Event is when Events.Add_Atom => State.Set_Image (Value, Arguments.Current_Atom); when others => State.Remove_Image (Value); end case; end Update_Image; procedure Image_Interpreter is new Interpreter_Loop (Format, Meaningless_Type, Update_Image, Insert_Image); procedure Update_Format (State : in out Format; Context : in Meaningless_Type; Name : in Atom; Arguments : in out Lockable.Descriptor'Class) is pragma Unreferenced (Context); Command : constant String := To_String (Name); Event : Events.Event; begin case Commands.Main (Command) is when Commands.Error => null; when Commands.Align => case Arguments.Current_Event is when Events.Add_Atom => case Commands.To_Align_Command (To_String (Arguments.Current_Atom)) is when Commands.Unknown_Align => null; when Commands.Set_Left => State.Set_Align (Left_Aligned); when Commands.Set_Center => State.Set_Align (Centered); when Commands.Set_Right => State.Set_Align (Right_Aligned); end case; when others => null; end case; when Commands.Align_Center => State.Set_Align (Centered); when Commands.Align_Left => State.Set_Align (Left_Aligned); when Commands.Align_Right => State.Set_Align (Right_Aligned); when Commands.Base => State.Set_Symbols (Arguments); when Commands.Image_Range => Parse (State.Images, Arguments); when Commands.Images => Image_Interpreter (Arguments, State, Meaningless_Value); when Commands.Padding => case Arguments.Current_Event is when Events.Add_Atom => State.Left_Padding := Create (Arguments.Current_Atom); State.Right_Padding := State.Left_Padding; when others => return; end case; Arguments.Next (Event); case Event is when Events.Add_Atom => State.Set_Right_Padding (Arguments.Current_Atom); when others => null; end case; when Commands.Padding_Left => case Arguments.Current_Event is when Events.Add_Atom => State.Set_Left_Padding (Arguments.Current_Atom); when others => null; end case; when Commands.Padding_Right => case Arguments.Current_Event is when Events.Add_Atom => State.Set_Right_Padding (Arguments.Current_Atom); when others => null; end case; when Commands.Prefix => Parse (State.Prefix, Arguments); when Commands.Sign => case Arguments.Current_Event is when Events.Add_Atom => State.Set_Positive_Sign (Arguments.Current_Atom); when others => return; end case; Arguments.Next (Event); case Event is when Events.Add_Atom => State.Set_Negative_Sign (Arguments.Current_Atom); when others => null; end case; when Commands.Suffix => Parse (State.Suffix, Arguments); when Commands.Width => case Arguments.Current_Event is when Events.Add_Atom => declare New_Width : constant Width := Width'Value (To_String (Arguments.Current_Atom)); begin State.Set_Maximum_Width (New_Width); State.Set_Minimum_Width (New_Width); end; when others => return; end case; Arguments.Next (Event); case Event is when Events.Add_Atom => State.Set_Maximum_Width (Width'Value (To_String (Arguments.Current_Atom))); when others => return; end case; Arguments.Next (Event); case Event is when Events.Add_Atom => State.Set_Overflow_Message (Arguments.Current_Atom); when others => return; end case; when Commands.Width_Max => case Arguments.Current_Event is when Events.Add_Atom => State.Set_Maximum_Width (Width'Value (To_String (Arguments.Current_Atom))); when others => return; end case; Arguments.Next (Event); case Event is when Events.Add_Atom => State.Set_Overflow_Message (Arguments.Current_Atom); when others => return; end case; when Commands.Width_Min => case Arguments.Current_Event is when Events.Add_Atom => State.Set_Minimum_Width (Width'Value (To_String (Arguments.Current_Atom))); when others => null; end case; end case; end Update_Format; procedure Interpreter is new Interpreter_Loop (Format, Meaningless_Type, Update_Format, Insert_Image); ------------------------- -- Dynamic Atom Arrays -- ------------------------- function Create (Atom_List : in out S_Expressions.Descriptor'Class) return Atom_Array is function Current_Atom return Atom is (Atom_List.Current_Atom); New_Ref : Atom_Refs.Immutable_Reference; begin case Atom_List.Current_Event is when Events.Add_Atom => New_Ref := Atom_Refs.Create (Current_Atom'Access); Atom_List.Next; return (0 => New_Ref) & Create (Atom_List); when others => return Atom_Array'(1 .. 0 => <>); end case; end Create; function Create (Atom_List : in out S_Expressions.Descriptor'Class) return Atom_Arrays.Immutable_Reference is function Create_Array return Atom_Array is (Create (Atom_List)); begin return Atom_Arrays.Create (Create_Array'Access); end Create; function Decimal return Atom_Arrays.Immutable_Reference is function Create return Atom_Array is ((0 => Create ((1 => Character'Pos ('0'))), 1 => Create ((1 => Character'Pos ('1'))), 2 => Create ((1 => Character'Pos ('2'))), 3 => Create ((1 => Character'Pos ('3'))), 4 => Create ((1 => Character'Pos ('4'))), 5 => Create ((1 => Character'Pos ('5'))), 6 => Create ((1 => Character'Pos ('6'))), 7 => Create ((1 => Character'Pos ('7'))), 8 => Create ((1 => Character'Pos ('8'))), 9 => Create ((1 => Character'Pos ('9'))))); begin if Base_10.Is_Empty then Base_10 := Atom_Arrays.Create (Create'Access); end if; return Base_10; end Decimal; procedure Reverse_Render (Value : in Natural_T; Symbols : in Atom_Array; Output : in out Atom_Buffers.Atom_Buffer; Length : out Width) is Digit : Natural_T; Remainder : Natural_T := Value; begin Length := 0; loop Digit := Remainder mod Symbols'Length; Remainder := Remainder / Symbols'Length; Length := Length + 1; Output.Append (Symbols (Digit).Query.Data.all); exit when Remainder = 0; end loop; end Reverse_Render; ----------------------- -- Dynamic Atom Maps -- ----------------------- procedure Exclude (Map : in out Atom_Maps.Map; Values : in Interval) is procedure Delete_And_Next (Target : in out Atom_Maps.Map; Cursor : in out Atom_Maps.Cursor); procedure Delete_And_Next (Target : in out Atom_Maps.Map; Cursor : in out Atom_Maps.Cursor) is Next : constant Atom_Maps.Cursor := Atom_Maps.Next (Cursor); begin Target.Delete (Cursor); Cursor := Next; end Delete_And_Next; Cursor : Atom_Maps.Cursor := Map.Ceiling ((Values.First, Values.First)); begin if not Atom_Maps.Has_Element (Cursor) then return; end if; pragma Assert (not (Atom_Maps.Key (Cursor).Last < Values.First)); if Atom_Maps.Key (Cursor).First < Values.First then declare Old_Key : constant Interval := Atom_Maps.Key (Cursor); Prefix_Key : constant Interval := (Old_Key.First, T'Pred (Values.First)); Prefix_Image : constant Displayed_Atom := Atom_Maps.Element (Cursor); begin Delete_And_Next (Map, Cursor); Map.Insert (Prefix_Key, Prefix_Image); if Values.Last < Old_Key.Last then Map.Insert ((T'Succ (Values.Last), Old_Key.Last), Prefix_Image); return; end if; end; end if; while Atom_Maps.Has_Element (Cursor) and then not (Values.Last < Atom_Maps.Key (Cursor).Last) loop Delete_And_Next (Map, Cursor); end loop; if Atom_Maps.Has_Element (Cursor) and then not (Values.Last < Atom_Maps.Key (Cursor).First) then declare Old_Key : constant Interval := Atom_Maps.Key (Cursor); Suffix_Key : constant Interval := (T'Succ (Values.Last), Old_Key.Last); Suffix_Image : constant Displayed_Atom := Atom_Maps.Element (Cursor); begin Delete_And_Next (Map, Cursor); Map.Insert (Suffix_Key, Suffix_Image); end; end if; end Exclude; procedure Include (Map : in out Atom_Maps.Map; Values : in Interval; Image : in Atom_Refs.Immutable_Reference; Width : in Generic_Integers.Width) is begin Exclude (Map, Values); if not Image.Is_Empty then Map.Insert (Values, (Image, Width)); end if; end Include; procedure Parse (Map : in out Atom_Maps.Map; Expression : in out Lockable.Descriptor'Class) is Event : Events.Event := Expression.Current_Event; Lock : Lockable.Lock_State; begin loop case Event is when Events.Add_Atom => declare Image : constant Atom := Expression.Current_Atom; begin Include (Map, (T'First, T'Last), Create (Image), Image'Length); end; when Events.Open_List => Expression.Lock (Lock); begin Expression.Next; Parse_Single_Affix (Map, Expression); exception when others => Expression.Unlock (Lock, False); raise; end; Expression.Unlock (Lock); Event := Expression.Current_Event; exit when Event in Events.Error | Events.End_Of_Input; when Events.Close_List | Events.Error | Events.End_Of_Input => exit; end case; Expression.Next (Event); end loop; end Parse; procedure Parse_Single_Affix (Map : in out Atom_Maps.Map; Expression : in out Lockable.Descriptor'Class) is function Read_Interval (Exp : in out Descriptor'Class) return Interval; function Read_Interval (Exp : in out Descriptor'Class) return Interval is Event : Events.Event; First, Last : T; begin Exp.Next (Event); case Event is when Events.Add_Atom => First := T'Value (To_String (Exp.Current_Atom)); when others => raise Constraint_Error with "Lower bound not an atom"; end case; Exp.Next (Event); case Event is when Events.Add_Atom => Last := T'Value (To_String (Exp.Current_Atom)); when others => raise Constraint_Error with "Upper bound not an atom"; end case; if Last < First then raise Constraint_Error with "Invalid interval (Last < First)"; end if; return (First, Last); end Read_Interval; Event : Events.Event := Expression.Current_Event; Lock : Lockable.Lock_State; Affix : Atom_Refs.Immutable_Reference; Affix_Width : Width := 0; begin case Event is when Events.Add_Atom => declare Current : constant Atom := Expression.Current_Atom; begin if Current'Length > 0 then Affix := Create (Current); Affix_Width := Current'Length; end if; end; when Events.Open_List => Expression.Lock (Lock); begin Expression.Next (Event); if Event /= Events.Add_Atom then Expression.Unlock (Lock, False); return; end if; Affix := Create (Expression.Current_Atom); Affix_Width := Affix.Query.Data.all'Length; Expression.Next (Event); if Event = Events.Add_Atom then begin Affix_Width := Width'Value (To_String (Expression.Current_Atom)); exception when Constraint_Error => null; end; end if; exception when others => Expression.Unlock (Lock, False); raise; end; Expression.Unlock (Lock); when others => return; end case; loop Expression.Next (Event); case Event is when Events.Add_Atom => declare Value : T; begin Value := T'Value (To_String (Expression.Current_Atom)); Include (Map, (Value, Value), Affix, Affix_Width); exception when Constraint_Error => null; end; when Events.Open_List => Expression.Lock (Lock); begin Include (Map, Read_Interval (Expression), Affix, Affix_Width); exception when Constraint_Error => null; when others => Expression.Unlock (Lock, False); raise; end; Expression.Unlock (Lock); when others => exit; end case; end loop; end Parse_Single_Affix; ---------------------- -- Public Interface -- ---------------------- function Render (Value : T; Template : Format) return Atom is function "*" (Count : Width; Symbol : Atom) return Atom; function Safe_Atom (Ref : Atom_Refs.Immutable_Reference; Fallback : String) return Atom; -- The expression below seems to trigger an infinite loop in -- GNAT-AUX 4.9.0 20140422, but the if-statement form doesn't. -- is (if Ref.Is_Empty then To_Atom (Fallback) else Ref.Query.Data.all); function Safe_Atom (Ref : Atom_Refs.Immutable_Reference; Fallback : String) return Atom is begin if Ref.Is_Empty then return To_Atom (Fallback); else return Ref.Query.Data.all; end if; end Safe_Atom; function "*" (Count : Width; Symbol : Atom) return Atom is Result : Atom (1 .. Offset (Count) * Symbol'Length); begin for I in 0 .. Offset (Count) - 1 loop Result (I * Symbol'Length + 1 .. (I + 1) * Symbol'Length) := Symbol; end loop; return Result; end "*"; Output : Atom_Buffers.Atom_Buffer; Has_Sign : Boolean := True; Length : Width; Symbols : constant Atom_Arrays.Immutable_Reference := (if Template.Symbols.Is_Empty then Decimal else Template.Symbols); begin Check_Explicit_Image : declare Cursor : constant Atom_Maps.Cursor := Template.Images.Find ((Value, Value)); begin if Atom_Maps.Has_Element (Cursor) then return Atom_Maps.Element (Cursor).Image.Query.Data.all; end if; end Check_Explicit_Image; if Value < 0 then Reverse_Render (-Value, Symbols.Query.Data.all, Output, Length); Output.Append (Safe_Atom (Template.Negative_Sign, "-")); else Reverse_Render (Value, Symbols.Query.Data.all, Output, Length); if not Template.Positive_Sign.Is_Empty then Output.Append (Template.Positive_Sign.Query.Data.all); else Has_Sign := False; end if; end if; if Has_Sign then Length := Length + 1; end if; Add_Prefix : declare Cursor : constant Atom_Maps.Cursor := Template.Prefix.Find ((Value, Value)); begin if Atom_Maps.Has_Element (Cursor) then declare Data : constant Displayed_Atom := Atom_Maps.Element (Cursor); begin Output.Append_Reverse (Data.Image.Query.Data.all); Length := Length + Data.Width; end; end if; end Add_Prefix; Output.Invert; Add_Suffix : declare Cursor : constant Atom_Maps.Cursor := Template.Suffix.Find ((Value, Value)); begin if Atom_Maps.Has_Element (Cursor) then declare Data : constant Displayed_Atom := Atom_Maps.Element (Cursor); begin Output.Append (Data.Image.Query.Data.all); Length := Length + Data.Width; end; end if; end Add_Suffix; if Length > Template.Maximum_Width then return Safe_Atom (Template.Overflow_Message, ""); end if; if Length < Template.Minimum_Width then declare Needed : constant Width := Template.Minimum_Width - Length; Left_Count, Right_Count : Width := 0; begin case Template.Align is when Left_Aligned => Right_Count := Needed; when Centered => Left_Count := Needed / 2; Right_Count := Needed - Left_Count; when Right_Aligned => Left_Count := Needed; end case; return Left_Count * Safe_Atom (Template.Left_Padding, " ") & Output.Data & Right_Count * Safe_Atom (Template.Right_Padding, " "); end; end if; return Output.Data; end Render; procedure Parse (Template : in out Format; Expression : in out Lockable.Descriptor'Class) is begin Interpreter (Expression, Template, Meaningless_Value); end Parse; procedure Render (Output : in out Ada.Streams.Root_Stream_Type'Class; Template : in out Lockable.Descriptor'Class; Value : in T) is Parsed_Template : Format; begin Parse (Parsed_Template, Template); Output.Write (Render (Value, Parsed_Template)); end Render; procedure Render (Output : in out Ada.Streams.Root_Stream_Type'Class; Default_Format : in Format; Template : in out Lockable.Descriptor'Class; Value : in T) is Parsed_Template : Format := Default_Format; begin Parse (Parsed_Template, Template); Output.Write (Render (Value, Parsed_Template)); end Render; --------------------- -- Format Mutators -- --------------------- procedure Append_Image (Object : in out Format; Image : in Atom_Refs.Immutable_Reference) is begin Set_Image (Object, Next_Index (Object.Images), Image); end Append_Image; procedure Append_Image (Object : in out Format; Image : in Atom) is begin Append_Image (Object, Create (Image)); end Append_Image; procedure Remove_Image (Object : in out Format; Value : in T) is begin Exclude (Object.Images, (Value, Value)); end Remove_Image; procedure Remove_Prefix (Object : in out Format; Value : in T) is begin Remove_Prefix (Object, (Value, Value)); end Remove_Prefix; procedure Remove_Prefix (Object : in out Format; Values : in Interval) is begin Set_Prefix (Object, Values, Atom_Refs.Null_Immutable_Reference, 0); end Remove_Prefix; procedure Remove_Suffix (Object : in out Format; Value : in T) is begin Remove_Suffix (Object, (Value, Value)); end Remove_Suffix; procedure Remove_Suffix (Object : in out Format; Values : in Interval) is begin Set_Suffix (Object, Values, Atom_Refs.Null_Immutable_Reference, 0); end Remove_Suffix; procedure Set_Align (Object : in out Format; Value : in Alignment) is begin Object.Align := Value; end Set_Align; procedure Set_Image (Object : in out Format; Value : in T; Image : in Atom_Refs.Immutable_Reference) is begin Include (Object.Images, (Value, Value), Image, 0); end Set_Image; procedure Set_Image (Object : in out Format; Value : in T; Image : in Atom) is begin Set_Image (Object, Value, Create (Image)); end Set_Image; procedure Set_Left_Padding (Object : in out Format; Symbol : in Atom_Refs.Immutable_Reference) is begin Object.Left_Padding := Symbol; end Set_Left_Padding; procedure Set_Left_Padding (Object : in out Format; Symbol : in Atom) is begin Set_Left_Padding (Object, Create (Symbol)); end Set_Left_Padding; procedure Set_Maximum_Width (Object : in out Format; Value : in Width) is begin Object.Maximum_Width := Value; if Object.Minimum_Width > Object.Maximum_Width then Object.Minimum_Width := Value; end if; end Set_Maximum_Width; procedure Set_Minimum_Width (Object : in out Format; Value : in Width) is begin Object.Minimum_Width := Value; if Object.Minimum_Width > Object.Maximum_Width then Object.Maximum_Width := Value; end if; end Set_Minimum_Width; procedure Set_Negative_Sign (Object : in out Format; Sign : in Atom_Refs.Immutable_Reference) is begin Object.Negative_Sign := Sign; end Set_Negative_Sign; procedure Set_Negative_Sign (Object : in out Format; Sign : in Atom) is begin Set_Negative_Sign (Object, Create (Sign)); end Set_Negative_Sign; procedure Set_Overflow_Message (Object : in out Format; Message : in Atom_Refs.Immutable_Reference) is begin Object.Overflow_Message := Message; end Set_Overflow_Message; procedure Set_Overflow_Message (Object : in out Format; Message : in Atom) is begin Set_Overflow_Message (Object, Create (Message)); end Set_Overflow_Message; procedure Set_Positive_Sign (Object : in out Format; Sign : in Atom_Refs.Immutable_Reference) is begin Object.Positive_Sign := Sign; end Set_Positive_Sign; procedure Set_Positive_Sign (Object : in out Format; Sign : in Atom) is begin Set_Positive_Sign (Object, Create (Sign)); end Set_Positive_Sign; procedure Set_Prefix (Object : in out Format; Value : in T; Prefix : in Atom_Refs.Immutable_Reference; Width : in Generic_Integers.Width) is begin Set_Prefix (Object, (Value, Value), Prefix, Width); end Set_Prefix; procedure Set_Prefix (Object : in out Format; Value : in T; Prefix : in Atom) is begin Set_Prefix (Object, Value, Prefix, Prefix'Length); end Set_Prefix; procedure Set_Prefix (Object : in out Format; Value : in T; Prefix : in Atom; Width : in Generic_Integers.Width) is begin Set_Prefix (Object, Value, Create (Prefix), Width); end Set_Prefix; procedure Set_Prefix (Object : in out Format; Values : in Interval; Prefix : in Atom_Refs.Immutable_Reference; Width : in Generic_Integers.Width) is begin Include (Object.Prefix, Values, Prefix, Width); end Set_Prefix; procedure Set_Prefix (Object : in out Format; Values : in Interval; Prefix : in Atom) is begin Set_Prefix (Object, Values, Prefix, Prefix'Length); end Set_Prefix; procedure Set_Prefix (Object : in out Format; Values : in Interval; Prefix : in Atom; Width : in Generic_Integers.Width) is begin Set_Prefix (Object, Values, Create (Prefix), Width); end Set_Prefix; procedure Set_Right_Padding (Object : in out Format; Symbol : in Atom_Refs.Immutable_Reference) is begin Object.Right_Padding := Symbol; end Set_Right_Padding; procedure Set_Right_Padding (Object : in out Format; Symbol : in Atom) is begin Set_Right_Padding (Object, Create (Symbol)); end Set_Right_Padding; procedure Set_Suffix (Object : in out Format; Value : in T; Suffix : in Atom_Refs.Immutable_Reference; Width : in Generic_Integers.Width) is begin Set_Suffix (Object, (Value, Value), Suffix, Width); end Set_Suffix; procedure Set_Suffix (Object : in out Format; Value : in T; Suffix : in Atom) is begin Set_Suffix (Object, Value, Suffix, Suffix'Length); end Set_Suffix; procedure Set_Suffix (Object : in out Format; Value : in T; Suffix : in Atom; Width : in Generic_Integers.Width) is begin Set_Suffix (Object, Value, Create (Suffix), Width); end Set_Suffix; procedure Set_Suffix (Object : in out Format; Values : in Interval; Suffix : in Atom_Refs.Immutable_Reference; Width : in Generic_Integers.Width) is begin Include (Object.Suffix, Values, Suffix, Width); end Set_Suffix; procedure Set_Suffix (Object : in out Format; Values : in Interval; Suffix : in Atom) is begin Set_Suffix (Object, Values, Suffix, Suffix'Length); end Set_Suffix; procedure Set_Suffix (Object : in out Format; Values : in Interval; Suffix : in Atom; Width : in Generic_Integers.Width) is begin Set_Suffix (Object, Values, Create (Suffix), Width); end Set_Suffix; procedure Set_Symbols (Object : in out Format; Symbols : in Atom_Arrays.Immutable_Reference) is begin if not Symbols.Is_Empty and then Symbols.Query.Data.all'Length >= 2 then Object.Symbols := Symbols; end if; end Set_Symbols; procedure Set_Symbols (Object : in out Format; Expression : in out S_Expressions.Descriptor'Class) is begin Set_Symbols (Object, Create (Expression)); end Set_Symbols; end Natools.S_Expressions.Templates.Generic_Integers;
private package GL.Text.UTF8 is type Code_Point is mod 2**32; subtype UTF8_Code_Point is Code_Point range 0 .. 16#10FFFF#; procedure Read (Buffer : String; Position : in out Positive; Result : out UTF8_Code_Point); end GL.Text.UTF8;
package body Julia_Set is procedure Calculate_Pixel (Re : Real; Im : Real; Z_Escape : out Real; Iter_Escape : out Natural) is Re_Mod : Real := Re; Im_Mod : Real := Im; begin for I in 1 .. IT.Max_Iterations loop declare ReS : constant Real := Re_Mod * Re_Mod; ImS : constant Real := Im_Mod * Im_Mod; begin if (ReS + ImS) >= Escape_Threshold then Iter_Escape := I; Z_Escape := ReS + ImS; return; end if; Im_Mod := (To_Real (2) * Re_Mod * Im_Mod) + Im; Re_Mod := (ReS - ImS) + Re; end; end loop; Iter_Escape := IT.Max_Iterations; Z_Escape := Re_Mod * Re_Mod + Im_Mod * Im_Mod; end Calculate_Pixel; end Julia_Set;
with Ada.Unchecked_Deallocation; package body Oriented is function NewObj return Object_Access is Local : Object_Access; begin Local := new Object'(Counter => 3, Id => (Serial => 1, Subpart => 2)); return Local; end NewObj; procedure Free (Obj : in out Object_Access) is procedure Free_Object is new Ada.Unchecked_Deallocation (Object => Object, Name => Object_Access); begin --null; Free_Object (Obj); end Free; procedure Initialize (Ob : in out Object; P_Id : Positive) is begin Ob.Counter := 2; Ob.Id.Serial := P_Id + 1; Ob.Id.Subpart := Ob.Id.Serial + P_Id * 2; end Initialize; function Get_Item_Id (Ob : in Object) return Positive is begin return Ob.Counter + Ob.Id.Serial + Ob.Id.Subpart; end Get_Item_Id; end Oriented;
------------------------------------------------------------------------------- -- This file is part of libsparkcrypto. -- -- Copyright (C) 2010, Alexander Senier -- Copyright (C) 2010, secunet Security Networks AG -- 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 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 LSC.Internal.Types; with LSC.Internal.AES; with LSC.Internal.AES.CBC; with AUnit.Assertions; use AUnit.Assertions; with Util; use Util; pragma Elaborate_All (Util); pragma Style_Checks ("-s"); pragma Warnings (Off, "formal parameter ""T"" is not referenced"); use type LSC.Internal.Types.Word32_Array_Type; package body LSC_Internal_Test_AES_CBC is subtype Msg_Index is Natural range 1 .. 10; subtype Msg_Type is LSC.Internal.AES.Message_Type (Msg_Index); Plaintext : constant Msg_Type := Msg_Type' (LSC.Internal.AES.Block_Type'(M (16#6bc1bee2#), M (16#2e409f96#), M (16#e93d7e11#), M (16#7393172a#)), LSC.Internal.AES.Block_Type'(M (16#ae2d8a57#), M (16#1e03ac9c#), M (16#9eb76fac#), M (16#45af8e51#)), LSC.Internal.AES.Block_Type'(M (16#30c81c46#), M (16#a35ce411#), M (16#e5fbc119#), M (16#1a0a52ef#)), LSC.Internal.AES.Block_Type'(M (16#f69f2445#), M (16#df4f9b17#), M (16#ad2b417b#), M (16#e66c3710#)), others => LSC.Internal.AES.Null_Block); IV : constant LSC.Internal.AES.Block_Type := LSC.Internal.AES.Block_Type' (M (16#00010203#), M (16#04050607#), M (16#08090a0b#), M (16#0c0d0e0f#)); --------------------------------------------------------------------------- function Equal (Left : Msg_Type; Right : Msg_Type; Length : Msg_Index) return Boolean is Result : Boolean := True; begin for I in Msg_Index range Left'First .. Length loop if Left (I) /= Right (I) then Result := False; exit; end if; end loop; return Result; end Equal; --------------------------------------------------------------------------- procedure Test_AES128_CBC (T : in out Test_Cases.Test_Case'Class) is Key : LSC.Internal.AES.AES128_Key_Type; Ciphertext : Msg_Type; Enc_Context : LSC.Internal.AES.AES_Enc_Context; Dec_Context : LSC.Internal.AES.AES_Dec_Context; Result : Msg_Type; begin Key := LSC.Internal.AES.AES128_Key_Type' (M (16#2b7e1516#), M (16#28aed2a6#), M (16#abf71588#), M (16#09cf4f3c#)); Ciphertext := Msg_Type' (LSC.Internal.AES.Block_Type'(M (16#7649abac#), M (16#8119b246#), M (16#cee98e9b#), M (16#12e9197d#)), (LSC.Internal.AES.Block_Type'(M (16#5086cb9b#), M (16#507219ee#), M (16#95db113a#), M (16#917678b2#))), (LSC.Internal.AES.Block_Type'(M (16#73bed6b8#), M (16#e3c1743b#), M (16#7116e69e#), M (16#22229516#))), (LSC.Internal.AES.Block_Type'(M (16#3ff1caa1#), M (16#681fac09#), M (16#120eca30#), M (16#7586e1a7#))), others => LSC.Internal.AES.Null_Block); -- Encryption Enc_Context := LSC.Internal.AES.Create_AES128_Enc_Context (Key); LSC.Internal.AES.CBC.Encrypt (Enc_Context, IV, Plaintext, 4, Result); Assert (Equal (Result, Ciphertext, 4), "Invalid ciphertext"); -- Decryption Dec_Context := LSC.Internal.AES.Create_AES128_Dec_Context (Key); LSC.Internal.AES.CBC.Decrypt (Dec_Context, IV, Ciphertext, 4, Result); Assert (Equal (Result, Plaintext, 4), "Invalid plaintext"); end Test_AES128_CBC; --------------------------------------------------------------------------- procedure Test_AES192_CBC (T : in out Test_Cases.Test_Case'Class) is Key : LSC.Internal.AES.AES192_Key_Type; Ciphertext : Msg_Type; Enc_Context : LSC.Internal.AES.AES_Enc_Context; Dec_Context : LSC.Internal.AES.AES_Dec_Context; Result : Msg_Type; begin Key := LSC.Internal.AES.AES192_Key_Type' (M (16#8e73b0f7#), M (16#da0e6452#), M (16#c810f32b#), M (16#809079e5#), M (16#62f8ead2#), M (16#522c6b7b#)); Ciphertext := Msg_Type' (LSC.Internal.AES.Block_Type'(M (16#4f021db2#), M (16#43bc633d#), M (16#7178183a#), M (16#9fa071e8#)), LSC.Internal.AES.Block_Type'(M (16#b4d9ada9#), M (16#ad7dedf4#), M (16#e5e73876#), M (16#3f69145a#)), LSC.Internal.AES.Block_Type'(M (16#571b2420#), M (16#12fb7ae0#), M (16#7fa9baac#), M (16#3df102e0#)), LSC.Internal.AES.Block_Type'(M (16#08b0e279#), M (16#88598881#), M (16#d920a9e6#), M (16#4f5615cd#)), others => LSC.Internal.AES.Null_Block); -- Encryption Enc_Context := LSC.Internal.AES.Create_AES192_Enc_Context (Key); LSC.Internal.AES.CBC.Encrypt (Enc_Context, IV, Plaintext, 4, Result); Assert (Equal (Result, Ciphertext, 4), "Invalid ciphertext"); -- Decryption Dec_Context := LSC.Internal.AES.Create_AES192_Dec_Context (Key); LSC.Internal.AES.CBC.Decrypt (Dec_Context, IV, Ciphertext, 4, Result); Assert (Equal (Result, Plaintext, 4), "Invalid plaintext"); end Test_AES192_CBC; --------------------------------------------------------------------------- procedure Test_AES256_CBC (T : in out Test_Cases.Test_Case'Class) is Key : LSC.Internal.AES.AES256_Key_Type; Ciphertext : Msg_Type; Enc_Context : LSC.Internal.AES.AES_Enc_Context; Dec_Context : LSC.Internal.AES.AES_Dec_Context; Result : Msg_Type; begin Key := LSC.Internal.AES.AES256_Key_Type' (M (16#603deb10#), M (16#15ca71be#), M (16#2b73aef0#), M (16#857d7781#), M (16#1f352c07#), M (16#3b6108d7#), M (16#2d9810a3#), M (16#0914dff4#)); Ciphertext := Msg_Type' (LSC.Internal.AES.Block_Type'(M (16#f58c4c04#), M (16#d6e5f1ba#), M (16#779eabfb#), M (16#5f7bfbd6#)), LSC.Internal.AES.Block_Type'(M (16#9cfc4e96#), M (16#7edb808d#), M (16#679f777b#), M (16#c6702c7d#)), LSC.Internal.AES.Block_Type'(M (16#39f23369#), M (16#a9d9bacf#), M (16#a530e263#), M (16#04231461#)), LSC.Internal.AES.Block_Type'(M (16#b2eb05e2#), M (16#c39be9fc#), M (16#da6c1907#), M (16#8c6a9d1b#)), others => LSC.Internal.AES.Null_Block); -- Encryption Enc_Context := LSC.Internal.AES.Create_AES256_Enc_Context (Key); LSC.Internal.AES.CBC.Encrypt (Enc_Context, IV, Plaintext, 4, Result); Assert (Equal (Result, Ciphertext, 4), "Invalid ciphertext"); -- Decryption Dec_Context := LSC.Internal.AES.Create_AES256_Dec_Context (Key); LSC.Internal.AES.CBC.Decrypt (Dec_Context, IV, Ciphertext, 4, Result); Assert (Equal (Result, Plaintext, 4), "Invalid plaintext"); end Test_AES256_CBC; --------------------------------------------------------------------------- procedure Register_Tests (T : in out Test_Case) is use AUnit.Test_Cases.Registration; begin Register_Routine (T, Test_AES128_CBC'Access, "128 (F.2.1/F.2.2)"); Register_Routine (T, Test_AES192_CBC'Access, "192 (F.2.3/F.2.4)"); Register_Routine (T, Test_AES256_CBC'Access, "256 (F.2.5/F.2.6)"); end Register_Tests; --------------------------------------------------------------------------- function Name (T : Test_Case) return Test_String is begin return Format ("AES-CBC"); end Name; end LSC_Internal_Test_AES_CBC;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- N A M E T . S P -- -- -- -- B o d y -- -- -- -- Copyright (C) 2008-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. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with System.WCh_Cnv; use System.WCh_Cnv; with GNAT.UTF_32_Spelling_Checker; package body Namet.Sp is ----------------------- -- Local Subprograms -- ----------------------- procedure Get_Name_String_UTF_32 (Id : Name_Id; Result : out UTF_32_String; Length : out Natural); -- This procedure is similar to Get_Decoded_Name except that the output -- is stored in the given Result array as single codes, so in particular -- any Uhh, Whhhh, or WWhhhhhhhh sequences are decoded to appear as a -- single value in the output. This call does not affect the contents of -- either Name_Buffer or Name_Len. The result is in Result (1 .. Length). -- The caller must ensure that the result buffer is long enough. ---------------------------- -- Get_Name_String_UTF_32 -- ---------------------------- procedure Get_Name_String_UTF_32 (Id : Name_Id; Result : out UTF_32_String; Length : out Natural) is pragma Assert (Result'First = 1); SPtr : Int := Name_Entries.Table (Id).Name_Chars_Index + 1; -- Index through characters of name in Name_Chars table. Initial value -- points to first character of the name. SLen : constant Nat := Nat (Name_Entries.Table (Id).Name_Len); -- Length of the name SLast : constant Int := SPtr + SLen - 1; -- Last index in Name_Chars table for name C : Character; -- Current character from Name_Chars table procedure Store_Hex (N : Natural); -- Read and store next N characters starting at SPtr and store result -- in next character of Result. Update SPtr past characters read. --------------- -- Store_Hex -- --------------- procedure Store_Hex (N : Natural) is T : UTF_32_Code; C : Character; begin T := 0; for J in 1 .. N loop C := Name_Chars.Table (SPtr); SPtr := SPtr + 1; if C in '0' .. '9' then T := 16 * T + Character'Pos (C) - Character'Pos ('0'); else pragma Assert (C in 'a' .. 'f'); T := 16 * T + Character'Pos (C) - (Character'Pos ('a') - 10); end if; end loop; Length := Length + 1; pragma Assert (Length <= Result'Length); Result (Length) := T; end Store_Hex; -- Start of processing for Get_Name_String_UTF_32 begin Length := 0; while SPtr <= SLast loop C := Name_Chars.Table (SPtr); -- Uhh encoding if C = 'U' and then SPtr <= SLast - 2 and then Name_Chars.Table (SPtr + 1) not in 'A' .. 'Z' then SPtr := SPtr + 1; Store_Hex (2); -- Whhhh encoding elsif C = 'W' and then SPtr <= SLast - 4 and then Name_Chars.Table (SPtr + 1) not in 'A' .. 'Z' then SPtr := SPtr + 1; Store_Hex (4); -- WWhhhhhhhh encoding elsif C = 'W' and then SPtr <= SLast - 8 and then Name_Chars.Table (SPtr + 1) = 'W' then SPtr := SPtr + 2; Store_Hex (8); -- Q encoding (character literal) elsif C = 'Q' and then SPtr < SLast then -- Put apostrophes around character pragma Assert (Length <= Result'Last - 3); Result (Length + 1) := UTF_32_Code'Val (Character'Pos (''')); Result (Length + 2) := UTF_32_Code (Get_Char_Code (Name_Chars.Table (SPtr + 1))); Result (Length + 3) := UTF_32_Code'Val (Character'Pos (''')); SPtr := SPtr + 2; Length := Length + 3; -- Unencoded case else SPtr := SPtr + 1; Length := Length + 1; pragma Assert (Length <= Result'Last); Result (Length) := UTF_32_Code (Get_Char_Code (C)); end if; end loop; end Get_Name_String_UTF_32; ------------------------ -- Is_Bad_Spelling_Of -- ------------------------ function Is_Bad_Spelling_Of (Found, Expect : Name_Id) return Boolean is FL : constant Natural := Natural (Length_Of_Name (Found)); EL : constant Natural := Natural (Length_Of_Name (Expect)); -- Length of input names FB : UTF_32_String (1 .. 2 * FL); EB : UTF_32_String (1 .. 2 * EL); -- Buffers for results, a factor of 2 is more than enough, the only -- sequence which expands is Q (character literal) by 1.5 times. FBL : Natural; EBL : Natural; -- Length of decoded names begin Get_Name_String_UTF_32 (Found, FB, FBL); Get_Name_String_UTF_32 (Expect, EB, EBL); -- For an exact match, return False, otherwise check bad spelling. We -- need this special test because the library routine returns True for -- an exact match. if FB (1 .. FBL) = EB (1 .. EBL) then return False; else return GNAT.UTF_32_Spelling_Checker.Is_Bad_Spelling_Of (FB (1 .. FBL), EB (1 .. EBL)); end if; end Is_Bad_Spelling_Of; end Namet.Sp;
------------------------------------------------------------------------------- -- Copyright (c) 2019, Daniel King -- 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. -- * The name of the copyright holder may not 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 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 Keccak.Generic_CSHAKE; with Keccak.Generic_XOF; with Keccak.Generic_Parallel_XOF; with Keccak.Types; -- @summary -- Generic implementation of the ParallelHash algorithm as defined in NIST SP 800-185. -- -- @description -- The purpose of ParallelHash10 is to support the efficient hashing of very long -- strings, by taking advantage of the parallelism available in modern processors. -- ParallelHash provides variable-length output. Changing any input parameter to -- ParallelHash, even the requested output length, will result in unrelated output. -- Like the other functions defined in this document, ParallelHash also supports -- user-selected customization strings. -- -- The block size defines the size of each input block that is processed in parallel. -- It can be any positive value up to Block_Size_Number'Last / 8. Since Block_Size_Number -- is defined as a subtype of Positive, this guaranteeds the maximum block size to -- be at least 4095 bytes when Integer is at least a 16-bit signed type. On most systems -- is likely to be at least 268_435_455 bytes (256 MiB - 1 B) when Integer is a -- 32-bit signed type. -- -- This API is used as follows: -- -- 1 Call Init to initialise a new context. The block size and an optional -- customisation string (for domain separation) are provided here. -- -- 2 Call Update one or more times to input an arbitrary amount of data into -- the ParallelHash context. -- -- 3 Call either Finish or Extract to produce the desired type of output -- (ParallelHash or ParallelHashXOF): -- -- * Finish is used to produce a single output of arbitrary length (ParallelHash). -- The requested output length affects the output. For example, requesting -- a 10-byte output will produce an unrelated hash to requesting a 20-byte -- output. -- -- * Extract can be called one or more times to produce an arbitrary number -- of output bytes (ParallelHashXOF). In this case, the total output length is -- unknown in advance so the output does not change based on the overall length. -- For example, a 10-byte output is the truncated version of a 20-byte output. -- -- @group ParallelHash generic CV_Size_Bytes : Positive; -- Length of the Chaining Values, in bytes. with package CSHAKE_Serial is new Keccak.Generic_CSHAKE (<>); -- This CSHAKE must be configured with NO SUFFIX BITS. -- The Generic_KangarooTwelve implementation takes care of the appropriate -- suffix bits when using this CSHAKE_Serial. with package SHAKE_Serial is new Keccak.Generic_XOF (<>); with package SHAKE_Parallel_2 is new Keccak.Generic_Parallel_XOF (<>); -- This CSHAKE must be configured to add the 3 suffix bits 2#011#. with package SHAKE_Parallel_4 is new Keccak.Generic_Parallel_XOF (<>); -- This CSHAKE must be configured to add the 3 suffix bits 2#011#. with package SHAKE_Parallel_8 is new Keccak.Generic_Parallel_XOF (<>); -- This CSHAKE must be configured to add the 3 suffix bits 2#011#. package Keccak.Generic_Parallel_Hash is -- Assertions to check that the correct parallel instances have -- been provided. pragma Assert (SHAKE_Parallel_2.Num_Parallel_Instances = 2); pragma Assert (SHAKE_Parallel_4.Num_Parallel_Instances = 4); pragma Assert (SHAKE_Parallel_8.Num_Parallel_Instances = 8); type Context is private; type States is (Updating, Extracting, Finished); -- @value Updating When in this state additional data can be input into the -- ParallelHash context. -- -- @value Extracting When in this state, the ParallelHash context can generate -- output bytes by calling the Extract procedure. -- -- @value Finished When in this state the context is finished and no more data -- can be input or output. type Byte_Count is new Long_Long_Integer range 0 .. Long_Long_Integer'Last; subtype Block_Size_Number is Positive range 1 .. Positive'Last / 8; procedure Init (Ctx : out Context; Block_Size : in Block_Size_Number; Customization : in String) with Global => null, Post => State_Of (Ctx) = Updating; -- Initialise the ParallelHash instance. -- -- @param Ctx The context to initialise. -- -- @param Block_Size The block size in bytes for parallel hashing. procedure Update (Ctx : in out Context; Data : in Types.Byte_Array) with Global => null, Pre => (State_Of (Ctx) = Updating and Byte_Count (Data'Length) <= Max_Input_Length (Ctx)), Post => (State_Of (Ctx) = Updating and Num_Bytes_Processed (Ctx) = Num_Bytes_Processed (Ctx'Old) + Byte_Count (Data'Length)); -- Process input bytes with ParallelHash. -- -- This procedure is most efficient when the input Data buffer is -- at least 8 times larger than the ParallelHash block size. -- -- This may be called multiple times to process a large amount of data. -- -- Note that there is an overall limit to the maximum amount of data that -- can be processed with ParallelHash. The maximum input size is returned -- by calling the Max_Input_Length function. -- -- @param Ctx The context to update with new input data. -- -- @param Data The data to process with ParallelHash. procedure Finish (Ctx : in out Context; Data : out Types.Byte_Array) with Global => null, Pre => State_Of (Ctx) = Updating, Post => State_Of (Ctx) = Finished; -- Extract a fixed number of output bytes. -- -- This procedure finalizes the ParallelHash and outputs a fixed number -- of output bytes. The ParallelHash parameter L is the requested output -- length, and is determined by the length of the @Data@ array. -- I.e. Data'Length is used as the ParallelHash parameter L. -- -- After calling this procedure the ParallelHash instance cannot be used -- further. procedure Extract (Ctx : in out Context; Data : out Types.Byte_Array) with Global => null, Pre => State_Of (Ctx) in Updating | Extracting, Post => State_Of (Ctx) = Extracting; -- Extract an arbitrary number of output bytes. -- -- This procedure finalizes the ParallelHash and puts it into XOF mode -- where an arbitary number of bytes can be output. When this parameter -- is called for the first time after inputting data, the value 0 is used -- as the ParallelHash parameter L. -- -- This procedure can be called multiple times to produce any output length. function State_Of (Ctx : in Context) return States with Global => null; function Num_Bytes_Processed (Ctx : in Context) return Byte_Count with Global => null; -- Get the total number of bytes that have been input to the ParllelHash -- instance so far. -- -- This restricts the maximum permitted input length to a maximum of -- Byte_Count'Last bytes. function Max_Input_Length (Ctx : in Context) return Byte_Count with Global => null; -- Gets the maximum number of bytes that may be input into the ParallelHash context. -- -- This value decreases as the context is updated with additional input data. function Block_Size_Of (Ctx : in Context) return Block_Size_Number with Global => null; -- Get the configured block size parameter of the ParallelHash instance. private use type CSHAKE_Serial.States; use type SHAKE_Serial.States; type Context is record Outer_CSHAKE : CSHAKE_Serial.Context; Partial_Block_CSHAKE : SHAKE_Serial.Context; Input_Len : Byte_Count; Block_Size : Block_Size_Number; Partial_Block_Length : Natural; Finished : Boolean; end record with Predicate => Context.Partial_Block_Length < Context.Block_Size; function State_Of (Ctx : in Context) return States is (if (Ctx.Finished or SHAKE_Serial.State_Of (Ctx.Partial_Block_CSHAKE) /= SHAKE_Serial.Updating or CSHAKE_Serial.State_Of (Ctx.Outer_CSHAKE) = CSHAKE_Serial.Ready_To_Extract) then Finished elsif CSHAKE_Serial.State_Of (Ctx.Outer_CSHAKE) = CSHAKE_Serial.Updating then Updating else Extracting); function Num_Bytes_Processed (Ctx : in Context) return Byte_Count is (Ctx.Input_Len); function Max_Input_Length (Ctx : in Context) return Byte_Count is (Byte_Count'Last - Num_Bytes_Processed (Ctx)); function Block_Size_Of (Ctx : in Context) return Block_Size_Number is (Ctx.Block_Size); end Keccak.Generic_Parallel_Hash;
-- { dg-do run } -- { dg-options "-gnatws" } procedure Tfren is type R; type Ar is access all R; type R is record F1: Integer; F2: Ar; end record; for R use record F1 at 1 range 0..31; F2 at 5 range 0..63; end record; procedure Foo (RR1, RR2: Ar); procedure Foo (RR1, RR2 : Ar) is begin if RR2.all.F1 /= 55 then raise program_error; end if; end; R3: aliased R := (55, Null); R2: aliased R := (44, R3'Access); R1: aliased R := (22, R2'Access); P: Ar := R1'Access; X: Ar renames P.all.F2; Y: Ar renames X.all.F2; begin P := R2'Access; R1.F2 := R1'Access; Foo (X, Y); Y.F1 := -111; if Y.F1 /= -111 then raise Constraint_Error; end if; end Tfren;
----------------------------------------------------------------------- -- security-oauth-servers-tests - Unit tests for server side OAuth -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Security.Auth.Tests; with Security.OAuth.File_Registry; package body Security.OAuth.Servers.Tests is use Auth.Tests; use File_Registry; package Caller is new Util.Test_Caller (Test, "Security.OAuth.Servers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Find_Application", Test_Application_Manager'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Verify", Test_User_Verify'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Token", Test_Token_Password'Access); Caller.Add_Test (Suite, "Test Security.OAuth.Servers.Authenticate", Test_Bad_Token'Access); Caller.Add_Test (Suite, "Test Security.OAuth.File_Registry.Load", Test_Load_Registry'Access); end Add_Tests; -- ------------------------------ -- Test the application manager. -- ------------------------------ procedure Test_Application_Manager (T : in out Test) is Manager : File_Application_Manager; App : Application; begin App.Set_Application_Identifier ("my-app-id"); App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback"); Manager.Add_Application (App); -- Check that we can find our application. declare A : constant Application'Class := Manager.Find_Application ("my-app-id"); begin Util.Tests.Assert_Equals (T, "my-app-id", A.Get_Application_Identifier, "Invalid application returned by Find"); end; -- Check that an exception is raised for an invalid client ID. begin declare A : constant Application'Class := Manager.Find_Application ("unkown-app-id"); begin Util.Tests.Fail (T, "Found the application " & A.Get_Application_Identifier); end; exception when Invalid_Application => null; end; end Test_Application_Manager; -- ------------------------------ -- Test the user registration and verification. -- ------------------------------ procedure Test_User_Verify (T : in out Test) is Manager : File_Realm_Manager; Auth : Principal_Access; begin Manager.Add_User ("Gandalf", "Mithrandir"); Manager.Verify ("Gandalf", "mithrandir", Auth); T.Assert (Auth = null, "Verify password should fail with an invalid password"); Manager.Verify ("Sauron", "Mithrandir", Auth); T.Assert (Auth = null, "Verify password should fail with an invalid user"); Manager.Verify ("Gandalf", "Mithrandir", Auth); T.Assert (Auth /= null, "Verify password operation failed for a good user/password"); end Test_User_Verify; -- ------------------------------ -- Test the token operation that produces an access token from user/password. -- RFC 6749: Section 4.3. Resource Owner Password Credentials Grant -- ------------------------------ procedure Test_Token_Password (T : in out Test) is use type Util.Strings.Name_Access; Apps : aliased File_Application_Manager; Realm : aliased File_Realm_Manager; Manager : Auth_Manager; App : Application; Grant : Grant_Type; Auth_Grant : Grant_Type; Params : Test_Parameters; begin -- Add one test application. App.Set_Application_Identifier ("my-app-id"); App.Set_Application_Secret ("my-secret"); App.Set_Application_Callback ("my-callback"); Apps.Add_Application (App); -- Add one test user. Realm.Add_User ("Gandalf", "Mithrandir"); -- Configure the auth manager. Manager.Set_Application_Manager (Apps'Unchecked_Access); Manager.Set_Realm_Manager (Realm'Unchecked_Access); Manager.Set_Private_Key ("server-private-key-no-so-secure"); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is missing"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, ""); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, "unkown-app"); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is invalid"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, "my-app-id"); Params.Set_Parameter (Security.OAuth.GRANT_TYPE, ""); Manager.Token (Params, Grant); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when client_id is empty"); Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the user/password is missing"); Params.Set_Parameter (Security.OAuth.USERNAME, "Gandalf"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the password is missing"); Params.Set_Parameter (Security.OAuth.PASSWORD, "test"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the password is invalid"); Params.Set_Parameter (Security.OAuth.PASSWORD, "Mithrandir"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Invalid_Grant, "Expecting Invalid_Grant when the client_secret is invalid"); Params.Set_Parameter (Security.OAuth.CLIENT_SECRET, "my-secret"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct"); T.Assert (Grant.Error = null, "Expecting null error"); T.Assert (Length (Grant.Token) > 20, "Expecting a token with some reasonable size"); T.Assert (Grant.Auth /= null, "Expecting a non null auth principal"); Util.Tests.Assert_Equals (T, "Gandalf", Grant.Auth.Get_Name, "Invalid user name in the principal"); -- Verify the access token. for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Request = Access_Grant, "Expecting Access_Grant for the authenticate"); T.Assert (Auth_Grant.Status = Valid_Grant, "Expecting Valid_Grant when the access token is checked"); T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token"); T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal"); end loop; -- Verify the modified access token. Manager.Authenticate (To_String (Grant.Token) & "x", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for the authenticate"); Manager.Revoke (To_String (Grant.Token)); -- Verify the access is now denied. for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Status = Revoked_Grant, "Expecting Revoked_Grant for the authenticate"); end loop; -- Change application token expiration time to 1 second. App.Expire_Timeout := 1.0; Apps.Add_Application (App); -- Make the access token. Manager.Token (Params, Grant); T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct"); -- Verify the access token. for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Request = Access_Grant, "Expecting Access_Grant for the authenticate"); T.Assert (Auth_Grant.Status = Valid_Grant, "Expecting Valid_Grant when the access token is checked"); T.Assert (Auth_Grant.Error = null, "Expecting null error for access_token"); T.Assert (Auth_Grant.Auth = Grant.Auth, "Expecting valid auth principal"); end loop; -- Wait for the token to expire. delay 2.0; for I in 1 .. 5 loop Manager.Authenticate (To_String (Grant.Token), Auth_Grant); T.Assert (Auth_Grant.Status = Expired_Grant, "Expecting Expired when the access token is checked"); end loop; end Test_Token_Password; -- ------------------------------ -- Test the access token validation with invalid tokens (bad formed). -- ------------------------------ procedure Test_Bad_Token (T : in out Test) is Manager : Auth_Manager; Auth_Grant : Grant_Type; begin Manager.Authenticate ("x", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate (".", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("..", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("a..", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("..b", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); Manager.Authenticate ("a..b", Auth_Grant); T.Assert (Auth_Grant.Status = Invalid_Grant, "Expecting Invalid_Grant for badly formed token"); end Test_Bad_Token; -- ------------------------------ -- Test the loading configuration files for the File_Registry. -- ------------------------------ procedure Test_Load_Registry (T : in out Test) is Apps : aliased File_Application_Manager; Realm : aliased File_Realm_Manager; Manager : Auth_Manager; Grant : Grant_Type; Params : Test_Parameters; begin Apps.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "apps"); Realm.Load (Util.Tests.Get_Path ("regtests/files/user_apps.properties"), "users"); -- Configure the auth manager. Manager.Set_Application_Manager (Apps'Unchecked_Access); Manager.Set_Realm_Manager (Realm'Unchecked_Access); Manager.Set_Private_Key ("server-private-key-no-so-secure"); Params.Set_Parameter (Security.OAuth.CLIENT_ID, "app-id-1"); Params.Set_Parameter (Security.OAuth.CLIENT_SECRET, "app-secret-1"); Params.Set_Parameter (Security.OAuth.GRANT_TYPE, "password"); Params.Set_Parameter (Security.OAuth.USERNAME, "joe"); Params.Set_Parameter (Security.OAuth.PASSWORD, "test"); Manager.Token (Params, Grant); T.Assert (Grant.Request = Password_Grant, "Expecting Password_Grant for the grant request"); T.Assert (Grant.Status = Valid_Grant, "Expecting Valid_Grant when the user/password are correct"); end Test_Load_Registry; end Security.OAuth.Servers.Tests;
with Drawing; use Drawing; package body Tracks_Display is Entry_Sign_Size : constant := 6; Entry_Sign_Pixel : constant array (Entry_Sign_Color) of Color := (Green => Screen_Interface.Green, Orange => Screen_Interface.Orange, Red => Screen_Interface.Red); Track_Color : constant Color := Screen_Interface.Light_Gray; Track_Thickness : constant := 4; Train_Thickness : constant := 2; Switch_Color : constant Color := Screen_Interface.Violet; Switch_Thickness : constant := 2; use type Trains.Train_Id; function First_Bogie_Track (Train : Train_T) return Trains.Track_Id; function Last_Bogie_Track (Train : Train_T) return Trains.Track_Id; procedure Build_Straight_Track (Track : in out Track_T; Start, Stop : Point) is Diff_X : constant Float := (Float(Stop.X) - Float(Start.X)) / (Float (Track.Points'Length) - 1.0); Diff_Y : constant Float := (Float(Stop.Y) - Float(Start.Y)) / (Float (Track.Points'Length) - 1.0); begin for I in Track.Points'Range loop declare T : constant Float := (Float (I) - 1.0); begin Track.Points (I).X := Width (Float (Start.X) + T * Diff_X); Track.Points (I).Y := Height (Float (Start.Y) + T * Diff_Y); end; end loop; Track.Is_Straight := True; -- Default Sign Position Set_Sign_Position (Track, Top); end Build_Straight_Track; procedure Build_Curve_Track (Track : in out Track_T; P1, P2, P3, P4 : Point) is begin for I in Track.Points'Range loop declare T : constant Float := Float (I) / Float (Track.Points'Length); A : constant Float := (1.0 - T)**3; B : constant Float := 3.0 * T * (1.0 - T)**2; C : constant Float := 3.0 * T**2 * (1.0 - T); D : constant Float := T**3; begin Track.Points (I).X := Width (A * Float (P1.X) + B * Float (P2.X) + C * Float (P3.X) + D * Float (P4.X)); Track.Points (I).Y := Height (A * Float (P1.Y) + B * Float (P2.Y) + C * Float (P3.Y) + D * Float (P4.Y)); end; end loop; Track.Is_Straight := False; -- Fix first and last coordinate Track.Points (Track.Points'First) := P1; Track.Points (Track.Points'Last) := P4; -- Default Sign Position Set_Sign_Position (Track, Top); end Build_Curve_Track; procedure Set_Sign_Position (Track : in out Track_T; Pos : Entry_Sign_Position) is First : constant Point := Track.Points (Track.Points'First); Coord : Point; begin case Pos is when Top => Coord := (First.X - Width (Entry_Sign_Size * 1.5), First.Y); when Left => Coord := (First.X, First.Y + Height (Entry_Sign_Size * 1.5)); when Bottom => Coord := (First.X + Width (Entry_Sign_Size * 1.5), First.Y); when Right => Coord := (First.X, First.Y - Height (Entry_Sign_Size * 1.5)); end case; Track.Entry_Sign.Coord := Coord; end Set_Sign_Position; procedure Connect_Track (Track : in out Track_T; E1, E2 : Track_Access) is begin if E1 = null then raise Program_Error; else Track.Exits (S1) := E1; Track.Switch_State := S1; Track.Switchable := False; -- Connected track should share point coordinate if Track.Points (Track.Points'Last) /= E1.all.Points (E1.all.Points'First) then raise Program_Error; end if; end if; if E2 /= null then Track.Exits (S2) := E2; Track.Switchable := True; E2.Entry_Sign.Disabled := True; -- Connected track should share point coordinate if Track.Points (Track.Points'Last) /= E2.all.Points (E2.all.Points'First) then raise Program_Error; end if; end if; end Connect_Track; procedure Init_Train (Train : in out Train_T; Track : Track_Access) is Cnt : Natural := 1; begin if Train.Nb_Bogies > Track.all.Points'Length then -- Not enough space to put the train. raise Program_Error; end if; Train.Id := Trains.Cur_Num_Trains; for Bog of Train.Bogies loop Bog.Track := Track; Bog.Track_Pos := Track.all.Points'First + Train.Nb_Bogies - Cnt; if Bog.Track_Pos not in Track.Points'Range then raise Program_Error; end if; Cnt := Cnt + 1; end loop; end Init_Train; function Next_Track (Track : Track_Access) return Track_Access is begin if Track.all.Switchable and then Track.all.Switch_State = S2 then return Track.all.Exits (S2); else return Track.all.Exits (S1); end if; end Next_Track; -- Return True when the bogie moves to the entry of a new track procedure Move_Bogie (Bog : in out Bogie) is begin if Bog.Track_Pos = Bog.Track.all.Points'Last then Bog.Track := Next_Track (Bog.Track); -- The first point of track has the same position has the last of -- previous tack, so we skip it. Bog.Track_Pos := Bog.Track.all.Points'First + 1; else Bog.Track_Pos := Bog.Track_Pos + 1; end if; end Move_Bogie; procedure Move_Train (Train : in out Train_T) is use type Trains.Move_Result; Cnt : Integer := 0; Train_Copy : Train_T (Train.Nb_Bogies); Sign_Command : Trains.Move_Result; begin loop -- Make a copy of the train an move it Train_Copy := Train; -- Each bogie takes the previous position of the bogie in front him for Index in reverse Train_Copy.Bogies'First + 1 .. Train_Copy.Bogies'Last loop Train_Copy.Bogies (Index) := Train_Copy.Bogies (Index - 1); end loop; -- To move the first bogie we need to see if we are at the end of a -- track and maybe a switch. Move_Bogie (Train_Copy.Bogies (Train_Copy.Bogies'First)); -- Check if that move was legal Trains.Move (Train_Copy.Id, (First_Bogie_Track (Train_Copy), 0, Last_Bogie_Track (Train_Copy)), Sign_Command); if Sign_Command /= Trains.Stop then -- Redraw the track under the last bogie this is an optimisation to -- avoid redrawing all tracks at each loop. Line (Get_Coords (Train.Bogies (Train.Bogies'Last)), Get_Coords (Train.Bogies (Train.Bogies'Last - 1)), Track_Color, Track_Thickness); -- This move is ilegal, set train to the new position Train := Train_Copy; end if; case Sign_Command is when Trains.Full_Speed => Train.Speed := 3; when Trains.Slow_Down => Train.Speed := 1; when Trains.Stop => Train.Speed := 0; when Trains.Keep_Going => -- Keep the same speed null; end case; exit when Train.Speed <= Cnt; Cnt := Cnt + 1; end loop; end Move_Train; procedure Draw_Sign (Track : Track_T) is begin if (Track.Entry_Sign.Coord /= (0, 0)) then if not Track.Entry_Sign.Disabled then Circle (Track.Entry_Sign.Coord, Entry_Sign_Size / 2, Entry_Sign_Pixel (Track.Entry_Sign.Color), True); else -- Draw a black circle to "erase" the previous drawing Circle (Track.Entry_Sign.Coord, Entry_Sign_Size / 2, Black, True); end if; end if; end Draw_Sign; procedure Draw_Track (Track : Track_T) is begin if Track.Is_Straight then Line (Track.Points (Track.Points'First), Track.Points (Track.Points'Last), Track_Color, Track_Thickness); else for Index in Track.Points'First .. Track.Points'Last - 1 loop Line (Track.Points (Index), Track.Points (Index + 1), Track_Color, Track_Thickness); end loop; end if; Draw_Sign (Track); end Draw_Track; procedure Draw_Switch (Track : Track_T) is Target : constant Track_Access := Track.Exits (Track.Switch_State); begin if Track.Switchable then For Cnt in Target.Points'First .. Target.Points'First + 10 loop declare P1 : constant Point := Target.all.Points (Cnt); P2 : constant Point := Target.all.Points (Cnt + 1); begin Line (P1, P2, Switch_Color, Switch_Thickness); end; end loop; end if; end Draw_Switch; procedure Draw_Train (Train : Train_T) is Train_Color : Color; begin for Index in Train.Bogies'First .. Train.Bogies'Last - 1 loop declare B1 : constant Bogie := Train.Bogies (Index); Track1 : constant Track_Access := B1.Track; P1 : constant Point := Track1.Points (B1.Track_Pos); B2 : constant Bogie := Train.Bogies (Index + 1); Track2 : constant Track_Access := B2.Track; P2 : constant Point := Track2.Points (B2.Track_Pos); begin case Train.Speed is when 0 => Train_Color := Screen_Interface.Red; when 1 => Train_Color := Screen_Interface.Orange; when others => Train_Color := Screen_Interface.Black; end case; Line (P1, P2, Train_Color, Train_Thickness); end; end loop; end Draw_Train; procedure Update_Sign (Track : in out Track_T) is Prev_Color : constant Entry_Sign_Color := Track.Entry_Sign.Color; begin case Trains.Track_Signals (Track.Id) is when Trains.Green => Track.Entry_Sign.Color := Green; when Trains.Orange => Track.Entry_Sign.Color := Orange; Draw_Track (Track); when Trains.Red => Track.Entry_Sign.Color := Red; end case; if Track.Entry_Sign.Color /= Prev_Color then Draw_Sign (Track); end if; end Update_Sign; procedure Change_Switch (Track : in out Track_T) is begin if Track.Switch_State = S1 then Track.Switch_State := S2; Track.Exits (S1).Entry_Sign.Disabled := True; Track.Exits (S2).Entry_Sign.Disabled := False; else Track.Switch_State := S1; Track.Exits (S2).Entry_Sign.Disabled := True; Track.Exits (S1).Entry_Sign.Disabled := False; end if; Draw_Track (Track.Exits (S1).all); Draw_Track (Track.Exits (S2).all); Draw_Track (Track); end Change_Switch; function Get_Coords (Bog : Bogie) return Point is begin return Bog.Track.Points (Bog.Track_Pos); end Get_Coords; function First_Bogie_Track (Train : Train_T) return Trains.Track_Id is Bog : constant Bogie := Train.Bogies(Train.Bogies'First); begin return Bog.Track.Id; end First_Bogie_Track; function Last_Bogie_Track (Train : Train_T) return Trains.Track_Id is Bog : constant Bogie := Train.Bogies(Train.Bogies'Last); begin return Bog.Track.Id; end Last_Bogie_Track; function Start_Coord (Track : Track_T) return Point is begin return Track.Points (1); end Start_Coord; function end_Coord (Track : Track_T) return Point is begin return Track.Points (Track.Points'Last); end end_Coord; end Tracks_Display;
with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line, Ada.Directories; procedure Global_Replace is subtype U_String is Ada.Strings.Unbounded.Unbounded_String; function "+"(S: String) return U_String renames Ada.Strings.Unbounded.To_Unbounded_String; function "-"(U: U_String) return String renames Ada.Strings.Unbounded.To_String; procedure String_Replace(S: in out U_String; Pattern, Replacement: String) is -- example: if S is "Mary had a XX lamb", then String_Replace(S, "X", "little"); -- will turn S into "Mary had a littlelittle lamb" -- and String_Replace(S, "Y", "small"); will not change S Index : Natural; begin loop Index := Ada.Strings.Unbounded.Index(Source => S, Pattern => Pattern); exit when Index = 0; Ada.Strings.Unbounded.Replace_Slice (Source => S, Low => Index, High => Index+Pattern'Length-1, By => Replacement); end loop; end String_Replace; procedure File_Replace(Filename: String; Pattern, Replacement: String) is -- applies String_Rplace to each line in the file with the given Filename -- propagates any exceptions, when, e.g., the file does not exist I_File, O_File: Ada.Text_IO.File_Type; Line: U_String; Tmp_Name: String := Filename & ".tmp"; -- name of temporary file; if that file already exists, it will be overwritten begin Ada.Text_IO.Open(I_File, Ada.Text_IO.In_File, Filename); Ada.Text_IO.Create(O_File, Ada.Text_IO.Out_File, Tmp_Name); while not Ada.Text_IO.End_Of_File(I_File) loop Line := +Ada.Text_IO.Get_Line(I_File); String_Replace(Line, Pattern, Replacement); Ada.Text_IO.Put_Line(O_File, -Line); end loop; Ada.Text_IO.Close(I_File); Ada.Text_IO.Close(O_File); Ada.Directories.Delete_File(Filename); Ada.Directories.Rename(Old_Name => Tmp_Name, New_Name => Filename); end File_Replace; Pattern: String := Ada.Command_Line.Argument(1); Replacement: String := Ada.Command_Line.Argument(2); begin Ada.Text_IO.Put_Line("Replacing """ & Pattern & """ by """ & Replacement & """ in" & Integer'Image(Ada.Command_Line.Argument_Count - 2) & " files."); for I in 3 .. Ada.Command_Line.Argument_Count loop File_Replace(Ada.Command_Line.Argument(I), Pattern, Replacement); end loop; end Global_Replace;
-- { dg-do compile } -- { dg-options "-O" } with Unchecked_Conversion; with System; use System; with Opt58_Pkg; use Opt58_Pkg; procedure Opt58 is function Convert is new Unchecked_Conversion (Integer, Rec); Dword : Integer := 0; I : Small_Int := F1 (Convert (Dword)); begin if F2 (Null_Address, I = 0) then null; end if; end Opt58;
with Solve; use Solve; with Ada.Text_IO; use Ada.Text_IO; procedure Solve_Part_2 is Input_File : File_Type; A : Integer; B : Integer; C : Integer; Previous_Sum : Integer := 16#7FFF_FFFF#; Answer : Integer := 0; begin Open (Input_File, In_File, "input.txt"); A := Get_Line_Integer (Input_File); B := Get_Line_Integer (Input_File); C := Get_Line_Integer (Input_File); loop if A + B + C > Previous_Sum then Answer := Answer + 1; end if; exit when End_Of_File (Input_File); Previous_Sum := A + B + C; A := B; B := C; C := Get_Line_Integer (Input_File); end loop; Put ("ANSWER:" & Integer'Image (Answer)); New_Line; Close (Input_File); end Solve_Part_2;
-- -- Copyright (C) 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 Interfaces.C; use type Interfaces.C.long; package body HW.Time.Timer with Refined_State => (Timer_State => null, Abstract_Time => null) is CLOCK_MONOTONIC_RAW : constant := 4; subtype Clock_ID_T is Interfaces.C.int; subtype Time_T is Interfaces.C.long; type Struct_Timespec is record TV_Sec : aliased Time_T; TV_NSec : aliased Interfaces.C.long; end record; pragma Convention (C_Pass_By_Copy, Struct_Timespec); function Clock_Gettime (Clock_ID : Clock_ID_T; Timespec : access Struct_Timespec) return Interfaces.C.int; pragma Import (C, Clock_Gettime, "clock_gettime"); function Raw_Value_Min return T is Ignored : Interfaces.C.int; Timespec : aliased Struct_Timespec; begin Ignored := Clock_Gettime (CLOCK_MONOTONIC_RAW, Timespec'Access); return T (Timespec.TV_Sec * 1_000_000_000 + Timespec.TV_NSec); end Raw_Value_Min; function Raw_Value_Max return T is begin return Raw_Value_Min + 1; end Raw_Value_Max; function Hz return T is begin return 1_000_000_000; -- clock_gettime(2) is fixed to nanoseconds end Hz; end HW.Time.Timer;
with Interfaces.C.Strings, System; use type Interfaces.C.int, System.Address; package body FLTK.Widgets.Valuators.Value_Outputs is procedure value_output_set_draw_hook (W, D : in System.Address); pragma Import (C, value_output_set_draw_hook, "value_output_set_draw_hook"); pragma Inline (value_output_set_draw_hook); procedure value_output_set_handle_hook (W, H : in System.Address); pragma Import (C, value_output_set_handle_hook, "value_output_set_handle_hook"); pragma Inline (value_output_set_handle_hook); function new_fl_value_output (X, Y, W, H : in Interfaces.C.int; Text : in Interfaces.C.char_array) return System.Address; pragma Import (C, new_fl_value_output, "new_fl_value_output"); pragma Inline (new_fl_value_output); procedure free_fl_value_output (A : in System.Address); pragma Import (C, free_fl_value_output, "free_fl_value_output"); pragma Inline (free_fl_value_output); function fl_value_output_is_soft (A : in System.Address) return Interfaces.C.int; pragma Import (C, fl_value_output_is_soft, "fl_value_output_is_soft"); pragma Inline (fl_value_output_is_soft); procedure fl_value_output_set_soft (A : in System.Address; T : in Interfaces.C.int); pragma Import (C, fl_value_output_set_soft, "fl_value_output_set_soft"); pragma Inline (fl_value_output_set_soft); function fl_value_output_get_text_color (TD : in System.Address) return Interfaces.C.unsigned; pragma Import (C, fl_value_output_get_text_color, "fl_value_output_get_text_color"); pragma Inline (fl_value_output_get_text_color); procedure fl_value_output_set_text_color (TD : in System.Address; C : in Interfaces.C.unsigned); pragma Import (C, fl_value_output_set_text_color, "fl_value_output_set_text_color"); pragma Inline (fl_value_output_set_text_color); function fl_value_output_get_text_font (TD : in System.Address) return Interfaces.C.int; pragma Import (C, fl_value_output_get_text_font, "fl_value_output_get_text_font"); pragma Inline (fl_value_output_get_text_font); procedure fl_value_output_set_text_font (TD : in System.Address; F : in Interfaces.C.int); pragma Import (C, fl_value_output_set_text_font, "fl_value_output_set_text_font"); pragma Inline (fl_value_output_set_text_font); function fl_value_output_get_text_size (TD : in System.Address) return Interfaces.C.int; pragma Import (C, fl_value_output_get_text_size, "fl_value_output_get_text_size"); pragma Inline (fl_value_output_get_text_size); procedure fl_value_output_set_text_size (TD : in System.Address; S : in Interfaces.C.int); pragma Import (C, fl_value_output_set_text_size, "fl_value_output_set_text_size"); pragma Inline (fl_value_output_set_text_size); procedure fl_value_output_draw (W : in System.Address); pragma Import (C, fl_value_output_draw, "fl_value_output_draw"); pragma Inline (fl_value_output_draw); function fl_value_output_handle (W : in System.Address; E : in Interfaces.C.int) return Interfaces.C.int; pragma Import (C, fl_value_output_handle, "fl_value_output_handle"); pragma Inline (fl_value_output_handle); procedure Finalize (This : in out Value_Output) is begin if This.Void_Ptr /= System.Null_Address and then This in Value_Output'Class then free_fl_value_output (This.Void_Ptr); This.Void_Ptr := System.Null_Address; end if; Finalize (Valuator (This)); end Finalize; package body Forge is function Create (X, Y, W, H : in Integer; Text : in String) return Value_Output is begin return This : Value_Output do This.Void_Ptr := new_fl_value_output (Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H), Interfaces.C.To_C (Text)); fl_widget_set_user_data (This.Void_Ptr, Widget_Convert.To_Address (This'Unchecked_Access)); value_output_set_draw_hook (This.Void_Ptr, Draw_Hook'Address); value_output_set_handle_hook (This.Void_Ptr, Handle_Hook'Address); end return; end Create; end Forge; function Is_Soft (This : in Value_Output) return Boolean is begin return fl_value_output_is_soft (This.Void_Ptr) /= 0; end Is_Soft; procedure Set_Soft (This : in out Value_Output; To : in Boolean) is begin fl_value_output_set_soft (This.Void_Ptr, Boolean'Pos (To)); end Set_Soft; function Get_Text_Color (This : in Value_Output) return Color is begin return Color (fl_value_output_get_text_color (This.Void_Ptr)); end Get_Text_Color; procedure Set_Text_Color (This : in out Value_Output; Col : in Color) is begin fl_value_output_set_text_color (This.Void_Ptr, Interfaces.C.unsigned (Col)); end Set_Text_Color; function Get_Text_Font (This : in Value_Output) return Font_Kind is begin return Font_Kind'Val (fl_value_output_get_text_font (This.Void_Ptr)); end Get_Text_Font; procedure Set_Text_Font (This : in out Value_Output; Font : in Font_Kind) is begin fl_value_output_set_text_font (This.Void_Ptr, Font_Kind'Pos (Font)); end Set_Text_Font; function Get_Text_Size (This : in Value_Output) return Font_Size is begin return Font_Size (fl_value_output_get_text_size (This.Void_Ptr)); end Get_Text_Size; procedure Set_Text_Size (This : in out Value_Output; Size : in Font_Size) is begin fl_value_output_set_text_size (This.Void_Ptr, Interfaces.C.int (Size)); end Set_Text_Size; procedure Draw (This : in out Value_Output) is begin fl_value_output_draw (This.Void_Ptr); end Draw; function Handle (This : in out Value_Output; Event : in Event_Kind) return Event_Outcome is begin return Event_Outcome'Val (fl_value_output_handle (This.Void_Ptr, Event_Kind'Pos (Event))); end Handle; end FLTK.Widgets.Valuators.Value_Outputs;
with Ada.Text_IO; with Ada.Integer_Text_IO; with Ada.Command_Line; with Ada.Strings.Fixed; procedure Recursion is use Ada.Strings.Fixed; Input, Cycles, Total, F: Integer; function Fib(P: Integer) return Integer is begin if P < 2 then return 1; else return Fib(P-1) + Fib(P-2); end if; end Fib; begin Input := Integer'Value(Ada.Command_Line.Argument(1)); Cycles := Integer'Value(Ada.Command_Line.Argument(2)); F := 0; Total := 0; for I in 0 .. Cycles loop F := Fib(Input); Total := Total + F; end loop; Ada.Text_IO.Put(Trim(Integer'Image(Input), Ada.Strings.Left)); Ada.Text_IO.Put("-th Fibonacci number is "); Ada.Text_IO.Put_Line(Trim(Integer'Image(F), Ada.Strings.Left)); Ada.Text_IO.Put("Total is "); Ada.Text_IO.Put_Line(Trim(Integer'Image(Total), Ada.Strings.Left)); end Recursion;
with Ada.Text_IO; use Ada.Text_IO; --with NRF52_DK.Time; --with NRF52_DK.IOs; use NRF52_DK.IOs; package Setup is protected Motor_Setup with Priority => 25 is procedure Calibrate_Motors_If_Required; private Setup_Done : Boolean := False; end Motor_Setup; end Setup;
------------------------------------------------------------------------------- -- Copyright (c) 2020 Daniel King -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- generic type Byte is mod <>; type Index is range <>; type Byte_Count is range <>; type Byte_Array is array (Index range <>) of Byte; package Generic_COBS with Pure, SPARK_Mode => On is pragma Compile_Time_Error (Byte'First /= 0, "Byte'First must be 0"); pragma Compile_Time_Error (Byte'Last <= 1, "Byte'Last must be greater than 1"); pragma Compile_Time_Error (Byte_Count'First /= 0, "Byte_Count'First must be 0"); pragma Compile_Time_Error (Byte_Count'Pos (Byte_Count'Last) /= Index'Pos (Index'Last), "Byte_Count'Last must be equal to Index'Last"); subtype Positive_Byte_Count is Byte_Count range 1 .. Byte_Count'Last; Frame_Delimiter : constant Byte := 0; -- COBS uses 0 as the frame delimiter byte. procedure Decode (Input : Byte_Array; Output : out Byte_Array; Length : out Byte_Count) with Global => null, Relaxed_Initialization => Output, Pre => ( -- The bounds of the input arrays must not be large enough to -- cause a Constraint_Error when reading the 'Length attribute. Array_Length_Within_Bounds (Input'First, Input'Last) and then Array_Length_Within_Bounds (Output'First, Output'Last) -- Cannot decode an empty Input array. and then Input'Length > 0 -- The Output array must be large enough to store all of the -- decoded data. and then Output'Length >= Input'Length), Post => ( -- The decoded length does not exceed the length of -- either array parameter. Length <= Output'Length and then Length <= Input'Length -- Only the first 'Length' bytes of the Output are initialized. and then (for all I in 0 .. Length - 1 => Output (Output'First + Index'Base (I))'Initialized)), Annotate => (GNATProve, Terminating); -- Decodes a COBS-encoded byte array. -- -- @param Input The COBS encoded bytes to be decoded. This may or may not -- contain a frame delimiter (zero) byte. If a frame delimiter -- is present then this subprogram decodes bytes up to the -- frame delimiter. Otherwise, if no frame delimiter byte is -- present then the entire input array is decoded. -- -- @param Output The decoded bytes are written to the first "Length" bytes -- of this array. -- -- @param Length The length of the decoded frame is written here. procedure Encode (Input : Byte_Array; Output : out Byte_Array; Length : out Byte_Count) with Global => null, Relaxed_Initialization => Output, Pre => ( -- The bounds of the input arrays must not be large enough to -- cause a Constraint_Error when reading the 'Length attribute. Array_Length_Within_Bounds (Input'First, Input'Last) and then Array_Length_Within_Bounds (Output'First, Output'Last) -- The number of bytes to encode in the Input array must leave -- enough headroom for COBS overhead bytes plus frame delimiter. and then Input'Length <= (Positive_Byte_Count'Last - (Max_Overhead_Bytes (Positive_Byte_Count'Last) + 1)) -- Output array must be large enough to encode the Input array -- and the additional overhead bytes. and then Output'Length >= Input'Length + Max_Overhead_Bytes (Input'Length) + 1), Post => ( -- The length of the output is always bigger than the input (Length in Input'Length + 1 .. Output'Length) -- Only the first 'Length' bytes of the Output are initialized. and then Output (Output'First .. Output'First + Index'Base (Length - 1))'Initialized -- The last byte in the output is a frame delimiter. -- All other bytes before the frame delimiter are non-zero. and then (for all I in Output'First .. Output'First + Index'Base (Length - 1) => (if I < Output'First + Index'Base (Length - 1) then Output (I) /= Frame_Delimiter else Output (I) = Frame_Delimiter))), Annotate => (GNATProve, Terminating); -- Encode a byte array. -- -- The contents of the "Input" array are encoded and written -- to the "Output" array, followed by a single frame delimiter. The length -- of the complete frame (including the frame delimiter) is output as the -- "Length" parameter. -- -- @param Input The bytes to encode. -- -- @param Output The COBS-encoded data is written to the first "Length" -- bytes of this array. The last byte is a frame delimiter. -- -- @param Length The length of the encoded frame is written here. function Max_Overhead_Bytes (Input_Length : Byte_Count) return Positive_Byte_Count with Global => null; -- Return the maximum number of overhead bytes that are inserted into -- the output during COBS encoding for a given input length. function Array_Length_Within_Bounds (First, Last : Index'Base) return Boolean is (Last < First or else First > 0 or else Last < First + Index (Byte_Count'Last)); -- Check that the length of the given range does not exceed Byte_Count'Last -- -- This check is equivalent to: (Last - First) + 1 <= Byte_Count'Last -- -- The purpose of this check is to ensure that we can take the 'Length -- of a Byte_Array without causing an integer overflow. Such an overflow -- could happen if the Index type is a signed integer. For example, -- consider the following concrete types: -- -- type Index is range -10 .. +10; -- subtype Byte_Count is Index range 0 .. Index'Last; -- -- With these types it is possible to construct a Byte_Array whose length -- is larger than Byte_Count'Last: -- -- Buffer : Byte_Array (-10 .. +10); -- -- The length of this array is 21 bytes, which does not fit in Byte_Count. -- -- This check constrains the range of the Byte_Array object's range such -- that the maximum length does not exceed 10. For example: -- Buffer_1 : Byte_Array (-10 .. 10); -- Not OK, 'Length = 21 -- Buffer_2 : Byte_Array ( 1 .. 10); -- OK, 'Length = 10 -- Buffer_3 : Byte_Array ( 0 .. 10); -- Not OK, 'Length = 11 -- BUffer_4 : Byte_Array ( 0 .. 9); -- OK, 'Length = 10 -- Buffer_5 : Byte_Array ( -5 .. -1); -- OK, 'Length = 5 private Maximum_Run_Length : constant Byte_Count := Byte_Count (Byte'Last - 1); -- Maximum run of non-zero bytes before an overhead byte is added. -- -- COBS specifies that data is grouped into either 254 non-zero bytes, -- or 0-253 non-zero bytes followed by a zero byte. The 254 byte case -- allows for the trailing zero byte to be omitted, but for simplicity -- this case is not implemented in our encoder (but is supported by -- the decoder). function Max_Overhead_Bytes (Input_Length : Byte_Count) return Positive_Byte_Count is ((Input_Length / Maximum_Run_Length) + 1); procedure Encode_Block (Input : Byte_Array; Output : out Byte_Array; Length : out Byte_Count) with Inline, Global => null, Relaxed_Initialization => Output, Pre => (Array_Length_Within_Bounds (Input'First, Input'Last) and then Array_Length_Within_Bounds (Output'First, Output'Last) and then Output'Length > Input'Length), Post => (Length <= Input'Length + 1 and then (if Length < Input'Length + 1 then Length >= Maximum_Run_Length + 1) and then Output (Output'First .. Output'First + Index'Base (Length - 1))'Initialized and then (for all I in Output'First .. Output'First + Index'Base (Length - 1) => Output (I) /= Frame_Delimiter)), Annotate => (GNATProve, Terminating); -- Encodes a single block of bytes. -- -- This prepends one overhead byte, then encodes as many bytes as possible -- until another overhead byte is needed. Another overhead byte is needed -- when another full run of Maximum_Run_Length non-zero bytes is reached. end Generic_COBS;
----------------------------------------------------------------------- -- package body Chebychev_Quadrature. Coefficients for Chebychev-Gaussian quadrature. -- 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 Chebychev_Quadrature is Pii : constant := 3.14159_26535_89793_23846_26433_83279_50288_41971_694; Gauss_Root : Gauss_Values := (others => 0.0); Gauss_Weight : Gauss_Values := (others => 0.0); -- Arrays initialized after the "begin" below. --------------------------- -- Construct_Gauss_Roots -- --------------------------- procedure Construct_Gauss_Roots is Factor : constant Real := Pii / Real (Gauss_Index'Last); begin for i in Gauss_Index loop Gauss_Root (i) := -Cos (Factor * (Real (i) - 0.5)); end loop; end Construct_Gauss_Roots; ----------------------------- -- Construct_Gauss_Weights -- ----------------------------- procedure Construct_Gauss_Weights is Factor : constant Real := Pii / Real (Gauss_Index'Last); begin for i in Gauss_Index loop Gauss_Weight (i) := 0.5 * Factor * Abs (Sin (Factor * (Real (i) - 0.5))); end loop; end Construct_Gauss_Weights; ---------------------- -- Find_Gauss_Nodes -- ---------------------- procedure Find_Gauss_Nodes (X_Starting : in Real; X_Final : in Real; X_gauss : out Gauss_Values) is Half_Delta_X : constant Real := (X_Final - X_Starting) * 0.5; X_Center : constant Real := X_Starting + Half_Delta_X; begin for i in Gauss_Index loop X_gauss(i) := X_Center + Gauss_Root(i) * Half_Delta_X; end loop; end Find_Gauss_Nodes; ------------------ -- Get_Integral -- ------------------ procedure Get_Integral (F_val : in Function_Values; X_Starting : in Real; X_Final : in Real; Area : out Real) is Sum : Real; Delta_X : constant Real := (X_Final - X_Starting); begin Area := 0.0; Sum := 0.0; for i in Gauss_Index loop Sum := Sum + Gauss_Weight (i) * F_val (i); end loop; Area := Sum * Delta_X; end Get_Integral; begin Construct_Gauss_Roots; Construct_Gauss_Weights; end Chebychev_Quadrature;
with GID.Buffering; with Ada.Exceptions; package body GID.Color_tables is procedure Convert(c, d: in U8; rgb: out RGB_color) is begin rgb.red := (d and 127) / 4; rgb.green:= (d and 3) * 8 + c / 32; rgb.blue := c and 31; -- rgb.red := U8((U16(rgb.red ) * 255) / 31); rgb.green:= U8((U16(rgb.green) * 255) / 31); rgb.blue := U8((U16(rgb.blue ) * 255) / 31); end Convert; procedure Load_palette (image: in out Image_descriptor) is c, d: U8; use GID.Buffering; begin if image.palette = null then return; end if; declare palette: Color_table renames image.palette.all; begin for i in palette'Range loop case image.format is when BMP => -- order is BGRx U8'Read(image.stream, palette(i).blue); U8'Read(image.stream, palette(i).green); U8'Read(image.stream, palette(i).red); U8'Read(image.stream, c); -- x discarded when GIF | PNG => -- buffered; order is RGB Get_Byte(image.buffer, palette(i).red); Get_Byte(image.buffer, palette(i).green); Get_Byte(image.buffer, palette(i).blue); when TGA => case image.subformat_id is -- = palette's bit depth when 8 => -- Grey U8'Read(image.stream, c); palette(i).red := c; palette(i).green:= c; palette(i).blue := c; when 15 | 16 => -- RGB, 5 bit per channel U8'Read(image.stream, c); U8'Read(image.stream, d); Convert(c, d, palette(i)); when 24 | 32 => -- RGB | RGBA, 8 bit per channel U8'Read(image.stream, palette(i).blue); U8'Read(image.stream, palette(i).green); U8'Read(image.stream, palette(i).red); when others => null; end case; when others => Ada.Exceptions.Raise_Exception( unsupported_image_subformat'Identity, "Palette loading not implemented for " & Image_format_type'Image(image.format) ); end case; end loop; end; end Load_palette; end GID.Color_tables;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2018 onox <denkpadje@gmail.com> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- Based on Ada gem #97 [1] and #107 [2] -- -- [1] https://www.adacore.com/gems/gem-97-reference-counting-in-ada-part-1 -- [2] https://www.adacore.com/gems/gem-107-preventing-deallocation-for-reference-counted-types private with Ada.Finalization; private with Orka.Atomics; generic type Object_Type (<>) is limited private; type Object_Access is access Object_Type; with procedure Free_Object (Value : in out Object_Access); package Orka.Smart_Pointers is pragma Preelaborate; type Reference (Value : not null access Object_Type) is limited private with Implicit_Dereference => Value; type Constant_Reference (Value : not null access constant Object_Type) is limited private with Implicit_Dereference => Value; type Abstract_Pointer is abstract tagged private; function Is_Null (Object : Abstract_Pointer) return Boolean; function References (Object : Abstract_Pointer) return Natural with Pre => not Object.Is_Null; procedure Set (Object : in out Abstract_Pointer; Value : not null Object_Access) with Post => not Object.Is_Null and then Object.References = 1; type Mutable_Pointer is new Abstract_Pointer with private; function Get (Object : Mutable_Pointer) return Reference with Pre => not Object.Is_Null; type Pointer is new Abstract_Pointer with private; function Get (Object : Pointer) return Constant_Reference with Pre => not Object.Is_Null; private type Data_Record is limited record References : Atomics.Counter (Initial_Value => 1); Object : Object_Access; end record; type Data_Record_Access is access Data_Record; type Abstract_Pointer is abstract new Ada.Finalization.Controlled with record Data : Data_Record_Access; end record; overriding procedure Adjust (Object : in out Abstract_Pointer); overriding procedure Finalize (Object : in out Abstract_Pointer); type Mutable_Pointer is new Abstract_Pointer with null record; type Pointer is new Abstract_Pointer with null record; type Reference (Value : not null access Object_Type) is limited record Hold : Mutable_Pointer; end record; type Constant_Reference (Value : not null access constant Object_Type) is limited record Hold : Pointer; end record; end Orka.Smart_Pointers;
with Ada; with System.Address_To_Access_Conversions; with System.Address_To_Constant_Access_Conversions; with System.Address_To_Named_Access_Conversions; procedure addrconv is package AC1 is new System.Address_To_Access_Conversions (Integer); type TA is access all Integer; pragma No_Strict_Aliasing (TA); package AC2 is new System.Address_To_Named_Access_Conversions (Integer, TA); type TC is access constant Integer; pragma No_Strict_Aliasing (TC); package AC3 is new System.Address_To_Constant_Access_Conversions (Integer, TC); V : aliased Integer; V1 : AC1.Object_Pointer := AC1.To_Pointer (V'Address); V2 : TA := AC2.To_Pointer (V'Address); V3 : TC := AC3.To_Pointer (V'Address); pragma Suppress (Access_Check); begin V := 10; V1.all := V1.all + 10; V2.all := V2.all + 10; pragma Assert (V3.all = 30); pragma Debug (Ada.Debug.Put ("OK")); end addrconv;
with Ada.Text_IO; procedure Catamorphism is type Fun is access function (Left, Right: Natural) return Natural; type Arr is array(Natural range <>) of Natural; function Fold_Left (F: Fun; A: Arr) return Natural is Result: Natural := A(A'First); begin for I in A'First+1 .. A'Last loop Result := F(Result, A(I)); end loop; return Result; end Fold_Left; function Max (L, R: Natural) return Natural is (if L > R then L else R); function Min (L, R: Natural) return Natural is (if L < R then L else R); function Add (Left, Right: Natural) return Natural is (Left + Right); function Mul (Left, Right: Natural) return Natural is (Left * Right); package NIO is new Ada.Text_IO.Integer_IO(Natural); begin NIO.Put(Fold_Left(Min'Access, (1,2,3,4)), Width => 3); NIO.Put(Fold_Left(Max'Access, (1,2,3,4)), Width => 3); NIO.Put(Fold_Left(Add'Access, (1,2,3,4)), Width => 3); NIO.Put(Fold_Left(Mul'Access, (1,2,3,4)), Width => 3); end Catamorphism;
with Ada.Text_IO, Ada.Float_Text_IO; procedure FindMedian is f: array(1..10) of float := ( 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5 ); min_idx: integer; min_val, median_val, swap: float; begin for i in f'range loop min_idx := i; min_val := f(i); for j in i+1 .. f'last loop if f(j) < min_val then min_idx := j; min_val := f(j); end if; end loop; swap := f(i); f(i) := f(min_idx); f(min_idx) := swap; end loop; if f'length mod 2 /= 0 then median_val := f( f'length/2+1 ); else median_val := ( f(f'length/2) + f(f'length/2+1) ) / 2.0; end if; Ada.Text_IO.Put( "Median value: " ); Ada.Float_Text_IO.Put( median_val ); Ada.Text_IO.New_line; end FindMedian;
with Interfaces.C.Strings, System; use type System.Address; package body FLTK.Widgets.Clocks is procedure clock_output_set_draw_hook (W, D : in System.Address); pragma Import (C, clock_output_set_draw_hook, "clock_output_set_draw_hook"); pragma Inline (clock_output_set_draw_hook); procedure clock_output_set_handle_hook (W, H : in System.Address); pragma Import (C, clock_output_set_handle_hook, "clock_output_set_handle_hook"); pragma Inline (clock_output_set_handle_hook); function new_fl_clock_output (X, Y, W, H : in Interfaces.C.int; Text : in Interfaces.C.char_array) return System.Address; pragma Import (C, new_fl_clock_output, "new_fl_clock_output"); pragma Inline (new_fl_clock_output); procedure free_fl_clock_output (F : in System.Address); pragma Import (C, free_fl_clock_output, "free_fl_clock_output"); pragma Inline (free_fl_clock_output); function fl_clock_output_get_hour (C : in System.Address) return Interfaces.C.int; pragma Import (C, fl_clock_output_get_hour, "fl_clock_output_get_hour"); pragma Inline (fl_clock_output_get_hour); function fl_clock_output_get_minute (C : in System.Address) return Interfaces.C.int; pragma Import (C, fl_clock_output_get_minute, "fl_clock_output_get_minute"); pragma Inline (fl_clock_output_get_minute); function fl_clock_output_get_second (C : in System.Address) return Interfaces.C.int; pragma Import (C, fl_clock_output_get_second, "fl_clock_output_get_second"); pragma Inline (fl_clock_output_get_second); function fl_clock_output_get_value (C : in System.Address) return Interfaces.C.unsigned_long; pragma Import (C, fl_clock_output_get_value, "fl_clock_output_get_value"); pragma Inline (fl_clock_output_get_value); procedure fl_clock_output_set_value (C : in System.Address; V : in Interfaces.C.unsigned_long); pragma Import (C, fl_clock_output_set_value, "fl_clock_output_set_value"); pragma Inline (fl_clock_output_set_value); procedure fl_clock_output_set_value2 (C : in System.Address; H, M, S : in Interfaces.C.int); pragma Import (C, fl_clock_output_set_value2, "fl_clock_output_set_value2"); pragma Inline (fl_clock_output_set_value2); procedure fl_clock_output_draw (W : in System.Address); pragma Import (C, fl_clock_output_draw, "fl_clock_output_draw"); pragma Inline (fl_clock_output_draw); procedure fl_clock_output_draw2 (C : in System.Address; X, Y, W, H : in Interfaces.C.int); pragma Import (C, fl_clock_output_draw2, "fl_clock_output_draw2"); pragma Inline (fl_clock_output_draw2); function fl_clock_output_handle (W : in System.Address; E : in Interfaces.C.int) return Interfaces.C.int; pragma Import (C, fl_clock_output_handle, "fl_clock_output_handle"); pragma Inline (fl_clock_output_handle); procedure Finalize (This : in out Clock) is begin if This.Void_Ptr /= System.Null_Address and then This in Clock'Class then free_fl_clock_output (This.Void_Ptr); This.Void_Ptr := System.Null_Address; end if; Finalize (Widget (This)); end Finalize; package body Forge is function Create (X, Y, W, H : in Integer; Text : in String) return Clock is begin return This : Clock do This.Void_Ptr := new_fl_clock_output (Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H), Interfaces.C.To_C (Text)); fl_widget_set_user_data (This.Void_Ptr, Widget_Convert.To_Address (This'Unchecked_Access)); clock_output_set_draw_hook (This.Void_Ptr, Draw_Hook'Address); clock_output_set_handle_hook (This.Void_Ptr, Handle_Hook'Address); end return; end Create; end Forge; function Get_Hour (This : in Clock) return Hour is begin return Hour (fl_clock_output_get_hour (This.Void_Ptr)); end Get_Hour; function Get_Minute (This : in Clock) return Minute is begin return Minute (fl_clock_output_get_minute (This.Void_Ptr)); end Get_Minute; function Get_Second (This : in Clock) return Second is begin return Second (fl_clock_output_get_second (This.Void_Ptr)); end Get_Second; function Get_Time (This : in Clock) return Time_Value is begin return Time_Value (fl_clock_output_get_value (This.Void_Ptr)); end Get_Time; procedure Set_Time (This : in out Clock; To : in Time_Value) is begin fl_clock_output_set_value (This.Void_Ptr, Interfaces.C.unsigned_long (To)); end Set_Time; procedure Set_Time (This : in out Clock; Hours : in Hour; Minutes : in Minute; Seconds : in Second) is begin fl_clock_output_set_value2 (This.Void_Ptr, Interfaces.C.int (Hours), Interfaces.C.int (Minutes), Interfaces.C.int (Seconds)); end Set_Time; procedure Draw (This : in out Clock) is begin fl_clock_output_draw (This.Void_Ptr); end Draw; procedure Draw (This : in out Clock; X, Y, W, H : in Integer) is begin fl_clock_output_draw2 (This.Void_Ptr, Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H)); end Draw; function Handle (This : in out Clock; Event : in Event_Kind) return Event_Outcome is begin return Event_Outcome'Val (fl_clock_output_handle (This.Void_Ptr, Event_Kind'Pos (Event))); end Handle; end FLTK.Widgets.Clocks;
-- { dg-do run } -- { dg-options "-gnatws" } with System; procedure Pack11 is type R1 is record A1, A2, A3 : System.Address; end record; type R2 is record C : Character; R : R1; end record; pragma Pack (R2); procedure Dummy (R : R1) is begin null; end; procedure Init (X : R2) is begin Dummy (X.R); end; My_R2 : R2; begin Init (My_R2); end;
------------------------------------------------------------------------------ -- -- -- Modular Hash Infrastructure -- -- -- -- SHA2 (256) -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2019-2021, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Ensi Martini (ANNEXI-STRAYLINE) -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- -- -- * Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Interfaces; with Ada.Streams; package Modular_Hashing.SHA256 is type SHA256_Hash is new Hash with private; -- The final hash is a 256-bit message digest, which can also be displayed -- as a 64 character hex string and is 32 bytes long overriding function "<" (Left, Right : SHA256_Hash) return Boolean; overriding function ">" (Left, Right : SHA256_Hash) return Boolean; overriding function "=" (Left, Right : SHA256_Hash) return Boolean; SHA256_Hash_Bytes: constant := 32; overriding function Binary_Bytes (Value: SHA256_Hash) return Positive is (SHA256_Hash_Bytes); overriding function Binary (Value: SHA256_Hash) return Hash_Binary_Value with Post => Binary'Result'Length = SHA256_Hash_Bytes; type SHA256_Engine is new Hash_Algorithm with private; overriding procedure Write (Stream : in out SHA256_Engine; Item : in Ada.Streams.Stream_Element_Array); overriding procedure Reset (Engine : in out SHA256_Engine); overriding function Digest (Engine : in out SHA256_Engine) return Hash'Class; private use Ada.Streams, Interfaces; type Message_Digest is array (1 .. 8) of Unsigned_32; type SHA256_Hash is new Hash with record Digest: Message_Digest; end record; ------------------- -- SHA256_Engine -- ------------------- -- SHA-2 Defined initialization constants H0_Initial: constant := 16#6a09e667#; H1_Initial: constant := 16#bb67ae85#; H2_Initial: constant := 16#3c6ef372#; H3_Initial: constant := 16#a54ff53a#; H4_Initial: constant := 16#510e527f#; H5_Initial: constant := 16#9b05688c#; H6_Initial: constant := 16#1f83d9ab#; H7_Initial: constant := 16#5be0cd19#; type K_Arr is array (1 .. 64) of Unsigned_32; K : constant K_Arr := (16#428a2f98#, 16#71374491#, 16#b5c0fbcf#, 16#e9b5dba5#, 16#3956c25b#, 16#59f111f1#, 16#923f82a4#, 16#ab1c5ed5#, 16#d807aa98#, 16#12835b01#, 16#243185be#, 16#550c7dc3#, 16#72be5d74#, 16#80deb1fe#, 16#9bdc06a7#, 16#c19bf174#, 16#e49b69c1#, 16#efbe4786#, 16#0fc19dc6#, 16#240ca1cc#, 16#2de92c6f#, 16#4a7484aa#, 16#5cb0a9dc#, 16#76f988da#, 16#983e5152#, 16#a831c66d#, 16#b00327c8#, 16#bf597fc7#, 16#c6e00bf3#, 16#d5a79147#, 16#06ca6351#, 16#14292967#, 16#27b70a85#, 16#2e1b2138#, 16#4d2c6dfc#, 16#53380d13#, 16#650a7354#, 16#766a0abb#, 16#81c2c92e#, 16#92722c85#, 16#a2bfe8a1#, 16#a81a664b#, 16#c24b8b70#, 16#c76c51a3#, 16#d192e819#, 16#d6990624#, 16#f40e3585#, 16#106aa070#, 16#19a4c116#, 16#1e376c08#, 16#2748774c#, 16#34b0bcb5#, 16#391c0cb3#, 16#4ed8aa4a#, 16#5b9cca4f#, 16#682e6ff3#, 16#748f82ee#, 16#78a5636f#, 16#84c87814#, 16#8cc70208#, 16#90befffa#, 16#a4506ceb#, 16#bef9a3f7#, 16#c67178f2#); type SHA256_Engine is new Hash_Algorithm with record Last_Element_Index : Stream_Element_Offset := 0; Buffer : Stream_Element_Array(1 .. 64); Message_Length : Unsigned_64 := 0; H0 : Unsigned_32 := H0_Initial; H1 : Unsigned_32 := H1_Initial; H2 : Unsigned_32 := H2_Initial; H3 : Unsigned_32 := H3_Initial; H4 : Unsigned_32 := H4_Initial; H5 : Unsigned_32 := H5_Initial; H6 : Unsigned_32 := H6_Initial; H7 : Unsigned_32 := H7_Initial; end record; end Modular_Hashing.SHA256;
with Tkmrpc.Types; with Tkmrpc.Operations.Cfg; package Tkmrpc.Response.Cfg.Tkm_Limits is Data_Size : constant := 132; type Data_Type is record Max_Active_Requests : Types.Active_Requests_Type; Authag_Contexts : Types.Authag_Id_Type; Cag_Contexts : Types.Cag_Id_Type; Li_Contexts : Types.Li_Id_Type; Ri_Contexts : Types.Ri_Id_Type; Iag_Contexts : Types.Iag_Id_Type; Eag_Contexts : Types.Eag_Id_Type; Dhag_Contexts : Types.Dhag_Id_Type; Sp_Contexts : Types.Sp_Id_Type; Authp_Contexts : Types.Authp_Id_Type; Dhp_Contexts : Types.Dhp_Id_Type; Autha_Contexts : Types.Autha_Id_Type; Ca_Contexts : Types.Ca_Id_Type; Lc_Contexts : Types.Lc_Id_Type; Ia_Contexts : Types.Ia_Id_Type; Ea_Contexts : Types.Ea_Id_Type; Dha_Contexts : Types.Dha_Id_Type; end record; for Data_Type use record Max_Active_Requests at 0 range 0 .. (8 * 8) - 1; Authag_Contexts at 8 range 0 .. (8 * 8) - 1; Cag_Contexts at 16 range 0 .. (8 * 8) - 1; Li_Contexts at 24 range 0 .. (8 * 8) - 1; Ri_Contexts at 32 range 0 .. (8 * 8) - 1; Iag_Contexts at 40 range 0 .. (8 * 8) - 1; Eag_Contexts at 48 range 0 .. (8 * 8) - 1; Dhag_Contexts at 56 range 0 .. (8 * 8) - 1; Sp_Contexts at 64 range 0 .. (4 * 8) - 1; Authp_Contexts at 68 range 0 .. (8 * 8) - 1; Dhp_Contexts at 76 range 0 .. (8 * 8) - 1; Autha_Contexts at 84 range 0 .. (8 * 8) - 1; Ca_Contexts at 92 range 0 .. (8 * 8) - 1; Lc_Contexts at 100 range 0 .. (8 * 8) - 1; Ia_Contexts at 108 range 0 .. (8 * 8) - 1; Ea_Contexts at 116 range 0 .. (8 * 8) - 1; Dha_Contexts at 124 range 0 .. (8 * 8) - 1; end record; for Data_Type'Size use Data_Size * 8; Padding_Size : constant := Response.Body_Size - Data_Size; subtype Padding_Range is Natural range 1 .. Padding_Size; subtype Padding_Type is Types.Byte_Sequence (Padding_Range); type Response_Type is record Header : Response.Header_Type; Data : Data_Type; Padding : Padding_Type; end record; for Response_Type use record Header at 0 range 0 .. (Response.Header_Size * 8) - 1; Data at Response.Header_Size range 0 .. (Data_Size * 8) - 1; Padding at Response.Header_Size + Data_Size range 0 .. (Padding_Size * 8) - 1; end record; for Response_Type'Size use Response.Response_Size * 8; Null_Response : constant Response_Type := Response_Type' (Header => Response.Header_Type'(Operation => Operations.Cfg.Tkm_Limits, Result => Results.Invalid_Operation, Request_Id => 0), Data => Data_Type'(Max_Active_Requests => Types.Active_Requests_Type'First, Authag_Contexts => Types.Authag_Id_Type'First, Cag_Contexts => Types.Cag_Id_Type'First, Li_Contexts => Types.Li_Id_Type'First, Ri_Contexts => Types.Ri_Id_Type'First, Iag_Contexts => Types.Iag_Id_Type'First, Eag_Contexts => Types.Eag_Id_Type'First, Dhag_Contexts => Types.Dhag_Id_Type'First, Sp_Contexts => Types.Sp_Id_Type'First, Authp_Contexts => Types.Authp_Id_Type'First, Dhp_Contexts => Types.Dhp_Id_Type'First, Autha_Contexts => Types.Autha_Id_Type'First, Ca_Contexts => Types.Ca_Id_Type'First, Lc_Contexts => Types.Lc_Id_Type'First, Ia_Contexts => Types.Ia_Id_Type'First, Ea_Contexts => Types.Ea_Id_Type'First, Dha_Contexts => Types.Dha_Id_Type'First), Padding => Padding_Type'(others => 0)); end Tkmrpc.Response.Cfg.Tkm_Limits;