repo_name
stringlengths
9
74
language
stringclasses
1 value
length_bytes
int64
11
9.34M
extension
stringclasses
2 values
content
stringlengths
11
9.34M
reznikmm/matreshka
Ada
4,267
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.DOM_Nodes; with XML.DOM.Elements.Internals; package body ODF.DOM.Elements.Text.Sequence_Decls.Internals is ------------ -- Create -- ------------ function Create (Node : Matreshka.ODF_Elements.Text.Sequence_Decls.Text_Sequence_Decls_Access) return ODF.DOM.Elements.Text.Sequence_Decls.ODF_Text_Sequence_Decls is begin return (XML.DOM.Elements.Internals.Create (Matreshka.DOM_Nodes.Element_Access (Node)) with null record); end Create; ---------- -- Wrap -- ---------- function Wrap (Node : Matreshka.ODF_Elements.Text.Sequence_Decls.Text_Sequence_Decls_Access) return ODF.DOM.Elements.Text.Sequence_Decls.ODF_Text_Sequence_Decls is begin return (XML.DOM.Elements.Internals.Wrap (Matreshka.DOM_Nodes.Element_Access (Node)) with null record); end Wrap; end ODF.DOM.Elements.Text.Sequence_Decls.Internals;
reznikmm/cvsweb2git
Ada
1,667
ads
-- BSD 3-Clause License -- -- Copyright (c) 2017, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- -- * Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- -- * Neither the name of the copyright holder nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -- THE POSSIBILITY OF SUCH DAMAGE. package CvsWeb is pragma Pure; end CvsWeb;
stcarrez/hyperion
Ada
3,338
adb
----------------------------------------------------------------------- -- hyperion-agents-beans -- Beans for module agents -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- 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 ASF.Events.Faces.Actions; package body Hyperion.Agents.Beans is -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Action (Bean : in out Agent_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Action; package Action_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Agent_Bean, Method => Action, Name => "action"); Agent_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (Action_Binding.Proxy'Access, null); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Agent_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Agent_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Agent_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Agent_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Agent_Bean bean instance. -- ------------------------------ function Create_Agent_Bean (Module : in Hyperion.Agents.Modules.Agent_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Agent_Bean_Access := new Agent_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Agent_Bean; end Hyperion.Agents.Beans;
AdaCore/training_material
Ada
843
ads
pragma Unevaluated_Use_Of_Old (Allow); package Basics is type Rec (Disc : Boolean := False) is record case Disc is when True => A : Integer; when False => B : Integer; end case; end record; type Index is range 1 .. 10; type Table is array (Index range <>) of Integer; procedure Swap (X, Y : in out Integer); The_Rec : Rec; The_Table : Table (1 .. 10); function Value_Rec (R : Rec) return Integer is (if R.Disc then R.A else R.B); procedure Bump_Rec (R : in out Rec); procedure Swap_Table (T : in out Table; I, J : Index); procedure Bump_The_Rec; procedure Swap_The_Table (I, J : Index); procedure Init_Rec (R : out Rec); procedure Init_Table (T : out Table); procedure Init_The_Rec; procedure Init_The_Table; end Basics;
mfkiwl/ewok-kernel-security-OS
Ada
3,131
adb
-- -- Copyright 2018 The wookey project team <[email protected]> -- - 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. -- -- package body soc.nvic with spark_mode => on is function to_irq_number (intr : soc.interrupts.t_interrupt) return t_irq_index is begin return t_irq_index'val (soc.interrupts.t_interrupt'pos (intr) - 16); end to_irq_number; procedure enable_irq (irq : in t_irq_index) is begin case irq is -- NOTE: Rather cumbersome but implied by SPARK verifications when 0 .. 31 => -- NVIC.ISER0.irq(irq) := IRQ_ENABLED; declare irq_states : t_irq_states (0 .. 31) := NVIC.ISER0.irq; begin irq_states(irq) := IRQ_ENABLED; NVIC.ISER0.irq := irq_states; end; when 32 .. 63 =>-- NVIC.ISER1.irq(irq) := IRQ_ENABLED; declare irq_states : t_irq_states (32 .. 63) := NVIC.ISER1.irq; begin irq_states(irq) := IRQ_ENABLED; NVIC.ISER1.irq := irq_states; end; when 64 .. 90 =>-- NVIC.ISER2.irq(irq) := IRQ_ENABLED; declare irq_states : t_irq_states (64 .. 90) := NVIC.ISER2.irq; begin irq_states(irq) := IRQ_ENABLED; NVIC.ISER2.irq := irq_states; end; end case; end enable_irq; procedure clear_pending_irq (irq : in t_irq_index) is begin case irq is when 0 .. 31 => -- NVIC.ICPR0.irq(irq) := CLEAR_PENDING; declare irq_pendings : t_irq_pendings (0 .. 31) := NVIC.ICPR0.irq; begin irq_pendings(irq) := CLEAR_PENDING; NVIC.ICPR0.irq := irq_pendings; end; when 32 .. 63 => -- NVIC.ICPR1.irq(irq) := CLEAR_PENDING; declare irq_pendings : t_irq_pendings (32 .. 63) := NVIC.ICPR1.irq; begin irq_pendings(irq) := CLEAR_PENDING; NVIC.ICPR1.irq := irq_pendings; end; when 64 .. 90 => -- NVIC.ICPR2.irq(irq) := CLEAR_PENDING; declare irq_pendings : t_irq_pendings (64 .. 90) := NVIC.ICPR2.irq; begin irq_pendings(irq) := CLEAR_PENDING; NVIC.ICPR2.irq := irq_pendings; end; end case; end clear_pending_irq; end soc.nvic;
stcarrez/ada-security
Ada
10,812
adb
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Auth.OpenID; with Security.Auth.OAuth.Facebook; with Security.Auth.OAuth.Googleplus; with Security.Auth.OAuth.Yahoo; with Security.Auth.OAuth.Github; package body Security.Auth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth"); Def_Factory : Factory_Access := Default_Factory'Access; -- ------------------------------ -- Get the provider. -- ------------------------------ function Get_Provider (Assoc : in Association) return String is begin return To_String (Assoc.Provider); end Get_Provider; -- ------------------------------ -- Get the email address -- ------------------------------ function Get_Email (Auth : in Authentication) return String is begin return To_String (Auth.Email); end Get_Email; -- ------------------------------ -- Get the user first name. -- ------------------------------ function Get_First_Name (Auth : in Authentication) return String is begin return To_String (Auth.First_Name); end Get_First_Name; -- ------------------------------ -- Get the user last name. -- ------------------------------ function Get_Last_Name (Auth : in Authentication) return String is begin return To_String (Auth.Last_Name); end Get_Last_Name; -- ------------------------------ -- Get the user full name. -- ------------------------------ function Get_Full_Name (Auth : in Authentication) return String is begin return To_String (Auth.Full_Name); end Get_Full_Name; -- ------------------------------ -- Get the user identity. -- ------------------------------ function Get_Identity (Auth : in Authentication) return String is begin return To_String (Auth.Identity); end Get_Identity; -- ------------------------------ -- Get the user claimed identity. -- ------------------------------ function Get_Claimed_Id (Auth : in Authentication) return String is begin return To_String (Auth.Claimed_Id); end Get_Claimed_Id; -- ------------------------------ -- Get the user language. -- ------------------------------ function Get_Language (Auth : in Authentication) return String is begin return To_String (Auth.Language); end Get_Language; -- ------------------------------ -- Get the user country. -- ------------------------------ function Get_Country (Auth : in Authentication) return String is begin return To_String (Auth.Country); end Get_Country; -- ------------------------------ -- Get the result of the authentication. -- ------------------------------ function Get_Status (Auth : in Authentication) return Auth_Result is begin return Auth.Status; end Get_Status; -- ------------------------------ -- Default principal -- ------------------------------ -- ------------------------------ -- Get the principal name. -- ------------------------------ overriding function Get_Name (From : in Principal) return String is begin return Get_First_Name (From.Auth) & " " & Get_Last_Name (From.Auth); end Get_Name; -- ------------------------------ -- Get the user email address. -- ------------------------------ function Get_Email (From : in Principal) return String is begin return Get_Email (From.Auth); end Get_Email; -- ------------------------------ -- Get the authentication data. -- ------------------------------ function Get_Authentication (From : in Principal) return Authentication is begin return From.Auth; end Get_Authentication; -- ------------------------------ -- Create a principal with the given authentication results. -- ------------------------------ function Create_Principal (Auth : in Authentication) return Principal_Access is P : constant Principal_Access := new Principal; begin P.Auth := Auth; return P; end Create_Principal; -- ------------------------------ -- Default factory used by `Initialize`. It supports OpenID, Google, Facebook. -- ------------------------------ function Default_Factory (Provider : in String) return Manager_Access is begin if Provider = PROVIDER_OPENID then return new Security.Auth.OpenID.Manager; elsif Provider = PROVIDER_FACEBOOK then return new Security.Auth.OAuth.Facebook.Manager; elsif Provider = PROVIDER_GOOGLE_PLUS then return new Security.Auth.OAuth.Googleplus.Manager; elsif Provider = PROVIDER_YAHOO then return new Security.Auth.OAuth.Yahoo.Manager; elsif Provider = PROVIDER_GITHUB then return new Security.Auth.OAuth.Github.Manager; else Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; end Default_Factory; -- ------------------------------ -- Initialize the OpenID realm. -- ------------------------------ procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID) is begin Initialize (Realm, Params, Def_Factory, Name); end Initialize; procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Factory : not null access function (Name : in String) return Manager_Access; Name : in String := PROVIDER_OPENID) is Provider : constant String := Params.Get_Parameter ("auth.provider." & Name); Impl : constant Manager_Access := Factory (Provider); begin if Impl = null then Log.Error ("Authentication provider {0} not recognized", Provider); raise Service_Error with "Authentication provider not supported"; end if; Realm.Delegate := Impl; Impl.Initialize (Params, Name); Realm.Provider := To_Unbounded_String (Name); end Initialize; -- ------------------------------ -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) -- ------------------------------ procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point) is begin if Realm.Delegate /= null then Realm.Delegate.Discover (Name, Result); else -- Result.URL := Realm.Realm; Result.Alias := To_Unbounded_String (""); end if; end Discover; -- ------------------------------ -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) -- ------------------------------ procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association) is begin Result.Provider := Realm.Provider; if Realm.Delegate /= null then Realm.Delegate.Associate (OP, Result); end if; end Associate; -- ------------------------------ -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. -- ------------------------------ function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is begin if Realm.Delegate /= null then return Realm.Delegate.Get_Authentication_URL (OP, Assoc); else return To_String (OP.URL); end if; end Get_Authentication_URL; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String) is begin if Status /= AUTHENTICATED then Log.Error ("OpenID verification failed: {0}", Message); else Log.Info ("OpenID verification: {0}", Message); end if; Result.Status := Status; end Set_Result; -- ------------------------------ -- Verify the authentication result -- ------------------------------ procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is begin if Realm.Delegate /= null then Realm.Delegate.Verify (Assoc, Request, Result); else Set_Result (Result, SETUP_NEEDED, "Setup is needed"); end if; end Verify; function To_String (OP : End_Point) return String is begin return "openid://" & To_String (OP.URL); end To_String; function To_String (Assoc : Association) return String is begin return "session_type=" & To_String (Assoc.Session_Type) & "&assoc_type=" & To_String (Assoc.Assoc_Type) & "&assoc_handle=" & To_String (Assoc.Assoc_Handle) & "&mac_key=" & To_String (Assoc.Mac_Key); end To_String; -- ------------------------------ -- Set the default factory to use. -- ------------------------------ procedure Set_Default_Factory (Factory : in Factory_Access) is begin Def_Factory := Factory; end Set_Default_Factory; overriding procedure Finalize (Realm : in out Manager) is procedure Free is new Ada.Unchecked_Deallocation (Manager'Class, Manager_Access); begin Free (Realm.Delegate); end Finalize; end Security.Auth;
Blady-Com/Gate3
Ada
1,325
ads
----------------------------------------------------------------------------- -- Legal licensing note : !!! Edit the file gate3_license.txt !!! -- -- Copyright (c) F. J. FABIEN - 2013 -- Berry -- FRANCE -- Send bug reports or feedback to : [email protected] -- -- 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. -- NB: this is the MIT License, as found 12-Sep-2007 on the site -- http://www.opensource.org/licenses/mit-license.php ----------------------------------------------------------------------------- with Gtkada.Builder; use Gtkada.Builder; package Window1_Callbacks is function On_Window1_Delete_Event (Builder : access Gtkada_Builder_Record'Class) return Boolean; procedure Gtk_Main_Quit (Builder : access Gtkada_Builder_Record'Class); procedure On_Button2_Clicked (Builder : access Gtkada_Builder_Record'Class); end Window1_Callbacks;
Ximalas/synth
Ada
33,897
adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Directories; with Ada.Text_IO; with Ada.Characters.Latin_1; with GNAT.OS_Lib; with Unix; package body Parameters is package AD renames Ada.Directories; package TIO renames Ada.Text_IO; package LAT renames Ada.Characters.Latin_1; package OSL renames GNAT.OS_Lib; -------------------------- -- load_configuration -- -------------------------- function load_configuration (num_cores : cpu_range) return Boolean is fields_present : Boolean; global_present : Boolean; sel_profile : JT.Text; begin if not AD.Exists (conf_location) then declare test : String := determine_portsdirs; begin if test = "" then return False; end if; end; declare File_Handle : TIO.File_Type; begin mkdirp_from_file (conf_location); TIO.Create (File => File_Handle, Mode => TIO.Out_File, Name => conf_location); TIO.Put_Line (File_Handle, "; This Synth configuration file is " & "automatically generated"); TIO.Put_Line (File_Handle, "; Take care when hand editing!"); TIO.Close (File => File_Handle); exception when Error : others => TIO.Put_Line ("Failed to create " & conf_location); return False; end; end if; internal_config.Init (File_Name => conf_location, On_Type_Mismatch => Config.Be_Quiet); if section_exists (master_section, global_01) then global_present := all_global_present; else write_blank_section (master_section); global_present := False; end if; declare envprofile : String := OSL.Getenv ("SYNTHPROFILE").all; begin sel_profile := extract_string (master_section, global_01, live_system); if envprofile /= "" then if section_exists (envprofile, Field_01) then sel_profile := JT.SUS (envprofile); end if; end if; end; declare profile : constant String := JT.USS (sel_profile); begin if section_exists (profile, Field_01) then fields_present := all_params_present (profile); else write_blank_section (section => profile); fields_present := False; end if; configuration := load_specific_profile (profile, num_cores); end; if not fields_present then write_configuration (JT.USS (configuration.profile)); end if; if not global_present then write_master_section; end if; return True; exception when mishap : others => return False; end load_configuration; --------------------------- -- determine_portsdirs -- --------------------------- function determine_portsdirs return String is function get_varname return String; function get_mkconf return String; function get_varname return String is begin case software_framework is when pkgsrc => return "PKGSRCDIR"; when ports_collection => return "PORTSDIR"; end case; end get_varname; function get_mkconf return String is begin case software_framework is when pkgsrc => return "mk.conf"; when ports_collection => return "/etc/make.conf"; end case; end get_mkconf; varname : constant String := get_varname; mkconf : constant String := get_mkconf; begin -- PORTSDIR in environment takes precedence declare portsdir : String := OSL.Getenv (varname).all; begin if portsdir /= "" then if AD.Exists (portsdir) then return portsdir; end if; end if; end; case software_framework is when pkgsrc => if AD.Exists (std_pkgsrc_loc & "/mk/pkgformat/pkgng") then return std_pkgsrc_loc; end if; when ports_collection => declare portsdir : String := query_portsdir; begin if portsdir = "" then TIO.Put_Line ("It seems that a blank " & varname & " is defined in " & mkconf); return ""; end if; if AD.Exists (portsdir) then return portsdir; end if; end; if AD.Exists (std_dports_loc) then return std_dports_loc; elsif AD.Exists (std_ports_loc) then return std_ports_loc; end if; end case; TIO.Put_Line (varname & " cannot be determined."); TIO.Put_Line ("Please set " & varname & " to a valid path in the environment or " & mkconf); return ""; end determine_portsdirs; ----------------------------- -- load_specific_profile -- ----------------------------- function load_specific_profile (profile : String; num_cores : cpu_range) return configuration_record is function opsys_ok return Boolean; def_builders : Integer; def_jlimit : Integer; res : configuration_record; function opsys_ok return Boolean is begin case software_framework is when ports_collection => return (JT.equivalent (res.operating_sys, "FreeBSD") or else JT.equivalent (res.operating_sys, "DragonFly")); when pkgsrc => -- OpenBSD and derivatives are not supported because they lack mount_null (!) return (JT.equivalent (res.operating_sys, "FreeBSD") or else JT.equivalent (res.operating_sys, "DragonFly") or else JT.equivalent (res.operating_sys, "NetBSD") or else JT.equivalent (res.operating_sys, "Linux") or else JT.equivalent (res.operating_sys, "SunOS") ); end case; end opsys_ok; begin -- The profile *must* exist before this procedure is called! default_parallelism (num_cores => num_cores, num_builders => def_builders, jobs_per_builder => def_jlimit); res.dir_packages := extract_string (profile, Field_01, LS_Packages); if param_set (profile, Field_03) then -- We can only check determine_portsdirs when no synth.ini file -- exists. It's possible that it was configured with PORTSDIR -- set which can be removed later. Use the dummy std_ports_loc -- when we are sure the parameter is set (so dummy will NOT be used) res.dir_portsdir := extract_string (profile, Field_03, std_ports_loc); else res.dir_portsdir := extract_string (profile, Field_03, determine_portsdirs); end if; res.dir_repository := res.dir_packages; JT.SU.Append (res.dir_repository, "/All"); if param_set (profile, Field_04) then res.dir_distfiles := extract_string (profile, Field_04, std_distfiles); else res.dir_distfiles := extract_string (profile, Field_04, query_distfiles (JT.USS (res.dir_portsdir))); end if; res.dir_buildbase := extract_string (profile, Field_05, LS_Buildbase); res.dir_logs := extract_string (profile, Field_06, LS_Logs); res.dir_ccache := extract_string (profile, Field_07, no_ccache); res.num_builders := builders (extract_integer (profile, Field_08, def_builders)); res.jobs_limit := builders (extract_integer (profile, Field_09, def_jlimit)); if param_set (profile, Field_12) then res.operating_sys := extract_string (profile, Field_12, std_opsys); else res.operating_sys := extract_string (profile, Field_12, query_opsys (JT.USS (res.dir_portsdir))); end if; if not opsys_ok then TIO.Put_Line ("Unknown operating system: " & JT.USS (res.operating_sys)); case software_framework is when ports_collection => TIO.Put_Line ("This configuration entry must be either 'FreeBSD' or 'DragonFly'"); when pkgsrc => TIO.Put_Line ("This configuration entry must be one of: FreeBSD,DragonFly," & "NetBSD,Linux,SunOS"); end case; TIO.Put_Line ("Manually edit " & Definitions.host_localbase & "/etc/synth/synth.ini file to remove the line of the"); TIO.Put_Line (profile & " profile starting with 'Operating_system='"); TIO.Put_Line ("The synth.ini file should regenerate properly on the next Synth command."); TIO.Put_Line (""); raise bad_opsys; end if; if param_set (profile, Field_10) then res.tmpfs_workdir := extract_boolean (profile, Field_10, False); else res.tmpfs_workdir := extract_boolean (profile, Field_10, enough_memory (res.num_builders, res.operating_sys)); end if; if param_set (profile, Field_11) then res.tmpfs_localbase := extract_boolean (profile, Field_11, False); else res.tmpfs_localbase := extract_boolean (profile, Field_11, enough_memory (res.num_builders, res.operating_sys)); end if; res.dir_options := extract_string (profile, Field_13, std_options); res.dir_system := extract_string (profile, Field_14, std_sysbase); res.avec_ncurses := extract_boolean (profile, Field_15, True); res.defer_prebuilt := extract_boolean (profile, Field_16, False); res.profile := JT.SUS (profile); return res; end load_specific_profile; --------------------------- -- write_configuration -- --------------------------- procedure write_configuration (profile : String := live_system) is contents : String := generated_section; begin internal_config.Replace_Section (profile, contents); exception when Error : others => raise update_config with "Failed to update [" & profile & "] at " & conf_location; end write_configuration; --------------------------- -- write_blank_section -- --------------------------- procedure write_blank_section (section : String) is File_Handle : TIO.File_Type; begin TIO.Open (File => File_Handle, Mode => TIO.Append_File, Name => conf_location); TIO.Put_Line (File_Handle, ""); TIO.Put_Line (File_Handle, "[" & section & "]"); TIO.Close (File_Handle); exception when Error : others => raise update_config with "Failed to append [" & section & "] at " & conf_location; end write_blank_section; --------------------------- -- default_parallelism -- --------------------------- procedure default_parallelism (num_cores : cpu_range; num_builders : out Integer; jobs_per_builder : out Integer) is begin case num_cores is when 1 => num_builders := 1; jobs_per_builder := 1; when 2 | 3 => num_builders := 2; jobs_per_builder := 2; when 4 | 5 => num_builders := 3; jobs_per_builder := 3; when 6 | 7 => num_builders := 4; jobs_per_builder := 3; when 8 | 9 => num_builders := 6; jobs_per_builder := 4; when 10 | 11 => num_builders := 8; jobs_per_builder := 4; when others => num_builders := (Integer (num_cores) * 3) / 4; jobs_per_builder := 5; end case; end default_parallelism; ---------------------- -- extract_string -- ---------------------- function extract_string (profile, mark, default : String) return JT.Text is begin return JT.SUS (internal_config.Value_Of (profile, mark, default)); end extract_string; ----------------------- -- extract_boolean -- ----------------------- function extract_boolean (profile, mark : String; default : Boolean) return Boolean is begin return internal_config.Value_Of (profile, mark, default); end extract_boolean; ----------------------- -- extract_integer -- ----------------------- function extract_integer (profile, mark : String; default : Integer) return Integer is begin return internal_config.Value_Of (profile, mark, default); end extract_integer; ----------------- -- param_set -- ----------------- function param_set (profile, field : String) return Boolean is garbage : constant String := "this-is-garbage"; begin return internal_config.Value_Of (profile, field, garbage) /= garbage; end param_set; ---------------------- -- section_exists -- ---------------------- function section_exists (profile, mark : String) return Boolean is begin return param_set (profile, mark); end section_exists; -------------------------- -- all_params_present -- -------------------------- function all_params_present (profile : String) return Boolean is begin return param_set (profile, Field_01) and then param_set (profile, Field_02) and then param_set (profile, Field_03) and then param_set (profile, Field_04) and then param_set (profile, Field_05) and then param_set (profile, Field_06) and then param_set (profile, Field_07) and then param_set (profile, Field_08) and then param_set (profile, Field_09) and then param_set (profile, Field_10) and then param_set (profile, Field_11) and then param_set (profile, Field_12) and then param_set (profile, Field_13) and then param_set (profile, Field_14) and then param_set (profile, Field_15) and then param_set (profile, Field_16); end all_params_present; -------------------------- -- all_global_present -- -------------------------- function all_global_present return Boolean is begin return param_set (master_section, global_01); end all_global_present; ------------------------- -- generated_section -- ------------------------- function generated_section return String is function USS (US : JT.Text) return String; function BDS (BD : builders) return String; function TFS (TF : Boolean) return String; function USS (US : JT.Text) return String is begin return "= " & JT.USS (US) & LAT.LF; end USS; function BDS (BD : builders) return String is BDI : constant String := Integer'Image (Integer (BD)); begin return LAT.Equals_Sign & BDI & LAT.LF; end BDS; function TFS (TF : Boolean) return String is begin if TF then return LAT.Equals_Sign & " true" & LAT.LF; else return LAT.Equals_Sign & " false" & LAT.LF; end if; end TFS; begin return Field_12 & USS (configuration.operating_sys) & Field_01 & USS (configuration.dir_packages) & Field_02 & USS (configuration.dir_repository) & Field_03 & USS (configuration.dir_portsdir) & Field_13 & USS (configuration.dir_options) & Field_04 & USS (configuration.dir_distfiles) & Field_05 & USS (configuration.dir_buildbase) & Field_06 & USS (configuration.dir_logs) & Field_07 & USS (configuration.dir_ccache) & Field_14 & USS (configuration.dir_system) & Field_08 & BDS (configuration.num_builders) & Field_09 & BDS (configuration.jobs_limit) & Field_10 & TFS (configuration.tmpfs_workdir) & Field_11 & TFS (configuration.tmpfs_localbase) & Field_15 & TFS (configuration.avec_ncurses) & Field_16 & TFS (configuration.defer_prebuilt); end generated_section; ----------------------- -- query_distfiles -- ----------------------- function query_distfiles (portsdir : String) return String is -- DISTDIR is used by both pkgsrc and ports collection begin return query_generic (portsdir, "DISTDIR"); end query_distfiles; ------------------ -- query_opsys -- ------------------- function query_opsys (portsdir : String) return String is -- OPSYS is used by both pkgsrc and ports collection begin return query_generic (portsdir, "OPSYS"); end query_opsys; --------------------- -- query_generic -- --------------------- function query_generic (portsdir, value : String) return String is -- devel/gmake exists on both pkgsrc and the ports collection -- The actual port is not significant command : constant String := host_make_program & " -C " & portsdir & "/devel/gmake .MAKE.EXPAND_VARIABLES=yes -V " & value; begin return query_generic_core (command); end query_generic; -------------------------- -- query_generic_core -- -------------------------- function query_generic_core (command : String) return String is content : JT.Text; status : Integer; CR_loc : Integer; CR : constant String (1 .. 1) := (1 => Character'Val (10)); begin content := Unix.piped_command (command, status); if status /= 0 then raise make_query with command; end if; CR_loc := JT.SU.Index (Source => content, Pattern => CR); return JT.SU.Slice (Source => content, Low => 1, High => CR_loc - 1); end query_generic_core; ---------------------- -- query_portsdir -- ---------------------- function query_portsdir return String is -- This is specific to the ports collection (invalid for pkgsrc) command : constant String := host_make_program & " -f /usr/share/mk/bsd.port.mk -V PORTSDIR"; begin return query_generic_core (command); exception when others => return ""; end query_portsdir; ----------------------------- -- query_physical_memory -- ----------------------------- procedure query_physical_memory is -- Works for *BSD, DragonFly, Bitrig -- DF/Free "hw.physmem: 8525971456" (8G) -- NetBSD "hw.physmem = 1073278976" (1G) command : constant String := "/sbin/sysctl hw.physmem"; content : JT.Text; status : Integer; begin memory_megs := 1024; content := Unix.piped_command (command, status); if status /= 0 then TIO.Put_Line ("command failed: " & command); return; end if; declare type styles is (unknown, dragonfly, netbsd); function get_number_string return String; style : styles := unknown; response : constant String := JT.USS (content) (1 .. JT.SU.Length (content) - 1); SP1 : constant String (1 .. 2) := (1 => LAT.Colon, 2 => LAT.Space); SP2 : constant String (1 .. 2) := (1 => LAT.Equals_Sign, 2 => LAT.Space); function get_number_string return String is begin case style is when dragonfly => return JT.part_2 (response, SP1); when netbsd => return JT.part_2 (response, SP2); when unknown => return "1073741824"; end case; end get_number_string; begin if JT.contains (response, SP1) then style := dragonfly; elsif JT.contains (response, SP2) then style := netbsd; else TIO.Put_Line ("Anomaly, unable to detect physical memory"); TIO.Put_Line (response); return; end if; declare type memtype is mod 2**64; numbers : String := get_number_string; bytes : constant memtype := memtype'Value (numbers); megs : constant memtype := bytes / 1024 / 1024; begin memory_megs := Natural (megs); end; end; end query_physical_memory; ----------------------------------- -- query_physical_memory_linux -- ----------------------------------- procedure query_physical_memory_linux is -- On linux, MemTotal should be on first line and that's what we're looking for command : constant String := "/usr/bin/head /proc/meminfo"; found : Boolean := False; status : Integer; comres : JT.Text; topline : JT.Text; crlen1 : Natural; crlen2 : Natural; begin comres := Unix.piped_command (command, status); if status /= 0 then raise make_query with command; end if; crlen1 := JT.SU.Length (comres); loop exit when found; JT.nextline (lineblock => comres, firstline => topline); crlen2 := JT.SU.Length (comres); exit when crlen1 = crlen2; crlen1 := crlen2; if JT.SU.Length (topline) > 12 then declare line : String := JT.USS (topline); begin if line (line'First .. line'First + 8) = "MemTotal:" then declare type memtype is mod 2**64; numbers : String := JT.part_1 (S => JT.trim (line (line'First + 9 .. line'Last)), separator => " "); kilobytes : constant memtype := memtype'Value (numbers); megs : constant memtype := kilobytes / 1024; begin memory_megs := Natural (megs); end; found := True; end if; end; end if; end loop; end query_physical_memory_linux; ----------------------------------- -- query_physical_memory_sunos -- ----------------------------------- procedure query_physical_memory_sunos is -- On Solaris, we're looking for "Memory size" which should be on second line command : constant String := "/usr/sbin/prtconf"; found : Boolean := False; status : Integer; comres : JT.Text; topline : JT.Text; crlen1 : Natural; crlen2 : Natural; begin comres := Unix.piped_command (command, status); if status /= 0 then raise make_query with command; end if; crlen1 := JT.SU.Length (comres); loop exit when found; JT.nextline (lineblock => comres, firstline => topline); crlen2 := JT.SU.Length (comres); exit when crlen1 = crlen2; crlen1 := crlen2; if JT.SU.Length (topline) > 12 then declare line : String := JT.USS (topline); begin if line (line'First .. line'First + 11) = "Memory size:" then declare type memtype is mod 2**64; numbers : String := JT.part_1 (line (line'First + 13 .. line'Last), " "); megabytes : constant memtype := memtype'Value (numbers); begin memory_megs := Natural (megabytes); end; found := True; end if; end; end if; end loop; end query_physical_memory_sunos; --------------------- -- enough_memory -- --------------------- function enough_memory (num_builders : builders; opsys : JT.Text) return Boolean is megs_per_slave : Natural; begin if memory_megs = 0 then if JT.equivalent (opsys, "Linux") then query_physical_memory_linux; elsif JT.equivalent (opsys, "SunOS") then query_physical_memory_sunos; else query_physical_memory; end if; end if; megs_per_slave := memory_megs / Positive (num_builders); return megs_per_slave >= 1280; end enough_memory; ---------------------------- -- write_master_section -- ---------------------------- procedure write_master_section is function USS (US : JT.Text) return String; function USS (US : JT.Text) return String is begin return "= " & JT.USS (US) & LAT.LF; end USS; contents : String := global_01 & USS (configuration.profile); begin internal_config.Replace_Section (master_section, contents); exception when Error : others => raise update_config with "Failed to update [" & master_section & "] at " & conf_location; end write_master_section; --------------------- -- sections_list -- --------------------- function sections_list return JT.Text is handle : TIO.File_Type; result : JT.Text; begin TIO.Open (File => handle, Mode => TIO.In_File, Name => conf_location); while not TIO.End_Of_File (handle) loop declare Line : String := TIO.Get_Line (handle); begin if Line'Length > 0 and then Line (1) = '[' and then Line /= "[" & master_section & "]" then JT.SU.Append (result, Line (2 .. Line'Last - 1) & LAT.LF); end if; end; end loop; TIO.Close (handle); return result; end sections_list; ----------------------- -- default_profile -- ----------------------- function default_profile (new_profile : String; num_cores : cpu_range) return configuration_record is result : configuration_record; def_builders : Integer; def_jlimit : Integer; begin default_parallelism (num_cores => num_cores, num_builders => def_builders, jobs_per_builder => def_jlimit); result.dir_portsdir := JT.SUS (std_ports_loc); result.operating_sys := JT.SUS (query_opsys (std_ports_loc)); result.profile := JT.SUS (new_profile); result.dir_system := JT.SUS (std_sysbase); result.dir_repository := JT.SUS (LS_Packages & "/All"); result.dir_packages := JT.SUS (LS_Packages); result.dir_distfiles := JT.SUS (std_distfiles); result.dir_buildbase := JT.SUS (LS_Buildbase); result.dir_logs := JT.SUS (LS_Logs); result.dir_ccache := JT.SUS (no_ccache); result.dir_options := JT.SUS (std_options); result.num_builders := builders (def_builders); result.jobs_limit := builders (def_jlimit); result.tmpfs_workdir := enough_memory (result.num_builders, result.operating_sys); result.tmpfs_localbase := enough_memory (result.num_builders, result.operating_sys); result.avec_ncurses := True; result.defer_prebuilt := False; write_blank_section (section => new_profile); return result; end default_profile; ------------------------ -- mkdirp_from_file -- ------------------------ procedure mkdirp_from_file (filename : String) is condir : String := AD.Containing_Directory (Name => filename); begin AD.Create_Path (New_Directory => condir); exception when others => raise update_config; end mkdirp_from_file; ----------------------- -- all_paths_valid -- ----------------------- function all_paths_valid return Boolean is use type AD.File_Kind; function invalid_directory (folder : JT.Text; desc : String) return Boolean; function invalid_directory (folder : JT.Text; desc : String) return Boolean is dossier : constant String := JT.USS (folder); errmsg : constant String := "Configuration invalid: "; begin if AD.Exists (dossier) and then AD.Kind (dossier) = AD.Directory then return False; else TIO.Put_Line (errmsg & desc & " directory: " & dossier); return True; end if; end invalid_directory; begin declare synth_tmp : constant String := "/var/synth"; begin if invalid_directory (JT.SUS (synth_tmp), "xxx") then if AD.Exists (synth_tmp) then AD.Delete_File (synth_tmp); end if; AD.Create_Path (New_Directory => synth_tmp); end if; exception when others => TIO.Put_Line ("Failed to create " & synth_tmp); return False; end; if invalid_directory (configuration.dir_system, "[G] System root") then return False; elsif invalid_directory (configuration.dir_packages, "[B] Packages") then return False; elsif invalid_directory (configuration.dir_portsdir, "[A] Ports") then return False; elsif invalid_directory (configuration.dir_distfiles, "[C] Distfiles") then if JT.equivalent (configuration.dir_distfiles, "/usr/ports/distfiles") then TIO.Put_Line ("Rather than manually creating a directory at this location, " & "consider" & LAT.LF & "using a location outside of the ports tree. Don't forget " & "to set" & LAT.LF & "'DISTDIR' to this new location in /etc/make.conf though."); end if; return False; elsif invalid_directory (configuration.dir_logs, "[E] Build logs") then return False; elsif invalid_directory (configuration.dir_options, "[D] Port options") then return False; end if; if JT.USS (configuration.dir_ccache) = no_ccache then return True; end if; return not invalid_directory (configuration.dir_ccache, "[H] Compiler cache"); end all_paths_valid; ---------------------- -- delete_profile -- ---------------------- procedure delete_profile (profile : String) is old_file : TIO.File_Type; new_file : TIO.File_Type; nextgen : constant String := synth_confdir & "/synth.ini.next"; pattern : constant String := "[" & profile & "]"; blocking : Boolean := False; begin if not AD.Exists (conf_location) then raise update_config with "The " & conf_location & " configuration file does not exist."; end if; -- Try to defend malicious symlink: https://en.wikipedia.org/wiki/Symlink_race if AD.Exists (nextgen) then AD.Delete_File (nextgen); end if; TIO.Create (File => new_file, Mode => TIO.Out_File, Name => nextgen); TIO.Open (File => old_file, Mode => TIO.In_File, Name => conf_location); while not TIO.End_Of_File (old_file) loop declare Line : constant String := TIO.Get_Line (old_file); bracket : Boolean := False; begin if not JT.IsBlank (Line) then bracket := Line (1) = '['; end if; if bracket and then blocking then blocking := False; end if; if not blocking and then Line = pattern then blocking := True; end if; if not blocking then TIO.Put_Line (new_file, Line); end if; end; end loop; TIO.Close (old_file); TIO.Close (new_file); AD.Delete_File (conf_location); AD.Rename (Old_Name => nextgen, New_Name => conf_location); exception when others => if TIO.Is_Open (new_file) then TIO.Close (new_file); end if; if AD.Exists (nextgen) then AD.Delete_File (nextgen); end if; if TIO.Is_Open (old_file) then TIO.Close (old_file); end if; raise update_config with "Failed to remove " & profile & " profile"; end delete_profile; ---------------------------------- -- alternative_profiles_exist -- ---------------------------------- function alternative_profiles_exist return Boolean is counter : Natural := 0; conf_file : TIO.File_Type; begin if not AD.Exists (conf_location) then return False; end if; TIO.Open (File => conf_file, Mode => TIO.In_File, Name => conf_location); while not TIO.End_Of_File (conf_file) loop declare Line : constant String := TIO.Get_Line (conf_file); bracket : Boolean := False; begin if not JT.IsBlank (Line) then bracket := Line (1) = '['; end if; if bracket and then Line /= "[" & master_section & "]" then counter := counter + 1; end if; end; end loop; TIO.Close (conf_file); return counter > 1; exception when others => if TIO.Is_Open (conf_file) then TIO.Close (conf_file); end if; return False; end alternative_profiles_exist; end Parameters;
Heziode/ada-dotenv
Ada
187
adb
with Ada.Text_IO; with Dotenv; package body Load_Environment_Variables is begin Ada.Text_IO.Put_Line ("Load Environment Variables"); Dotenv.Config; end Load_Environment_Variables;
egustafson/sandbox
Ada
6,109
adb
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Unchecked_Deallocation; use Ada.Text_IO, Ada.Integer_Text_IO; package body Int_Binary_Tree is type Compare_Result_Type is ( Less_Than, Equal, Greater_Than ); type Traced_Node_Type is record Node : Tree_Node_Ptr; Parent : Tree_Node_Ptr; end record; ---------------------------------------------------------------------- procedure Free is new Ada.Unchecked_Deallocation( Tree_Node, Tree_Node_Ptr ); ---------------------------------------------------------------------- function Compare( Left, Right : in Integer ) return Compare_Result_Type is begin if Left < Right then return Less_Than; elsif Left > Right then return Greater_Than; else return Equal; end if; end Compare; ---------------------------------------------------------------------- function Find_Node( Tree: in T; Number: in Integer ) return Traced_Node_Type is T_Node : Traced_Node_Type := Traced_Node_Type'( Node => Tree.Root, Parent => null ); Node : Tree_Node_Ptr renames T_Node.Node; Parent : Tree_Node_Ptr renames T_Node.Parent; begin while Node /= null loop case Compare ( Number, Node.Data ) is when Equal => return T_Node; when Less_Than => Parent := Node; Node := Node.Left; when Greater_Than => Parent := Node; Node := Node.Right; end case; end loop; return T_Node; end Find_Node; ---------------------------------------------------------------------- function Is_In_Tree( Tree: in T; Number: in Integer ) return Boolean is T_Node : Traced_Node_Type := Find_Node( Tree, Number ); begin if T_Node.Node /= null then return True; else return False; end if; end Is_In_Tree; ---------------------------------------------------------------------- procedure Insert( Tree: in out T; Number: in Integer ) is T_Node : Traced_Node_Type := Find_Node( Tree, Number ); New_Node : Tree_Node_Ptr := new Tree_Node'( Data => Number, Left => null, Right => null ); begin if T_Node.Node /= null then return; elsif T_Node.Parent = null then Tree.Root := New_Node; else case Compare( Number, T_Node.Parent.Data ) is when Less_Than => T_Node.Parent.Left := New_Node; when Greater_Than => T_Node.Parent.Right := New_Node; when Equal => null; end case; end if; end Insert; ---------------------------------------------------------------------- procedure Remove( Tree: in out T; Number: in Integer ) is Remove_Node : Traced_Node_Type := Find_Node( Tree, Number ); Pivot_Node : Tree_Node_Ptr; Pivot_Node_Parent : Tree_Node_Ptr; procedure Graft( Tree: in out T; Old_Node, New_Node, Parent: in out Tree_Node_Ptr ) is begin if Parent /= null then if Parent.Left = Old_Node then Parent.Left := New_Node; else Parent.Right := New_Node; end if; else Tree.Root := New_Node; end if; end Graft; begin if Remove_Node.Node = null then return; end if; if Remove_Node.Node.Left = null then Graft( Tree, Remove_Node.Node, Remove_Node.Node.Right, Remove_Node.Parent ); Free( Remove_Node.Node ); elsif Remove_Node.Node.Right = null then Graft( Tree, Remove_Node.Node, Remove_Node.Node.Left, Remove_Node.Parent ); Free( Remove_Node.Node ); else Pivot_Node_Parent := Remove_Node.Node; Pivot_Node := Remove_Node.Node.Left; while Pivot_Node.Right /= null loop Pivot_Node_Parent := Pivot_Node; Pivot_Node := Pivot_Node.Right; end loop; if Pivot_Node_Parent = Remove_Node.Node then Pivot_Node.Right := Remove_Node.Node.Right; else Pivot_Node_Parent.Right := Pivot_Node.Left; Pivot_Node.Left := Remove_Node.Node.Left; Pivot_Node.Right := Remove_Node.Node.Right; end if; Graft( Tree, Remove_Node.Node, Pivot_Node, Remove_Node.Parent ); end if; end Remove; ---------------------------------------------------------------------- procedure Print( Tree: in T ) is procedure Print_Node( Node: in Tree_Node_Ptr ) is begin if Node.Left /= null then Print_Node( Node.Left ); end if; Put(Node.Data); New_Line; if Node.Right /= null then Print_Node( Node.Right ); end if; end; begin Print_Node( Tree.Root ); end Print; ---------------------------------------------------------------------- procedure Debug_Print( Tree: in T ) is procedure Print_Node( Node: in Tree_Node_Ptr ) is procedure Print_Branch( Node: in Tree_Node_Ptr ) is begin if Node = null then Put(" null"); else Put(Node.Data); end if; end Print_Branch; begin if Node.Left /= null then Print_Node( Node.Left ); end if; Put(Node.Data); Put(" Left: "); Print_Branch(Node.Left); Put(" Right:"); Print_Branch(Node.Right); New_Line; if Node.Right /= null then Print_Node( Node.Right ); end if; end Print_Node; begin Print_Node( Tree.Root ); end Debug_Print; end Int_Binary_Tree;
reznikmm/matreshka
Ada
4,752
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Visitors; with ODF.DOM.Style_Footer_Style_Elements; package Matreshka.ODF_Style.Footer_Style_Elements is type Style_Footer_Style_Element_Node is new Matreshka.ODF_Style.Abstract_Style_Element_Node and ODF.DOM.Style_Footer_Style_Elements.ODF_Style_Footer_Style with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Style_Footer_Style_Element_Node; overriding function Get_Local_Name (Self : not null access constant Style_Footer_Style_Element_Node) return League.Strings.Universal_String; overriding procedure Enter_Node (Self : not null access Style_Footer_Style_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Leave_Node (Self : not null access Style_Footer_Style_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Visit_Node (Self : not null access Style_Footer_Style_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); end Matreshka.ODF_Style.Footer_Style_Elements;
fractal-mind/Amass
Ada
1,362
ads
-- Copyright © by Jeff Foley 2022. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. -- SPDX-License-Identifier: Apache-2.0 local json = require("json") name = "BeVigil" type = "api" function start() set_rate_limit(2) end function check() local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c ~= nil and c.key ~= nil and c.key ~= "") then return true end return false end function vertical(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end local resp, err = request(ctx, { url=build_url(domain), headers={ ['X-Access-Token']=c.key, ['User-Agent']="OWASP Amass" }, }) if (err ~= nil and err ~= "") then log(ctx, "vertical request to service failed: " .. err) return end local d = json.decode(resp) if (d == nil or d.subdomains == nil or #(d.subdomains) == 0) then return end for _, sub in pairs(d.subdomains) do new_name(ctx, sub) end end function build_url(domain) return "http://osint.bevigil.com/api/" .. domain .. "/subdomains/" end
AdaCore/langkit
Ada
1,613
adb
-- -- Copyright (C) 2014-2022, AdaCore -- SPDX-License-Identifier: Apache-2.0 -- with Ada.Containers.Vectors; package body Langkit_Support.Iterators is ------------- -- Iterate -- ------------- procedure Iterate (I : in out Iterator'Class; Proc : access procedure (Element : Element_Type)) is Element : Element_Type; begin while I.Next (Element) loop Proc (Element); end loop; end Iterate; ------------- -- Consume -- ------------- function Consume (I : Iterator'Class) return Element_Array is package Element_Vectors is new Ada.Containers.Vectors (Positive, Element_Type); Element : Element_Type; V : Element_Vectors.Vector; begin -- Note: This is bad design in Ada: We're hiding mutation of the -- Iterator object, because if we make it mutable, then you can no -- longer call consume on an expression that returns an Iterator, which -- in user APIs is not very friendly, because it means you cannot write -- write:: -- -- for Element of Node.Find (...).Consume loop -- ... -- end loop; -- -- You have to declare the iterator explicitly. while I'Unrestricted_Access.Next (Element) loop V.Append (Element); end loop; declare Result : Element_Array (1 .. Natural (V.Length)); begin for I in Result'Range loop Result (I) := V.Element (I); end loop; return Result; end; end Consume; end Langkit_Support.Iterators;
reznikmm/matreshka
Ada
5,394
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.Generic_Collections; package AMF.Standard_Profile_L2.Services.Collections is pragma Preelaborate; package Standard_Profile_L2_Service_Collections is new AMF.Generic_Collections (Standard_Profile_L2_Service, Standard_Profile_L2_Service_Access); type Set_Of_Standard_Profile_L2_Service is new Standard_Profile_L2_Service_Collections.Set with null record; Empty_Set_Of_Standard_Profile_L2_Service : constant Set_Of_Standard_Profile_L2_Service; type Ordered_Set_Of_Standard_Profile_L2_Service is new Standard_Profile_L2_Service_Collections.Ordered_Set with null record; Empty_Ordered_Set_Of_Standard_Profile_L2_Service : constant Ordered_Set_Of_Standard_Profile_L2_Service; type Bag_Of_Standard_Profile_L2_Service is new Standard_Profile_L2_Service_Collections.Bag with null record; Empty_Bag_Of_Standard_Profile_L2_Service : constant Bag_Of_Standard_Profile_L2_Service; type Sequence_Of_Standard_Profile_L2_Service is new Standard_Profile_L2_Service_Collections.Sequence with null record; Empty_Sequence_Of_Standard_Profile_L2_Service : constant Sequence_Of_Standard_Profile_L2_Service; private Empty_Set_Of_Standard_Profile_L2_Service : constant Set_Of_Standard_Profile_L2_Service := (Standard_Profile_L2_Service_Collections.Set with null record); Empty_Ordered_Set_Of_Standard_Profile_L2_Service : constant Ordered_Set_Of_Standard_Profile_L2_Service := (Standard_Profile_L2_Service_Collections.Ordered_Set with null record); Empty_Bag_Of_Standard_Profile_L2_Service : constant Bag_Of_Standard_Profile_L2_Service := (Standard_Profile_L2_Service_Collections.Bag with null record); Empty_Sequence_Of_Standard_Profile_L2_Service : constant Sequence_Of_Standard_Profile_L2_Service := (Standard_Profile_L2_Service_Collections.Sequence with null record); end AMF.Standard_Profile_L2.Services.Collections;
GauBen/Arbre-Genealogique
Ada
4,190
adb
with Ada.Unchecked_Deallocation; package body Registre is procedure Initialiser (Registre : out T_Registre) is begin Registre := (others => null); end Initialiser; function Hash (Cle : Integer) return Integer is begin return Cle mod Modulo; end Hash; function Est_Vide (Registre : T_Registre) return Boolean is begin for I in Registre'Range loop if Registre (I) /= null then return False; end if; end loop; return True; end Est_Vide; -- Renvoie vrai si la clé est presente dans le registre. function Existe (Registre : T_Registre; Cle : Integer) return Boolean is Pointeur : T_Pointeur_Sur_Maillon; begin Pointeur := Registre (Hash (Cle)); while Pointeur /= null loop if Pointeur.all.Cle = Cle then return True; end if; Pointeur := Pointeur.all.Suivant; end loop; return False; end Existe; procedure Attribuer (Registre : in out T_Registre; Cle : in Integer; Element : in T_Element) is Pointeur : T_Pointeur_Sur_Maillon; begin if Registre (Hash (Cle)) = null then Pointeur := new T_Maillon; Pointeur.all := (Cle, Element, null); Registre (Hash (Cle)) := Pointeur; else Pointeur := Registre (Hash (Cle)); while Pointeur.all.Suivant /= null loop if Pointeur.all.Cle = Cle then Pointeur.all.Element := Element; return; end if; Pointeur := Pointeur.all.Suivant; end loop; if Pointeur.all.Cle = Cle then Pointeur.all.Element := Element; else Pointeur.all.Suivant := new T_Maillon; Pointeur.all.Suivant.all := (Cle, Element, null); end if; end if; end Attribuer; function Acceder (Registre : T_Registre; Cle : Integer) return T_Element is Pointeur : T_Pointeur_Sur_Maillon; begin Pointeur := Registre (Hash (Cle)); while Pointeur /= null loop if Pointeur.all.Cle = Cle then return Pointeur.all.Element; end if; Pointeur := Pointeur.all.Suivant; end loop; raise Cle_Absente_Exception; end Acceder; procedure Appliquer_Sur_Tous (Registre : in T_Registre) is procedure Appliquer_Sur_Maillon (Pointeur : in T_Pointeur_Sur_Maillon) is begin if Pointeur /= null then P (Pointeur.all.Cle, Pointeur.all.Element); Appliquer_Sur_Maillon (Pointeur.all.Suivant); end if; end Appliquer_Sur_Maillon; begin for I in Registre'Range loop Appliquer_Sur_Maillon (Registre (I)); end loop; end Appliquer_Sur_Tous; procedure Desallouer_Maillon is new Ada.Unchecked_Deallocation (T_Maillon, T_Pointeur_Sur_Maillon); procedure Supprimer (Registre : in out T_Registre; Cle : in Integer) is Pointeur : T_Pointeur_Sur_Maillon; Ancien : T_Pointeur_Sur_Maillon; begin if Registre (Hash (Cle)) /= null then Pointeur := Registre (Hash (Cle)); if Pointeur.all.Cle = Cle then Registre (Hash (Cle)) := Pointeur.all.Suivant; Desallouer_Maillon (Pointeur); return; end if; while Pointeur.all.Suivant /= null loop if Pointeur.all.Suivant.all.Cle = Cle then Ancien := Pointeur.all.Suivant; Pointeur.all.Suivant := Pointeur.all.Suivant.all.Suivant; Desallouer_Maillon (Ancien); return; end if; Pointeur := Pointeur.all.Suivant; end loop; end if; end Supprimer; procedure Supprimer_Maillons (Pointeur : in out T_Pointeur_Sur_Maillon) is begin if Pointeur /= null then Supprimer_Maillons (Pointeur.all.Suivant); end if; Desallouer_Maillon (Pointeur); end Supprimer_Maillons; procedure Detruire (Registre : in out T_Registre) is begin for I in Registre'Range loop Supprimer_Maillons (Registre (I)); end loop; end Detruire; end Registre;
reznikmm/matreshka
Ada
4,673
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Visitors; with ODF.DOM.Form_Column_Elements; package Matreshka.ODF_Form.Column_Elements is type Form_Column_Element_Node is new Matreshka.ODF_Form.Abstract_Form_Element_Node and ODF.DOM.Form_Column_Elements.ODF_Form_Column with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Form_Column_Element_Node; overriding function Get_Local_Name (Self : not null access constant Form_Column_Element_Node) return League.Strings.Universal_String; overriding procedure Enter_Node (Self : not null access Form_Column_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Leave_Node (Self : not null access Form_Column_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Visit_Node (Self : not null access Form_Column_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); end Matreshka.ODF_Form.Column_Elements;
charlie5/cBound
Ada
1,610
ads
-- This file is generated by SWIG. Please do not modify by hand. -- with Interfaces; with Interfaces.C; with Interfaces.C.Pointers; package xcb.xcb_glx_get_doublev_request_t is -- Item -- type Item is record major_opcode : aliased Interfaces.Unsigned_8; minor_opcode : aliased Interfaces.Unsigned_8; length : aliased Interfaces.Unsigned_16; context_tag : aliased xcb.xcb_glx_context_tag_t; pname : aliased Interfaces.Unsigned_32; end record; -- Item_Array -- type Item_Array is array (Interfaces.C .size_t range <>) of aliased xcb.xcb_glx_get_doublev_request_t .Item; -- Pointer -- package C_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_glx_get_doublev_request_t.Item, Element_Array => xcb.xcb_glx_get_doublev_request_t.Item_Array, Default_Terminator => (others => <>)); subtype Pointer is C_Pointers.Pointer; -- Pointer_Array -- type Pointer_Array is array (Interfaces.C .size_t range <>) of aliased xcb.xcb_glx_get_doublev_request_t .Pointer; -- Pointer_Pointer -- package C_Pointer_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_glx_get_doublev_request_t.Pointer, Element_Array => xcb.xcb_glx_get_doublev_request_t.Pointer_Array, Default_Terminator => null); subtype Pointer_Pointer is C_Pointer_Pointers.Pointer; end xcb.xcb_glx_get_doublev_request_t;
stcarrez/ada-ado
Ada
1,641
adb
----------------------------------------------------------------------- -- ADO Databases -- Database Objects -- Copyright (C) 2009, 2010, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Testsuite; with ADO.Drivers; with Regtests; with Util.Tests; with Util.Properties; procedure ADO_Harness is procedure Initialize (Props : in Util.Properties.Manager); procedure Harness is new Util.Tests.Harness (ADO.Testsuite.Suite, Initialize); -- ------------------------------ -- Initialization procedure: setup the database -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager) is DB : constant String := Props.Get ("test.database", "sqlite:///regtests.db"); begin ADO.Drivers.Initialize (Props); Regtests.Initialize (DB); end Initialize; begin Harness ("ado-tests.xml"); end ADO_Harness;
godunko/adawebpack
Ada
4,053
ads
------------------------------------------------------------------------------ -- -- -- AdaWebPack -- -- -- ------------------------------------------------------------------------------ -- Copyright © 2022, Vadim Godunko -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- ------------------------------------------------------------------------------ with WASM.Objects; with WASM.Stringifiers; with Web.Strings; package Web.URL.URL_Search_Params is pragma Preelaborate; type URL_Search_Params is new WASM.Objects.Object_Reference and WASM.Stringifiers.Expose_Stringifier with null record; -- interface URLSearchParams { -- constructor(optional (sequence<sequence<USVString>> or record<USVString, USVString> or USVString) init = ""); -- -- undefined append(USVString name, USVString value); -- undefined delete(USVString name); -- sequence<USVString> getAll(USVString name); -- boolean has(USVString name); -- -- undefined sort(); -- -- iterable<USVString, USVString>; -- }; function Get (Self : URL_Search_Params'Class; Name : Web.Strings.Web_String) return Web.Strings.Web_String; procedure Set (Self : in out URL_Search_Params'Class; Name : Web.Strings.Web_String; Value : Web.Strings.Web_String); function Has (Self : URL_Search_Params'Class; Name : Web.Strings.Web_String) return Boolean; package Constructors is function New_URL_Search_Params return URL_Search_Params; function New_URL_Search_Params (Init : Web.Strings.Web_String) return URL_Search_Params; end Constructors; end Web.URL.URL_Search_Params;
reznikmm/matreshka
Ada
5,987
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- XML Processor -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2017, Vadim Godunko <[email protected]> -- -- 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 XML.SAX.Simple_Readers.Callbacks; package body XML.SAX.Simple_Readers.Analyzer is use Matreshka.Internals.XML; use Matreshka.Internals.XML.Element_Tables; use Matreshka.Internals.XML.Entity_Tables; --------------------------------------- -- Analyze_Document_Type_Declaration -- --------------------------------------- procedure Analyze_Document_Type_Declaration (Self : in out Simple_Reader'Class) is Current : Entity_Identifier; Current_Element : Element_Identifier; begin if Self.Validation.Enabled then Current := First_Entity (Self.Entities); while Current /= No_Entity loop -- [XML 4.2.2 VC: Notation Declared] -- -- "The Name MUST match the declared name of a notation." -- -- Check whether entity is unparsed and its notation is declared. if Is_External_Unparsed_General_Entity (Self.Entities, Current) and then Symbol_Tables.Notation (Self.Symbols, Notation (Self.Entities, Current)) = No_Notation then Callbacks.Call_Error (Self, League.Strings.To_Universal_String ("[XML 4.2.2 VC: Notation Declared]" & " notation name must match the declared name of a" & " notation")); end if; Next_Entity (Self.Entities, Current); end loop; end if; -- [XML 3.3] Attribute List Declaration -- -- "The Name in the AttlistDecl rule is the type of an element. At user -- option, an XML processor MAY issue a warning if attributes are -- declared for an element type not itself declared, but this is not an -- error. The Name in the AttDef rule is the name of the attribute." -- -- Check whether element is not declared and has declared attributes. Current_Element := First_Element (Self.Elements); while Current_Element /= No_Element loop if not Is_Declared (Self.Elements, Current_Element) and Is_Attributes_Declared (Self.Elements, Current_Element) then Callbacks.Call_Warning (Self, League.Strings.To_Universal_String ("[XML 3.3]" & " attribute list declaration for element type not itself" & " declared")); end if; Next_Element (Self.Elements, Current_Element); end loop; end Analyze_Document_Type_Declaration; end XML.SAX.Simple_Readers.Analyzer;
kraileth/ravenadm
Ada
125,597
adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt -- To enable ncurses support, use sed to change Options_Dialog_Console => Options_Dialog -- Also change Display.Console => Display.Curses with Unix; with Signals; with Replicant; with Ada.Exceptions; with Ada.Directories; with Ada.Characters.Latin_1; with PortScan.Log; with PortScan.Buildcycle; with Specification_Parser; with Port_Specification.Makefile; with Port_Specification.Transform; with INI_File_Manager; with Options_Dialog_Console; with Display.Console; package body PortScan.Operations is package EX renames Ada.Exceptions; package DIR renames Ada.Directories; package LAT renames Ada.Characters.Latin_1; package LOG renames PortScan.Log; package CYC renames PortScan.Buildcycle; package REP renames Replicant; package PAR renames Specification_Parser; package PSM renames Port_Specification.Makefile; package PST renames Port_Specification.Transform; package IFM renames INI_File_Manager; package DLG renames Options_Dialog_Console; package DPY renames Display; package DPC renames Display.Console; -------------------------------------------------------------------------------------------- -- parallel_bulk_run -------------------------------------------------------------------------------------------- procedure parallel_bulk_run (num_builders : builders; sysrootver : sysroot_characteristics) is subtype cycle_count is Natural range 1 .. 9; subtype refresh_count is Natural range 1 .. 4; subtype www_count is Natural range 1 .. 3; subtype alert_count is Natural range 1 .. 200; procedure text_display (builder : builders; info : String); procedure common_display (flavor : count_type; info : String); procedure slave_display (flavor : count_type; builder : builders; info : String); function slave_name (slave : builders) return String; function slave_bucket (slave : builders) return String; instructions : dim_instruction := (others => port_match_failed); builder_states : dim_builder_state := (others => idle); cntcycle : cycle_count := cycle_count'First; cntrefresh : refresh_count := refresh_count'First; cntalert : alert_count := alert_count'First; cntwww : www_count := www_count'First; run_complete : Boolean := False; available : Positive := Integer (num_builders); target : port_id; all_idle : Boolean; cntskip : Natural; sumdata : DPY.summary_rec; procedure text_display (builder : builders; info : String) is begin TIO.Put_Line (LOG.elapsed_now & " => [" & HT.zeropad (Integer (builder), 2) & "] " & info); end text_display; procedure slave_display (flavor : count_type; builder : builders; info : String) is slavid : constant String := HT.zeropad (Integer (builder), 2); begin LOG.scribe (flavor, LOG.elapsed_now & " [" & slavid & "] => " & info, False); end slave_display; procedure common_display (flavor : count_type; info : String) is begin LOG.scribe (flavor, LOG.elapsed_now & " " & info, False); end common_display; function slave_name (slave : builders) return String is begin return get_port_variant (instructions (slave)); end slave_name; function slave_bucket (slave : builders) return String is begin return get_bucket (instructions (slave)); end slave_bucket; task type build (builder : builders); task body build is build_result : Boolean; need_procfs : Boolean; begin if builder <= num_builders then if not curses_support then text_display (builder, "Builder launched"); end if; loop exit when builder_states (builder) = shutdown; if builder_states (builder) = tasked then builder_states (builder) := busy; need_procfs := all_ports (instructions (builder)).use_procfs; begin REP.launch_slave (builder, need_procfs); build_result := build_subpackages (builder, instructions (builder), sysrootver); exception when tremor : others => build_result := False; LOG.scribe (total, LOG.elapsed_now & " TASK" & builder'Img & " EXCEPTION: " & EX.Exception_Information (tremor), False); end; REP.destroy_slave (builder, need_procfs); if build_result then builder_states (builder) := done_success; else builder_states (builder) := done_failure; end if; else -- idle or done-(failure|success), just wait a bit delay 0.1; end if; end loop; if not curses_support then text_display (builder, " Shutting down"); end if; end if; exception when earthquake : others => LOG.scribe (total, LOG.elapsed_now & " UNHANDLED TASK" & builder'Img & " EXCEPTION: " & EX.Exception_Information (earthquake), False); Signals.initiate_shutdown; end build; builder_01 : build (builder => 1); builder_02 : build (builder => 2); builder_03 : build (builder => 3); builder_04 : build (builder => 4); builder_05 : build (builder => 5); builder_06 : build (builder => 6); builder_07 : build (builder => 7); builder_08 : build (builder => 8); builder_09 : build (builder => 9); builder_10 : build (builder => 10); builder_11 : build (builder => 11); builder_12 : build (builder => 12); builder_13 : build (builder => 13); builder_14 : build (builder => 14); builder_15 : build (builder => 15); builder_16 : build (builder => 16); builder_17 : build (builder => 17); builder_18 : build (builder => 18); builder_19 : build (builder => 19); builder_20 : build (builder => 20); builder_21 : build (builder => 21); builder_22 : build (builder => 22); builder_23 : build (builder => 23); builder_24 : build (builder => 24); builder_25 : build (builder => 25); builder_26 : build (builder => 26); builder_27 : build (builder => 27); builder_28 : build (builder => 28); builder_29 : build (builder => 29); builder_30 : build (builder => 30); builder_31 : build (builder => 31); builder_32 : build (builder => 32); builder_33 : build (builder => 33); builder_34 : build (builder => 34); builder_35 : build (builder => 35); builder_36 : build (builder => 36); builder_37 : build (builder => 37); builder_38 : build (builder => 38); builder_39 : build (builder => 39); builder_40 : build (builder => 40); builder_41 : build (builder => 41); builder_42 : build (builder => 42); builder_43 : build (builder => 43); builder_44 : build (builder => 44); builder_45 : build (builder => 45); builder_46 : build (builder => 46); builder_47 : build (builder => 47); builder_48 : build (builder => 48); builder_49 : build (builder => 49); builder_50 : build (builder => 50); builder_51 : build (builder => 51); builder_52 : build (builder => 52); builder_53 : build (builder => 53); builder_54 : build (builder => 54); builder_55 : build (builder => 55); builder_56 : build (builder => 56); builder_57 : build (builder => 57); builder_58 : build (builder => 58); builder_59 : build (builder => 59); builder_60 : build (builder => 60); builder_61 : build (builder => 61); builder_62 : build (builder => 62); builder_63 : build (builder => 63); builder_64 : build (builder => 64); -- Expansion of cpu_range from 32 to 64 means 128 possible builders builder_65 : build (builder => 65); builder_66 : build (builder => 66); builder_67 : build (builder => 67); builder_68 : build (builder => 68); builder_69 : build (builder => 69); builder_70 : build (builder => 70); builder_71 : build (builder => 71); builder_72 : build (builder => 72); builder_73 : build (builder => 73); builder_74 : build (builder => 74); builder_75 : build (builder => 75); builder_76 : build (builder => 76); builder_77 : build (builder => 77); builder_78 : build (builder => 78); builder_79 : build (builder => 79); builder_80 : build (builder => 80); builder_81 : build (builder => 81); builder_82 : build (builder => 82); builder_83 : build (builder => 83); builder_84 : build (builder => 84); builder_85 : build (builder => 85); builder_86 : build (builder => 86); builder_87 : build (builder => 87); builder_88 : build (builder => 88); builder_89 : build (builder => 89); builder_90 : build (builder => 90); builder_91 : build (builder => 91); builder_92 : build (builder => 92); builder_93 : build (builder => 93); builder_94 : build (builder => 94); builder_95 : build (builder => 95); builder_96 : build (builder => 96); builder_97 : build (builder => 97); builder_98 : build (builder => 98); builder_99 : build (builder => 99); builder_100 : build (builder => 100); builder_101 : build (builder => 101); builder_102 : build (builder => 102); builder_103 : build (builder => 103); builder_104 : build (builder => 104); builder_105 : build (builder => 105); builder_106 : build (builder => 106); builder_107 : build (builder => 107); builder_108 : build (builder => 108); builder_109 : build (builder => 109); builder_110 : build (builder => 110); builder_111 : build (builder => 111); builder_112 : build (builder => 112); builder_113 : build (builder => 113); builder_114 : build (builder => 114); builder_115 : build (builder => 115); builder_116 : build (builder => 116); builder_117 : build (builder => 117); builder_118 : build (builder => 118); builder_119 : build (builder => 119); builder_120 : build (builder => 120); builder_121 : build (builder => 121); builder_122 : build (builder => 122); builder_123 : build (builder => 123); builder_124 : build (builder => 124); builder_125 : build (builder => 125); builder_126 : build (builder => 126); builder_127 : build (builder => 127); builder_128 : build (builder => 128); begin loop all_idle := True; for slave in 1 .. num_builders loop begin case builder_states (slave) is when busy | tasked => all_idle := False; when shutdown => null; when idle => if run_complete then builder_states (slave) := shutdown; else target := top_buildable_port; if target = port_match_failed then if Signals.graceful_shutdown_requested or else nothing_left (num_builders) then run_complete := True; builder_states (slave) := shutdown; if curses_support then DPY.insert_history (CYC.assemble_history_record (slave, 0, DPY.action_shutdown)); end if; else if shutdown_recommended (available) then builder_states (slave) := shutdown; if curses_support then DPY.insert_history (CYC.assemble_history_record (slave, 0, DPY.action_shutdown)); end if; available := available - 1; end if; end if; else lock_package (target); instructions (slave) := target; builder_states (slave) := tasked; slave_display (total, slave, slave_name (slave)); if not curses_support then text_display (slave, " Kickoff " & slave_name (slave)); end if; end if; end if; when done_success | done_failure => all_idle := False; if builder_states (slave) = done_success then if curses_support then DPY.insert_history (CYC.assemble_history_record (slave, instructions (slave), DPY.action_success)); else text_display (slave, CYC.elapsed_build (slave) & " Success " & slave_name (slave)); end if; record_history_built (elapsed => LOG.elapsed_now, slave_id => slave, bucket => slave_bucket (slave), origin => slave_name (slave), duration => CYC.elapsed_build (slave)); run_package_hook (pkg_success, instructions (slave)); cascade_successful_build (instructions (slave)); LOG.increment_build_counter (success); common_display (success, slave_name (slave)); common_display (total, slave_name (slave) & " success"); else common_display (total, slave_name (slave) & " FAILED!"); cascade_failed_build (instructions (slave), cntskip); LOG.increment_build_counter (skipped, cntskip); LOG.increment_build_counter (failure); common_display (total, slave_name (slave) & " failure skips:" & cntskip'Img); common_display (failure, slave_name (slave) & " (skipped" & cntskip'Img & ")"); if curses_support then DPY.insert_history (CYC.assemble_history_record (slave, instructions (slave), DPY.action_failure)); else text_display (slave, CYC.elapsed_build (slave) & " Failure " & slave_name (slave)); end if; record_history_failed (elapsed => LOG.elapsed_now, slave_id => slave, bucket => slave_bucket (slave), origin => slave_name (slave), duration => CYC.elapsed_build (slave), die_phase => CYC.last_build_phase (slave), skips => cntskip); run_package_hook (pkg_failure, instructions (slave)); end if; instructions (slave) := port_match_failed; if run_complete then builder_states (slave) := shutdown; if curses_support then DPY.insert_history (CYC.assemble_history_record (slave, 0, DPY.action_shutdown)); end if; else builder_states (slave) := idle; end if; end case; exception when earthquake : others => LOG.scribe (total, LOG.elapsed_now & " UNHANDLED SLAVE LOOP EXCEPTION: " & EX.Exception_Information (earthquake), False); Signals.initiate_shutdown; end; end loop; exit when run_complete and all_idle; begin if cntcycle = cycle_count'Last then cntcycle := cycle_count'First; LOG.flush_log (success); LOG.flush_log (failure); LOG.flush_log (skipped); LOG.flush_log (total); if curses_support then if cntrefresh = refresh_count'Last then cntrefresh := refresh_count'First; DPC.set_full_redraw_next_update; else cntrefresh := cntrefresh + 1; end if; sumdata.Initially := LOG.port_counter_value (total); sumdata.Built := LOG.port_counter_value (success); sumdata.Failed := LOG.port_counter_value (failure); sumdata.Ignored := LOG.port_counter_value (ignored); sumdata.Skipped := LOG.port_counter_value (skipped); sumdata.elapsed := LOG.elapsed_now; sumdata.swap := get_swap_status; sumdata.load := CYC.load_core (True); sumdata.pkg_hour := LOG.hourly_build_rate; sumdata.impulse := LOG.impulse_rate; DPC.summarize (sumdata); for b in builders'First .. num_builders loop if builder_states (b) = shutdown then DPC.update_builder (CYC.builder_status (b, True, False)); elsif builder_states (b) = idle then DPC.update_builder (CYC.builder_status (b, False, True)); else CYC.set_log_lines (b); DPC.update_builder (CYC.builder_status (b)); end if; end loop; DPC.refresh_builder_window; DPC.refresh_history_window; else -- text mode support, periodic status reports if cntalert = alert_count'Last then cntalert := alert_count'First; TIO.Put_Line (LOG.elapsed_now & " => " & " Left:" & LOG.ports_remaining_to_build'Img & " Succ:" & LOG.port_counter_value (success)'Img & " Fail:" & LOG.port_counter_value (failure)'Img & " Skip:" & LOG.port_counter_value (skipped)'Img & " Ign:" & LOG.port_counter_value (ignored)'Img); else cntalert := cntalert + 1; end if; -- Update log lines every 4 seconds for the watchdog if cntrefresh = refresh_count'Last then cntrefresh := refresh_count'First; for b in builders'First .. num_builders loop if builder_states (b) /= shutdown and then builder_states (b) /= idle then CYC.set_log_lines (b); end if; end loop; else cntrefresh := cntrefresh + 1; end if; end if; -- Generate latest history file every 3 seconds. -- With a poll period of 6 seconds, we need twice that frequency to avoid aliasing -- Note that in text mode, the logs are updated every 4 seconds, so in this mode -- the log lines will often be identical for a cycle. if cntwww = www_count'Last then cntwww := www_count'First; write_history_json; write_summary_json (active => True, states => builder_states, num_builders => num_builders, num_history_files => history.segment); else cntwww := cntwww + 1; end if; else cntcycle := cntcycle + 1; end if; delay 0.10; exception when earthquake : others => LOG.scribe (total, LOG.elapsed_now & " UNHANDLED BULK RUN EXCEPTION: " & EX.Exception_Information (earthquake), False); exit; end; end loop; if PM.configuration.avec_ncurses and then curses_support then DPC.terminate_monitor; end if; write_history_json; write_summary_json (active => False, states => builder_states, num_builders => num_builders, num_history_files => history.segment); run_hook (run_end, "PORTS_BUILT=" & HT.int2str (LOG.port_counter_value (success)) & " PORTS_FAILED=" & HT.int2str (LOG.port_counter_value (failure)) & " PORTS_IGNORED=" & HT.int2str (LOG.port_counter_value (ignored)) & " PORTS_SKIPPED=" & HT.int2str (LOG.port_counter_value (skipped))); end parallel_bulk_run; -------------------------------------------------------------------------------------------- -- initialize_hooks -------------------------------------------------------------------------------------------- procedure initialize_hooks is begin for hook in hook_type'Range loop declare script : constant String := HT.USS (hook_location (hook)); begin active_hook (hook) := DIR.Exists (script) and then file_is_executable (script); end; end loop; end initialize_hooks; -------------------------------------------------------------------------------------------- -- run_hook -------------------------------------------------------------------------------------------- procedure run_hook (hook : hook_type; envvar_list : String) is function nvpair (name : String; value : HT.Text) return String; function nvpair (name : String; value : HT.Text) return String is begin return name & LAT.Equals_Sign & HT.replace_char (HT.USS (value), LAT.Space, "\ ") & LAT.Space; end nvpair; common_env : constant String := nvpair ("PROFILE", PM.configuration.profile) & nvpair ("DIR_PACKAGES", PM.configuration.dir_packages) & nvpair ("DIR_LOCALBASE", PM.configuration.dir_localbase) & nvpair ("DIR_CONSPIRACY", PM.configuration.dir_conspiracy) & nvpair ("DIR_CUSTOM_PORTS", PM.configuration.dir_unkindness) & nvpair ("DIR_DISTFILES", PM.configuration.dir_distfiles) & nvpair ("DIR_LOGS", PM.configuration.dir_logs) & nvpair ("DIR_BUILDBASE", PM.configuration.dir_buildbase); -- The follow command works on every platform command : constant String := "/usr/bin/env -i " & common_env & envvar_list & " " & HT.USS (hook_location (hook)); begin if not active_hook (hook) then return; end if; if Unix.external_command (command) then null; end if; end run_hook; -------------------------------------------------------------------------------------------- -- run_start_hook -------------------------------------------------------------------------------------------- procedure run_start_hook is begin run_hook (run_start, "PORTS_QUEUED=" & HT.int2str (queue_length) & " "); end run_start_hook; -------------------------------------------------------------------------------------------- -- run_hook_after_build -------------------------------------------------------------------------------------------- procedure run_hook_after_build (built : Boolean; id : port_id) is begin if built then run_package_hook (pkg_success, id); else run_package_hook (pkg_failure, id); end if; end run_hook_after_build; -------------------------------------------------------------------------------------------- -- run_package_hook -------------------------------------------------------------------------------------------- procedure run_package_hook (hook : hook_type; id : port_id) is tail : String := " ORIGIN=" & get_port_variant (id); begin case hook is when pkg_success => run_hook (hook, "RESULT=success" & tail); when pkg_failure => run_hook (hook, "RESULT=failure" & tail); when pkg_ignored => run_hook (hook, "RESULT=ignored" & tail); when pkg_skipped => run_hook (hook, "RESULT=skipped" & tail); when others => null; end case; end run_package_hook; -------------------------------------------------------------------------------------------- -- file_is_executable -------------------------------------------------------------------------------------------- function file_is_executable (filename : String) return Boolean is status : Integer; sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); command : constant String := sysroot & "/usr/bin/file -m " & sysroot & "/usr/share/file/magic.mgc -b " & filename; cmdout : String := HT.USS (Unix.piped_command (command, status)); begin if status = 0 then return HT.contains (cmdout, "executable"); else return False; end if; end file_is_executable; -------------------------------------------------------------------------------------------- -- delete_existing_web_history_files -------------------------------------------------------------------------------------------- procedure delete_existing_web_history_files is search : DIR.Search_Type; dirent : DIR.Directory_Entry_Type; pattern : constant String := "*_history.json"; filter : constant DIR.Filter_Type := (DIR.Ordinary_File => True, others => False); reportdir : constant String := HT.USS (PM.configuration.dir_logs); begin if not DIR.Exists (reportdir) then return; end if; DIR.Start_Search (Search => search, Directory => reportdir, Pattern => pattern, Filter => filter); while DIR.More_Entries (search) loop DIR.Get_Next_Entry (search, dirent); DIR.Delete_File (reportdir & "/" & DIR.Simple_Name (dirent)); end loop; DIR.End_Search (search); exception when DIR.Name_Error => null; end delete_existing_web_history_files; -------------------------------------------------------------------------------------------- -- delete_existing_packages_of_ports_list -------------------------------------------------------------------------------------------- procedure delete_existing_packages_of_ports_list is procedure force_delete (plcursor : string_crate.Cursor); compkey : HT.Text := HT.SUS (default_compiler & LAT.Colon & variant_standard); compiler : constant port_index := ports_keys.Element (compkey); binutils : constant port_index := ports_keys.Element (HT.SUS (default_binutils)); procedure force_delete (plcursor : string_crate.Cursor) is procedure delete_subpackage (position : subpackage_crate.Cursor); origin : HT.Text := string_crate.Element (plcursor); pndx : constant port_index := ports_keys.Element (origin); repo : constant String := HT.USS (PM.configuration.dir_repository) & "/"; procedure delete_subpackage (position : subpackage_crate.Cursor) is rec : subpackage_record renames subpackage_crate.Element (position); subpackage : constant String := HT.USS (rec.subpackage); tball : constant String := repo & PortScan.calculate_package_name (pndx, subpackage) & arc_ext; begin -- Never delete the port binutils or compiler's packages if pndx /= compiler and then pndx /= binutils then if DIR.Exists (tball) then DIR.Delete_File (tball); end if; end if; end delete_subpackage; begin all_ports (pndx).subpackages.Iterate (delete_subpackage'Access); end force_delete; begin portlist.Iterate (Process => force_delete'Access); end delete_existing_packages_of_ports_list; -------------------------------------------------------------------------------------------- -- list_subpackages_of_queued_ports -------------------------------------------------------------------------------------------- procedure list_subpackages_of_queued_ports is procedure list (plcursor : string_crate.Cursor); procedure list (plcursor : string_crate.Cursor) is procedure name (position : subpackage_crate.Cursor); origin : HT.Text renames string_crate.Element (plcursor); pndx : constant port_index := ports_keys.Element (origin); procedure name (position : subpackage_crate.Cursor) is rec : subpackage_record renames subpackage_crate.Element (position); subpackage : constant String := HT.USS (rec.subpackage); begin TIO.Put (" " & subpackage); end name; begin TIO.Put (HT.USS (origin) & " subpackages:"); all_ports (pndx).subpackages.Iterate (name'Access); TIO.Put_Line (""); end list; begin portlist.Iterate (list'Access); end list_subpackages_of_queued_ports; -------------------------------------------------------------------------------------------- -- next_ignored_port -------------------------------------------------------------------------------------------- function next_ignored_port return port_id is list_len : constant Integer := Integer (rank_queue.Length); cursor : ranking_crate.Cursor; QR : queue_record; result : port_id := port_match_failed; begin if list_len = 0 then return result; end if; cursor := rank_queue.First; for k in 1 .. list_len loop QR := ranking_crate.Element (Position => cursor); if all_ports (QR.ap_index).ignored then result := QR.ap_index; DPY.insert_history (CYC.assemble_history_record (1, QR.ap_index, DPY.action_ignored)); run_package_hook (pkg_ignored, QR.ap_index); exit; end if; cursor := ranking_crate.Next (Position => cursor); end loop; return result; end next_ignored_port; -------------------------------------------------------------------------------------------- -- assimulate_substring -------------------------------------------------------------------------------------------- procedure assimulate_substring (history : in out progress_history; substring : String) is first : constant Positive := history.last_index + 1; last : constant Positive := history.last_index + substring'Length; begin -- silently fail (this shouldn't be practically possible) if last < kfile_content'Last then history.content (first .. last) := substring; end if; history.last_index := last; end assimulate_substring; -------------------------------------------------------------------------------------------- -- nv #1 -------------------------------------------------------------------------------------------- function nv (name, value : String) return String is begin return LAT.Quotation & name & LAT.Quotation & LAT.Colon & LAT.Quotation & value & LAT.Quotation; end nv; -------------------------------------------------------------------------------------------- -- nv #2 -------------------------------------------------------------------------------------------- function nv (name : String; value : Integer) return String is begin return LAT.Quotation & name & LAT.Quotation & LAT.Colon & HT.int2str (value); end nv; -------------------------------------------------------------------------------------------- -- handle_first_history_entry -------------------------------------------------------------------------------------------- procedure handle_first_history_entry is begin if history.segment_count = 1 then assimulate_substring (history, "[" & LAT.LF & " {" & LAT.LF); else assimulate_substring (history, " ,{" & LAT.LF); end if; end handle_first_history_entry; -------------------------------------------------------------------------------------------- -- write_history_json -------------------------------------------------------------------------------------------- procedure write_history_json is jsonfile : TIO.File_Type; filename : constant String := HT.USS (PM.configuration.dir_logs) & "/" & HT.zeropad (history.segment, 2) & "_history.json"; begin if history.segment_count = 0 then return; end if; if history.last_written = history.last_index then return; end if; TIO.Create (File => jsonfile, Mode => TIO.Out_File, Name => filename); TIO.Put (jsonfile, history.content (1 .. history.last_index)); TIO.Put (jsonfile, "]"); TIO.Close (jsonfile); history.last_written := history.last_index; exception when others => if TIO.Is_Open (jsonfile) then TIO.Close (jsonfile); end if; end write_history_json; -------------------------------------------------------------------------------------------- -- check_history_segment_capacity -------------------------------------------------------------------------------------------- procedure check_history_segment_capacity is begin if history.segment_count = 1 then history.segment := history.segment + 1; return; end if; if history.segment_count < kfile_units_limit then return; end if; write_history_json; history.last_index := 0; history.last_written := 0; history.segment_count := 0; end check_history_segment_capacity; -------------------------------------------------------------------------------------------- -- record_history_ignored -------------------------------------------------------------------------------------------- procedure record_history_ignored (elapsed : String; bucket : String; origin : String; reason : String; skips : Natural) is cleantxt : constant String := HT.strip_control (reason); info : constant String := HT.replace_char (HT.replace_char (cleantxt, LAT.Quotation, "&nbsp;"), LAT.Reverse_Solidus, "&#92;") & ":|:" & HT.int2str (skips); begin history.log_entry := history.log_entry + 1; history.segment_count := history.segment_count + 1; handle_first_history_entry; assimulate_substring (history, " " & nv ("entry", history.log_entry) & LAT.LF); assimulate_substring (history, " ," & nv ("elapsed", elapsed) & LAT.LF); assimulate_substring (history, " ," & nv ("ID", "--") & LAT.LF); assimulate_substring (history, " ," & nv ("result", "ignored") & LAT.LF); assimulate_substring (history, " ," & nv ("bucket", bucket) & LAT.LF); assimulate_substring (history, " ," & nv ("origin", origin) & LAT.LF); assimulate_substring (history, " ," & nv ("info", info) & LAT.LF); assimulate_substring (history, " ," & nv ("duration", "--:--:--") & LAT.LF); assimulate_substring (history, " }" & LAT.LF); check_history_segment_capacity; end record_history_ignored; -------------------------------------------------------------------------------------------- -- record_history_skipped -------------------------------------------------------------------------------------------- procedure record_history_skipped (elapsed : String; bucket : String; origin : String; reason : String) is begin history.log_entry := history.log_entry + 1; history.segment_count := history.segment_count + 1; handle_first_history_entry; assimulate_substring (history, " " & nv ("entry", history.log_entry) & LAT.LF); assimulate_substring (history, " ," & nv ("elapsed", elapsed) & LAT.LF); assimulate_substring (history, " ," & nv ("ID", "--") & LAT.LF); assimulate_substring (history, " ," & nv ("result", "skipped") & LAT.LF); assimulate_substring (history, " ," & nv ("bucket", bucket) & LAT.LF); assimulate_substring (history, " ," & nv ("origin", origin) & LAT.LF); assimulate_substring (history, " ," & nv ("info", reason) & LAT.LF); assimulate_substring (history, " ," & nv ("duration", "--:--:--") & LAT.LF); assimulate_substring (history, " }" & LAT.LF); check_history_segment_capacity; end record_history_skipped; -------------------------------------------------------------------------------------------- -- record_history_built -------------------------------------------------------------------------------------------- procedure record_history_built (elapsed : String; slave_id : builders; bucket : String; origin : String; duration : String) is ID : constant String := HT.zeropad (Integer (slave_id), 2); begin history.log_entry := history.log_entry + 1; history.segment_count := history.segment_count + 1; handle_first_history_entry; assimulate_substring (history, " " & nv ("entry", history.log_entry) & LAT.LF); assimulate_substring (history, " ," & nv ("elapsed", elapsed) & LAT.LF); assimulate_substring (history, " ," & nv ("ID", ID) & LAT.LF); assimulate_substring (history, " ," & nv ("result", "built") & LAT.LF); assimulate_substring (history, " ," & nv ("bucket", bucket) & LAT.LF); assimulate_substring (history, " ," & nv ("origin", origin) & LAT.LF); assimulate_substring (history, " ," & nv ("info", "") & LAT.LF); assimulate_substring (history, " ," & nv ("duration", duration) & LAT.LF); assimulate_substring (history, " }" & LAT.LF); check_history_segment_capacity; end record_history_built; -------------------------------------------------------------------------------------------- -- record_history_built -------------------------------------------------------------------------------------------- procedure record_history_failed (elapsed : String; slave_id : builders; bucket : String; origin : String; duration : String; die_phase : String; skips : Natural) is info : constant String := die_phase & ":" & HT.int2str (skips); ID : constant String := HT.zeropad (Integer (slave_id), 2); begin history.log_entry := history.log_entry + 1; history.segment_count := history.segment_count + 1; handle_first_history_entry; assimulate_substring (history, " " & nv ("entry", history.log_entry) & LAT.LF); assimulate_substring (history, " ," & nv ("elapsed", elapsed) & LAT.LF); assimulate_substring (history, " ," & nv ("ID", ID) & LAT.LF); assimulate_substring (history, " ," & nv ("result", "failed") & LAT.LF); assimulate_substring (history, " ," & nv ("bucket", bucket) & LAT.LF); assimulate_substring (history, " ," & nv ("origin", origin) & LAT.LF); assimulate_substring (history, " ," & nv ("info", info) & LAT.LF); assimulate_substring (history, " ," & nv ("duration", duration) & LAT.LF); assimulate_substring (history, " }" & LAT.LF); check_history_segment_capacity; end record_history_failed; -------------------------------------------------------------------------------------------- -- skip_verified -------------------------------------------------------------------------------------------- function skip_verified (id : port_id) return Boolean is begin if id = port_match_failed then return False; end if; return not all_ports (id).unlist_failed; end skip_verified; -------------------------------------------------------------------------------------------- -- delete_rank -------------------------------------------------------------------------------------------- procedure delete_rank (id : port_id) is rank_cursor : ranking_crate.Cursor := rank_arrow (id); use type ranking_crate.Cursor; begin if rank_cursor /= ranking_crate.No_Element then rank_queue.Delete (Position => rank_cursor); end if; end delete_rank; -------------------------------------------------------------------------------------------- -- still_ranked -------------------------------------------------------------------------------------------- function still_ranked (id : port_id) return Boolean is rank_cursor : ranking_crate.Cursor := rank_arrow (id); use type ranking_crate.Cursor; begin return rank_cursor /= ranking_crate.No_Element; end still_ranked; -------------------------------------------------------------------------------------------- -- unlist_first_port -------------------------------------------------------------------------------------------- function unlist_first_port return port_id is origin : HT.Text := string_crate.Element (portlist.First); id : port_id; begin if ports_keys.Contains (origin) then id := ports_keys.Element (origin); else return port_match_failed; end if; if id = port_match_failed then return port_match_failed; end if; delete_rank (id); return id; end unlist_first_port; -------------------------------------------------------------------------------------------- -- unlist_port -------------------------------------------------------------------------------------------- procedure unlist_port (id : port_id) is begin if id = port_match_failed then return; end if; if still_ranked (id) then delete_rank (id); else -- don't raise exception. Since we don't prune all_reverse as -- we go, there's no guarantee the reverse dependency hasn't already -- been removed (e.g. when it is a common reverse dep) all_ports (id).unlist_failed := True; end if; end unlist_port; -------------------------------------------------------------------------------------------- -- rank_arrow -------------------------------------------------------------------------------------------- function rank_arrow (id : port_id) return ranking_crate.Cursor is rscore : constant port_index := all_ports (id).reverse_score; seek_target : constant queue_record := (ap_index => id, reverse_score => rscore); begin return rank_queue.Find (seek_target); end rank_arrow; -------------------------------------------------------------------------------------------- -- skip_next_reverse_dependency -------------------------------------------------------------------------------------------- function skip_next_reverse_dependency (pinnacle : port_id) return port_id is rev_cursor : block_crate.Cursor; next_dep : port_index; begin if all_ports (pinnacle).all_reverse.Is_Empty then return port_match_failed; end if; rev_cursor := all_ports (pinnacle).all_reverse.First; next_dep := block_crate.Element (rev_cursor); unlist_port (id => next_dep); all_ports (pinnacle).all_reverse.Delete (rev_cursor); return next_dep; end skip_next_reverse_dependency; -------------------------------------------------------------------------------------------- -- cascade_failed_build -------------------------------------------------------------------------------------------- procedure cascade_failed_build (id : port_id; numskipped : out Natural) is purged : PortScan.port_id; culprit : constant String := get_port_variant (id); begin numskipped := 0; loop purged := skip_next_reverse_dependency (id); exit when purged = port_match_failed; if skip_verified (purged) then numskipped := numskipped + 1; LOG.scribe (PortScan.total, " Skipped: " & get_port_variant (purged), False); LOG.scribe (PortScan.skipped, get_port_variant (purged) & " by " & culprit, False); DPY.insert_history (CYC.assemble_history_record (1, purged, DPY.action_skipped)); record_history_skipped (elapsed => LOG.elapsed_now, bucket => get_bucket (purged), origin => get_port_variant (purged), reason => culprit); run_package_hook (pkg_skipped, purged); end if; end loop; unlist_port (id); end cascade_failed_build; -------------------------------------------------------------------------------------------- -- cascade_successful_build -------------------------------------------------------------------------------------------- procedure cascade_successful_build (id : port_id) is procedure cycle (cursor : block_crate.Cursor); procedure cycle (cursor : block_crate.Cursor) is target : port_index renames block_crate.Element (cursor); begin if all_ports (target).blocked_by.Contains (id) then all_ports (target).blocked_by.Delete (id); else raise seek_failure with get_port_variant (target) & " was expected to be blocked by " & get_port_variant (id); end if; end cycle; begin all_ports (id).blocks.Iterate (cycle'Access); delete_rank (id); end cascade_successful_build; -------------------------------------------------------------------------------------------- -- integrity_intact -------------------------------------------------------------------------------------------- function integrity_intact return Boolean is procedure check_dep (cursor : block_crate.Cursor); procedure check_rank (cursor : ranking_crate.Cursor); intact : Boolean := True; procedure check_dep (cursor : block_crate.Cursor) is did : constant port_index := block_crate.Element (cursor); begin if not still_ranked (did) then intact := False; end if; end check_dep; procedure check_rank (cursor : ranking_crate.Cursor) is QR : constant queue_record := ranking_crate.Element (cursor); begin if intact then all_ports (QR.ap_index).blocked_by.Iterate (check_dep'Access); end if; end check_rank; begin rank_queue.Iterate (check_rank'Access); return intact; end integrity_intact; -------------------------------------------------------------------------------------------- -- located_external_repository -------------------------------------------------------------------------------------------- function located_external_repository return Boolean is command : constant String := host_pkg8 & " -vv"; found : Boolean := False; inspect : Boolean := False; status : Integer; begin declare dump : String := HT.USS (Unix.piped_command (command, status)); markers : HT.Line_Markers; linenum : Natural := 0; begin if status /= 0 then return False; end if; HT.initialize_markers (dump, markers); loop exit when not HT.next_line_present (dump, markers); declare line : constant String := HT.extract_line (dump, markers); len : constant Natural := line'Length; begin if inspect then if len > 7 and then line (line'First .. line'First + 1) = " " and then line (line'Last - 3 .. line'Last) = ": { " and then line (line'First + 2 .. line'Last - 4) /= "ravenadm" then found := True; external_repository := HT.SUS (line (line'First + 2 .. line'Last - 4)); exit; end if; else if line = "Repositories:" then inspect := True; end if; end if; end; end loop; end; return found; end located_external_repository; -------------------------------------------------------------------------------------------- -- top_external_repository -------------------------------------------------------------------------------------------- function top_external_repository return String is begin return HT.USS (external_repository); end top_external_repository; -------------------------------------------------------------------------------------------- -- isolate_arch_from_file_type -------------------------------------------------------------------------------------------- function isolate_arch_from_file_type (fileinfo : String) return filearch is -- DF: ELF 64-bit LSB executable, x86-64 -- FB: ELF 64-bit LSB executable, x86-64 -- FB: ELF 32-bit LSB executable, Intel 80386 -- NB: ELF 64-bit LSB executable, x86-64 -- L: ELF 64-bit LSB executable, x86-64 -- NATIVE Solaris (we use our own file) -- /usr/bin/sh: ELF 64-bit LSB executable AMD64 Version 1 fragment : constant String := HT.trim (HT.specific_field (fileinfo, 2, ",")); answer : filearch := (others => ' '); begin if fragment'Length > filearch'Length then answer := fragment (fragment'First .. fragment'First + filearch'Length - 1); else answer (answer'First .. answer'First + fragment'Length - 1) := fragment; end if; return answer; end isolate_arch_from_file_type; -------------------------------------------------------------------------------------------- -- isolate_arch_from_macho_file -------------------------------------------------------------------------------------------- function isolate_arch_from_macho_file (fileinfo : String) return filearch is -- Mac: Mach-O 64-bit executable x86_64 fragment : constant String := HT.trim (HT.specific_field (fileinfo, 4)); answer : filearch := (others => ' '); begin if fragment'Length > filearch'Length then answer := fragment (fragment'First .. fragment'First + filearch'Length - 1); else answer (answer'First .. answer'First + fragment'Length - 1) := fragment; end if; return answer; end isolate_arch_from_macho_file; -------------------------------------------------------------------------------------------- -- establish_package_architecture -------------------------------------------------------------------------------------------- procedure establish_package_architecture (release : String; architecture : supported_arch) is function newsuffix return String; function suffix return String; function get_version (fileinfo : String; OS : String) return String; procedure craft_common_endings (release : String); function suffix return String is begin case architecture is when x86_64 => return "x86:64"; when i386 => return "x86:32"; when aarch64 => return "aarch64:64"; end case; end suffix; function newsuffix return String is begin case architecture is when x86_64 => return "amd64"; when i386 => return "i386"; when aarch64 => return "arm64"; end case; end newsuffix; procedure craft_common_endings (release : String) is begin HT.SU.Append (abi_formats.calculated_abi, release & ":"); HT.SU.Append (abi_formats.calculated_alt_abi, release & ":"); abi_formats.calc_abi_noarch := abi_formats.calculated_abi; abi_formats.calc_alt_abi_noarch := abi_formats.calculated_alt_abi; HT.SU.Append (abi_formats.calculated_abi, newsuffix); HT.SU.Append (abi_formats.calculated_alt_abi, suffix); HT.SU.Append (abi_formats.calc_abi_noarch, "*"); HT.SU.Append (abi_formats.calc_alt_abi_noarch, "*"); end craft_common_endings; function get_version (fileinfo : String; OS : String) return String is -- GNU/Linux 2.6.32, BuildID[sha1]=03d7a9de009544a1fe82313544a3c36e249858cc, stripped rest : constant String := HT.part_2 (fileinfo, OS); begin return HT.part_1 (rest, ","); end get_version; begin case platform_type is when dragonfly => declare dfly : constant String := "dragonfly:"; begin abi_formats.calculated_abi := HT.SUS (dfly); HT.SU.Append (abi_formats.calculated_abi, release & ":"); abi_formats.calc_abi_noarch := abi_formats.calculated_abi; HT.SU.Append (abi_formats.calculated_abi, suffix); HT.SU.Append (abi_formats.calc_abi_noarch, "*"); abi_formats.calculated_alt_abi := abi_formats.calculated_abi; abi_formats.calc_alt_abi_noarch := abi_formats.calc_abi_noarch; end; when freebsd => declare fbsd1 : constant String := "FreeBSD:"; fbsd2 : constant String := "freebsd:"; begin abi_formats.calculated_abi := HT.SUS (fbsd1); abi_formats.calculated_alt_abi := HT.SUS (fbsd2); craft_common_endings (release); end; when netbsd => declare net1 : constant String := "NetBSD:"; net2 : constant String := "netbsd:"; begin abi_formats.calculated_abi := HT.SUS (net1); abi_formats.calculated_alt_abi := HT.SUS (net2); craft_common_endings (release); end; when openbsd => declare open1 : constant String := "OpenBSD:"; open2 : constant String := "openbsd:"; begin abi_formats.calculated_abi := HT.SUS (open1); abi_formats.calculated_alt_abi := HT.SUS (open2); craft_common_endings (release); end; when sunos => declare sol1 : constant String := "Solaris:"; sol2 : constant String := "solaris:"; solrel : constant String := "10"; -- hardcoded in pkg(8), release=5.10 begin abi_formats.calculated_abi := HT.SUS (sol1); abi_formats.calculated_alt_abi := HT.SUS (sol2); craft_common_endings (solrel); end; when macos => -- Hardcode i386 for now until pkg(8) fixed to provide correct arch abi_formats.calculated_abi := HT.SUS ("Darwin:" & release & ":"); abi_formats.calculated_alt_abi := HT.SUS ("darwin:" & release & ":"); abi_formats.calc_abi_noarch := abi_formats.calculated_abi; abi_formats.calc_alt_abi_noarch := abi_formats.calculated_alt_abi; HT.SU.Append (abi_formats.calculated_abi, "i386"); HT.SU.Append (abi_formats.calculated_alt_abi, "i386:32"); HT.SU.Append (abi_formats.calc_abi_noarch, "*"); HT.SU.Append (abi_formats.calc_alt_abi_noarch, "*"); when linux => declare sysroot : constant String := HT.USS (PM.configuration.dir_sysroot); command : constant String := sysroot & "/usr/bin/file -m " & sysroot & "/usr/share/file/magic.mgc -b " & sysroot & "/bin/sh"; status : Integer; UN : HT.Text; begin UN := Unix.piped_command (command, status); declare gnu1 : constant String := "Linux:"; gnu2 : constant String := "linux:"; gnurel : constant String := get_version (HT.USS (UN), "GNU/Linux "); begin abi_formats.calculated_abi := HT.SUS (gnu1); abi_formats.calculated_alt_abi := HT.SUS (gnu2); craft_common_endings (gnurel); end; end; end case; end establish_package_architecture; -------------------------------------------------------------------------------------------- -- limited_sanity_check -------------------------------------------------------------------------------------------- procedure limited_sanity_check (repository : String; dry_run : Boolean; rebuild_compiler : Boolean; rebuild_binutils : Boolean; suppress_remote : Boolean; major_release : String; architecture : supported_arch) is procedure prune_packages (cursor : ranking_crate.Cursor); procedure check_package (cursor : ranking_crate.Cursor); procedure determine_fully_built (cursor : subpackage_queue.Cursor); procedure prune_queue (cursor : subqueue.Cursor); procedure print (cursor : subpackage_queue.Cursor); procedure fetch (cursor : subpackage_queue.Cursor); procedure check (cursor : subpackage_queue.Cursor); procedure set_delete (Element : in out subpackage_record); procedure kill_remote (Element : in out subpackage_record); compkey : HT.Text := HT.SUS (default_compiler & LAT.Colon & variant_standard); bukey : HT.Text := HT.SUS (default_binutils); compiler : constant port_index := ports_keys.Element (compkey); binutils : constant port_index := ports_keys.Element (bukey); already_built : subpackage_queue.Vector; fetch_list : subpackage_queue.Vector; prune_list : subqueue.Vector; fetch_fail : Boolean := False; clean_pass : Boolean := False; listlog : TIO.File_Type; goodlog : Boolean; using_screen : constant Boolean := Unix.screen_attached; filename : constant String := "/tmp/ravenadm_prefetch_list.txt"; package_list : HT.Text := HT.blank; procedure set_delete (Element : in out subpackage_record) is begin Element.deletion_due := True; end set_delete; procedure kill_remote (Element : in out subpackage_record) is begin Element.remote_pkg := False; end kill_remote; procedure check_package (cursor : ranking_crate.Cursor) is procedure check_subpackage (position : subpackage_crate.Cursor); target : port_id := ranking_crate.Element (cursor).ap_index; procedure check_subpackage (position : subpackage_crate.Cursor) is rec : subpackage_record renames subpackage_crate.Element (position); subpackage : constant String := HT.USS (rec.subpackage); pkgname : constant String := calculate_package_name (target, subpackage); available : constant Boolean := (rec.remote_pkg or else rec.pkg_present) and then not rec.deletion_due; newrec : subpackage_identifier := (target, rec.subpackage); begin if not available then return; end if; if passed_dependency_check (subpackage => subpackage, query_result => rec.pkg_dep_query, id => target) then if not ( (rebuild_binutils and then target = binutils) or else (rebuild_compiler and then target = compiler) ) then already_built.Append (New_Item => newrec); if rec.remote_pkg then fetch_list.Append (New_Item => newrec); end if; end if; else if rec.remote_pkg then -- silently fail, remote packages are a bonus anyway all_ports (target).subpackages.Update_Element (Position => position, Process => kill_remote'Access); else TIO.Put_Line (pkgname & " failed dependency check."); all_ports (target).subpackages.Update_Element (Position => position, Process => set_delete'Access); end if; clean_pass := False; end if; end check_subpackage; begin all_ports (target).subpackages.Iterate (check_subpackage'Access); end check_package; procedure prune_queue (cursor : subqueue.Cursor) is id : constant port_index := subqueue.Element (cursor); begin cascade_successful_build (id); end prune_queue; procedure prune_packages (cursor : ranking_crate.Cursor) is procedure check_subpackage (position : subpackage_crate.Cursor); target : port_id := ranking_crate.Element (cursor).ap_index; procedure check_subpackage (position : subpackage_crate.Cursor) is rec : subpackage_record renames subpackage_crate.Element (position); delete_it : Boolean := rec.deletion_due; begin if delete_it then declare subpackage : constant String := HT.USS (rec.subpackage); pkgname : constant String := calculate_package_name (target, subpackage); fullpath : constant String := repository & "/" & pkgname & arc_ext; begin DIR.Delete_File (fullpath); exception when others => null; end; end if; end check_subpackage; begin all_ports (target).subpackages.Iterate (check_subpackage'Access); end prune_packages; procedure print (cursor : subpackage_queue.Cursor) is id : constant port_index := subpackage_queue.Element (cursor).id; subpkg : constant String := HT.USS (subpackage_queue.Element (cursor).subpackage); pkgfile : constant String := calculate_package_name (id, subpkg) & arc_ext; begin TIO.Put_Line (" => " & pkgfile); if goodlog then TIO.Put_Line (listlog, pkgfile); end if; end print; procedure fetch (cursor : subpackage_queue.Cursor) is id : constant port_index := subpackage_queue.Element (cursor).id; subpkg : constant String := HT.USS (subpackage_queue.Element (cursor).subpackage); pkgbase : constant String := " " & calculate_package_name (id, subpkg); begin HT.SU.Append (package_list, pkgbase); end fetch; procedure check (cursor : subpackage_queue.Cursor) is id : constant port_index := subpackage_queue.Element (cursor).id; subpkg : constant String := HT.USS (subpackage_queue.Element (cursor).subpackage); pkgfile : constant String := calculate_package_name (id, subpkg) & arc_ext; loc : constant String := HT.USS (PM.configuration.dir_repository) & "/" & pkgfile; begin if not DIR.Exists (loc) then TIO.Put_Line ("Download failed: " & pkgfile); fetch_fail := True; end if; end check; procedure determine_fully_built (cursor : subpackage_queue.Cursor) is procedure check_subpackage (cursor : subpackage_crate.Cursor); glass_full : Boolean := True; target : port_id := subpackage_queue.Element (cursor).id; procedure check_subpackage (cursor : subpackage_crate.Cursor) is procedure check_already_built (position : subpackage_queue.Cursor); rec : subpackage_record renames subpackage_crate.Element (cursor); found : Boolean := False; procedure check_already_built (position : subpackage_queue.Cursor) is builtrec : subpackage_identifier renames subpackage_queue.Element (position); begin if not found then if HT.equivalent (builtrec.subpackage, rec.subpackage) then found := True; if rec.deletion_due or else not (rec.pkg_present or else rec.remote_pkg) then glass_full := False; end if; end if; end if; end check_already_built; begin if glass_full then already_built.Iterate (check_already_built'Access); end if; end check_subpackage; begin all_ports (target).subpackages.Iterate (check_subpackage'Access); if glass_full then if not prune_list.Contains (target) then prune_list.Append (target); end if; end if; end determine_fully_built; begin if Unix.env_variable_defined ("WHYFAIL") then activate_debugging_code; end if; establish_package_architecture (major_release, architecture); original_queue_len := rank_queue.Length; for m in scanners'Range loop mq_progress (m) := 0; end loop; LOG.start_obsolete_package_logging; parallel_package_scan (repository, False, using_screen); if Signals.graceful_shutdown_requested then LOG.stop_obsolete_package_logging; return; end if; while not clean_pass loop clean_pass := True; already_built.Clear; rank_queue.Iterate (check_package'Access); end loop; if not suppress_remote and then PM.configuration.defer_prebuilt then -- The defer_prebuilt options has been elected, so check all the -- missing and to-be-pruned ports for suitable prebuilt packages -- So we need to an incremental scan (skip valid, present packages) for m in scanners'Range loop mq_progress (m) := 0; end loop; parallel_package_scan (repository, True, using_screen); if Signals.graceful_shutdown_requested then LOG.stop_obsolete_package_logging; return; end if; clean_pass := False; while not clean_pass loop clean_pass := True; already_built.Clear; fetch_list.Clear; rank_queue.Iterate (check_package'Access); end loop; end if; LOG.stop_obsolete_package_logging; if Signals.graceful_shutdown_requested then return; end if; if dry_run then if not fetch_list.Is_Empty then begin TIO.Create (File => listlog, Mode => TIO.Out_File, Name => filename); goodlog := True; exception when others => goodlog := False; end; TIO.Put_Line ("These are the packages that would be fetched:"); fetch_list.Iterate (print'Access); TIO.Put_Line ("Total packages that would be fetched:" & fetch_list.Length'Img); if goodlog then TIO.Close (listlog); TIO.Put_Line ("The complete build list can also be found at:" & LAT.LF & filename); end if; else if PM.configuration.defer_prebuilt then TIO.Put_Line ("No packages qualify for prefetching from " & "official package repository."); end if; end if; else rank_queue.Iterate (prune_packages'Access); fetch_list.Iterate (fetch'Access); if not HT.equivalent (package_list, HT.blank) then declare cmd : constant String := host_pkg8 & " fetch -r " & HT.USS (external_repository) & " -U -y --output " & HT.USS (PM.configuration.dir_packages) & HT.USS (package_list); begin if Unix.external_command (cmd) then null; end if; end; fetch_list.Iterate (check'Access); end if; end if; if fetch_fail then TIO.Put_Line ("At least one package failed to fetch, aborting build!"); rank_queue.Clear; else -- All subpackages must be "already_built" before we can prune. -- we have iterate through the rank_queue, then subiterate through subpackages. -- If all subpackages are present, add port to prune queue. already_built.Iterate (determine_fully_built'Access); prune_list.Iterate (prune_queue'Access); end if; end limited_sanity_check; -------------------------------------------------------------------------------------------- -- result_of_dependency_query -------------------------------------------------------------------------------------------- function result_of_dependency_query (repository : String; id : port_id; subpackage : String) return HT.Text is rec : port_record renames all_ports (id); pkg_base : constant String := PortScan.calculate_package_name (id, subpackage); fullpath : constant String := repository & "/" & pkg_base & arc_ext; pkg8 : constant String := HT.USS (PM.configuration.sysroot_pkg8); command : constant String := pkg8 & " query -F " & fullpath & " %dn-%dv@%do"; remocmd : constant String := pkg8 & " rquery -r " & HT.USS (external_repository) & " -U %dn-%dv@%do " & pkg_base; status : Integer; comres : HT.Text; begin if repository = "" then comres := Unix.piped_command (remocmd, status); else comres := Unix.piped_command (command, status); end if; if status = 0 then return comres; else return HT.blank; end if; end result_of_dependency_query; -------------------------------------------------------------------------------------------- -- activate_debugging_code -------------------------------------------------------------------------------------------- procedure activate_debugging_code is begin debug_opt_check := True; debug_dep_check := True; end activate_debugging_code; -------------------------------------------------------------------------------------------- -- passed_dependency_check -------------------------------------------------------------------------------------------- function passed_dependency_check (subpackage : String; query_result : HT.Text; id : port_id) return Boolean is procedure get_rundeps (position : subpackage_crate.Cursor); procedure log_run_deps (position : subpackage_crate.Cursor); content : String := HT.USS (query_result); headport : constant String := HT.USS (all_ports (id).port_namebase) & LAT.Colon & subpackage & LAT.Colon & HT.USS (all_ports (id).port_variant); counter : Natural := 0; req_deps : Natural := 0; markers : HT.Line_Markers; pkgfound : Boolean := False; procedure get_rundeps (position : subpackage_crate.Cursor) is rec : subpackage_record renames subpackage_crate.Element (position); begin if not pkgfound then if HT.equivalent (rec.subpackage, subpackage) then req_deps := Natural (rec.spkg_run_deps.Length); pkgfound := True; end if; end if; end get_rundeps; procedure log_run_deps (position : subpackage_crate.Cursor) is procedure logme (logpos : spkg_id_crate.Cursor); rec : subpackage_record renames subpackage_crate.Element (position); procedure logme (logpos : spkg_id_crate.Cursor) is rec2 : PortScan.subpackage_identifier renames spkg_id_crate.Element (logpos); message : constant String := get_port_variant (rec2.port) & " (" & HT.USS (rec2.subpackage) & ")"; begin LOG.obsolete_notice (message, debug_dep_check); end logme; begin if HT.equivalent (rec.subpackage, subpackage) then LOG.obsolete_notice ("Port requirements:", debug_dep_check); rec.spkg_run_deps.Iterate (logme'Access); end if; end log_run_deps; begin all_ports (id).subpackages.Iterate (get_rundeps'Access); HT.initialize_markers (content, markers); loop exit when not HT.next_line_present (content, markers); declare line : constant String := HT.extract_line (content, markers); deppkg : constant String := HT.part_1 (line, "@"); origin : constant String := HT.part_2 (line, "@"); begin exit when line = ""; declare procedure set_available (position : subpackage_crate.Cursor); subpackage : String := subpackage_from_pkgname (deppkg); target_id : port_index := ports_keys.Element (HT.SUS (origin)); target_pkg : String := calculate_package_name (target_id, subpackage); available : Boolean; procedure set_available (position : subpackage_crate.Cursor) is rec : subpackage_record renames subpackage_crate.Element (position); begin if not pkgfound and then HT.equivalent (rec.subpackage, subpackage) then available := (rec.remote_pkg or else rec.pkg_present) and then not rec.deletion_due; pkgfound := True; end if; end set_available; begin if valid_port_id (target_id) then pkgfound := False; all_ports (target_id).subpackages.Iterate (set_available'Access); else -- package seems to have a dependency that has been removed from the conspiracy LOG.obsolete_notice (message => origin & " has been removed from Ravenports", write_to_screen => debug_dep_check); return False; end if; counter := counter + 1; if counter > req_deps then -- package has more dependencies than we are looking for LOG.obsolete_notice (write_to_screen => debug_dep_check, message => headport & " package has more dependencies than the " & "port requires (" & HT.int2str (req_deps) & ")" & LAT.LF & "Query: " & LAT.LF & HT.USS (query_result) & "Tripped on: " & line); all_ports (id).subpackages.Iterate (log_run_deps'Access); return False; end if; if deppkg /= target_pkg then -- The version that the package requires differs from the -- version that Ravenports will now produce declare -- If the target package is GCC7, let version mismatches slide. We are -- probably bootstrapping a new sysroot compiler nbase : constant String := HT.USS (all_ports (target_id).port_namebase); variant : constant String := HT.USS (all_ports (target_id).port_variant); begin if nbase /= default_compiler and then not (nbase = "binutils" and then variant = "ravensys") then LOG.obsolete_notice (write_to_screen => debug_dep_check, message => "Current " & headport & " package depends on " & deppkg & ", but this is a different version than requirement of " & target_pkg & " (from " & origin & ")"); return False; else LOG.obsolete_notice (write_to_screen => debug_dep_check, message => "Ignored dependency check failure: " & "Current " & headport & " package depends on " & deppkg & ", but this is a different version than requirement of " & target_pkg & " (from " & origin & ")"); end if; end; end if; if not available then -- Even if all the versions are matching, we still need -- the package to be in repository. LOG.obsolete_notice (write_to_screen => debug_dep_check, message => headport & " package depends on " & target_pkg & " which doesn't exist or has been scheduled for deletion"); return False; end if; end; end; end loop; if counter < req_deps then -- The ports tree requires more dependencies than the existing package does LOG.obsolete_notice (write_to_screen => debug_dep_check, message => headport & " package has less dependencies than the port " & "requires (" & HT.int2str (req_deps) & ")" & LAT.LF & "Query: " & LAT.LF & HT.USS (query_result)); all_ports (id).subpackages.Iterate (log_run_deps'Access); return False; end if; -- If we get this far, the package dependencies match what the -- port tree requires exactly. This package passed sanity check. return True; exception when issue : others => LOG.obsolete_notice (write_to_screen => debug_dep_check, message => content & "Dependency check exception" & LAT.LF & EX.Exception_Message (issue)); return False; end passed_dependency_check; -------------------------------------------------------------------------------------------- -- package_scan_progress -------------------------------------------------------------------------------------------- function package_scan_progress return String is type percent is delta 0.01 digits 5; complete : port_index := 0; pc : percent; total : constant Float := Float (pkgscan_total); begin for k in scanners'Range loop complete := complete + pkgscan_progress (k); end loop; pc := percent (100.0 * Float (complete) / total); return " progress:" & pc'Img & "% " & LAT.CR; end package_scan_progress; -------------------------------------------------------------------------------------------- -- passed_abi_check -------------------------------------------------------------------------------------------- function passed_abi_check (repository : String; id : port_id; subpackage : String; skip_exist_check : Boolean := False) return Boolean is rec : port_record renames all_ports (id); pkg_base : constant String := PortScan.calculate_package_name (id, subpackage); fullpath : constant String := repository & "/" & pkg_base & arc_ext; pkg8 : constant String := HT.USS (PM.configuration.sysroot_pkg8); command : constant String := pkg8 & " query -F " & fullpath & " %q"; remocmd : constant String := pkg8 & " rquery -r " & HT.USS (external_repository) & " -U %q " & pkg_base; status : Integer; comres : HT.Text; begin if not skip_exist_check and then not DIR.Exists (Name => fullpath) then return False; end if; if repository = "" then comres := Unix.piped_command (remocmd, status); else comres := Unix.piped_command (command, status); end if; if status /= 0 then return False; end if; declare topline : String := HT.first_line (HT.USS (comres)); begin if HT.equivalent (abi_formats.calculated_abi, topline) or else HT.equivalent (abi_formats.calculated_alt_abi, topline) or else HT.equivalent (abi_formats.calc_abi_noarch, topline) or else HT.equivalent (abi_formats.calc_alt_abi_noarch, topline) then return True; end if; end; return False; end passed_abi_check; -------------------------------------------------------------------------------------------- -- passed_option_check -------------------------------------------------------------------------------------------- function passed_option_check (repository : String; id : port_id; subpackage : String; skip_exist_check : Boolean := False) return Boolean is rec : port_record renames all_ports (id); pkg_base : constant String := PortScan.calculate_package_name (id, subpackage); fullpath : constant String := repository & "/" & pkg_base & arc_ext; pkg8 : constant String := HT.USS (PM.configuration.sysroot_pkg8); command : constant String := pkg8 & " query -F " & fullpath & " %Ok:%Ov"; remocmd : constant String := pkg8 & " rquery -r " & HT.USS (external_repository) & " -U %Ok:%Ov " & pkg_base; status : Integer; comres : HT.Text; counter : Natural := 0; required : constant Natural := Natural (all_ports (id).options.Length); extquery : constant Boolean := (repository = ""); begin if id = port_match_failed or else not all_ports (id).scanned or else (not skip_exist_check and then not DIR.Exists (fullpath)) then LOG.obsolete_notice (write_to_screen => debug_opt_check, message => pkg_base & " => passed_option_check() failed sanity check."); return False; end if; if extquery then comres := Unix.piped_command (remocmd, status); else comres := Unix.piped_command (command, status); end if; if status /= 0 then if extquery then LOG.obsolete_notice (write_to_screen => debug_opt_check, message => pkg_base & " => failed to execute: " & remocmd); else LOG.obsolete_notice (write_to_screen => debug_opt_check, message => pkg_base & " => failed to execute: " & command); end if; LOG.obsolete_notice (write_to_screen => debug_opt_check, message => "output => " & HT.USS (comres)); return False; end if; declare command_result : constant String := HT.USS (comres); markers : HT.Line_Markers; begin HT.initialize_markers (command_result, markers); loop exit when not HT.next_line_present (command_result, markers); declare line : constant String := HT.extract_line (command_result, markers); namekey : constant String := HT.part_1 (line, ":"); knob : constant String := HT.part_2 (line, ":"); nametext : HT.Text := HT.SUS (namekey); knobval : Boolean; begin exit when line = ""; if HT.count_char (line, LAT.Colon) /= 1 then raise unknown_format with line; end if; if knob = "on" then knobval := True; elsif knob = "off" then knobval := False; else raise unknown_format with "knob=" & knob & "(" & line & ")"; end if; counter := counter + 1; if counter > required then -- package has more options than we are looking for LOG.obsolete_notice (write_to_screen => debug_opt_check, message => "options " & namekey & LAT.LF & pkg_base & " has more options than required (" & HT.int2str (required) & ")"); return False; end if; if all_ports (id).options.Contains (nametext) then if knobval /= all_ports (id).options.Element (nametext) then -- port option value doesn't match package option value if knobval then LOG.obsolete_notice (write_to_screen => debug_opt_check, message => pkg_base & " " & namekey & " is ON but specifcation says it must be OFF"); else LOG.obsolete_notice (write_to_screen => debug_opt_check, message => pkg_base & " " & namekey & " is OFF but specifcation says it must be ON"); end if; return False; end if; else -- Name of package option not found in port options LOG.obsolete_notice (write_to_screen => debug_opt_check, message => pkg_base & " option " & namekey & " is no longer present in the specification"); return False; end if; end; end loop; if counter < required then -- The ports tree has more options than the existing package LOG.obsolete_notice (write_to_screen => debug_opt_check, message => pkg_base & " has less options than required (" & HT.int2str (required) & ")"); return False; end if; -- If we get this far, the package options must match port options return True; end; exception when issue : others => LOG.obsolete_notice (write_to_screen => debug_opt_check, message => "option check exception" & LAT.LF & EX.Exception_Message (issue)); return False; end passed_option_check; -------------------------------------------------------------------------------------------- -- initial_package_scan -------------------------------------------------------------------------------------------- procedure initial_package_scan (repository : String; id : port_id; subpackage : String) is procedure set_position (position : subpackage_crate.Cursor); procedure set_delete (Element : in out subpackage_record); procedure set_present (Element : in out subpackage_record); procedure set_query (Element : in out subpackage_record); subpackage_position : subpackage_crate.Cursor := subpackage_crate.No_Element; query_result : HT.Text; procedure set_position (position : subpackage_crate.Cursor) is rec : subpackage_record renames subpackage_crate.Element (position); begin if HT.USS (rec.subpackage) = subpackage then subpackage_position := position; end if; end set_position; procedure set_delete (Element : in out subpackage_record) is begin Element.deletion_due := True; end set_delete; procedure set_present (Element : in out subpackage_record) is begin Element.pkg_present := True; end set_present; procedure set_query (Element : in out subpackage_record) is begin Element.pkg_dep_query := query_result; end set_query; use type subpackage_crate.Cursor; begin if id = port_match_failed or else not all_ports (id).scanned then return; end if; all_ports (id).subpackages.Iterate (set_position'Access); if subpackage_position = subpackage_crate.No_Element then return; end if; declare pkgname : constant String := calculate_package_name (id, subpackage); fullpath : constant String := repository & "/" & pkgname & arc_ext; msg_opt : constant String := pkgname & " failed option check."; msg_abi : constant String := pkgname & " failed architecture (ABI) check."; begin if DIR.Exists (fullpath) then all_ports (id).subpackages.Update_Element (subpackage_position, set_present'Access); else return; end if; if not passed_option_check (repository, id, subpackage, True) then LOG.obsolete_notice (msg_opt, True); all_ports (id).subpackages.Update_Element (subpackage_position, set_delete'Access); return; end if; if not passed_abi_check (repository, id, subpackage, True) then LOG.obsolete_notice (msg_abi, True); all_ports (id).subpackages.Update_Element (subpackage_position, set_delete'Access); return; end if; end; query_result := result_of_dependency_query (repository, id, subpackage); all_ports (id).subpackages.Update_Element (subpackage_position, set_query'Access); end initial_package_scan; -------------------------------------------------------------------------------------------- -- remote_package_scan -------------------------------------------------------------------------------------------- procedure remote_package_scan (id : port_id; subpackage : String) is procedure set_position (position : subpackage_crate.Cursor); procedure set_remote_on (Element : in out subpackage_record); procedure set_remote_off (Element : in out subpackage_record); procedure set_query (Element : in out subpackage_record); subpackage_position : subpackage_crate.Cursor := subpackage_crate.No_Element; query_result : HT.Text; procedure set_position (position : subpackage_crate.Cursor) is rec : subpackage_record renames subpackage_crate.Element (position); begin if HT.USS (rec.subpackage) = subpackage then subpackage_position := position; end if; end set_position; procedure set_remote_on (Element : in out subpackage_record) is begin Element.remote_pkg := True; end set_remote_on; procedure set_remote_off (Element : in out subpackage_record) is begin Element.remote_pkg := False; end set_remote_off; procedure set_query (Element : in out subpackage_record) is begin Element.pkg_dep_query := query_result; end set_query; use type subpackage_crate.Cursor; begin all_ports (id).subpackages.Iterate (set_position'Access); if subpackage_position = subpackage_crate.No_Element then return; end if; if passed_abi_check (repository => "", id => id, subpackage => subpackage, skip_exist_check => True) then all_ports (id).subpackages.Update_Element (subpackage_position, set_remote_on'Access); else return; end if; if not passed_option_check (repository => "", id => id, subpackage => subpackage, skip_exist_check => True) then all_ports (id).subpackages.Update_Element (subpackage_position, set_remote_off'Access); return; end if; query_result := result_of_dependency_query ("", id, subpackage); all_ports (id).subpackages.Update_Element (subpackage_position, set_query'Access); end remote_package_scan; -------------------------------------------------------------------------------------------- -- parallel_package_scan -------------------------------------------------------------------------------------------- procedure parallel_package_scan (repository : String; remote_scan : Boolean; show_progress : Boolean) is task type scan (lot : scanners); finished : array (scanners) of Boolean := (others => False); combined_wait : Boolean := True; label_shown : Boolean := False; aborted : Boolean := False; task body scan is procedure populate (cursor : subqueue.Cursor); procedure populate (cursor : subqueue.Cursor) is procedure check_subpackage (position : subpackage_crate.Cursor); target_port : port_index := subqueue.Element (cursor); important : constant Boolean := all_ports (target_port).scanned; procedure check_subpackage (position : subpackage_crate.Cursor) is rec : subpackage_record renames subpackage_crate.Element (position); subpackage : String := HT.USS (rec.subpackage); begin if not aborted and then important then if remote_scan and then not rec.never_remote then if not rec.pkg_present or else rec.deletion_due then remote_package_scan (target_port, subpackage); end if; else initial_package_scan (repository, target_port, subpackage); end if; end if; end check_subpackage; begin all_ports (target_port).subpackages.Iterate (check_subpackage'Access); mq_progress (lot) := mq_progress (lot) + 1; end populate; begin make_queue (lot).Iterate (populate'Access); finished (lot) := True; end scan; scan_01 : scan (lot => 1); scan_02 : scan (lot => 2); scan_03 : scan (lot => 3); scan_04 : scan (lot => 4); scan_05 : scan (lot => 5); scan_06 : scan (lot => 6); scan_07 : scan (lot => 7); scan_08 : scan (lot => 8); scan_09 : scan (lot => 9); scan_10 : scan (lot => 10); scan_11 : scan (lot => 11); scan_12 : scan (lot => 12); scan_13 : scan (lot => 13); scan_14 : scan (lot => 14); scan_15 : scan (lot => 15); scan_16 : scan (lot => 16); scan_17 : scan (lot => 17); scan_18 : scan (lot => 18); scan_19 : scan (lot => 19); scan_20 : scan (lot => 20); scan_21 : scan (lot => 21); scan_22 : scan (lot => 22); scan_23 : scan (lot => 23); scan_24 : scan (lot => 24); scan_25 : scan (lot => 25); scan_26 : scan (lot => 26); scan_27 : scan (lot => 27); scan_28 : scan (lot => 28); scan_29 : scan (lot => 29); scan_30 : scan (lot => 30); scan_31 : scan (lot => 31); scan_32 : scan (lot => 32); -- Expansion of cpu_range from 32 to 64 means 64 possible scanners scan_33 : scan (lot => 33); scan_34 : scan (lot => 34); scan_35 : scan (lot => 35); scan_36 : scan (lot => 36); scan_37 : scan (lot => 37); scan_38 : scan (lot => 38); scan_39 : scan (lot => 39); scan_40 : scan (lot => 40); scan_41 : scan (lot => 41); scan_42 : scan (lot => 42); scan_43 : scan (lot => 43); scan_44 : scan (lot => 44); scan_45 : scan (lot => 45); scan_46 : scan (lot => 46); scan_47 : scan (lot => 47); scan_48 : scan (lot => 48); scan_49 : scan (lot => 49); scan_50 : scan (lot => 50); scan_51 : scan (lot => 51); scan_52 : scan (lot => 52); scan_53 : scan (lot => 53); scan_54 : scan (lot => 54); scan_55 : scan (lot => 55); scan_56 : scan (lot => 56); scan_57 : scan (lot => 57); scan_58 : scan (lot => 58); scan_59 : scan (lot => 59); scan_60 : scan (lot => 60); scan_61 : scan (lot => 61); scan_62 : scan (lot => 62); scan_63 : scan (lot => 63); scan_64 : scan (lot => 64); begin while combined_wait loop delay 1.0; combined_wait := False; for j in scanners'Range loop if not finished (j) then combined_wait := True; exit; end if; end loop; if combined_wait then if not label_shown then label_shown := True; TIO.Put_Line ("Scanning existing packages."); end if; if show_progress then TIO.Put (scan_progress); end if; if Signals.graceful_shutdown_requested then aborted := True; end if; end if; end loop; end parallel_package_scan; -------------------------------------------------------------------------------------------- -- initialize_web_report -------------------------------------------------------------------------------------------- procedure initialize_web_report (num_builders : builders) is idle_slaves : constant dim_builder_state := (others => idle); reportdir : constant String := HT.USS (PM.configuration.dir_logs); sharedir : constant String := host_localbase & "/share/ravenadm"; ravenlogo : constant String := "/raven-project.png"; favicon : constant String := "/favicon.png"; webjs : constant String := "/progress.js"; webcss : constant String := "/progress.css"; begin DIR.Create_Path (reportdir); DIR.Copy_File (sharedir & ravenlogo, reportdir & ravenlogo); DIR.Copy_File (sharedir & favicon, reportdir & favicon); DIR.Copy_File (sharedir & webjs, reportdir & webjs); DIR.Copy_File (sharedir & webcss, reportdir & webcss); DIR.Copy_File (sharedir & "/progress.html", reportdir & "/index.html"); write_summary_json (active => True, states => idle_slaves, num_builders => num_builders, num_history_files => 0); end initialize_web_report; -------------------------------------------------------------------------------------------- -- write_summary_json -------------------------------------------------------------------------------------------- procedure write_summary_json (active : Boolean; states : dim_builder_state; num_builders : builders; num_history_files : Natural) is function TF (value : Boolean) return Natural; jsonfile : TIO.File_Type; filename : constant String := HT.USS (PM.configuration.dir_logs) & "/summary.json"; leftover : constant Integer := LOG.ports_remaining_to_build; slave : DPY.builder_rec; function TF (value : Boolean) return Natural is begin if value then return 1; else return 0; end if; end TF; begin TIO.Create (File => jsonfile, Mode => TIO.Out_File, Name => filename); TIO.Put (jsonfile, "{" & LAT.LF & " " & nv ("profile", HT.USS (PM.configuration.profile)) & LAT.LF); TIO.Put (jsonfile, " ," & nv ("kickoff", LOG.www_timestamp_start_time) & LAT.LF & " ," & nv ("kfiles", num_history_files) & LAT.LF & " ," & nv ("active", TF (active)) & LAT.LF & " ," & LAT.Quotation & "stats" & LAT.Quotation & LAT.Colon & "{" & LAT.LF); TIO.Put (jsonfile, " " & nv ("queued", LOG.port_counter_value (total)) & LAT.LF & " ," & nv ("built", LOG.port_counter_value (success)) & LAT.LF & " ," & nv ("failed", LOG.port_counter_value (failure)) & LAT.LF & " ," & nv ("ignored", LOG.port_counter_value (ignored)) & LAT.LF & " ," & nv ("skipped", LOG.port_counter_value (skipped)) & LAT.LF & " ," & nv ("remains", leftover) & LAT.LF & " ," & nv ("elapsed", LOG.elapsed_now) & LAT.LF & " ," & nv ("pkghour", LOG.hourly_build_rate) & LAT.LF & " ," & nv ("impulse", LOG.impulse_rate) & LAT.LF & " ," & nv ("swapinfo", DPY.fmtpc (get_swap_status, True)) & LAT.LF & " ," & nv ("load", DPY.fmtload (CYC.load_core (True))) & LAT.LF & " }" & LAT.LF & " ," & LAT.Quotation & "builders" & LAT.Quotation & LAT.Colon & "[" & LAT.LF); for b in builders'First .. num_builders loop if states (b) = shutdown then slave := CYC.builder_status (b, True, False); elsif states (b) = idle then slave := CYC.builder_status (b, False, True); else slave := CYC.builder_status (b); end if; if b = builders'First then TIO.Put (jsonfile, " {" & LAT.LF); else TIO.Put (jsonfile, " ,{" & LAT.LF); end if; TIO.Put (jsonfile, " " & nv ("ID", slave.slavid) & LAT.LF & " ," & nv ("elapsed", HT.trim (slave.Elapsed)) & LAT.LF & " ," & nv ("phase", HT.trim (slave.phase)) & LAT.LF & " ," & nv ("origin", HT.trim (slave.origin)) & LAT.LF & " ," & nv ("lines", HT.trim (slave.LLines)) & LAT.LF & " }" & LAT.LF); end loop; TIO.Put (jsonfile, " ]" & LAT.LF & "}" & LAT.LF); TIO.Close (jsonfile); exception when others => if TIO.Is_Open (jsonfile) then TIO.Close (jsonfile); end if; end write_summary_json; -------------------------------------------------------------------------------------------- -- swapinfo_command -------------------------------------------------------------------------------------------- function swapinfo_command return String is begin case platform_type is when dragonfly | freebsd => return "/usr/sbin/swapinfo -k"; when netbsd | openbsd => return "/sbin/swapctl -lk"; when linux => return "/sbin/swapon --bytes --show=NAME,SIZE,USED,PRIO"; when sunos => return "/usr/sbin/swap -l"; when macos => return "/usr/bin/vm_stat"; end case; end swapinfo_command; -------------------------------------------------------------------------------------------- -- get_swap_status -------------------------------------------------------------------------------------------- function get_swap_status return Float is type memtype is mod 2**64; command : String := swapinfo_command; status : Integer; comres : HT.Text; blocks_total : memtype := 0; blocks_used : memtype := 0; begin if platform_type = macos then -- MacOS has no limit, it will keep generating swapfiles as needed, so return 0.0 -- Anything divided by infinity is zero ... return 0.0; end if; comres := Unix.piped_command (command, status); if status /= 0 then return 200.0; -- [ERROR] Signal to set swap display to "N/A" end if; -- Throw first line away, e.g "Device 1K-blocks Used Avail ..." -- Distinguishes platforms though: -- Net/Free/Dragon start with "Device" -- Linux starts with "NAME" -- Solaris starts with "swapfile" -- On FreeBSD (DragonFly too?), when multiple swap used, ignore line starting "Total" declare command_result : String := HT.USS (comres); markers : HT.Line_Markers; line_present : Boolean; oneline_total : memtype; oneline_other : memtype; begin HT.initialize_markers (command_result, markers); -- Throw first line away (valid for all platforms line_present := HT.next_line_present (command_result, markers); if line_present then declare line : String := HT.extract_line (command_result, markers); begin null; end; else return 200.0; -- [ERROR] Signal to set swap display to "N/A" end if; case platform_type is when freebsd | dragonfly | netbsd | openbsd | linux | sunos => -- Normally 1 swap line, but there is no limit loop exit when not HT.next_line_present (command_result, markers); declare line : constant String := HT.strip_excessive_spaces (HT.extract_line (command_result, markers)); begin case platform_type is when freebsd | dragonfly | netbsd | openbsd => if HT.specific_field (line, 1) /= "Total" then blocks_total := blocks_total + memtype'Value (HT.specific_field (line, 2)); blocks_used := blocks_used + memtype'Value (HT.specific_field (line, 3)); end if; when sunos => oneline_total := memtype'Value (HT.specific_field (line, 4)); oneline_other := memtype'Value (HT.specific_field (line, 5)); blocks_total := blocks_total + oneline_total; blocks_used := blocks_used + (oneline_total - oneline_other); when linux => blocks_total := blocks_total + memtype'Value (HT.specific_field (line, 2)); blocks_used := blocks_used + memtype'Value (HT.specific_field (line, 3)); when macos => null; end case; exception when Constraint_Error => return 200.0; -- [ERROR] Signal to set swap display to "N/A" end; end loop; when macos => null; end case; end; if blocks_total = 0 then return 200.0; -- Signal to set swap display to "N/A" else return 100.0 * Float (blocks_used) / Float (blocks_total); end if; end get_swap_status; -------------------------------------------------------------------------------------------- -- initialize_display -------------------------------------------------------------------------------------------- procedure initialize_display (num_builders : builders) is begin if PM.configuration.avec_ncurses then curses_support := DPC.launch_monitor (num_builders); end if; end initialize_display; -------------------------------------------------------------------------------------------- -- nothing_left -------------------------------------------------------------------------------------------- function nothing_left (num_builders : builders) return Boolean is list_len : constant Integer := Integer (rank_queue.Length); begin return list_len = 0; end nothing_left; -------------------------------------------------------------------------------------------- -- shutdown_recommended -------------------------------------------------------------------------------------------- function shutdown_recommended (active_builders : Positive) return Boolean is list_len : constant Natural := Integer (rank_queue.Length); list_max : constant Positive := 2 * active_builders; num_wait : Natural := 0; cursor : ranking_crate.Cursor; QR : queue_record; begin if list_len = 0 or else list_len >= list_max then return False; end if; cursor := rank_queue.First; for k in 1 .. list_len loop QR := ranking_crate.Element (Position => cursor); if not all_ports (QR.ap_index).work_locked then num_wait := num_wait + 1; if num_wait >= active_builders then return False; end if; end if; cursor := ranking_crate.Next (Position => cursor); end loop; return True; end shutdown_recommended; -------------------------------------------------------------------------------------------- -- lock_package -------------------------------------------------------------------------------------------- procedure lock_package (id : port_id) is begin if id /= port_match_failed then all_ports (id).work_locked := True; end if; end lock_package; -------------------------------------------------------------------------------------------- -- top_buildable_port -------------------------------------------------------------------------------------------- function top_buildable_port return port_id is list_len : constant Integer := Integer (rank_queue.Length); cursor : ranking_crate.Cursor; QR : queue_record; result : port_id := port_match_failed; begin if list_len = 0 then return result; end if; cursor := rank_queue.First; for k in 1 .. list_len loop QR := ranking_crate.Element (Position => cursor); if not all_ports (QR.ap_index).work_locked and then all_ports (QR.ap_index).blocked_by.Is_Empty then result := QR.ap_index; exit; end if; cursor := ranking_crate.Next (Position => cursor); end loop; if Signals.graceful_shutdown_requested then return port_match_failed; end if; return result; end top_buildable_port; -------------------------------------------------------------------------------------------- -- parse_and_transform_buildsheet -------------------------------------------------------------------------------------------- procedure parse_and_transform_buildsheet (specification : in out Port_Specification.Portspecs; successful : out Boolean; buildsheet : String; variant : String; portloc : String; excl_targets : Boolean; avoid_dialog : Boolean; for_webpage : Boolean; sysrootver : sysroot_characteristics) is function read_option_file return Boolean; function launch_and_read (optfile, cookie : String) return Boolean; makefile : String := portloc & "/Makefile"; dir_opt : constant String := HT.USS (PM.configuration.dir_options); function read_option_file return Boolean is result : Boolean := True; required : Natural := specification.get_list_length (Port_Specification.sp_opts_standard); begin IFM.scan_file (directory => dir_opt, filename => specification.get_namebase); declare list : constant String := IFM.show_value (section => "parameters", name => "available"); num_opt : Natural := HT.count_char (list, LAT.Comma) + 1; begin if num_opt /= required then result := False; end if; for item in 1 .. num_opt loop declare setting : Boolean; good : Boolean := True; nv_name : String := HT.specific_field (list, item, ","); nv_value : String := IFM.show_value ("options", nv_name); begin if nv_value = "true" then setting := True; elsif nv_value = "false" then setting := False; else good := False; result := False; end if; if good then if specification.option_exists (nv_name) then PST.define_option_setting (specification, nv_name, setting); else result := False; end if; end if; end; end loop; end; return result; exception when others => return False; end read_option_file; function launch_and_read (optfile, cookie : String) return Boolean is begin PST.set_option_to_default_values (specification); if not avoid_dialog then if not DLG.launch_dialog (specification) then return False; end if; if DIR.Exists (cookie) then -- We keep the already-set standard option settings return True; end if; if not DIR.Exists (optfile) then TIO.Put_Line ("Saved option file and cookie missing after dialog executed. bug?"); return False; end if; if not read_option_file then TIO.Put_Line ("Saved option file invalid after dialog executed. bug?"); return False; end if; end if; return True; end launch_and_read; begin PAR.parse_specification_file (dossier => buildsheet, spec => specification, opsys_focus => platform_type, arch_focus => sysrootver.arch, success => successful, stop_at_targets => excl_targets, extraction_dir => portloc); if not successful then TIO.Put_Line ("Failed to parse " & buildsheet); TIO.Put_Line (specification.get_parse_error); return; end if; if not specification.variant_exists (variant) then TIO.Put_Line ("The specified variant '" & variant & "' is invalid."); TIO.Put_Line ("Try again with a valid variant"); successful := False; return; end if; PST.set_option_defaults (specs => specification, variant => variant, opsys => platform_type, arch_standard => sysrootver.arch, osrelease => HT.USS (sysrootver.release)); -- If no available options, skip (remember, if variants there are ALWAYS options -- otherwise -- if batch mode, ignore cookies. if no option file, use default values. -- if not batch mode: -- If option file, use it. -- if no option file: if cookie exists, used default values, otherwise show dialog declare optfile : constant String := dir_opt & "/" & specification.get_namebase; cookie : constant String := dir_opt & "/defconf_cookies/" & specification.get_namebase; begin if variant = variant_standard then if specification.standard_options_present then -- This port has at least one user-definable option if PM.configuration.batch_mode then -- In batch mode, option settings are optional. Use default values if not set if DIR.Exists (optfile) then if not read_option_file then TIO.Put_Line ("BATCH MODE ERROR: Invalid option configuration of " & specification.get_namebase & ":standard port"); TIO.Put_Line ("Run ravenadm set-options " & specification.get_namebase & " to rectify the issue"); TIO.Put_Line ("Alternatively, set configuration option '[Q] Assume " & "default options' to False"); successful := False; return; end if; else PST.set_option_to_default_values (specification); end if; else if DIR.Exists (optfile) then if not read_option_file then if not launch_and_read (optfile, cookie) then successful := False; return; end if; end if; else if DIR.Exists (cookie) then PST.set_option_to_default_values (specification); else if not launch_and_read (optfile, cookie) then successful := False; return; end if; end if; end if; end if; end if; else -- All defined options are dedicated to variant definition (nothing to configure) PST.set_option_to_default_values (specification); end if; end; if for_webpage then specification.do_not_apply_opsys_dependencies; end if; PST.apply_directives (specs => specification, variant => variant, arch_standard => sysrootver.arch, osmajor => HT.USS (sysrootver.major)); PST.set_outstanding_ignore (specs => specification, variant => variant, opsys => platform_type, arch_standard => sysrootver.arch, osrelease => HT.USS (sysrootver.release), osmajor => HT.USS (sysrootver.major)); if portloc /= "" then PST.shift_extra_patches (specs => specification, extract_dir => portloc); PSM.generator (specs => specification, variant => variant, opsys => platform_type, arch => sysrootver.arch, output_file => makefile); end if; end parse_and_transform_buildsheet; -------------------------------------------------------------------------------------------- -- build_subpackages -------------------------------------------------------------------------------------------- function build_subpackages (builder : builders; sequence_id : port_id; sysrootver : sysroot_characteristics; interactive : Boolean := False; enterafter : String := "") return Boolean is function get_buildsheet return String; namebase : String := HT.USS (all_ports (sequence_id).port_namebase); variant : String := HT.USS (all_ports (sequence_id).port_variant); bucket : String := all_ports (sequence_id).bucket; portloc : String := HT.USS (PM.configuration.dir_buildbase) & "/" & REP.slave_name (builder) & "/port"; function get_buildsheet return String is buckname : constant String := "/bucket_" & bucket & "/" & namebase; begin if all_ports (sequence_id).unkind_custom then return HT.USS (PM.configuration.dir_profile) & "/unkindness" & buckname; else return HT.USS (PM.configuration.dir_conspiracy) & buckname; end if; end get_buildsheet; buildsheet : constant String := get_buildsheet; specification : Port_Specification.Portspecs; successful : Boolean; begin parse_and_transform_buildsheet (specification => specification, successful => successful, buildsheet => buildsheet, variant => variant, portloc => portloc, excl_targets => False, avoid_dialog => True, for_webpage => False, sysrootver => sysrootver); if not successful then return False; end if; return CYC.build_package (id => builder, specification => specification, sequence_id => sequence_id, interactive => interactive, interphase => enterafter); end build_subpackages; -------------------------------------------------------------------------------------------- -- eliminate_obsolete_packages -------------------------------------------------------------------------------------------- procedure eliminate_obsolete_packages is procedure search (position : subpackage_crate.Cursor); procedure kill (position : string_crate.Cursor); id : port_index; counter : Natural := 0; repo : constant String := HT.USS (PM.configuration.dir_repository) & "/"; procedure search (position : subpackage_crate.Cursor) is rec : subpackage_record renames subpackage_crate.Element (position); subpackage : constant String := HT.USS (rec.subpackage); package_name : HT.Text := HT.SUS (calculate_package_name (id, subpackage) & arc_ext); begin if package_list.Contains (package_name) then package_list.Delete (package_list.Find_Index (package_name)); end if; end search; procedure kill (position : string_crate.Cursor) is package_name : constant String := HT.USS (string_crate.Element (position)); begin DIR.Delete_File (repo & package_name); counter := counter + 1; exception when others => TIO.Put (LAT.LF & "Failed to remove " & package_name); end kill; begin for index in port_index'First .. last_port loop id := index; all_ports (index).subpackages.Iterate (search'Access); end loop; TIO.Put ("Removing obsolete packages ... "); package_list.Iterate (kill'Access); TIO.Put_Line ("done! (packages deleted: " & HT.int2str (counter) & ")"); end eliminate_obsolete_packages; end PortScan.Operations;
reznikmm/matreshka
Ada
4,647
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Text.Number_Position_Attributes is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Text_Number_Position_Attribute_Node is begin return Self : Text_Number_Position_Attribute_Node do Matreshka.ODF_Text.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Text_Prefix); end return; end Create; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Text_Number_Position_Attribute_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Number_Position_Attribute; end Get_Local_Name; begin Matreshka.DOM_Documents.Register_Attribute (Matreshka.ODF_String_Constants.Text_URI, Matreshka.ODF_String_Constants.Number_Position_Attribute, Text_Number_Position_Attribute_Node'Tag); end Matreshka.ODF_Text.Number_Position_Attributes;
zhmu/ananas
Ada
2,062
ads
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- C L E A N -- -- -- -- S p e c -- -- -- -- Copyright (C) 2003-2022, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the implementation of gnatclean (see gnatclean.adb) package Clean is procedure Gnatclean; -- The driver for gnatclean end Clean;
optikos/oasis
Ada
468
ads
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Program.Nodes.Generic_Vectors; with Program.Elements.Discrete_Ranges; package Program.Nodes.Discrete_Range_Vectors is new Program.Nodes.Generic_Vectors (Program.Elements.Discrete_Ranges.Discrete_Range_Vector); pragma Preelaborate (Program.Nodes.Discrete_Range_Vectors);
reznikmm/jwt
Ada
7,325
adb
-- Copyright (c) 2020 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with GNAT.SHA256; with League.JSON.Values; with JWS.Integers; with JWS.To_Base_64_URL; package body JWS.RS256 is function "+" (V : Wide_Wide_String) return League.Strings.Universal_String renames League.Strings.To_Universal_String; type Private_Key (N, E, D, P, Q, E1, E2, C : Positive) is record Modulus : JWS.Integers.Number (1 .. N); -- n Public_Exponent : JWS.Integers.Number (1 .. E); -- e Private_Exponent : JWS.Integers.Number (1 .. D); -- d Prime_1 : JWS.Integers.Number (1 .. P); -- p Prime_2 : JWS.Integers.Number (1 .. Q); -- q Exponent_1 : JWS.Integers.Number (1 .. E1); -- d mod (p-1) Exponent_2 : JWS.Integers.Number (1 .. E2); -- d mod (q-1) Coefficient : JWS.Integers.Number (1 .. C); -- (inver. of q) mod p end record; type Public_Key (N, E : Positive) is record Modulus : JWS.Integers.Number (1 .. N); -- n Public_Exponent : JWS.Integers.Number (1 .. E); -- e end record; function Do_Sign (Data : Ada.Streams.Stream_Element_Array; Key : Private_Key) return Ada.Streams.Stream_Element_Array; function Do_Validate (Data : Ada.Streams.Stream_Element_Array; Key : Public_Key; Sign : Ada.Streams.Stream_Element_Array) return Boolean; package Read_DER is function Read_Private_Key (Input : Ada.Streams.Stream_Element_Array) return Private_Key; function Read_Public_Key (Input : Ada.Streams.Stream_Element_Array) return Public_Key; end Read_DER; function Signature (Data : League.Stream_Element_Vectors.Stream_Element_Vector; Secret : Ada.Streams.Stream_Element_Array) return League.Stream_Element_Vectors.Stream_Element_Vector; function Validate (Data : League.Stream_Element_Vectors.Stream_Element_Vector; Secret : Ada.Streams.Stream_Element_Array; Value : League.Stream_Element_Vectors.Stream_Element_Vector) return Boolean; package body Read_DER is separate; procedure Encode (Data : Ada.Streams.Stream_Element_Array; Value : out Ada.Streams.Stream_Element_Array); -- Calculate EMSA-PKCS1-V1_5-ENCODE from RFC 8017 ------------- -- Do_Sign -- ------------- function Do_Sign (Data : Ada.Streams.Stream_Element_Array; Key : Private_Key) return Ada.Streams.Stream_Element_Array is k : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Key.N * 4); EM : Ada.Streams.Stream_Element_Array (1 .. k); M : JWS.Integers.Number (1 .. Key.N); S : JWS.Integers.Number (1 .. Key.N); begin Encode (Data, EM); JWS.Integers.BER_Decode (EM, M); -- s = m^d mod n. JWS.Integers.Power (M, Key.Private_Exponent, Key.Modulus, S); JWS.Integers.BER_Encode (S, EM); return EM; end Do_Sign; ----------------- -- Do_Validate -- ----------------- function Do_Validate (Data : Ada.Streams.Stream_Element_Array; Key : Public_Key; Sign : Ada.Streams.Stream_Element_Array) return Boolean is use type Ada.Streams.Stream_Element_Array; k : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Key.N * 4); EM : Ada.Streams.Stream_Element_Array (1 .. k); ME : Ada.Streams.Stream_Element_Array (1 .. k); S : JWS.Integers.Number (1 .. Key.N); M : JWS.Integers.Number (1 .. Key.N); begin Encode (Data, EM); JWS.Integers.BER_Decode (Sign, S); JWS.Integers.Power (S, Key.Public_Exponent, Key.Modulus, M); JWS.Integers.BER_Encode (M, ME); return EM = ME; end Do_Validate; ------------ -- Encode -- ------------ procedure Encode (Data : Ada.Streams.Stream_Element_Array; Value : out Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; H : constant GNAT.SHA256.Binary_Message_Digest := GNAT.SHA256.Digest (Data); T : constant Ada.Streams.Stream_Element_Array := (16#30#, 16#31#, 16#30#, 16#0d#, 16#06#, 16#09#, 16#60#, 16#86#, 16#48#, 16#01#, 16#65#, 16#03#, 16#04#, 16#02#, 16#01#, 16#05#, 16#00#, 16#04#, 16#20#) & H; begin Value := (00, 01) & (1 .. Value'Length - T'Length - 3 => 16#FF#) & 00 & T; null; end Encode; ---------------- -- Public_JWK -- ---------------- function Public_JWK (Raw_Key : Ada.Streams.Stream_Element_Array) return League.JSON.Objects.JSON_Object is function "-" (V : Wide_Wide_String) return League.JSON.Values.JSON_Value is (League.JSON.Values.To_JSON_Value (+V)); function "-" (V : JWS.Integers.Number) return League.JSON.Values.JSON_Value; --------- -- "-" -- --------- function "-" (V : JWS.Integers.Number) return League.JSON.Values.JSON_Value is use type Ada.Streams.Stream_Element; use type Ada.Streams.Stream_Element_Count; Raw : Ada.Streams.Stream_Element_Array (1 .. V'Length * 4); From : Ada.Streams.Stream_Element_Count := Raw'Last + 1; Vector : League.Stream_Element_Vectors.Stream_Element_Vector; begin JWS.Integers.BER_Encode (V, Raw); for J in Raw'Range loop if Raw (J) /= 0 then From := J; exit; end if; end loop; Vector.Append (Raw (From .. Raw'Last)); return League.JSON.Values.To_JSON_Value (JWS.To_Base_64_URL (Vector)); end "-"; Key : constant Public_Key := Read_DER.Read_Public_Key (Raw_Key); begin return Result : League.JSON.Objects.JSON_Object do Result.Insert (+"kty", -"RSA"); Result.Insert (+"e", -Key.Public_Exponent); Result.Insert (+"n", -Key.Modulus); end return; end Public_JWK; --------------- -- Signature -- --------------- function Signature (Data : League.Stream_Element_Vectors.Stream_Element_Vector; Secret : Ada.Streams.Stream_Element_Array) return League.Stream_Element_Vectors.Stream_Element_Vector is Key : constant Private_Key := Read_DER.Read_Private_Key (Secret); begin return League.Stream_Element_Vectors.To_Stream_Element_Vector (Do_Sign (Data.To_Stream_Element_Array, Key)); end Signature; -------------- -- Validate -- -------------- function Validate (Data : League.Stream_Element_Vectors.Stream_Element_Vector; Secret : Ada.Streams.Stream_Element_Array; Value : League.Stream_Element_Vectors.Stream_Element_Vector) return Boolean is Key : constant Public_Key := Read_DER.Read_Public_Key (Secret); begin return Do_Validate (Data.To_Stream_Element_Array, Key, Value.To_Stream_Element_Array); end Validate; begin RS256_Signature_Link := Signature'Access; RS256_Validation_Link := Validate'Access; end JWS.RS256;
damaki/SPARKNaCl
Ada
3,159
adb
with SPARKNaCl.Utils; package body SPARKNaCl.Scalar with SPARK_Mode => On is pragma Warnings (GNATProve, Off, "pragma * ignored (not yet supported)"); Nine : constant Bytes_32 := (9, others => 0); GF_121665 : constant Normal_GF := (16#DB41#, 1, others => 0); -------------------------------------------------------- -- Scalar multiplication -------------------------------------------------------- function Mult (N : in Bytes_32; P : in Bytes_32) return Bytes_32 is -- X and Z are variables not constants, so can be sanitized X : Normal_GF := Utils.Unpack_25519 (P); Z : Bytes_32 := (N (0) and 248) & N (1 .. 30) & ((N (31) and 127) or 64); Swap : Boolean; CB : Byte; Shift : Natural; A, B, C, D, E, F : Normal_GF; -- Additional temporaries needed to avoid aliasing of -- function results and their arguments. This enables RSO -- in all function/operator calls below. T1, T2 : Normal_GF; Result : Bytes_32; begin B := X; C := GF_0; A := GF_1; D := GF_1; for I in reverse U32 range 0 .. 254 loop pragma Loop_Optimize (No_Unroll); CB := Z (I32 (Shift_Right (I, 3))); Shift := Natural (I and 7); Swap := Boolean'Val (Shift_Right (CB, Shift) mod 2); pragma Loop_Invariant (A in Normal_GF and B in Normal_GF and C in Normal_GF and D in Normal_GF); Utils.CSwap16 (A, B, Swap); Utils.CSwap16 (C, D, Swap); -- Single binary operator or unary function call per statement to -- avoid introduction of a compiler-generated temporary that we -- won't be able to sanitize. E := A + C; T1 := A - C; C := B + D; T2 := B - D; D := Square (E); F := Square (T1); A := C * T1; C := T2 * E; E := A + C; T2 := A - C; B := Square (T2); T1 := D - F; A := T1 * GF_121665; T2 := A + D; C := T1 * T2; A := D * F; D := B * X; B := Square (E); Utils.CSwap16 (A, B, Swap); Utils.CSwap16 (C, D, Swap); end loop; -- Compute Result in 3 steps here to avoid introducing a -- compiler-generated temporary which we won't be able -- to sanitize. T1 := Utils.Inv_25519 (C); T2 := A * T1; Result := Utils.Pack_25519 (T2); -- Sanitize as per WireGuard sources pragma Warnings (GNATProve, Off, "statement has no effect"); Sanitize_Boolean (Swap); Sanitize (Z); Sanitize_GF16 (X); Sanitize_GF16 (A); Sanitize_GF16 (B); Sanitize_GF16 (C); Sanitize_GF16 (D); Sanitize_GF16 (E); Sanitize_GF16 (F); Sanitize_GF16 (T1); Sanitize_GF16 (T2); pragma Unreferenced (Swap, Z, X, A, B, C, D, E, F, T1, T2); return Result; end Mult; function Mult_Base (N : in Bytes_32) return Bytes_32 is begin return Mult (N, Nine); end Mult_Base; end SPARKNaCl.Scalar;
zhmu/ananas
Ada
6,246
adb
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . P A C K _ 8 1 -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2022, 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.Storage_Elements; with System.Unsigned_Types; package body System.Pack_81 is subtype Bit_Order is System.Bit_Order; Reverse_Bit_Order : constant Bit_Order := Bit_Order'Val (1 - Bit_Order'Pos (System.Default_Bit_Order)); subtype Ofs is System.Storage_Elements.Storage_Offset; subtype Uns is System.Unsigned_Types.Unsigned; subtype N07 is System.Unsigned_Types.Unsigned range 0 .. 7; use type System.Storage_Elements.Storage_Offset; use type System.Unsigned_Types.Unsigned; type Cluster is record E0, E1, E2, E3, E4, E5, E6, E7 : Bits_81; end record; for Cluster use record E0 at 0 range 0 * Bits .. 0 * Bits + Bits - 1; E1 at 0 range 1 * Bits .. 1 * Bits + Bits - 1; E2 at 0 range 2 * Bits .. 2 * Bits + Bits - 1; E3 at 0 range 3 * Bits .. 3 * Bits + Bits - 1; E4 at 0 range 4 * Bits .. 4 * Bits + Bits - 1; E5 at 0 range 5 * Bits .. 5 * Bits + Bits - 1; E6 at 0 range 6 * Bits .. 6 * Bits + Bits - 1; E7 at 0 range 7 * Bits .. 7 * Bits + Bits - 1; end record; for Cluster'Size use Bits * 8; for Cluster'Alignment use Integer'Min (Standard'Maximum_Alignment, 1 + 1 * Boolean'Pos (Bits mod 2 = 0) + 2 * Boolean'Pos (Bits mod 4 = 0)); -- Use maximum possible alignment, given the bit field size, since this -- will result in the most efficient code possible for the field. type Cluster_Ref is access Cluster; type Rev_Cluster is new Cluster with Bit_Order => Reverse_Bit_Order, Scalar_Storage_Order => Reverse_Bit_Order; type Rev_Cluster_Ref is access Rev_Cluster; ------------ -- Get_81 -- ------------ function Get_81 (Arr : System.Address; N : Natural; Rev_SSO : Boolean) return Bits_81 is A : constant System.Address := Arr + Bits * Ofs (Uns (N) / 8); C : Cluster_Ref with Address => A'Address, Import; RC : Rev_Cluster_Ref with Address => A'Address, Import; begin if Rev_SSO then case N07 (Uns (N) mod 8) is when 0 => return RC.E0; when 1 => return RC.E1; when 2 => return RC.E2; when 3 => return RC.E3; when 4 => return RC.E4; when 5 => return RC.E5; when 6 => return RC.E6; when 7 => return RC.E7; end case; else case N07 (Uns (N) mod 8) is when 0 => return C.E0; when 1 => return C.E1; when 2 => return C.E2; when 3 => return C.E3; when 4 => return C.E4; when 5 => return C.E5; when 6 => return C.E6; when 7 => return C.E7; end case; end if; end Get_81; ------------ -- Set_81 -- ------------ procedure Set_81 (Arr : System.Address; N : Natural; E : Bits_81; Rev_SSO : Boolean) is A : constant System.Address := Arr + Bits * Ofs (Uns (N) / 8); C : Cluster_Ref with Address => A'Address, Import; RC : Rev_Cluster_Ref with Address => A'Address, Import; begin if Rev_SSO then case N07 (Uns (N) mod 8) is when 0 => RC.E0 := E; when 1 => RC.E1 := E; when 2 => RC.E2 := E; when 3 => RC.E3 := E; when 4 => RC.E4 := E; when 5 => RC.E5 := E; when 6 => RC.E6 := E; when 7 => RC.E7 := E; end case; else case N07 (Uns (N) mod 8) is when 0 => C.E0 := E; when 1 => C.E1 := E; when 2 => C.E2 := E; when 3 => C.E3 := E; when 4 => C.E4 := E; when 5 => C.E5 := E; when 6 => C.E6 := E; when 7 => C.E7 := E; end case; end if; end Set_81; end System.Pack_81;
zhmu/ananas
Ada
4,983
ads
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . V X W O R K S . E X T -- -- -- -- S p e c -- -- -- -- Copyright (C) 2008-2022, Free Software Foundation, Inc. -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. 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/>. -- -- -- ------------------------------------------------------------------------------ -- This package provides vxworks specific support functions needed -- by System.OS_Interface. -- This is the VxWorks 6 kernel version of this package with Interfaces.C; package System.VxWorks.Ext is pragma Preelaborate; subtype SEM_ID is Long_Integer; -- typedef struct semaphore *SEM_ID; type sigset_t is mod 2 ** Long_Long_Integer'Size; type t_id is new Long_Integer; subtype int is Interfaces.C.int; subtype unsigned is Interfaces.C.unsigned; type STATUS is new int; -- Equivalent of the C type STATUS OK : constant STATUS := 0; ERROR : constant STATUS := -1; type BOOL is new int; -- Equivalent of the C type BOOL type vx_freq_t is new unsigned; -- Equivalent of the C type _Vx_freq_t type Interrupt_Handler is access procedure (parameter : System.Address); pragma Convention (C, Interrupt_Handler); type Interrupt_Vector is new System.Address; function Int_Lock return int; pragma Convention (C, Int_Lock); procedure Int_Unlock (Old : int); pragma Convention (C, Int_Unlock); function Interrupt_Connect (Vector : Interrupt_Vector; Handler : Interrupt_Handler; Parameter : System.Address := System.Null_Address) return STATUS; pragma Import (C, Interrupt_Connect, "intConnect"); function Interrupt_Context return BOOL; pragma Import (C, Interrupt_Context, "intContext"); function Interrupt_Number_To_Vector (intNum : int) return Interrupt_Vector; pragma Import (C, Interrupt_Number_To_Vector, "__gnat_inum_to_ivec"); function semDelete (Sem : SEM_ID) return STATUS; pragma Convention (C, semDelete); function Task_Cont (tid : t_id) return STATUS; pragma Convention (C, Task_Cont); function Task_Stop (tid : t_id) return STATUS; pragma Convention (C, Task_Stop); function kill (pid : t_id; sig : int) return int; pragma Import (C, kill, "kill"); function getpid return t_id; pragma Import (C, getpid, "taskIdSelf"); function Set_Time_Slice (ticks : int) return STATUS; pragma Import (C, Set_Time_Slice, "kernelTimeSlice"); type UINT64 is mod 2 ** Long_Long_Integer'Size; function tickGet return UINT64; -- Needed for ravenscar-cert pragma Import (C, tickGet, "tick64Get"); -------------------------------- -- Processor Affinity for SMP -- -------------------------------- function taskCpuAffinitySet (tid : t_id; CPU : int) return int; pragma Convention (C, taskCpuAffinitySet); -- For SMP run-times set the CPU affinity. -- For uniprocessor systems return ERROR status. function taskMaskAffinitySet (tid : t_id; CPU_Set : unsigned) return int; pragma Convention (C, taskMaskAffinitySet); -- For SMP run-times set the CPU mask affinity. -- For uniprocessor systems return ERROR status. end System.VxWorks.Ext;
DrenfongWong/tkm-rpc
Ada
77
ads
package Tkmrpc.Operation_Handlers.Ike is end Tkmrpc.Operation_Handlers.Ike;
jquorning/iNow
Ada
4,298
adb
-- -- The author disclaims copyright to this source code. In place of -- a legal notice, here is a blessing: -- -- May you do good and not evil. -- May you find forgiveness for yourself and forgive others. -- May you share freely, not taking more than you give. -- package body Readline_Helper is type String_Access is access constant String; type Compl_List is array (Natural range <>) of String_Access; -- List of commands to match function Base_Commands (Text : String; State : Integer) return String; -- Return to-do-it commands one by one iterating by State from 0 and up. function Null_Commands (Text : String; State : Integer) return String; -- Return NUL string unconditionally signalling no completions. function Find (Text : String; State : Integer; List : Compl_List) return String; -- Find Text in List. Is to be called with State iterating -- from 0 and up. Returns matching string from List or "" when -- no more entrys matched. function "-" (S : String) return String_Access; -- Helper. function "-" (S : String) return String_Access is begin return new String'(S); end "-"; function Find (Text : String; State : Integer; List : Compl_List) return String is Count : Integer := 0; begin for Ent of List loop declare ST : constant String := Ent.all; begin if Text'Length <= ST'Length and then Text = ST (Text'Range) then if State = Count then return ST; end if; Count := Count + 1; end if; end; end loop; return ""; end Find; Command_List : constant Compl_List := (-"view", -"lists", -"set", -"add", -"move", -"trans", -"help", -"quit", -"show", -"event"); function Base_Commands (Text : String; State : Integer) return String is Match : constant String := Find (Text, State, Command_List); begin return Match; end Base_Commands; function Null_Commands (Text : String; State : Integer) return String is pragma Unreferenced (Text, State); begin return ""; end Null_Commands; -- function Entry_Func (Text : String; State : Integer) return String; -- function Entry_Func (Text : String; State : Integer) return String is -- begin -- case Command is -- when Base => return Find (Text, State, BAS); -- when Loop_1 => return Find (Text, State, CMD1); -- when Loop_2 => return Find (Text, State, CMD2); -- when Define => return Find (Text, State, KEY); -- when T_Procedure => null; -- -- return Symbols.Find (Symbols.K_Procedure, -- -- Text, State); -- when Load => return ""; -- when Save => return ""; -- when others => return ""; -- end case; -- end Entry_Func; -- procedure Parse (S : String); -- procedure Parse (S : String) is -- use Ada.Strings.Fixed; -- Pos : constant Natural := Index (S, " "); -- CMD : constant String := S (S'First .. Pos - 1); -- -- LC : constant String := To_Lower (CMD); -- begin -- if CMD = "" then Command := Base; -- elsif CMD = ".save" then Command := Save; -- elsif CMD = ".load" then Command := Load; -- elsif CMD = ".def" then Command := Define; -- elsif CMD = "loop1" then Command := Loop_1; -- elsif CMD = "loop2" then Command := Loop_2; -- elsif CMD = "procedure" then Command := T_Procedure; -- else Command := None; -- end if; -- end Parse; function Completer (Full_Line : String; Text : String; Start, Last : Integer) return GNATCOLL.Readline.Possible_Completions is pragma Unreferenced (Full_Line, Last); begin -- Parse (Full_Line); if Start = 0 then return GNATCOLL.Readline.Completion_Matches (Text, Base_Commands'Access); end if; return GNATCOLL.Readline.Completion_Matches (Text, Null_Commands'Access); end Completer; end Readline_Helper;
jquorning/iNow
Ada
811
ads
-- -- The author disclaims copyright to this source code. In place of -- a legal notice, here is a blessing: -- -- May you do good and not evil. -- May you find forgiveness for yourself and forgive others. -- May you share freely, not taking more than you give. -- with Status; package Decoration is use Status; function Status_Image (Status : Status_Type) return String; -- Return string descriping Status of a job. function Title_Image (Title : String; Status : Status_Type) return String; -- Return Title with optional decoration depending on Status. function Current_Image (Status : Status_Type) return String; -- Return marking when current. end Decoration;
AdaCore/libadalang
Ada
1,721
adb
procedure Test_Float_Attrs is A : Float := Float'Floor (12.0); pragma Test_Statement; B : Float := Float'Rounding (A); pragma Test_Statement; C : Float := Float'Ceiling (B + 15.0); pragma Test_Statement; D : Float := Float'Truncation (C + 0.120834); pragma Test_Statement; E : Float := Float'Copy_Sign (C, D); pragma Test_Statement; F : Float := Float'Remainder (D, E); pragma Test_Statement; G : Float := Float'Adjacent (E, F); pragma Test_Statement; H : Float := Float'Invalid_Value; pragma Test_Statement; I : Float := Float'Model_Small; pragma Test_Statement; J : Float := Float'Model_Epsilon; pragma Test_Statement; K : Float := Float'Machine_Rounding (A); pragma Test_Statement; L : Integer := Float'Exponent (A); pragma Test_Statement; M : Integer := Float'Machine_Radix; pragma Test_Statement; N : Integer := Duration'Small_Numerator; pragma Test_Statement; O : Integer := Duration'Small_Denominator; pragma Test_Statement; P : Boolean := Float'Machine_Overflows; pragma Test_Statement; Q : Float := Float'Scaling (A, 2); pragma Test_Statement; R : Boolean := Float'Machine_Rounds; pragma Test_Statement; S : Float := Float'Machine (1.0E+11); pragma Test_Statement; T : Float := Float'Compose(A, 2); pragma Test_Statement; U : Float := Float'Fraction (A); pragma Test_Statement; V : Integer := Float'Machine_Emin; pragma Test_Statement; W : Integer := Float'Machine_Emax; pragma Test_Statement; X : Float := Float'Safe_First; pragma Test_Statement; Y : Float := Float'Safe_Last; pragma Test_Statement; begin null; end Test_Float_Attrs;
reznikmm/matreshka
Ada
5,328
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.Generic_Collections; package AMF.UMLDI.UML_Diagram_Elements.Collections is pragma Preelaborate; package UMLDI_UML_Diagram_Element_Collections is new AMF.Generic_Collections (UMLDI_UML_Diagram_Element, UMLDI_UML_Diagram_Element_Access); type Set_Of_UMLDI_UML_Diagram_Element is new UMLDI_UML_Diagram_Element_Collections.Set with null record; Empty_Set_Of_UMLDI_UML_Diagram_Element : constant Set_Of_UMLDI_UML_Diagram_Element; type Ordered_Set_Of_UMLDI_UML_Diagram_Element is new UMLDI_UML_Diagram_Element_Collections.Ordered_Set with null record; Empty_Ordered_Set_Of_UMLDI_UML_Diagram_Element : constant Ordered_Set_Of_UMLDI_UML_Diagram_Element; type Bag_Of_UMLDI_UML_Diagram_Element is new UMLDI_UML_Diagram_Element_Collections.Bag with null record; Empty_Bag_Of_UMLDI_UML_Diagram_Element : constant Bag_Of_UMLDI_UML_Diagram_Element; type Sequence_Of_UMLDI_UML_Diagram_Element is new UMLDI_UML_Diagram_Element_Collections.Sequence with null record; Empty_Sequence_Of_UMLDI_UML_Diagram_Element : constant Sequence_Of_UMLDI_UML_Diagram_Element; private Empty_Set_Of_UMLDI_UML_Diagram_Element : constant Set_Of_UMLDI_UML_Diagram_Element := (UMLDI_UML_Diagram_Element_Collections.Set with null record); Empty_Ordered_Set_Of_UMLDI_UML_Diagram_Element : constant Ordered_Set_Of_UMLDI_UML_Diagram_Element := (UMLDI_UML_Diagram_Element_Collections.Ordered_Set with null record); Empty_Bag_Of_UMLDI_UML_Diagram_Element : constant Bag_Of_UMLDI_UML_Diagram_Element := (UMLDI_UML_Diagram_Element_Collections.Bag with null record); Empty_Sequence_Of_UMLDI_UML_Diagram_Element : constant Sequence_Of_UMLDI_UML_Diagram_Element := (UMLDI_UML_Diagram_Element_Collections.Sequence with null record); end AMF.UMLDI.UML_Diagram_Elements.Collections;
sungyeon/drake
Ada
1,372
adb
with System.Address_To_Named_Access_Conversions; with System.Formatting.Address; package body Ada.Task_Identification is package Task_Id_Conv is new System.Address_To_Named_Access_Conversions ( System.Tasks.Task_Record, Task_Id); -- implementation function Image (T : Task_Id) return String is begin if T = null then return ""; else declare N : constant not null access constant String := Name (T); N_Length : constant Natural := N'Length; Result : String ( 1 .. N_Length + 1 + System.Formatting.Address.Address_String'Length); Last : Natural := 0; begin if N_Length /= 0 then Last := N_Length; Result (1 .. Last) := N.all; Last := Last + 1; Result (Last) := ':'; end if; System.Formatting.Address.Image ( Task_Id_Conv.To_Address (T), Result ( Last + 1 .. Last + System.Formatting.Address.Address_String'Length), Set => System.Formatting.Upper_Case); Last := Last + System.Formatting.Address.Address_String'Length; return Result (1 .. Last); end; end if; end Image; end Ada.Task_Identification;
Rodeo-McCabe/orka
Ada
4,324
ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2012 Felix Krause <[email protected]> -- -- 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. private with GL.Low_Level; with GL.Types; package GL.Toggles is pragma Preelaborate; type Toggle_State is (Disabled, Enabled); type Toggle is (Cull_Face, Depth_Test, Stencil_Test, Dither, Blend, Color_Logic_Op, Scissor_Test, Polygon_Offset_Point, Polygon_Offset_Line, Clip_Distance_0, Clip_Distance_1, Clip_Distance_2, Clip_Distance_3, Clip_Distance_4, Clip_Distance_5, Clip_Distance_6, Clip_Distance_7, Polygon_Offset_Fill, Multisample, Sample_Alpha_To_Coverage, Sample_Alpha_To_One, Sample_Coverage, Debug_Output_Synchronous, Program_Point_Size, Depth_Clamp, Texture_Cube_Map_Seamless, Sample_Shading, Rasterizer_Discard, Primitive_Restart_Fixed_Index, Framebuffer_SRGB, Sample_Mask, Primitive_Restart, Debug_Output); procedure Enable (Subject : Toggle); procedure Disable (Subject : Toggle); procedure Set (Subject : Toggle; Value : Toggle_State); function State (Subject : Toggle) return Toggle_State; type Toggle_Indexed is (Blend, Scissor_Test); procedure Enable (Subject : Toggle_Indexed; Index : Types.UInt); procedure Disable (Subject : Toggle_Indexed; Index : Types.UInt); procedure Set (Subject : Toggle_Indexed; Index : Types.UInt; Value : Toggle_State); function State (Subject : Toggle_Indexed; Index : Types.UInt) return Toggle_State; private for Toggle use (Cull_Face => 16#0B44#, Depth_Test => 16#0B71#, Stencil_Test => 16#0B90#, Dither => 16#0BD0#, Blend => 16#0BE2#, Color_Logic_Op => 16#0BF2#, Scissor_Test => 16#0C11#, Polygon_Offset_Point => 16#2A01#, Polygon_Offset_Line => 16#2A02#, Clip_Distance_0 => 16#3000#, Clip_Distance_1 => 16#3001#, Clip_Distance_2 => 16#3002#, Clip_Distance_3 => 16#3003#, Clip_Distance_4 => 16#3004#, Clip_Distance_5 => 16#3005#, Clip_Distance_6 => 16#3006#, Clip_Distance_7 => 16#3007#, Polygon_Offset_Fill => 16#8037#, Multisample => 16#809D#, Sample_Alpha_To_Coverage => 16#809E#, Sample_Alpha_To_One => 16#809F#, Sample_Coverage => 16#80A0#, Debug_Output_Synchronous => 16#8242#, Program_Point_Size => 16#8642#, Depth_Clamp => 16#864F#, Texture_Cube_Map_Seamless => 16#884F#, Sample_Shading => 16#8C36#, Rasterizer_Discard => 16#8C89#, Primitive_Restart_Fixed_Index => 16#8D69#, Framebuffer_SRGB => 16#8DB9#, Sample_Mask => 16#8E51#, Primitive_Restart => 16#8F9D#, Debug_Output => 16#92E0#); for Toggle'Size use Low_Level.Enum'Size; for Toggle_Indexed use (Blend => 16#0BE2#, Scissor_Test => 16#0C11#); for Toggle_Indexed'Size use Low_Level.Enum'Size; end GL.Toggles;
yluo39github/MachineLearningSAT
Ada
15,821
ads
---------------------------------------------------------------- -- ZLib for Ada thick binding. -- -- -- -- Copyright (C) 2002-2003 Dmitriy Anisimkov -- -- -- -- Open source license information is in the zlib.ads file. -- ---------------------------------------------------------------- -- $Id: zlib-thin.ads,v 1.1 2008/12/11 02:41:27 xulin730 Exp $ with Interfaces.C.Strings; with System; private package ZLib.Thin is -- From zconf.h MAX_MEM_LEVEL : constant := 9; -- zconf.h:105 -- zconf.h:105 MAX_WBITS : constant := 15; -- zconf.h:115 -- 32K LZ77 window -- zconf.h:115 SEEK_SET : constant := 8#0000#; -- zconf.h:244 -- Seek from beginning of file. -- zconf.h:244 SEEK_CUR : constant := 1; -- zconf.h:245 -- Seek from current position. -- zconf.h:245 SEEK_END : constant := 2; -- zconf.h:246 -- Set file pointer to EOF plus "offset" -- zconf.h:246 type Byte is new Interfaces.C.unsigned_char; -- 8 bits -- zconf.h:214 type UInt is new Interfaces.C.unsigned; -- 16 bits or more -- zconf.h:216 type Int is new Interfaces.C.int; type ULong is new Interfaces.C.unsigned_long; -- 32 bits or more -- zconf.h:217 subtype Chars_Ptr is Interfaces.C.Strings.chars_ptr; type ULong_Access is access ULong; type Int_Access is access Int; subtype Voidp is System.Address; -- zconf.h:232 subtype Byte_Access is Voidp; Nul : constant Voidp := System.Null_Address; -- end from zconf Z_NO_FLUSH : constant := 8#0000#; -- zlib.h:125 -- zlib.h:125 Z_PARTIAL_FLUSH : constant := 1; -- zlib.h:126 -- will be removed, use -- Z_SYNC_FLUSH instead -- zlib.h:126 Z_SYNC_FLUSH : constant := 2; -- zlib.h:127 -- zlib.h:127 Z_FULL_FLUSH : constant := 3; -- zlib.h:128 -- zlib.h:128 Z_FINISH : constant := 4; -- zlib.h:129 -- zlib.h:129 Z_OK : constant := 8#0000#; -- zlib.h:132 -- zlib.h:132 Z_STREAM_END : constant := 1; -- zlib.h:133 -- zlib.h:133 Z_NEED_DICT : constant := 2; -- zlib.h:134 -- zlib.h:134 Z_ERRNO : constant := -1; -- zlib.h:135 -- zlib.h:135 Z_STREAM_ERROR : constant := -2; -- zlib.h:136 -- zlib.h:136 Z_DATA_ERROR : constant := -3; -- zlib.h:137 -- zlib.h:137 Z_MEM_ERROR : constant := -4; -- zlib.h:138 -- zlib.h:138 Z_BUF_ERROR : constant := -5; -- zlib.h:139 -- zlib.h:139 Z_VERSION_ERROR : constant := -6; -- zlib.h:140 -- zlib.h:140 Z_NO_COMPRESSION : constant := 8#0000#; -- zlib.h:145 -- zlib.h:145 Z_BEST_SPEED : constant := 1; -- zlib.h:146 -- zlib.h:146 Z_BEST_COMPRESSION : constant := 9; -- zlib.h:147 -- zlib.h:147 Z_DEFAULT_COMPRESSION : constant := -1; -- zlib.h:148 -- zlib.h:148 Z_FILTERED : constant := 1; -- zlib.h:151 -- zlib.h:151 Z_HUFFMAN_ONLY : constant := 2; -- zlib.h:152 -- zlib.h:152 Z_DEFAULT_STRATEGY : constant := 8#0000#; -- zlib.h:153 -- zlib.h:153 Z_BINARY : constant := 8#0000#; -- zlib.h:156 -- zlib.h:156 Z_ASCII : constant := 1; -- zlib.h:157 -- zlib.h:157 Z_UNKNOWN : constant := 2; -- zlib.h:158 -- zlib.h:158 Z_DEFLATED : constant := 8; -- zlib.h:161 -- zlib.h:161 Z_NULL : constant := 8#0000#; -- zlib.h:164 -- for initializing zalloc, zfree, opaque -- zlib.h:164 type gzFile is new Voidp; -- zlib.h:646 type Z_Stream is private; type Z_Streamp is access all Z_Stream; -- zlib.h:89 type alloc_func is access function (Opaque : Voidp; Items : UInt; Size : UInt) return Voidp; -- zlib.h:63 type free_func is access procedure (opaque : Voidp; address : Voidp); function zlibVersion return Chars_Ptr; function Deflate (strm : Z_Streamp; flush : Int) return Int; function DeflateEnd (strm : Z_Streamp) return Int; function Inflate (strm : Z_Streamp; flush : Int) return Int; function InflateEnd (strm : Z_Streamp) return Int; function deflateSetDictionary (strm : Z_Streamp; dictionary : Byte_Access; dictLength : UInt) return Int; function deflateCopy (dest : Z_Streamp; source : Z_Streamp) return Int; -- zlib.h:478 function deflateReset (strm : Z_Streamp) return Int; -- zlib.h:495 function deflateParams (strm : Z_Streamp; level : Int; strategy : Int) return Int; -- zlib.h:506 function inflateSetDictionary (strm : Z_Streamp; dictionary : Byte_Access; dictLength : UInt) return Int; -- zlib.h:548 function inflateSync (strm : Z_Streamp) return Int; -- zlib.h:565 function inflateReset (strm : Z_Streamp) return Int; -- zlib.h:580 function compress (dest : Byte_Access; destLen : ULong_Access; source : Byte_Access; sourceLen : ULong) return Int; -- zlib.h:601 function compress2 (dest : Byte_Access; destLen : ULong_Access; source : Byte_Access; sourceLen : ULong; level : Int) return Int; -- zlib.h:615 function uncompress (dest : Byte_Access; destLen : ULong_Access; source : Byte_Access; sourceLen : ULong) return Int; function gzopen (path : Chars_Ptr; mode : Chars_Ptr) return gzFile; function gzdopen (fd : Int; mode : Chars_Ptr) return gzFile; function gzsetparams (file : gzFile; level : Int; strategy : Int) return Int; function gzread (file : gzFile; buf : Voidp; len : UInt) return Int; function gzwrite (file : in gzFile; buf : in Voidp; len : in UInt) return Int; function gzprintf (file : in gzFile; format : in Chars_Ptr) return Int; function gzputs (file : in gzFile; s : in Chars_Ptr) return Int; function gzgets (file : gzFile; buf : Chars_Ptr; len : Int) return Chars_Ptr; function gzputc (file : gzFile; char : Int) return Int; function gzgetc (file : gzFile) return Int; function gzflush (file : gzFile; flush : Int) return Int; function gzseek (file : gzFile; offset : Int; whence : Int) return Int; function gzrewind (file : gzFile) return Int; function gztell (file : gzFile) return Int; function gzeof (file : gzFile) return Int; function gzclose (file : gzFile) return Int; function gzerror (file : gzFile; errnum : Int_Access) return Chars_Ptr; function adler32 (adler : ULong; buf : Byte_Access; len : UInt) return ULong; function crc32 (crc : ULong; buf : Byte_Access; len : UInt) return ULong; function deflateInit (strm : Z_Streamp; level : Int; version : Chars_Ptr; stream_size : Int) return Int; function deflateInit2 (strm : Z_Streamp; level : Int; method : Int; windowBits : Int; memLevel : Int; strategy : Int; version : Chars_Ptr; stream_size : Int) return Int; function Deflate_Init (strm : Z_Streamp; level : Int; method : Int; windowBits : Int; memLevel : Int; strategy : Int) return Int; pragma Inline (Deflate_Init); function inflateInit (strm : Z_Streamp; version : Chars_Ptr; stream_size : Int) return Int; function inflateInit2 (strm : in Z_Streamp; windowBits : in Int; version : in Chars_Ptr; stream_size : in Int) return Int; function inflateBackInit (strm : in Z_Streamp; windowBits : in Int; window : in Byte_Access; version : in Chars_Ptr; stream_size : in Int) return Int; -- Size of window have to be 2**windowBits. function Inflate_Init (strm : Z_Streamp; windowBits : Int) return Int; pragma Inline (Inflate_Init); function zError (err : Int) return Chars_Ptr; function inflateSyncPoint (z : Z_Streamp) return Int; function get_crc_table return ULong_Access; -- Interface to the available fields of the z_stream structure. -- The application must update next_in and avail_in when avail_in has -- dropped to zero. It must update next_out and avail_out when avail_out -- has dropped to zero. The application must initialize zalloc, zfree and -- opaque before calling the init function. procedure Set_In (Strm : in out Z_Stream; Buffer : in Voidp; Size : in UInt); pragma Inline (Set_In); procedure Set_Out (Strm : in out Z_Stream; Buffer : in Voidp; Size : in UInt); pragma Inline (Set_Out); procedure Set_Mem_Func (Strm : in out Z_Stream; Opaque : in Voidp; Alloc : in alloc_func; Free : in free_func); pragma Inline (Set_Mem_Func); function Last_Error_Message (Strm : in Z_Stream) return String; pragma Inline (Last_Error_Message); function Avail_Out (Strm : in Z_Stream) return UInt; pragma Inline (Avail_Out); function Avail_In (Strm : in Z_Stream) return UInt; pragma Inline (Avail_In); function Total_In (Strm : in Z_Stream) return ULong; pragma Inline (Total_In); function Total_Out (Strm : in Z_Stream) return ULong; pragma Inline (Total_Out); function inflateCopy (dest : in Z_Streamp; Source : in Z_Streamp) return Int; function compressBound (Source_Len : in ULong) return ULong; function deflateBound (Strm : in Z_Streamp; Source_Len : in ULong) return ULong; function gzungetc (C : in Int; File : in gzFile) return Int; function zlibCompileFlags return ULong; private type Z_Stream is record -- zlib.h:68 Next_In : Voidp := Nul; -- next input byte Avail_In : UInt := 0; -- number of bytes available at next_in Total_In : ULong := 0; -- total nb of input bytes read so far Next_Out : Voidp := Nul; -- next output byte should be put there Avail_Out : UInt := 0; -- remaining free space at next_out Total_Out : ULong := 0; -- total nb of bytes output so far msg : Chars_Ptr; -- last error message, NULL if no error state : Voidp; -- not visible by applications zalloc : alloc_func := null; -- used to allocate the internal state zfree : free_func := null; -- used to free the internal state opaque : Voidp; -- private data object passed to -- zalloc and zfree data_type : Int; -- best guess about the data type: -- ascii or binary adler : ULong; -- adler32 value of the uncompressed -- data reserved : ULong; -- reserved for future use end record; pragma Convention (C, Z_Stream); pragma Import (C, zlibVersion, "zlibVersion"); pragma Import (C, Deflate, "deflate"); pragma Import (C, DeflateEnd, "deflateEnd"); pragma Import (C, Inflate, "inflate"); pragma Import (C, InflateEnd, "inflateEnd"); pragma Import (C, deflateSetDictionary, "deflateSetDictionary"); pragma Import (C, deflateCopy, "deflateCopy"); pragma Import (C, deflateReset, "deflateReset"); pragma Import (C, deflateParams, "deflateParams"); pragma Import (C, inflateSetDictionary, "inflateSetDictionary"); pragma Import (C, inflateSync, "inflateSync"); pragma Import (C, inflateReset, "inflateReset"); pragma Import (C, compress, "compress"); pragma Import (C, compress2, "compress2"); pragma Import (C, uncompress, "uncompress"); pragma Import (C, gzopen, "gzopen"); pragma Import (C, gzdopen, "gzdopen"); pragma Import (C, gzsetparams, "gzsetparams"); pragma Import (C, gzread, "gzread"); pragma Import (C, gzwrite, "gzwrite"); pragma Import (C, gzprintf, "gzprintf"); pragma Import (C, gzputs, "gzputs"); pragma Import (C, gzgets, "gzgets"); pragma Import (C, gzputc, "gzputc"); pragma Import (C, gzgetc, "gzgetc"); pragma Import (C, gzflush, "gzflush"); pragma Import (C, gzseek, "gzseek"); pragma Import (C, gzrewind, "gzrewind"); pragma Import (C, gztell, "gztell"); pragma Import (C, gzeof, "gzeof"); pragma Import (C, gzclose, "gzclose"); pragma Import (C, gzerror, "gzerror"); pragma Import (C, adler32, "adler32"); pragma Import (C, crc32, "crc32"); pragma Import (C, deflateInit, "deflateInit_"); pragma Import (C, inflateInit, "inflateInit_"); pragma Import (C, deflateInit2, "deflateInit2_"); pragma Import (C, inflateInit2, "inflateInit2_"); pragma Import (C, zError, "zError"); pragma Import (C, inflateSyncPoint, "inflateSyncPoint"); pragma Import (C, get_crc_table, "get_crc_table"); -- since zlib 1.2.0: pragma Import (C, inflateCopy, "inflateCopy"); pragma Import (C, compressBound, "compressBound"); pragma Import (C, deflateBound, "deflateBound"); pragma Import (C, gzungetc, "gzungetc"); pragma Import (C, zlibCompileFlags, "zlibCompileFlags"); pragma Import (C, inflateBackInit, "inflateBackInit_"); -- I stopped binding the inflateBack routines, becouse realize that -- it does not support zlib and gzip headers for now, and have no -- symmetric deflateBack routines. -- ZLib-Ada is symmetric regarding deflate/inflate data transformation -- and has a similar generic callback interface for the -- deflate/inflate transformation based on the regular Deflate/Inflate -- routines. -- pragma Import (C, inflateBack, "inflateBack"); -- pragma Import (C, inflateBackEnd, "inflateBackEnd"); end ZLib.Thin;
io7m/coreland-opengl-ada
Ada
4,588
adb
package body OpenGL.Matrix is function Mode_To_Constant (Mode : in Mode_t) return Thin.Enumeration_t is begin case Mode is when Texture => return Thin.GL_TEXTURE; when Modelview => return Thin.GL_MODELVIEW; when Color => return Thin.GL_COLOR; when Projection => return Thin.GL_PROJECTION; end case; end Mode_To_Constant; procedure Mode (Mode : in Mode_t) is begin Thin.Matrix_Mode (Mode_To_Constant (Mode)); end Mode; -- -- Load -- procedure Load (Matrix : in Matrix_4x4f_t) is begin Thin.Load_Matrixf (Matrix (Matrix'First (1), Matrix'First (1))'Address); end Load; procedure Load (Matrix : in Matrix_4x4d_t) is begin Thin.Load_Matrixd (Matrix (Matrix'First (1), Matrix'First (1))'Address); end Load; -- -- Multiply -- procedure Multiply (Matrix : in Matrix_4x4f_t) is begin Thin.Mult_Matrixf (Matrix (Matrix'First (1), Matrix'First (1))'Address); end Multiply; procedure Multiply (Matrix : in Matrix_4x4d_t) is begin Thin.Mult_Matrixd (Matrix (Matrix'First (1), Matrix'First (1))'Address); end Multiply; -- -- Load_Transpose -- procedure Load_Transpose (Matrix : in Matrix_4x4f_t) is begin Thin.Load_Transpose_Matrixf (Matrix (Matrix'First (1), Matrix'First (1))'Address); end Load_Transpose; procedure Load_Transpose (Matrix : in Matrix_4x4d_t) is begin Thin.Load_Transpose_Matrixd (Matrix (Matrix'First (1), Matrix'First (1))'Address); end Load_Transpose; -- -- Multiply_Transpose -- procedure Multiply_Transpose (Matrix : in Matrix_4x4f_t) is begin Thin.Mult_Transpose_Matrixf (Matrix (Matrix'First (1), Matrix'First (1))'Address); end Multiply_Transpose; procedure Multiply_Transpose (Matrix : in Matrix_4x4d_t) is begin Thin.Mult_Transpose_Matrixd (Matrix (Matrix'First (1), Matrix'First (1))'Address); end Multiply_Transpose; -- -- Rotate -- procedure Rotate (Angle : in OpenGL.Types.Float_t; X : in OpenGL.Types.Float_t; Y : in OpenGL.Types.Float_t; Z : in OpenGL.Types.Float_t) is begin Thin.Rotatef (Angle => Angle, X => X, Y => Y, Z => Z); end Rotate; procedure Rotate (Angle : in OpenGL.Types.Double_t; X : in OpenGL.Types.Double_t; Y : in OpenGL.Types.Double_t; Z : in OpenGL.Types.Double_t) is begin Thin.Rotated (Angle => Angle, X => X, Y => Y, Z => Z); end Rotate; -- -- Translate -- procedure Translate (X : in OpenGL.Types.Float_t; Y : in OpenGL.Types.Float_t; Z : in OpenGL.Types.Float_t) is begin Thin.Translatef (X => X, Y => Y, Z => Z); end Translate; procedure Translate (X : in OpenGL.Types.Double_t; Y : in OpenGL.Types.Double_t; Z : in OpenGL.Types.Double_t) is begin Thin.Translated (X => X, Y => Y, Z => Z); end Translate; -- -- Scale -- procedure Scale (X : in OpenGL.Types.Float_t; Y : in OpenGL.Types.Float_t; Z : in OpenGL.Types.Float_t) is begin Thin.Scalef (X => X, Y => Y, Z => Z); end Scale; procedure Scale (X : in OpenGL.Types.Double_t; Y : in OpenGL.Types.Double_t; Z : in OpenGL.Types.Double_t) is begin Thin.Scaled (X => X, Y => Y, Z => Z); end Scale; -- -- Frustum -- procedure Frustum (Left : in OpenGL.Types.Double_t; Right : in OpenGL.Types.Double_t; Bottom : in OpenGL.Types.Double_t; Top : in OpenGL.Types.Double_t; Near : in Near_Double_t; Far : in OpenGL.Types.Double_t) is begin Thin.Frustum (Left => Thin.Double_t (Left), Right => Thin.Double_t (Right), Top => Thin.Double_t (Top), Bottom => Thin.Double_t (Bottom), Near => Thin.Double_t (Near), Far => Thin.Double_t (Far)); end Frustum; -- -- Ortho -- procedure Ortho (Left : in OpenGL.Types.Double_t; Right : in OpenGL.Types.Double_t; Bottom : in OpenGL.Types.Double_t; Top : in OpenGL.Types.Double_t; Near : in OpenGL.Types.Double_t; Far : in OpenGL.Types.Double_t) is begin Thin.Ortho (Left => Thin.Double_t (Left), Right => Thin.Double_t (Right), Top => Thin.Double_t (Top), Bottom => Thin.Double_t (Bottom), Near_Value => Thin.Double_t (Near), Far_Value => Thin.Double_t (Far)); end Ortho; end OpenGL.Matrix;
datdojp/davu
Ada
480
ads
if(window["ADS_CHECKER"] != undefined && window["ADS_CHECKER"] != "undefined") document.write('<script type="text/javascript" src="http://admicro1.vcmedia.vn/ads_codes/ads_code_1615.ads"></script>'); else document.write('<script type="text/javascript" src="http://admicro1.vcmedia.vn/core/admicro_core.js?id=1"></script><script type="text/javascript" src="http://admicro1.vcmedia.vn/ads_codes/ads_code_1615.ads"></script>'); var url_write='http://admicro.vn/adproject/write.php';
reznikmm/matreshka
Ada
9,745
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- XML Processor -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with League.Strings; package XML.SAX.Lexical_Handlers is pragma Preelaborate; type SAX_Lexical_Handler is limited interface; not overriding procedure Comment (Self : in out SAX_Lexical_Handler; Text : League.Strings.Universal_String; Success : in out Boolean) is null; -- The reader calls this subprogram to report an XML comment anywhere in -- the document (inside and outside document element, and in the external -- DTD subset). It reports the text of the comment in ch. -- -- If this subprogram sets Success to False the reader stops parsing and -- reports an error. The reader uses the function Error_String to get the -- error message. not overriding procedure End_CDATA (Self : in out SAX_Lexical_Handler; Success : in out Boolean) is null; -- The reader calls this subprogram to report the end of a CDATA section. -- -- If this subprogram sets Success to False the reader stops parsing and -- reports an error. The reader uses the function Error_String to get the -- error message. not overriding procedure End_DTD (Self : in out SAX_Lexical_Handler; Success : in out Boolean) is null; -- The reader calls this subprogram to report the end of a DTD declaration, -- if any. -- -- If this subprogram sets Success to False the reader stops parsing and -- reports an error. The reader uses the function Error_String to get the -- error message. not overriding procedure End_Entity (Self : in out SAX_Lexical_Handler; Name : League.Strings.Universal_String; Success : in out Boolean) is null; -- The reader calls this subprogram to report the end of an entity called -- Name. -- -- If this subprogram sets Success to False the reader stops parsing and -- reports an error. The reader uses the function Error_String to get the -- error message. not overriding function Error_String (Self : SAX_Lexical_Handler) return League.Strings.Universal_String is abstract; -- The reader calls this function to get an error string, e.g. if any of -- the handler subprograms sets Success to False. not overriding procedure Start_CDATA (Self : in out SAX_Lexical_Handler; Success : in out Boolean) is null; -- The reader calls this subprogram to report the start of a CDATA section. -- The content of the CDATA section is reported through the -- SAX_Content_Handler's Characters subprogram. This subprogram is intended -- only to report the boundary. -- -- If this subprogram sets Success to False the reader stops parsing and -- reports an error. The reader uses the function Error_String to get the -- error message. not overriding procedure Start_DTD (Self : in out SAX_Lexical_Handler; Name : League.Strings.Universal_String; Public_Id : League.Strings.Universal_String; System_Id : League.Strings.Universal_String; Success : in out Boolean) is null; -- The reader calls this subprogram to report the start of a DTD -- declaration, if any. It reports the name of the document type in Name, -- the public identifier in Public_Id and the system identifier in -- System_Id. -- -- If the public identifier is missing, Public_Id is set to an empty -- string. If the system identifier is missing, System_Id is set to an -- empty string. Note that it is not valid XML to have a public identifier -- but no system identifier; in such cases a parse error will occur. -- -- This subprogram is intended to report the beginning of the DOCTYPE -- declaration; if the document has no DOCTYPE declaration, this subprogram -- will not be invoked. -- -- All declarations reported through SAX_DTD_Handler or SAX_Decl_Handler -- appear between the Start_DTD and End_DTD calls. Declarations belong to -- the internal DTD subsets unless they appear between Start_Entity and -- End_Entity calls. Comments and processing instructions from the DTD also -- are reported between the Start_DTD and End_DTD calls, in their original -- order of (logical) occurrence; they are not appear in their correct -- locations relative to others calls of SAX_DTD_Handler or -- SAX_Decl_Handler, however. -- -- Note that the Start_DTD/End_DTD calls will appear within the -- Start_Document/End_Document calls from SAX_Content_Handler and before -- the first Start_Element event. -- -- If this subprogram sets Success to False the reader stops parsing and -- reports an error. The reader uses the function Error_String to get the -- error message. not overriding procedure Start_Entity (Self : in out SAX_Lexical_Handler; Name : League.Strings.Universal_String; Success : in out Boolean) is null; -- The reader calls this subprogram to report the start of an internal or -- external entity called Name. -- -- General entities are reported with their regular names, parameter -- entities have '%' prepended to their names, and the external DTD subset -- has the pseudo-entity name "[dtd]". -- -- Note that if the entity is unknown, the reader reports it through -- SAX_Content_Handler's Skipped_Entity and not through this subprogram. -- -- Because of the streaming event model that SAX uses, some entity -- boundaries cannot be reported under any circumstances: -- -- * general entities within attribute values -- * parameter entities within declarations -- -- These will be silently expanded, with no indication of where the -- original entity boundaries were. -- -- Note also that the boundaries of character references (which are not -- really entities anyway) are not reported. -- -- The reporting of parameter entities (including the external DTD subset) -- is optional, and SAX2 drivers that report Lexical_Handler events may not -- implement it; you can use the -- http://xml.org/sax/features/lexical-handler/parameter-entities feature -- to query or control the reporting of parameter entities. -- -- If this subprogram sets Success to False the reader stops parsing and -- reports an error. The reader uses the function Error_String to get the -- error message. end XML.SAX.Lexical_Handlers;
usnistgov/rcslib
Ada
2,805
adb
-- -- New Ada Body File starts here. -- This file should be named test_msg_.adb -- Automatically generated by NML CodeGen Java Applet. -- on Thu Aug 19 15:46:42 EDT 2004 -- with Nml; use Nml; -- Some standard Ada Packages we always need. with Unchecked_Deallocation; with Unchecked_Conversion; with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings; package body test_msg_ is -- Every NMLmsg type needs an update and an initialize function. procedure Initialize(Msg : in out TEST_B_MSG) is begin Msg.NmlType := TEST_B_MSG_TYPE; Msg.Size := TEST_B_MSG'Size; end Initialize; procedure Update_TEST_B_MSG(Cms : in Cms_Access; Msg : in TEST_B_MSG_Access) is begin Msg.NmlType := TEST_B_MSG_TYPE; Msg.Size := TEST_B_MSG'Size; CmsUpdateInt(Cms, "i", Msg.i); end Update_TEST_B_MSG; procedure Initialize(Msg : in out TEST_MSG) is begin Msg.NmlType := TEST_MSG_TYPE; Msg.Size := TEST_MSG'Size; end Initialize; procedure Update_TEST_MSG(Cms : in Cms_Access; Msg : in TEST_MSG_Access) is begin Msg.NmlType := TEST_MSG_TYPE; Msg.Size := TEST_MSG'Size; CmsUpdateInt(Cms, "i", Msg.i); CmsUpdateIntArray(Cms, "ia", Msg.ia,10); CmsUpdateInt(Cms, "ida_length", Msg.ida_length); CmsUpdateIntDla(Cms, "ida", Msg.ida,Msg.ida_length,8); end Update_TEST_MSG; NameList : constant Char_Array(1..33) := ( 'T','E','S','T','_','B','_','M','S','G',nul, 'T','E','S','T','_','M','S','G',nul,nul,nul, nul,nul,nul,nul,nul,nul,nul,nul,nul,nul,nul ); IdList : constant Nml.Long_Array(1..3) := ( TEST_B_MSG_TYPE, -- 1002, 0 TEST_MSG_TYPE, -- 1001, 1 -1); SizeList : constant Nml.Size_T_Array(1..3) := ( TEST_B_MSG'Size, TEST_MSG'Size, 0); function Symbol_Lookup(Nml_Type : in long) return Interfaces.C.Strings.chars_ptr; pragma Export(C,Symbol_Lookup,"ada_test_msg__symbol_lookup"); function Symbol_Lookup(Nml_Type : in long) return Interfaces.C.Strings.chars_ptr is begin case Nml_Type is when TEST_B_MSG_TYPE => return Nml.ReturnSymbol(NameList(1..12)); when TEST_MSG_TYPE => return Nml.ReturnSymbol(NameList(12..21)); when others => return Null_Ptr; end case; end Symbol_Lookup; function Format(Nml_Type : in long; Msg : in Nml.NmlMsg_Access; Cms : in Nml.Cms_Access) return int is Checked_Nml_Type : long; begin Checked_Nml_Type := CmsCheckTypeInfo(Cms,Nml_Type,Msg,"test_msg_", Symbol_Lookup'Access, NameList,IdList,SizeList,3,11); if Msg = Null then return 0; end if; case Checked_Nml_Type is when TEST_B_MSG_TYPE => Update_TEST_B_MSG(Cms, NmlMsg_to_TEST_B_MSG(Msg)); when TEST_MSG_TYPE => Update_TEST_MSG(Cms, NmlMsg_to_TEST_MSG(Msg)); when others => return 0; end case; return 1; end Format; end test_msg_; -- End of Ada Body file test_msg_.adb
annexi-strayline/AURA
Ada
4,337
ads
------------------------------------------------------------------------------ -- -- -- Ada User Repository Annex (AURA) -- -- ANNEXI-STRAYLINE Reference Implementation -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2020, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Richard Wai (ANNEXI-STRAYLINE) -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- -- -- * Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Child_Processes.Platform; private package Child_Processes.Standard_IO is type Standard_IO_Stream is new Root_Stream_Type with record Handle : Platform.Stream_Handle; Timeout: Duration := 0.0; end record; overriding procedure Read (Stream: in out Standard_IO_Stream; Item : out Stream_Element_Array; Last : out Stream_Element_Offset); -- Timeout indicates that Last is < Item'Last overriding procedure Write (Stream: in out Standard_IO_Stream; Item : in Stream_Element_Array); -- A timeout raises Storage_Error, since it would indicate a -- full buffer not overriding procedure Read_Immediate (Stream: in out Standard_IO_Stream; Item : out Stream_Element_Array; Last : out Stream_Element_Offset); -- Returns any data immediately available, and does not block end Child_Processes.Standard_IO;
persan/AdaYaml
Ada
70,900
adb
-- part of AdaYaml, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" with Ada.Containers; with Text.Builder; with Yaml.Tags; package body Yaml.Parser is use type Lexer.Token_Kind; use type Text.Reference; function New_Parser return Reference is Ptr : constant not null Instance_Access := new Instance; begin return Reference'(Ada.Finalization.Controlled with Data => Ptr); end New_Parser; function Value (Object : Reference) return Accessor is ((Data => Object.Data)); procedure Adjust (Object : in out Reference) is begin Increase_Refcount (Object.Data); end Adjust; procedure Finalize (Object : in out Reference) is begin Decrease_Refcount (Object.Data); end Finalize; procedure Init (P : in out Instance) with Inline is begin P.Levels := Level_Stacks.New_Stack (32); P.Levels.Push ((State => At_Stream_Start'Access, Indentation => -2)); P.Pool.Create (Text.Pool.Default_Size); Tag_Handle_Sets.Init (P.Tag_Handles, P.Pool, 16); P.Header_Props := Default_Properties; P.Inline_Props := Default_Properties; end Init; procedure Set_Input (P : in out Instance; Input : Source.Pointer) is begin Init (P); Lexer.Init (P.L, Input, P.Pool); end Set_Input; procedure Set_Input (P : in out Instance; Input : String) is begin Init (P); Lexer.Init (P.L, Input, P.Pool); end Set_Input; procedure Set_Warning_Handler (P : in out Instance; Handler : access Warning_Handler'Class) is begin P.Handler := Handler; end Set_Warning_Handler; function Next (P : in out Instance) return Event is begin return E : Event do while not P.Levels.Top.State (P, E) loop null; end loop; end return; end Next; function Pool (P : Instance) return Text.Pool.Reference is (P.Pool); procedure Finalize (P : in out Instance) is null; function Current_Lexer_Token_Start (P : Instance) return Mark is (Lexer.Recent_Start_Mark (P.L)); function Current_Input_Character (P : Instance) return Mark is (Lexer.Cur_Mark (P.L)); function Recent_Lexer_Token_Start (P : Instance) return Mark is (P.Current.Start_Pos); function Recent_Lexer_Token_End (P : Instance) return Mark is (P.Current.End_Pos); ----------------------------------------------------------------------------- -- internal utility subroutines ----------------------------------------------------------------------------- procedure Reset_Tag_Handles (P : in out Class) is begin Tag_Handle_Sets.Clear (P.Tag_Handles); pragma Warnings (Off); if P.Tag_Handles.Set ("!", P.Pool.From_String ("!")) and P.Tag_Handles.Set ("!!", P.Pool.From_String ("tag:yaml.org,2002:")) then null; end if; pragma Warnings (On); end Reset_Tag_Handles; function Parse_Tag (P : in out Class) return Text.Reference is use type Ada.Containers.Hash_Type; Tag_Handle : constant String := Lexer.Full_Lexeme (P.L); Holder : constant access constant Tag_Handle_Sets.Holder := P.Tag_Handles.Get (Tag_Handle, False); begin if Holder.Hash = 0 then raise Parser_Error with "Unknown tag handle: " & Tag_Handle; end if; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind /= Lexer.Suffix then raise Parser_Error with "Unexpected token (expected tag suffix): " & P.Current.Kind'Img; end if; return P.Pool.From_String (Holder.Value & Lexer.Current_Content (P.L)); end Parse_Tag; function To_Style (T : Lexer.Scalar_Token_Kind) return Scalar_Style_Type is (case T is when Lexer.Plain_Scalar => Plain, when Lexer.Single_Quoted_Scalar => Single_Quoted, when Lexer.Double_Quoted_Scalar => Double_Quoted, when Lexer.Literal_Scalar => Literal, when Lexer.Folded_Scalar => Folded) with Inline; ----------------------------------------------------------------------------- -- state implementations ----------------------------------------------------------------------------- function At_Stream_Start (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.all := (State => At_Stream_End'Access, Indentation => -2); P.Levels.Push ((State => Before_Doc'Access, Indentation => -1)); E := Event'(Kind => Stream_Start, Start_Position => (Line => 1, Column => 1, Index => 1), End_Position => (Line => 1, Column => 1, Index => 1)); P.Current := Lexer.Next_Token (P.L); Reset_Tag_Handles (P); return True; end At_Stream_Start; function At_Stream_End (P : in out Class; E : out Event) return Boolean is T : constant Lexer.Token := Lexer.Next_Token (P.L); begin E := Event'(Kind => Stream_End, Start_Position => T.Start_Pos, End_Position => T.End_Pos); return True; end At_Stream_End; function Before_Doc (P : in out Class; E : out Event) return Boolean is Version : Text.Reference := Text.Empty; Seen_Directives : Boolean := False; begin loop case P.Current.Kind is when Lexer.Document_End => if Seen_Directives then raise Parser_Error with "Directives must be followed by '---'"; end if; P.Current := Lexer.Next_Token (P.L); when Lexer.Directives_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Document_Start, Implicit_Start => False, Version => Version); P.Current := Lexer.Next_Token (P.L); P.Levels.Top.State := Before_Doc_End'Access; P.Levels.Push ((State => After_Directives_End'Access, Indentation => -1)); return True; when Lexer.Stream_End => P.Levels.Pop; return False; when Lexer.Indentation => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Document_Start, Implicit_Start => True, Version => Version); P.Levels.Top.State := Before_Doc_End'Access; P.Levels.Push ((State => Before_Implicit_Root'Access, Indentation => -1)); return True; when Lexer.Yaml_Directive => Seen_Directives := True; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind /= Lexer.Directive_Param then raise Parser_Error with "Invalid token (expected YAML version string): " & P.Current.Kind'Img; elsif Version /= Text.Empty then raise Parser_Error with "Duplicate YAML directive"; end if; Version := P.Pool.From_String (Lexer.Full_Lexeme (P.L)); if Version /= "1.3" and then P.Handler /= null then P.Handler.Wrong_Yaml_Version (Version.Value); end if; P.Current := Lexer.Next_Token (P.L); when Lexer.Tag_Directive => Seen_Directives := True; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind /= Lexer.Tag_Handle then raise Parser_Error with "Invalid token (expected tag handle): " & P.Current.Kind'Img; end if; declare Tag_Handle : constant String := Lexer.Full_Lexeme (P.L); Holder : access Tag_Handle_Sets.Holder; begin P.Current := Lexer.Next_Token (P.L); if P.Current.Kind /= Lexer.Suffix then raise Parser_Error with "Invalid token (expected tag URI): " & P.Current.Kind'Img; end if; if Tag_Handle = "!" or Tag_Handle = "!!" then Holder := Tag_Handle_Sets.Get (P.Tag_Handles, Tag_Handle, False); Holder.Value := Lexer.Current_Content (P.L); else if not Tag_Handle_Sets.Set (P.Tag_Handles, Tag_Handle, Lexer.Current_Content (P.L)) then raise Parser_Error with "Redefinition of tag handle " & Tag_Handle; end if; end if; end; P.Current := Lexer.Next_Token (P.L); when Lexer.Unknown_Directive => Seen_Directives := True; if P.Handler /= null then declare Name : constant String := Lexer.Short_Lexeme (P.L); Params : Text.Builder.Reference := Text.Builder.Create (P.Pool); First : Boolean := True; begin loop P.Current := Lexer.Next_Token (P.L); exit when P.Current.Kind /= Lexer.Directive_Param; if First then First := False; else Params.Append (' '); end if; Params.Append (Lexer.Full_Lexeme (P.L)); end loop; P.Handler.Unknown_Directive (Name, Params.Lock.Value.Data.all); end; else loop P.Current := Lexer.Next_Token (P.L); exit when P.Current.Kind /= Lexer.Directive_Param; end loop; end if; when others => raise Parser_Error with "Unexpected token (expected directive or document start): " & P.Current.Kind'Img; end case; end loop; end Before_Doc; function After_Directives_End (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Node_Property_Kind => P.Inline_Start := P.Current.Start_Pos; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Indentation => P.Header_Start := P.Inline_Start; P.Levels.Top.State := At_Block_Indentation'Access; P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); return False; when Lexer.Document_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Pop; return True; when Lexer.Folded_Scalar | Lexer.Literal_Scalar => E := Event'( Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => (if P.Current.Kind = Lexer.Folded_Scalar then Folded else Literal), Content => Lexer.Current_Content (P.L)); P.Levels.Pop; P.Current := Lexer.Next_Token (P.L); return True; when others => raise Parser_Error with "Illegal content at '---' line: " & P.Current.Kind'Img; end case; end After_Directives_End; function Before_Implicit_Root (P : in out Class; E : out Event) return Boolean is pragma Unreferenced (E); begin if P.Current.Kind /= Lexer.Indentation then raise Parser_Error with "Unexpected token (expected line start) :" & P.Current.Kind'Img; end if; P.Inline_Start := P.Current.End_Pos; P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); P.Current := Lexer.Next_Token (P.L); case P.Current.Kind is when Lexer.Seq_Item_Ind | Lexer.Map_Key_Ind | Lexer.Map_Value_Ind => P.Levels.Top.State := After_Compact_Parent'Access; return False; when Lexer.Scalar_Token_Kind => P.Levels.Top.State := Require_Implicit_Map_Start'Access; return False; when Lexer.Node_Property_Kind => P.Levels.Top.State := Require_Implicit_Map_Start'Access; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Flow_Map_Start | Lexer.Flow_Seq_Start => P.Levels.Top.State := After_Compact_Parent_Props'Access; return False; when others => raise Parser_Error with "Unexpected token (expected collection start): " & P.Current.Kind'Img; end case; end Before_Implicit_Root; function Require_Implicit_Map_Start (P : in out Class; E : out Event) return Boolean is Header_End : Mark; begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); Header_End := P.Current.Start_Pos; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then P.Cached := E; E := Event'(Start_Position => P.Header_Start, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; else if not Is_Empty (P.Header_Props) then raise Parser_Error with "Alias may not have properties2"; end if; -- alias is allowed on document root without '---' P.Levels.Pop; end if; return True; when Lexer.Flow_Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; Header_End := P.Current.Start_Pos; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then if Lexer.Last_Scalar_Was_Multiline (P.L) then raise Parser_Error with "Implicit mapping key may not be multiline"; end if; P.Cached := E; E := Event'(Start_Position => P.Header_Start, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; elsif P.Current.Kind in Lexer.Indentation | Lexer.Document_End | Lexer.Directives_End | Lexer.Stream_End then raise Parser_Error with "Scalar at root level requires '---'."; end if; return True; when Lexer.Flow_Map_Start | Lexer.Flow_Seq_Start => P.Levels.Top.State := Before_Flow_Item_Props'Access; return False; when Lexer.Indentation => raise Parser_Error with "Stand-alone node properties not allowed on non-header line"; when others => raise Parser_Error with "Unexpected token (expected implicit mapping key): " & P.Current.Kind'Img; end case; end Require_Implicit_Map_Start; function At_Block_Indentation (P : in out Class; E : out Event) return Boolean is Header_End : Mark; begin if P.Block_Indentation = P.Levels.Top.Indentation and then (P.Current.Kind /= Lexer.Seq_Item_Ind or else P.Levels.Element (P.Levels.Length - 2).State = In_Block_Seq'Access) then -- empty element is empty scalar E := Event'(Start_Position => P.Header_Start, End_Position => P.Header_Start, Kind => Scalar, Scalar_Properties => P.Header_Props, Scalar_Style => Plain, Content => Text.Empty); P.Header_Props := Default_Properties; P.Levels.Pop; P.Levels.Pop; return True; end if; P.Inline_Start := P.Current.Start_Pos; P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Node_Property_Kind => if Is_Empty (P.Header_Props) then P.Levels.Top.State := Require_Inline_Block_Item'Access; else P.Levels.Top.State := Require_Implicit_Map_Start'Access; end if; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Seq_Item_Ind => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Sequence_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.all := (In_Block_Seq'Access, Lexer.Recent_Indentation (P.L)); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => Lexer.Recent_Indentation (P.L))); P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Map_Key_Ind => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.all := (Before_Block_Map_Value'Access, Lexer.Recent_Indentation (P.L)); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => Lexer.Recent_Indentation (P.L))); P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Flow_Scalar_Token_Kind => P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Header_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Header_Props := Default_Properties; Header_End := P.Current.Start_Pos; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then if Lexer.Last_Scalar_Was_Multiline (P.L) then raise Parser_Error with "Implicit mapping key may not be multiline"; end if; P.Cached := E; E := Event'(Start_Position => P.Header_Start, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => P.Cached.Scalar_Properties, Collection_Style => Block); P.Cached.Scalar_Properties := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; else P.Levels.Pop; end if; return True; when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); P.Inline_Props := Default_Properties; Header_End := P.Current.Start_Pos; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then P.Cached := E; E := Event'(Start_Position => P.Header_Start, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; elsif not Is_Empty (P.Header_Props) then raise Parser_Error with "Alias may not have properties1"; else P.Levels.Pop; end if; return True; when others => P.Levels.Top.State := At_Block_Indentation_Props'Access; return False; end case; end At_Block_Indentation; function At_Block_Indentation_Props (P : in out Class; E : out Event) return Boolean is Header_End : Mark; begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Map_Value_Ind => P.Cached := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Inline_Props := Default_Properties; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; return True; when Lexer.Flow_Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; Header_End := P.Current.Start_Pos; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then if Lexer.Last_Scalar_Was_Multiline (P.L) then raise Parser_Error with "Implicit mapping key may not be multiline"; end if; P.Cached := E; E := Event'(Start_Position => P.Header_Start, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Map_Start'Access; else P.Levels.Pop; end if; return True; when Lexer.Flow_Map_Start => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Flow); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Flow_Map_Sep'Access; P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Flow_Seq_Start => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Sequence_Start, Collection_Properties => P.Header_Props, Collection_Style => Flow); P.Header_Props := Default_Properties; P.Levels.Top.State := After_Flow_Seq_Sep'Access; P.Current := Lexer.Next_Token (P.L); return True; when others => raise Parser_Error with "Unexpected token (expected block content): " & P.Current.Kind'Img; end case; end At_Block_Indentation_Props; function Before_Node_Properties (P : in out Class; E : out Event) return Boolean is pragma Unreferenced (E); begin case P.Current.Kind is when Lexer.Tag_Handle => if P.Inline_Props.Tag /= Tags.Question_Mark then raise Parser_Error with "Only one tag allowed per element"; end if; P.Inline_Props.Tag := Parse_Tag (P); when Lexer.Verbatim_Tag => if P.Inline_Props.Tag /= Tags.Question_Mark then raise Parser_Error with "Only one tag allowed per element"; end if; P.Inline_Props.Tag := Lexer.Current_Content (P.L); when Lexer.Anchor => if P.Inline_Props.Anchor /= Text.Empty then raise Parser_Error with "Only one anchor allowed per element"; end if; P.Inline_Props.Anchor := P.Pool.From_String (Lexer.Short_Lexeme (P.L)); when Lexer.Annotation_Handle => declare NS : constant String := Lexer.Full_Lexeme (P.L); begin P.Current := Lexer.Next_Token (P.L); if P.Current.Kind /= Lexer.Suffix then raise Parser_Error with "Unexpected token (expected annotation suffix): " & P.Current.Kind'Img; end if; if NS = "@@" then E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.Start_Pos, Kind => Annotation_Start, Annotation_Properties => P.Inline_Props, Namespace => Standard_Annotation_Namespace, Name => Lexer.Current_Content (P.L)); else E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.Start_Pos, Kind => Annotation_Start, Annotation_Properties => P.Inline_Props, Namespace => P.Pool.From_String (NS), Name => Lexer.Current_Content (P.L)); end if; end; P.Inline_Props := Default_Properties; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Params_Start then P.Current := Lexer.Next_Token (P.L); P.Levels.Push ((State => After_Param_Sep'Access, Indentation => P.Block_Indentation)); else P.Levels.Top.State := After_Annotation'Access; end if; return True; when Lexer.Indentation => P.Header_Props := P.Inline_Props; P.Inline_Props := Default_Properties; P.Levels.Pop; return False; when Lexer.Alias => raise Parser_Error with "Alias may not have node properties"; when others => P.Levels.Pop; return False; end case; P.Current := Lexer.Next_Token (P.L); return False; end Before_Node_Properties; function After_Compact_Parent (P : in out Class; E : out Event) return Boolean is begin P.Inline_Start := P.Current.Start_Pos; case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Top.State := After_Compact_Parent_Props'Access; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); when Lexer.Seq_Item_Ind => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Sequence_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.all := (In_Block_Seq'Access, Lexer.Recent_Indentation (P.L)); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => <>)); P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Map_Key_Ind => E := Event'(Start_Position => P.Header_Start, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Header_Props, Collection_Style => Block); P.Header_Props := Default_Properties; P.Levels.Top.all := (Before_Block_Map_Value'Access, Lexer.Recent_Indentation (P.L)); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => <>)); P.Current := Lexer.Next_Token (P.L); return True; when others => P.Levels.Top.State := After_Compact_Parent_Props'Access; return False; end case; return False; end After_Compact_Parent; function After_Compact_Parent_Props (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Indentation => P.Header_Start := P.Inline_Start; P.Levels.Top.all := (State => At_Block_Indentation'Access, Indentation => P.Levels.Element (P.Levels.Length - 2).Indentation); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); return False; when Lexer.Stream_End | Lexer.Document_End | Lexer.Directives_End => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.Start_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Inline_Props := Default_Properties; P.Levels.Pop; return True; when Lexer.Map_Value_Ind => P.Cached := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Inline_Props := Default_Properties; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.Start_Pos, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Block); P.Levels.Top.State := After_Implicit_Map_Start'Access; return True; when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); declare Header_End : constant Mark := P.Current.Start_Pos; begin P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then P.Cached := E; E := Event'(Start_Position => Header_End, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Block); P.Levels.Top.State := After_Implicit_Map_Start'Access; else P.Levels.Pop; end if; end; return True; when Lexer.Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; declare Header_End : constant Mark := P.Current.Start_Pos; begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then if Lexer.Last_Scalar_Was_Multiline (P.L) then raise Parser_Error with "Implicit mapping key may not be multiline"; end if; P.Cached := E; E := Event'(Start_Position => Header_End, End_Position => Header_End, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Block); P.Levels.Top.State := After_Implicit_Map_Start'Access; else P.Levels.Pop; end if; end; return True; when Lexer.Flow_Map_Start => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Inline_Props, Collection_Style => Flow); P.Inline_Props := Default_Properties; P.Levels.Top.State := After_Flow_Map_Sep'Access; P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Flow_Seq_Start => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Sequence_Start, Collection_Properties => P.Inline_Props, Collection_Style => Flow); P.Inline_Props := Default_Properties; P.Levels.Top.State := After_Flow_Seq_Sep'Access; P.Current := Lexer.Next_Token (P.L); return True; when others => raise Parser_Error with "Unexpected token (expected newline or flow item start): " & P.Current.Kind'Img; end case; end After_Compact_Parent_Props; function After_Block_Parent (P : in out Class; E : out Event) return Boolean is pragma Unreferenced (E); begin P.Inline_Start := P.Current.Start_Pos; case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Top.State := After_Block_Parent_Props'Access; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); when Lexer.Seq_Item_Ind | Lexer.Map_Key_Ind => raise Parser_Error with "Compact notation not allowed after implicit key"; when others => P.Levels.Top.State := After_Block_Parent_Props'Access; end case; return False; end After_Block_Parent; function After_Block_Parent_Props (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Map_Value_Ind => raise Parser_Error with "Compact notation not allowed after implicit key"; when Lexer.Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then raise Parser_Error with "Compact notation not allowed after implicit key"; end if; P.Levels.Pop; return True; when others => P.Levels.Top.State := After_Compact_Parent_Props'Access; return False; end case; end After_Block_Parent_Props; function Require_Inline_Block_Item (P : in out Class; E : out Event) return Boolean is pragma Unreferenced (E); begin P.Levels.Top.Indentation := Lexer.Recent_Indentation (P.L); case P.Current.Kind is when Lexer.Indentation => raise Parser_Error with "Node properties may not stand alone on a line"; when others => P.Levels.Top.State := After_Compact_Parent_Props'Access; return False; end case; end Require_Inline_Block_Item; function Before_Doc_End (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Document_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Document_End, Implicit_End => False); P.Levels.Top.State := Before_Doc'Access; Reset_Tag_Handles (P); P.Current := Lexer.Next_Token (P.L); when Lexer.Stream_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Document_End, Implicit_End => True); P.Levels.Pop; when Lexer.Directives_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Document_End, Implicit_End => True); Reset_Tag_Handles (P); P.Levels.Top.State := Before_Doc'Access; when others => raise Parser_Error with "Unexpected token (expected document end): " & P.Current.Kind'Img; end case; return True; end Before_Doc_End; function In_Block_Seq (P : in out Class; E : out Event) return Boolean is begin if P.Block_Indentation > P.Levels.Top.Indentation then raise Parser_Error with "Invalid indentation (bseq); got" & P.Block_Indentation'Img & ", expected" & P.Levels.Top.Indentation'Img; end if; case P.Current.Kind is when Lexer.Seq_Item_Ind => P.Current := Lexer.Next_Token (P.L); P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => P.Block_Indentation)); return False; when others => if P.Levels.Element (P.Levels.Length - 2).Indentation = P.Levels.Top.Indentation then E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Sequence_End); P.Levels.Pop; P.Levels.Pop; return True; else raise Parser_Error with "Illegal token (expected block sequence indicator): " & P.Current.Kind'Img; end if; end case; end In_Block_Seq; function After_Implicit_Map_Start (P : in out Class; E : out Event) return Boolean is begin E := P.Cached; P.Levels.Top.State := After_Implicit_Key'Access; return True; end After_Implicit_Map_Start; function Before_Block_Map_Key (P : in out Class; E : out Event) return Boolean is begin if P.Block_Indentation > P.Levels.Top.Indentation then raise Parser_Error with "Invalid indentation (bmk); got" & P.Block_Indentation'Img & ", expected" & P.Levels.Top.Indentation'Img & ", token = " & P.Current.Kind'Img; end if; case P.Current.Kind is when Lexer.Map_Key_Ind => P.Levels.Top.State := Before_Block_Map_Value'Access; P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => P.Levels.Top.Indentation)); P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Node_Property_Kind => P.Levels.Top.State := At_Block_Map_Key_Props'Access; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Flow_Scalar_Token_Kind => P.Levels.Top.State := At_Block_Map_Key_Props'Access; return False; when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); P.Current := Lexer.Next_Token (P.L); P.Levels.Top.State := After_Implicit_Key'Access; return True; when Lexer.Map_Value_Ind => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Top.State := Before_Block_Map_Value'Access; return True; when others => raise Parser_Error with "Unexpected token (expected mapping key): " & P.Current.Kind'Img; end case; end Before_Block_Map_Key; function At_Block_Map_Key_Props (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); when Lexer.Flow_Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; if Lexer.Last_Scalar_Was_Multiline (P.L) then raise Parser_Error with "Implicit mapping key may not be multiline"; end if; when Lexer.Map_Value_Ind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.Start_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Inline_Props := Default_Properties; P.Levels.Top.State := After_Implicit_Key'Access; return True; when others => raise Parser_Error with "Unexpected token (expected implicit mapping key): " & P.Current.Kind'Img; end case; P.Current := Lexer.Next_Token (P.L); P.Levels.Top.State := After_Implicit_Key'Access; return True; end At_Block_Map_Key_Props; function After_Implicit_Key (P : in out Class; E : out Event) return Boolean is pragma Unreferenced (E); begin if P.Current.Kind /= Lexer.Map_Value_Ind then raise Parser_Error with "Unexpected token (expected ':'): " & P.Current.Kind'Img; end if; P.Current := Lexer.Next_Token (P.L); P.Levels.Top.State := Before_Block_Map_Key'Access; P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Block_Parent'Access, Indentation => P.Levels.Top.Indentation)); return False; end After_Implicit_Key; function Before_Block_Map_Value (P : in out Class; E : out Event) return Boolean is begin if P.Block_Indentation > P.Levels.Top.Indentation then raise Parser_Error with "Invalid indentation (bmv)"; end if; case P.Current.Kind is when Lexer.Map_Value_Ind => P.Levels.Top.State := Before_Block_Map_Key'Access; P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); P.Levels.Push ((State => After_Compact_Parent'Access, Indentation => P.Levels.Top.Indentation)); P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Map_Key_Ind | Lexer.Flow_Scalar_Token_Kind | Lexer.Node_Property_Kind => -- the value is allowed to be missing after an explicit key E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Top.State := Before_Block_Map_Key'Access; return True; when others => raise Parser_Error with "Unexpected token (expected mapping value): " & P.Current.Kind'Img; end case; end Before_Block_Map_Value; function Before_Block_Indentation (P : in out Class; E : out Event) return Boolean is procedure End_Block_Node is begin if P.Levels.Top.State = Before_Block_Map_Key'Access then E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_End); elsif P.Levels.Top.State = Before_Block_Map_Value'Access then E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Top.State := Before_Block_Map_Key'Access; P.Levels.Push ((State => Before_Block_Indentation'Access, Indentation => <>)); return; elsif P.Levels.Top.State = In_Block_Seq'Access then E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Sequence_End); elsif P.Levels.Top.State = At_Block_Indentation'Access then E := Event'(Start_Position => P.Header_Start, End_Position => P.Header_Start, Kind => Scalar, Scalar_Properties => P.Header_Props, Scalar_Style => Plain, Content => Text.Empty); P.Header_Props := Default_Properties; elsif P.Levels.Top.State = Before_Block_Indentation'Access then raise Parser_Error with "Unexpected double Before_Block_Indentation"; else raise Parser_Error with "Internal error (please report this bug)"; end if; P.Levels.Pop; end End_Block_Node; begin P.Levels.Pop; case P.Current.Kind is when Lexer.Indentation => P.Block_Indentation := Lexer.Current_Indentation (P.L); if P.Block_Indentation < P.Levels.Top.Indentation then End_Block_Node; return True; else P.Current := Lexer.Next_Token (P.L); return False; end if; when Lexer.Stream_End | Lexer.Document_End | Lexer.Directives_End => P.Block_Indentation := 0; if P.Levels.Top.State /= Before_Doc_End'Access then End_Block_Node; return True; else return False; end if; when others => raise Parser_Error with "Unexpected content after node in block context (expected newline): " & P.Current.Kind'Img; end case; end Before_Block_Indentation; function Before_Flow_Item (P : in out Class; E : out Event) return Boolean is begin P.Inline_Start := P.Current.Start_Pos; case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Top.State := Before_Flow_Item_Props'Access; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; when others => P.Levels.Top.State := Before_Flow_Item_Props'Access; end case; return False; end Before_Flow_Item; function Before_Flow_Item_Props (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Node_Property_Kind => P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); when Lexer.Alias => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Alias, Target => P.Pool.From_String (Lexer.Short_Lexeme (P.L))); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; when Lexer.Scalar_Token_Kind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; when Lexer.Flow_Map_Start => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => P.Inline_Props, Collection_Style => Flow); P.Levels.Top.State := After_Flow_Map_Sep'Access; P.Current := Lexer.Next_Token (P.L); when Lexer.Flow_Seq_Start => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Sequence_Start, Collection_Properties => P.Inline_Props, Collection_Style => Flow); P.Levels.Top.State := After_Flow_Seq_Sep'Access; P.Current := Lexer.Next_Token (P.L); when Lexer.Flow_Map_End | Lexer.Flow_Seq_End | Lexer.Flow_Separator | Lexer.Map_Value_Ind => E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Pop; when others => raise Parser_Error with "Unexpected token (expected flow node): " & P.Current.Kind'Img; end case; P.Inline_Props := Default_Properties; return True; end Before_Flow_Item_Props; function After_Flow_Map_Key (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Map_Value_Ind => P.Levels.Top.State := After_Flow_Map_Value'Access; P.Levels.Push ((State => Before_Flow_Item'Access, others => <>)); P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Flow_Separator | Lexer.Flow_Map_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Top.State := After_Flow_Map_Value'Access; return True; when others => raise Parser_Error with "Unexpected token (expected ':'): " & P.Current.Kind'Img; end case; end After_Flow_Map_Key; function After_Flow_Map_Value (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Flow_Separator => P.Levels.Top.State := After_Flow_Map_Sep'Access; P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Flow_Map_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_End); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; when Lexer.Flow_Scalar_Token_Kind | Lexer.Map_Key_Ind | Lexer.Anchor | Lexer.Alias | Lexer.Annotation_Handle | Lexer.Flow_Map_Start | Lexer.Flow_Seq_Start => raise Parser_Error with "Missing ','"; when others => raise Parser_Error with "Unexpected token (expected ',' or '}'): " & P.Current.Kind'Img; end case; end After_Flow_Map_Value; function After_Flow_Seq_Item (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Flow_Separator => P.Levels.Top.State := After_Flow_Seq_Sep'Access; P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Flow_Seq_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Sequence_End); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; when Lexer.Flow_Scalar_Token_Kind | Lexer.Map_Key_Ind | Lexer.Anchor | Lexer.Alias | Lexer.Annotation_Handle | Lexer.Flow_Map_Start | Lexer.Flow_Seq_Start => raise Parser_Error with "Missing ','"; when others => raise Parser_Error with "Unexpected token (expected ',' or ']'): " & P.Current.Kind'Img; end case; end After_Flow_Seq_Item; function After_Flow_Map_Sep (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Map_Key_Ind => P.Current := Lexer.Next_Token (P.L); when Lexer.Flow_Map_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_End); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; when others => null; end case; P.Levels.Top.State := After_Flow_Map_Key'Access; P.Levels.Push ((State => Before_Flow_Item'Access, Indentation => <>)); return False; end After_Flow_Map_Sep; function Possible_Next_Sequence_Item (P : in out Class; E : out Event; End_Token : Lexer.Token_Kind; After_Props, After_Item : State_Type) return Boolean is begin P.Inline_Start := P.Current.Start_Pos; case P.Current.Kind is when Lexer.Flow_Separator => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.Start_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Current := Lexer.Next_Token (P.L); return True; when Lexer.Node_Property_Kind => P.Levels.Top.State := After_Props; P.Levels.Push ((State => Before_Node_Properties'Access, Indentation => <>)); return False; when Lexer.Flow_Scalar_Token_Kind => P.Levels.Top.State := After_Props; return False; when Lexer.Map_Key_Ind => P.Levels.Top.State := After_Item; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Flow); P.Current := Lexer.Next_Token (P.L); P.Levels.Push ((State => Before_Pair_Value'Access, others => <>)); P.Levels.Push ((State => Before_Flow_Item'Access, others => <>)); return True; when Lexer.Map_Value_Ind => P.Levels.Top.State := After_Item; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Flow); P.Levels.Push ((State => At_Empty_Pair_Key'Access, others => <>)); return True; when others => if P.Current.Kind = End_Token then E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Sequence_End); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; else P.Levels.Top.State := After_Item; P.Levels.Push ((State => Before_Flow_Item'Access, others => <>)); return False; end if; end case; end Possible_Next_Sequence_Item; function After_Flow_Seq_Sep (P : in out Class; E : out Event) return Boolean is begin return Possible_Next_Sequence_Item (P, E, Lexer.Flow_Seq_End, After_Flow_Seq_Sep_Props'Access, After_Flow_Seq_Item'Access); end After_Flow_Seq_Sep; function Forced_Next_Sequence_Item (P : in out Class; E : out Event) return Boolean is begin if P.Current.Kind in Lexer.Flow_Scalar_Token_Kind then E := Event'(Start_Position => P.Inline_Start, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => P.Inline_Props, Scalar_Style => To_Style (P.Current.Kind), Content => Lexer.Current_Content (P.L)); P.Inline_Props := Default_Properties; P.Current := Lexer.Next_Token (P.L); if P.Current.Kind = Lexer.Map_Value_Ind then P.Cached := E; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.Start_Pos, Kind => Mapping_Start, Collection_Properties => Default_Properties, Collection_Style => Flow); P.Levels.Push ((State => After_Implicit_Pair_Start'Access, Indentation => <>)); end if; return True; else P.Levels.Push ((State => Before_Flow_Item_Props'Access, others => <>)); return False; end if; end Forced_Next_Sequence_Item; function After_Flow_Seq_Sep_Props (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.State := After_Flow_Seq_Item'Access; return Forced_Next_Sequence_Item (P, E); end After_Flow_Seq_Sep_Props; function At_Empty_Pair_Key (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.State := Before_Pair_Value'Access; E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.Start_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); return True; end At_Empty_Pair_Key; function Before_Pair_Value (P : in out Class; E : out Event) return Boolean is begin if P.Current.Kind = Lexer.Map_Value_Ind then P.Levels.Top.State := After_Pair_Value'Access; P.Levels.Push ((State => Before_Flow_Item'Access, others => <>)); P.Current := Lexer.Next_Token (P.L); return False; else -- pair ends here without value. E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Scalar, Scalar_Properties => Default_Properties, Scalar_Style => Plain, Content => Text.Empty); P.Levels.Pop; return True; end if; end Before_Pair_Value; function After_Implicit_Pair_Start (P : in out Class; E : out Event) return Boolean is begin E := P.Cached; P.Current := Lexer.Next_Token (P.L); P.Levels.Top.State := After_Pair_Value'Access; P.Levels.Push ((State => Before_Flow_Item'Access, others => <>)); return True; end After_Implicit_Pair_Start; function After_Pair_Value (P : in out Class; E : out Event) return Boolean is begin E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Mapping_End); P.Levels.Pop; return True; end After_Pair_Value; function After_Param_Sep (P : in out Class; E : out Event) return Boolean is begin return Possible_Next_Sequence_Item (P, E, Lexer.Params_End, After_Param_Sep_Props'Access, After_Param'Access); end After_Param_Sep; function After_Param_Sep_Props (P : in out Class; E : out Event) return Boolean is begin P.Levels.Top.State := After_Param'Access; return Forced_Next_Sequence_Item (P, E); end After_Param_Sep_Props; function After_Param (P : in out Class; E : out Event) return Boolean is begin case P.Current.Kind is when Lexer.Flow_Separator => P.Levels.Top.State := After_Param_Sep'Access; P.Current := Lexer.Next_Token (P.L); return False; when Lexer.Params_End => E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.End_Pos, Kind => Annotation_End); P.Current := Lexer.Next_Token (P.L); P.Levels.Pop; return True; when Lexer.Flow_Scalar_Token_Kind | Lexer.Map_Key_Ind | Lexer.Anchor | Lexer.Alias | Lexer.Annotation_Handle | Lexer.Flow_Map_Start | Lexer.Flow_Seq_Start => raise Parser_Error with "Missing ','"; when others => raise Parser_Error with "Unexpected token (expected ',' or ')'): " & P.Current.Kind'Img; end case; end After_Param; function After_Annotation (P : in out Class; E : out Event) return Boolean is begin E := Event'(Start_Position => P.Current.Start_Pos, End_Position => P.Current.Start_Pos, Kind => Annotation_End); P.Levels.Pop; return True; end After_Annotation; end Yaml.Parser;
charlie5/lace
Ada
136
ads
with any_Math.any_Analysis; package float_Math.Analysis is new float_Math.any_Analysis; pragma Pure (float_Math.Analysis);
jrmarino/AdaBase
Ada
1,891
ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package AdaBase is pragma Pure; type Error_Modes is (silent, warning, raise_exception); type Case_Modes is (lower_case, natural_case, upper_case); type Trax_Isolation is (read_uncommitted, read_committed, repeatable_read, serializable); type Log_Category is (connecting, disconnecting, transaction, execution, statement_preparation, statement_execution, miscellaneous, note); type Driver_Type is (foundation, driver_mysql, driver_postgresql, driver_sqlite, driver_firebird); type Null_Priority is (native, nulls_first, nulls_last); type ISO_Keyword_List is array (Trax_Isolation) of String (1 .. 16); type Trax_ID is mod 2 ** 64; subtype BLOB_Maximum is Positive range 2 ** 12 .. 2 ** 30; subtype SQL_State is String (1 .. 5); subtype Driver_Codes is Integer range -999 .. 4999; subtype Posix_Port is Natural range 0 .. 65535; subtype Affected_Rows is Trax_ID; ISO_Keywords : constant ISO_Keyword_List := ("READ UNCOMMITTED", "READ COMMITTED ", "REPEATABLE READ ", "SERIALIZABLE "); blankstring : constant String := ""; stateless : constant SQL_State := " "; portless : constant Posix_Port := 0; type field_types is (ft_nbyte0, ft_nbyte1, ft_nbyte2, ft_nbyte3, ft_nbyte4, ft_nbyte8, ft_byte1, ft_byte2, ft_byte3, ft_byte4, ft_byte8, ft_real9, ft_real18, ft_textual, ft_widetext, ft_supertext, ft_timestamp, ft_chain, ft_enumtype, ft_settype, ft_bits, ft_utf8, ft_geometry); ERRMODE_EXCEPTION : exception; end AdaBase;
rogermc2/GA_Ada
Ada
415
ads
with Interfaces; use Interfaces; package Bits is function Bit_Count (Bitmap : Unsigned_32) return Natural; function Highest_One_Bit (Bitmap : Unsigned_32) return Natural; function Lowest_One_Bit (Bitmap : Unsigned_32) return Natural; function Number_Of_Leading_Zero_Bits (Bitmap : Unsigned_32) return Natural; function Number_Of_Trailing_Zero_Bits (Bitmap : Unsigned_32) return Natural; end Bits;
reznikmm/matreshka
Ada
3,679
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Elements; package ODF.DOM.Table_Background_Elements is pragma Preelaborate; type ODF_Table_Background is limited interface and XML.DOM.Elements.DOM_Element; type ODF_Table_Background_Access is access all ODF_Table_Background'Class with Storage_Size => 0; end ODF.DOM.Table_Background_Elements;
Rodeo-McCabe/orka
Ada
972
ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2020 onox <[email protected]> -- -- 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 Ahven.Framework; package Test_SIMD_FMA_Doubles_Arithmetic is type Test is new Ahven.Framework.Test_Case with null record; overriding procedure Initialize (T : in out Test); private procedure Test_Multiply_Vector; procedure Test_Multiply_Matrices; end Test_SIMD_FMA_Doubles_Arithmetic;
reznikmm/matreshka
Ada
3,714
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Attributes; package ODF.DOM.Dr3d_Shade_Mode_Attributes is pragma Preelaborate; type ODF_Dr3d_Shade_Mode_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Dr3d_Shade_Mode_Attribute_Access is access all ODF_Dr3d_Shade_Mode_Attribute'Class with Storage_Size => 0; end ODF.DOM.Dr3d_Shade_Mode_Attributes;
stcarrez/helios
Ada
8,524
adb
----------------------------------------------------------------------- -- helios-monitor -- Helios monitor -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Helios.Datas is use type Schemas.Definition_Type_Access; use type Schemas.Value_Index; function Allocate (Queue : in Snapshot_Queue_Type) return Snapshot_Type_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Helios.Datas"); Reports : Report_Queue_Type; function Allocate (Queue : in Snapshot_Queue_Type) return Snapshot_Type_Access is Snapshot : constant Snapshot_Type_Access := new Snapshot_Type; Count : constant Value_Array_Index := Queue.Schema.Index * Value_Array_Index (Queue.Count); begin Log.Info ("Allocate snapshot with {0} values", Value_Array_Index'Image (Count)); Snapshot.Schema := Queue.Schema; Snapshot.Offset := 0; Snapshot.Count := Queue.Schema.Index; Snapshot.Values := new Value_Array (1 .. Count); Snapshot.Values.all := (others => 0); Snapshot.Start_Time := Ada.Real_Time.Clock; return Snapshot; end Allocate; -- ------------------------------ -- Initialize the snapshot queue for the schema. -- ------------------------------ procedure Initialize (Queue : in out Snapshot_Queue_Type; Schema : in Helios.Schemas.Definition_Type_Access; Count : in Positive) is begin Log.Info ("Initialize schema queue {0} with{1} samples of{2} values", Schema.Name, Positive'Image (Count), Value_Array_Index'Image (Schema.Index)); Queue.Schema := Schema; Queue.Count := Count; Queue.Current := Allocate (Queue); end Initialize; -- ------------------------------ -- Get the snapshot start time. -- ------------------------------ function Get_Start_Time (Data : in Snapshot_Type) return Ada.Real_Time.Time is begin return Data.Start_Time; end Get_Start_Time; -- ------------------------------ -- Get the snapshot end time. -- ------------------------------ function Get_End_Time (Data : in Snapshot_Type) return Ada.Real_Time.Time is begin return Data.End_Time; end Get_End_Time; -- ------------------------------ -- Finish updating the current values of the snapshot. -- ------------------------------ procedure Finish (Data : in out Snapshot_Type) is begin Data.Offset := Data.Offset + Data.Count; end Finish; -- ------------------------------ -- Set the value in the snapshot. -- ------------------------------ procedure Set_Value (Into : in out Snapshot_Type; Def : in Schemas.Definition_Type_Access; Value : in Uint64) is begin if Def /= null and then Def.Index > 0 then Into.Values (Def.Index + Into.Offset) := Value; end if; end Set_Value; -- ------------------------------ -- Iterate over the values in the snapshot and collected for the definition node. -- ------------------------------ procedure Iterate (Data : in Helios.Datas.Snapshot_Type; Node : in Helios.Schemas.Definition_Type_Access; Process : not null access procedure (Value : in Uint64)) is Count : constant Helios.Datas.Value_Array_Index := Data.Count; Pos : Helios.Datas.Value_Array_Index := Node.Index; begin Log.Debug ("Iterate {0} from {1} to {2} step {3}", Node.Name, Value_Array_Index'Image (Count), Value_Array_Index'Image (Pos)); while Pos < Data.Offset loop Process (Data.Values (Pos)); Pos := Pos + Count; end loop; end Iterate; -- ------------------------------ -- Iterate over the values in the snapshot and collected for the definition node. -- ------------------------------ procedure Iterate (Data : in Helios.Datas.Snapshot_Type; Node : in Helios.Schemas.Definition_Type_Access; Process_Snapshot : not null access procedure (D : in Snapshot_Type; N : in Definition_Type_Access); Process_Values : not null access procedure (D : in Snapshot_Type; N : in Definition_Type_Access)) is Child : Helios.Schemas.Definition_Type_Access; begin Child := Node.Child; while Child /= null loop if Child.Child /= null then Process_Snapshot (Data, Child); elsif Child.Index > 0 then Process_Values (Data, Child); end if; Child := Child.Next; end loop; end Iterate; -- ------------------------------ -- Iterate over the values of the reports. -- ------------------------------ procedure Iterate (Report : in Report_Queue_Type; Process : not null access procedure (Data : in Snapshot_Type; Node : in Definition_Type_Access)) is begin if not Report.Snapshot.Is_Null then declare List : constant Snapshot_Accessor := Report.Snapshot.Value; Snapshot : Snapshot_Type_Access := List.First; begin while Snapshot /= null loop Process (Snapshot.all, Snapshot.Schema); Snapshot := Snapshot.Next; end loop; end; end if; end Iterate; -- ------------------------------ -- Prepare the snapshot queue to collect new values. -- ------------------------------ procedure Prepare (Queue : in out Snapshot_Queue_Type; Snapshot : out Snapshot_Type_Access) is begin Snapshot := Queue.Current; -- Snapshot.Offset := Snapshot.Offset + Snapshot.Count; if Snapshot.Offset >= Snapshot.Values'Last then Flush (Queue); Snapshot := Queue.Current; end if; end Prepare; -- ------------------------------ -- Flush the snapshot to start a fresh one for the queue. -- ------------------------------ procedure Flush (Queue : in out Snapshot_Queue_Type) is Snapshot : constant Snapshot_Type_Access := Queue.Current; begin if Reports.Snapshot.Is_Null then Reports.Snapshot := Snapshot_Refs.Create; end if; Snapshot.Next := Reports.Snapshot.Value.First; Reports.Snapshot.Value.First := Queue.Current; Queue.Current := Allocate (Queue); Snapshot.End_Time := Queue.Current.Start_Time; end Flush; -- ------------------------------ -- Release the snapshots when the reference counter reaches 0. -- ------------------------------ overriding procedure Finalize (Object : in out Snapshot_List) is procedure Free is new Ada.Unchecked_Deallocation (Object => Snapshot_Type, Name => Snapshot_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => Value_Array, Name => Value_Array_Access); Snapshot : Snapshot_Type_Access := Object.First; Next : Snapshot_Type_Access; begin while Snapshot /= null loop Next := Snapshot.Next; Free (Snapshot.Values); Free (Snapshot); Snapshot := Next; end loop; end Finalize; Empty_Snapshot : Snapshot_Refs.Ref; function Get_Report return Report_Queue_Type is Result : constant Report_Queue_Type := Reports; begin Reports.Snapshot := Empty_Snapshot; return Result; end Get_Report; end Helios.Datas;
apple-oss-distributions/old_ncurses
Ada
3,595
ads
------------------------------------------------------------------------------ -- -- -- GNAT ncurses Binding -- -- -- -- Terminal_Interface.Curses.Text_IO.Aux -- -- -- -- S P E C -- -- -- ------------------------------------------------------------------------------ -- Copyright (c) 1998 Free Software Foundation, Inc. -- -- -- -- 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, distribute with modifications, 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 ABOVE 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. -- -- -- -- Except as contained in this notice, the name(s) of the above copyright -- -- holders shall not be used in advertising or otherwise to promote the -- -- sale, use or other dealings in this Software without prior written -- -- authorization. -- ------------------------------------------------------------------------------ -- Author: Juergen Pfeifer <[email protected]> 1996 -- Version Control: -- $Revision: 1.1.1.1 $ -- Binding Version 01.00 ------------------------------------------------------------------------------ private package Terminal_Interface.Curses.Text_IO.Aux is -- pragma Preelaborate (Aux); -- This routine is called from the Text_IO output routines for numeric -- and enumeration types. -- procedure Put_Buf (Win : in Window; -- The output window Buf : in String; -- The buffer containing the text Width : in Field; -- The width of the output field Signal : in Boolean := True; -- If true, we raise Layout_Error Ljust : in Boolean := False); -- The Buf is left justified end Terminal_Interface.Curses.Text_IO.Aux;
reznikmm/matreshka
Ada
3,974
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ -- An initial node is a control node at which flow starts when the activity -- is invoked. ------------------------------------------------------------------------------ with AMF.UML.Control_Nodes; package AMF.UML.Initial_Nodes is pragma Preelaborate; type UML_Initial_Node is limited interface and AMF.UML.Control_Nodes.UML_Control_Node; type UML_Initial_Node_Access is access all UML_Initial_Node'Class; for UML_Initial_Node_Access'Storage_Size use 0; end AMF.UML.Initial_Nodes;
AaronC98/PlaneSystem
Ada
4,107
ads
------------------------------------------------------------------------------ -- Ada Web Server -- -- -- -- Copyright (C) 2000-2015, AdaCore -- -- -- -- This library is free software; you can redistribute it and/or modify -- -- it under terms of the GNU General Public License as published by the -- -- Free Software Foundation; either version 3, or (at your option) any -- -- later version. This library is distributed in the hope that it will be -- -- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- 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/>. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ------------------------------------------------------------------------------ pragma Ada_2012; with AWS.Client; with SOAP.Message.Payload; with SOAP.Message.Response; with SOAP.WSDL.Schema; package SOAP.Client is Not_Specified : String renames AWS.Client.No_Data; function Call (URL : String; P : Message.Payload.Object; SOAPAction : String := No_SOAPAction; User : String := Not_Specified; Pwd : String := Not_Specified; Proxy : String := Not_Specified; Proxy_User : String := Not_Specified; Proxy_Pwd : String := Not_Specified; Timeouts : AWS.Client.Timeouts_Values := AWS.Client.No_Timeout; Asynchronous : Boolean := False; Schema : WSDL.Schema.Definition := WSDL.Schema.Empty) return Message.Response.Object'Class with Pre => URL'Length > 0; -- Send a SOAP HTTP request to URL address. The P is the Payload and -- SOAPAction is the required HTTP field. If it is not specified then the -- URI (URL resource) will be used for the SOAPAction field. The complete -- format is "URL & '#' & Procedure_Name" (Procedure_Name is retrieved -- from the Payload object. -- -- If Asynchronous is set to True the response from the server may be -- empty. In this specific case the success of the call depends on the -- HTTP status code. function Call (Connection : AWS.Client.HTTP_Connection; SOAPAction : String; P : Message.Payload.Object; Asynchronous : Boolean := False; Schema : WSDL.Schema.Definition := WSDL.Schema.Empty) return Message.Response.Object'Class with Pre => AWS.Client.Host (Connection)'Length > 0; -- Idem as above, but use an already opened connection end SOAP.Client;
JohnYang97/Space-Convoy
Ada
1,284
ads
-- -- Jan & Uwe R. Zimmer, Australia, July 2011 -- with Vectors_xD_I; pragma Elaborate_All (Vectors_xD_I); package Vectors_2D_P is type xy_Coordinates is (x, y); package Vectors_2Di is new Vectors_xD_I (Positive, xy_Coordinates); subtype Vector_2D_P is Vectors_2Di.Vector_xD_I; Zero_Vector_2D_P : constant Vector_2D_P := Vectors_2Di.Zero_Vector_xD; function Image (V : Vector_2D_P) return String renames Vectors_2Di.Image; function Norm (V : Vector_2D_P) return Vector_2D_P renames Vectors_2Di.Norm; function "*" (Scalar : Float; V : Vector_2D_P) return Vector_2D_P renames Vectors_2Di."*"; function "*" (V : Vector_2D_P; Scalar : Float) return Vector_2D_P renames Vectors_2Di."*"; function "/" (V : Vector_2D_P; Scalar : Float) return Vector_2D_P renames Vectors_2Di."/"; function "*" (V_Left, V_Right : Vector_2D_P) return Float renames Vectors_2Di."*"; function Angle_Between (V_Left, V_Right : Vector_2D_P) return Float renames Vectors_2Di.Angle_Between; function "+" (V_Left, V_Right : Vector_2D_P) return Vector_2D_P renames Vectors_2Di."+"; function "-" (V_Left, V_Right : Vector_2D_P) return Vector_2D_P renames Vectors_2Di."-"; function "abs" (V : Vector_2D_P) return Float renames Vectors_2Di."abs"; end Vectors_2D_P;
reznikmm/slimp
Ada
1,025
ads
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with League.Strings; package Slim.Messages.META is type META_Message is new Message with private; not overriding function Value (Self : META_Message) return League.Strings.Universal_String; private subtype Byte is Ada.Streams.Stream_Element; type META_Message is new Message with record Value : League.Strings.Universal_String; end record; overriding function Read (Data : not null access League.Stream_Element_Vectors.Stream_Element_Vector) return META_Message; overriding procedure Write (Self : META_Message; Tag : out Message_Tag; Data : out League.Stream_Element_Vectors.Stream_Element_Vector); overriding procedure Visit (Self : not null access META_Message; Visiter : in out Slim.Message_Visiters.Visiter'Class); end Slim.Messages.META;
PThierry/ewok-kernel
Ada
3,944
adb
-- -- Copyright 2018 The wookey project team <[email protected]> -- - Ryad Benadjila -- - Arnauld Michelizza -- - Mathieu Renard -- - Philippe Thierry -- - Philippe Trebuchet -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- with ewok.tasks; use ewok.tasks; with ewok.sanitize; with ewok.perm; with ewok.debug; with ewok.rng; with types.c; use type types.c.t_retval; package body ewok.syscalls.rng with spark_mode => off is procedure svc_get_random (caller_id : in ewok.tasks_shared.t_task_id; params : in out t_parameters; mode : in ewok.tasks_shared.t_task_mode) is length : unsigned_16 with address => params(2)'address; buffer : unsigned_8_array (1 .. unsigned_32 (length)) with address => to_address (params(1)); ok : boolean; begin -- Forbidden after end of task initialization if not is_init_done (caller_id) then goto ret_denied; end if; -- Does buffer'address is in the caller address space ? if not ewok.sanitize.is_range_in_data_slot (to_system_address (buffer'address), types.to_unsigned_32(length), caller_id, mode) then pragma DEBUG (debug.log (debug.ERROR, ewok.tasks.tasks_list(caller_id).name & ": svc_get_random(): 'value' parameter not in caller space")); goto ret_inval; end if; -- Size is arbitrary limited to 16 bytes to avoid exhausting the entropy pool -- FIXME - is that check really correct? if length > 16 then goto ret_inval; end if; -- Is the task allowed to use the RNG? if not ewok.perm.ressource_is_granted (ewok.perm.PERM_RES_TSK_RNG, caller_id) then pragma DEBUG (debug.log (debug.ERROR, ewok.tasks.tasks_list(caller_id).name & ": svc_get_random(): permission not granted")); goto ret_denied; end if; -- Calling the RNG which handle the potential random source errors (case -- of harware random sources such as TRNG IP) -- NOTE: there is some time when the generated random -- content may be weak for various reason due to arch-specific -- constraint. In this case, the return value is set to -- busy. Please check this return value when using this -- syscall to avoid using weak random content ewok.rng.random_array (buffer, ok); if not ok then pragma DEBUG (debug.log (debug.ERROR, ewok.tasks.tasks_list(caller_id).name & ": svc_get_random(): weak seed")); goto ret_busy; end if; set_return_value (caller_id, mode, SYS_E_DONE); ewok.tasks.set_state (caller_id, mode, TASK_STATE_RUNNABLE); return; <<ret_inval>> set_return_value (caller_id, mode, SYS_E_INVAL); ewok.tasks.set_state (caller_id, mode, TASK_STATE_RUNNABLE); return; <<ret_busy>> set_return_value (caller_id, mode, SYS_E_BUSY); ewok.tasks.set_state (caller_id, mode, TASK_STATE_RUNNABLE); return; <<ret_denied>> set_return_value (caller_id, mode, SYS_E_DENIED); ewok.tasks.set_state (caller_id, mode, TASK_STATE_RUNNABLE); return; end svc_get_random; end ewok.syscalls.rng;
zhmu/ananas
Ada
1,338
adb
-- { dg-do compile } -- { dg-options "-gnateF" } PACKAGE BODY Entry1 IS PROTECTED TYPE key_buffer IS PROCEDURE clear; ENTRY incr; ENTRY put (val : IN Natural); ENTRY get (val : OUT Natural); PRIVATE -- Stores Key states (key state controller) -- purpose: exclusive access max_len : Natural := 10; cnt : Natural := 0; END key_buffer; PROTECTED BODY key_buffer IS PROCEDURE clear IS BEGIN cnt := 0; END clear; ENTRY incr WHEN cnt < max_len IS BEGIN cnt := cnt + 1; END; ENTRY put (val : IN Natural) WHEN cnt < max_len IS BEGIN cnt := val; END put; ENTRY get (val : OUT Natural) WHEN cnt > 0 IS BEGIN val := cnt; END get; END key_buffer; my_buffer : key_buffer; FUNCTION pt2 (t : IN Float) RETURN Natural IS c : Natural; t2 : duration := duration (t); BEGIN SELECT my_buffer.get (c); RETURN c; OR DELAY t2; RETURN 0; END SELECT; END pt2; FUNCTION pt (t : IN Float) RETURN Natural IS c : Natural; BEGIN SELECT my_buffer.get (c); RETURN c; OR DELAY Duration (t); RETURN 0; END SELECT; END pt; END Entry1;
optikos/oasis
Ada
4,122
adb
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Streams.Stream_IO; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Interfaces; with Program.Scanners; package body Program.Plain_Source_Buffers is subtype UTF_8_String is Ada.Strings.UTF_Encoding.UTF_8_String; ---------------- -- Initialize -- ---------------- not overriding procedure Initialize (Self : in out Source_Buffer; Name : Program.Text) is procedure Read_File (Text : in out UTF_8_String); Input : Ada.Streams.Stream_IO.File_Type; --------------- -- Read_File -- --------------- procedure Read_File (Text : in out UTF_8_String) is Data : Ada.Streams.Stream_Element_Array (1 .. Text'Length) with Import, Convention => Ada, Address => Text'Address; Last : Ada.Streams.Stream_Element_Offset; begin Ada.Streams.Stream_IO.Read (Input, Data, Last); end Read_File; File_Size : Natural; File_Name : constant UTF_8_String := Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode (Name); begin Ada.Streams.Stream_IO.Open (Input, Ada.Streams.Stream_IO.In_File, File_Name); File_Size := Natural (Ada.Streams.Stream_IO.Size (Input)); Self.Text := new UTF_8_String (1 .. File_Size); Read_File (Self.Text.all); Ada.Streams.Stream_IO.Close (Input); Self.Rewind; end Initialize; ---------- -- Read -- ---------- overriding procedure Read (Self : in out Source_Buffer; Data : out Program.Source_Buffers.Character_Info_Array; Last : out Natural) is use all type Interfaces.Unsigned_32; procedure Add (Value : in out Interfaces.Unsigned_32; Continuation : String); --------- -- Add -- --------- procedure Add (Value : in out Interfaces.Unsigned_32; Continuation : String) is Code : Interfaces.Unsigned_32 range 2#10_000000# .. 2#10_111111#; begin for Next of Continuation loop Code := Character'Pos (Next); Value := Shift_Left (Value, 6) or (Code and 2#00_111111#); end loop; end Add; Index : Positive := Data'First; Min : constant Natural := Natural'Min (Data'Length, Self.Text'Last - Self.From + 1); Char : Interfaces.Unsigned_32; begin Last := Data'First + Min - 1; while Index <= Last and Self.From <= Self.Text'Last loop Char := Character'Pos (Self.Text (Self.From)); case Char is when 0 .. 16#7F# => Data (Index).Length := 1; when 2#110_00000# .. 2#110_11111# => Char := Char and 2#000_11111#; Data (Index).Length := 2; when 2#1110_0000# .. 2#1110_1111# => Char := Char and 2#0000_1111#; Data (Index).Length := 3; when 2#11110_000# .. 2#11110_111# => Char := Char and 2#00000_111#; Data (Index).Length := 4; when others => raise Constraint_Error with "Wrong UTF-8 data"; end case; Add (Char, Self.Text (Self.From + 1 .. Self.From + Data (Index).Length - 1)); Data (Index).Class := Program.Scanners.Tables.To_Class (Natural (Char)); Self.From := Self.From + Data (Index).Length; Index := Index + 1; end loop; end Read; ------------ -- Rewind -- ------------ overriding procedure Rewind (Self : in out Source_Buffer) is begin Self.From := 1; end Rewind; ---------- -- Text -- ---------- overriding function Text (Self : Source_Buffer; Span : Program.Source_Buffers.Span) return Program.Text is begin return Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode (Self.Text (Span.From .. Span.To)); end Text; end Program.Plain_Source_Buffers;
reznikmm/matreshka
Ada
4,805
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Visitors; with ODF.DOM.Text_Table_Index_Source_Elements; package Matreshka.ODF_Text.Table_Index_Source_Elements is type Text_Table_Index_Source_Element_Node is new Matreshka.ODF_Text.Abstract_Text_Element_Node and ODF.DOM.Text_Table_Index_Source_Elements.ODF_Text_Table_Index_Source with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Text_Table_Index_Source_Element_Node; overriding function Get_Local_Name (Self : not null access constant Text_Table_Index_Source_Element_Node) return League.Strings.Universal_String; overriding procedure Enter_Node (Self : not null access Text_Table_Index_Source_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Leave_Node (Self : not null access Text_Table_Index_Source_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Visit_Node (Self : not null access Text_Table_Index_Source_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); end Matreshka.ODF_Text.Table_Index_Source_Elements;
luk9400/nsi
Ada
308
ads
package Square_Root with SPARK_Mode is function Sqrt (X : Float; Tolerance : Float) return Float with SPARK_Mode, Pre => X >= 0.0 and X <= 1.8E19 and Tolerance > Float'Model_Epsilon and Tolerance <= 1.0, Post => abs (X - Sqrt'Result ** 2) <= X * Tolerance; end Square_Root;
AdaCore/spat
Ada
1,051
adb
------------------------------------------------------------------------------ -- Copyright (C) 2020 by Heisenbug Ltd. ([email protected]) -- -- This work is free. You can redistribute it and/or modify it under the -- terms of the Do What The Fuck You Want To Public License, Version 2, -- as published by Sam Hocevar. See the LICENSE file for more details. ------------------------------------------------------------------------------ pragma License (Unrestricted); with SPAT.Field_Names; package body SPAT.Flow_Item is --------------------------------------------------------------------------- -- Create --------------------------------------------------------------------------- overriding function Create (Object : in JSON_Value) return T is (Entity_Location.Create (Object => Object) with Rule => Rule_Name (Subject_Name'(Object.Get (Field => Field_Names.Rule))), Severity => Severity_Name (Subject_Name'(Object.Get (Field => Field_Names.Severity)))); end SPAT.Flow_Item;
optikos/oasis
Ada
3,876
ads
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Program.Elements.Expressions; with Program.Lexical_Elements; with Program.Elements.Discrete_Ranges; with Program.Elements.Slices; with Program.Element_Visitors; package Program.Nodes.Slices is pragma Preelaborate; type Slice is new Program.Nodes.Node and Program.Elements.Slices.Slice and Program.Elements.Slices.Slice_Text with private; function Create (Prefix : not null Program.Elements.Expressions .Expression_Access; Left_Bracket_Token : not null Program.Lexical_Elements .Lexical_Element_Access; Slice_Range : not null Program.Elements.Discrete_Ranges .Discrete_Range_Access; Right_Bracket_Token : not null Program.Lexical_Elements .Lexical_Element_Access) return Slice; type Implicit_Slice is new Program.Nodes.Node and Program.Elements.Slices.Slice with private; function Create (Prefix : not null Program.Elements.Expressions .Expression_Access; Slice_Range : not null Program.Elements.Discrete_Ranges .Discrete_Range_Access; Is_Part_Of_Implicit : Boolean := False; Is_Part_Of_Inherited : Boolean := False; Is_Part_Of_Instance : Boolean := False) return Implicit_Slice with Pre => Is_Part_Of_Implicit or Is_Part_Of_Inherited or Is_Part_Of_Instance; private type Base_Slice is abstract new Program.Nodes.Node and Program.Elements.Slices.Slice with record Prefix : not null Program.Elements.Expressions.Expression_Access; Slice_Range : not null Program.Elements.Discrete_Ranges .Discrete_Range_Access; end record; procedure Initialize (Self : aliased in out Base_Slice'Class); overriding procedure Visit (Self : not null access Base_Slice; Visitor : in out Program.Element_Visitors.Element_Visitor'Class); overriding function Prefix (Self : Base_Slice) return not null Program.Elements.Expressions.Expression_Access; overriding function Slice_Range (Self : Base_Slice) return not null Program.Elements.Discrete_Ranges.Discrete_Range_Access; overriding function Is_Slice_Element (Self : Base_Slice) return Boolean; overriding function Is_Expression_Element (Self : Base_Slice) return Boolean; type Slice is new Base_Slice and Program.Elements.Slices.Slice_Text with record Left_Bracket_Token : not null Program.Lexical_Elements .Lexical_Element_Access; Right_Bracket_Token : not null Program.Lexical_Elements .Lexical_Element_Access; end record; overriding function To_Slice_Text (Self : aliased in out Slice) return Program.Elements.Slices.Slice_Text_Access; overriding function Left_Bracket_Token (Self : Slice) return not null Program.Lexical_Elements.Lexical_Element_Access; overriding function Right_Bracket_Token (Self : Slice) return not null Program.Lexical_Elements.Lexical_Element_Access; type Implicit_Slice is new Base_Slice with record Is_Part_Of_Implicit : Boolean; Is_Part_Of_Inherited : Boolean; Is_Part_Of_Instance : Boolean; end record; overriding function To_Slice_Text (Self : aliased in out Implicit_Slice) return Program.Elements.Slices.Slice_Text_Access; overriding function Is_Part_Of_Implicit (Self : Implicit_Slice) return Boolean; overriding function Is_Part_Of_Inherited (Self : Implicit_Slice) return Boolean; overriding function Is_Part_Of_Instance (Self : Implicit_Slice) return Boolean; end Program.Nodes.Slices;
SietsevanderMolen/fly-thing
Ada
1,812
ads
pragma Ada_2005; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; package sys_ioctl_h is -- Copyright (C) 1991-2014 Free Software Foundation, Inc. -- This file is part of the GNU C Library. -- The GNU C Library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- The GNU C Library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- You should have received a copy of the GNU Lesser General Public -- License along with the GNU C Library; if not, see -- <http://www.gnu.org/licenses/>. -- Get the list of `ioctl' requests and related constants. -- Define some types used by `ioctl' requests. -- On a Unix system, the system <sys/ioctl.h> probably defines some of -- the symbols we define in <sys/ttydefaults.h> (usually with the same -- values). The code to generate <bits/ioctls.h> has omitted these -- symbols to avoid the conflict, but a Unix program expects <sys/ioctl.h> -- to define them, so we must include <sys/ttydefaults.h> here. -- Perform the I/O control operation specified by REQUEST on FD. -- One argument may follow; its presence and type depend on REQUEST. -- Return value depends on REQUEST. Usually -1 indicates error. function ioctl (arg1 : int; arg2 : unsigned_long -- , ... ) return int; -- /usr/include/sys/ioctl.h:41 pragma Import (C, ioctl, "ioctl"); end sys_ioctl_h;
Fabien-Chouteau/Ada_Drivers_Library
Ada
4,554
ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This package defines an abstract data type for a "serial port" providing -- blocking input (Get) and output (Put) procedures. The procedures are -- considered blocking in that they do not return to the caller until the -- entire message is received or sent. -- -- The serial port abstraction is a wrapper around a USART peripheral, -- described by a value of type Peripheral_Descriptor. -- -- Polling is used within the procedures to determine when characters are sent -- and received. with Message_Buffers; use Message_Buffers; package Serial_IO.Blocking is pragma Elaborate_Body; type Serial_Port (Device : not null access Peripheral_Descriptor) is tagged limited private; procedure Initialize (This : out Serial_Port) with Post => (Initialized (This)); function Initialized (This : Serial_Port) return Boolean with Inline; Serial_Port_Uninitialized : exception; procedure Configure (This : in out Serial_Port; Baud_Rate : Baud_Rates; Parity : Parities := No_Parity; Data_Bits : Word_Lengths := Word_Length_8; End_Bits : Stop_Bits := Stopbits_1; Control : Flow_Control := No_Flow_Control) with Pre => (Initialized (This) or else raise Serial_Port_Uninitialized); procedure Put (This : in out Serial_Port; Msg : not null access Message) with Pre => (Initialized (This) or else raise Serial_Port_Uninitialized); -- Sends Msg.Length characters of Msg via USART attached to This. Callers -- wait until all characters are sent. procedure Get (This : in out Serial_Port; Msg : not null access Message) with Pre => (Initialized (This) or else raise Serial_Port_Uninitialized), Post => Msg.Length <= Msg.Physical_Size and Msg.Content_At (Msg.Length) /= Msg.Terminator; -- Callers wait until all characters are received. private type Serial_Port (Device : access Peripheral_Descriptor) is tagged limited record Initialized : Boolean := False; end record; procedure Await_Send_Ready (This : USART) with Inline; procedure Await_Data_Available (This : USART) with Inline; end Serial_IO.Blocking;
sungyeon/drake
Ada
633
adb
package body System.Tasking.Async_Delays is function Enqueue_Duration ( T : Duration; D : not null access Delay_Block) return Boolean is begin raise Program_Error; -- unimplemented return Enqueue_Duration (T, D); end Enqueue_Duration; procedure Cancel_Async_Delay (D : not null access Delay_Block) is begin raise Program_Error; -- unimplemented end Cancel_Async_Delay; function Timed_Out (D : not null access Delay_Block) return Boolean is begin raise Program_Error; -- unimplemented return Timed_Out (D); end Timed_Out; end System.Tasking.Async_Delays;
KLOC-Karsten/adaoled
Ada
2,255
adb
with Ada.Text_IO; use Ada.Text_IO; with OLED_SH1106; use OLED_SH1106; with Interfaces.C; use Interfaces.C; with Bitmap_Graphics; use Bitmap_Graphics; procedure AdaOLED is Center : Point := (64, 32); P : Point := (10, 10); Q : Point := (100, 40); begin Put_Line ("OLED Display Driver Test"); if Start_Driver then Init_Display; -- Display initialisation Clear; Put(P, "This is a test", 20); Show; delay 1.0; Clear; Put(P, "This is a TEST", 20, Black, White); Show; delay 2.0; for Size in 1..6 loop Clear; Dot(Center, Size*2); Show; delay 0.1; end loop; delay 1.0; for X in 0..20 loop Clear; Q.X := 20+4*X; Q.Y := 10+X; Line(P, Q); Show; delay 0.1; end loop; delay 1.0; for X in 0..20 loop for Y in 0..5 loop delay 0.05; Clear; Q.X := 20+4*X; Q.Y := 10+X; Rectangle(P, Q, 2); Show; end loop; end loop; for X in 0..40 loop delay 0.1; Clear; Q.X := P.X + 2* X; Q.Y := 60; Rectangle(P, (P.X+80, Q.Y) ); Fill_Rectangle(P, Q); Show; end loop; delay 2.0; for R in 0..20 loop delay 0.4; Clear; Circle(Center, R, 3); Show; end loop; for R in 0..20 loop delay 0.4; Clear; Fill_Circle(Center, R); Show; end loop; delay 1.0; Clear; Put(Center, 'E', 8); Show; delay 1.0; Clear; Put(Center, 'F', 12); Show; delay 1.0; Clear; Put(Center, 'G', 16); Show; delay 1.0; Clear; Put(Center, 'H', 20, Black, White); Show; delay 1.0; Clear; Put(Center, 'K', 24, Black, White); Show; delay 1.0; Clear; Put(Center, 127, 16, Black, White); Show; delay 1.0; Clear; Put(Center, 1234, 20); Show; delay 0.8; Clear; Bitmap(Center, Signal); Show; delay 0.8; Clear; Bitmap(Center, Message); Show; delay 10.0; else Put_Line ("Driver initialisation failed!"); end if; Stop_Driver; end AdaOLED;
sungyeon/drake
Ada
36
ads
../machine-apple-darwin/s-natpro.ads
reznikmm/matreshka
Ada
4,680
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Style.Font_Charset_Asian_Attributes is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Style_Font_Charset_Asian_Attribute_Node is begin return Self : Style_Font_Charset_Asian_Attribute_Node do Matreshka.ODF_Style.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Style_Prefix); end return; end Create; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Style_Font_Charset_Asian_Attribute_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Font_Charset_Asian_Attribute; end Get_Local_Name; begin Matreshka.DOM_Documents.Register_Attribute (Matreshka.ODF_String_Constants.Style_URI, Matreshka.ODF_String_Constants.Font_Charset_Asian_Attribute, Style_Font_Charset_Asian_Attribute_Node'Tag); end Matreshka.ODF_Style.Font_Charset_Asian_Attributes;
zhmu/ananas
Ada
31,136
ads
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ A T T R -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2022, 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 along -- -- with this program; see file COPYING3. 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. -- -- -- ------------------------------------------------------------------------------ -- Attribute handling is isolated in a separate package to ease the addition -- of implementation defined attributes. Logically this processing belongs -- in chapter 4. See Sem_Ch4 for a description of the relation of the -- Analyze and Resolve routines for expression components. -- This spec also documents all GNAT implementation defined pragmas with Exp_Tss; use Exp_Tss; with Namet; use Namet; with Snames; use Snames; with Types; use Types; package Sem_Attr is ----------------------------------------- -- Implementation Dependent Attributes -- ----------------------------------------- -- This section describes the implementation dependent attributes provided -- in GNAT, as well as constructing an array of flags indicating which -- attributes these are. Attribute_Impl_Def : constant Attribute_Class_Array := Attribute_Class_Array'( ------------------ -- Abort_Signal -- ------------------ Attribute_Abort_Signal => True, -- Standard'Abort_Signal (Standard is the only allowed prefix) provides -- the entity for the special exception used to signal task abort or -- asynchronous transfer of control. Normally this attribute should only -- be used in the tasking runtime (it is highly peculiar, and completely -- outside the normal semantics of Ada, for a user program to intercept -- the abort exception). ------------------ -- Address_Size -- ------------------ Attribute_Address_Size => True, -- Standard'Address_Size (Standard is the only allowed prefix) is -- a static constant giving the number of bits in an Address. It -- is used primarily for constructing the definition of Memory_Size -- in package Standard, but may be freely used in user programs. -- This is a static attribute. --------------- -- Asm_Input -- --------------- Attribute_Asm_Input => True, -- Used only in conjunction with the Asm subprograms in package -- Machine_Code to construct machine instructions. See documentation -- in package Machine_Code in file s-maccod.ads. ---------------- -- Asm_Output -- ---------------- Attribute_Asm_Output => True, -- Used only in conjunction with the Asm subprograms in package -- Machine_Code to construct machine instructions. See documentation -- in package Machine_Code in file s-maccod.ads. --------- -- Bit -- --------- Attribute_Bit => True, -- Obj'Bit, where Obj is any object, yields the bit offset within the -- storage unit (byte) that contains the first bit of storage allocated -- for the object. The attribute value is of type Universal_Integer, -- and is always a non-negative number not exceeding the value of -- System.Storage_Unit. -- -- For an object that is a variable or a constant allocated in a -- register, the value is zero. (The use of this attribute does not -- force the allocation of a variable to memory). -- -- For an object that is a formal parameter, this attribute applies to -- either the matching actual parameter or to a copy of the matching -- actual parameter. -- -- For an access object the value is zero. Note that Obj.all'Bit is -- subject to an Access_Check for the designated object. Similarly -- for a record component X.C'Bit is subject to a discriminant check -- and X(I).Bit and X(I1..I2)'Bit are subject to index checks. -- -- This attribute is designed to be compatible with the DEC Ada -- definition and implementation of the Bit attribute. ------------------ -- Code_Address -- ------------------ Attribute_Code_Address => True, -- The reference subp'Code_Address, where subp is a subprogram entity, -- gives the address of the first generated instruction for the sub- -- program. This is often, but not always the same as the 'Address -- value, which is the address to be used in a call. The differences -- occur in the case of a nested procedure (where Address yields the -- address of the trampoline code used to load the static link), and on -- some systems which use procedure descriptors (in which case Address -- yields the address of the descriptor). ----------------------- -- Default_Bit_Order -- ----------------------- Attribute_Default_Bit_Order => True, -- Standard'Default_Bit_Order (Standard is the only permissible prefix) -- provides the value System.Default_Bit_Order as a Pos value (0 for -- High_Order_First, 1 for Low_Order_First). This is used to construct -- the definition of Default_Bit_Order in package System. This is a -- static attribute. ---------------------------------- -- Default_Scalar_Storage_Order -- ---------------------------------- Attribute_Default_Scalar_Storage_Order => True, -- Standard'Default_Scalar_Storage_Order (Standard is the -- only permissible prefix) provides the current value of the -- default scalar storage order (as specified using pragma -- Default_Scalar_Storage_Order, or equal to Default_Bit_Order if -- unspecified) as a System.Bit_Order value. This is a static attribute. ----------- -- Deref -- ----------- Attribute_Deref => True, -- typ'Deref (expr) is valid only if expr is of type System'Address. -- The result is an object of type typ that is obtained by treating the -- address as an access-to-typ value that points to the result. It is -- basically equivalent to (atyp!expr).all where atyp is an access type -- for the type. --------------- -- Elab_Body -- --------------- Attribute_Elab_Body => True, -- This attribute can only be applied to a program unit name. It -- returns the entity for the corresponding elaboration procedure for -- elaborating the body of the referenced unit. This is used in the main -- generated elaboration procedure by the binder, and is not normally -- used in any other context, but there may be specialized situations in -- which it is useful to be able to call this elaboration procedure from -- Ada code, e.g. if it is necessary to do selective reelaboration to -- fix some error. -------------------- -- Elab_Subp_Body -- -------------------- Attribute_Elab_Subp_Body => True, -- This attribute can only be applied to a library level subprogram -- name and is only relevant in CodePeer mode. It returns the entity -- for the corresponding elaboration procedure for elaborating the body -- of the referenced subprogram unit. This is used in the main generated -- elaboration procedure by the binder in CodePeer mode only. --------------- -- Elab_Spec -- --------------- Attribute_Elab_Spec => True, -- This attribute can only be applied to a program unit name. It -- returns the entity for the corresponding elaboration procedure for -- elaborating the spec of the referenced unit. This is used in the main -- generated elaboration procedure by the binder, and is not normally -- used in any other context, but there may be specialized situations in -- which it is useful to be able to call this elaboration procedure from -- Ada code, e.g. if it is necessary to do selective reelaboration to -- fix some error. ---------------- -- Elaborated -- ---------------- Attribute_Elaborated => True, -- Lunit'Elaborated, where Lunit is a library unit, yields a boolean -- value indicating whether or not the body of the designated library -- unit has been elaborated yet. ----------------------- -- Finalization_Size -- ----------------------- Attribute_Finalization_Size => True, -- For every object or non-class-wide-type, Finalization_Size returns -- the size of the hidden header used for finalization purposes as if -- the object or type was allocated on the heap. The size of the header -- does take into account any extra padding due to alignment issues. ----------------- -- Fixed_Value -- ----------------- Attribute_Fixed_Value => True, -- For every fixed-point type S, S'Fixed_Value denotes a function -- with the following specification: -- -- function S'Fixed_Value (Arg : universal_integer) return S; -- -- The value returned is the fixed-point value V such that -- -- V = Arg * S'Small -- -- The effect is thus equivalent to first converting the argument to -- the integer type used to represent S, and then doing an unchecked -- conversion to the fixed-point type. This attribute is primarily -- intended for use in implementation of the input-output functions -- for fixed-point values. ----------------------- -- Has_Discriminants -- ----------------------- Attribute_Has_Discriminants => True, -- Gtyp'Has_Discriminants, where Gtyp is a generic formal type, yields -- a Boolean value indicating whether or not the actual instantiation -- type has discriminants. --------- -- Img -- --------- Attribute_Img => True, -- The 'Img function is defined for any prefix, P, that denotes an -- object of scalar type T. P'Img is equivalent to T'Image (P). This -- is convenient for debugging. For example: -- -- Put_Line ("X = " & X'Img); -- -- has the same meaning as the more verbose: -- -- Put_Line ("X = " & Temperature_Type'Image (X)); -- -- where Temperature_Type is the subtype of the object X. ------------------- -- Integer_Value -- ------------------- Attribute_Integer_Value => True, -- For every integer type S, S'Integer_Value denotes a function -- with the following specification: -- -- function S'Integer_Value (Arg : universal_fixed) return S; -- -- The value returned is the integer value V, such that -- -- Arg = V * fixed-type'Small -- -- The effect is thus equivalent to first doing an unchecked convert -- from the fixed-point type to its corresponding implementation type, -- and then converting the result to the target integer type. This -- attribute is primarily intended for use in implementation of the -- standard input-output functions for fixed-point values. Attribute_Invalid_Value => True, -- For every scalar type, S'Invalid_Value designates an undefined value -- of the type. If possible this value is an invalid value, and in fact -- is identical to the value that would be set if Initialize_Scalars -- mode were in effect (including the behavior of its value on -- environment variables or binder switches). The intended use is to -- set a value where initialization is required (e.g. as a result of the -- coding standards in use), but logically no initialization is needed, -- and the value should never be accessed. Attribute_Loop_Entry => True, -- For every object of a non-limited type, S'Loop_Entry [(Loop_Name)] -- denotes the constant value of prefix S at the point of entry into the -- related loop. The type of the attribute is the type of the prefix. ------------------ -- Machine_Size -- ------------------ Attribute_Machine_Size => True, -- This attribute is identical to the Object_Size attribute. It is -- provided for compatibility with the DEC attribute of this name. ---------------------- -- Max_Integer_Size -- ---------------------- Attribute_Max_Integer_Size => True, -- Standard'Max_Integer_Size (Standard is the only permissible prefix) -- provides values System.Min_Int and System.Max_Int, and is intended -- primarily for constructing these definitions in package System. This -- is a static attribute. ----------------------- -- Maximum_Alignment -- ----------------------- Attribute_Maximum_Alignment => True, -- Standard'Maximum_Alignment (Standard is the only permissible prefix) -- provides the maximum useful alignment value for the target. This is a -- static value that can be used to specify the alignment for an object, -- guaranteeing that it is properly aligned in all cases. The time this -- is useful is when an external object is imported and its alignment -- requirements are unknown. This is a static attribute. -------------------- -- Mechanism_Code -- -------------------- Attribute_Mechanism_Code => True, -- function'Mechanism_Code yields an integer code for the mechanism -- used for the result of function, and subprogram'Mechanism_Code (n) -- yields the mechanism used for formal parameter number n (a static -- integer value, 1 = first parameter). The code returned is: -- -- 1 = by copy (value) -- 2 = by reference -- 3 = by descriptor (default descriptor type) -- 4 = by descriptor (UBS unaligned bit string) -- 5 = by descriptor (UBSB aligned bit string with arbitrary bounds) -- 6 = by descriptor (UBA unaligned bit array) -- 7 = by descriptor (S string, also scalar access type parameter) -- 8 = by descriptor (SB string with arbitrary bounds) -- 9 = by descriptor (A contiguous array) -- 10 = by descriptor (NCA non-contiguous array) -------------------- -- Null_Parameter -- -------------------- Attribute_Null_Parameter => True, -- A reference T'Null_Parameter denotes an (imaginary) object of type -- or subtype T allocated at (machine) address zero. The attribute is -- allowed only as the default expression of a formal parameter, or -- as an actual expression of a subprogram call. In either case, the -- subprogram must be imported. -- -- The identity of the object is represented by the address zero in -- the argument list, independent of the passing mechanism (explicit -- or default). -- -- The reason that this capability is needed is that for a record or -- other composite object passed by reference, there is no other way -- of specifying that a zero address should be passed. ----------------- -- Object_Size -- ----------------- Attribute_Object_Size => True, -- Type'Object_Size is the same as Type'Size for all types except -- fixed-point types and discrete types. For fixed-point types and -- discrete types, this attribute gives the size used for default -- allocation of objects and components of the size. See section in -- Einfo ("Handling of Type'Size values") for further details. ------------------------- -- Passed_By_Reference -- ------------------------- Attribute_Passed_By_Reference => True, -- T'Passed_By_Reference for any subtype T returns a boolean value that -- is true if the type is normally passed by reference and false if the -- type is normally passed by copy in calls. For scalar types, the -- result is always False and is static. For non-scalar types, the -- result is non-static (since it is computed by Gigi). ------------------ -- Range_Length -- ------------------ Attribute_Range_Length => True, -- T'Range_Length for any discrete type T yields the number of values -- represented by the subtype (zero for a null range). The result is -- static for static subtypes. Note that Range_Length applied to the -- index subtype of a one dimensional array always gives the same result -- as Range applied to the array itself. The result is of type universal -- integer. ------------ -- Reduce -- ------------ Attribute_Reduce => True, -- See AI12-0262-1 --------- -- Ref -- --------- Attribute_Ref => True, -- System.Address'Ref (Address is the only permissible prefix) is -- equivalent to System'To_Address, provided for compatibility with -- other compilers. ------------------ -- Storage_Unit -- ------------------ Attribute_Storage_Unit => True, -- Standard'Storage_Unit (Standard is the only permissible prefix) -- provides the value System.Storage_Unit, and is intended primarily -- for constructing this definition in package System (see note above -- in Default_Bit_Order description). The is a static attribute. --------------- -- Stub_Type -- --------------- Attribute_Stub_Type => True, -- The GNAT implementation of remote access-to-classwide types is -- organised as described in AARM E.4(20.t): a value of an RACW type -- (designating a remote object) is represented as a normal access -- value, pointing to a "stub" object which in turn contains the -- necessary information to contact the designated remote object. A -- call on any dispatching operation of such a stub object does the -- remote call, if necessary, using the information in the stub object -- to locate the target partition, etc. -- -- For a prefix T that denotes a remote access-to-classwide type, -- T'Stub_Type denotes the type of the corresponding stub objects. -- -- By construction, the layout of T'Stub_Type is identical to that of -- System.Partition_Interface.RACW_Stub_Type (see implementation notes -- in body of Exp_Dist). ----------------- -- Target_Name -- ----------------- Attribute_Target_Name => True, -- Standard'Target_Name yields the string identifying the target for the -- compilation, taken from Sdefault.Target_Name. ---------------- -- To_Address -- ---------------- Attribute_To_Address => True, -- System'To_Address (System is the only permissible prefix) is a -- function that takes any integer value, and converts it into an -- address value. The semantics is to first convert the integer value to -- type Integer_Address according to normal conversion rules, and then -- to convert this to an address using the same semantics as the -- System.Storage_Elements.To_Address function. The important difference -- is that this is a static attribute so it can be used in -- initializations in preelaborate packages. ---------------- -- Type_Class -- ---------------- Attribute_Type_Class => True, -- T'Type_Class for any type or subtype T yields the value of the type -- class for the full type of T. If T is a generic formal type, then the -- value is the value for the corresponding actual subtype. The value of -- this attribute is of type System.Aux_DEC.Type_Class, which has the -- following definition: -- -- type Type_Class is -- (Type_Class_Enumeration, -- Type_Class_Integer, -- Type_Class_Fixed_Point, -- Type_Class_Floating_Point, -- Type_Class_Array, -- Type_Class_Record, -- Type_Class_Access, -- Type_Class_Task, -- Type_Class_Address); -- -- Protected types yield the value Type_Class_Task, which thus applies -- to all concurrent types. This attribute is designed to be compatible -- with the DEC Ada attribute of the same name. -- -- Note: if pragma Extend_System is used to merge the definitions of -- Aux_DEC into System, then the type Type_Class can be referenced -- as an entity within System, as can its enumeration literals. ------------------------------ -- Universal_Literal_String -- ------------------------------ Attribute_Universal_Literal_String => True, -- The prefix of 'Universal_Literal_String must be a named number. -- The static result is the string consisting of the characters of -- the number as defined in the original source. This allows the -- user program to access the actual text of named numbers without -- intermediate conversions and without the need to enclose the -- strings in quotes (which would preclude their use as numbers). ------------------------- -- Unrestricted_Access -- ------------------------- Attribute_Unrestricted_Access => True, -- The Unrestricted_Access attribute is similar to Access except that -- all accessibility and aliased view checks are omitted. This is very -- much a user-beware attribute. Basically its status is very similar -- to Address, for which it is a desirable replacement where the value -- desired is an access type. In other words, its effect is identical -- to first taking 'Address and then doing an unchecked conversion to -- a desired access type. Note that in GNAT, but not necessarily in -- other implementations, the use of static chains for inner level -- subprograms means that Unrestricted_Access applied to a subprogram -- yields a value that can be called as long as the subprogram is in -- scope (normal Ada 95 accessibility rules restrict this usage). --------------- -- VADS_Size -- --------------- Attribute_VADS_Size => True, -- Typ'VADS_Size yields the Size value typically yielded by some Ada 83 -- compilers. The differences between VADS_Size and Size is that for -- scalar types for which no Size has been specified, VADS_Size yields -- the Object_Size rather than the Value_Size. For example, while -- Natural'Size is typically 31, the value of Natural'VADS_Size is 32. -- For all other types, Size and VADS_Size yield the same value. ------------------- -- Valid_Scalars -- ------------------- Attribute_Valid_Scalars => True, -- Obj'Valid_Scalars can be applied to any object. The result depends -- on the type of the object: -- -- For a scalar type, the result is the same as obj'Valid -- -- For an array object, the result is True if the result of applying -- Valid_Scalars to every component is True. For an empty array the -- result is True. -- -- For a record object, the result is True if the result of applying -- Valid_Scalars to every component is True. For class-wide types, -- only the components of the base type are checked. For variant -- records, only the components actually present are checked. The -- discriminants, if any, are also checked. If there are no components -- or discriminants, the result is True. -- -- For any other type that has discriminants, the result is True if -- the result of applying Valid_Scalars to each discriminant is True. -- -- For all other types, the result is always True -- -- A warning is given for a trivially True result, when the attribute -- is applied to an object that is not of scalar, array, or record -- type, or in the composite case if no scalar subcomponents exist. For -- a variant record, the warning is given only if none of the variants -- have scalar subcomponents. In addition, the warning is suppressed -- for private types, or generic formal types in an instance. ---------------- -- Value_Size -- ---------------- Attribute_Value_Size => True, -- Type'Value_Size is the number of bits required to represent value of -- the given subtype. It is the same as Type'Size, but, unlike Size, may -- be set for non-first subtypes. See section in Einfo ("Handling of -- type'Size values") for further details. --------------- -- Word_Size -- --------------- Attribute_Word_Size => True, -- Standard'Word_Size (Standard is the only permissible prefix) -- provides the value System.Word_Size, and is intended primarily -- for constructing this definition in package System (see note above -- in Default_Bit_Order description). This is a static attribute. others => False); -- The following table lists all attributes that yield a result of a -- universal type. Universal_Type_Attribute : constant array (Attribute_Id) of Boolean := (Attribute_Aft => True, Attribute_Alignment => True, Attribute_Component_Size => True, Attribute_Count => True, Attribute_Delta => True, Attribute_Digits => True, Attribute_Exponent => True, Attribute_First_Bit => True, Attribute_Fore => True, Attribute_Last_Bit => True, Attribute_Length => True, Attribute_Machine_Emax => True, Attribute_Machine_Emin => True, Attribute_Machine_Mantissa => True, Attribute_Machine_Radix => True, Attribute_Max_Alignment_For_Allocation => True, Attribute_Max_Size_In_Storage_Elements => True, Attribute_Model_Emin => True, Attribute_Model_Epsilon => True, Attribute_Model_Mantissa => True, Attribute_Model_Small => True, Attribute_Modulus => True, Attribute_Pos => True, Attribute_Position => True, Attribute_Safe_First => True, Attribute_Safe_Last => True, Attribute_Scale => True, Attribute_Size => True, Attribute_Small => True, Attribute_Wide_Wide_Width => True, Attribute_Wide_Width => True, Attribute_Width => True, others => False); ----------------- -- Subprograms -- ----------------- procedure Analyze_Attribute (N : Node_Id); -- Performs bottom up semantic analysis of an attribute. Note that the -- parser has already checked that type returning attributes appear only -- in appropriate contexts (i.e. in subtype marks, or as prefixes for -- other attributes). function Name_Implies_Lvalue_Prefix (Nam : Name_Id) return Boolean; -- Determine whether the name of an attribute reference categorizes its -- prefix as an lvalue. The following attributes fall under this bracket -- by directly or indirectly modifying their prefixes. -- Access -- Address -- Input -- Read -- Unchecked_Access -- Unrestricted_Access procedure Resolve_Attribute (N : Node_Id; Typ : Entity_Id); -- Performs type resolution of attribute. If the attribute yields a -- universal value, mark its type as that of the context. On the other -- hand, if the context itself is universal (as in T'Val (T'Pos (X)), mark -- the type as being the largest type of that class that can be used at -- run-time. This is correct since either the value gets folded (in which -- case it doesn't matter what type of the class we give if, since the -- folding uses universal arithmetic anyway) or it doesn't get folded (in -- which case it is going to be dealt with at runtime, and the largest type -- is right). function Stream_Attribute_Available (Typ : Entity_Id; Nam : TSS_Name_Type; Partial_View : Entity_Id := Empty) return Boolean; -- For a limited type Typ, return True if and only if the given attribute -- is available. For Ada 2005, availability is defined by 13.13.2(36/1). -- For Ada 95, an attribute is considered to be available if it has been -- specified using an attribute definition clause for the type, or for its -- full view, or for an ancestor of either. Parameter Partial_View is used -- only internally, when checking for an attribute definition clause that -- is not visible (Ada 95 only). end Sem_Attr;
DrenfongWong/tkm-rpc
Ada
11,494
adb
package body Tkmrpc.Contexts.ae is pragma Warnings (Off, "* already use-visible through previous use type clause"); use type Types.ae_id_type; use type Types.iag_id_type; use type Types.dhag_id_type; use type Types.ca_id_type; use type Types.lc_id_type; use type Types.ri_id_type; use type Types.authag_id_type; use type Types.init_type; use type Types.nonce_type; use type Types.nonce_type; use type Types.key_type; use type Types.key_type; use type Types.rel_time_type; use type Types.abs_time_type; use type Types.abs_time_type; pragma Warnings (On, "* already use-visible through previous use type clause"); type ae_FSM_Type is record State : ae_State_Type; iag_id : Types.iag_id_type; dhag_id : Types.dhag_id_type; ca_id : Types.ca_id_type; lc_id : Types.lc_id_type; ri_id : Types.ri_id_type; authag_id : Types.authag_id_type; initiator : Types.init_type; nonce_loc : Types.nonce_type; nonce_rem : Types.nonce_type; sk_ike_auth_loc : Types.key_type; sk_ike_auth_rem : Types.key_type; creation_time : Types.rel_time_type; cc_not_before : Types.abs_time_type; cc_not_after : Types.abs_time_type; end record; -- Authentication Endpoint Context Null_ae_FSM : constant ae_FSM_Type := ae_FSM_Type' (State => clean, iag_id => Types.iag_id_type'First, dhag_id => Types.dhag_id_type'First, ca_id => Types.ca_id_type'First, lc_id => Types.lc_id_type'First, ri_id => Types.ri_id_type'First, authag_id => Types.authag_id_type'First, initiator => Types.init_type'First, nonce_loc => Types.Null_nonce_type, nonce_rem => Types.Null_nonce_type, sk_ike_auth_loc => Types.Null_key_type, sk_ike_auth_rem => Types.Null_key_type, creation_time => Types.rel_time_type'First, cc_not_before => Types.abs_time_type'First, cc_not_after => Types.abs_time_type'First); type Context_Array_Type is array (Types.ae_id_type) of ae_FSM_Type; Context_Array : Context_Array_Type := Context_Array_Type' (others => (Null_ae_FSM)); ------------------------------------------------------------------------- function Get_State (Id : Types.ae_id_type) return ae_State_Type is begin return Context_Array (Id).State; end Get_State; ------------------------------------------------------------------------- function Has_authag_id (Id : Types.ae_id_type; authag_id : Types.authag_id_type) return Boolean is (Context_Array (Id).authag_id = authag_id); ------------------------------------------------------------------------- function Has_ca_id (Id : Types.ae_id_type; ca_id : Types.ca_id_type) return Boolean is (Context_Array (Id).ca_id = ca_id); ------------------------------------------------------------------------- function Has_cc_not_after (Id : Types.ae_id_type; cc_not_after : Types.abs_time_type) return Boolean is (Context_Array (Id).cc_not_after = cc_not_after); ------------------------------------------------------------------------- function Has_cc_not_before (Id : Types.ae_id_type; cc_not_before : Types.abs_time_type) return Boolean is (Context_Array (Id).cc_not_before = cc_not_before); ------------------------------------------------------------------------- function Has_creation_time (Id : Types.ae_id_type; creation_time : Types.rel_time_type) return Boolean is (Context_Array (Id).creation_time = creation_time); ------------------------------------------------------------------------- function Has_dhag_id (Id : Types.ae_id_type; dhag_id : Types.dhag_id_type) return Boolean is (Context_Array (Id).dhag_id = dhag_id); ------------------------------------------------------------------------- function Has_iag_id (Id : Types.ae_id_type; iag_id : Types.iag_id_type) return Boolean is (Context_Array (Id).iag_id = iag_id); ------------------------------------------------------------------------- function Has_initiator (Id : Types.ae_id_type; initiator : Types.init_type) return Boolean is (Context_Array (Id).initiator = initiator); ------------------------------------------------------------------------- function Has_lc_id (Id : Types.ae_id_type; lc_id : Types.lc_id_type) return Boolean is (Context_Array (Id).lc_id = lc_id); ------------------------------------------------------------------------- function Has_nonce_loc (Id : Types.ae_id_type; nonce_loc : Types.nonce_type) return Boolean is (Context_Array (Id).nonce_loc = nonce_loc); ------------------------------------------------------------------------- function Has_nonce_rem (Id : Types.ae_id_type; nonce_rem : Types.nonce_type) return Boolean is (Context_Array (Id).nonce_rem = nonce_rem); ------------------------------------------------------------------------- function Has_ri_id (Id : Types.ae_id_type; ri_id : Types.ri_id_type) return Boolean is (Context_Array (Id).ri_id = ri_id); ------------------------------------------------------------------------- function Has_sk_ike_auth_loc (Id : Types.ae_id_type; sk_ike_auth_loc : Types.key_type) return Boolean is (Context_Array (Id).sk_ike_auth_loc = sk_ike_auth_loc); ------------------------------------------------------------------------- function Has_sk_ike_auth_rem (Id : Types.ae_id_type; sk_ike_auth_rem : Types.key_type) return Boolean is (Context_Array (Id).sk_ike_auth_rem = sk_ike_auth_rem); ------------------------------------------------------------------------- function Has_State (Id : Types.ae_id_type; State : ae_State_Type) return Boolean is (Context_Array (Id).State = State); ------------------------------------------------------------------------- pragma Warnings (Off, "condition can only be False if invalid values present"); function Is_Valid (Id : Types.ae_id_type) return Boolean is (Context_Array'First <= Id and Id <= Context_Array'Last); pragma Warnings (On, "condition can only be False if invalid values present"); ------------------------------------------------------------------------- procedure activate (Id : Types.ae_id_type) is begin Context_Array (Id).State := active; end activate; ------------------------------------------------------------------------- procedure authenticate (Id : Types.ae_id_type; ca_context : Types.ca_id_type; authag_id : Types.authag_id_type; ri_id : Types.ri_id_type; not_before : Types.abs_time_type; not_after : Types.abs_time_type) is begin Context_Array (Id).ca_id := ca_context; Context_Array (Id).authag_id := authag_id; Context_Array (Id).ri_id := ri_id; Context_Array (Id).cc_not_before := not_before; Context_Array (Id).cc_not_after := not_after; Context_Array (Id).State := authenticated; end authenticate; ------------------------------------------------------------------------- procedure create (Id : Types.ae_id_type; iag_id : Types.iag_id_type; dhag_id : Types.dhag_id_type; creation_time : Types.rel_time_type; initiator : Types.init_type; sk_ike_auth_loc : Types.key_type; sk_ike_auth_rem : Types.key_type; nonce_loc : Types.nonce_type; nonce_rem : Types.nonce_type) is begin Context_Array (Id).iag_id := iag_id; Context_Array (Id).dhag_id := dhag_id; Context_Array (Id).creation_time := creation_time; Context_Array (Id).initiator := initiator; Context_Array (Id).sk_ike_auth_loc := sk_ike_auth_loc; Context_Array (Id).sk_ike_auth_rem := sk_ike_auth_rem; Context_Array (Id).nonce_loc := nonce_loc; Context_Array (Id).nonce_rem := nonce_rem; Context_Array (Id).State := unauth; end create; ------------------------------------------------------------------------- function get_lc_id (Id : Types.ae_id_type) return Types.lc_id_type is begin return Context_Array (Id).lc_id; end get_lc_id; ------------------------------------------------------------------------- function get_nonce_loc (Id : Types.ae_id_type) return Types.nonce_type is begin return Context_Array (Id).nonce_loc; end get_nonce_loc; ------------------------------------------------------------------------- function get_nonce_rem (Id : Types.ae_id_type) return Types.nonce_type is begin return Context_Array (Id).nonce_rem; end get_nonce_rem; ------------------------------------------------------------------------- function get_ri_id (Id : Types.ae_id_type) return Types.ri_id_type is begin return Context_Array (Id).ri_id; end get_ri_id; ------------------------------------------------------------------------- function get_sk_ike_auth_loc (Id : Types.ae_id_type) return Types.key_type is begin return Context_Array (Id).sk_ike_auth_loc; end get_sk_ike_auth_loc; ------------------------------------------------------------------------- function get_sk_ike_auth_rem (Id : Types.ae_id_type) return Types.key_type is begin return Context_Array (Id).sk_ike_auth_rem; end get_sk_ike_auth_rem; ------------------------------------------------------------------------- procedure invalidate (Id : Types.ae_id_type) is begin Context_Array (Id).State := invalid; end invalidate; ------------------------------------------------------------------------- function is_initiator (Id : Types.ae_id_type) return Types.init_type is begin return Context_Array (Id).initiator; end is_initiator; ------------------------------------------------------------------------- procedure reset (Id : Types.ae_id_type) is begin Context_Array (Id).iag_id := Types.iag_id_type'First; Context_Array (Id).dhag_id := Types.dhag_id_type'First; Context_Array (Id).ca_id := Types.ca_id_type'First; Context_Array (Id).lc_id := Types.lc_id_type'First; Context_Array (Id).ri_id := Types.ri_id_type'First; Context_Array (Id).authag_id := Types.authag_id_type'First; Context_Array (Id).initiator := Types.init_type'First; Context_Array (Id).nonce_loc := Types.Null_nonce_type; Context_Array (Id).nonce_rem := Types.Null_nonce_type; Context_Array (Id).sk_ike_auth_loc := Types.Null_key_type; Context_Array (Id).sk_ike_auth_rem := Types.Null_key_type; Context_Array (Id).creation_time := Types.rel_time_type'First; Context_Array (Id).cc_not_before := Types.abs_time_type'First; Context_Array (Id).cc_not_after := Types.abs_time_type'First; Context_Array (Id).State := clean; end reset; ------------------------------------------------------------------------- procedure sign (Id : Types.ae_id_type; lc_id : Types.lc_id_type) is begin Context_Array (Id).lc_id := lc_id; Context_Array (Id).State := loc_auth; end sign; end Tkmrpc.Contexts.ae;
burratoo/Acton
Ada
3,477
ads
------------------------------------------------------------------------------------------ -- -- -- OAK CORE SUPPORT PACKAGE -- -- FREESCALE e200 -- -- -- -- ISA.POWER.E200.Z6.HID -- -- -- -- Copyright (C) 2010-2021, Patrick Bernardi -- -- -- ------------------------------------------------------------------------------------------ package ISA.Power.e200.z6.HID with Pure is type Branch_Prediction_Type is ( Enable, Disable_Backwards, Disable_Forward, Disable); type Hardware_Reset_Type is (Occurred, Not_Occurred); type Time_Base_Source is (Processor_Clock, P_Tbclk); type Hardware_Implementation_Dependent_Register_0_Type is record Machine_Check_Signal : Enable_Type; Branch_Prediction_Control : Branch_Prediction_Type; Doze_Mode : Enable_Type; Nap_Mode : Enable_Type; Sleep_Mode : Enable_Type; Interrupt_Inputs_Clear_Reservation : Decision_Type; Hardware_Reset : Hardware_Reset_Type; Time_Base : Enable_Type; Select_Time_Base_Clock : Time_Base_Source; Debug_Interrupt_Clears_MSR_EE : Decision_Type; Debug_Interrupt_Clears_MSR_CE : Decision_Type; Critical_Interrupt_Clears_MSR_DE : Decision_Type; Machine_Check_Interrupt_Clears_MSR_DE : Decision_Type; Debug_APU : Enable_Type; end record with Size => Standard'Word_Size; for Branch_Prediction_Type use (Enable => 2#00#, Disable_Backwards => 2#01#, Disable_Forward => 2#10#, Disable => 2#11#); for Hardware_Reset_Type use (Occurred => 0, Not_Occurred => 1); for Time_Base_Source use (Processor_Clock => 0, P_Tbclk => 1); for Hardware_Implementation_Dependent_Register_0_Type use record Machine_Check_Signal at 0 range 0 .. 0; Branch_Prediction_Control at 0 range 6 .. 7; Doze_Mode at 0 range 8 .. 8; Nap_Mode at 0 range 9 .. 9; Sleep_Mode at 0 range 10 .. 10; Interrupt_Inputs_Clear_Reservation at 0 range 14 .. 14; Hardware_Reset at 0 range 15 .. 15; Time_Base at 0 range 17 .. 17; Select_Time_Base_Clock at 0 range 18 .. 18; Debug_Interrupt_Clears_MSR_EE at 0 range 19 .. 19; Debug_Interrupt_Clears_MSR_CE at 0 range 20 .. 20; Critical_Interrupt_Clears_MSR_DE at 0 range 21 .. 21; Machine_Check_Interrupt_Clears_MSR_DE at 0 range 22 .. 22; Debug_APU at 0 range 23 .. 23; end record; end ISA.Power.e200.z6.HID;
afrl-rq/OpenUxAS
Ada
10,213
adb
-- see C:\AFRL_mentorship\OpenUxAS\src\Utilities\UxAS_ConfigurationManager.cpp with String_Utils; use String_Utils; with Ada.Strings.Fixed; with Input_Sources.Strings; with Input_Sources.File; with DOM.Readers; with DOM.Core.Documents; with DOM.Core.Nodes; with Sax.Encodings; with DOM.Core.Elements; with UxAS.Common.String_Constant; package body UxAS.Common.Configuration_Manager is -------------- -- Instance -- -------------- function Instance return not null Manager_Reference is begin if The_Instance = null then The_Instance := new Manager; end if; return The_Instance; end Instance; ------------------- -- Get_Entity_Id -- ------------------- function Get_Entity_Id (This : not null access Manager) return UInt32 is (This.Entity_Id); --------------------- -- Get_Entity_Type -- --------------------- function Get_Entity_Type (This : not null access Manager) return String is (Value (This.Entity_Type)); -------------------------- -- Get_Enabled_Services -- -------------------------- procedure Get_Enabled_Services (This : not null access Manager; Services : out DOM.Core.Element; Result : out Boolean) is begin if This.Base_XML_Doc_Loaded and not This.Enabled_Services_XML_Doc_Built then Reset (This.Enabled_Services_XML_Doc); This.Populate_Enabled_Components (This.Enabled_Services_XML_Doc, Node_Name => String_Constant.Service); This.Enabled_Services_XML_Doc_Built := True; end if; Services := DOM.Core.Documents.Get_Element (This.Enabled_Services_XML_Doc); Result := True; exception when others => Result := False; end Get_Enabled_Services; ------------------------- -- Get_Enabled_Bridges -- ------------------------- procedure Get_Enabled_Bridges (This : not null access Manager; Bridges : out DOM.Core.Element; Result : out Boolean) is begin if This.Base_XML_Doc_Loaded and not This.Enabled_Bridges_XML_Doc_Built then Reset (This.Enabled_Bridges_XML_Doc); This.Populate_Enabled_Components (This.Enabled_Bridges_XML_Doc, Node_Name => String_Constant.Bridge); This.Enabled_Bridges_XML_Doc_Built := True; end if; Bridges := DOM.Core.Documents.Get_Element (This.Enabled_Bridges_XML_Doc); Result := True; exception when others => Result := False; end Get_Enabled_Bridges; --------------------------------- -- Populate_Enabled_Components -- --------------------------------- procedure Populate_Enabled_Components (This : not null access Manager; Doc : in out DOM.Core.Document; Node_Name : String) is use DOM.Core; use DOM.Core.Nodes; Unused : DOM.Core.Element; Matching_Children : Node_List := DOM.Core.Documents.Get_Elements_By_Tag_Name (This.Base_XML_Doc, Node_Name); UxAS_Node : DOM.Core.Element; begin UxAS_Node := DOM.Core.Documents.Create_Element (Doc, Tag_Name => String_Constant.UxAS); UxAS_Node := DOM.Core.Nodes.Append_Child (Doc, New_Child => UxAS_Node); DOM.Core.Elements.Set_Attribute (UxAS_Node, Name => "FormatVersion", Value => "1.0"); DOM.Core.Elements.Set_Attribute (UxAS_Node, Name => String_Constant.EntityId, Value => To_String (This.Get_Entity_Id)); DOM.Core.Elements.Set_Attribute (UxAS_Node, Name => String_Constant.EntityType, Value => This.Get_Entity_Type); for K in Natural range 1 .. DOM.Core.Nodes.Length (Matching_Children) loop Unused := Append_Child (UxAS_Node, New_Child => DOM.Core.Documents.Import_Node (Doc, Item (Matching_Children, K - 1), Deep => True)); end loop; DOM.Core.Free (Matching_Children); end Populate_Enabled_Components; ------------------------ -- Load_Base_XML_File -- ------------------------ procedure Load_Base_XML_File (This : not null access Manager; XML_File_Path : String; Result : out Boolean) is begin This.Load_XML (XML_Input => XML_File_Path, XML_Is_File => True, Is_Base_XML => True, Result => Result); end Load_Base_XML_File; -------------------------- -- Load_Base_XML_String -- -------------------------- procedure Load_Base_XML_String (This : not null access Manager; XML_Content : String; Result : out Boolean) is begin This.Load_XML (XML_Input => XML_Content, XML_Is_File => False, Is_Base_XML => True, Result => Result); end Load_Base_XML_String; -------------- -- Load_XML -- -------------- procedure Load_XML (This : not null access Manager; XML_Input : String; XML_Is_File : Boolean; Is_Base_XML : Boolean; Result : out Boolean) is XML_Parse_Success : Boolean; Reader : DOM.Readers.Tree_Reader; begin if Is_Base_XML then if This.Base_XML_Doc_Loaded then Reset (This.Base_XML_Doc); This.Base_XML_Doc_Loaded := False; This.Enabled_Bridges_XML_Doc_Built := False; This.Enabled_Services_XML_Doc_Built := False; end if; if XML_Is_File then declare Input : Input_Sources.File.File_Input; begin Input_Sources.File.Open (XML_Input, Input); Reader.Parse (Input); Input_Sources.File.Close (Input); This.Base_XML_Doc := DOM.Readers.Get_Tree (Reader); XML_Parse_Success := True; exception when others => XML_Parse_Success := False; end; else -- input is not a file declare Input : Input_Sources.Strings.String_Input; begin Input_Sources.Strings.Open (XML_Input, Sax.Encodings.Encoding, Input); Reader.Parse (Input); Input_Sources.Strings.Close (Input); This.Base_XML_Doc := DOM.Readers.Get_Tree (Reader); XML_Parse_Success := True; exception when others => XML_Parse_Success := False; end; end if; This.Base_XML_Doc_Loaded := True; end if; if XML_Parse_Success then This.Set_Entity_Values_From_XML_Node (Root => This.Base_XML_Doc, Result => Result); end if; if not Result then if Is_Base_XML then This.Base_XML_Doc_Loaded := False; end if; end if; end Load_XML; ---------------- -- Unload_XML -- ---------------- procedure Unload_XML (This : not null access Manager) is begin Reset (This.Base_XML_Doc); This.Base_XML_Doc_Loaded := False; Reset (This.Enabled_Bridges_XML_Doc); This.Enabled_Bridges_XML_Doc_Built := False; Reset (This.Enabled_Services_XML_Doc); This.Enabled_Services_XML_Doc_Built := False; end Unload_XML; ------------------------------------- -- Set_Entity_Values_From_XML_Node -- ------------------------------------- procedure Set_Entity_Values_From_XML_Node (This : not null access Manager; Root : DOM.Core.Document; Result : out Boolean) is Success : Boolean := False; use DOM.Core; use DOM.Core.Elements; Children : constant Node_List := DOM.Core.Documents.Get_Elements_By_Tag_Name (Root, String_Constant.UxAS); EntityInfoXmlNode : constant Node := DOM.Core.Nodes.Item (Children, Index => 0); begin if EntityInfoXmlNode /= null then declare Str : constant DOM_String := Get_Attribute (EntityInfoXmlNode, Name => String_Constant.EntityId); begin if Str /= "" then This.Entity_Id := UInt32'Value (Str); Success := True; end if; end; if Success then declare Str : constant DOM_String := Get_Attribute (EntityInfoXmlNode, Name => String_Constant.EntityType); begin if Str /= "" then Copy (Str, To => This.Entity_Type); else Success := False; end if; end; end if; -- and so on, for ConsoleLoggerSeverityLevel, MainFileLoggerSeverityLevel, etc. pragma Compile_Time_Warning (True, "Set_Entity_Values_From_XML_Node is incomplete"); end if; Result := Success; end Set_Entity_Values_From_XML_Node; ----------- -- Reset -- ----------- procedure Reset (This : in out DOM.Core.Document) is Impl : DOM.Core.DOM_Implementation; begin -- the Pugi version first does a destroy() call but that doesn't seem to -- exist in the XMLAda version This := DOM.Core.Create_Document (Impl); end Reset; ------------------------------ -- Root_Data_Work_Directory -- ------------------------------ function Root_Data_Work_Directory return String is (Value (Root_Data_Work_Dir)); ---------------------------------- -- Set_Root_Data_Work_Directory -- ---------------------------------- procedure Set_Root_Data_Work_Directory (Value : String) is begin Copy (Value, To => Root_Data_Work_Dir); end Set_Root_Data_Work_Directory; ------------------------------ -- Component_Data_Directory -- ------------------------------ function Component_Data_Directory (Directory_Name : String) return String is use Ada.Strings.Fixed; use Ada.Strings; Trimmed_Dir : constant String := Trim (Directory_Name, Both); Suffix : constant String := (if Index (Trimmed_Dir, "/", Going => Backward) = 1 then "" else "/"); begin -- return (s_rootDataInDirectory + directoryName + ((*(directoryName.rbegin()) == '/') ? "" : "/")); return Root_DataIn_Directory & Trimmed_Dir & Suffix; end Component_Data_Directory; end UxAS.Common.Configuration_Manager;
sungyeon/drake
Ada
3,142
adb
pragma License (Unrestricted); -- BSD 3-Clause -- translated unit from MT19937 (mtTest.c) -- -- A C-program for MT19937, with initialization improved 2002/1/26. -- Coded by Takuji Nishimura and Makoto Matsumoto. -- -- Before using, initialize the state by using init_genrand(seed) -- or init_by_array(init_key, key_length). -- -- Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, -- All rights reserved. -- Copyright (C) 2005, Mutsuo Saito, -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. The names of its contributors 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 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. -- -- -- Any feedback is very welcome. -- http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html -- email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) -- -- -- Ada version by yt -- with Ada.Long_Long_Float_Text_IO; with Ada.Numerics.MT19937; with Ada.Text_IO; procedure random_mt19937 is use Ada.Numerics.MT19937; package Unsigned_32_IO is new Ada.Text_IO.Modular_IO (Unsigned_32); init : Unsigned_32_Array (0 .. 3) := (16#123#, 16#234#, 16#345#, 16#456#); Gen : aliased Generator := Initialize (init); begin Ada.Text_IO.Put_Line ("1000 outputs of genrand_int32()"); for i in 0 .. 1000 - 1 loop Unsigned_32_IO.Put ( Random_32 (Gen), Width => 10); Ada.Text_IO.Put (' '); if i rem 5 = 4 then Ada.Text_IO.New_Line; end if; end loop; Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("1000 outputs of genrand_real2()"); for i in 0 .. 1000 - 1 loop Ada.Long_Long_Float_Text_IO.Put ( Random_0_To_Less_Than_1 (Gen), Fore => 0, Aft => 8, Exp => 0); Ada.Text_IO.Put (' '); if i rem 5 = 4 then Ada.Text_IO.New_Line; end if; end loop; end random_mt19937;
strenkml/EE368
Ada
487
ads
package Benchmark.Hash is type Hash_Type is new Benchmark_Type with private; function Create_Hash return Benchmark_Pointer; overriding procedure Set_Argument(benchmark : in out Hash_Type; arg : in String); overriding procedure Run(benchmark : in Hash_Type); private type Hash_Type is new Benchmark_Type with record size : Positive := 1024; iterations : Positive := 1000; end record; end Benchmark.Hash;
charlie5/cBound
Ada
1,402
ads
-- This file is generated by SWIG. Please do not modify by hand. -- with xcb.xcb_glx_generic_error_t; with Interfaces.C; with Interfaces.C.Pointers; package xcb.xcb_glx_bad_context_state_error_t is -- Item -- subtype Item is xcb.xcb_glx_generic_error_t.Item; -- Item_Array -- type Item_Array is array (Interfaces.C .size_t range <>) of aliased xcb.xcb_glx_bad_context_state_error_t .Item; -- Pointer -- package C_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_glx_bad_context_state_error_t.Item, Element_Array => xcb.xcb_glx_bad_context_state_error_t.Item_Array, Default_Terminator => (others => <>)); subtype Pointer is C_Pointers.Pointer; -- Pointer_Array -- type Pointer_Array is array (Interfaces.C .size_t range <>) of aliased xcb.xcb_glx_bad_context_state_error_t .Pointer; -- Pointer_Pointer -- package C_Pointer_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_glx_bad_context_state_error_t.Pointer, Element_Array => xcb.xcb_glx_bad_context_state_error_t.Pointer_Array, Default_Terminator => null); subtype Pointer_Pointer is C_Pointer_Pointers.Pointer; end xcb.xcb_glx_bad_context_state_error_t;
coopht/axmpp
Ada
3,576
ads
------------------------------------------------------------------------------ -- -- -- AXMPP Project -- -- -- -- XMPP Library for Ada -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011, Alexander Basov <[email protected]> -- -- 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 Alexander Basov, 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$ ------------------------------------------------------------------------------ package XML.SAX.Input_Sources.Streams.Sockets.Debug is type Debug_Socket_Input_Source is new Socket_Input_Source with null record; overriding procedure Next (Self : in out Debug_Socket_Input_Source; Buffer : in out not null Matreshka.Internals.Strings.Shared_String_Access; End_Of_Data : out Boolean); end XML.SAX.Input_Sources.Streams.Sockets.Debug;
onox/sdlada
Ada
2,372
ads
-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2013-2018 Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- -- SDL.Libraries -- -- Mechanism for accessing shared objects (libraries). -------------------------------------------------------------------------------------------------------------------- with Ada.Finalization; package SDL.Libraries is Library_Error : exception; type Handles is new Ada.Finalization.Limited_Controlled with private; Null_Handle : constant Handles; procedure Load (Self : out Handles; Name : in String); procedure Unload (Self : in out Handles); -- with -- Static_Predicate => Handle /= Null_Handle; generic type Access_To_Sub_Program is private; Name : String; function Load_Sub_Program (From_Library : in Handles) return Access_To_Sub_Program; private type Internal_Handle is null record with Convention => C; type Internal_Handle_Access is access all Internal_Handle with Convention => C; type Handles is new Ada.Finalization.Limited_Controlled with record Internal : Internal_Handle_Access; end record; overriding procedure Finalize (Self : in out Handles); Null_Handle : constant Handles := (Ada.Finalization.Limited_Controlled with Internal => null); end SDL.Libraries;
charlie5/aIDE
Ada
1,250
ads
with AdaM.Entity; private with ada.Streams; package AdaM.Comment is type Item is new Entity.item with private; type View is access all Item'Class; -- Forge -- function new_Comment return Comment.view; procedure free (Self : in out Comment.view); procedure destruct (Self : in out Item); -- Attributes -- overriding function Id (Self : access Item) return AdaM.Id; function Lines (Self : in Item) return text_Lines; procedure Lines_are (Self : in out Item; Now : in text_Lines); overriding function to_Source (Self : in Item) return text_Vectors.Vector; overriding function Name (Self : in Item) return Identifier; private type Item is new Entity.item with record Lines : text_Lines; end record; -- Streams -- procedure View_write (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Self : in View); procedure View_read (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Self : out View); for View'write use View_write; for View'read use View_read; end AdaM.Comment;
davidkristola/vole
Ada
9,784
adb
with Ada.Exceptions; use Ada.Exceptions; with Ada.Unchecked_Deallocation; with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Text_IO; --use Ada.Text_IO; with Ada.Strings.Maps; with Ada.Strings.Fixed; with Ada.Characters.Latin_1; with Interfaces; with String_Ops; with kv.avm.Assemblers; with kv.avm.File_Reader; with kv.avm.Memories; with kv.avm.Registers; with kv.avm.Log; use kv.avm.Log; package body kv.avm.Ini is package String_Lists is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); package Configurations is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => String_Lists.Vector, "=" => String_Lists."="); use Configurations; type Configuration_Access is access Configurations.Map; type Settings_Reference_Counter_Type is record Count : Natural := 0; Data : Configuration_Access; end record; ----------------------------------------------------------------------------- procedure Free is new Ada.Unchecked_Deallocation(Settings_Reference_Counter_Type, Settings_Reference_Counter_Access); ----------------------------------------------------------------------------- procedure Free is new Ada.Unchecked_Deallocation(Configurations.Map, Configuration_Access); ----------------------------------------------------------------------------- procedure Initialize (Self : in out Settings_Type) is begin Self.Ref := new Settings_Reference_Counter_Type; Self.Ref.Count := 1; Self.Ref.Data := new Configurations.Map; end Initialize; ----------------------------------------------------------------------------- procedure Adjust (Self : in out Settings_Type) is Ref : Settings_Reference_Counter_Access := Self.Ref; begin if Ref /= null then Ref.Count := Ref.Count + 1; end if; end Adjust; ----------------------------------------------------------------------------- procedure Finalize (Self : in out Settings_Type) is Ref : Settings_Reference_Counter_Access := Self.Ref; begin Self.Ref := null; if Ref /= null then Ref.Count := Ref.Count - 1; if Ref.Count = 0 then Free(Ref.Data); Free(Ref); end if; end if; end Finalize; ----------------------------------------------------------------------------- function Split_Index(The_String : String) return Natural is begin return Ada.Strings.Fixed.Index(The_String, "="); end Split_Index; ----------------------------------------------------------------------------- procedure Parse_Line (Self : in out Settings_Type; Line : in String) is Split_Point : Natural; Key_And_Value : constant String := String_Ops.Drop_Vole_Comments(Line); begin --Put_Line("Parse_Line = <"&Key_And_Value&">"); Split_Point := Split_Index(Key_And_Value); --Put_Line("Split_Point =" & Natural'IMAGE(Split_Point)); if Split_Point /= 0 then declare Key : constant String := String_Ops.Trim_Blanks(Key_And_Value(Key_And_Value'FIRST .. Split_Point-1)); Value : constant String := String_Ops.Trim_Blanks(Key_And_Value(Split_Point+1 .. Key_And_Value'LAST)); begin --Put_Line("Key = <"& Key &">"); --Put_Line("Value = <"& Value &">"); if Self.Has(Key) then Self.Add_Value_To_Existing_Key(Key, Value); else Self.Insert(Key, Value); end if; --Self.Ref.Data.Insert(Key, Value); end; end if; end Parse_Line; ----------------------------------------------------------------------------- procedure Add_Value_To_Existing_Key (Self : in out Settings_Type; Key : in String; Value : in String) is Value_List : String_Lists.Vector; Location : Cursor; begin --Put_Line("Adding <" & Value & "> to existing key <" & Key & ">"); Location := Self.Ref.Data.Find(Key); if Location /= No_Element then Value_List := Element(Location); String_Lists.Append(Value_List, Value); Self.Ref.Data.Replace_Element(Location, Value_List); else --raise Constraint_Error; --TODO: define an exception and raise it with a message Raise_Exception(Constraint_Error'IDENTITY, "Error: key <" & Key & "> not found."); end if; end Add_Value_To_Existing_Key; ----------------------------------------------------------------------------- procedure Insert (Self : in out Settings_Type; Key : in String; Value : in String) is Value_List : String_Lists.Vector; begin --Put_Line("Inserting <" & Value & "> at key <" & Key & ">"); String_Lists.Append(Value_List, Value); Self.Ref.Data.Insert(Key, Value_List); end Insert; ----------------------------------------------------------------------------- function Has(Self : Settings_Type; Key : String) return Boolean is begin return Self.Ref.Data.Contains(Key); end Has; ----------------------------------------------------------------------------- function Lookup_As_String(Self : Settings_Type; Key : String; Index : Positive := 1) return String is Location : Cursor; Value_List : String_Lists.Vector; begin Location := Self.Ref.Data.Find(Key); if Location /= No_Element then Value_List := Element(Location); return String_Lists.Element(Value_List, Index); end if; return ""; end Lookup_As_String; ----------------------------------------------------------------------------- function Lookup_As_Integer(Self : Settings_Type; Key : String; Index : Positive := 1) return Integer is Image : constant String := Self.Lookup_As_String(Key, Index); begin return Integer'VALUE(Image); end Lookup_As_Integer; ---------------------------------------------------------------------------- function Tuple_String_Count_Elements(Tuple_String : String) return Positive is begin return Ada.Strings.Fixed.Count(Tuple_String, ",") + 1; -- The number of delimiters plus one end Tuple_String_Count_Elements; ---------------------------------------------------------------------------- function Tuple_String_Get(Tuple_String : String; Index : Positive) return String is begin return String_Ops.Nth(Tuple_String, Index, Ada.Strings.Maps.To_Set(',')); end Tuple_String_Get; ---------------------------------------------------------------------------- function Make_String_Register(Value : String) return kv.avm.Registers.Register_Type is Clean : constant String := String_Ops.Trim_One_From_Both_Ends(Value); use kv.avm.Registers; begin return (Format => Immutable_String, The_String => +Clean); end Make_String_Register; ---------------------------------------------------------------------------- function Make_Intger_Value(Value : String) return kv.avm.Registers.Register_Type is begin return kv.avm.Registers.Make_S(Interfaces.Integer_64'VALUE(Value)); end Make_Intger_Value; ---------------------------------------------------------------------------- function Make_Register(Value : String) return kv.avm.Registers.Register_Type is begin if Value(Value'FIRST) = Ada.Characters.Latin_1.Quotation then return Make_String_Register(Value); else return Make_Intger_Value(Value); end if; end Make_Register; ---------------------------------------------------------------------------- function String_To_Registers(Tuple_String : String) return kv.avm.Memories.Register_Set_Type is Clean : constant String := String_Ops.Trim_One_From_Both_Ends(Tuple_String); -- drop [] Count : constant Positive := Tuple_String_Count_Elements(Clean); Answer : kv.avm.Memories.Register_Set_Type(0 .. Interfaces.Unsigned_32(Count - 1)); use Interfaces; begin --Put_Line("String_To_Registers processing <" & Clean & "> (count =" & Positive'IMAGE(Count) & ")"); for Index in Answer'RANGE loop Answer(Index) := Make_Register(Tuple_String_Get(Clean, Positive(Index + 1))); end loop; return Answer; end String_To_Registers; ---------------------------------------------------------------------------- function Lookup_As_Tuple(Self : Settings_Type; Key : String; Index : Positive := 1) return kv.avm.Tuples.Tuple_Type is Answer : kv.avm.Tuples.Tuple_Type; Contents : kv.avm.Memories.Register_Array_Type; begin Contents.Initialize(String_To_Registers(Self.Lookup_As_String(Key, Index))); Answer.Fold(Contents); return Answer; end Lookup_As_Tuple; ---------------------------------------------------------------------------- function Value_Count_For_Key(Self : Settings_Type; Key : String) return Natural is Location : Cursor; Value_List : String_Lists.Vector; begin Location := Self.Ref.Data.Find(Key); if Location /= No_Element then Value_List := Element(Location); return Natural(String_Lists.Length(Value_List)); end if; return 0; end Value_Count_For_Key; ---------------------------------------------------------------------------- package Settings_Reader is new kv.avm.File_Reader(Settings_Type); ---------------------------------------------------------------------------- procedure Parse_Input_File (Self : in out Settings_Type; File_In : in String) renames Settings_Reader.Parse_Input_File; end kv.avm.Ini;
zhmu/ananas
Ada
8,017
adb
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . O S _ I N T E R F A C E -- -- -- -- B o d y -- -- -- -- Copyright (C) 1997-2022, Free Software Foundation, Inc. -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by Ada Core Technologies, Inc. -- -- -- ------------------------------------------------------------------------------ -- This is the VxWorks version -- This package encapsulates all direct interfaces to OS services that are -- needed by children of System. package body System.OS_Interface is use type Interfaces.C.int; Low_Priority : constant := 255; -- VxWorks native (default) lowest scheduling priority ----------------- -- To_Duration -- ----------------- function To_Duration (TS : timespec) return Duration is begin return Duration (TS.ts_sec) + Duration (TS.ts_nsec) / 10#1#E9; end To_Duration; ----------------- -- To_Timespec -- ----------------- function To_Timespec (D : Duration) return timespec is S : time_t; F : Duration; begin S := time_t (Long_Long_Integer (D)); F := D - Duration (S); -- If F is negative due to a round-up, adjust for positive F value if F < 0.0 then S := S - 1; F := F + 1.0; end if; return timespec'(ts_sec => S, ts_nsec => long (Long_Long_Integer (F * 10#1#E9))); end To_Timespec; ------------------------- -- To_VxWorks_Priority -- ------------------------- function To_VxWorks_Priority (Priority : int) return int is begin return Low_Priority - Priority; end To_VxWorks_Priority; -------------------- -- To_Clock_Ticks -- -------------------- -- ??? - For now, we'll always get the system clock rate since it is -- allowed to be changed during run-time in VxWorks. A better method would -- be to provide an operation to set it that so we can always know its -- value. -- Another thing we should probably allow for is a resultant tick count -- greater than int'Last. This should probably be a procedure with two -- output parameters, one in the range 0 .. int'Last, and another -- representing the overflow count. function To_Clock_Ticks (D : Duration) return int is Ticks : Long_Long_Integer; Rate_Duration : Duration; Ticks_Duration : Duration; IERR : constant int := -1; begin if D < 0.0 then return IERR; end if; -- Ensure that the duration can be converted to ticks -- at the current clock tick rate without overflowing. Rate_Duration := Duration (sysClkRateGet); if D > (Duration'Last / Rate_Duration) then Ticks := Long_Long_Integer (int'Last); else Ticks_Duration := D * Rate_Duration; Ticks := Long_Long_Integer (Ticks_Duration); if Ticks_Duration > Duration (Ticks) then Ticks := Ticks + 1; end if; if Ticks > Long_Long_Integer (int'Last) then Ticks := Long_Long_Integer (int'Last); end if; end if; return int (Ticks); end To_Clock_Ticks; ----------------------------- -- Binary_Semaphore_Create -- ----------------------------- function Binary_Semaphore_Create return Binary_Semaphore_Id is begin return Binary_Semaphore_Id (semBCreate (SEM_Q_FIFO, SEM_EMPTY)); end Binary_Semaphore_Create; ----------------------------- -- Binary_Semaphore_Delete -- ----------------------------- function Binary_Semaphore_Delete (ID : Binary_Semaphore_Id) return STATUS is begin return semDelete (SEM_ID (ID)); end Binary_Semaphore_Delete; ----------------------------- -- Binary_Semaphore_Obtain -- ----------------------------- function Binary_Semaphore_Obtain (ID : Binary_Semaphore_Id) return STATUS is begin return semTake (SEM_ID (ID), WAIT_FOREVER); end Binary_Semaphore_Obtain; ------------------------------ -- Binary_Semaphore_Release -- ------------------------------ function Binary_Semaphore_Release (ID : Binary_Semaphore_Id) return STATUS is begin return semGive (SEM_ID (ID)); end Binary_Semaphore_Release; ---------------------------- -- Binary_Semaphore_Flush -- ---------------------------- function Binary_Semaphore_Flush (ID : Binary_Semaphore_Id) return STATUS is begin return semFlush (SEM_ID (ID)); end Binary_Semaphore_Flush; ---------- -- kill -- ---------- function kill (pid : t_id; sig : Signal) return int is begin return System.VxWorks.Ext.kill (pid, int (sig)); end kill; ----------------------- -- Interrupt_Connect -- ----------------------- function Interrupt_Connect (Vector : Interrupt_Vector; Handler : Interrupt_Handler; Parameter : System.Address := System.Null_Address) return STATUS is begin return System.VxWorks.Ext.Interrupt_Connect (System.VxWorks.Ext.Interrupt_Vector (Vector), System.VxWorks.Ext.Interrupt_Handler (Handler), Parameter); end Interrupt_Connect; ----------------------- -- Interrupt_Context -- ----------------------- function Interrupt_Context return BOOL is begin return System.VxWorks.Ext.Interrupt_Context; end Interrupt_Context; -------------------------------- -- Interrupt_Number_To_Vector -- -------------------------------- function Interrupt_Number_To_Vector (intNum : int) return Interrupt_Vector is begin return Interrupt_Vector (System.VxWorks.Ext.Interrupt_Number_To_Vector (intNum)); end Interrupt_Number_To_Vector; ----------------- -- Current_CPU -- ----------------- function Current_CPU return Multiprocessors.CPU is begin -- ??? Should use vxworks multiprocessor interface return Multiprocessors.CPU'First; end Current_CPU; end System.OS_Interface;
zrmyers/VulkanAda
Ada
4,926
ads
-------------------------------------------------------------------------------- -- MIT License -- -- Copyright (c) 2020 Zane Myers -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. -------------------------------------------------------------------------------- with Vulkan.Math.GenDType; use Vulkan.Math.GenDType; -------------------------------------------------------------------------------- --< @group Vulkan Math Basic Types -------------------------------------------------------------------------------- --< @summary --< This package defines a double precision floating point vector type with 2 --< components. -------------------------------------------------------------------------------- package Vulkan.Math.Dvec2 is pragma Preelaborate; pragma Pure; --< A 2 component vector of double-precision floating point values. subtype Vkm_Dvec2 is Vkm_GenDType(Last_Index => 1); ---------------------------------------------------------------------------- -- Ada does not have the concept of constructors in the sense that they exist -- in C++. For this reason, we will instead define multiple methods for -- instantiating a vec2 here. ---------------------------------------------------------------------------- -- The following are explicit constructors for Vec2: ---------------------------------------------------------------------------- --< @summary --< Constructor for Vkm_Dvec2 type. --< --< @description --< Produce a default vector with all components set to 0.0. --< --< @return --< A Vec2 with all components set to 0.0. ---------------------------------------------------------------------------- function Make_Dvec2 return Vkm_Dvec2 is (GDT.Make_GenType(Last_Index => 1, value => 0.0)) with Inline; ---------------------------------------------------------------------------- --< @summary --< Constructor for Vkm_Dvec2 type. --< --< @description --< Produce a vector with all components set to the same value. --< --< @param scalar_value --< The value to set all components to. --< --< @returns A Vec2 with all components set to scalar_value. ---------------------------------------------------------------------------- function Make_Dvec2 (scalar_value : in Vkm_Double) return Vkm_Dvec2 is (GDT.Make_GenType(Last_Index => 1, value => scalar_value)) with Inline; ---------------------------------------------------------------------------- --< @summary --< Constructor for Vkm_Dvec2 type. --< --< @description --< Produce a vector by copying components from an existing vector. --< --< @param vec2_value --< The vec2 to copy components from. --< --< @return --< A vec2 with all of its components set equal to the corresponding --< components of vec2_value. ---------------------------------------------------------------------------- function Make_Dvec2 (vec2_value : in Vkm_Dvec2) return Vkm_Dvec2 is (GDT.Make_GenType(vec2_value.x,vec2_value.y)) with Inline; ---------------------------------------------------------------------------- --< @summary --< Constructor for Vkm_Dvec2 type. --< --< @description --< Produce a vector by specifying the values for each of its components. --< --< @param value1 --< Value for component 1. --< --< @param value2 --< Value for component 2. --< --< @return --< A Vec2 with all components set as specified. ---------------------------------------------------------------------------- function Make_Dvec2 (value1, value2 : in Vkm_Double) return Vkm_Dvec2 renames GDT.Make_GenType; end Vulkan.Math.Dvec2;
optikos/oasis
Ada
1,628
adb
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Wide_Wide_Characters.Handling; package body Program.Units.Vectors is ------------ -- Append -- ------------ procedure Append (Self : in out Unit_Vector; Value : not null Program.Compilation_Units.Compilation_Unit_Access) is begin Self.Data.Append (Value); end Append; ----------- -- Clear -- ----------- procedure Clear (Self : in out Unit_Vector) is begin Self.Data.Clear; end Clear; ------------- -- Element -- ------------- overriding function Element (Self : Unit_Vector; Index : Positive) return not null Program.Compilation_Units.Compilation_Unit_Access is begin return Self.Data (Index); end Element; --------------- -- Find_Unit -- --------------- overriding function Find_Unit (Self : Unit_Vector; Name : Text) return Program.Compilation_Units.Compilation_Unit_Access is use Ada.Wide_Wide_Characters.Handling; Name_To_Lower : constant Text := To_Lower (Name); begin for J of Self.Data loop if To_Lower (J.Full_Name) = Name_To_Lower then return J; end if; end loop; return null; end Find_Unit; ---------------- -- Get_Length -- ---------------- overriding function Get_Length (Self : Unit_Vector) return Positive is begin return Self.Data.Last_Index; end Get_Length; end Program.Units.Vectors;
reznikmm/matreshka
Ada
3,814
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.ODF_Elements.Style.Tab_Stops; package ODF.DOM.Elements.Style.Tab_Stops.Internals is function Create (Node : Matreshka.ODF_Elements.Style.Tab_Stops.Style_Tab_Stops_Access) return ODF.DOM.Elements.Style.Tab_Stops.ODF_Style_Tab_Stops; function Wrap (Node : Matreshka.ODF_Elements.Style.Tab_Stops.Style_Tab_Stops_Access) return ODF.DOM.Elements.Style.Tab_Stops.ODF_Style_Tab_Stops; end ODF.DOM.Elements.Style.Tab_Stops.Internals;
stcarrez/ada-libsecret
Ada
2,876
ads
----------------------------------------------------------------------- -- Secret -- Ada wrapper for Secret Service -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Ada.Finalization; private with Interfaces.C.Strings; -- == Secret Service API == -- The Secret Service API is a service developped for the Gnome keyring and the KDE KWallet. -- It allows application to access and manage stored passwords and secrets in the two -- desktop environments. The libsecret is the C library that gives access to the secret -- service. The <tt>Secret</tt> package provides an Ada binding for this secret service API. -- -- @include secret-values.ads -- @include secret-attributes.ads -- @include secret-services.ads package Secret is type Object_Type is tagged private; -- Check if the value is empty. function Is_Null (Value : in Object_Type'Class) return Boolean; private use type System.Address; subtype Opaque_Type is System.Address; type Object_Type is new Ada.Finalization.Controlled with record Opaque : Opaque_Type := System.Null_Address; end record; -- Internal operation to set the libsecret internal pointer. procedure Set_Opaque (Into : in out Object_Type'Class; Data : in Opaque_Type); -- Internal operation to get the libsecret internal pointer. function Get_Opaque (From : in Object_Type'Class) return Opaque_Type; subtype Chars_Ptr is Interfaces.C.Strings.chars_ptr; procedure Free (P : in out Chars_Ptr) renames Interfaces.C.Strings.Free; function To_String (P : Chars_Ptr) return String renames Interfaces.C.Strings.Value; function New_String (V : in String) return Chars_Ptr renames Interfaces.C.Strings.New_String; type GError_Type is record Domain : Interfaces.Unsigned_32 := 0; Code : Interfaces.C.int := 0; Message : Chars_Ptr; end record with Convention => C; type GError is access all GError_Type with Convention => C; pragma Linker_Options ("-lsecret-1"); pragma Linker_Options ("-lglib-2.0"); pragma Linker_Options ("-lgio-2.0"); -- pragma Linker_Options ("-liconv"); end Secret;
zhmu/ananas
Ada
6,931
ads
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- I N T E R F A C E S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2002-2022, Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. The copyright notice above, and the license provisions that follow -- -- apply solely to the implementation dependent sections of this file. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This is the compiler version of this unit package Interfaces is pragma No_Elaboration_Code_All; pragma Pure; -- All identifiers in this unit are implementation defined pragma Implementation_Defined; type Integer_8 is range -2 ** 7 .. 2 ** 7 - 1; 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 new Long_Long_Integer; for Integer_64'Size use 64; -- Note: we use Long_Long_Integer'First instead of -2 ** 63 to allow this -- unit to compile when using custom target configuration files where the -- maximum integer is 32 bits. This is useful for static analysis tools -- such as SPARK or CodePeer. In the normal case Long_Long_Integer is -- always 64-bits so we get the desired 64-bit type. 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_24 is mod 2 ** 24; for Unsigned_24'Size use 24; -- Declare this type for compatibility with legacy Ada compilers. -- This is particularly useful in the context of CodePeer analysis. type Unsigned_32 is mod 2 ** 32; for Unsigned_32'Size use 32; type Unsigned_64 is mod 2 ** Long_Long_Integer'Size; for Unsigned_64'Size use 64; -- See comment on Integer_64 above function Shift_Left (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Shift_Right (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Shift_Right_Arithmetic (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Rotate_Left (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Rotate_Right (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Shift_Left (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Shift_Right (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Shift_Right_Arithmetic (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Rotate_Left (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Rotate_Right (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Shift_Left (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Shift_Right (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Shift_Right_Arithmetic (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Rotate_Left (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Rotate_Right (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Shift_Left (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Shift_Right (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Shift_Right_Arithmetic (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Rotate_Left (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Rotate_Right (Value : Unsigned_64; Amount : Natural) return Unsigned_64; pragma Import (Intrinsic, Shift_Left); pragma Import (Intrinsic, Shift_Right); pragma Import (Intrinsic, Shift_Right_Arithmetic); pragma Import (Intrinsic, Rotate_Left); pragma Import (Intrinsic, Rotate_Right); -- IEEE Floating point types type IEEE_Float_32 is digits 6; for IEEE_Float_32'Size use 32; type IEEE_Float_64 is digits 15; for IEEE_Float_64'Size use 64; -- If there is an IEEE extended float available on the machine, we assume -- that it is available as Long_Long_Float. -- Note: it is harmless, and explicitly permitted, to include additional -- types in interfaces, so it is not wrong to have IEEE_Extended_Float -- defined even if the extended format is not available. type IEEE_Extended_Float is new Long_Long_Float; end Interfaces;
AdaCore/gpr
Ada
54
adb
separate (AAA) procedure AA is begin null; end AA;
Fabien-Chouteau/Ada_Drivers_Library
Ada
2,555
ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with HAL; use HAL; package nRF51.RNG is procedure Enable_Digital_Error_Correction; procedure Disable_Digital_Error_Correction; function Read return UInt8; end nRF51.RNG;
Gabriel-Degret/adalib
Ada
2,842
ads
-- Standard Ada library specification -- Copyright (c) 2003-2018 Maxim Reznik <[email protected]> -- Copyright (c) 2004-2016 AXE Consultants -- Copyright (c) 2004, 2005, 2006 Ada-Europe -- Copyright (c) 2000 The MITRE Corporation, Inc. -- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc. -- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual --------------------------------------------------------------------------- with Ada.Numerics.Generic_Complex_Types; generic with package Complex_Types is new Ada.Numerics.Generic_Complex_Types (<>); package Ada.Numerics.Generic_Complex_Elementary_Functions is pragma Pure (Generic_Complex_Elementary_Functions); function Sqrt (X : in Complex_Types.Complex) return Complex_Types.Complex; function Log (X : in Complex_Types.Complex) return Complex_Types.Complex; function Exp (X : in Complex_Types.Complex) return Complex_Types.Complex; function Exp (X : in Complex_Types.Imaginary) return Complex_Types.Complex; function "**" (Left : in Complex_Types.Complex; Right : in Complex_Types.Complex) return Complex_Types.Complex; function "**" (Left : in Complex_Types.Complex; Right : in Complex_Types.Real'Base) return Complex_Types.Complex; function "**" (Left : in Complex_Types.Real'Base; Right : in Complex_Types.Complex) return Complex_Types.Complex; function Sin (X : in Complex_Types.Complex) return Complex_Types.Complex; function Cos (X : in Complex_Types.Complex) return Complex_Types.Complex; function Tan (X : in Complex_Types.Complex) return Complex_Types.Complex; function Cot (X : in Complex_Types.Complex) return Complex_Types.Complex; function Arcsin (X : in Complex_Types.Complex) return Complex_Types.Complex; function Arccos (X : in Complex_Types.Complex) return Complex_Types.Complex; function Arctan (X : in Complex_Types.Complex) return Complex_Types.Complex; function Arccot (X : in Complex_Types.Complex) return Complex_Types.Complex; function Sinh (X : in Complex_Types.Complex) return Complex_Types.Complex; function Cosh (X : in Complex_Types.Complex) return Complex_Types.Complex; function Tanh (X : in Complex_Types.Complex) return Complex_Types.Complex; function Coth (X : in Complex_Types.Complex) return Complex_Types.Complex; function Arcsinh (X : in Complex_Types.Complex) return Complex_Types.Complex; function Arccosh (X : in Complex_Types.Complex) return Complex_Types.Complex; function Arctanh (X : in Complex_Types.Complex) return Complex_Types.Complex; function Arccoth (X : in Complex_Types.Complex) return Complex_Types.Complex; end Ada.Numerics.Generic_Complex_Elementary_Functions;
onox/orka
Ada
2,245
ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2019 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Orka.Rendering.Buffers; with Orka.Resources.Locations; with Orka.Transforms.Singles.Matrices; private with GL.Low_Level.Enums; private with Orka.Rendering.Programs.Uniforms; package Orka.Rendering.Debug.Lines is pragma Preelaborate; package Transforms renames Orka.Transforms.Singles.Matrices; type Line is tagged private; function Create_Line (Location : Resources.Locations.Location_Ptr) return Line; procedure Render (Object : in out Line; View, Proj : Transforms.Matrix4; Transforms, Colors, Points : Rendering.Buffers.Bindable_Buffer'Class) with Pre => Transforms.Length in 1 | Points.Length / 2 and Colors.Length in 1 | Points.Length / 2 and Points.Length mod 2 = 0; -- Render lines between pairs of points -- -- The buffer Transforms, containing the transform matrices, must -- contain one or n matrices for n lines. If all lines exist -- in the same world space, then one matrix transform is sufficient. -- -- The buffer Colors must contain one or n vectors. -- -- The buffer Points must contain 2 * n points. This buffers controls -- how many lines are rendered. private package LE renames GL.Low_Level.Enums; type Line is tagged record Program : Rendering.Programs.Program; Uniform_Visible : Programs.Uniforms.Uniform (LE.Bool_Type); Uniform_View : Programs.Uniforms.Uniform (LE.Single_Matrix4); Uniform_Proj : Programs.Uniforms.Uniform (LE.Single_Matrix4); end record; end Orka.Rendering.Debug.Lines;
persan/A-gst
Ada
2,393
ads
pragma Ada_2005; pragma Style_Checks (Off); pragma Warnings (Off); with Interfaces.C; use Interfaces.C; limited with GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstelement_h; limited with GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h; limited with GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h; package GStreamer.GST_Low_Level.gstreamer_0_10_gst_check_gstbufferstraw_h is -- GStreamer -- * -- * Copyright (C) 2006 Andy Wingo <wingo at pobox.com> -- * -- * This library is free software; you can redistribute it and/or -- * modify it under the terms of the GNU Library General Public -- * License as published by the Free Software Foundation; either -- * version 2 of the License, or (at your option) any later version. -- * -- * This library is distributed in the hope that it will be useful, -- * but WITHOUT ANY WARRANTY; without even the implied warranty of -- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- * Library General Public License for more details. -- * -- * You should have received a copy of the GNU Library General Public -- * License along with this library; if not, write to the -- * Free Software Foundation, Inc., 59 Temple Place - Suite 330, -- * Boston, MA 02111-1307, USA. -- procedure gst_buffer_straw_start_pipeline (bin : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstelement_h.GstElement; pad : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstPad); -- gst/check/gstbufferstraw.h:29 pragma Import (C, gst_buffer_straw_start_pipeline, "gst_buffer_straw_start_pipeline"); function gst_buffer_straw_get_buffer (bin : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstelement_h.GstElement; pad : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstPad) return access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer; -- gst/check/gstbufferstraw.h:30 pragma Import (C, gst_buffer_straw_get_buffer, "gst_buffer_straw_get_buffer"); procedure gst_buffer_straw_stop_pipeline (bin : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstelement_h.GstElement; pad : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstPad); -- gst/check/gstbufferstraw.h:31 pragma Import (C, gst_buffer_straw_stop_pipeline, "gst_buffer_straw_stop_pipeline"); end GStreamer.GST_Low_Level.gstreamer_0_10_gst_check_gstbufferstraw_h;
jrmarino/zstd-ada
Ada
2,004
adb
with Zstandard.Functions; use Zstandard.Functions; with Ada.Text_IO; use Ada.Text_IO; procedure Demo_Ada is message : constant String := "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus " & "tempor erat quis metus faucibus, a elementum odio varius. Donec " & "ultrices posuere nisl. Aliquam molestie, nibh a ultrices dictum, " & "neque nisi pellentesque sapien, a molestie urna quam eu leo. Morbi " & "nec finibus odio, vel maximus lorem. Proin eget viverra tellus, eu " & "vestibulum est. Aliquam pharetra vulputate porttitor. Integer eu " & "varius dui. Vivamus non metus id metus cursus auctor. Integer erat " & "augue, pharetra in nisl a, aliquet tempor leo."; begin Put_Line ("Zstandard version: " & Zstd_Version); Put_Line (""); Put_Line ("message:"); Put_Line (message); declare nominal : Boolean; compacted : constant String := Compress (source_data => message, successful => nominal, quality => 1); begin if not nominal then Put_Line ("FAILURE!"); Put_Line (compacted); return; end if; Put_Line (""); Put_Line (" original length:" & message'Length'Img); Put_Line ("compressed length:" & compacted'Length'Img); Put_Line (""); Put_Line ("Testing decompression ..."); declare vessel : String := Decompress (source_data => compacted, successful => nominal); begin if not nominal then Put_Line ("FAILURE!"); Put_Line (vessel); return; end if; if message = vessel then Put_Line ("SUCCESS! Decompressed text is the same as the original"); else Put_Line ("ERROR! Return value different"); Put_Line (vessel); end if; end; end; end Demo_Ada;
zhmu/ananas
Ada
34,595
adb
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ E L I M -- -- -- -- B o d y -- -- -- -- Copyright (C) 1997-2022, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Einfo; use Einfo; with Einfo.Entities; use Einfo.Entities; with Einfo.Utils; use Einfo.Utils; with Errout; use Errout; with Lib; use Lib; with Namet; use Namet; with Nlists; use Nlists; with Opt; use Opt; with Sem; use Sem; with Sem_Aux; use Sem_Aux; with Sem_Prag; use Sem_Prag; with Sem_Util; use Sem_Util; with Sinput; use Sinput; with Sinfo; use Sinfo; with Sinfo.Nodes; use Sinfo.Nodes; with Snames; use Snames; with Stand; use Stand; with Stringt; use Stringt; with Table; with GNAT.HTable; use GNAT.HTable; package body Sem_Elim is No_Elimination : Boolean; -- Set True if no Eliminate pragmas active --------------------- -- Data Structures -- --------------------- -- A single pragma Eliminate is represented by the following record type Elim_Data; type Access_Elim_Data is access Elim_Data; type Names is array (Nat range <>) of Name_Id; -- Type used to represent set of names. Used for names in Unit_Name -- and also the set of names in Argument_Types. type Access_Names is access Names; type Elim_Data is record Unit_Name : Access_Names; -- Unit name, broken down into a set of names (e.g. A.B.C is -- represented as Name_Id values for A, B, C in sequence). Entity_Name : Name_Id; -- Entity name if Entity parameter if present. If no Entity parameter -- was supplied, then Entity_Node is set to Empty, and the Entity_Name -- field contains the last identifier name in the Unit_Name. Entity_Scope : Access_Names; -- Static scope of the entity within the compilation unit represented by -- Unit_Name. Entity_Node : Node_Id; -- Save node of entity argument, for posting error messages. Set -- to Empty if there is no entity argument. Parameter_Types : Access_Names; -- Set to set of names given for parameter types. If no parameter -- types argument is present, this argument is set to null. Result_Type : Name_Id; -- Result type name if Result_Types parameter present, No_Name if not Source_Location : Name_Id; -- String describing the source location of subprogram defining name if -- Source_Location parameter present, No_Name if not Hash_Link : Access_Elim_Data; -- Link for hash table use Homonym : Access_Elim_Data; -- Pointer to next entry with same key Prag : Node_Id; -- Node_Id for Eliminate pragma end record; ---------------- -- Hash_Table -- ---------------- -- Setup hash table using the Entity_Name field as the hash key subtype Element is Elim_Data; subtype Elmt_Ptr is Access_Elim_Data; subtype Key is Name_Id; type Header_Num is range 0 .. 1023; Null_Ptr : constant Elmt_Ptr := null; ---------------------- -- Hash_Subprograms -- ---------------------- package Hash_Subprograms is function Equal (F1, F2 : Key) return Boolean; pragma Inline (Equal); function Get_Key (E : Elmt_Ptr) return Key; pragma Inline (Get_Key); function Hash (F : Key) return Header_Num; pragma Inline (Hash); function Next (E : Elmt_Ptr) return Elmt_Ptr; pragma Inline (Next); procedure Set_Next (E : Elmt_Ptr; Next : Elmt_Ptr); pragma Inline (Set_Next); end Hash_Subprograms; package body Hash_Subprograms is ----------- -- Equal -- ----------- function Equal (F1, F2 : Key) return Boolean is begin return F1 = F2; end Equal; ------------- -- Get_Key -- ------------- function Get_Key (E : Elmt_Ptr) return Key is begin return E.Entity_Name; end Get_Key; ---------- -- Hash -- ---------- function Hash (F : Key) return Header_Num is begin return Header_Num (Int (F) mod 1024); end Hash; ---------- -- Next -- ---------- function Next (E : Elmt_Ptr) return Elmt_Ptr is begin return E.Hash_Link; end Next; -------------- -- Set_Next -- -------------- procedure Set_Next (E : Elmt_Ptr; Next : Elmt_Ptr) is begin E.Hash_Link := Next; end Set_Next; end Hash_Subprograms; ------------ -- Tables -- ------------ -- The following table records the data for each pragma, using the -- entity name as the hash key for retrieval. Entries in this table -- are set by Process_Eliminate_Pragma and read by Check_Eliminated. package Elim_Hash_Table is new Static_HTable ( Header_Num => Header_Num, Element => Element, Elmt_Ptr => Elmt_Ptr, Null_Ptr => Null_Ptr, Set_Next => Hash_Subprograms.Set_Next, Next => Hash_Subprograms.Next, Key => Key, Get_Key => Hash_Subprograms.Get_Key, Hash => Hash_Subprograms.Hash, Equal => Hash_Subprograms.Equal); -- The following table records entities for subprograms that are -- eliminated, and corresponding eliminate pragmas that caused the -- elimination. Entries in this table are set by Check_Eliminated -- and read by Eliminate_Error_Msg. type Elim_Entity_Entry is record Prag : Node_Id; Subp : Entity_Id; end record; package Elim_Entities is new Table.Table ( Table_Component_Type => Elim_Entity_Entry, Table_Index_Type => Name_Id'Base, Table_Low_Bound => First_Name_Id, Table_Initial => 50, Table_Increment => 200, Table_Name => "Elim_Entries"); ---------------------- -- Check_Eliminated -- ---------------------- procedure Check_Eliminated (E : Entity_Id) is Elmt : Access_Elim_Data; Scop : Entity_Id; Form : Entity_Id; Up : Nat; begin if No_Elimination then return; -- Elimination of objects and types is not implemented yet elsif not Is_Subprogram (E) then return; end if; -- Loop through homonyms for this key Elmt := Elim_Hash_Table.Get (Chars (E)); while Elmt /= null loop Check_Homonyms : declare procedure Set_Eliminated; -- Set current subprogram entity as eliminated -------------------- -- Set_Eliminated -- -------------------- procedure Set_Eliminated is Overridden : Entity_Id; begin if Is_Dispatching_Operation (E) then -- If an overriding dispatching primitive is eliminated then -- its parent must have been eliminated. If the parent is an -- inherited operation, check the operation that it renames, -- because flag Eliminated is only set on source operations. Overridden := Overridden_Operation (E); if Present (Overridden) and then not Comes_From_Source (Overridden) and then Present (Alias (Overridden)) then Overridden := Alias (Overridden); end if; if Present (Overridden) and then not Is_Eliminated (Overridden) and then not Is_Abstract_Subprogram (Overridden) then Error_Msg_Name_1 := Chars (E); Error_Msg_N ("cannot eliminate subprogram %", E); return; end if; end if; Set_Is_Eliminated (E); Elim_Entities.Append ((Prag => Elmt.Prag, Subp => E)); end Set_Eliminated; -- Start of processing for Check_Homonyms begin -- First we check that the name of the entity matches if Elmt.Entity_Name /= Chars (E) then goto Continue; end if; -- Find enclosing unit, and verify that its name and those of its -- parents match. Scop := Cunit_Entity (Current_Sem_Unit); -- Now see if compilation unit matches Up := Elmt.Unit_Name'Last; -- If we are within a subunit, the name in the pragma has been -- parsed as a child unit, but the current compilation unit is in -- fact the parent in which the subunit is embedded. We must skip -- the first name which is that of the subunit to match the pragma -- specification. Body may be that of a package or subprogram. declare Par : Node_Id; begin Par := Parent (E); while Present (Par) loop if Nkind (Par) = N_Subunit then if Chars (Defining_Entity (Proper_Body (Par))) = Elmt.Unit_Name (Up) then Up := Up - 1; exit; else goto Continue; end if; end if; Par := Parent (Par); end loop; end; for J in reverse Elmt.Unit_Name'First .. Up loop if Elmt.Unit_Name (J) /= Chars (Scop) then goto Continue; end if; Scop := Scope (Scop); if Scop /= Standard_Standard and then J = 1 then goto Continue; end if; end loop; if Scop /= Standard_Standard then goto Continue; end if; if Present (Elmt.Entity_Node) and then Elmt.Entity_Scope /= null then -- Check that names of enclosing scopes match. Skip blocks and -- wrapper package of subprogram instances, which do not appear -- in the pragma. Scop := Scope (E); for J in reverse Elmt.Entity_Scope'Range loop while Ekind (Scop) = E_Block or else (Ekind (Scop) = E_Package and then Is_Wrapper_Package (Scop)) loop Scop := Scope (Scop); end loop; if Elmt.Entity_Scope (J) /= Chars (Scop) then if Ekind (Scop) /= E_Protected_Type or else Comes_From_Source (Scop) then goto Continue; -- For simple protected declarations, retrieve the source -- name of the object, which appeared in the Eliminate -- pragma. else declare Decl : constant Node_Id := Original_Node (Parent (Scop)); begin if Elmt.Entity_Scope (J) /= Chars (Defining_Identifier (Decl)) then if J > 0 then null; end if; goto Continue; end if; end; end if; end if; Scop := Scope (Scop); end loop; end if; -- If given entity is a library level subprogram and pragma had a -- single parameter, a match. if Is_Compilation_Unit (E) and then Is_Subprogram (E) and then No (Elmt.Entity_Node) then Set_Eliminated; return; -- Check for case of type or object with two parameter case elsif (Is_Type (E) or else Is_Object (E)) and then Elmt.Result_Type = No_Name and then Elmt.Parameter_Types = null then Set_Eliminated; return; -- Check for case of subprogram elsif Ekind (E) in E_Function | E_Procedure then -- If Source_Location present, then see if it matches if Elmt.Source_Location /= No_Name then Get_Name_String (Elmt.Source_Location); declare Sloc_Trace : constant String := Name_Buffer (1 .. Name_Len); Idx : Natural := Sloc_Trace'First; -- Index in Sloc_Trace, if equals to 0, then we have -- completely traversed Sloc_Trace Last : constant Natural := Sloc_Trace'Last; P : Source_Ptr; Sindex : Source_File_Index; function File_Name_Match return Boolean; -- This function is supposed to be called when Idx points -- to the beginning of the new file name, and Name_Buffer -- is set to contain the name of the proper source file -- from the chain corresponding to the Sloc of E. First -- it checks that these two files have the same name. If -- this check is successful, moves Idx to point to the -- beginning of the column number. function Line_Num_Match return Boolean; -- This function is supposed to be called when Idx points -- to the beginning of the column number, and P is -- set to point to the proper Sloc the chain -- corresponding to the Sloc of E. First it checks that -- the line number Idx points on and the line number -- corresponding to P are the same. If this check is -- successful, moves Idx to point to the beginning of -- the next file name in Sloc_Trace. If there is no file -- name any more, Idx is set to 0. function Different_Trace_Lengths return Boolean; -- From Idx and P, defines if there are in both traces -- more element(s) in the instantiation chains. Returns -- False if one trace contains more element(s), but -- another does not. If both traces contains more -- elements (that is, the function returns False), moves -- P ahead in the chain corresponding to E, recomputes -- Sindex and sets the name of the corresponding file in -- Name_Buffer function Skip_Spaces return Natural; -- If Sloc_Trace (Idx) is not space character, returns -- Idx. Otherwise returns the index of the nearest -- non-space character in Sloc_Trace to the right of Idx. -- Returns 0 if there is no such character. ----------------------------- -- Different_Trace_Lengths -- ----------------------------- function Different_Trace_Lengths return Boolean is begin P := Instantiation (Sindex); if (P = No_Location and then Idx /= 0) or else (P /= No_Location and then Idx = 0) then return True; else if P /= No_Location then Sindex := Get_Source_File_Index (P); Get_Name_String (File_Name (Sindex)); end if; return False; end if; end Different_Trace_Lengths; --------------------- -- File_Name_Match -- --------------------- function File_Name_Match return Boolean is Tmp_Idx : Natural; End_Idx : Natural; begin if Idx = 0 then return False; end if; -- Find first colon. If no colon, then return False. -- If there is a colon, Tmp_Idx is set to point just -- before the colon. Tmp_Idx := Idx - 1; loop if Tmp_Idx >= Last then return False; elsif Sloc_Trace (Tmp_Idx + 1) = ':' then exit; else Tmp_Idx := Tmp_Idx + 1; end if; end loop; -- Find last non-space before this colon. If there is -- no space character before this colon, then return -- False. Otherwise, End_Idx is set to point to this -- non-space character. End_Idx := Tmp_Idx; loop if End_Idx < Idx then return False; elsif Sloc_Trace (End_Idx) /= ' ' then exit; else End_Idx := End_Idx - 1; end if; end loop; -- Now see if file name matches what is in Name_Buffer -- and if so, step Idx past it and return True. If the -- name does not match, return False. if Sloc_Trace (Idx .. End_Idx) = Name_Buffer (1 .. Name_Len) then Idx := Tmp_Idx + 2; Idx := Skip_Spaces; return True; else return False; end if; end File_Name_Match; -------------------- -- Line_Num_Match -- -------------------- function Line_Num_Match return Boolean is N : Nat := 0; begin if Idx = 0 then return False; end if; while Idx <= Last and then Sloc_Trace (Idx) in '0' .. '9' loop N := N * 10 + (Character'Pos (Sloc_Trace (Idx)) - Character'Pos ('0')); Idx := Idx + 1; end loop; if Get_Physical_Line_Number (P) = Physical_Line_Number (N) then while Idx <= Last and then Sloc_Trace (Idx) /= '[' loop Idx := Idx + 1; end loop; if Idx <= Last then pragma Assert (Sloc_Trace (Idx) = '['); Idx := Idx + 1; Idx := Skip_Spaces; else Idx := 0; end if; return True; else return False; end if; end Line_Num_Match; ----------------- -- Skip_Spaces -- ----------------- function Skip_Spaces return Natural is Res : Natural; begin Res := Idx; while Sloc_Trace (Res) = ' ' loop Res := Res + 1; if Res > Last then Res := 0; exit; end if; end loop; return Res; end Skip_Spaces; begin P := Sloc (E); Sindex := Get_Source_File_Index (P); Get_Name_String (File_Name (Sindex)); Idx := Skip_Spaces; while Idx > 0 loop if not File_Name_Match then goto Continue; elsif not Line_Num_Match then goto Continue; end if; if Different_Trace_Lengths then goto Continue; end if; end loop; end; end if; -- If we have a Result_Type, then we must have a function with -- the proper result type. if Elmt.Result_Type /= No_Name then if Ekind (E) /= E_Function or else Chars (Etype (E)) /= Elmt.Result_Type then goto Continue; end if; end if; -- If we have Parameter_Types, they must match if Elmt.Parameter_Types /= null then Form := First_Formal (E); if No (Form) and then Elmt.Parameter_Types'Length = 1 and then Elmt.Parameter_Types (1) = No_Name then -- Parameterless procedure matches null; elsif Elmt.Parameter_Types = null then goto Continue; else for J in Elmt.Parameter_Types'Range loop if No (Form) or else Chars (Etype (Form)) /= Elmt.Parameter_Types (J) then goto Continue; else Next_Formal (Form); end if; end loop; if Present (Form) then goto Continue; end if; end if; end if; -- If we fall through, this is match Set_Eliminated; return; end if; end Check_Homonyms; <<Continue>> Elmt := Elmt.Homonym; end loop; return; end Check_Eliminated; ------------------------------------- -- Check_For_Eliminated_Subprogram -- ------------------------------------- procedure Check_For_Eliminated_Subprogram (N : Node_Id; S : Entity_Id) is Ultimate_Subp : constant Entity_Id := Ultimate_Alias (S); Enclosing_Subp : Entity_Id; begin -- No check needed within a default expression for a formal, since this -- is not really a use, and the expression (a call or attribute) may -- never be used if the enclosing subprogram is itself eliminated. if In_Spec_Expression then return; end if; if Is_Eliminated (Ultimate_Subp) and then not Inside_A_Generic and then not Is_Generic_Unit (Cunit_Entity (Current_Sem_Unit)) then Enclosing_Subp := Current_Subprogram; while Present (Enclosing_Subp) loop if Is_Eliminated (Enclosing_Subp) then return; end if; Enclosing_Subp := Enclosing_Subprogram (Enclosing_Subp); end loop; -- Emit error, unless we are within an instance body and the expander -- is disabled, indicating an instance within an enclosing generic. -- In an instance, the ultimate alias is an internal entity, so place -- the message on the original subprogram. if In_Instance_Body and then not Expander_Active then null; elsif Comes_From_Source (Ultimate_Subp) then Eliminate_Error_Msg (N, Ultimate_Subp); else Eliminate_Error_Msg (N, S); end if; end if; end Check_For_Eliminated_Subprogram; ------------------------- -- Eliminate_Error_Msg -- ------------------------- procedure Eliminate_Error_Msg (N : Node_Id; E : Entity_Id) is begin for J in Elim_Entities.First .. Elim_Entities.Last loop if E = Elim_Entities.Table (J).Subp then Error_Msg_Sloc := Sloc (Elim_Entities.Table (J).Prag); Error_Msg_NE ("cannot reference subprogram & eliminated #", N, E); return; end if; end loop; -- If this is an internal operation generated for a protected operation, -- its name does not match the source name, so just report the error. if not Comes_From_Source (E) and then Present (First_Entity (E)) and then Is_Concurrent_Record_Type (Etype (First_Entity (E))) then Error_Msg_NE ("cannot reference eliminated protected subprogram&", N, E); -- Otherwise should not fall through, entry should be in table else Error_Msg_NE ("subprogram& is called but its alias is eliminated", N, E); -- raise Program_Error; end if; end Eliminate_Error_Msg; ---------------- -- Initialize -- ---------------- procedure Initialize is begin Elim_Hash_Table.Reset; Elim_Entities.Init; No_Elimination := True; end Initialize; ------------------------------ -- Process_Eliminate_Pragma -- ------------------------------ procedure Process_Eliminate_Pragma (Pragma_Node : Node_Id; Arg_Unit_Name : Node_Id; Arg_Entity : Node_Id; Arg_Parameter_Types : Node_Id; Arg_Result_Type : Node_Id; Arg_Source_Location : Node_Id) is Data : constant Access_Elim_Data := new Elim_Data; -- Build result data here Elmt : Access_Elim_Data; Num_Names : Nat := 0; -- Number of names in unit name Lit : Node_Id; Arg_Ent : Entity_Id; Arg_Uname : Node_Id; function OK_Selected_Component (N : Node_Id) return Boolean; -- Test if N is a selected component with all identifiers, or a selected -- component whose selector is an operator symbol. As a side effect -- if result is True, sets Num_Names to the number of names present -- (identifiers, and operator if any). --------------------------- -- OK_Selected_Component -- --------------------------- function OK_Selected_Component (N : Node_Id) return Boolean is begin if Nkind (N) = N_Identifier or else Nkind (N) = N_Operator_Symbol then Num_Names := Num_Names + 1; return True; elsif Nkind (N) = N_Selected_Component then return OK_Selected_Component (Prefix (N)) and then OK_Selected_Component (Selector_Name (N)); else return False; end if; end OK_Selected_Component; -- Start of processing for Process_Eliminate_Pragma begin Data.Prag := Pragma_Node; Error_Msg_Name_1 := Name_Eliminate; -- Process Unit_Name argument if Nkind (Arg_Unit_Name) = N_Identifier then Data.Unit_Name := new Names'(1 => Chars (Arg_Unit_Name)); Num_Names := 1; elsif OK_Selected_Component (Arg_Unit_Name) then Data.Unit_Name := new Names (1 .. Num_Names); Arg_Uname := Arg_Unit_Name; for J in reverse 2 .. Num_Names loop Data.Unit_Name (J) := Chars (Selector_Name (Arg_Uname)); Arg_Uname := Prefix (Arg_Uname); end loop; Data.Unit_Name (1) := Chars (Arg_Uname); else Error_Msg_N ("wrong form for Unit_Name parameter of pragma%", Arg_Unit_Name); return; end if; -- Process Entity argument if Present (Arg_Entity) then Num_Names := 0; if Nkind (Arg_Entity) = N_Identifier or else Nkind (Arg_Entity) = N_Operator_Symbol then Data.Entity_Name := Chars (Arg_Entity); Data.Entity_Node := Arg_Entity; Data.Entity_Scope := null; elsif OK_Selected_Component (Arg_Entity) then Data.Entity_Scope := new Names (1 .. Num_Names - 1); Data.Entity_Name := Chars (Selector_Name (Arg_Entity)); Data.Entity_Node := Arg_Entity; Arg_Ent := Prefix (Arg_Entity); for J in reverse 2 .. Num_Names - 1 loop Data.Entity_Scope (J) := Chars (Selector_Name (Arg_Ent)); Arg_Ent := Prefix (Arg_Ent); end loop; Data.Entity_Scope (1) := Chars (Arg_Ent); elsif Is_Config_Static_String (Arg_Entity) then Data.Entity_Name := Name_Find; Data.Entity_Node := Arg_Entity; else return; end if; else Data.Entity_Node := Empty; Data.Entity_Name := Data.Unit_Name (Num_Names); end if; -- Process Parameter_Types argument if Present (Arg_Parameter_Types) then -- Here for aggregate case if Nkind (Arg_Parameter_Types) = N_Aggregate then Data.Parameter_Types := new Names (1 .. List_Length (Expressions (Arg_Parameter_Types))); Lit := First (Expressions (Arg_Parameter_Types)); for J in Data.Parameter_Types'Range loop if Is_Config_Static_String (Lit) then Data.Parameter_Types (J) := Name_Find; Next (Lit); else return; end if; end loop; -- Otherwise we must have case of one name, which looks like a -- parenthesized literal rather than an aggregate. elsif Paren_Count (Arg_Parameter_Types) /= 1 then Error_Msg_N ("wrong form for argument of pragma Eliminate", Arg_Parameter_Types); return; elsif Is_Config_Static_String (Arg_Parameter_Types) then String_To_Name_Buffer (Strval (Arg_Parameter_Types)); if Name_Len = 0 then -- Parameterless procedure Data.Parameter_Types := new Names'(1 => No_Name); else Data.Parameter_Types := new Names'(1 => Name_Find); end if; else return; end if; end if; -- Process Result_Types argument if Present (Arg_Result_Type) then if Is_Config_Static_String (Arg_Result_Type) then Data.Result_Type := Name_Find; else return; end if; -- Here if no Result_Types argument else Data.Result_Type := No_Name; end if; -- Process Source_Location argument if Present (Arg_Source_Location) then if Is_Config_Static_String (Arg_Source_Location) then Data.Source_Location := Name_Find; else return; end if; else Data.Source_Location := No_Name; end if; Elmt := Elim_Hash_Table.Get (Hash_Subprograms.Get_Key (Data)); -- If we already have an entry with this same key, then link -- it into the chain of entries for this key. if Elmt /= null then Data.Homonym := Elmt.Homonym; Elmt.Homonym := Data; -- Otherwise create a new entry else Elim_Hash_Table.Set (Data); end if; No_Elimination := False; end Process_Eliminate_Pragma; end Sem_Elim;
reznikmm/matreshka
Ada
6,740
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Form.Date_Elements is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Form_Date_Element_Node is begin return Self : Form_Date_Element_Node do Matreshka.ODF_Form.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Form_Prefix); end return; end Create; ---------------- -- Enter_Node -- ---------------- overriding procedure Enter_Node (Self : not null access Form_Date_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then ODF.DOM.Visitors.Abstract_ODF_Visitor'Class (Visitor).Enter_Form_Date (ODF.DOM.Form_Date_Elements.ODF_Form_Date_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Enter_Node (Visitor, Control); end if; end Enter_Node; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Form_Date_Element_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Date_Element; end Get_Local_Name; ---------------- -- Leave_Node -- ---------------- overriding procedure Leave_Node (Self : not null access Form_Date_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then ODF.DOM.Visitors.Abstract_ODF_Visitor'Class (Visitor).Leave_Form_Date (ODF.DOM.Form_Date_Elements.ODF_Form_Date_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Leave_Node (Visitor, Control); end if; end Leave_Node; ---------------- -- Visit_Node -- ---------------- overriding procedure Visit_Node (Self : not null access Form_Date_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Iterator in ODF.DOM.Iterators.Abstract_ODF_Iterator'Class then ODF.DOM.Iterators.Abstract_ODF_Iterator'Class (Iterator).Visit_Form_Date (Visitor, ODF.DOM.Form_Date_Elements.ODF_Form_Date_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Visit_Node (Iterator, Visitor, Control); end if; end Visit_Node; begin Matreshka.DOM_Documents.Register_Element (Matreshka.ODF_String_Constants.Form_URI, Matreshka.ODF_String_Constants.Date_Element, Form_Date_Element_Node'Tag); end Matreshka.ODF_Form.Date_Elements;
tum-ei-rcs/StratoX
Ada
3,379
adb
with System.Machine_Reset; with Ada.Real_Time; use Ada.Real_Time; with System.Task_Primitives.Operations; with Config.Tasking; with Bounded_Image; use Bounded_Image; with Logger; with NVRAM; with HIL; with Interfaces; use Interfaces; with Unchecked_Conversion; -- @summary Catches all exceptions, logs them to NVRAM and reboots. package body Crash with SPARK_Mode => Off is -- XXX! SPARK must be off here, otherwise this function is not being implemented. -- Reasons see below. function To_Unsigned is new Unchecked_Conversion (System.Address, Unsigned_32); -- SPARK RM 6.5.1: a call to a non-returning procedure introduces the -- obligation to prove that the statement will not be executed. -- This is the same as a run-time check that fails unconditionally. -- RM 11.3: ...must provably never be executed. procedure Last_Chance_Handler(location : System.Address; line : Integer) is now : constant Time := Clock; line16 : constant Unsigned_16 := (if line >= 0 and line <= Integer (Unsigned_16'Last) then Unsigned_16 (line) else Unsigned_16'Last); begin -- if the task which called this handler is not flight critical, -- silently hang here. as an effect, the system lives on without this task. declare use System.Task_Primitives.Operations; prio : constant ST.Extended_Priority := Get_Priority (Self); begin if prio < Config.Tasking.TASK_PRIO_FLIGHTCRITICAL then Logger.log (Logger.ERROR, "Non-critical task crashed"); loop null; end loop; -- FIXME: there exists a "sleep infinite" procedure...just can't find it -- but that'll do. at least it doesn't block flight-critical tasks end if; end; -- first log to NVRAM declare ba : constant HIL.Byte_Array := HIL.toBytes (line16); begin NVRAM.Store (NVRAM.VAR_EXCEPTION_LINE_L, ba (1)); NVRAM.Store (NVRAM.VAR_EXCEPTION_LINE_H, ba (2)); NVRAM.Store (NVRAM.VAR_EXCEPTION_ADDR_A, To_Unsigned (location)); end; -- now write to console (which might fail) Logger.log (Logger.ERROR, "Exception: Addr: " & Unsigned_Img (To_Unsigned (location)) & ", line " & Integer_Img (line)); -- wait until write finished (interrupt based) delay until now + Milliseconds(80); -- DEBUG ONLY: hang here to let us read the console output -- loop -- null; -- end loop; -- XXX! A last chance handler must always terminate or suspend the -- thread that executes the handler. Suspending cannot be used here, -- because we cannot distinguish the tasks (?). So we reboot. -- Abruptly stop the program. -- On bareboard platform, this returns to the monitor or reset the board. -- In the context of an OS, this terminates the process. System.Machine_Reset.Stop; -- this is a non-returning function. SPARK assumes it is never executed. -- The following junk raise of Program_Error is required because -- this is a No_Return function, and unfortunately Suspend can -- return (although this particular call won't). raise Program_Error; end Last_Chance_Handler; end Crash;
jhumphry/PRNG_Zoo
Ada
1,521
ads
-- -- PRNG Zoo -- Copyright (c) 2014 - 2015, James Humphry -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -- OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -- PERFORMANCE OF THIS SOFTWARE. with AUnit; use AUnit; with AUnit.Test_Cases; use AUnit.Test_Cases; with PRNG_Zoo.LFib; with PRNGTests_Suite.Sanity_Checks; package PRNGTests_Suite.LFib_Tests is type LFib_Test is new Test_Cases.Test_Case with null record; procedure Register_Tests (T: in out LFib_Test); function Name (T : LFib_Test) return Test_String; procedure Set_Up (T : in out LFib_Test); package Example_LFib is new LFib.Generic_LFib(j => 24, k => 55, Op => "+"); -- Test Routines: procedure Sanity_Check_LFib is new PRNGTests_Suite.Sanity_Checks(P => Example_LFib.LFib); end PRNGTests_Suite.LFib_Tests;
BrickBot/Bound-T-H8-300
Ada
62,065
adb
-- Bounds.Looping (body) -- -- A component of the Bound-T Worst-Case Execution Time Tool. -- ------------------------------------------------------------------------------- -- Copyright (c) 1999 .. 2015 Tidorum Ltd -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- -- This software is provided by the copyright holders and contributors "as is" and -- any express or implied warranties, including, but not limited to, the implied -- warranties of merchantability and fitness for a particular purpose are -- disclaimed. In no event shall the copyright owner or contributors be liable for -- any direct, indirect, incidental, special, exemplary, or consequential damages -- (including, but not limited to, procurement of substitute goods or services; -- loss of use, data, or profits; or business interruption) however caused and -- on any theory of liability, whether in contract, strict liability, or tort -- (including negligence or otherwise) arising in any way out of the use of this -- software, even if advised of the possibility of such damage. -- -- Other modules (files) of this software composition should contain their -- own copyright statements, which may have different copyright and usage -- conditions. The above conditions apply to this file. ------------------------------------------------------------------------------- -- -- $Revision: 1.23 $ -- $Date: 2015/10/24 20:05:46 $ -- -- $Log: bounds-looping.adb,v $ -- Revision 1.23 2015/10/24 20:05:46 niklas -- Moved to free licence. -- -- Revision 1.22 2012-02-13 17:52:19 niklas -- BT-CH-0230: Options -max_loop and -max_stack for spurious bounds. -- -- Revision 1.21 2011-09-08 08:56:06 niklas -- Extended function Step_Bounds to swap small negative steps, under -- control of the new options "sw_neg_step" and "warn sw_neg_step". -- -- Revision 1.20 2009-11-27 11:28:06 niklas -- BT-CH-0184: Bit-widths, Word_T, failed modular analysis. -- -- Revision 1.19 2009-10-07 19:26:09 niklas -- BT-CH-0183: Cell-sets are a tagged-type class. -- -- Revision 1.18 2009-08-16 13:34:57 niklas -- Corrected description of exceptions from General_Procedure. -- -- Revision 1.17 2009-01-18 08:05:15 niklas -- Removed unused context clauses. -- -- Revision 1.16 2008/09/24 08:38:51 niklas -- BT-CH-0146: Assertions on "loop starts <bound> times". -- BT-CH-0146: Loop-repeat assertions set both lower and upper bound. -- BT-CH-0146: Report locations of contradictory "count" assertions. -- BT-CH-0146: Contradictory "count" assertions imply infeasibility. -- -- Revision 1.15 2008/05/03 09:22:06 niklas -- BT-CH-0126: Combining joint-counter and each-counter analysis. -- -- Revision 1.14 2008/04/28 08:40:10 niklas -- BT-CH-0125: Fix loop-until-equal analysis. -- -- Revision 1.13 2008/04/26 19:19:43 niklas -- BT-CH-0124: Joint loop counters and induction variables. -- -- Revision 1.12 2007/12/17 13:54:34 niklas -- BT-CH-0098: Assertions on stack usage and final stack height, etc. -- -- Revision 1.11 2006/10/30 19:13:55 niklas -- BT-CH-0032. -- -- Revision 1.10 2006/02/06 21:14:40 niklas -- Removed dead warning from Assert_Repeat_Zer_Times. -- -- Revision 1.9 2006/02/06 14:23:09 niklas -- Corrected Bound_Asserted_Loop and subprocedures to handle -- eternal loops separately. It is now possible to assert one -- repetition for an eternal loop and keep the loop feasible. -- -- Revision 1.8 2005/10/20 11:28:28 niklas -- BT-CH-0015. -- -- Revision 1.7 2005/09/20 11:55:46 niklas -- BT-CH-0010. -- -- Revision 1.6 2005/09/17 14:42:04 niklas -- BT-CH-0009. -- -- Revision 1.5 2005/06/29 20:01:31 niklas -- Added Repeat_Zero_Times to extend the checks and warnings -- for unreachable parts of zero-repeat loops. -- -- Revision 1.4 2005/06/29 13:00:01 niklas -- Added optional (-warn reach) warnings about unreachable and -- unrepeatable loops. -- -- Revision 1.3 2005/06/28 08:35:24 niklas -- Updated for changes in Bounds.Opt. -- -- Revision 1.2 2005/02/19 20:34:55 niklas -- BT-CH-0003. -- -- Revision 1.1 2005/02/16 21:11:38 niklas -- BT-CH-0002. -- with Arithmetic; with Bounds.Looping.Opt; with Flow.Computation; with Flow.Execution; with Flow.Pruning; with Flow.Pruning.Opt; with Output; with Storage.Bounds; package body Bounds.Looping is procedure Assert_Infeasible_Loop ( Luup : in Loops.Loop_T; Model : in Flow.Computation.Model_Handle_T) -- -- Special actions for a loop that is found to be unreachable. -- is begin Flow.Computation.Mark_Infeasible ( Luup => Luup, Under => Model.all); end Assert_Infeasible_Loop; procedure Bound_Asserted_Start ( Luup : in Loops.Loop_T; Count : in Flow.Execution.Bound_T; Exec_Bounds : in Programs.Execution.Bounds_Ref; Infeasible : in out Boolean) -- -- Bounds the number of starts of the given Luup with an asserted -- start Count, within the given Execution Bounds. If the number of -- starts is zero, the loop-head is marked infeasible and Infeasible -- is returned as True, otherwise it is returned unchanged. If the -- loop starts at the entry point of the subprogram, but the Count -- does not allow one start, a void "start" bound is put in the -- execution bounds to mark this contradiction, and an error is -- issued. -- is use type Flow.Execution.Count_T; use type Flow.Node_T; Loop_Mark : Output.Nest_Mark_T; -- For the locus of the loop. begin Loop_Mark := Output.Nest (Programs.Execution.Locus (Luup, Exec_Bounds)); if Count.Max < 1 then -- The loop becomes infeasible. Output.Warning ("Unreachable loop (asserted to start zero times)."); Assert_Infeasible_Loop ( Luup => Luup, Model => Programs.Execution.Computation (Exec_Bounds)); Infeasible := True; elsif Loops.Head_Node (Luup) = Flow.Entry_Node (Programs.Execution.Flow_Graph (Exec_Bounds)) and then not Flow.Execution.Is_In (1, Count) then -- The loop starts at the entry point of the subprogram, -- which means that it starts exactly once, but the -- assertion forbids one start. This is contradictory. Output.Error ( "Loop at entry point starts once, not " & Flow.Execution.Image (Count) & " times."); Programs.Execution.Bound_Loop_Starts ( Luup => Luup, Starts => Flow.Execution.Impossible, Within => Exec_Bounds); else -- Nothing special, use Count as is. Programs.Execution.Bound_Loop_Starts ( Luup => Luup, Starts => Count, Within => Exec_Bounds); end if; Output.Unnest (Loop_Mark); end Bound_Asserted_Start; procedure Bound_Asserted_Starts ( Luups : in Loops.Loop_List_T; Asserts : in Assertions.Assertion_Map_T; Exec_Bounds : in Programs.Execution.Bounds_Ref) is Some_Infeasible_Parts : Boolean := False; -- Whether some flow-graph parts became infeasible because of -- the loop-start assertions. Count : Flow.Execution.Bound_T; -- Asserted bounds (if any) on the starts of a loop. begin for L in Luups'Range loop Count := Assertions.Loop_Start ( Luup => Luups(L), Asserts => Asserts); if Flow.Execution.Bounded (Count) then -- There is a start-assertion for this loop. Bound_Asserted_Start ( Luup => Luups(L), Count => Count, Exec_Bounds => Exec_Bounds, Infeasible => Some_Infeasible_Parts); end if; end loop; if Some_Infeasible_Parts then -- Let the infeasibility spread. Programs.Execution.Prune_Flow (Exec_Bounds); end if; end Bound_Asserted_Starts; procedure Assert_Repeat_Zero_Times ( Luup : in Loops.Loop_T; Model : in Flow.Computation.Model_Handle_T) -- -- Special actions for a loop that is asserted to repeat zero times -- through the repeat-edges. The repeat edges are marked infeasible. -- is begin Flow.Computation.Mark_Infeasible ( Edges => Flow.Computation.Repeat_Edges (Luup, Model.all), Under => Model.all); end Assert_Repeat_Zero_Times; procedure Assert_Repeat_Neck_Zero_Times ( Luup : in Loops.Loop_T; Model : in Flow.Computation.Model_Handle_T) -- -- Special actions for a loop that is asserted to repeat zero times -- through the loop-neck. -- -- If no exit-edges leave the loop-head, asserting zero repetitions -- makes the loop-head unreachable. This always evokes a warning. -- -- If all repeat-edges start from the loop-head, the entire loop -- consists of the loop-head node. This means that the loop body is -- executed once even when zero repetitions are asserted. This always -- evokes a warning. -- -- Otherwise, a warning is optionally issued that the loop body -- is unreachable. -- -- In any case, the neck edges are marked infeasible. -- is use type Flow.Node_T; Head : constant Flow.Node_T := Loops.Head_Node (Luup); -- The loop-head node. Exits : constant Flow.Edge_List_T := Flow.Computation.Exit_Edges (Luup, Model.all); -- The feasible exit edges. Repeats : constant Flow.Edge_List_T := Flow.Computation.Repeat_Edges (Luup, Model.all); -- The feasible repeat edges. Head_Exits : Boolean := False; -- Whether some exit edge starts from the Head. Only_Head_Repeats : Boolean := True; -- Whether all repeat edges start from the Head. begin -- Check the sources of the exit edges: for E in Exits'Range loop if Flow.Source (Exits(E)) = Head then -- This edge exits the loop from the head node. -- The edge will not be marked infeasible, so the head node -- may also remain feasible. Head_Exits := True; end if; end loop; -- Check the sources of the repeat edges: for R in Repeats'Range loop if Flow.Source (Repeats(R)) /= Head then -- This edge repeats the loop from a non-head node. -- This means that there is a non-null "real" loop body -- in addition to the head node. Only_Head_Repeats := False; end if; end loop; -- Warnings if indicated: if not Head_Exits then Output.Warning ( "Unreachable loop (asserted to repeat zero times)."); elsif Only_Head_Repeats then Output.Warning ( "Loop body executes once (asserted to repeat zero times)."); elsif Flow.Pruning.Opt.Warn_Unreachable then Output.Warning ( "Unreachable loop body (asserted to repeat zero times)."); end if; Flow.Computation.Mark_Infeasible ( Edges => Flow.Computation.Neck_Edges (Luup, Model.all), Under => Model.all); end Assert_Repeat_Neck_Zero_Times; procedure Bound_Asserted_Repeat ( Luup : in Loops.Loop_T; Count : in Flow.Execution.Bound_T; Exec_Bounds : in Programs.Execution.Bounds_Ref; Infeasible : in out Boolean) -- -- Bounds the given Luup with an asserted repetition Count, within -- the given Execution Bounds. If this causes some flow-graph parts -- to be marked infeasible (for example, for zero repetitions) then -- Infeasible is returned as True, otherwise it is returned unchanged. -- is use type Flow.Execution.Count_T; Model : constant Flow.Computation.Model_Handle_T := Programs.Execution.Computation (Exec_Bounds); -- The computation model in use. -- We may mark some edges as infeasible in this model. Loop_Mark : Output.Nest_Mark_T; -- For the locus of the loop. begin -- There are three cases: -- -- > Eternal loops: for Count <= 0 the loop becomes infeasible, -- otherwise the repeat edge(s) are bounded to Count. In the -- later IPET stage one execution of the repeat edge(s) can -- escape (exit the program) without entering the loop head. -- -- > Exit-at-end loops: for Count <= 0 the loop becomes infeasible, -- otherwise the repeat edge(s) are bounded to Count - 1 and -- become infeasible if Count = 1. -- -- > Exit-in-the middle loops: the neck edges are bounded to Count -- and become infeasible if Count <= 0. The loop-head remains -- feasible for all Count values. Loop_Mark := Output.Nest (Programs.Execution.Locus (Luup, Exec_Bounds)); if Flow.Computation.Is_Eternal (Luup, Model.all) then -- Assertions on eternal loops are interpreted differently. Output.Note ( "Loop" & Loops.Loop_Index_T'Image (Loops.Loop_Index (Luup)) & " is eternal."); if Count.Max <= 0 then -- The loop becomes infeasible. Output.Warning ( "Unreachable eternal loop (asserted to repeat zero times)."); Assert_Infeasible_Loop ( Luup => Luup, Model => Model); Infeasible := True; else -- The loop remains feasible and we can place a repetition -- bound on the repeat-edges. Note that this bound is Count, -- not Count - 1, but in the IPET stage we will let one -- execution escape from the repeat edges, to terminate -- the measured execution. Programs.Execution.Bound_Loop_Repeats ( Luup => Luup, Repeats => Count, Within => Exec_Bounds); end if; elsif Loops.Exits_At_End ( Luup => Luup, Within => Programs.Execution.Flow_Graph (Exec_Bounds)) then -- For a loop that exits only at the end (bottom), the -- bound can safely be reduced by one and applied to -- the repeat edges instead of to the neck. Output.Note ( "Loop" & Loops.Loop_Index_T'Image (Loops.Loop_Index (Luup)) & " exits only at its end."); if Count.Max <= 0 then -- The loop becomes infeasible. Output.Warning ( "Unreachable exit-at-end loop " & "(asserted to repeat zero times)."); Assert_Infeasible_Loop ( Luup => Luup, Model => Model); Infeasible := True; else -- The loop remains feasible (unless it is eternal) and we -- can place a reduced repetition bound on the repeat-edges. Programs.Execution.Bound_Loop_Repeats ( Luup => Luup, Repeats => ( Min => Flow.Execution.Count_T'Max (0, Count.Min - 1), Max => Count.Max - 1), Within => Exec_Bounds); if Count.Max = 1 then -- This loop-body is never repated; the repeat edges -- are infeasible. Assert_Repeat_Zero_Times ( Luup => Luup, Model => Model); Infeasible := True; end if; end if; else -- For a loop that does not exit only at the end (bottom), -- the bound is applied, as such, to the neck edges. Programs.Execution.Bound_Loop_Neck ( Luup => Luup, Count => Count, Within => Exec_Bounds); if Count.Max <= 0 then -- This loop is never entered; the neck edges are infeasible. Assert_Repeat_Neck_Zero_Times ( Luup => Luup, Model => Model); Infeasible := True; end if; end if; Output.Unnest (Loop_Mark); end Bound_Asserted_Repeat; procedure Bound_Asserted_Repeats ( Luups : in Loops.Loop_List_T; Asserts : in Assertions.Assertion_Map_T; Exec_Bounds : in Programs.Execution.Bounds_Ref) is Some_Infeasible_Parts : Boolean := False; -- Whether some flow-graph parts became infeasible because of -- the loop-repeat assertions. Count : Flow.Execution.Bound_T; -- Asserted bounds (if any) on the repetitions of a loop. begin for L in Luups'Range loop Count := Assertions.Loop_Count ( Luup => Luups(L), Asserts => Asserts); if Flow.Execution.Bounded (Count) then -- There is a repetition assertion for this loop. Bound_Asserted_Repeat ( Luup => Luups(L), Count => Count, Exec_Bounds => Exec_Bounds, Infeasible => Some_Infeasible_Parts); end if; end loop; if Some_Infeasible_Parts then -- Let the infeasibility spread. Programs.Execution.Prune_Flow (Exec_Bounds); end if; end Bound_Asserted_Repeats; -- -- Loop-bounds analysis -- Infeasible_Loop : exception; -- -- Signals that the loop under analysis is infeasible (cannot be -- entere) because the bounds on the initial values are void (the -- empty set). Unrepeatable_Loop : exception; -- -- Signals that the loop under analysis is unrepeatable (not really -- a loop) because the bounds on the values along the repeat edges -- are void (the empty set). type Loop_Vars_T (Num_Var : Natural) is record Num_Proc : Natural := 0; Num_Ind : Natural := 0; Eff_Ind : Boolean := False; Find : Natural := 0; Var : Storage.Cell_List_T(1 .. Num_Var); Ind_Var : Storage.Cell_List_T (1 .. Num_Var); Step : Storage.Bounds.Interval_List_T (1 .. Num_Var); end record; -- -- The loop-bounds analysis is based on a set of variables -- and their properties, as represented in this type. -- -- Num_Var -- The number of variables that are candidates for induction -- variables in the loop. -- Num_Proc -- The number of variables analysed for inductions so far. -- Num_Ind -- The number of induction variables found so far. -- An induction variable is a variable for which some Step -- bounds are known (but not necessarily both lower and -- upper bounds, and a zero step may be allowed). -- If Num_Proc = Num_Var, there are no more to be found. -- Eff_Ind -- Whether an effective induction variable has been found. -- An induction variable is effective if its Step bounds -- exclude a zero step (unchanged variable value). -- Find -- A cursor for finding counters in Ind_Var. -- The index of the last counter found and returned, or -- zero if none have been sought yet. Greater than Num_Ind -- if all counters have been found. -- Var -- The candidate variables, 1 .. Num_Var. -- These are the loop-variant "counter" cells. -- The cells Var(1 .. Num_Proc) have been analysed to see -- if they are induction variables. -- Ind_Var -- The induction variables found so far, 1 .. Num_Ind. -- Step -- The bounds on the step (change) for each each Ind_Var. -- Step(v) bounds the step for Ind_Var(v). function Initial_Counter_Bounds ( Initial : Calculator.Pool_T; Counter : Storage.Cell_T) return Storage.Bounds.Interval_T -- -- Bounds on the Counter cell, in the pool of Initial values -- for a loop (of all variables). -- -- May propagate Infeasible_Loop (if the Initial pool is null). -- is Result : Storage.Bounds.Interval_T; -- Guess what. begin Calculator.Comment ( Text => "Check initial value for counter candidate " & Storage.Image (Counter), Calc => Calculator.Owner_Of (Initial)); Result := Calculator.Bounds_From_Pool ( Pool => Initial, Cell => Counter); if Opt.Trace_Counters then Output.Trace (Text => "Loop-init bounds: " & Storage.Bounds.Image ( Item => Result, Name => Storage.Image (Counter)) ); end if; return Result; exception when Calculator.Null_Set_Error => -- The init pool is void: the loop seems infeasible. Output.Note ("Loop is infeasible (checking initial data)"); raise Infeasible_Loop; end Initial_Counter_Bounds; function Step_Bounds ( Var : Storage.Cell_T; Repeat : Calculator.Flux_T) return Storage.Bounds.Interval_T -- -- Bounds on the Step of the variant Variable, in the Repeat flux -- of a loop. -- -- May propagate Unrepeatable_Loop if the Repeat flux is void. -- is Step : Storage.Bounds.Interval_T; -- The result. begin Calculator.Comment ( Text => "Check step for induction candidate " & Storage.Image (Var), Calc => Calculator.Owner_Of (Repeat)); Step := Calculator.Step_From_Flux (Flux => Repeat, Cell => Var); if Opt.Trace_Counters then Output.Trace (Text => "Loop-step bounds: " & Storage.Bounds.Image ( Item => Step, Name => "step(" & Storage.Image (Var) & ')')); end if; if Opt.Swap_Small_Negative_Step and then Arithmetic.Is_Small_Negative ( Interval => Step, Width => Storage.Width_of (Var)) then if Opt.Warn_Swap_Small_Negative_Step then Output.Warning ( "Reversing sign of step for induction candidate" & Output.Field_Separator & Storage.Image (Var)); end if; Step := Arithmetic.Opposite_Sign ( Interval => Step, Width => Storage.Width_Of (Var)); if Opt.Trace_Counters then Output.Trace (Text => "Loop-step bounds, sign reversed: " & Storage.Bounds.Image ( Item => Step, Name => "step(" & Storage.Image (Var) & ')')); end if; end if; return Step; exception when Calculator.Null_Set_Error => -- The Repeat flux seems to be void. Output.Note ("Loop is unrepeatable (checking variable step)."); raise Unrepeatable_Loop; end Step_Bounds; function Repeat_Counter_Bounds ( Repeat : Calculator.Pool_T; Counter : Storage.Cell_T) return Storage.Bounds.Interval_T -- -- Bounds on the value of the Counter, in the domain of the Repeat -- flux of a loop. -- -- The Repeat parameter is the single-dimensional pool of the -- values of the Counter in the domain of the loop-repeat relation. -- -- May propagate Unrepeatable_Loop if the Repeat pool is void. -- is Result : Storage.Bounds.Interval_T; -- The result. begin Calculator.Comment ( Text => "Check repeat bounds for counter candidate " & Storage.Image (Counter), Calc => Calculator.Owner_Of (Repeat)); Result := Calculator.Bounds_Of (Repeat); if Opt.Trace_Counters then Output.Trace ( "Loop-repeat bounds: " & Storage.Bounds.Image (Result, Storage.Image (Counter))); end if; return Result; exception when Calculator.Null_Set_Error => -- The repeat flux is void: the loop seems unrepeatable. Output.Note ("Loop is unrepeatable (checking limit data)."); raise Unrepeatable_Loop; end Repeat_Counter_Bounds; procedure Find_Counters_Again (Vars : in out Loop_Vars_T) -- -- Restarts the scan for counter variables from the first variable. -- is begin Vars.Find := 0; end Find_Counters_Again; procedure Find_Next_Counter ( Repeat : in Calculator.Flux_T; Vars : in out Loop_Vars_T; Counter : out Storage.Cell_T; Step : out Storage.Bounds.Interval_T) -- -- Finds the next counter variable among the Vars, first looking -- among the known induction variables. If there are no more counters -- there, we analyse the unprocessed variables in the Vars one by -- one to see which are induction variables, and stop when we find -- an effective induction variable: a counter. -- -- If a counter if found, it is returned in Counter, with its Step -- bounds; otherwise Counter is returned as No_Cell and the Step -- bounds are undefined. -- -- All induction variables and their step bounds are also stored -- in the Vars. -- -- May propagate Unrepeatable_Loop if the Repeat flux is void. -- -- This rather complicated method is devised to support the "first" -- option, in which we accept the first loop-bound found. By finding -- counter variables one by one, we avoid the analysis of the steps -- of the remaining variables, after the first loop-bound is found. -- is use Storage.Bounds; Cand : Storage.Cell_T; -- A candidate variable. Found : Boolean := False; -- Whether we have found a counter. begin Found := False; -- First look at the induction variables known so far: while (Vars.Find < Vars.Num_Ind) and (not Found) loop Vars.Find := Vars.Find + 1; Cand := Vars.Ind_Var(Vars.Find); Step := Vars.Step (Vars.Find); Found := not Is_In (Value => 0, Interval => Step); end loop; -- If a counter was not found, analyse unprocessed variables: while Vars.Num_Proc < Vars.Num_Var and (not Found) loop Vars.Num_Proc := Vars.Num_Proc + 1; Cand := Vars.Var(Vars.Num_Proc); Step := Step_Bounds (Cand, Repeat); -- -- May propagate Unrepeatable_Loop, in which case -- we are done for this loop. if Known (Step) then -- This is an induction variable, because its Step -- has a lower bound, or an upper bound, or both. Vars.Num_Ind := Vars.Num_Ind + 1; Vars.Ind_Var(Vars.Num_Ind) := Cand; Vars.Step (Vars.Num_Ind) := Step; Found := not Is_In (Value => 0, Interval => Step); if Found then -- This is an effective induction variable : a counter. Vars.Eff_Ind := True; Vars.Find := Vars.Num_Ind; -- This counter was found now. end if; end if; end loop; if Found then Counter := Cand; else Counter := Storage.No_Cell; Vars.Find := Vars.Num_Ind + 1; -- No more counters to be found. end if; end Find_Next_Counter; procedure Find_Induction_Variables ( Repeat : in Calculator.Flux_T; Vars : in out Loop_Vars_T) -- -- Finds all the (remaining) indunction variables in the -- loop with the given Repeat flux (already restricted to -- the domain of initial values). -- -- May propagate Unrepeatable_Loop. -- is use type Storage.Cell_T; Counter : Storage.Cell_T; Step : Storage.Bounds.Interval_T; -- A counter variable and its step bounds. begin loop Find_Next_Counter ( Repeat => Repeat, Vars => Vars, Counter => Counter, Step => Step); exit when Counter = Storage.No_Cell; -- All variables processed. end loop; if Opt.Trace_Counters then Output.Trace ( "Induction variables: " & Storage.Image (Vars.Ind_Var(1 .. Vars.Num_Ind))); end if; end Find_Induction_Variables; Joint_Counter_Name : constant String := "#"; -- -- The name for the joint iteration counter, in Trace lines. function Joint_Induction_Bound ( Count_Repeat : Calculator.Pool_T) return Storage.Bounds.Limit_T -- -- Finds a repetition limit on a loop by analysing the domain -- of values of the joint iteration Count in the inductive -- Repeat relation, to find bounds on the Count. -- -- Count_Repeat is the domain of the inductive loop-repeat -- relation, projected to joint-counter variable. -- -- This is the "positive" form of the joint-counter analysis. -- -- Propagates Unrepeatable_Loop if loop-repetition turns out -- to be impossible. -- is use Storage.Bounds; use type Arithmetic.Value_T; Count_Bound : Interval_T; -- The bounds, if any, on the joint iteration counter, from -- Count_Repeat. Count : Arithmetic.Value_T; -- The limiting value of the joint iteration counter. begin -- Find the bounds on the joint iteration counter implied -- by the inductive repeat relation: Calculator.Comment ( Text => "Bounds on joint iteration counter", Calc => Calculator.Owner_Of (Count_Repeat)); Count_Bound := Calculator.Bounds_Of (Count_Repeat); -- -- May propagate Null_Set_Error. -- So, the loop seems to be repeatable, at least. if Opt.Trace_Counters then Output.Trace ( "Joint counter bounds for repeat: " & Storage.Bounds.Image ( Item => Count_Bound, Name => Joint_Counter_Name)); end if; if Known (Count_Bound.Max) then -- This is an upper bound on the iteration counter for -- the last iteration that can take a repeat edge. Count := Value (Count_Bound.Max) + 1; -- The "+1" because iterations are counted from zero. return Limit (Count); else -- No upper bound known here. return Not_Limited; end if; exception when Calculator.Null_Set_Error => -- The Count_Repeat flux seems to be void. Output.Note ("Loop is unrepeatable (checking joint counter)."); raise Unrepeatable_Loop; end Joint_Induction_Bound; function Joint_Induction_Limit ( Count_Repeat : Calculator.Pool_T) return Storage.Bounds.Limit_T -- -- Finds a repetition limit on a loop by analysing the complement -- of the domain of values of the joint iteration Count in the -- inductive Repeat relation, to find a limiting Count value that -- makes the loop terminate. -- -- Count_Repeat is the domain of the inductive loop-repeat -- relation, projected to joint-counter variable. -- -- This is the "negative" form of the joint-counter analysis. -- is First_Exit : Arithmetic.Value_T; -- The smallest non-negative value of the joint iteration -- counter that terminates the loop. begin Calculator.Comment ( Text => "Joint induction limit search", Calc => Calculator.Owner_Of (Count_Repeat)); First_Exit := Calculator.Smallest_Hole ( Pool => Count_Repeat, Min => 0); -- -- Since the joint iteration counter always starts from zero -- and then grows, we must omit all negative values. They -- represent exits that occur "before" the initial values. if Opt.Trace_Counters then Output.Trace ( "Loop exits for " & Joint_Counter_Name & '=' & Arithmetic.Image (First_Exit)); end if; return Storage.Bounds.Limit (First_Exit); exception when Calculator.Null_Set_Error => -- The complement of the Ind_Repeat flux seems to be void. -- The loop may be eternal, or the values of the induction -- variables variables and their steps may be so variable -- (eg. context-dependent) that the loop can potentially -- terminate after any number of iterations. Output.Note ("Loop unbounded (checking joint counter)."); return Storage.Bounds.Not_Limited; end Joint_Induction_Limit; procedure Find_Per_Counter_Bound ( Counter : in Storage.Cell_T; Initial : in Calculator.Pool_T; Step : in Storage.Bounds.Interval_T; Repeat : in Calculator.Pool_T; Init_Bounds : in out Storage.Bounds.Interval_T; Result : out Storage.Bounds.Limit_T) -- -- Finds a repetition limit on a loop by analysing the Initial -- values, the Step, and the Repeat relation for a given Counter -- cell, when this Counter cell is considered an unbounded -- integer variable (not a modular one). -- -- This is the "positive" form of the "each counter" loop analysis, -- for unbounded variables. -- -- The loop repeat relation is the relation R(t,t') that contains -- those pairs of tuples t,t' for which execution of the loop -- starting with the variable values in t can reach a repeat -- edge with the variable values in t'. -- -- For this analysis to work, the bounds on the Initial value, -- the Step, and the values that let the loop Repeat must have -- matching properties as follows: -- -- > The Step bounds must exclude zero, that is be all negative -- or all positive. -- -- > If the Step is positive: -- o Initial must have a lower bound. -- o Repeat must have an upper bound -- -- > If the Step is negative: -- o Initial must have an upper bound. -- o Repeat must have a lower bound. -- -- In each case, it follows that the number of Counter steps is -- limited from above by the distance between the "earliest" -- Initial value and the "latest" Repeat value. On the next step, -- the Counter passes beyond the Repeat pool and the loop must -- terminate. -- -- Counter -- A loop induction variable. -- Initial -- The initial values for the loop, of all variables. -- Step -- The (single possible) induction step of the Counter. -- Currently restricted to +1 or -1 for this analysis. -- Repeat -- The values of the Counter in the domain of the repeat -- relation of the loop. Other variables are not included -- so this is a one-dimensional pool. -- Init_Bounds -- Bounds on the Initial value of the Counter, computed -- here if (and only if) Step and Repeat are consistent -- with a possible loop repetition bound, so that the -- initial Counter values are relevant. Otherwise not -- changed. -- Result -- The loop repetition limit. -- -- May propagate Unrepeatable_Loop if the Repeat pool turns -- out to be empty. -- -- May propagate Infeasible_Loop if the Initial pool turns -- out to be empty. -- is use Storage.Bounds; use type Arithmetic.Value_T; type Role_T is (Up_Counter, Down_Counter, None); -- The types of counters we know of. subtype Counter_Role_T is Role_T range Up_Counter .. Down_Counter; -- The promising counter types. Role : Role_T; -- The possible role of the Counter, from Step and Repeat. Counter_Name : constant String := Storage.Image (Counter); -- The name of the counter cell. Repeat_Bounds : Interval_T; -- Bounds on the counter, implied by repetition of the loop. Rep : Arithmetic.Value_T; -- The upper bound on loop repetitions. begin Result := Not_Limited; -- Initially not known. -- Check the Step bounds: if Known (Step.Min) and then Value (Step.Min) > 0 then -- Counting up: Role := Up_Counter; elsif Known (Step.Max) and then Value (Step.Max) < 0 then -- Counting down: Role := Down_Counter; else -- Not good. Role := None; end if; -- Check the Repeat bounds if still relevant: if Role in Counter_Role_T then Repeat_Bounds := Repeat_Counter_Bounds (Repeat, Counter); -- -- May propagate Unrepeatable_Loop. case Counter_Role_T (Role) is when Up_Counter => if not Known (Repeat_Bounds.Max) then -- Counting up, but not bounded from above. Role := None; end if; when Down_Counter => if not Known (Repeat_Bounds.Min) then -- Counting down, but not bounded from below. Role := None; end if; end case; end if; -- Check the Initial bounds if still relevant: if Role in Counter_Role_T then Init_Bounds := Initial_Counter_Bounds (Initial, Counter); -- -- May propagate Infeasible_Loop. case Counter_Role_T (Role) is when Up_Counter => if Known (Init_Bounds.Min) then -- Longest from Init.Min by Step.Min to Repeat.Max. Rep := Ceil ( Left => Value (Repeat_Bounds.Max) - Value ( Init_Bounds.Min) + 1, Right => Value (Step.Min)); if Opt.Trace_Counters then Output.Trace ( Counter_Name & Output.Field_Separator & "Up_Counter" & Output.Field_Separator & Arithmetic.Image (Rep)); end if; Result := Limit (Rep); end if; when Down_Counter => if Known (Init_Bounds.Max) then -- Longest from Init.Max by Step.Max to Repeat.Min. Rep := Ceil ( Left => Value (Repeat_Bounds.Min) - Value ( Init_Bounds.Max) - 1, Right => Value (Step.Max)); if Opt.Trace_Counters then Output.Trace ( Counter_Name & Output.Field_Separator & "Down_Counter" & Output.Field_Separator & Arithmetic.Image (Rep)); end if; Result := Limit (Rep); end if; end case; end if; end Find_Per_Counter_Bound; procedure Find_Per_Modular_Counter_Bound ( Counter : in Storage.Cell_T; Initial : in Calculator.Pool_T; Step : in Storage.Bounds.Interval_T; Repeat : in Calculator.Pool_T; Init_Bounds : in out Storage.Bounds.Interval_T; Result : out Storage.Bounds.Limit_T) -- -- Finds a repetition limit on a loop by analysing the Initial -- values, the Step, and the Repeat relation for a given Counter -- cell, when this Counter is considered a bounded integer -- variable, modulus its width in bits. -- -- This is the "positive" form of the "each counter" loop analysis, -- for modular variables. -- -- All parameters have the same meaning as in Find_Per_Counter_Bound, -- above, for unbounded variables. -- -- The Step interval is assumed to be expressed in terms of signed -- values modulo the width of the Counter. -- -- If the Init_Bounds are computed here, they are bounds on the -- initial value of the Counter, unsigned-modulo its width. -- is use Storage.Bounds; use type Arithmetic.Value_T; type Role_T is (Up_Counter, Down_Counter, None); -- The types of counters we know of. subtype Counter_Role_T is Role_T range Up_Counter .. Down_Counter; -- The promising counter types. Role : Role_T; -- The possible role of the Counter, from Step and Repeat. Counter_Name : constant String := Storage.Image (Counter); -- The name of the counter cell. Repeat_Bounds : Interval_T; -- Bounds on the unsigned counter, modulo its width, implied by -- repetition of the loop. Rep : Arithmetic.Value_T; -- The upper bound on loop repetitions. begin Result := Not_Limited; -- Initially not known. -- Check the Step bounds: if Known (Step.Min) and then Value (Step.Min) > 0 then -- Counting up: Role := Up_Counter; elsif Known (Step.Max) and then Value (Step.Max) < 0 then -- Counting down: Role := Down_Counter; else -- Not good. Role := None; end if; -- Check the Repeat bounds if still relevant: -- TBA/TBD signed and/or unsigned modular bounds if Role in Counter_Role_T then Repeat_Bounds := Repeat_Counter_Bounds (Repeat, Counter); -- -- May propagate Unrepeatable_Loop. case Counter_Role_T (Role) is when Up_Counter => if not Known (Repeat_Bounds.Max) then -- Counting up, but not bounded from above. Role := None; end if; when Down_Counter => if not Known (Repeat_Bounds.Min) then -- Counting down, but not bounded from below. Role := None; end if; end case; end if; -- Check the Initial bounds if still relevant: if Role in Counter_Role_T then Init_Bounds := Initial_Counter_Bounds (Initial, Counter); -- -- May propagate Infeasible_Loop. case Counter_Role_T (Role) is when Up_Counter => if Known (Init_Bounds.Min) then -- Longest from Init.Min by Step.Min to Repeat.Max. Rep := Ceil ( Left => Value (Repeat_Bounds.Max) - Value ( Init_Bounds.Min) + 1, Right => Value (Step.Min)); if Opt.Trace_Counters then Output.Trace ( Counter_Name & Output.Field_Separator & "Up_Counter" & Output.Field_Separator & Arithmetic.Image (Rep)); end if; Result := Limit (Rep); end if; when Down_Counter => if Known (Init_Bounds.Max) then -- Longest from Init.Max by Step.Max to Repeat.Min. Rep := Ceil ( Left => Value (Repeat_Bounds.Min) - Value ( Init_Bounds.Max) - 1, Right => Value (Step.Max)); if Opt.Trace_Counters then Output.Trace ( Counter_Name & Output.Field_Separator & "Down_Counter" & Output.Field_Separator & Arithmetic.Image (Rep)); end if; Result := Limit (Rep); end if; end case; end if; end Find_Per_Modular_Counter_Bound; function Per_Counter_Limit ( Counter : Storage.Cell_T; Initial : Storage.Bounds.Interval_T; Step : Arithmetic.Value_T; Not_Repeat : Calculator.Pool_T) return Storage.Bounds.Limit_T -- -- Finds a repetition limit on a loop by analysing the Initial values, -- the (constant) Step, and the complement of the Repeat relation for -- a given Counter, using the complement of the Counter value domain -- to find a limiting Counter value that makes the loop terminate. -- This is the "negative" form of the "each counter" loop analysis. -- -- The loop repeat relation is the relation R(t,t') that contains -- those pairs of tuples t,t' for which execution of the loop -- starting with the variable values in t can reach a repeat -- edge with the variable values in t'. -- -- For this analysis to work, the Initial value of the Counter -- must have both a lower and an upper bound, say Imin..Imax. -- -- Assume that the Step is positive (+1); the negative case is -- symmetric. The analysis tries to find a "final" Counter value, -- larger or equal to Imax, such that the loop must terminate -- at this final value (if not earlier). In this way: -- -- > Compute the domain of R: -- -- domain := { t | exists t': R(t,t') } -- -- > Find the values of Counter in the domain of R: -- -- Repeat := { v | exists t,t': Counter(t) = v and R(t,t') } -- -- where Counter(t) means the value of the Counter variable -- in the tuple t. -- -- > Compute the complement, including only values >= Imax: -- -- cpl := (complement (Repeat)) intersect Imax..inf -- = { v >= Imax | for all t,t' with Counter(t) = v: not R(t,t') } -- -- > Find the least value in cpl: -- -- final := min (cpl). -- -- If this computation succeeds, the loop is sure to terminate -- when Counter reaches the final value. This happens after at -- most "final - Imin" repetitions of the loop. -- -- Counter -- A loop induction variable. -- Initial -- Bounds on the initial value of the Counter. -- Must be a finite interval. -- Step -- The (single possible) induction step of the Counter. -- Currently restricted to +1 or -1 for this analysis. -- Not_Repeat -- The values of the Counter not in the domain of the repeat -- relation of the loop. Other variables are not included -- so this is a one-dimensional pool. -- -- Preconditions: -- Step = +1 or Step = -1. -- Initial is a finite interval (Storage.Bounds.Known). -- is use Storage.Bounds; use type Arithmetic.Value_T; Counter_Name : constant String := Storage.Image (Counter); -- The name of the counter cell. First_Exit : Arithmetic.Value_T; -- The first (smallest for +ve step, largest for -ve step) value -- of the Counter for which the loop exits. Final : Limit_T; -- The actual final Counter value. Result : Limit_T := Not_Limited; -- The computed bound on loop repetitions. begin -- Check precondition on Step: if abs Step /= 1 then Output.Fault ( Location => "Bounds.Looping.Limit_By_Complement", Text => "Step is " & Arithmetic.Image (Step)); return Not_Limited; end if; -- Find a final Counter value, from the complement -- of the Counter values in the domain of Repeat: Calculator.Comment ( Text => "Check complement-limit for counter candidate " & Counter_Name, Calc => Calculator.Owner_Of (Not_Repeat)); -- The following may propagate Calculator.Null_Set_Error -- if the Smallest/Largest_Value is not found: if Step > 0 then -- Going up, so we must find a final value -- no less than the largest Initial value. First_Exit := Calculator.Smallest_Value ( Pool => Not_Repeat, Min => Value (Initial.Max)); else -- Going down, so we must find a final value -- no greater than the smallest Initial value. First_Exit := Calculator.Largest_Value ( Pool => Not_Repeat, Max => Value (Initial.Min)); end if; -- We have a First_Exit value. if Opt.Trace_Counters then Output.Trace ( "Loop exits for " & Counter_Name & '=' & Arithmetic.Image (First_Exit)); end if; if Step > 0 then Result := Limit (First_Exit - Value (Initial.Min)); else Result := Limit (Value (Initial.Max) - First_Exit); end if; -- Report the repetition limit, if found: if Known (Result) and Opt.Trace_Counters then Output.Trace ( "Count from " & Image (Initial, Counter_Name) & " by " & Arithmetic.Image (Step) & " to " & Arithmetic.Image (First_Exit) & Output.Field_Separator & Arithmetic.Image (Value (Result))); end if; return Result; exception when Calculator.Null_Set_Error => -- A Final_Bound was not found; the set was empty. -- This means that we have not found a Counter -- value that is impossible for the Repeat flux. return Not_Limited; end Per_Counter_Limit; procedure General_Procedure ( Initial : in Calculator.Pool_T; Repeat : in Calculator.Flux_T; Repeat_Inv : in Calculator.Cell_Set_T; Candidates : in Storage.Cell_List_T; Param : in Opt.Proc_Param_T; Repeat_Limit : out Storage.Bounds.Limit_T) -- -- The "general" procedure for applying various forms of -- loop-bounds analysis to a given loop. This general -- procedure is controlled by the Params to implement a -- specific procedure. -- -- May propagate Infeasible_Loop or Unrepeatable_Loop. -- is use Storage; use Storage.Bounds; use type Arithmetic.Value_T; Calc : constant Calculator.Calc_Handle_T := Calculator.Owner_Of (Initial); -- The calculator instance we use. Vars : Loop_Vars_T (Num_Var => Candidates'Length); -- Information about the induction variables. Ind_Repeat : Calculator.Flux_T; -- The Repeat flux, constrained by the joint inductive -- properties of the induction variables. Ind_Count_Repeat : Calculator.Pool_T; -- The set of joint iteration counts in the domain -- of Ind_Repeat. Counter : Cell_T; -- A counter, for the per-counter analysis. Initial_Bounds : Interval_T := Void_Interval; -- Bounds on the Initial value of the Counter. -- Void_Interval means that the bounds are not yet computed. Step : Interval_T; -- Bounds on the step of the Counter. Counter_Repeat : Calculator.Pool_T; -- The Counter values in the domain of the Repeat relation. -- Other variables are not included. Counter_Not_Repeat : Calculator.Pool_T; -- The complement of Counter_Repeat, if needed. Counter_Limit : Limit_T; -- Loop repetition limit from this Counter. Counter_Bounds_Loop : Boolean; -- Whether this Counter bounds the loop repetitions by the -- positive form of the per-counter analysis. Done : Boolean := False; -- Whether the analysis is finished. procedure Set_Repeat_Limit (Limit : in Limit_T) -- -- Sets a Limit on the number of loop repetitions. -- is begin Repeat_Limit := And_Max (Repeat_Limit, Limit); if Param.First and Known (Repeat_Limit) then -- We are content with this limit. Done := True; end if; end Set_Repeat_Limit; begin -- General_Procedure Repeat_Limit := Not_Limited; -- Initialize Vars: Vars.Var := Candidates; -- Vars.Num_Proc = 0 : No variables processed yet. -- Vars.Num_Var = 0 : No induction variables known yet. -- Vars.Eff_Ind = False: No effective induction variables known. -- Possible joint induction counter bounds: if Param.Joint then -- Analyse all induction variables together, using a joint -- counter and an induction model, and try to find positive -- bounds on the joint counter in the repeat flux. Find_Induction_Variables ( Repeat => Repeat, Vars => Vars); if Vars.Eff_Ind then -- There is at least one effective induction variable. -- Model the induction variables, at the start of the loop, -- as functions of their initial values and of the synthetic -- iteration counter: Calculator.Comment ( Text => "Compute inductive repeat relation", Calc => Calc); Ind_Repeat := Calculator.Repeat_With_Induction ( Initial => Initial, Invariant => Repeat_Inv, Induction => Vars.Ind_Var(1 .. Vars.Num_Ind), Step => Vars.Step (1 .. Vars.Num_Ind), Repeat => Repeat); if Opt.Use_Positive_Form then -- Try the "positive" joint-counter analysis: see if -- the inductive repeat relation implies an upper -- bound on the joint counter. Ind_Count_Repeat := Calculator.Domain_Of (Ind_Repeat); Set_Repeat_Limit (Joint_Induction_Bound (Ind_Count_Repeat)); end if; end if; end if; -- Possible bounds or limits from each counter: if (not Done) and Param.Each then -- Analyse each counter separately. Find_Counters_Again (Vars); Scan_Counters : loop Find_Next_Counter ( Repeat => Repeat, Vars => Vars, Counter => Counter, Step => Step); exit Scan_Counters when Counter = Storage.No_Cell; Calculator.Comment ( Text => "Analysing counter cell " & Storage.Image (Counter), Calc => Calculator.Owner_Of (Repeat)); -- Possible bounds on this Counter: if Param.Joint or (not Opt.Use_Positive_Form) then -- The positive form of the joint-counter analysis -- subsumes the positive form of the per-counter -- analysis, so the latter can be omitted. Of course -- it is omitted also if Use_Positive_Form is False. Counter_Bounds_Loop := False; else -- Try the positive form of the per-counter analysis. Counter_Repeat := Calculator.Values_In_Domain ( Flux => Repeat, Cell => Counter); Find_Per_Counter_Bound ( Counter => Counter, Initial => Initial, Step => Step, Repeat => Counter_Repeat, Init_Bounds => Initial_Bounds, Result => Counter_Limit); Counter_Bounds_Loop := Known (Counter_Limit); Set_Repeat_Limit (Counter_Limit); end if; exit Scan_Counters when Done; -- Possible limit on this Counter: if ((not Counter_Bounds_Loop) or Param.Neg) and (Singular (Step) and then abs Single_Value (Step) = 1) then -- The positive form of the per-counter analysis failed, -- or was omitted, or we are asked to do the negative -- form in any case, and the negative form may be applicable -- because the step is +1 or -1. if Void (Initial_Bounds) then -- Not yet computed above, and needed now. Initial_Bounds := Initial_Counter_Bounds (Initial, Counter); end if; if Bounded (Initial_Bounds) then -- The negative per-counter analysis is applicable. if Param.Joint then -- This was not done yet, and we need it now: Counter_Repeat := Calculator.Values_In_Domain ( Flux => Repeat, Cell => Counter); end if; Counter_Not_Repeat := Calculator.Complement (Counter_Repeat); Counter_Limit := Per_Counter_Limit ( Counter => Counter, Initial => Initial_Bounds, Step => Single_Value (Step), Not_Repeat => Counter_Not_Repeat); Set_Repeat_Limit (Counter_Limit); end if; end if; exit Scan_Counters when Done; end loop Scan_Counters; end if; -- Possible joint induction counter limits: if (not Done) and Param.Joint and Vars.Eff_Ind then -- Try the negative form of the joint counter analysis. if not Opt.Use_Positive_Form then -- Compute the domain of the inductive repeat relation, -- as we skipped it above. Ind_Count_Repeat := Calculator.Domain_Of (Ind_Repeat); end if; Set_Repeat_Limit (Joint_Induction_Limit (Ind_Count_Repeat)); end if; end General_Procedure; procedure Bound_Loop ( Luup : in Loops.Loop_T; Initial : in Calculator.Pool_T; Repeat : in Calculator.Flux_T; Repeat_Inv : in Calculator.Cell_Set_T; Inherit_Inv : in Storage.Cell_Set_T; Exec_Bounds : in Programs.Execution.Bounds_Ref) is use type Arithmetic.Value_T; Loop_Index : constant Loops.Loop_Index_T := Loops.Loop_Index (Luup); -- The index number of the loop, for display only. Var_List : constant Storage.Cell_List_T := Storage.To_List ( From => Calculator.Cells_Of (Repeat), Except => Repeat_Inv); -- The list of loop-variant cells. Candidates : constant Storage.Cell_List_T := Storage.Counter_Cells (Var_List); -- The list of counter candidate cells. Model : constant Flow.Computation.Model_Handle_T := Programs.Execution.Computation (Exec_Bounds); -- The computation model for this analysis. Repeat_Limit : Storage.Bounds.Limit_T; -- Computed bounds on the repetitions of the loop. Repeat_Value : Arithmetic.Value_T; -- The computed maximum number of loop-repetitions. -- Possibly negative, although unlikely. Repeat_Count : Flow.Execution.Count_T; -- The computed maximum number of loop-repetitions, -- non-negative. procedure Trace_Finish is begin if Opt.Trace_Counters then Output.Trace ( "Finished loop-counter analysis for loop" & Loops.Loop_Index_T'Image (Loop_Index)); end if; end Trace_Finish; begin -- Bound_Loop -- Show time: if Opt.Trace_Counters then Output.Trace ( "Starting loop-counter analysis for loop" & Loops.Loop_Index_T'Image (Loop_Index)); Output.Trace ( "Invariant cells: " & Calculator.Image (Repeat_Inv)); Output.Trace ( "Variant cells: " & Storage.Image (Var_List)); Output.Trace ( "Candidates for counters: " & Storage.Image (Candidates)); end if; -- Do it in your own way: General_Procedure ( Initial => Initial, Repeat => Repeat, Repeat_Inv => Repeat_Inv, Candidates => Candidates, Param => Opt.Param(Opt.Proc), Repeat_Limit => Repeat_Limit); -- Check if a credible bound was computed: if Storage.Bounds.Known (Repeat_Limit) then -- A bound was computed. Repeat_Value := Storage.Bounds.Value (Repeat_Limit); if Storage.Bounds.Over (Repeat_Value, Opt.Max_Loop_Bound) then -- The bound is too large to be credible (useful). Output.Warning ( "Large loop-bound ignored as spurious" & Output.Field_Separator & Arithmetic.Image (Repeat_Value)); else -- The bound is small enough to be credible. if Repeat_Value < 0 then Output.Warning ( "Negative loop-bound " & Arithmetic.Image (Repeat_Value) & " taken as zero (loop not repeatable)."); Repeat_Count := 0; else Repeat_Count := Flow.Execution.Count_T (Repeat_Value); end if; Programs.Execution.Bound_Loop_Repeats ( Luup => Luup, Repeats => (Min => 0, Max => Repeat_Count), Within => Exec_Bounds); Output.Result ( Key => "Loop_Bound", Text => Flow.Execution.Image (Repeat_Count)); if Repeat_Count = 0 then -- We found that the loop cannot repeat. Output.Note ("Loop is unrepeatable (zero bound)."); raise Unrepeatable_Loop; end if; end if; end if; -- Closing time: Trace_Finish; exception when Infeasible_Loop => if Flow.Pruning.Opt.Warn_Unreachable then Output.Warning ("Unreachable loop."); end if; Flow.Computation.Mark_Infeasible ( Luup => Luup, Under => Model.all); Trace_Finish; when Unrepeatable_Loop => if Flow.Pruning.Opt.Warn_Unreachable then Output.Warning ("Unrepeatable loop."); end if; Flow.Computation.Mark_Infeasible ( Edges => Flow.Computation.Repeat_Edges (Luup, Model.all), Under => Model.all); Trace_Finish; end Bound_Loop; end Bounds.Looping;
molostoff/AdaBaseXClient
Ada
8,498
adb
with Ahven; use Ahven; with AdaBaseXClient; use AdaBaseXClient; -- -- Requires BaseX server when testing -- package body ClientTest is procedure Initialize (T : in out Test) is begin Set_Name (T, "My tests"); T.Add_Test_Routine (Routine => Unknown_Fail'Access, Name => "Unknown_Fail"); T.Add_Test_Routine (Routine => Port_Fail'Access, Name => "Port_Fail"); T.Add_Test_Routine (Routine => Connect_Auth'Access, Name => "Connect_Auth"); T.Add_Test_Routine (Routine => Connect_Pass'Access, Name => "Connect_Pass"); T.Add_Test_Routine (Routine => Execute_Test'Access, Name => "Execute_Test"); T.Add_Test_Routine (Routine => Execute_Fail'Access, Name => "Execute_Fail"); T.Add_Test_Routine (Routine => Create_Drop'Access, Name => "Create_Drop"); T.Add_Test_Routine (Routine => Add_Test'Access, Name => "Add_Test"); T.Add_Test_Routine (Routine => Replace_Test'Access, Name => "Replace_Test"); T.Add_Test_Routine (Routine => Query_Test'Access, Name => "Query_Test"); T.Add_Test_Routine (Routine => Query_Bind'Access, Name => "Query_Bind"); end Initialize; procedure Unknown_Fail is result : Boolean; begin result := Connect ("unknown", 1_984); Fail (Message => "Exception expected"); exception when Error : BaseXException => null; end Unknown_Fail; procedure Port_Fail is result : Boolean; begin result := Connect ("localhost", 1_985); Fail (Message => "Exception expected"); exception when Error : BaseXException => null; end Port_Fail; procedure Connect_Auth is result : Boolean; begin result := Connect ("localhost", 1_984); Assert (Condition => result = True, Message => "Connect test"); result := Authenticate ("unknown", "test"); Assert (Condition => result = False, Message => "Auth test"); Close; end Connect_Auth; procedure Connect_Pass is result : Boolean; begin result := Connect ("localhost", 1_984); Assert (Condition => result = True, Message => "Connect test"); result := Authenticate ("admin", "admin"); Assert (Condition => result = True, Message => "Auth test"); Close; end Connect_Pass; procedure Execute_Test is result : Boolean; begin result := Connect ("localhost", 1_984); Assert (Condition => result = True, Message => "Connect test"); result := Authenticate ("admin", "admin"); Assert (Condition => result = True, Message => "Auth test"); declare Response : String := Execute ("xquery 1+1"); begin Assert (Condition => Response = "2", Message => "Execute test"); end; Close; end Execute_Test; procedure Execute_Fail is result : Boolean; begin result := Connect ("localhost", 1_984); Assert (Condition => result = True, Message => "Connect test"); result := Authenticate ("admin", "admin"); Assert (Condition => result = True, Message => "Auth test"); declare Response : String := Execute ("xquery unknown"); begin Fail (Message => "Exception expected"); end; exception when Error : BaseXException => Close; end Execute_Fail; procedure Create_Drop is result : Boolean; begin result := Connect ("localhost", 1_984); Assert (Condition => result = True, Message => "Connect test"); result := Authenticate ("admin", "admin"); Assert (Condition => result = True, Message => "Auth test"); declare Response : String := Create ("database", "<x>Hello World!</x>"); begin null; end; declare Response : String := Execute ("xquery /"); begin Assert (Condition => Response = "<x>Hello World!</x>", Message => "Query database"); end; declare Response : String := Execute ("drop db database"); begin null; end; Close; end Create_Drop; procedure Add_Test is result : Boolean; begin result := Connect ("localhost", 1_984); Assert (Condition => result = True, Message => "Connect test"); result := Authenticate ("admin", "admin"); Assert (Condition => result = True, Message => "Auth test"); declare Response : String := Create ("database", ""); begin null; end; declare Response : String := Add ("Ada.xml", "<x>Hello Ada!</x>"); begin null; end; declare Response : String := Execute ("xquery /"); begin Assert (Condition => Response = "<x>Hello Ada!</x>", Message => "Query database"); end; declare Response : String := Execute ("drop db database"); begin null; end; Close; end Add_Test; procedure Replace_Test is result : Boolean; begin result := Connect ("localhost", 1_984); Assert (Condition => result = True, Message => "Connect test"); result := Authenticate ("admin", "admin"); Assert (Condition => result = True, Message => "Auth test"); declare Response : String := Create ("database", ""); begin null; end; declare Response : String := Add ("Ada.xml", "<x>Hello Ada!</x>"); begin null; end; declare Response : String := Replace ("Ada.xml", "<x>Ada is awesome!</x>"); begin null; end; declare Response : String := Execute ("xquery /"); begin Assert (Condition => Response = "<x>Ada is awesome!</x>", Message => "Query database"); end; declare Response : String := Execute ("drop db database"); begin null; end; Close; end Replace_Test; procedure Query_Test is result : Boolean; begin result := Connect ("localhost", 1_984); Assert (Condition => result = True, Message => "Connect test"); result := Authenticate ("admin", "admin"); Assert (Condition => result = True, Message => "Auth test"); declare Response : Query := CreateQuery ("1+1"); V : String_Vectors.Vector; begin V := Response.Results; Assert (Condition => V (0) = "2", Message => "Query test"); Response.Close; end; Close; end Query_Test; procedure Query_Bind is result : Boolean; begin result := Connect ("localhost", 1_984); Assert (Condition => result = True, Message => "Connect test"); result := Authenticate ("admin", "admin"); Assert (Condition => result = True, Message => "Auth test"); declare Response : Query := CreateQuery ("declare variable $name external; for $i in 1 to 1 return element { $name } { $i }"); begin Response.Bind ("name", "number", ""); declare Res : String := Response.Execute; begin Assert (Condition => Res = "<number>1</number>", Message => "Query bind"); end; Response.Close; end; Close; end Query_Bind; end ClientTest;
reznikmm/matreshka
Ada
23,273
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- XML Processor -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with League.Characters.Internals; with League.Characters.Latin; with Matreshka.Internals.Unicode; package body XML.SAX.Pretty_Writers is use Matreshka.Internals.Unicode; use type League.Strings.Universal_String; XML_Namespace : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("http://www.w3.org/XML/1998/namespace"); XML_Prefix : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("xml"); XMLNS_Prefix : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("xmlns"); Amp_Entity_Reference : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("&amp;"); Apos_Entity_Reference : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("&apos;"); Quot_Entity_Reference : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("&quot;"); Gt_Entity_Reference : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("&gt;"); Lt_Entity_Reference : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("&lt;"); XML_1_0_Image : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("1.0"); XML_1_1_Image : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("1.1"); procedure Output_Name (Self : in out XML_Pretty_Writer; Namespace_URI : League.Strings.Universal_String; Local_Name : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String; Success : in out Boolean); -- Do vilidity checks, resolve namespace prefix when necessary and output -- name (of the tag or attribute). function Image (X_V : XML_Version) return League.Strings.Universal_String; -- Returns text representation of XML version. ---------------- -- Characters -- ---------------- overriding procedure Characters (Self : in out XML_Pretty_Writer; Text : League.Strings.Universal_String; Success : in out Boolean) is pragma Unreferenced (Success); begin if Self.Tag_Opened then Self.Destination.Put ('>'); Self.Tag_Opened := False; end if; Self.Destination.Put (Self.Escape (Text)); Self.Chars := True; end Characters; ------------- -- Comment -- ------------- overriding procedure Comment (Self : in out XML_Pretty_Writer; Text : League.Strings.Universal_String; Success : in out Boolean) is pragma Unreferenced (Success); begin -- Closing DTD, which was opened before. if Self.DTD_Opened then Self.Destination.Put ('>'); Self.DTD_Opened := False; end if; Self.Destination.Put ("<!-- "); Self.Destination.Put (Text); Self.Destination.Put (" -->"); end Comment; --------------- -- End_CDATA -- --------------- overriding procedure End_CDATA (Self : in out XML_Pretty_Writer; Success : in out Boolean) is begin null; end End_CDATA; ------------------ -- End_Document -- ------------------ overriding procedure End_Document (Self : in out XML_Pretty_Writer; Success : in out Boolean) is begin if Self.Nesting /= 0 then Success := False; return; end if; end End_Document; ------------- -- End_DTD -- ------------- overriding procedure End_DTD (Self : in out XML_Pretty_Writer; Success : in out Boolean) is pragma Unreferenced (Success); begin Self.Destination.Put ('>'); Self.DTD_Opened := False; end End_DTD; ----------------- -- End_Element -- ----------------- overriding procedure End_Element (Self : in out XML_Pretty_Writer; Namespace_URI : League.Strings.Universal_String; Local_Name : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String; Success : in out Boolean) is begin -- Validity check: Namespace_URI, Local_Name and Qualified_Name of close -- tag must match open tag. if Self.Current.Namespace_URI /= Namespace_URI or Self.Current.Local_Name /= Local_Name or Self.Current.Qualified_Name /= Qualified_Name then Self.Error := League.Strings.To_Universal_String ("namespace URI, local name or qualified name doesn't match" & " open tag"); Success := False; return; end if; -- Use empty tag when there are no any content inside the tag. if Self.Tag_Opened then Self.Destination.Put ("/>"); Self.Tag_Opened := False; -- Do automatic indentation then necessary. if Self.Offset /= 0 then Self.Indent := Self.Indent - Self.Offset; end if; else -- Do automatic indentation then necessary. if Self.Offset /= 0 then Self.Indent := Self.Indent - Self.Offset; if Self.Chars then Self.Chars := False; else Self.Destination.Put (League.Characters.Latin.Line_Feed); for J in 1 .. Self.Indent loop Self.Destination.Put (' '); end loop; end if; end if; Self.Destination.Put ("</"); Output_Name (Self, Namespace_URI, Local_Name, Qualified_Name, Success); Self.Destination.Put ('>'); end if; -- Pop current element information. Self.Current := Self.Stack.Last_Element; Self.Stack.Delete_Last; Self.Nesting := Self.Nesting - 1; end End_Element; ---------------- -- End_Entity -- ---------------- overriding procedure End_Entity (Self : in out XML_Pretty_Writer; Name : League.Strings.Universal_String; Success : in out Boolean) is begin null; end End_Entity; ------------------------ -- End_Prefix_Mapping -- ------------------------ overriding procedure End_Prefix_Mapping (Self : in out XML_Pretty_Writer; Prefix : League.Strings.Universal_String := League.Strings.Empty_Universal_String; Success : in out Boolean) is begin null; end End_Prefix_Mapping; ------------------ -- Error_String -- ------------------ overriding function Error_String (Self : XML_Pretty_Writer) return League.Strings.Universal_String is begin return Self.Error; end Error_String; ------------ -- Escape -- ------------ function Escape (Self : XML_Pretty_Writer; Text : League.Strings.Universal_String; Escape_All : Boolean := False) return League.Strings.Universal_String is Code : Code_Point; begin return Result : League.Strings.Universal_String do for J in 1 .. Text.Length loop Code := League.Characters.Internals.Internal (Text.Element (J)); case Text.Element (J).To_Wide_Wide_Character is when '&' => Result.Append (Amp_Entity_Reference); when ''' => if Escape_All then Result.Append (Apos_Entity_Reference); else Result.Append (Text.Element (J).To_Wide_Wide_Character); end if; when '"' => if Escape_All then Result.Append (Quot_Entity_Reference); else Result.Append (Text.Element (J).To_Wide_Wide_Character); end if; when '>' => if Escape_All then Result.Append (Gt_Entity_Reference); else Result.Append (Text.Element (J).To_Wide_Wide_Character); end if; when '<' => Result.Append (Lt_Entity_Reference); when others => -- Add support of choosing of Hexademical -- or Digital representation of Character references -- XML_1_1 2.2 Characters if Self.Version = XML_1_1 and then (Code in 16#1# .. 16#8# or else Code in 16#B# .. 16#C# or else Code in 16#E# .. 16#1F# or else Code in 16#7F# .. 16#84# or else Code in 16#86# .. 16#9F#) then declare Image : constant Wide_Wide_String := Code_Unit_32'Wide_Wide_Image (Code); begin Result := Result & "&#" & Image (Image'First + 1 .. Image'Last) & ";"; end; else Result.Append (Text.Element (J).To_Wide_Wide_Character); end if; end case; end loop; end return; end Escape; -------------------------- -- Ignorable_Whitespace -- -------------------------- overriding procedure Ignorable_Whitespace (Self : in out XML_Pretty_Writer; Text : League.Strings.Universal_String; Success : in out Boolean) is begin null; end Ignorable_Whitespace; ----------- -- Image -- ----------- function Image (X_V : XML_Version) return League.Strings.Universal_String is begin case X_V is when XML_1_0 => return XML_1_0_Image; when XML_1_1 => return XML_1_1_Image; end case; end Image; ----------- -- Merge -- ----------- procedure Merge (Current : in out Mappings.Map; Bank : Banks.Map) is C : Banks.Cursor := Banks.First (Bank); begin while Banks.Has_Element (C) loop Mappings.Include (Current, Banks.Key (C), Banks.Element (C)); Banks.Next (C); end loop; end Merge; ----------------- -- Output_Name -- ----------------- procedure Output_Name (Self : in out XML_Pretty_Writer; Namespace_URI : League.Strings.Universal_String; Local_Name : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String; Success : in out Boolean) is begin if Namespace_URI.Is_Empty then -- Non-namespaces mode. -- Validity check: Qualified_Name must not be empty. if Qualified_Name.Is_Empty then Self.Error := League.Strings.To_Universal_String ("qualified name is empty"); Success := False; return; end if; -- Append qualified name of the tag. Self.Destination.Put (Qualified_Name); else -- Namespaces mode. -- Validity check: local name must not be empty. if Local_Name.Is_Empty then Self.Error := League.Strings.To_Universal_String ("namespace is provides but local name is empty"); Success := False; return; end if; -- Lookup for namespace prefix. declare Position : constant Mappings.Cursor := Self.Current.Mapping.Find (Namespace_URI); begin if not Mappings.Has_Element (Position) then Self.Error := League.Strings.To_Universal_String ("namespace is not mapped to any prefix"); Success := False; return; end if; -- Output namespace prexif when namespace is not default. if not Mappings.Element (Position).Is_Empty then Self.Destination.Put (Mappings.Element (Position)); Self.Destination.Put (':'); end if; end; Self.Destination.Put (Local_Name); end if; end Output_Name; ---------------------------- -- Processing_Instruction -- ---------------------------- overriding procedure Processing_Instruction (Self : in out XML_Pretty_Writer; Target : League.Strings.Universal_String; Data : League.Strings.Universal_String; Success : in out Boolean) is pragma Unreferenced (Success); begin -- Closing DTD, which was opened before. if Self.DTD_Opened then Self.Destination.Put ('>'); Self.DTD_Opened := False; end if; end Processing_Instruction; ---------------- -- Set_Offset -- ---------------- not overriding procedure Set_Offset (Self : in out XML_Pretty_Writer; Offset : Natural) is begin Self.Offset := Offset; end Set_Offset; ---------------------------- -- Set_Output_Destination -- ---------------------------- procedure Set_Output_Destination (Self : in out XML_Pretty_Writer'Class; Output : not null SAX_Output_Destination_Access) is begin Self.Destination := Output; end Set_Output_Destination; ------------------------- -- Set_Value_Delimiter -- ------------------------- not overriding procedure Set_Value_Delimiter (Self : in out XML_Pretty_Writer; Delimiter : League.Characters.Universal_Character) is begin Self.Delimiter := Delimiter; end Set_Value_Delimiter; ----------------- -- Set_Version -- ----------------- procedure Set_Version (Self : in out XML_Pretty_Writer; Version : XML_Version) is begin Self.Version := Version; end Set_Version; -------------------- -- Skipped_Entity -- -------------------- overriding procedure Skipped_Entity (Self : in out XML_Pretty_Writer; Name : League.Strings.Universal_String; Success : in out Boolean) is begin null; end Skipped_Entity; ----------------- -- Start_CDATA -- ----------------- overriding procedure Start_CDATA (Self : in out XML_Pretty_Writer; Success : in out Boolean) is begin null; end Start_CDATA; -------------------- -- Start_Document -- -------------------- overriding procedure Start_Document (Self : in out XML_Pretty_Writer; Success : in out Boolean) is pragma Unreferenced (Success); begin Self.Destination.Put (League.Strings.To_Universal_String ("<?xml version=") & Self.Delimiter & Image (Self.Version) & Self.Delimiter & "?>"); Self.Nesting := 0; -- Reset namespace mapping and initialize it by XML namespace URI mapped -- to 'xml' prefix. Self.Current.Mapping.Clear; Self.Current.Mapping.Insert (XML_Namespace, XML_Prefix); end Start_Document; --------------- -- Start_DTD -- --------------- overriding procedure Start_DTD (Self : in out XML_Pretty_Writer; Name : League.Strings.Universal_String; Public_Id : League.Strings.Universal_String; System_Id : League.Strings.Universal_String; Success : in out Boolean) is pragma Unreferenced (Success); begin Self.Destination.Put ("<!DOCTYPE " & Name); if not Public_Id.Is_Empty then Self.Destination.Put (" PUBLIC " & Public_Id & " " & System_Id); elsif not System_Id.Is_Empty then Self.Destination.Put (" SYSTEM' " & System_Id); end if; Self.DTD_Opened := True; end Start_DTD; ------------------- -- Start_Element -- ------------------- overriding procedure Start_Element (Self : in out XML_Pretty_Writer; Namespace_URI : League.Strings.Universal_String; Local_Name : League.Strings.Universal_String; Qualified_Name : League.Strings.Universal_String; Attributes : XML.SAX.Attributes.SAX_Attributes; Success : in out Boolean) is begin -- Closing DTD, which was opened before. if Self.DTD_Opened then Self.Destination.Put ('>'); Self.DTD_Opened := False; end if; -- Closing Tag, which was opened before. if Self.Tag_Opened then Self.Destination.Put ('>'); Self.Tag_Opened := False; end if; -- Push to stack current element and namespace mapping Self.Stack.Append (Self.Current); Self.Current.Namespace_URI := Namespace_URI; Self.Current.Local_Name := Local_Name; Self.Current.Qualified_Name := Qualified_Name; if not Self.Requested_NS.Is_Empty then -- Append Bank and Current namespaces. Merge (Self.Current.Mapping, Self.Requested_NS); end if; if Self.Offset /= 0 then -- Do automatic indentation when necessary. if Self.Chars then Self.Chars := False; else Self.Destination.Put (League.Characters.Latin.Line_Feed); for J in 1 .. Self.Indent loop Self.Destination.Put (' '); end loop; end if; Self.Indent := Self.Indent + Self.Offset; end if; Self.Destination.Put ('<'); Output_Name (Self, Namespace_URI, Local_Name, Qualified_Name, Success); if not Success then return; end if; -- Output namespace mappings. declare Position : Banks.Cursor := Self.Requested_NS.First; begin while Banks.Has_Element (Position) loop Self.Destination.Put (' '); Self.Destination.Put (XMLNS_Prefix); if not Banks.Element (Position).Is_Empty then -- Non-default prefix. Self.Destination.Put (':'); Self.Destination.Put (Banks.Element (Position)); end if; Self.Destination.Put ('='); Self.Destination.Put (Self.Delimiter); Self.Destination.Put (Banks.Key (Position)); Self.Destination.Put (Self.Delimiter); Banks.Next (Position); end loop; end; -- Output attributes. for J in 1 .. Attributes.Length loop Self.Destination.Put (' '); Output_Name (Self, Attributes.Namespace_URI (J), Attributes.Local_Name (J), Attributes.Qualified_Name (J), Success); if not Success then return; end if; Self.Destination.Put ("="); Self.Destination.Put (Self.Delimiter); Self.Destination.Put (Self.Escape (Attributes.Value (J), True)); Self.Destination.Put (Self.Delimiter); end loop; Self.Nesting := Self.Nesting + 1; Self.Tag_Opened := True; Self.Requested_NS.Clear; end Start_Element; ------------------ -- Start_Entity -- ------------------ overriding procedure Start_Entity (Self : in out XML_Pretty_Writer; Name : League.Strings.Universal_String; Success : in out Boolean) is begin null; end Start_Entity; -------------------------- -- Start_Prefix_Mapping -- -------------------------- overriding procedure Start_Prefix_Mapping (Self : in out XML_Pretty_Writer; Prefix : League.Strings.Universal_String := League.Strings.Empty_Universal_String; Namespace_URI : League.Strings.Universal_String; Success : in out Boolean) is begin if Namespace_URI.Is_Empty then -- XXX error should be reported Success := False; return; end if; -- Append prefix mapping, to temp set of mapping scope Self.Requested_NS.Include (Namespace_URI, Prefix); end Start_Prefix_Mapping; end XML.SAX.Pretty_Writers;
reznikmm/matreshka
Ada
3,949
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.ODF_Attributes.Style.Text_Underline_Width; package ODF.DOM.Attributes.Style.Text_Underline_Width.Internals is function Create (Node : Matreshka.ODF_Attributes.Style.Text_Underline_Width.Style_Text_Underline_Width_Access) return ODF.DOM.Attributes.Style.Text_Underline_Width.ODF_Style_Text_Underline_Width; function Wrap (Node : Matreshka.ODF_Attributes.Style.Text_Underline_Width.Style_Text_Underline_Width_Access) return ODF.DOM.Attributes.Style.Text_Underline_Width.ODF_Style_Text_Underline_Width; end ODF.DOM.Attributes.Style.Text_Underline_Width.Internals;
AdaCore/libadalang
Ada
309
adb
procedure Test is type Sequence is array (Natural range <>) of Integer; function Foo (S1, S2 : Sequence) return Boolean is begin return (for all K in S1'Range => S1(K) > 0) and then (for some E of S2 => E < 0); pragma Test_Statement; end Foo; begin null; end Test;
reznikmm/matreshka
Ada
6,801
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Chart.Legend_Elements is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Chart_Legend_Element_Node is begin return Self : Chart_Legend_Element_Node do Matreshka.ODF_Chart.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Chart_Prefix); end return; end Create; ---------------- -- Enter_Node -- ---------------- overriding procedure Enter_Node (Self : not null access Chart_Legend_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then ODF.DOM.Visitors.Abstract_ODF_Visitor'Class (Visitor).Enter_Chart_Legend (ODF.DOM.Chart_Legend_Elements.ODF_Chart_Legend_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Enter_Node (Visitor, Control); end if; end Enter_Node; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Chart_Legend_Element_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Legend_Element; end Get_Local_Name; ---------------- -- Leave_Node -- ---------------- overriding procedure Leave_Node (Self : not null access Chart_Legend_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then ODF.DOM.Visitors.Abstract_ODF_Visitor'Class (Visitor).Leave_Chart_Legend (ODF.DOM.Chart_Legend_Elements.ODF_Chart_Legend_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Leave_Node (Visitor, Control); end if; end Leave_Node; ---------------- -- Visit_Node -- ---------------- overriding procedure Visit_Node (Self : not null access Chart_Legend_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Iterator in ODF.DOM.Iterators.Abstract_ODF_Iterator'Class then ODF.DOM.Iterators.Abstract_ODF_Iterator'Class (Iterator).Visit_Chart_Legend (Visitor, ODF.DOM.Chart_Legend_Elements.ODF_Chart_Legend_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Visit_Node (Iterator, Visitor, Control); end if; end Visit_Node; begin Matreshka.DOM_Documents.Register_Element (Matreshka.ODF_String_Constants.Chart_URI, Matreshka.ODF_String_Constants.Legend_Element, Chart_Legend_Element_Node'Tag); end Matreshka.ODF_Chart.Legend_Elements;