content
stringlengths
23
1.05M
with Interfaces.C; with System.Address_To_Access_Conversions; with System; package body Agar.Core.Database is package C renames Interfaces.C; use type C.int; use type C.size_t; procedure New_Database (Database_Type : in Type_t; Database : out Database_Access_t) is begin null; end New_Database; package body Generic_Database is package Data_Access_Conversion is new System.Address_To_Access_Conversions (Object => Data_Type); function Exists (Database : in Database_Not_Null_Access_t; Key : in Key_Type) return Boolean is begin return 1 = Thin.DB.Exists_Binary_Key (DB => Database, Key_Data => Key'Address, Key_Size => Key'Size / System.Storage_Unit); end Exists; procedure Lookup (Database : in Database_Not_Null_Access_t; Key : in Key_Type; Database_Entry : out Entry_t; Found : out Boolean) is DB_Entry : aliased Thin.DB.Entry_t; begin Found := 0 = Thin.DB.Lookup_Binary_Key (DB => Database, DB_Entry => DB_Entry'Unchecked_Access, Key_Data => Key'Address, Key_Size => Key'Size / System.Storage_Unit); if Found then Database_Entry.Data := Data_Type_Access (Data_Access_Conversion.To_Pointer (DB_Entry.Data)); Database_Entry.Data_Size := Natural (DB_Entry.Data_Size); else Database_Entry := Null_Entry; end if; end Lookup; function Delete (Database : in Database_Not_Null_Access_t; Key : in Key_Type) return Boolean is begin return 0 = Thin.DB.Delete_Binary_Key (DB => Database, Key_Data => Key'Address, Key_Size => Key'Size / System.Storage_Unit); end Delete; function Put (Database : in Database_Not_Null_Access_t; Key : in Key_Type_Access; Data : in Data_Type_Access) return Boolean is DB_Entry : aliased Thin.DB.Entry_t; begin DB_Entry.DB := Database; DB_Entry.Key := Key.all'Address; DB_Entry.Key_Size := Key'Size / System.Storage_Unit; DB_Entry.Data := Data.all'Address; DB_Entry.Data_Size := Data'Size / System.Storage_Unit; return 0 = Thin.DB.Put (DB => Database, DB_Entry => DB_Entry'Unchecked_Access); end Put; end Generic_Database; end Agar.Core.Database;
with STM32_SVD; use STM32_SVD; with STM32_SVD.GPIO; package STM32GD.GPIO is pragma Preelaborate; type GPIO_Port is (Port_A, Port_B, Port_C, Port_D, Port_F); type GPIO_Pin is (Pin_0, Pin_1, Pin_2, Pin_3, Pin_4, Pin_5, Pin_6, Pin_7, Pin_8, Pin_9, Pin_10, Pin_11, Pin_12, Pin_13, Pin_14, Pin_15); for GPIO_Pin use (Pin_0 => 16#0001#, Pin_1 => 16#0002#, Pin_2 => 16#0004#, Pin_3 => 16#0008#, Pin_4 => 16#0010#, Pin_5 => 16#0020#, Pin_6 => 16#0040#, Pin_7 => 16#0080#, Pin_8 => 16#0100#, Pin_9 => 16#0200#, Pin_10 => 16#0400#, Pin_11 => 16#0800#, Pin_12 => 16#1000#, Pin_13 => 16#2000#, Pin_14 => 16#4000#, Pin_15 => 16#8000#); for GPIO_Pin'Size use 16; -- for compatibility with hardware registers type GPIO_Pins is array (Positive range <>) of GPIO_Pin; -- Note that, in addition to aggregates, the language-defined catenation -- operator "&" is available for types GPIO_Pin and GPIO_Pins, allowing one -- to construct GPIO_Pins values conveniently All_Pins : constant GPIO_Pins := (Pin_0, Pin_1, Pin_2, Pin_3, Pin_4, Pin_5, Pin_6, Pin_7, Pin_8, Pin_9, Pin_10, Pin_11, Pin_12, Pin_13, Pin_14, Pin_15); type Pin_In_Conf is (In_Analog, In_Floating, In_PullUpDown) with Size => 2; for Pin_In_Conf use (In_Analog => 2#00#, In_Floating => 2#01#, In_PullUpDown => 2#10#); type Pin_Out_Conf is ( Out_PushPull, Out_OpenDrain, Alt_PushPull, Alt_OpenDrain) with Size => 2; for Pin_Out_Conf use (Out_PushPull => 2#00#, Out_OpenDrain => 2#01#, Alt_PushPull => 2#10#, Alt_OpenDrain => 2#11#); type Pin_IO_Modes is (Input, Speed_10MHz, Speed_2MHz, Speed_50MHz) with Size => 2; for Pin_IO_Modes use (Input => 2#00#, Speed_10MHz => 2#01#, Speed_2MHz => 2#10#, Speed_50MHz => 2#11#); end STM32GD.GPIO;
1 3 7 12 18 26 35 45 56 69 Test Passed: No overlap between FFR(I) and FFS(J)
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- package body Program.Library_Environments is ----------------- -- Public_View -- ----------------- function Public_View (Self : Library_Environment'Class; Name : Program.Symbol_Lists.Symbol_List) return Program.Visibility.Snapshot_Access is begin return Self.Public_Views (Name); end Public_View; --------------------- -- Put_Public_View -- --------------------- procedure Put_Public_View (Self : in out Library_Environment'Class; Name : Program.Symbol_Lists.Symbol_List; Value : Program.Visibility.Snapshot_Access) is begin Self.Public_Views.Insert (Name, Value); end Put_Public_View; end Program.Library_Environments;
procedure Very_Large_Value is begin if 16#2B.20000000000000000000000000000000000000000#E1 > 0.1 then null; end if; end Very_Large_Value;
-- part of FreeTypeAda, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "COPYING" with FT.Errors; with FT.Faces; package FT.API.Glyphs is pragma Preelaborate; procedure FT_Done_Glyph (Glyph : Glyph_Ptr); pragma Import (C, FT_Done_Glyph, "FT_Done_Glyph"); -- tell the compiler that we are aware that Bool is 8-bit and will need to -- be a char on the C side. pragma Warnings (Off, "8-bit Ada Boolean"); function FT_Glyph_To_Bitmap (theGlyph : Glyph_Ptr; Mode : Faces.Render_Mode; Origin : access Vector; Destroy : Bool) return Errors.Error_Code; pragma Import (C, FT_Glyph_To_Bitmap, "FT_Glyph_To_Bitmap"); pragma Warnings (On, "8-bit Ada Boolean"); function FT_Get_Glyph (Slot_Ptr : Glyph_Slot_Ptr; aGlyph : access Glyph_Ptr) return Errors.Error_Code; pragma Import (C, FT_Get_Glyph, "FT_Get_Glyph"); function FT_Render_Glyph (Slot : access Glyph_Slot_Record; Mode : Faces.Render_Mode) return Errors.Error_Code; pragma Import (C, FT_Render_Glyph, "FT_Render_Glyph"); end FT.API.Glyphs;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Float_Text_IO; use Ada.Float_Text_IO; procedure parfait is function Est_Parfait(nb : Integer) return Boolean is somme : Integer := 0; begin for i in 1..(nb / 2 + 1) loop if nb mod i = 0 then somme := somme + i; end if; end loop; return somme = nb; end Est_Parfait; n : Integer; begin while True loop Put(">>> "); Get(n); exit when n = -1; Put_Line(if Est_Parfait(n) then "parfait" else "pas parfait"); end loop; end parfait;
------------------------------------------------------------------------------- -- LSE -- L-System Editor -- Author: Heziode -- -- License: -- MIT License -- -- Copyright (c) 2018 Quentin Dauprat (Heziode) <Heziode@protonmail.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- with Ada.Text_IO.Editing; -- @description -- This package provides methods for colors processing -- package LSE.Utils.Colors is -- Bad string length STRING_LENGTH : exception; -- Unexpected character encountered during string conversion UNEXPECTED_CHARACTER : exception; -- Convert Hexa value to Natural function Str_Hex_To_Int (Input : String) return Natural; -- Convert Hexa value to Float function Str_Hex_To_Float (Input : String) return Float; -- Convert RGB String (in Hex foramt, ex #AABBCC) to Natural (0 .. 255) procedure To_RGB (Input : String; R, G, B : out Natural); -- Convert RGB String (in Hex foramt, ex #AABBCC) to Float (0.0 .. 1.0) procedure To_RGB (Input : String; R, G, B : out Float); -- Convert RGB value to string function RGB_To_String (R, G, B : Natural) return String with Pre => (R <= 255 and G <= 255 and B <= 255); -- Convert RGB value to string function RGB_To_String (R, G, B : Float) return String with Pre => (R in 0.0 .. 1.0 and G in 0.0 .. 1.0 and B in 0.0 .. 1.0); -- Convert RGB value to string (in Hex format, ex #AABBCC) function RGB_To_Hex_String (R, G, B : Natural) return String with Pre => (R <= 255 and G <= 255 and B <= 255); -- Convert RGB value to string (in Hex format, ex #AABBCC) function RGB_To_Hex_String (R, G, B : Float) return String with Pre => (R in 0.0 .. 1.0 and G in 0.0 .. 1.0 and B in 0.0 .. 1.0); private use Ada.Text_IO.Editing; type Fixed_Point is delta 0.001 digits 18; package Formatted_IO is new Ada.Text_IO.Editing.Decimal_Output (Fixed_Point); end LSE.Utils.Colors;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Tools Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012-2013, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Ada.Containers.Ordered_Maps; with Ada.Wide_Wide_Text_IO; use Ada.Wide_Wide_Text_IO; with League.Strings; with WSDL.AST.Bindings; pragma Unreferenced (WSDL.AST.Bindings); -- GNAT Pro 7.2.0w (20130423): package is needed to access to type's -- components. with WSDL.AST.Descriptions; pragma Unreferenced (WSDL.AST.Descriptions); -- GNAT Pro 7.2.0w (20130423): package is needed to access to type's -- components. with WSDL.AST.Interfaces; pragma Unreferenced (WSDL.AST.Interfaces); -- XXX GNAT 20130108 reports unreferenced unit. with WSDL.AST.Messages; pragma Unreferenced (WSDL.AST.Messages); -- GNAT Pro 7.2.0w (20130423): package is needed to access to type's -- components. with WSDL.AST.Operations; pragma Unreferenced (WSDL.AST.Operations); -- GNAT Pro 7.2.0w (20130423): package is needed to access to type's -- components. with WSDL.AST.Services; with WSDL.Constants; with WSDL.Generator.Naming_Conventions; package body WSDL.Generator is use WSDL.Constants; package Operation_Maps is new Ada.Containers.Ordered_Maps (League.Strings.Universal_String, WSDL.AST.Interface_Operation_Access, League.Strings."<", WSDL.AST."="); procedure Put (Item : League.Strings.Universal_String); procedure Put_Line (Item : League.Strings.Universal_String); procedure Generate_Service (Service_Node : not null WSDL.AST.Services.Service_Access); procedure Lookup_Binding (Interface_Node : not null WSDL.AST.Interface_Access; Binding_Node : out WSDL.AST.Binding_Access); function Compute_All_Operations (Interface_Node : not null WSDL.AST.Interface_Access) return Operation_Maps.Map; function Compute_SOAP_Action (Operation_Node : not null WSDL.AST.Interface_Operation_Access; Binding_Node : WSDL.AST.Binding_Access) return League.Strings.Universal_String; ---------------------------- -- Compute_All_Operations -- ---------------------------- function Compute_All_Operations (Interface_Node : not null WSDL.AST.Interface_Access) return Operation_Maps.Map is Result : Operation_Maps.Map; procedure Analyze_Interface (Interface_Node : not null WSDL.AST.Interface_Access); ----------------------- -- Analyze_Interface -- ----------------------- procedure Analyze_Interface (Interface_Node : not null WSDL.AST.Interface_Access) is begin -- Fill result by own operations of the interface, but excluding -- all operations which names is in the result already because they -- come from extended interface. for Operation_Node of Interface_Node.Interface_Operations loop if not Result.Contains (Operation_Node.Local_Name) then Result.Insert (Operation_Node.Local_Name, Operation_Node); end if; end loop; for Extended_Interface_Node of Interface_Node.Extended_Interfaces loop Analyze_Interface (Extended_Interface_Node); end loop; end Analyze_Interface; begin Analyze_Interface (Interface_Node); return Result; end Compute_All_Operations; ------------------------- -- Compute_SOAP_Action -- ------------------------- function Compute_SOAP_Action (Operation_Node : not null WSDL.AST.Interface_Operation_Access; Binding_Node : WSDL.AST.Binding_Access) return League.Strings.Universal_String is use type WSDL.AST.Interface_Operation_Access; begin for Binding_Operation of Binding_Node.Binding_Operations loop if Binding_Operation.Interface_Operation = Operation_Node then return Binding_Operation.SOAP.Action; end if; end loop; return League.Strings.Empty_Universal_String; end Compute_SOAP_Action; -------------- -- Generate -- -------------- procedure Generate (Description : not null WSDL.AST.Description_Access) is begin for Service_Node of Description.Services loop Generate_Service (Service_Node); end loop; end Generate; ---------------------- -- Generate_Service -- ---------------------- procedure Generate_Service (Service_Node : not null WSDL.AST.Services.Service_Access) is use type League.Strings.Universal_String; use type WSDL.AST.Binding_Access; use type WSDL.AST.Message_Content_Models; use type WSDL.AST.Message_Directions; use type WSDL.AST.Interface_Message_Access; Binding_Node : WSDL.AST.Binding_Access; Operations : Operation_Maps.Map; Interface_Type_Name : League.Strings.Universal_String; Interface_Package_Name : League.Strings.Universal_String; SOAP_Action : League.Strings.Universal_String; Input_Message : WSDL.AST.Interface_Message_Access; Output_Message : WSDL.AST.Interface_Message_Access; First_Operation : Boolean; begin -- Lookup for corresponding binding component. Lookup_Binding (Service_Node.Interface_Node, Binding_Node); if Binding_Node = null then -- There is no binding for interface element specified. raise Program_Error; end if; if Binding_Node.Binding_Type /= SOAP_Binding_Type then -- This binding type is not supported. raise Program_Error; end if; if Binding_Node.SOAP.Version /= SOAP_Version_12_Literal then -- This version of SOAP is not supported. raise Program_Error; end if; -- Compute set of all interface's operations, including inherited. Operations := Compute_All_Operations (Service_Node.Interface_Node); -- Generate specification of delegation package. Interface_Package_Name := "Generic_" & Naming_Conventions.To_Ada_Identifier (Service_Node.Interface_Node.Local_Name); Interface_Type_Name := Naming_Conventions.To_Ada_Identifier (Service_Node.Interface_Node.Local_Name); Put_Line ("--------------------------------------------------------------------" & "----------"); Put_Line ("-- This compilation unit was generated by WSDL2Ada translator."); Put_Line ("--------------------------------------------------------------------" & "----------"); Put_Line ("pragma Style_Checks (""NM32766"");"); New_Line; Put_Line ("with Web_Services.SOAP.Payloads.Faults;"); Put_Line ("with Payloads;"); New_Line; Put_Line ("generic"); First_Operation := True; for Operation_Node of Operations loop if Operation_Node.Message_Exchange_Pattern.IRI /= In_Out_MEP and Operation_Node.Message_Exchange_Pattern.IRI /= Robust_In_Only_MEP then -- Only in-out and robust-in-only MEPs are supported. raise Program_Error; end if; -- All supported MEPs has at most one input and at most one output -- placeholder. Lookup for input and output messages to simplify -- code. Input_Message := null; Output_Message := null; for Message_Node of Operation_Node.Interface_Message_References loop case Message_Node.Direction is when WSDL.AST.In_Message => Input_Message := Message_Node; when WSDL.AST.Out_Message => Output_Message := Message_Node; end case; end loop; if not First_Operation then New_Line; else First_Operation := False; end if; Put (" with procedure " & Naming_Conventions.To_Ada_Identifier (Operation_Node.Local_Name)); -- Generate input parameter, if any. if Input_Message /= null then if Input_Message.Message_Content_Model not in WSDL.AST.None | WSDL.AST.Element then -- Only '#none' and '#element' message content models are -- supported. raise Program_Error; end if; if Input_Message.Message_Content_Model = WSDL.AST.Element then New_Line; Put (" (Input : Payloads." & Naming_Conventions.To_Ada_Identifier (Input_Message.Element.Local_Name) & "'Class"); end if; end if; -- Generate output parameter, if any. if Output_Message /= null then if Input_Message /= null and then Input_Message.Message_Content_Model = WSDL.AST.Element then Put_Line (";"); Put (" "); else New_Line; Put (" ("); end if; Put ("Output : out Payloads." & Naming_Conventions.To_Ada_Identifier (Output_Message.Element.Local_Name) & "_Access"); end if; -- Generate output fault parameter, if eny. if not Operation_Node.Interface_Fault_References.Is_Empty then Put_Line (";"); Put (" Fault :" & " out Web_Services.SOAP.Payloads.Faults.SOAP_Fault_Access"); end if; Put_Line (");"); end loop; New_Line; Put_Line ("package " & Interface_Package_Name & " is"); New_Line; Put_Line (" procedure Register_Interface;"); New_Line; Put_Line ("end " & Interface_Package_Name & ";"); -- Generate package for invocation dispatching. Put_Line ("--------------------------------------------------------------------" & "----------"); Put_Line ("-- This compilation unit was generated by WSDL2Ada translator."); Put_Line ("--------------------------------------------------------------------" & "----------"); Put_Line ("pragma Style_Checks (""NM32766"");"); New_Line; Put_Line ("with League.Strings;"); Put_Line ("with Web_Services.SOAP.Handler_Registry;"); Put_Line ("with Web_Services.SOAP.Messages;"); Put_Line ("with Web_Services.SOAP.Payloads;"); New_Line; Put_Line ("package body " & Interface_Package_Name & " is"); New_Line; Put_Line (" use type League.Strings.Universal_String;"); New_Line; Put_Line (" function ""+"""); Put_Line (" (Item : Wide_Wide_String)"); Put_Line (" return League.Strings.Universal_String"); Put_Line (" renames League.Strings.To_Universal_String;"); New_Line; Put_Line (" procedure Dispatch"); Put_Line (" (Input : Web_Services.SOAP.Messages.SOAP_Message;"); Put_Line (" Output : out Web_Services.SOAP.Messages.SOAP_Message_Access;"); Put_Line (" Found : in out Boolean);"); New_Line; Put_Line (" --------------"); Put_Line (" -- Dispatch --"); Put_Line (" --------------"); New_Line; Put_Line (" procedure Dispatch"); Put_Line (" (Input : Web_Services.SOAP.Messages.SOAP_Message;"); Put_Line (" Output : out Web_Services.SOAP.Messages.SOAP_Message_Access;"); Put_Line (" Found : in out Boolean)"); Put_Line (" is"); Put_Line (" use type Web_Services.SOAP.Payloads.Faults.SOAP_Fault_Access;"); New_Line; Put_Line (" Fault : Web_Services.SOAP.Payloads.Faults.SOAP_Fault_Access;"); New_Line; Put_Line (" begin"); First_Operation := True; for Operation_Node of Operations loop if Operation_Node.Message_Exchange_Pattern.IRI /= In_Out_MEP and Operation_Node.Message_Exchange_Pattern.IRI /= Robust_In_Only_MEP then -- Only in-out and robust-in-only MEPs are supported. raise Program_Error; end if; -- All supported MEPs has at most one input and at most one output -- placeholder. Lookup for input and output messages to simplify -- code. Input_Message := null; Output_Message := null; for Message_Node of Operation_Node.Interface_Message_References loop case Message_Node.Direction is when WSDL.AST.In_Message => Input_Message := Message_Node; when WSDL.AST.Out_Message => Output_Message := Message_Node; end case; end loop; SOAP_Action := Compute_SOAP_Action (Operation_Node, Binding_Node); if First_Operation then Put (" if"); else New_Line; Put (" elsif"); end if; -- Use SOAP Action to dispatch call when specified. if not SOAP_Action.Is_Empty then Put_Line (" Input.Action = +""" & SOAP_Action & """ then"); else Put_Line (" Input.Namespace_URI = +""" & Input_Message.Element.Namespace_URI & '"'); Put_Line (" and Input.Local_Name = +""" & Input_Message.Element.Local_Name & '"'); Put_Line (" then"); end if; First_Operation := False; Put_Line (" declare"); if Output_Message /= null then Put_Line (" Aux : Payloads." & Naming_Conventions.To_Ada_Identifier (Output_Message.Element.Local_Name) & "_Access;"); New_Line; end if; Put_Line (" begin"); Put_Line (" Found := True;"); Put (" " & Naming_Conventions.To_Ada_Identifier (Operation_Node.Local_Name)); -- Generate input parameter, if any. if Input_Message /= null then if Input_Message.Message_Content_Model not in WSDL.AST.None | WSDL.AST.Element then -- Only '#none' and '#element' message content models are -- supported. raise Program_Error; end if; if Input_Message.Message_Content_Model = WSDL.AST.Element then New_Line; Put (" (Payloads." & Naming_Conventions.To_Ada_Identifier (Input_Message.Element.Local_Name) & "'Class (Input.Payload.all)"); end if; end if; -- Generate output parameter, if any. if Output_Message /= null then if Input_Message = null or else Input_Message.Message_Content_Model /= WSDL.AST.Element then New_Line; Put (" (Aux"); else Put_Line (","); Put (" Aux"); end if; end if; -- Generate output fault parameter, if eny. if not Operation_Node.Interface_Fault_References.Is_Empty then Put_Line (","); Put (" Fault"); end if; Put_Line (");"); if Operation_Node.Message_Exchange_Pattern.IRI = In_Out_MEP then Put_Line (" Output :=" & " new Web_Services.SOAP.Messages.SOAP_Message;"); if not Operation_Node.Interface_Fault_References.Is_Empty then New_Line; Put_Line (" if Fault = null then"); Put_Line (" Output.Payload :="); Put_Line (" " & "Web_Services.SOAP.Payloads.SOAP_Payload_Access (Aux);"); New_Line; Put_Line (" else"); Put_Line (" Output.Payload :="); Put_Line (" " & "Web_Services.SOAP.Payloads.SOAP_Payload_Access (Fault);"); Put_Line (" end if;"); else Put_Line (" Output.Payload :="); Put_Line (" " & "Web_Services.SOAP.Payloads.SOAP_Payload_Access (Aux);"); end if; elsif Operation_Node.Message_Exchange_Pattern.IRI = Robust_In_Only_MEP then -- Generate fault handling code when necessary. if not Operation_Node.Interface_Fault_References.Is_Empty then Put_Line (" Output :=" & " new Web_Services.SOAP.Messages.SOAP_Message;"); Put_Line (" Output.Payload :="); Put_Line (" " & "Web_Services.SOAP.Payloads.SOAP_Payload_Access (Fault);"); end if; end if; Put_Line (" end;"); end loop; Put_Line (" end if;"); Put_Line (" end Dispatch;"); New_Line; Put_Line (" ------------------------"); Put_Line (" -- Register_Interface --"); Put_Line (" ------------------------"); New_Line; Put_Line (" procedure Register_Interface is"); Put_Line (" begin"); Put_Line (" Web_Services.SOAP.Handler_Registry.Register"); Put_Line (" (Dispatch'Unrestricted_Access);"); Put_Line (" end Register_Interface;"); New_Line; Put_Line ("end " & Interface_Package_Name & ";"); end Generate_Service; -------------------- -- Lookup_Binding -- -------------------- procedure Lookup_Binding (Interface_Node : not null WSDL.AST.Interface_Access; Binding_Node : out WSDL.AST.Binding_Access) is use type WSDL.AST.Interface_Access; begin Binding_Node := null; for Binding of Interface_Node.Parent.Bindings loop -- Use default binding when found. Default value will be overwritten -- when interface specific binding will be found. if Binding.Interface_Node = null then Binding_Node := Binding; end if; -- Use interface specific binding when found. if Binding.Interface_Node = Interface_Node then Binding_Node := Binding; exit; end if; end loop; end Lookup_Binding; --------- -- Put -- --------- procedure Put (Item : League.Strings.Universal_String) is begin Put (Item.To_Wide_Wide_String); end Put; -------------- -- Put_Line -- -------------- procedure Put_Line (Item : League.Strings.Universal_String) is begin Put_Line (Item.To_Wide_Wide_String); end Put_Line; end WSDL.Generator;
pragma Style_Checks (Off); with Osint; use Osint; package body Sdefault is S0 : constant String := "/usr/local/"; S1 : constant String := "/usr/local/lib/gcc/i686-pc-linux-gnu/4.4.5/adainclude/"; S2 : constant String := "/usr/local/lib/gcc/i686-pc-linux-gnu/4.4.5/adalib/"; S3 : constant String := "i686-pc-linux-gnu/"; S4 : constant String := "/usr/local/lib/gcc/i686-pc-linux-gnu/4.4.5/"; function Include_Dir_Default_Name return String_Ptr is begin return Relocate_Path (S0, S1); end Include_Dir_Default_Name; function Object_Dir_Default_Name return String_Ptr is begin return Relocate_Path (S0, S2); end Object_Dir_Default_Name; function Target_Name return String_Ptr is begin return new String'(S3); end Target_Name; function Search_Dir_Prefix return String_Ptr is begin return Relocate_Path (S0, S4); end Search_Dir_Prefix; end Sdefault;
with Ada.Numerics.Generic_Elementary_Functions; package body Unit_Conversion_Utilities is package Real_Elementary_Fuctions is new Ada.Numerics.Generic_Elementary_Functions (Real); ---------------- -- Initialize -- ---------------- procedure Initialize (This : out Unit_Converter; LatitudeInit_Rad : Real; LongitudeInit_rad : Real) is dDenominatorMeridional : Real; dDenominatorTransverse : Real; use Real_Elementary_Fuctions; function Pow (Base, Exp : Real) return Real renames Real_Elementary_Fuctions."**"; begin -- if (!m_bInitialized) if not This.Initialized then -- //assumes that the conversions will all take place within the local area of the initial latitude/longitude. -- m_dLatitudeInitial_rad = dLatitudeInit_rad; This.m_dLatitudeInitial_rad := LatitudeInit_Rad; -- m_dLongitudeInitial_rad = dLongitudeInit_rad; This.m_dLongitudeInitial_rad := LongitudeInit_rad; -- double dDenominatorMeridional = std::pow((1.0 - (m_dEccentricitySquared * std::pow(std::sin(dLatitudeInit_rad), 2.0))), (3.0 / 2.0)); dDenominatorMeridional := Pow ((1.0 - (dEccentricitySquared * Pow (Sin (LatitudeInit_rad), 2.0))), (3.0 / 2.0)); -- assert(dDenominatorMeridional > 0.0); pragma Assert (dDenominatorMeridional> 0.0); -- m_dRadiusMeridional_m = (dDenominatorMeridional <= 0.0) ? (0.0) : (m_dRadiusEquatorial_m * (1.0 - m_dEccentricitySquared) / dDenominatorMeridional); This.m_dRadiusMeridional_m := (if dDenominatorMeridional <= 0.0 then 0.0 else (dRadiusEquatorial_m * (1.0 - dEccentricitySquared) / dDenominatorMeridional)); -- double dDenominatorTransverse = pow((1.0 - (m_dEccentricitySquared * std::pow(std::sin(dLatitudeInit_rad), 2.0))), 0.5); dDenominatorTransverse := Pow ((1.0 - (dEccentricitySquared * Pow (Sin (LatitudeInit_rad), 2.0))), 0.5); -- assert(dDenominatorTransverse > 0.0); pragma Assert (dDenominatorTransverse > 0.0); -- m_dRadiusTransverse_m = (dDenominatorTransverse <= 0.0) ? (0.0) : (m_dRadiusEquatorial_m / dDenominatorTransverse); This.m_dRadiusTransverse_m := (if dDenominatorTransverse <= 0.0 then 0.0 else (dRadiusEquatorial_m / dDenominatorTransverse)); -- m_dRadiusSmallCircleLatitude_m = m_dRadiusTransverse_m * cos(dLatitudeInit_rad); This.m_dRadiusSmallCircleLatitude_m := This.m_dRadiusTransverse_m * Cos (LatitudeInit_rad); -- m_bInitialized = true; This.Initialized := True; end if; end Initialize; ------------------------------------------------- -- Convert_LatLong_Degrees_To_NorthEast_Meters -- ------------------------------------------------- procedure Convert_LatLong_Degrees_To_NorthEast_Meters (This : in out Unit_Converter; Latitude_Deg : Real; Longitude_Deg : Real; North : out Real; East : out Real) is DegreesToRadians : constant := 180.0 / Ada.Numerics.Pi; -- double dLatitude_rad = dLatitude_deg * n_Const::c_Convert::dDegreesToRadians(); Latitude_rad : constant Real := Latitude_Deg * DegreesToRadians; -- double dLongitude_rad = dLongitude_deg * n_Const::c_Convert::dDegreesToRadians(); Longitude_rad : constant Real := Longitude_Deg * DegreesToRadians; begin -- //assumes that the conversions will all take place within the local area of the init longitude. -- if (!m_bInitialized) -- { -- Initialize(dLatitude_rad, dLongitude_rad); -- } if not This.Initialized then This.Initialize (LatitudeInit_Rad => Latitude_Rad, LongitudeInit_Rad => Longitude_Rad); end if; -- dNorth_m = m_dRadiusMeridional_m * (dLatitude_rad - m_dLatitudeInitial_rad); North := This.m_dRadiusMeridional_m * (Latitude_Rad - This.m_dLatitudeInitial_rad); -- dEast_m = m_dRadiusSmallCircleLatitude_m * (dLongitude_rad - m_dLongitudeInitial_rad); East := This.m_dRadiusSmallCircleLatitude_m * (Longitude_rad - This.m_dLongitudeInitial_rad); end Convert_LatLong_Degrees_To_NorthEast_Meters; end Unit_Conversion_Utilities;
with Numerics, Ada.Text_IO, Forward_AD.AD2D; use Numerics, Ada.Text_IO, Forward_AD.AD2D; procedure Forward_AD.Bubble is use Real_Functions, Real_IO, Int_IO; type Potential_Function is not null access function (X : in Pos2D_Vector) return AD_Type; function Potential (Q : in Pos2D_Vector) return AD_Type; function Potential (Q : in Pos2D_Vector) return AD_Type is X : AD2D_Vector := To_AD2D_Vector (Q); U : AD_Type := Zero (X'Length); begin for I in X'Range loop for J in I + 1 .. X'Last loop U := U + Square (X (I) - X (J)); end loop; end loop; return U; end Potential; procedure Verlet (Potential : in Potential_Function; X : in Pos2D_Vector; File : in File_Type); procedure Verlet (Potential : in Potential_Function; X : in Pos2D_Vector; File : in File_Type) is U : AD_Type := Potential (X); F : Real_Array := -Grad (U); begin for Item of F loop Put (File => File, Item => Item, Exp => 0, Aft => 3); New_Line (File); end loop; end Verlet; N : constant Nat := 5; M : constant Nat := 8; R2D : Pos2D_Vector (1 .. 2); -- X : Real_Array := (1.0, 2.0, 3.0); File : File_Type; begin R2D (1) := (0.0, 0.0); R2D (2) := (0.0, 1.0); null; Create (File => File, Name => "out.xyz"); Verlet (Potential => Potential'Access, X => R2D, File => File); Close (File => File); end Forward_AD.Bubble;
with System.Storage_Elements; package body System.Bit_Ops is pragma Suppress (All_Checks); use type Storage_Elements.Storage_Element; use type Storage_Elements.Storage_Offset; function Bit_Eq ( Left : Address; Llen : Natural; Right : Address; Rlen : Natural) return Boolean is begin if Llen /= Rlen then return False; else declare type Unsigned is mod 2 ** Integer'Size; Quotient : constant Storage_Elements.Storage_Count := Storage_Elements.Storage_Offset (Llen) / Standard'Storage_Unit; Remainder : constant Natural := Natural (Unsigned (Llen) rem Standard'Storage_Unit); type Unit_Array is array (1 .. Quotient) of Storage_Elements.Storage_Element; L_Units : Unit_Array; for L_Units'Address use Left; R_Units : Unit_Array; for R_Units'Address use Right; begin if L_Units /= R_Units then -- compiler will use memcmp return False; elsif Remainder /= 0 then declare L_Rem : Storage_Elements.Storage_Element; for L_Rem'Address use Left + Quotient; R_Rem : Storage_Elements.Storage_Element; for R_Rem'Address use Right + Quotient; begin case Default_Bit_Order is when High_Order_First => declare Mask : constant Storage_Elements.Storage_Element := not ( Storage_Elements.Shift_Left (1, 8 - Remainder) - 1); begin return (L_Rem and Mask) = (R_Rem and Mask); end; when Low_Order_First => declare Mask : constant Storage_Elements.Storage_Element := Storage_Elements.Shift_Left (1, Remainder) - 1; begin return (L_Rem and Mask) = (R_Rem and Mask); end; end case; end; else return True; end if; end; end if; end Bit_Eq; end System.Bit_Ops;
pragma SPARK_Mode; with Pwm; with Sparkduino; use Sparkduino; package body Zumo_Motors is PWM_L : constant := 10; PWM_R : constant := 9; DIR_L : constant := 8; DIR_R : constant := 7; procedure Init is begin Initd := True; SetPinMode (Pin => PWM_L, Mode => PinMode'Pos (OUTPUT)); SetPinMode (Pin => PWM_R, Mode => PinMode'Pos (OUTPUT)); SetPinMode (Pin => DIR_L, Mode => PinMode'Pos (OUTPUT)); SetPinMode (Pin => DIR_R, Mode => PinMode'Pos (OUTPUT)); Pwm.Configure_Timers; end Init; procedure FlipLeftMotor (Flip : Boolean) is begin FlipLeft := Flip; end FlipLeftMotor; procedure FlipRightMotor (Flip : Boolean) is begin FlipRight := Flip; end FlipRightMotor; procedure SetLeftSpeed (Velocity : Motor_Speed) is Rev : Boolean := False; Speed : Motor_Speed := Velocity; begin if Speed < 0 then Rev := True; Speed := abs Speed; end if; Pwm.SetRate (Index => Pwm.Left, Value => Word (Speed)); if Rev xor FlipLeft then DigitalWrite (Pin => DIR_L, Val => DigPinValue'Pos (HIGH)); else DigitalWrite (Pin => DIR_L, Val => DigPinValue'Pos (LOW)); end if; end SetLeftSpeed; procedure SetRightSpeed (Velocity : Motor_Speed) is Rev : Boolean := False; Speed : Motor_Speed := Velocity; begin if Speed < 0 then Rev := True; Speed := abs Speed; end if; Pwm.SetRate (Index => Pwm.Right, Value => Word (Speed)); if Rev xor FlipRight then DigitalWrite (Pin => DIR_R, Val => DigPinValue'Pos (HIGH)); else DigitalWrite (Pin => DIR_R, Val => DigPinValue'Pos (LOW)); end if; end SetRightSpeed; procedure SetSpeed (LeftVelocity : Motor_Speed; RightVelocity : Motor_Speed) is begin SetLeftSpeed (Velocity => LeftVelocity); SetRightSpeed (Velocity => RightVelocity); end SetSpeed; end Zumo_Motors;
----------------------------------------------------------------------- -- Ada Labs -- -- -- -- Copyright (C) 2008-2013, AdaCore -- -- -- -- Labs is free software; you can redistribute it and/or modify it -- -- under the terms of the GNU General Public License as published by -- -- the Free Software Foundation; either version 2 of the License, or -- -- (at your option) any later version. -- -- -- -- This program is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- General Public License for more details. You should have received -- -- a copy of the GNU General Public License along with this program; -- -- if not, write to the Free Software Foundation, Inc., 59 Temple -- -- Place - Suite 330, Boston, MA 02111-1307, USA. -- ----------------------------------------------------------------------- with GNAT.Strings; use GNAT.Strings; with GL_Gl_H; use GL_Gl_H; with Interfaces.C; use Interfaces.C; with Ada.Containers; with Ada.Containers.Doubly_Linked_Lists; with SDL_SDL_video_h; use SDL_SDL_video_h; with Display.Basic; use Display.Basic; private package Display.Kernel is -- This kernel is managing two sets of data. The protected object -- Data_Manager is responsible to manage a protected set of objects. It -- contains an internal representation of the graphical context, and -- buffers the sequence of commands that issued this representation since -- the last flush performed by the graphical loop. The graphical loops -- contains its own representation of the context (see Shapes in the body), -- which is only updated once at each iteration. type Id_Stack is array (Integer range <>) of Natural; -- This type offers a thread-safe interface to the graphical data. Commands -- are taken into account immediately by its internal state. However, -- the graphical loop will only read those commands once per cycle. type E_Pixel is record R : GLubyte; G : GLubyte; B : GLubyte; A : GLubyte; end record; pragma Convention (C, E_Pixel); type Pixel_Array is array (int range <>) of E_Pixel; pragma Convention (C, Pixel_Array); type Pixel_Array_Access is access all Pixel_Array; At_End : Boolean := False with Atomic; type OpenGL_Surface is record Canvas : Canvas_ID; surface : access SDL_Surface; vidInfo : access SDL_VideoInfo; w : Integer := 400; h : Integer := 400; bpp : Interfaces.C.int := 16; flags : Interfaces.C.unsigned := SDL_OPENGL + SDL_HWSURFACE + SDL_RESIZABLE; end record; procedure UpdateProjection(Canvas : Canvas_ID); procedure Swap_Buffers(S : in out OpenGL_Surface); procedure Poll_Events(S : in out OpenGL_Surface); procedure Reshape (S : in out OpenGL_Surface; W : Integer; H : Integer); function Create_Window(Width:Integer; Height : Integer; Name : String) return OpenGL_Surface; procedure Draw_Sphere (Radius:Float; Color: RGBA_T); procedure DrawDisk (InnerRadius : Float; OuterRadius : Float; VSlices : Integer; HSlices : Integer; Color: RGBA_T); function Is_Stopped return Boolean; function Get_Internal_Cursor return Cursor_T; end Display.Kernel;
with C.unistd; function System.Environment_Block return C.char_ptr_ptr is begin return C.unistd.environ; end System.Environment_Block;
with Ada.Text_IO; procedure Langtons_Ant is Size: constant Positive := 100; -- change this to extend the playground subtype Step is Integer range -1 .. +1; procedure Right(N, W: in out Step) is Tmp: Step := W; begin W := - N; N := Tmp; end Right; procedure Left(N, W: in out Step) is begin for I in 1 .. 3 loop Right(N, W); end loop; end Left; Color_Character: array(Boolean) of Character := (False => ' ', True => '#'); Is_Black: array (1 .. Size, 1 .. Size) of Boolean := (others => (others => False)); -- initially, the world is white; Ant_X, Ant_Y: Natural := Size/2; -- Position of Ant; Ant_North: Step := 1; Ant_West: Step := 0; -- initially, Ant looks northward Iteration: Positive := 1; begin loop -- iterate the loop until an exception is raised if Is_Black(Ant_X, Ant_Y) then Left(Ant_North, Ant_West); else Right(Ant_North, Ant_West); end if; Is_Black(Ant_X, Ant_Y) := not Is_Black(Ant_X, Ant_Y); Ant_X := Ant_X - Ant_North; -- this may raise an exception Ant_Y := Ant_Y - Ant_West; -- this may raise an exception Iteration := Iteration + 1; end loop; exception when Constraint_Error => -- Ant has left its playground ... now output for X in 1 .. Size loop for Y in 1 .. Size loop Ada.Text_IO.Put(Color_Character(Is_Black(X, Y))); end loop; Ada.Text_IO.New_Line; end loop; Ada.Text_IO.Put_Line("# Iteration:" & Integer'Image(Iteration)); end Langtons_Ant;
-- Copyright 2019-2021 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. with System; package Pck is type Enum_Idx is (e_000, e_001, e_002, e_003, e_004, e_005, e_006, e_007, e_008, e_009, e_010, e_011, e_012, e_013, e_014, e_015, e_016, e_017, e_018, e_019, e_020, e_021, e_022, e_023, e_024, e_025, e_026, e_027, e_028, e_029, e_030, e_031, e_032, e_033, e_034, e_035, e_036, e_037, e_038, e_039, e_040, e_041, e_042, e_043, e_044, e_045, e_046, e_047, e_048, e_049, e_050, e_051, e_052, e_053, e_054, e_055, e_056, e_057, e_058, e_059, e_060, e_061, e_062, e_063, e_064, e_065, e_066, e_067, e_068, e_069, e_070, e_071, e_072, e_073, e_074, e_075, e_076, e_077, e_078, e_079, e_080, e_081, e_082, e_083, e_084, e_085, e_086, e_087, e_088, e_089, e_090, e_091, e_092, e_093, e_094, e_095, e_096, e_097, e_098, e_099, e_100, e_101, e_102, e_103, e_104, e_105, e_106, e_107, e_108, e_109, e_110, e_111, e_112, e_113, e_114, e_115, e_116, e_117, e_118, e_119, e_120, e_121, e_122, e_123, e_124, e_125, e_126, e_127, e_128, e_129, e_130, e_131, e_132, e_133, e_134, e_135, e_136, e_137, e_138, e_139, e_140, e_141, e_142, e_143, e_144, e_145, e_146, e_147, e_148, e_149, e_150, e_151, e_152, e_153, e_154, e_155, e_156, e_157, e_158, e_159, e_160, e_161, e_162, e_163, e_164, e_165, e_166, e_167, e_168, e_169, e_170, e_171, e_172, e_173, e_174, e_175, e_176, e_177, e_178, e_179, e_180, e_181, e_182, e_183, e_184, e_185, e_186, e_187, e_188, e_189, e_190, e_191, e_192, e_193, e_194, e_195); type PA is array (Enum_Idx) of Boolean; pragma Pack (PA); type T is array (Enum_Idx) of Boolean; pragma Pack (T); T_Empty : constant T := (others => False); type Bad_Packed_Table is new T; Procedure Do_Nothing (A : System.Address); end Pck;
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Util.Tests; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Get the server function Get_Server return access ASF.Server.Container; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := ""); -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response); -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); end ASF.Tests;
-- C37304A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT ALL FORMS OF CHOICE ARE PERMITTED IN A VARIANT_PART, -- AND, IN PARTICULAR, THAT FORMS LIKE ST RANGE L..R, AND ST ARE -- PERMITTED. -- ASL 7/31/81 -- RM 8/26/82 -- SPS 1/21/83 WITH REPORT; PROCEDURE C37304A IS USE REPORT; BEGIN TEST("C37304A","ALL FORMS OF CHOICE ALLOWED IN A VARIANT_PART"); DECLARE TYPE T IS RANGE 1 .. 10; C5 : CONSTANT T := 5; SUBTYPE S1 IS T RANGE 1 .. 5; SUBTYPE S2 IS T RANGE C5 + 1 .. 7; SUBTYPE SN IS T RANGE C5 + 4 .. C5 - 4 + 7; -- NULL RANGE. SUBTYPE S10 IS T RANGE C5 + 5 .. T'LAST; TYPE VREC( DISC : T := 8 ) IS RECORD CASE DISC IS WHEN SN -- 9..8 | S1 RANGE 1 .. 0 -- 1..0 | S2 RANGE C5 + 2 .. C5 + 1 -- 7..6 | 3 .. 2 -- 3..2 => NULL; WHEN S1 RANGE 4 .. C5 -- 4..5 | S1 RANGE C5 - 4 .. C5 / 2 -- 1..2 | 3 .. 1 + C5 MOD 3 -- 3..3 | SN -- 9..8 | S1 RANGE 5 .. C5 - 1 -- 5..4 | 6 .. 7 -- 6..7 | S10 -- 10..10 | 9 -- 9 | S10 RANGE 10 .. 9 -- 10..9 => NULL; WHEN C5 + C5 - 2 .. 8 -- 8 => NULL; END CASE; END RECORD; V : VREC; BEGIN IF EQUAL(3,3) THEN V := (DISC => 5); END IF; IF V.DISC /= 5 THEN FAILED ("ASSIGNMENT FAILED"); END IF; END; RESULT; END C37304A;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $ -- Purpose: -- Implement permanent element Id on unmodified sources. -- For Id we use hash of an element concatenated with unit unique name. with Asis.Errors; with Asis.Elements; with Asis.Iterator; with Asis.Exceptions; with Asis.Implementation; with Asis.Compilation_Units; package body Asis.Ids is use type W.Unbounded_Wide_String; type State_Information is record Result : Asis.Element; Hash : Asis.ASIS_Integer; end record; procedure Pre_Operation (Element : in Asis.Element; Control : in out Traverse_Control; State : in out State_Information); procedure Post_Operation (Element : in Asis.Element; Control : in out Traverse_Control; State : in out State_Information); --------- -- "<" -- --------- function "<" (Left : in Id; Right : in Id) return Boolean is begin return Left.Hash < Right.Hash or else (Left.Hash = Right.Hash and then Left.Unit < Right.Unit); end "<"; --------- -- ">" -- --------- function ">" (Left : in Id; Right : in Id) return Boolean is begin return Left.Hash > Right.Hash or else (Left.Hash = Right.Hash and then Left.Unit > Right.Unit); end ">"; ------------------- -- Pre_Operation -- ------------------- procedure Pre_Operation (Element : in Asis.Element; Control : in out Traverse_Control; State : in out State_Information) is begin if Hash (Element.all) = State.Hash then State.Result := Element; Control := Terminate_Immediately; end if; end Pre_Operation; -------------------- -- Post_Operation -- -------------------- procedure Post_Operation (Element : in Asis.Element; Control : in out Traverse_Control; State : in out State_Information) is begin null; end Post_Operation; -------------------- -- Create_Element -- -------------------- function Create_Element (The_Id : in Id; The_Context : in Asis.Context) return Asis.Element is use Asis.Errors; use Asis.Compilation_Units; procedure Raise_Error (Text : Wide_String); procedure Search is new Asis.Iterator.Traverse_Element (State_Information); procedure Raise_Error (Text : Wide_String) is begin Asis.Implementation.Set_Status (Value_Error, Text); raise Asis.Exceptions.ASIS_Inappropriate_Element; end Raise_Error; Unit : Asis.Compilation_Unit; State : State_Information; Control : Traverse_Control := Continue; List : constant Asis.Compilation_Unit_List := Compilation_Units.Compilation_Units (The_Context); begin for I in List'Range loop if Unique_Name (List (I)) = The_Id.Unit then Unit := List (I); exit; end if; end loop; if Is_Nil (Unit) then Raise_Error ("No such unit"); else State.Hash := The_Id.Hash + Hash (Unit.all); end if; declare Clause : constant Asis.Element_List := Context_Clause_Elements (Unit.all, True); begin for I in Clause'Range loop Search (Clause (I), Control, State); if Assigned (State.Result) then return State.Result; end if; end loop; end; Search (Unit_Declaration (Unit.all), Control, State); if Assigned (State.Result) then return State.Result; else Raise_Error ("No element for this id"); return Nil_Element; end if; end Create_Element; --------------- -- Create_Id -- --------------- function Create_Id (Element : in Asis.Element) return Id is use Asis.Elements; use Asis.Compilation_Units; Result : Asis.ASIS_Integer; The_Unit : Asis.Compilation_Unit := Enclosing_Compilation_Unit (Element); begin if not Assigned (Element) then return Nil_Id; end if; The_Unit := Enclosing_Compilation_Unit (Element); Result := Hash (Element) - Hash (The_Unit.all); return (Result, W.To_Unbounded_Wide_String (Unique_Name (The_Unit))); end Create_Id; ----------------- -- Debug_Image -- ----------------- function Debug_Image (The_Id : in Id) return Wide_String is begin return ASIS_Integer'Wide_Image (The_Id.Hash) & "/" & W.To_Wide_String (The_Id.Unit); end Debug_Image; ---------- -- Hash -- ---------- function Hash (The_Id : in Id) return Asis.ASIS_Integer is begin return The_Id.Hash; end Hash; -------------- -- Is_Equal -- -------------- function Is_Equal (Left : in Id; Right : in Id) return Boolean is begin return Left.Hash = Right.Hash and then Left.Unit = Right.Unit; end Is_Equal; ------------ -- Is_Nil -- ------------ function Is_Nil (Right : in Id) return Boolean is begin return Right.Hash = 0 and then Right.Unit = ""; end Is_Nil; end Asis.Ids; ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
-- part of AdaYaml, (c) 2017 Felix Krause -- released under the terms of the MIT license, see the file "copying.txt" with Ada.Directories; with Ada.Direct_IO; package body Utils is function File_Content (Path : String) return String is File_Size : constant Natural := Natural (Ada.Directories.Size (Path)); subtype File_String is String (1 .. File_Size); package File_String_IO is new Ada.Direct_IO (File_String); File : File_String_IO.File_Type; begin File_String_IO.Open (File, File_String_IO.In_File, Path); return Contents : File_String do File_String_IO.Read (File, Contents); File_String_IO.Close (File); end return; end File_Content; end Utils;
-- $Id: DynArray.mi,v 1.8 1994/06/13 09:41:43 grosch rel $ -- $Log: DynArray.mi,v $ -- Ich, Doktor Josef Grosch, Informatiker, Aug. 1994 with Unchecked_Deallocation; package body DynArray is procedure Free is new Unchecked_Deallocation (tArray, FlexArray); procedure MakeArray (ArrayPtr : out FlexArray ; ElmtCount : Integer ) is begin ArrayPtr := new tArray (0 .. ElmtCount - 1); end MakeArray; procedure ResizeArray (ArrayPtr : in out FlexArray ; OldElmtCount : in out Integer ; NewElmtCount : Integer ) is NewPtr : FlexArray := new tArray (0 .. NewElmtCount - 1); begin if NewElmtCount < OldElmtCount then OldElmtCount := NewElmtCount; end if; NewPtr (0 .. OldElmtCount - 1) := ArrayPtr (0 .. OldElmtCount - 1); Free (ArrayPtr); ArrayPtr := NewPtr; OldElmtCount := NewElmtCount; end ResizeArray; procedure ExtendArray (ArrayPtr : in out FlexArray ; ElmtCount : in out Integer ) is begin ResizeArray (ArrayPtr, ElmtCount, ElmtCount * 2); end ExtendArray; procedure ReleaseArray (ArrayPtr : in out FlexArray ; ElmtCount : Integer ) is begin Free (ArrayPtr); end ReleaseArray; end DynArray;
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- G N A T . M D 5 -- -- -- -- S p e c -- -- -- -- XXXXXXXXX (C) 2002-2008, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package implements the MD5 Message-Digest Algorithm as described in -- RFC 1321. The complete text of RFC 1321 can be found at: -- -- http://www.ietf.org/rfc/rfc1321.txt -- -- The implementation is derived from the RSA Data Security, Inc. MD5 -- Message-Digest Algorithm, as described in RFC 1321. with Ada.Streams; with Interfaces; package GNAT.MD5 is type Context is private; -- This type is the four-word (16 byte) MD buffer, as described in -- RFC 1321 (3.3). Its initial value is Initial_Context below. Initial_Context : constant Context; -- Initial value of a Context object. May be used to reinitialize -- a Context value by simple assignment of this value to the object. procedure Update (C : in out Context; Input : String); procedure Wide_Update (C : in out Context; Input : Wide_String); procedure Update (C : in out Context; Input : Ada.Streams.Stream_Element_Array); -- Modify the Context C. If C has the initial value Initial_Context, -- then, after a call to one of these procedures, Digest (C) will return -- the Message-Digest of Input. -- -- These procedures may be called successively with the same context and -- different inputs, and these several successive calls will produce -- the same final context as a call with the concatenation of the inputs. subtype Message_Digest is String (1 .. 32); -- The string type returned by function Digest function Digest (C : Context) return Message_Digest; -- Extracts the Message-Digest from a context. This function should be -- used after one or several calls to Update. function Digest (S : String) return Message_Digest; function Wide_Digest (W : Wide_String) return Message_Digest; function Digest (A : Ada.Streams.Stream_Element_Array) return Message_Digest; -- These functions are equivalent to the corresponding Update (or -- Wide_Update) on a default initialized Context, followed by Digest -- on the resulting Context. private -- Magic numbers Initial_A : constant := 16#67452301#; Initial_B : constant := 16#EFCDAB89#; Initial_C : constant := 16#98BADCFE#; Initial_D : constant := 16#10325476#; type Context is record A : Interfaces.Unsigned_32 := Initial_A; B : Interfaces.Unsigned_32 := Initial_B; C : Interfaces.Unsigned_32 := Initial_C; D : Interfaces.Unsigned_32 := Initial_D; Buffer : String (1 .. 64) := (others => ASCII.NUL); Last : Natural := 0; Length : Natural := 0; end record; Initial_Context : constant Context := (A => Initial_A, B => Initial_B, C => Initial_C, D => Initial_D, Buffer => (others => ASCII.NUL), Last => 0, Length => 0); end GNAT.MD5;
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- G N A T . R E G P A T -- -- -- -- S p e c -- -- -- -- Copyright (C) 1986 by University of Toronto. -- -- Copyright (C) 1996-2006, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- -- -- -- -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package implements roughly the same set of regular expressions as -- are available in the Perl or Python programming languages. -- This is an extension of the original V7 style regular expression library -- written in C by Henry Spencer. Apart from the translation to Ada, the -- interface has been considerably changed to use the Ada String type -- instead of C-style nul-terminated strings. ------------------------------------------------------------ -- Summary of Pattern Matching Packages in GNAT Hierarchy -- ------------------------------------------------------------ -- There are three related packages that perform pattern maching functions. -- the following is an outline of these packages, to help you determine -- which is best for your needs. -- GNAT.Regexp (files g-regexp.ads/g-regexp.adb) -- This is a simple package providing Unix-style regular expression -- matching with the restriction that it matches entire strings. It -- is particularly useful for file name matching, and in particular -- it provides "globbing patterns" that are useful in implementing -- unix or DOS style wild card matching for file names. -- GNAT.Regpat (files g-regpat.ads/g-regpat.adb) -- This is a more complete implementation of Unix-style regular -- expressions, copied from the Perl regular expression engine, -- written originally in C by Henry Spencer. It is functionally the -- same as that library. -- GNAT.Spitbol.Patterns (files g-spipat.ads/g-spipat.adb) -- This is a completely general pattern matching package based on the -- pattern language of SNOBOL4, as implemented in SPITBOL. The pattern -- language is modeled on context free grammars, with context sensitive -- extensions that provide full (type 0) computational capabilities. package GNAT.Regpat is pragma Preelaborate; -- The grammar is the following: -- regexp ::= expr -- ::= ^ expr -- anchor at the beginning of string -- ::= expr $ -- anchor at the end of string -- expr ::= term -- ::= term | term -- alternation (term or term ...) -- term ::= item -- ::= item item ... -- concatenation (item then item) -- item ::= elmt -- match elmt -- ::= elmt * -- zero or more elmt's -- ::= elmt + -- one or more elmt's -- ::= elmt ? -- matches elmt or nothing -- ::= elmt *? -- zero or more times, minimum number -- ::= elmt +? -- one or more times, minimum number -- ::= elmt ?? -- zero or one time, minimum number -- ::= elmt { num } -- matches elmt exactly num times -- ::= elmt { num , } -- matches elmt at least num times -- ::= elmt { num , num2 } -- matches between num and num2 times -- ::= elmt { num }? -- matches elmt exactly num times -- ::= elmt { num , }? -- matches elmt at least num times -- non-greedy version -- ::= elmt { num , num2 }? -- matches between num and num2 times -- non-greedy version -- elmt ::= nchr -- matches given character -- ::= [range range ...] -- matches any character listed -- ::= [^ range range ...] -- matches any character not listed -- ::= . -- matches any single character -- -- except newlines -- ::= ( expr ) -- parens used for grouping -- ::= \ num -- reference to num-th parenthesis -- range ::= char - char -- matches chars in given range -- ::= nchr -- ::= [: posix :] -- any character in the POSIX range -- ::= [:^ posix :] -- not in the POSIX range -- posix ::= alnum -- alphanumeric characters -- ::= alpha -- alphabetic characters -- ::= ascii -- ascii characters (0 .. 127) -- ::= cntrl -- control chars (0..31, 127..159) -- ::= digit -- digits ('0' .. '9') -- ::= graph -- graphic chars (32..126, 160..255) -- ::= lower -- lower case characters -- ::= print -- printable characters (32..127) -- ::= punct -- printable, except alphanumeric -- ::= space -- space characters -- ::= upper -- upper case characters -- ::= word -- alphanumeric characters -- ::= xdigit -- hexadecimal chars (0..9, a..f) -- char ::= any character, including special characters -- ASCII.NUL is not supported. -- nchr ::= any character except \()[].*+?^ or \char to match char -- \n means a newline (ASCII.LF) -- \t means a tab (ASCII.HT) -- \r means a return (ASCII.CR) -- \b matches the empty string at the beginning or end of a -- word. A word is defined as a set of alphanumerical -- characters (see \w below). -- \B matches the empty string only when *not* at the -- beginning or end of a word. -- \d matches any digit character ([0-9]) -- \D matches any non digit character ([^0-9]) -- \s matches any white space character. This is equivalent -- to [ \t\n\r\f\v] (tab, form-feed, vertical-tab,... -- \S matches any non-white space character. -- \w matches any alphanumeric character or underscore. -- This include accented letters, as defined in the -- package Ada.Characters.Handling. -- \W matches any non-alphanumeric character. -- \A match the empty string only at the beginning of the -- string, whatever flags are used for Compile (the -- behavior of ^ can change, see Regexp_Flags below). -- \G match the empty string only at the end of the -- string, whatever flags are used for Compile (the -- behavior of $ can change, see Regexp_Flags below). -- ... ::= is used to indication repetition (one or more terms) -- Embedded newlines are not matched by the ^ operator. -- It is possible to retrieve the substring matched a parenthesis -- expression. Although the depth of parenthesis is not limited in the -- regexp, only the first 9 substrings can be retrieved. -- The highest value possible for the arguments to the curly operator ({}) -- are given by the constant Max_Curly_Repeat below. -- The operators '*', '+', '?' and '{}' always match the longest possible -- substring. They all have a non-greedy version (with an extra ? after the -- operator), which matches the shortest possible substring. -- For instance: -- regexp="<.*>" string="<h1>title</h1>" matches="<h1>title</h1>" -- regexp="<.*?>" string="<h1>title</h1>" matches="<h1>" -- -- '{' and '}' are only considered as special characters if they appear -- in a substring that looks exactly like '{n}', '{n,m}' or '{n,}', where -- n and m are digits. No space is allowed. In other contexts, the curly -- braces will simply be treated as normal characters. -- Compiling Regular Expressions -- ============================= -- To use this package, you first need to compile the regular expression -- (a string) into a byte-code program, in a Pattern_Matcher structure. -- This first step checks that the regexp is valid, and optimizes the -- matching algorithms of the second step. -- Two versions of the Compile subprogram are given: one in which this -- package will compute itself the best possible size to allocate for the -- byte code; the other where you must allocate enough memory yourself. An -- exception is raised if there is not enough memory. -- declare -- Regexp : String := "a|b"; -- Matcher : Pattern_Matcher := Compile (Regexp); -- -- The size for matcher is automatically allocated -- Matcher2 : Pattern_Matcher (1000); -- -- Some space is allocated directly. -- begin -- Compile (Matcher2, Regexp); -- ... -- end; -- Note that the second version is significantly faster, since with the -- first version the regular expression has in fact to be compiled twice -- (first to compute the size, then to generate the byte code). -- Note also that you cannot use the function version of Compile if you -- specify the size of the Pattern_Matcher, since the discriminants will -- most probably be different and you will get a Constraint_Error -- Matching Strings -- ================ -- Once the regular expression has been compiled, you can use it as often -- as needed to match strings. -- Several versions of the Match subprogram are provided, with different -- parameters and return results. -- See the description under each of these subprograms -- Here is a short example showing how to get the substring matched by -- the first parenthesis pair. -- declare -- Matches : Match_Array (0 .. 1); -- Regexp : String := "a(b|c)d"; -- Str : String := "gacdg"; -- begin -- Match (Compile (Regexp), Str, Matches); -- return Str (Matches (1).First .. Matches (1).Last); -- -- returns 'c' -- end; -- Finding all occurrences -- ======================= -- Finding all the occurrences of a regular expression in a string cannot -- be done by simply passing a slice of the string. This wouldn't work for -- anchored regular expressions (the ones starting with "^" or ending with -- "$"). -- Instead, you need to use the last parameter to Match (Data_First), as in -- the following loop: -- declare -- Str : String := -- "-- first line" & ASCII.LF & "-- second line"; -- Matches : Match_array (0 .. 0); -- Regexp : Pattern_Matcher := Compile ("^--", Multiple_Lines); -- Current : Natural := Str'First; -- begin -- loop -- Match (Regexp, Str, Matches, Current); -- exit when Matches (0) = No_Match; -- -- -- Process the match at position Matches (0).First -- -- Current := Matches (0).Last + 1; -- end loop; -- end; -- String Substitution -- =================== -- No subprogram is currently provided for string substitution. -- However, this is easy to simulate with the parenthesis groups, as -- shown below. -- This example swaps the first two words of the string: -- declare -- Regexp : String := "([a-z]+) +([a-z]+)"; -- Str : String := " first second third "; -- Matches : Match_Array (0 .. 2); -- begin -- Match (Compile (Regexp), Str, Matches); -- return Str (Str'First .. Matches (1).First - 1) -- & Str (Matches (2).First .. Matches (2).Last) -- & " " -- & Str (Matches (1).First .. Matches (1).Last) -- & Str (Matches (2).Last + 1 .. Str'Last); -- -- returns " second first third " -- end; --------------- -- Constants -- --------------- Expression_Error : exception; -- This exception is raised when trying to compile an invalid regular -- expression. All subprograms taking an expression as parameter may raise -- Expression_Error. Max_Paren_Count : constant := 255; -- Maximum number of parenthesis in a regular expression. This is limited -- by the size of a Character, as found in the byte-compiled version of -- regular expressions. Max_Curly_Repeat : constant := 32767; -- Maximum number of repetition for the curly operator. The digits in the -- {n}, {n,} and {n,m } operators cannot be higher than this constant, -- since they have to fit on two characters in the byte-compiled version of -- regular expressions. Max_Program_Size : constant := 2**15 - 1; -- Maximum size that can be allocated for a program type Program_Size is range 0 .. Max_Program_Size; for Program_Size'Size use 16; -- Number of bytes allocated for the byte-compiled version of a regular -- expression. The size required depends on the complexity of the regular -- expression in a complex manner that is undocumented (other than in the -- body of the Compile procedure). Normally the size is automatically set -- and the programmer need not be concerned about it. There are two -- exceptions to this. First in the calls to Match, it is possible to -- specify a non-zero size that is known to be large enough. This can -- slightly increase the efficiency by avoiding a copy. Second, in the case -- of calling compile, it is possible using the procedural form of Compile -- to use a single Pattern_Matcher variable for several different -- expressions by setting its size sufficiently large. Auto_Size : constant := 0; -- Used in calls to Match to indicate that the Size should be set to -- a value appropriate to the expression being used automatically. type Regexp_Flags is mod 256; for Regexp_Flags'Size use 8; -- Flags that can be given at compile time to specify default -- properties for the regular expression. No_Flags : constant Regexp_Flags; Case_Insensitive : constant Regexp_Flags; -- The automaton is optimized so that the matching is done in a case -- insensitive manner (upper case characters and lower case characters -- are all treated the same way). Single_Line : constant Regexp_Flags; -- Treat the Data we are matching as a single line. This means that -- ^ and $ will ignore \n (unless Multiple_Lines is also specified), -- and that '.' will match \n. Multiple_Lines : constant Regexp_Flags; -- Treat the Data as multiple lines. This means that ^ and $ will also -- match on internal newlines (ASCII.LF), in addition to the beginning -- and end of the string. -- -- This can be combined with Single_Line. ----------------- -- Match_Array -- ----------------- subtype Match_Count is Natural range 0 .. Max_Paren_Count; type Match_Location is record First : Natural := 0; Last : Natural := 0; end record; type Match_Array is array (Match_Count range <>) of Match_Location; -- The substring matching a given pair of parenthesis. Index 0 is the whole -- substring that matched the full regular expression. -- -- For instance, if your regular expression is something like: "a(b*)(c+)", -- then Match_Array(1) will be the indexes of the substring that matched -- "b*" and Match_Array(2) will be the substring that matched "c+". -- -- The number of parenthesis groups that can be retrieved is unlimited, and -- all the Match subprograms below can use a Match_Array of any size. -- Indexes that do not have any matching parenthesis are set to No_Match. No_Match : constant Match_Location := (First => 0, Last => 0); -- The No_Match constant is (0, 0) to differentiate between matching a null -- string at position 1, which uses (1, 0) and no match at all. --------------------------------- -- Pattern_Matcher Compilation -- --------------------------------- -- The subprograms here are used to precompile regular expressions for use -- in subsequent Match calls. Precompilation improves efficiency if the -- same regular expression is to be used in more than one Match call. type Pattern_Matcher (Size : Program_Size) is private; -- Type used to represent a regular expression compiled into byte code Never_Match : constant Pattern_Matcher; -- A regular expression that never matches anything function Compile (Expression : String; Flags : Regexp_Flags := No_Flags) return Pattern_Matcher; -- Compile a regular expression into internal code -- -- Raises Expression_Error if Expression is not a legal regular expression -- -- The appropriate size is calculated automatically to correspond to the -- provided expression. This is the normal default method of compilation. -- Note that it is generally not possible to assign the result of two -- different calls to this Compile function to the same Pattern_Matcher -- variable, since the sizes will differ. -- -- Flags is the default value to use to set properties for Expression -- (e.g. case sensitivity,...). procedure Compile (Matcher : out Pattern_Matcher; Expression : String; Final_Code_Size : out Program_Size; Flags : Regexp_Flags := No_Flags); -- Compile a regular expression into into internal code -- This procedure is significantly faster than the Compile function since -- it avoids the extra step of precomputing the required size. -- -- However, it requires the user to provide a Pattern_Matcher variable -- whose size is preset to a large enough value. One advantage of this -- approach, in addition to the improved efficiency, is that the same -- Pattern_Matcher variable can be used to hold the compiled code for -- several different regular expressions by setting a size that is large -- enough to accomodate all possibilities. -- -- In this version of the procedure call, the actual required code size is -- returned. Also if Matcher.Size is zero on entry, then the resulting code -- is not stored. A call with Matcher.Size set to Auto_Size can thus be -- used to determine the space required for compiling the given regular -- expression. -- -- This function raises Storage_Error if Matcher is too small to hold -- the resulting code (i.e. Matcher.Size has too small a value). -- -- Expression_Error is raised if the string Expression does not contain -- a valid regular expression. -- -- Flags is the default value to use to set properties for Expression (case -- sensitivity,...). procedure Compile (Matcher : out Pattern_Matcher; Expression : String; Flags : Regexp_Flags := No_Flags); -- -- Same procedure as above, expect it does not return the final -- -- program size, and Matcher.Size cannot be Auto_Size. function Paren_Count (Regexp : Pattern_Matcher) return Match_Count; pragma Inline (Paren_Count); -- Return the number of parenthesis pairs in Regexp. -- -- This is the maximum index that will be filled if a Match_Array is -- used as an argument to Match. -- -- Thus, if you want to be sure to get all the parenthesis, you should -- do something like: -- -- declare -- Regexp : Pattern_Matcher := Compile ("a(b*)(c+)"); -- Matched : Match_Array (0 .. Paren_Count (Regexp)); -- begin -- Match (Regexp, "a string", Matched); -- end; ------------- -- Quoting -- ------------- function Quote (Str : String) return String; -- Return a version of Str so that every special character is quoted. -- The resulting string can be used in a regular expression to match -- exactly Str, whatever character was present in Str. -------------- -- Matching -- -------------- -- The Match subprograms are given a regular expression in string -- form, and perform the corresponding match. The following parameters -- are present in all forms of the Match call. -- Expression contains the regular expression to be matched as a string -- Data contains the string to be matched -- Data_First is the lower bound for the match, i.e. Data (Data_First) -- will be the first character to be examined. If Data_First is set to -- the special value of -1 (the default), then the first character to -- be examined is Data (Data_First). However, the regular expression -- character ^ (start of string) still refers to the first character -- of the full string (Data (Data'First)), which is why there is a -- separate mechanism for specifying Data_First. -- Data_Last is the upper bound for the match, i.e. Data (Data_Last) -- will be the last character to be examined. If Data_Last is set to -- the special value of Positive'Last (the default), then the last -- character to be examined is Data (Data_Last). However, the regular -- expression character $ (end of string) still refers to the last -- character of the full string (Data (Data'Last)), which is why there -- is a separate mechanism for specifying Data_Last. -- Note: the use of Data_First and Data_Last is not equivalent to -- simply passing a slice as Expression because of the handling of -- regular expression characters ^ and $. -- Size is the size allocated for the compiled byte code. Normally -- this is defaulted to Auto_Size which means that the appropriate -- size is allocated automatically. It is possible to specify an -- explicit size, which must be sufficiently large. This slightly -- increases the efficiency by avoiding the extra step of computing -- the appropriate size. -- The following exceptions can be raised in calls to Match -- -- Storage_Error is raised if a non-zero value is given for Size -- and it is too small to hold the compiled byte code. -- -- Expression_Error is raised if the given expression is not a legal -- regular expression. procedure Match (Expression : String; Data : String; Matches : out Match_Array; Size : Program_Size := Auto_Size; Data_First : Integer := -1; Data_Last : Positive := Positive'Last); -- This version returns the result of the match stored in Match_Array. -- At most Matches'Length parenthesis are returned. function Match (Expression : String; Data : String; Size : Program_Size := Auto_Size; Data_First : Integer := -1; Data_Last : Positive := Positive'Last) return Natural; -- This version returns the position where Data matches, or if there is -- no match, then the value Data'First - 1. function Match (Expression : String; Data : String; Size : Program_Size := Auto_Size; Data_First : Integer := -1; Data_Last : Positive := Positive'Last) return Boolean; -- This version returns True if the match succeeds, False otherwise ------------------------------------------------ -- Matching a Pre-Compiled Regular Expression -- ------------------------------------------------ -- The following functions are significantly faster if you need to reuse -- the same regular expression multiple times, since you only have to -- compile it once. For these functions you must first compile the -- expression with a call to Compile as previously described. -- The parameters Data, Data_First and Data_Last are as described -- in the previous section. function Match (Self : Pattern_Matcher; Data : String; Data_First : Integer := -1; Data_Last : Positive := Positive'Last) return Natural; -- Match Data using the given pattern matcher. Returns the position -- where Data matches, or (Data'First - 1) if there is no match. function Match (Self : Pattern_Matcher; Data : String; Data_First : Integer := -1; Data_Last : Positive := Positive'Last) return Boolean; -- Return True if Data matches using the given pattern matcher pragma Inline (Match); -- All except the last one below procedure Match (Self : Pattern_Matcher; Data : String; Matches : out Match_Array; Data_First : Integer := -1; Data_Last : Positive := Positive'Last); -- Match Data using the given pattern matcher and store result in Matches. -- The expression matches if Matches (0) /= No_Match. The lower bound of -- Matches is required to be zero. -- -- At most Matches'Length parenthesis are returned ----------- -- Debug -- ----------- procedure Dump (Self : Pattern_Matcher); -- Dump the compiled version of the regular expression matched by Self -------------------------- -- Private Declarations -- -------------------------- private subtype Pointer is Program_Size; -- The Pointer type is used to point into Program_Data -- Note that the pointer type is not necessarily 2 bytes -- although it is stored in the program using 2 bytes type Program_Data is array (Pointer range <>) of Character; Program_First : constant := 1; -- The "internal use only" fields in regexp are present to pass info from -- compile to execute that permits the execute phase to run lots faster on -- simple cases. They are: -- First character that must begin a match or ASCII.Nul -- Anchored true iff match must start at beginning of line -- Must_Have pointer to string that match must include or null -- Must_Have_Length length of Must_Have string -- First and Anchored permit very fast decisions on suitable starting -- points for a match, cutting down the work a lot. Must_Have permits fast -- rejection of lines that cannot possibly match. -- The Must_Have tests are costly enough that Optimize supplies a Must_Have -- only if the r.e. contains something potentially expensive (at present, -- the only such thing detected is * or at the start of the r.e., which can -- involve a lot of backup). The length is supplied because the test in -- Execute needs it and Optimize is computing it anyway. -- The initialization is meant to fail-safe in case the user of this -- package tries to use an uninitialized matcher. This takes advantage -- of the knowledge that ASCII.Nul translates to the end-of-program (EOP) -- instruction code of the state machine. No_Flags : constant Regexp_Flags := 0; Case_Insensitive : constant Regexp_Flags := 1; Single_Line : constant Regexp_Flags := 2; Multiple_Lines : constant Regexp_Flags := 4; type Pattern_Matcher (Size : Pointer) is record First : Character := ASCII.NUL; -- internal use only Anchored : Boolean := False; -- internal use only Must_Have : Pointer := 0; -- internal use only Must_Have_Length : Natural := 0; -- internal use only Paren_Count : Natural := 0; -- # paren groups Flags : Regexp_Flags := No_Flags; Program : Program_Data (Program_First .. Size) := (others => ASCII.NUL); end record; Never_Match : constant Pattern_Matcher := (0, ASCII.NUL, False, 0, 0, 0, No_Flags, (others => ASCII.NUL)); end GNAT.Regpat;
-- ============================================================================= -- Package AVR.TIMERS.SCHEDULER -- -- Implements timers configurations specific for a fixed scheduler which uses -- for handling scheduler-type threads. -- -- This timer is used for handling the device clock: -- - TIMER1_COMPA (16 bits timer) -- -- These timers are configured for Clear Timer on Compare (CTC) to handle each -- task: -- - TIMER5_COMPA (16 bits timer) -- - TIMER5_COMPB (16 bits timer) -- - TIMER5_COMPC (16 bits timer) -- - TIMER0_COMPA (8 bits timer) -- ============================================================================= package AVR.TIMERS.SCHEDULER is -- Initialize Timer1 or Timer5 channels as CTC procedure Initialize_CTC_Timer (Timer : TIMERS.Timer_Type; Priority : TIMERS.Channel_Priority_Type); end AVR.TIMERS.SCHEDULER;
------------------------------------------------------------------------------ -- Copyright (c) 2013-2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.S_Expressions.Test_Tools provides tools used in S-expression -- -- test suites. -- -- Memory_Stream is a stream implementation around a memory buffer where -- -- written data can be subsequently read. A secondary buffer of expected -- -- data can be optionally used, and the mismatch marker is set when written -- -- data does not match expected data. -- ------------------------------------------------------------------------------ with Ada.Streams; with Natools.Tests; with Natools.S_Expressions.Atom_Buffers; with Natools.S_Expressions.Caches; package Natools.S_Expressions.Test_Tools is pragma Preelaborate (Test_Tools); package NT renames Natools.Tests; procedure Dump_Atom (Report : in out NT.Reporter'Class; Data : in Atom; Label : in String := ""); procedure Dump_Atom (Test : in out NT.Test; Data : in Atom; Label : in String := ""); -- Dump contents on Data as info in Report procedure Test_Atom (Report : in out NT.Reporter'Class; Test_Name : in String; Expected : in Atom; Found : in Atom); procedure Test_Atom (Test : in out NT.Test; Expected : in Atom; Found : in Atom); -- Report success when Found is equal to Expected, and failure -- with diagnostics otherwise. procedure Test_Atom_Accessors (Test : in out NT.Test; Tested : in Descriptor'Class; Expected : in Atom; Expected_Level : in Integer := -1; Context : in String := ""); -- Test all the ways of accessing atom in Tested procedure Test_Atom_Accessor_Exceptions (Test : in out NT.Test; Tested : in Descriptor'Class; Context : in String := ""); -- Check that all atom accessors raise Program_Error procedure Next_And_Check (Test : in out NT.Test; Tested : in out Descriptor'Class; Expected : in Events.Event; Level : in Natural; Context : in String := ""); -- Call Tested.Next and check the current event and level procedure Next_And_Check (Test : in out NT.Test; Tested : in out Descriptor'Class; Expected : in Atom; Level : in Natural; Context : in String := ""); -- Call Tested.Next and check current event is Add_Atom with Expected, -- using Test_Atom_Accessors. function To_S_Expression (Text : String) return Caches.Reference; function To_S_Expression (Data : Atom) return Caches.Reference; -- Store a S-expression from its serialization type Memory_Stream is new Ada.Streams.Root_Stream_Type with private; overriding procedure Read (Stream : in out Memory_Stream; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Consume data from the beginning of internal buffer overriding procedure Write (Stream : in out Memory_Stream; Item : in Ada.Streams.Stream_Element_Array); -- Append data at the end of internal buffer function Get_Data (Stream : Memory_Stream) return Atom; -- Return internal buffer function Unread_Data (Stream : Memory_Stream) return Atom; -- Return part of internal buffer that has not yet been read procedure Set_Data (Stream : in out Memory_Stream; Data : in Atom); -- Replace whole internal buffer with Data function Unread_Expected (Stream : Memory_Stream) return Atom; -- Return part of expected buffer that has not been matched yet procedure Set_Expected (Stream : in out Memory_Stream; Data : in Atom; Reset_Mismatch : in Boolean := True); -- Replace buffer of expected data function Has_Mismatch (Stream : Memory_Stream) return Boolean; procedure Reset_Mismatch (Stream : in out Memory_Stream); -- Accessor and mutator of the mismatch flag function Mismatch_Index (Stream : Memory_Stream) return Count; -- Return the position of the first mismatching octet, -- or 0 when there has been no mismatch. procedure Check_Stream (Stream : in Test_Tools.Memory_Stream; Test : in out NT.Test); -- On error in Stream, report error and dump relevant information. private type Memory_Stream is new Ada.Streams.Root_Stream_Type with record Internal : Atom_Buffers.Atom_Buffer; Expected : Atom_Buffers.Atom_Buffer; Read_Pointer : Count := 0; Expect_Pointer : Count := 0; Mismatch : Boolean := False; end record; end Natools.S_Expressions.Test_Tools;
with Libadalang.Analysis; use Libadalang.Analysis; with Libadalang.Common; use Libadalang.Common; with String_Vectors; use String_Vectors; private with Ada.Strings.Unbounded; package Generators is -- For now: single placeholder - so single Name -- package String_Vector_Vectors is new Ada.Containers.Indefinite_Vectors -- (Index_Type => Positive, -- Element_Type => String_Vectors.Vector); type Generator is private; function Generate_Pattern (G : Generator) return Analysis_Unit; function Generate_Instance (G : Generator) return Analysis_Unit; function Get_Name (G : Generator) return String; function Get_Values (G : Generator) return String_Vectors.Vector; type String_Generator is not null access function (Strings : String_Vectors.Vector) return String; function Make_Generator (Name : String; Values : String_Vectors.Vector; Rule : Grammar_Rule; SG : String_Generator ) return Generator; private use Ada.Strings.Unbounded; type Generator is record Name : Unbounded_String; Values : String_Vectors.Vector; -- TODO: is a copy needed to make it immutable from the outside? Rule : Grammar_Rule; SG : String_Generator; end record; function Make_Generator (Name : String; Values : String_Vectors.Vector; Rule : Grammar_Rule; SG : String_Generator) return Generator is ((To_Unbounded_String (Name), Values, Rule, SG)); function Get_Name (G : Generator) return String is (To_String (G.Name)); function Get_Values (G : Generator) return String_Vectors.Vector is (G.Values); end Generators;
----------------------------------------------------------------------- -- AWA.Settings.Models -- AWA.Settings.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-body.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body AWA.Settings.Models is use type ADO.Objects.Object_Record_Access; use type ADO.Objects.Object_Ref; use type ADO.Objects.Object_Record; pragma Warnings (Off, "formal parameter * is not referenced"); function Setting_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => SETTING_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Setting_Key; function Setting_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => SETTING_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Setting_Key; function "=" (Left, Right : Setting_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end "="; procedure Set_Field (Object : in out Setting_Ref'Class; Impl : out Setting_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Setting_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Setting_Ref) is Impl : Setting_Access; begin Impl := new Setting_Impl; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Setting -- ---------------------------------------- procedure Set_Id (Object : in out Setting_Ref; Value : in ADO.Identifier) is Impl : Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); end Set_Id; function Get_Id (Object : in Setting_Ref) return ADO.Identifier is Impl : constant Setting_Access := Setting_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Name (Object : in out Setting_Ref; Value : in String) is Impl : Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 2, Impl.Name, Value); end Set_Name; procedure Set_Name (Object : in out Setting_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 2, Impl.Name, Value); end Set_Name; function Get_Name (Object : in Setting_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Name); end Get_Name; function Get_Name (Object : in Setting_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Setting_Access := Setting_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Name; end Get_Name; -- Copy of the object. procedure Copy (Object : in Setting_Ref; Into : in out Setting_Ref) is Result : Setting_Ref; begin if not Object.Is_Null then declare Impl : constant Setting_Access := Setting_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Setting_Access := new Setting_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Name := Impl.Name; end; end if; Into := Result; end Copy; procedure Find (Object : in out Setting_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Setting_Access := new Setting_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Setting_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Setting_Access := new Setting_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Setting_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Setting_Access := new Setting_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Setting_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Setting_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Setting_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Setting_Impl) is type Setting_Impl_Ptr is access all Setting_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Setting_Impl, Setting_Impl_Ptr); pragma Warnings (Off, "*redundant conversion*"); Ptr : Setting_Impl_Ptr := Setting_Impl (Object.all)'Access; pragma Warnings (On, "*redundant conversion*"); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Setting_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, SETTING_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Setting_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Setting_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (SETTING_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_1_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_1_NAME, -- name Value => Object.Name); Object.Clear_Modified (2); end if; if Stmt.Has_Save_Fields then Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; end if; end if; end; end if; end Save; procedure Create (Object : in out Setting_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (SETTING_DEF'Access); Result : Integer; begin Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_1_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_1_NAME, -- name Value => Object.Name); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Setting_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (SETTING_DEF'Access); begin Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Setting_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Setting_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Setting_Impl (Obj.all)'Access; if Name = "id" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = "name" then return Util.Beans.Objects.To_Object (Impl.Name); end if; return Util.Beans.Objects.Null_Object; end Get_Value; procedure List (Object : in out Setting_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, SETTING_DEF'Access); begin Stmt.Execute; Setting_Vectors.Clear (Object); while Stmt.Has_Elements loop declare Item : Setting_Ref; Impl : constant Setting_Access := new Setting_Impl; begin Impl.Load (Stmt, Session); ADO.Objects.Set_Object (Item, Impl.all'Access); Object.Append (Item); end; Stmt.Next; end loop; end List; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Setting_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is pragma Unreferenced (Session); begin Object.Set_Key_Value (Stmt.Get_Identifier (0)); Object.Name := Stmt.Get_Unbounded_String (1); ADO.Objects.Set_Created (Object); end Load; function Global_Setting_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => GLOBAL_SETTING_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Global_Setting_Key; function Global_Setting_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => GLOBAL_SETTING_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end Global_Setting_Key; function "=" (Left, Right : Global_Setting_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end "="; procedure Set_Field (Object : in out Global_Setting_Ref'Class; Impl : out Global_Setting_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := Global_Setting_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out Global_Setting_Ref) is Impl : Global_Setting_Access; begin Impl := new Global_Setting_Impl; Impl.Version := 0; Impl.Server_Id := 0; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: Global_Setting -- ---------------------------------------- procedure Set_Id (Object : in out Global_Setting_Ref; Value : in ADO.Identifier) is Impl : Global_Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); end Set_Id; function Get_Id (Object : in Global_Setting_Ref) return ADO.Identifier is Impl : constant Global_Setting_Access := Global_Setting_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Value (Object : in out Global_Setting_Ref; Value : in String) is Impl : Global_Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 2, Impl.Value, Value); end Set_Value; procedure Set_Value (Object : in out Global_Setting_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : Global_Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 2, Impl.Value, Value); end Set_Value; function Get_Value (Object : in Global_Setting_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Value); end Get_Value; function Get_Value (Object : in Global_Setting_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant Global_Setting_Access := Global_Setting_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Value; end Get_Value; function Get_Version (Object : in Global_Setting_Ref) return Integer is Impl : constant Global_Setting_Access := Global_Setting_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Server_Id (Object : in out Global_Setting_Ref; Value : in Integer) is Impl : Global_Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Integer (Impl.all, 4, Impl.Server_Id, Value); end Set_Server_Id; function Get_Server_Id (Object : in Global_Setting_Ref) return Integer is Impl : constant Global_Setting_Access := Global_Setting_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Server_Id; end Get_Server_Id; procedure Set_Setting (Object : in out Global_Setting_Ref; Value : in AWA.Settings.Models.Setting_Ref'Class) is Impl : Global_Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 5, Impl.Setting, Value); end Set_Setting; function Get_Setting (Object : in Global_Setting_Ref) return AWA.Settings.Models.Setting_Ref'Class is Impl : constant Global_Setting_Access := Global_Setting_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Setting; end Get_Setting; -- Copy of the object. procedure Copy (Object : in Global_Setting_Ref; Into : in out Global_Setting_Ref) is Result : Global_Setting_Ref; begin if not Object.Is_Null then declare Impl : constant Global_Setting_Access := Global_Setting_Impl (Object.Get_Load_Object.all)'Access; Copy : constant Global_Setting_Access := new Global_Setting_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Value := Impl.Value; Copy.Version := Impl.Version; Copy.Server_Id := Impl.Server_Id; Copy.Setting := Impl.Setting; end; end if; Into := Result; end Copy; procedure Find (Object : in out Global_Setting_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant Global_Setting_Access := new Global_Setting_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out Global_Setting_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant Global_Setting_Access := new Global_Setting_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out Global_Setting_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant Global_Setting_Access := new Global_Setting_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out Global_Setting_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new Global_Setting_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out Global_Setting_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access Global_Setting_Impl) is type Global_Setting_Impl_Ptr is access all Global_Setting_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Global_Setting_Impl, Global_Setting_Impl_Ptr); pragma Warnings (Off, "*redundant conversion*"); Ptr : Global_Setting_Impl_Ptr := Global_Setting_Impl (Object.all)'Access; pragma Warnings (On, "*redundant conversion*"); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out Global_Setting_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, GLOBAL_SETTING_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out Global_Setting_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out Global_Setting_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (GLOBAL_SETTING_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_2_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_2_NAME, -- value Value => Object.Value); Object.Clear_Modified (2); end if; if Object.Is_Modified (4) then Stmt.Save_Field (Name => COL_3_2_NAME, -- server_id Value => Object.Server_Id); Object.Clear_Modified (4); end if; if Object.Is_Modified (5) then Stmt.Save_Field (Name => COL_4_2_NAME, -- setting_id Value => Object.Setting); Object.Clear_Modified (5); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => "version", Value => Object.Version); Stmt.Set_Filter (Filter => "id = ? and version = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out Global_Setting_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (GLOBAL_SETTING_DEF'Access); Result : Integer; begin Object.Version := 1; Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_2_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_2_NAME, -- value Value => Object.Value); Query.Save_Field (Name => COL_2_2_NAME, -- version Value => Object.Version); Query.Save_Field (Name => COL_3_2_NAME, -- server_id Value => Object.Server_Id); Query.Save_Field (Name => COL_4_2_NAME, -- setting_id Value => Object.Setting); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out Global_Setting_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (GLOBAL_SETTING_DEF'Access); begin Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in Global_Setting_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access Global_Setting_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := Global_Setting_Impl (Obj.all)'Access; if Name = "id" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = "value" then return Util.Beans.Objects.To_Object (Impl.Value); elsif Name = "server_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Server_Id)); end if; return Util.Beans.Objects.Null_Object; end Get_Value; procedure List (Object : in out Global_Setting_Vector; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, GLOBAL_SETTING_DEF'Access); begin Stmt.Execute; Global_Setting_Vectors.Clear (Object); while Stmt.Has_Elements loop declare Item : Global_Setting_Ref; Impl : constant Global_Setting_Access := new Global_Setting_Impl; begin Impl.Load (Stmt, Session); ADO.Objects.Set_Object (Item, Impl.all'Access); Object.Append (Item); end; Stmt.Next; end loop; end List; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out Global_Setting_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Set_Key_Value (Stmt.Get_Identifier (0)); Object.Value := Stmt.Get_Unbounded_String (1); Object.Server_Id := Stmt.Get_Integer (3); if not Stmt.Is_Null (4) then Object.Setting.Set_Key_Value (Stmt.Get_Identifier (4), Session); end if; Object.Version := Stmt.Get_Integer (2); ADO.Objects.Set_Created (Object); end Load; function User_Setting_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => USER_SETTING_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end User_Setting_Key; function User_Setting_Key (Id : in String) return ADO.Objects.Object_Key is Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => USER_SETTING_DEF'Access); begin ADO.Objects.Set_Value (Result, Id); return Result; end User_Setting_Key; function "=" (Left, Right : User_Setting_Ref'Class) return Boolean is begin return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right); end "="; procedure Set_Field (Object : in out User_Setting_Ref'Class; Impl : out User_Setting_Access) is Result : ADO.Objects.Object_Record_Access; begin Object.Prepare_Modify (Result); Impl := User_Setting_Impl (Result.all)'Access; end Set_Field; -- Internal method to allocate the Object_Record instance procedure Allocate (Object : in out User_Setting_Ref) is Impl : User_Setting_Access; begin Impl := new User_Setting_Impl; Impl.Version := 0; ADO.Objects.Set_Object (Object, Impl.all'Access); end Allocate; -- ---------------------------------------- -- Data object: User_Setting -- ---------------------------------------- procedure Set_Id (Object : in out User_Setting_Ref; Value : in ADO.Identifier) is Impl : User_Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value); end Set_Id; function Get_Id (Object : in User_Setting_Ref) return ADO.Identifier is Impl : constant User_Setting_Access := User_Setting_Impl (Object.Get_Object.all)'Access; begin return Impl.Get_Key_Value; end Get_Id; procedure Set_Value (Object : in out User_Setting_Ref; Value : in String) is Impl : User_Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_String (Impl.all, 2, Impl.Value, Value); end Set_Value; procedure Set_Value (Object : in out User_Setting_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String) is Impl : User_Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Unbounded_String (Impl.all, 2, Impl.Value, Value); end Set_Value; function Get_Value (Object : in User_Setting_Ref) return String is begin return Ada.Strings.Unbounded.To_String (Object.Get_Value); end Get_Value; function Get_Value (Object : in User_Setting_Ref) return Ada.Strings.Unbounded.Unbounded_String is Impl : constant User_Setting_Access := User_Setting_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Value; end Get_Value; function Get_Version (Object : in User_Setting_Ref) return Integer is Impl : constant User_Setting_Access := User_Setting_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Version; end Get_Version; procedure Set_Setting (Object : in out User_Setting_Ref; Value : in AWA.Settings.Models.Setting_Ref'Class) is Impl : User_Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 4, Impl.Setting, Value); end Set_Setting; function Get_Setting (Object : in User_Setting_Ref) return AWA.Settings.Models.Setting_Ref'Class is Impl : constant User_Setting_Access := User_Setting_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.Setting; end Get_Setting; procedure Set_User (Object : in out User_Setting_Ref; Value : in AWA.Users.Models.User_Ref'Class) is Impl : User_Setting_Access; begin Set_Field (Object, Impl); ADO.Objects.Set_Field_Object (Impl.all, 5, Impl.User, Value); end Set_User; function Get_User (Object : in User_Setting_Ref) return AWA.Users.Models.User_Ref'Class is Impl : constant User_Setting_Access := User_Setting_Impl (Object.Get_Load_Object.all)'Access; begin return Impl.User; end Get_User; -- Copy of the object. procedure Copy (Object : in User_Setting_Ref; Into : in out User_Setting_Ref) is Result : User_Setting_Ref; begin if not Object.Is_Null then declare Impl : constant User_Setting_Access := User_Setting_Impl (Object.Get_Load_Object.all)'Access; Copy : constant User_Setting_Access := new User_Setting_Impl; begin ADO.Objects.Set_Object (Result, Copy.all'Access); Copy.Copy (Impl.all); Copy.Value := Impl.Value; Copy.Version := Impl.Version; Copy.Setting := Impl.Setting; Copy.User := Impl.User; end; end if; Into := Result; end Copy; procedure Find (Object : in out User_Setting_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Impl : constant User_Setting_Access := new User_Setting_Impl; begin Impl.Find (Session, Query, Found); if Found then ADO.Objects.Set_Object (Object, Impl.all'Access); else ADO.Objects.Set_Object (Object, null); Destroy (Impl); end if; end Find; procedure Load (Object : in out User_Setting_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier) is Impl : constant User_Setting_Access := new User_Setting_Impl; Found : Boolean; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); raise ADO.Objects.NOT_FOUND; end if; ADO.Objects.Set_Object (Object, Impl.all'Access); end Load; procedure Load (Object : in out User_Setting_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean) is Impl : constant User_Setting_Access := new User_Setting_Impl; Query : ADO.SQL.Query; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Impl.Find (Session, Query, Found); if not Found then Destroy (Impl); else ADO.Objects.Set_Object (Object, Impl.all'Access); end if; end Load; procedure Save (Object : in out User_Setting_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl = null then Impl := new User_Setting_Impl; ADO.Objects.Set_Object (Object, Impl); end if; if not ADO.Objects.Is_Created (Impl.all) then Impl.Create (Session); else Impl.Save (Session); end if; end Save; procedure Delete (Object : in out User_Setting_Ref; Session : in out ADO.Sessions.Master_Session'Class) is Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object; begin if Impl /= null then Impl.Delete (Session); end if; end Delete; -- -------------------- -- Free the object -- -------------------- procedure Destroy (Object : access User_Setting_Impl) is type User_Setting_Impl_Ptr is access all User_Setting_Impl; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (User_Setting_Impl, User_Setting_Impl_Ptr); pragma Warnings (Off, "*redundant conversion*"); Ptr : User_Setting_Impl_Ptr := User_Setting_Impl (Object.all)'Access; pragma Warnings (On, "*redundant conversion*"); begin Unchecked_Free (Ptr); end Destroy; procedure Find (Object : in out User_Setting_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean) is Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query, USER_SETTING_DEF'Access); begin Stmt.Execute; if Stmt.Has_Elements then Object.Load (Stmt, Session); Stmt.Next; Found := not Stmt.Has_Elements; else Found := False; end if; end Find; overriding procedure Load (Object : in out User_Setting_Impl; Session : in out ADO.Sessions.Session'Class) is Found : Boolean; Query : ADO.SQL.Query; Id : constant ADO.Identifier := Object.Get_Key_Value; begin Query.Bind_Param (Position => 1, Value => Id); Query.Set_Filter ("id = ?"); Object.Find (Session, Query, Found); if not Found then raise ADO.Objects.NOT_FOUND; end if; end Load; procedure Save (Object : in out User_Setting_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Update_Statement := Session.Create_Statement (USER_SETTING_DEF'Access); begin if Object.Is_Modified (1) then Stmt.Save_Field (Name => COL_0_3_NAME, -- id Value => Object.Get_Key); Object.Clear_Modified (1); end if; if Object.Is_Modified (2) then Stmt.Save_Field (Name => COL_1_3_NAME, -- value Value => Object.Value); Object.Clear_Modified (2); end if; if Object.Is_Modified (4) then Stmt.Save_Field (Name => COL_3_3_NAME, -- setting_id Value => Object.Setting); Object.Clear_Modified (4); end if; if Object.Is_Modified (5) then Stmt.Save_Field (Name => COL_4_3_NAME, -- user_id Value => Object.User); Object.Clear_Modified (5); end if; if Stmt.Has_Save_Fields then Object.Version := Object.Version + 1; Stmt.Save_Field (Name => "version", Value => Object.Version); Stmt.Set_Filter (Filter => "id = ? and version = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Add_Param (Value => Object.Version - 1); declare Result : Integer; begin Stmt.Execute (Result); if Result /= 1 then if Result /= 0 then raise ADO.Objects.UPDATE_ERROR; else raise ADO.Objects.LAZY_LOCK; end if; end if; end; end if; end Save; procedure Create (Object : in out User_Setting_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Query : ADO.Statements.Insert_Statement := Session.Create_Statement (USER_SETTING_DEF'Access); Result : Integer; begin Object.Version := 1; Session.Allocate (Id => Object); Query.Save_Field (Name => COL_0_3_NAME, -- id Value => Object.Get_Key); Query.Save_Field (Name => COL_1_3_NAME, -- value Value => Object.Value); Query.Save_Field (Name => COL_2_3_NAME, -- version Value => Object.Version); Query.Save_Field (Name => COL_3_3_NAME, -- setting_id Value => Object.Setting); Query.Save_Field (Name => COL_4_3_NAME, -- user_id Value => Object.User); Query.Execute (Result); if Result /= 1 then raise ADO.Objects.INSERT_ERROR; end if; ADO.Objects.Set_Created (Object); end Create; procedure Delete (Object : in out User_Setting_Impl; Session : in out ADO.Sessions.Master_Session'Class) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (USER_SETTING_DEF'Access); begin Stmt.Set_Filter (Filter => "id = ?"); Stmt.Add_Param (Value => Object.Get_Key); Stmt.Execute; end Delete; -- ------------------------------ -- Get the bean attribute identified by the name. -- ------------------------------ overriding function Get_Value (From : in User_Setting_Ref; Name : in String) return Util.Beans.Objects.Object is Obj : ADO.Objects.Object_Record_Access; Impl : access User_Setting_Impl; begin if From.Is_Null then return Util.Beans.Objects.Null_Object; end if; Obj := From.Get_Load_Object; Impl := User_Setting_Impl (Obj.all)'Access; if Name = "id" then return ADO.Objects.To_Object (Impl.Get_Key); elsif Name = "value" then return Util.Beans.Objects.To_Object (Impl.Value); end if; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Load the object from current iterator position -- ------------------------------ procedure Load (Object : in out User_Setting_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class) is begin Object.Set_Key_Value (Stmt.Get_Identifier (0)); Object.Value := Stmt.Get_Unbounded_String (1); if not Stmt.Is_Null (3) then Object.Setting.Set_Key_Value (Stmt.Get_Identifier (3), Session); end if; if not Stmt.Is_Null (4) then Object.User.Set_Key_Value (Stmt.Get_Identifier (4), Session); end if; Object.Version := Stmt.Get_Integer (2); ADO.Objects.Set_Created (Object); end Load; end AWA.Settings.Models;
-- Copyright 2017-2021 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. name = "Alterations" type = "alt" ldh_chars = "_abcdefghijklmnopqrstuvwxyz0123456789-" function resolved(ctx, name, domain, records) local nparts = split(name, ".") local dparts = split(domain, ".") -- Do not process resolved root domain names if #nparts <= #dparts then return end local cfg = config(ctx) if (cfg.mode == "passive" or not cfg['alterations'].active) then return end makenames(ctx, cfg.alterations, name) end function makenames(ctx, cfg, name) local words = alt_wordlist(ctx) if cfg['flip_words'] then for i, n in pairs(flip_words(name, words)) do local expired = sendnames(ctx, n) if expired then return end end end if cfg['flip_numbers'] then for i, n in pairs(flip_numbers(name)) do local expired = sendnames(ctx, n) if expired then return end end end if cfg['add_numbers'] then for i, n in pairs(append_numbers(name)) do local expired = sendnames(ctx, n) if expired then return end end end if cfg['add_words'] then for i, n in pairs(add_prefix_word(name, words)) do local expired = sendnames(ctx, n) if expired then return end end for i, n in pairs(add_suffix_word(name, words)) do local expired = sendnames(ctx, n) if expired then return end end end local distance = cfg['edit_distance'] if distance > 0 then for i, n in pairs(fuzzy_label_searches(name, distance)) do local expired = sendnames(ctx, n) if expired then return end end end end function flip_words(name, words) local s = {} local parts = split(name, ".") local hostname = parts[1] local base = partial_join(parts, ".", 2, #parts) parts = split(hostname, "-") if #parts < 2 then return s end local post = partial_join(parts, "-", 2, #parts) for i, word in pairs(words) do set_insert(s, word .. "-" .. post .. "." .. base) end local pre = partial_join(parts, "-", 1, #parts - 1) for i, word in pairs(words) do set_insert(s, pre .. "-" .. word .. "." .. base) end return set_elements(s) end function flip_numbers(name) local parts = split(name, ".") local hostname = parts[1] local base = partial_join(parts, ".", 2, #parts) local s = {} local start = 1 while true do local b, e = string.find(hostname, "%d+", start) if b == nil then break end start = e + 1 local pre = string.sub(hostname, 1, b - 1) local post = string.sub(hostname, e + 1) -- Create an entry with the number removed set_insert(s, pre .. post .. "." .. base) local seq = numseq(tonumber(string.sub(hostname, b, e))) for i, sn in pairs(seq) do set_insert(s, pre .. sn .. post .. "." .. base) end end return set_elements(s) end function numseq(num) local s = {} local start = num - 50 if start < 1 then start = 1 end local max = num + 50 for i=start,max do set_insert(s, tostring(i)) end return set_elements(s) end function append_numbers(name) local s = {} local parts = split(name, ".") local hostname = parts[1] local base = partial_join(parts, ".", 2, #parts) for i=0,9 do set_insert(s, hostname .. tostring(i) .. "." .. base) set_insert(s, hostname .. "-" .. tostring(i) .. "." .. base) end return set_elements(s) end function add_prefix_word(name, words) local s = {} local parts = split(name, ".") local hostname = parts[1] local base = partial_join(parts, ".", 2, #parts) for i, w in pairs(words) do set_insert(s, w .. hostname .. "." .. base) set_insert(s, w .. "-" .. hostname .. "." .. base) end return set_elements(s) end function add_suffix_word(name, words) local s = {} local parts = split(name, ".") local hostname = parts[1] local base = partial_join(parts, ".", 2, #parts) for i, w in pairs(words) do set_insert(s, hostname .. w .. "." .. base) set_insert(s, hostname .. "-" .. w .. "." .. base) end return set_elements(s) end function fuzzy_label_searches(name, distance) local parts = split(name, ".") local hostname = parts[1] local base = partial_join(parts, ".", 2, #parts) local s = {hostname} for i=1,distance do local tb = set_elements(s) set_insert_many(s, additions(tb)) set_insert_many(s, deletions(tb)) set_insert_many(s, substitutions(tb)) end local results = {} for i, n in pairs(set_elements(s)) do set_insert(results, n .. "." .. base) end return set_elements(results) end function additions(set) local results = {} local l = string.len(ldh_chars) for x, name in pairs(set) do local nlen = string.len(name) for i=1,nlen do for j=1,l do local c = string.sub(ldh_chars, j, j) local post = string.sub(name, i) local pre = "" if i > 1 then pre = string.sub(name, 1, i - 1) end set_insert(results, pre .. c .. post) end end end return set_elements(results) end function deletions(set) local results = {} for x, name in pairs(set) do local nlen = string.len(name) for i=1,nlen do local post = string.sub(name, i + 1) local pre = "" if i > 1 then pre = string.sub(name, 1, i - 1) end set_insert(results, pre .. post) end end return set_elements(results) end function substitutions(set) local results = {} local l = string.len(ldh_chars) for x, name in pairs(set) do local nlen = string.len(name) for i=1,nlen do for j=1,l do local c = string.sub(ldh_chars, j, j) local post = string.sub(name, i + 1) local pre = "" if i > 1 then pre = string.sub(name, 1, i - 1) end set_insert(results, pre .. c .. post) end end end return set_elements(results) end function split(str, delim) local result = {} local pattern = "[^%" .. delim .. "]+" local matches = find(str, pattern) if (matches == nil or #matches == 0) then return result end for i, match in pairs(matches) do table.insert(result, match) end return result end function join(parts, sep) local result = "" for i, v in pairs(parts) do result = result .. sep .. v end return result end function partial_join(parts, sep, first, last) if (first < 1 or last > #parts) then return "" end local result = parts[first] first = first + 1 for i=first,last do result = result .. sep .. parts[i] end return result end function set_insert(tb, name) if name ~= "" then tb[name] = true end return tb end function set_insert_many(tb, list) if list == nil then return tb end for i, v in pairs(list) do tb[v] = true end return tb end function set_elements(tb) local result = {} if tb == nil then return result end for k, v in pairs(tb) do table.insert(result, k) end return result end function sendnames(ctx, content) local names = find(content, subdomainre) if names == nil then return false end local found = {} for i, v in pairs(names) do if found[v] == nil then local expired = newname(ctx, v) if expired then return expired end found[v] = true end end return false end
generic type Elem is limited private; type Index is (<>); type Tomb is array (Index range <>) of Elem; with procedure Swap (A, B: in out Elem); procedure Reversal (T: in out Tomb);
------------------------------------------------------------------------------- -- Copyright (c) 2019, Daniel King -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * The name of the copyright holder may not be used to endorse or promote -- Products derived from this software without specific prior written -- permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY -- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- with Keccak.Types; -- @summary -- Generic implementation of the Keccak-f permutations. -- -- @description -- This generic package implements the Keccak-f permutations for bit sizes of: -- 25, 50, 100, 200, 400, 800, and 1600 bits. -- -- @group Keccak-f generic -- The binary logarithm of the lane size. -- -- This determines the Keccak-f state size. Possible values are: -- * Lane_Size_Log = 0 => 1-bit lanes, Keccak-f[25] -- * Lane_Size_Log = 1 => 2-bit lanes, Keccak-f[50] -- * Lane_Size_Log = 2 => 4-bit lanes, Keccak-f[100] -- * Lane_Size_Log = 3 => 8-bit lanes, Keccak-f[200] -- * Lane_Size_Log = 4 => 16-bit lanes, Keccak-f[400] -- * Lane_Size_Log = 5 => 32-bit lanes, Keccak-f[800] -- * Lane_Size_Log = 6 => 64-bit lanes, Keccak-f[1600] Lane_Size_Log : in Natural; -- Modular type for a lane of the Keccak state. -- -- Lane_Type'Modulus must be equal to 2**(2**Lane_Size_Log). -- For example, when Lane_Size_Log=6 Lane_Type must be a 64-bit -- mod type (2**Lane_Size_Log = 64 when Lane_Size_Log = 6). type Lane_Type is mod <>; -- Bit-wise left shift for Lane_Type. with function Shift_Left (Value : in Lane_Type; Amount : in Natural) return Lane_Type; -- Bit-wise right shift for Lane_Type. with function Shift_Right (Value : in Lane_Type; Amount : in Natural) return Lane_Type; -- Bit-wise left rotate for Lane_Type. with function Rotate_Left (Value : in Lane_Type; Amount : in Natural) return Lane_Type; package Keccak.Generic_KeccakF is Lane_Size_Bits : constant Positive := 2**Lane_Size_Log; State_Size_Bits : constant Positive := Lane_Size_Bits * 25; pragma Assert (Lane_Type'Modulus = 2**Lane_Size_Bits, "Value for Lane_Size_Log is incompatible with the specified lane type"); subtype Round_Count is Positive range 1 .. 24; type Round_Index is new Natural range 0 .. 23; type State is private; -- Keccak-f[B] state, where B is the state size in bits (e.g. 1600 bits). type Lane_Complemented_State is private; -- State type used for the lane complementing implementation. -- -- A distinct type is used here to prevent confusion in using the wrong -- subprograms with the wrong type, as specific implementations are needed -- to handle the lane complemented Keccak-f state. procedure Init (A : out State) with Global => null, Depends => (A => null); -- Initialize the Keccak-f state. -- -- Initially, the Keccak state is set to 0. procedure Init (A : out Lane_Complemented_State) with Global => null, Depends => (A => null); -- Initialize the Keccak-f state. -- -- Initially, the Keccak state is set to 0. private type X_Coord is mod 5; type Y_Coord is mod 5; type State is array (X_Coord, Y_Coord) of Lane_Type; type Lane_Complemented_State is new State; end Keccak.Generic_KeccakF;
-- The Village of Vampire by YT, このソースコードはNYSLです with Serialization; package Tabula.Villages.Village_IO is package Village_State_IO is new Serialization.IO_Enumeration (Tabula.Villages.Village_State); end Tabula.Villages.Village_IO;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- C U D A -- -- -- -- S p e c -- -- -- -- Copyright (C) 2010-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package defines CUDA-specific datastructures and subprograms. -- -- Compiling for CUDA requires compiling for two targets. One is the CPU (more -- frequently named "host"), the other is the GPU (the "device"). Compiling -- for the host requires compiling the whole program. Compiling for the device -- only requires compiling packages that contain CUDA kernels. -- -- When compiling for the device, GNAT-LLVM is used. It produces assembly -- tailored to Nvidia's GPU (NVPTX). This NVPTX code is then assembled into -- an object file by ptxas, an assembler provided by Nvidia. This object file -- is then combined with its source code into a fat binary by a tool named -- `fatbin`, also provided by Nvidia. The resulting fat binary is turned into -- a regular object file by the host's linker and linked with the program that -- executes on the host. -- -- A CUDA kernel is a procedure marked with the CUDA_Global pragma or aspect. -- CUDA_Global does not have any effect when compiling for the device. When -- compiling for the host, the frontend stores procedures marked with -- CUDA_Global in a hash table the key of which is the Node_Id of the package -- body that contains the CUDA_Global procedure. This is done in sem_prag.adb. -- Once the declarations of a package body have been analyzed, variable, type -- and procedure declarations necessary for the initialization of the CUDA -- runtime are appended to the package that contains the CUDA_Global -- procedure. -- -- These declarations are used to register the CUDA kernel with the CUDA -- runtime when the program is launched. Registering a CUDA kernel with the -- CUDA runtime requires multiple function calls: -- - The first one registers the fat binary which corresponds to the package -- with the CUDA runtime. -- - Then, as many function calls as there are kernels in order to bind them -- with the fat binary. -- fat binary. -- - The last call lets the CUDA runtime know that we are done initializing -- CUDA. -- Expansion of the CUDA_Global aspect is triggered in sem_ch7.adb, during -- analysis of the package. All of this expansion is performed in the -- Insert_CUDA_Initialization procedure defined in GNAT_CUDA. -- -- Once a CUDA package is initialized, its kernels are ready to be used. -- Launching CUDA kernels is done by using the CUDA_Execute pragma. When -- compiling for the host, the CUDA_Execute pragma is expanded into a declare -- block which performs calls to the CUDA runtime functions. -- - The first one pushes a "launch configuration" on the "configuration -- stack" of the CUDA runtime. -- - The second call pops this call configuration, making it effective. -- - The third call actually launches the kernel. -- Light validation of the CUDA_Execute pragma is performed in sem_prag.adb -- and expansion is performed in exp_prag.adb. with Types; use Types; package GNAT_CUDA is procedure Add_CUDA_Kernel (Pack_Id : Entity_Id; Kernel : Entity_Id); -- Add Kernel to the list of CUDA_Global nodes that belong to Pack_Id. -- Kernel is a procedure entity marked with CUDA_Global, Pack_Id is the -- entity of its parent package body. procedure Build_And_Insert_CUDA_Initialization (N : Node_Id); -- Builds declarations necessary for CUDA initialization and inserts them -- in N, the package body that contains CUDA_Global nodes. These -- declarations are: -- -- * A symbol to hold the pointer to the CUDA fat binary -- -- * A type definition for a wrapper that contains the pointer to the -- CUDA fat binary -- -- * An object of the aforementioned type to hold the aforementioned -- pointer. -- -- * For each CUDA_Global procedure in the package, a declaration of a C -- string containing the function's name. -- -- * A function that takes care of calling CUDA functions that register -- CUDA_Global procedures with the runtime. -- -- * A boolean that holds the result of the call to the aforementioned -- function. end GNAT_CUDA;
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr> -- MIT license. Please refer to the LICENSE file. with Apsepp.Abstract_Test_Suite; use Apsepp.Abstract_Test_Suite; private with Apsepp_Test_Node_Class_Early_Test_Case, Apsepp_Test_Reporter_Class_Struct_Builder_Early_Test_Case, Apsepp_Scope_Bound_Locks_Test_Case, Apsepp_Shared_Instance_Test_Case, Apsepp_Scope_Debug_Test_Case; package Apsepp_Test_Suite is type Apsepp_T_S is limited new Test_Suite with null record; overriding function Child_Array (Obj : Apsepp_T_S) return Test_Node_Array; private use Apsepp_Test_Node_Class_Early_Test_Case, Apsepp_Test_Reporter_Class_Struct_Builder_Early_Test_Case, Apsepp_Scope_Bound_Locks_Test_Case, Apsepp_Shared_Instance_Test_Case, Apsepp_Scope_Debug_Test_Case; Test_Node_Class_E_T_C : aliased Apsepp_Test_Node_Class_E_T_C; Test_Reporter_Class_Struct_Builder_E_T_C : aliased Apsepp_Test_Reporter_Class_Struct_Builder_E_T_C; Scope_Bound_Locks_T_C : aliased Apsepp_Scope_Bound_Locks_T_C; Shared_Instance_T_C : aliased Apsepp_Shared_Instance_T_C; Scope_Debug_T_C : aliased Apsepp_Scope_Debug_T_C; end Apsepp_Test_Suite;
-- with Ada.Text_IO; use Ada.Text_IO; package body Iface_Lists is function Has_Element (Position : Cursor) return Boolean is -- Ada's stock ACV checks for Position = No_Element here, -- which requires much more bookkeeping, possibly type specific. -- Here we deal with type hierarchy, with possibly different iteration implementation deltails -- for each derived type. It makes way more sense to let the container handle this itself. -- So we just redispatch here.. begin -- Put("Cursor.Has_Element (" & Position.Index'Img & "); "); return Position.Container.Has_Element(Position.Index); end Has_Element; end Iface_Lists;
with m4.mpu; with types; package soc.layout with spark_mode => on is FLASH_BASE : constant system_address := 16#0800_0000#; FLASH_SIZE : constant := 1 * MBYTE; SRAM_BASE : constant system_address := 16#1000_0000#; SRAM_SIZE : constant := 64 * KBYTE; BOOT_ROM_BASE : constant system_address := 16#1FFF_0000#; RAM_BASE : constant system_address := 16#2000_0000#; -- SRAM RAM_SIZE : constant := 128 * KBYTE; USER_RAM_BASE : constant system_address := 16#2000_0000#; -- SRAM USER_RAM_SIZE : constant := 128 * KBYTE; KERNEL_RAM_BASE : constant system_address := 16#1000_0000#; KERNEL_RAM_SIZE : constant := 64 * KBYTE; PERIPH_BASE : constant system_address := 16#4000_0000#; MEMORY_BANK1_BASE : constant system_address := 16#6000_0000#; MEMORY_BANK2_BASE : constant system_address := MEMORY_BANK1_BASE; APB1PERIPH_BASE : constant system_address := PERIPH_BASE; APB2PERIPH_BASE : constant system_address := PERIPH_BASE + 16#0001_0000#; AHB1PERIPH_BASE : constant system_address := PERIPH_BASE + 16#0002_0000#; AHB2PERIPH_BASE : constant system_address := PERIPH_BASE + 16#1000_0000#; -- -- AHB1 peripherals -- GPIOA_BASE : constant system_address := AHB1PERIPH_BASE + 16#0000#; GPIOB_BASE : constant system_address := AHB1PERIPH_BASE + 16#0400#; GPIOC_BASE : constant system_address := AHB1PERIPH_BASE + 16#0800#; GPIOD_BASE : constant system_address := AHB1PERIPH_BASE + 16#0C00#; GPIOE_BASE : constant system_address := AHB1PERIPH_BASE + 16#1000#; GPIOF_BASE : constant system_address := AHB1PERIPH_BASE + 16#1400#; GPIOG_BASE : constant system_address := AHB1PERIPH_BASE + 16#1800#; GPIOH_BASE : constant system_address := AHB1PERIPH_BASE + 16#1C00#; GPIOI_BASE : constant system_address := AHB1PERIPH_BASE + 16#2000#; DMA1_BASE : constant system_address := AHB1PERIPH_BASE + 16#6000#; DMA2_BASE : constant system_address := AHB1PERIPH_BASE + 16#6400#; -- -- APB2 peripherals -- SYSCFG_BASE : constant system_address := APB2PERIPH_BASE + 16#3800#; -- -- Flash and firmware structure -- -- -- Flip bank FW1_SIZE : constant unsigned_32 := 576*1024; FW1_KERN_BASE : constant unsigned_32 := 16#08020000#; FW1_KERN_SIZE : constant unsigned_32 := 64*1024; FW1_KERN_REGION_SIZE : constant m4.mpu.t_region_size := m4.mpu.REGION_SIZE_64KB; FW1_USER_BASE : constant unsigned_32 := 16#08080000#; FW1_USER_SIZE : constant unsigned_32 := 512*1024; FW1_USER_REGION_SIZE : constant m4.mpu.t_region_size := m4.mpu.REGION_SIZE_512KB; -- DFU 1 DFU1_SIZE : constant unsigned_32 := 320*1024; DFU1_KERN_BASE : constant unsigned_32 := 16#08030000#; DFU1_USER_BASE : constant unsigned_32 := 16#08040000#; DFU1_KERN_SIZE : constant unsigned_32 := 64*1024; DFU1_KERN_REGION_SIZE: constant m4.mpu.t_region_size := m4.mpu.REGION_SIZE_64KB; DFU1_USER_SIZE : constant unsigned_32 := 256*1024; DFU1_USER_REGION_SIZE: constant m4.mpu.t_region_size := m4.mpu.REGION_SIZE_256KB; -- STM32F429 has 1MB flash that can be mapped at a time, which forbid -- the usage of efficient dual banking. -- This layout does not declare the complete dual bank end soc.layout;
-------------------------------------------------------------------------------- -- Copyright (C) 2020 by Heisenbug Ltd. (gh+owm@heisenbug.eu) -- -- 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); limited with Ada.Calendar.Time_Zones; with Types; package GNATCOLL.JSON.Conversions is ----------------------------------------------------------------------------- -- To_Humidity ----------------------------------------------------------------------------- function To_Humidity (Value : in JSON_Value; Field : in UTF8_String) return Types.Humidity with Inline => True, Global => null, Pre => (Value.Kind = JSON_Object_Type and then Value.Get (Field).Kind in JSON_Int_Type | JSON_Float_Type); --% Converts a numeric (either float or integer) JSON field value into a --% Humidity. -- --% @param Value --% The JSON value containing the humidity data. -- --% @param Field --% The name of the field containing the humidity value. -- --% @return --% The humidity value extracted from the given JSON value. ----------------------------------------------------------------------------- -- To_Latitude ----------------------------------------------------------------------------- function To_Latitude (Value : in JSON_Value; Field : in UTF8_String) return Types.Latitude with Inline => True, Global => null, Pre => (Value.Kind = JSON_Object_Type and then Value.Get (Field).Kind in JSON_Int_Type | JSON_Float_Type); --% Converts a numeric (either float or integer) JSON field value into a --% Latitude. -- --% @param Value --% The JSON value containing the latitude data. -- --% @param Field --% The name of the field containing the latitude value. -- --% @return --% The latitude value extracted from the given JSON value. ----------------------------------------------------------------------------- -- To_Longitude ----------------------------------------------------------------------------- function To_Longitude (Value : in JSON_Value; Field : in UTF8_String) return Types.Longitude with Inline => True, Global => null, Pre => (Value.Kind = JSON_Object_Type and then Value.Get (Field).Kind in JSON_Int_Type | JSON_Float_Type); --% Converts a numeric (either float or integer) JSON field value into a --% Longitude. -- --% @param Value --% The JSON value containing the longitude data. -- --% @param Field --% The name of the field containing the longitude value. -- --% @return --% The longitude value extracted from the given JSON value. ----------------------------------------------------------------------------- -- To_Pressure ----------------------------------------------------------------------------- function To_Pressure (Value : in JSON_Value; Field : in UTF8_String) return Types.Pressure with Inline => True, Global => null, Pre => (Value.Kind = JSON_Object_Type and then Value.Get (Field).Kind in JSON_Int_Type | JSON_Float_Type); --% Converts a numeric (either float or integer) JSON field value into a --% Pressure. -- --% @param Value --% The JSON value containing the pressure data. -- --% @param Field --% The name of the field containing the pressure value. -- --% @return --% The pressure value extracted from the given JSON value. ----------------------------------------------------------------------------- -- To_Scalar ----------------------------------------------------------------------------- function To_Scalar (Value : in JSON_Value; Field : in UTF8_String) return Types.Scalar with Global => null, Pre => (Value.Kind = JSON_Object_Type and then Value.Get (Field).Kind in JSON_Int_Type | JSON_Float_Type); --% Converts a numeric (either float or integer) JSON field value into a --% Scalar. -- --% @param Value --% The JSON value containing the numeric data. -- --% @param Field --% The name of the field containing the numeric value. -- --% @return --% The numeric value extracted from the given JSON value. ----------------------------------------------------------------------------- -- To_Temperature ----------------------------------------------------------------------------- function To_Temperature (Value : in JSON_Value; Field : in UTF8_String) return Types.Kelvin with Global => null, Pre => (Value.Kind = JSON_Object_Type and then Value.Get (Field).Kind in JSON_Int_Type | JSON_Float_Type); --% Converts a numeric (either float or integer) JSON field value, expected --% to be a value given in Kelvin. -- --% @param Value --% The JSON value containing the temperature data. -- --% @param Field --% The name of the field containing the temperature value. -- --% @return --% The temperature value extracted from the given JSON value. ----------------------------------------------------------------------------- -- To_Time ----------------------------------------------------------------------------- function To_Time (Value : in JSON_Value; Field : in UTF8_String) return Ada.Calendar.Time with Global => null, Pre => (Value.Kind = JSON_Object_Type and then Value.Get (Field).Kind = JSON_Int_Type); --% Converts an integer JSON field which is expected to contain a Unix time --% (i.e. number of seconds since 1970-01-01) into a proper Ada Time. -- --% @param Value --% The JSON value containing the time data. -- --% @param Field --% The name of the field containing the time value. -- --% @return --% The time extracted from the given JSON value. ----------------------------------------------------------------------------- -- To_Time_Offset ----------------------------------------------------------------------------- function To_Time_Offset (Value : in JSON_Value; Field : in UTF8_String) return Ada.Calendar.Time_Zones.Time_Offset with Global => null, Pre => (Value.Kind = JSON_Object_Type and then Value.Get (Field).Kind = JSON_Int_Type); --% Converts an integer JSON field which is expected to contain a time zone --% offset in seconds into Time_Offset. -- --% @param Value --% The JSON value containing the time zone data. -- --% @param Field --% The name of the field containing the time zone value. -- --% @return --% The time zone offset extracted from the given JSON value. end GNATCOLL.JSON.Conversions;
-- -- 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. -- ----------------------------------------------------------------------------- -- Navigate -- Todo lists are hieracial. -- with Ada.Containers.Vectors; with Types; package Navigate is procedure Top; -- Go to top level. procedure Parent; -- Go one level up. If top level: stay there. function Path_Image return String; -- Image of path. procedure Build_Path (Job : in Types.Job_Id); -- Build Path from Job and up. function Current_Job return Types.Job_Id; -- Get current job. procedure Refresh_List; -- Refresh job naviagtion list. procedure Lookup_Job (Text : in String; Job : out Types.Job_Id; Success : out Boolean); -- Loopup Text as job in navigation list. Job is set on Success. subtype Ref_Type is String (1 .. 3); type Ref_Pair is record Ref : Ref_Type; Level : Natural; -- 0: Top level end record; package Ref_Vectors is new Ada.Containers.Vectors (Types.Job_Index, Ref_Pair); type List_Type is record Set : Types.Job_Sets.Vector; Refs : Ref_Vectors.Vector; Current : Types.Job_Id; end record; List : List_Type; end Navigate;
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Containers.Vectors; with League.String_Vectors; with League.Strings; with Slim.Players; package Slim.Menu_Models.Play_Lists is type Play_List_Menu_Model (Player : Slim.Players.Player_Access) is limited new Slim.Menu_Models.Menu_Model with private; procedure Initialize (Self : in out Play_List_Menu_Model'Class; Label : League.Strings.Universal_String; Root : League.Strings.Universal_String; File : League.Strings.Universal_String) with Pre => File.Starts_With (Root); -- Read playlist in M3U format, as described in rfc8216. -- Root is HTTP server folder. procedure Collect (Self : Play_List_Menu_Model'Class; Path_List : in out League.String_Vectors.Universal_String_Vector; Title_List : in out League.String_Vectors.Universal_String_Vector); private type Play_List_Item is record URI : League.Strings.Universal_String; Label : League.Strings.Universal_String; end record; package Play_List_Item_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Play_List_Item); type Play_List_Menu_Model (Player : Slim.Players.Player_Access) is limited new Slim.Menu_Models.Menu_Model with record Root : League.Strings.Universal_String; -- Directory where Path is located (HTTP server root folder) Path : League.Strings.Universal_String; -- Path from the Root Label : League.Strings.Universal_String; M3U : League.Strings.Universal_String; Items : Play_List_Item_Vectors.Vector; end record; overriding function Label (Self : Play_List_Menu_Model; Path : Slim.Menu_Models.Menu_Path) return League.Strings.Universal_String; overriding function Item_Count (Self : Play_List_Menu_Model; Path : Slim.Menu_Models.Menu_Path) return Natural; overriding function Enter_Command (Self : Play_List_Menu_Model; Path : Menu_Path) return Slim.Menu_Commands.Menu_Command_Access; overriding function Play_Command (Self : Play_List_Menu_Model; Path : Menu_Path) return Slim.Menu_Commands.Menu_Command_Access; end Slim.Menu_Models.Play_Lists;
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Elements.Definitions; with Program.Lexical_Elements; package Program.Elements.Null_Components is pragma Pure (Program.Elements.Null_Components); type Null_Component is limited interface and Program.Elements.Definitions.Definition; type Null_Component_Access is access all Null_Component'Class with Storage_Size => 0; type Null_Component_Text is limited interface; type Null_Component_Text_Access is access all Null_Component_Text'Class with Storage_Size => 0; not overriding function To_Null_Component_Text (Self : in out Null_Component) return Null_Component_Text_Access is abstract; not overriding function Null_Token (Self : Null_Component_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Semicolon_Token (Self : Null_Component_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; end Program.Elements.Null_Components;
with Garden_Pkg, tools; use Garden_Pkg, tools; procedure main is task Mantis; task Gardener; task body Mantis is pos : Position := GetRandPos; hp : Natural := 1; begin while hp > 0 loop if GetField(pos) = true then hp := hp - 1; Output.Puts("Mantis died - pos:" & Position'Image(pos), 1); else pos := GetRandPos; Output.Puts("Mantis jumped - pos:" & Position'Image(pos), 1); if GetField(pos) = true then hp := hp - 1; Output.Puts("Mantis died - pos:" & Position'Image(pos), 1); end if; end if; delay 0.1; end loop; end Mantis; task body Gardener is pos : Position := GetRandPos; begin while Mantis'Callable loop pos := GetRandPos; SprayField(pos); Output.Puts("Gardener sprayed - pos:" & Position'Image(pos), 1); delay 0.2; SprayAbsorbed; Output.Puts("Spray absorbed", 1); end loop; end Gardener; begin null; exception when others => Output.Puts("Catched an exception in main."); end main;
with Ada.Unchecked_Conversion; with SDL; with SDL.Events.Events; with SDL.Events.Keyboards; with SDL.Log; with SDL.Video.Pixel_Formats; with SDL.Video.Rectangles; with SDL.Video.Surfaces; with SDL.Video.Windows.Makers; procedure Surface is W : SDL.Video.Windows.Window; begin SDL.Log.Set (Category => SDL.Log.Application, Priority => SDL.Log.Debug); if SDL.Initialise (Flags => SDL.Enable_Screen) = True then SDL.Video.Windows.Makers.Create (Win => W, Title => "Surface (Esc to exit)", Position => SDL.Natural_Coordinates'(X => 100, Y => 100), Size => SDL.Positive_Sizes'(800, 640), Flags => SDL.Video.Windows.Resizable); -- Main loop. declare Event : SDL.Events.Events.Events; Window_Surface : SDL.Video.Surfaces.Surface; Area : constant SDL.Video.Rectangles.Rectangle := (X => 10, Y => 10, Width => 50, Height => 50); Areas : constant SDL.Video.Rectangles.Rectangle_Arrays := ((X => 100, Y => 10, Width => 50, Height => 50), (X => 120, Y => 20, Width => 50, Height => 50), (X => 160, Y => 40, Width => 50, Height => 50)); Green_Area : constant SDL.Video.Rectangles.Rectangle := (X => 15, Y => 15, Width => 10, Height => 10); Blue_Areas : constant SDL.Video.Rectangles.Rectangle_Arrays := ((X => 150, Y => 15, Width => 10, Height => 10), (X => 125, Y => 25, Width => 10, Height => 10), (X => 165, Y => 45, Width => 10, Height => 10)); Blit_Copy_Area : constant SDL.Video.Rectangles.Rectangle := (X => 10, Y => 10, Width => 150, Height => 70); Blit_Dest_Area : SDL.Video.Rectangles.Rectangle := (X => 10, Y => 130, Width => 100, Height => 100); Finished : Boolean := False; use type SDL.Events.Keyboards.Key_Codes; begin Window_Surface := W.Get_Surface; Window_Surface.Fill (Area, SDL.Video.Pixel_Formats.To_Pixel (Format => Window_Surface.Pixel_Format, Red => 200, Green => 100, Blue => 150)); Window_Surface.Fill (Areas, SDL.Video.Pixel_Formats.To_Pixel (Format => Window_Surface.Pixel_Format, Red => 100, Green => 100, Blue => 150)); W.Update_Surface; -- Shows the above two calls. Window_Surface.Fill (Green_Area, SDL.Video.Pixel_Formats.To_Pixel (Format => Window_Surface.Pixel_Format, Red => 100, Green => 200, Blue => 100)); W.Update_Surface_Rectangle (Rectangle => Green_Area); Window_Surface.Fill (Blue_Areas, SDL.Video.Pixel_Formats.To_Pixel (Format => Window_Surface.Pixel_Format, Red => 150, Green => 150, Blue => 250)); W.Update_Surface_Rectangles (Rectangles => Blue_Areas); Window_Surface.Blit_Scaled (Self_Area => Blit_Dest_Area, Source => Window_Surface, Source_Area => Blit_Copy_Area); W.Update_Surface_Rectangle (Blit_Dest_Area); loop while SDL.Events.Events.Poll (Event) loop case Event.Common.Event_Type is when SDL.Events.Quit => Finished := True; when SDL.Events.Keyboards.Key_Down => if Event.Keyboard.Key_Sym.Key_Code = SDL.Events.Keyboards.Code_Escape then Finished := True; end if; when others => null; end case; end loop; exit when Finished; end loop; end; SDL.Log.Put_Debug (""); W.Finalize; SDL.Finalise; end if; end Surface;
-- This spec has been automatically generated from msp430g2553.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with System; -- System Clock package MSP430_SVD.SYSTEM_CLOCK is pragma Preelaborate; --------------- -- Registers -- --------------- -- XIN/XOUT Cap 0 type BCSCTL3_XCAP_Field is (-- XIN/XOUT Cap : 0 pF Xcap_0, -- XIN/XOUT Cap : 6 pF Xcap_1, -- XIN/XOUT Cap : 10 pF Xcap_2, -- XIN/XOUT Cap : 12.5 pF Xcap_3) with Size => 2; for BCSCTL3_XCAP_Field use (Xcap_0 => 0, Xcap_1 => 1, Xcap_2 => 2, Xcap_3 => 3); -- Mode 0 for LFXT1 (XTS = 0) type BCSCTL3_LFXT1S_Field is (-- Mode 0 for LFXT1 : Normal operation Lfxt1S_0, -- Mode 1 for LFXT1 : Reserved Lfxt1S_1, -- Mode 2 for LFXT1 : VLO Lfxt1S_2, -- Mode 3 for LFXT1 : Digital input signal Lfxt1S_3) with Size => 2; for BCSCTL3_LFXT1S_Field use (Lfxt1S_0 => 0, Lfxt1S_1 => 1, Lfxt1S_2 => 2, Lfxt1S_3 => 3); -- Mode 0 for XT2 type BCSCTL3_XT2S_Field is (-- Mode 0 for XT2 : 0.4 - 1 MHz Xt2S_0, -- Mode 1 for XT2 : 1 - 4 MHz Xt2S_1, -- Mode 2 for XT2 : 2 - 16 MHz Xt2S_2, -- Mode 3 for XT2 : Digital input signal Xt2S_3) with Size => 2; for BCSCTL3_XT2S_Field use (Xt2S_0 => 0, Xt2S_1 => 1, Xt2S_2 => 2, Xt2S_3 => 3); -- Basic Clock System Control 3 type BCSCTL3_Register is record -- Low/high Frequency Oscillator Fault Flag LFXT1OF : MSP430_SVD.Bit := 16#0#; -- High frequency oscillator 2 fault flag XT2OF : MSP430_SVD.Bit := 16#0#; -- XIN/XOUT Cap 0 XCAP : BCSCTL3_XCAP_Field := MSP430_SVD.SYSTEM_CLOCK.Xcap_0; -- Mode 0 for LFXT1 (XTS = 0) LFXT1S : BCSCTL3_LFXT1S_Field := MSP430_SVD.SYSTEM_CLOCK.Lfxt1S_0; -- Mode 0 for XT2 XT2S : BCSCTL3_XT2S_Field := MSP430_SVD.SYSTEM_CLOCK.Xt2S_0; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for BCSCTL3_Register use record LFXT1OF at 0 range 0 .. 0; XT2OF at 0 range 1 .. 1; XCAP at 0 range 2 .. 3; LFXT1S at 0 range 4 .. 5; XT2S at 0 range 6 .. 7; end record; -- DCOCTL_MOD array type DCOCTL_MOD_Field_Array is array (0 .. 4) of MSP430_SVD.Bit with Component_Size => 1, Size => 5; -- Type definition for DCOCTL_MOD type DCOCTL_MOD_Field (As_Array : Boolean := False) is record case As_Array is when False => -- MOD as a value Val : MSP430_SVD.UInt5; when True => -- MOD as an array Arr : DCOCTL_MOD_Field_Array; end case; end record with Unchecked_Union, Size => 5; for DCOCTL_MOD_Field use record Val at 0 range 0 .. 4; Arr at 0 range 0 .. 4; end record; -- DCOCTL_DCO array type DCOCTL_DCO_Field_Array is array (0 .. 2) of MSP430_SVD.Bit with Component_Size => 1, Size => 3; -- Type definition for DCOCTL_DCO type DCOCTL_DCO_Field (As_Array : Boolean := False) is record case As_Array is when False => -- DCO as a value Val : MSP430_SVD.UInt3; when True => -- DCO as an array Arr : DCOCTL_DCO_Field_Array; end case; end record with Unchecked_Union, Size => 3; for DCOCTL_DCO_Field use record Val at 0 range 0 .. 2; Arr at 0 range 0 .. 2; end record; -- DCO Clock Frequency Control type DCOCTL_Register is record -- Modulation Bit 0 MOD_k : DCOCTL_MOD_Field := (As_Array => False, Val => 16#0#); -- DCO Select Bit 0 DCO : DCOCTL_DCO_Field := (As_Array => False, Val => 16#0#); end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for DCOCTL_Register use record MOD_k at 0 range 0 .. 4; DCO at 0 range 5 .. 7; end record; -- BCSCTL1_RSEL array type BCSCTL1_RSEL_Field_Array is array (0 .. 3) of MSP430_SVD.Bit with Component_Size => 1, Size => 4; -- Type definition for BCSCTL1_RSEL type BCSCTL1_RSEL_Field (As_Array : Boolean := False) is record case As_Array is when False => -- RSEL as a value Val : MSP430_SVD.UInt4; when True => -- RSEL as an array Arr : BCSCTL1_RSEL_Field_Array; end case; end record with Unchecked_Union, Size => 4; for BCSCTL1_RSEL_Field use record Val at 0 range 0 .. 3; Arr at 0 range 0 .. 3; end record; -- ACLK Divider 0 type BCSCTL1_DIVA_Field is (-- ACLK Divider 0: /1 Diva_0, -- ACLK Divider 1: /2 Diva_1, -- ACLK Divider 2: /4 Diva_2, -- ACLK Divider 3: /8 Diva_3) with Size => 2; for BCSCTL1_DIVA_Field use (Diva_0 => 0, Diva_1 => 1, Diva_2 => 2, Diva_3 => 3); -- Basic Clock System Control 1 type BCSCTL1_Register is record -- Range Select Bit 0 RSEL : BCSCTL1_RSEL_Field := (As_Array => False, Val => 16#0#); -- ACLK Divider 0 DIVA : BCSCTL1_DIVA_Field := MSP430_SVD.SYSTEM_CLOCK.Diva_0; -- LFXTCLK 0:Low Freq. / 1: High Freq. XTS : MSP430_SVD.Bit := 16#0#; -- Enable XT2CLK XT2OFF : MSP430_SVD.Bit := 16#0#; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for BCSCTL1_Register use record RSEL at 0 range 0 .. 3; DIVA at 0 range 4 .. 5; XTS at 0 range 6 .. 6; XT2OFF at 0 range 7 .. 7; end record; -- SMCLK Divider 0 type BCSCTL2_DIVS_Field is (-- SMCLK Divider 0: /1 Divs_0, -- SMCLK Divider 1: /2 Divs_1, -- SMCLK Divider 2: /4 Divs_2, -- SMCLK Divider 3: /8 Divs_3) with Size => 2; for BCSCTL2_DIVS_Field use (Divs_0 => 0, Divs_1 => 1, Divs_2 => 2, Divs_3 => 3); -- MCLK Divider 0 type BCSCTL2_DIVM_Field is (-- MCLK Divider 0: /1 Divm_0, -- MCLK Divider 1: /2 Divm_1, -- MCLK Divider 2: /4 Divm_2, -- MCLK Divider 3: /8 Divm_3) with Size => 2; for BCSCTL2_DIVM_Field use (Divm_0 => 0, Divm_1 => 1, Divm_2 => 2, Divm_3 => 3); -- MCLK Source Select 0 type BCSCTL2_SELM_Field is (-- MCLK Source Select 0: DCOCLK Selm_0, -- MCLK Source Select 1: DCOCLK Selm_1, -- MCLK Source Select 2: XT2CLK/LFXTCLK Selm_2, -- MCLK Source Select 3: LFXTCLK Selm_3) with Size => 2; for BCSCTL2_SELM_Field use (Selm_0 => 0, Selm_1 => 1, Selm_2 => 2, Selm_3 => 3); -- Basic Clock System Control 2 type BCSCTL2_Register is record -- unspecified Reserved_0_0 : MSP430_SVD.Bit := 16#0#; -- SMCLK Divider 0 DIVS : BCSCTL2_DIVS_Field := MSP430_SVD.SYSTEM_CLOCK.Divs_0; -- SMCLK Source Select 0:DCOCLK / 1:XT2CLK/LFXTCLK SELS : MSP430_SVD.Bit := 16#0#; -- MCLK Divider 0 DIVM : BCSCTL2_DIVM_Field := MSP430_SVD.SYSTEM_CLOCK.Divm_0; -- MCLK Source Select 0 SELM : BCSCTL2_SELM_Field := MSP430_SVD.SYSTEM_CLOCK.Selm_0; end record with Volatile_Full_Access, Object_Size => 8, Bit_Order => System.Low_Order_First; for BCSCTL2_Register use record Reserved_0_0 at 0 range 0 .. 0; DIVS at 0 range 1 .. 2; SELS at 0 range 3 .. 3; DIVM at 0 range 4 .. 5; SELM at 0 range 6 .. 7; end record; ----------------- -- Peripherals -- ----------------- -- System Clock type SYSTEM_CLOCK_Peripheral is record -- Basic Clock System Control 3 BCSCTL3 : aliased BCSCTL3_Register; -- DCO Clock Frequency Control DCOCTL : aliased DCOCTL_Register; -- Basic Clock System Control 1 BCSCTL1 : aliased BCSCTL1_Register; -- Basic Clock System Control 2 BCSCTL2 : aliased BCSCTL2_Register; end record with Volatile; for SYSTEM_CLOCK_Peripheral use record BCSCTL3 at 16#1# range 0 .. 7; DCOCTL at 16#4# range 0 .. 7; BCSCTL1 at 16#5# range 0 .. 7; BCSCTL2 at 16#6# range 0 .. 7; end record; -- System Clock SYSTEM_CLOCK_Periph : aliased SYSTEM_CLOCK_Peripheral with Import, Address => SYSTEM_CLOCK_Base; end MSP430_SVD.SYSTEM_CLOCK;
with Ada.Text_IO; use Ada.Text_IO; package body Menu is procedure Add_Item(M : in out T_Menu; Item : T_Item) is begin T_Items.Append(M.Items, Item); end; procedure Show(M : in T_Menu) is Item : T_Item; First : T_Items.Extended_Index := T_Items.First_Index(M.Items); Last : T_Items.Extended_Index := T_Items.Last_Index(M.Items); begin Put_Line(SU.To_String(M.Title)); New_Line; for I in First..Last loop Item := T_Items.Element(M.Items, I); Put_Line(" (" & Item.Symbol & ") " & SU.To_String(Item.Name)); end loop; New_Line; end; procedure Query(M : in T_Menu) is Response : Character; Item : T_Item; First : T_Items.Extended_Index := T_Items.First_Index(M.Items); Last : T_Items.Extended_Index := T_Items.Last_Index(M.Items); Found : Boolean := False; begin while not Found loop Show(M); Put("> "); Get(Response); for I in First..Last loop Item := T_Items.Element(M.Items, I); -- If we got existing symbol and the func does exists, call it if Item.Symbol = Response then if Item.Func /= null then Item.Func.all; end if; Found := True; exit; end if; end loop; if not Found then Put_Line("Bad answer !"); Put_Line("Please answer an existing choice."); end if; end loop; end; end Menu;
with Ada.Formatting; with Interfaces; with System.Machine_Code; procedure fpu is use type Interfaces.Unsigned_16; CW : aliased Interfaces.Unsigned_16 := 0; begin System.Machine_Code.Asm ("fstcw (%0)", Inputs => System.Address'Asm_Input ("r", CW'Address), Volatile => True); declare function Image is new Ada.Formatting.Modular_Image ( Interfaces.Unsigned_16, Form => Ada.Formatting.Simple, Signs => Ada.Formatting.Triming_Unsign_Marks, Base => 16, Digits_Width => 4); begin Ada.Debug.Put (Image (CW)); end; -- 0 : IM (Invalid-op Mask), 1 as masking exceptions -- 1 : DM (Denormal Mask) -- 2 : ZM (Zero-divide Mask) -- 3 : OM (Overflow Mask) -- 4 : UM (Underflow Mask) -- 5 : PM (Precision Mask) -- 6 .. 7 : ?? -- 8 .. 9 : PC (Precision Control), expected to 2#11# as extended -- 10 .. 11 : RC (Rounding Control), 0 as rounding -- 12 : X (Infinity Control), no effect -- 13 .. 15 : ?? if (CW and 16#0300#) = 16#0300# then Ada.Debug.Put ("ok, extended precision"); end if; end fpu;
-- Copyright (c) 2010 - 2018, Nordic Semiconductor ASA -- -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without modification, -- are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form, except as embedded into a Nordic -- Semiconductor ASA integrated circuit in a product or a software update for -- such product, must reproduce the above copyright notice, this list of -- conditions and the following disclaimer in the documentation and/or other -- materials provided with the distribution. -- -- 3. Neither the name of Nordic Semiconductor ASA nor the names of its -- contributors may be used to endorse or promote products derived from this -- software without specific prior written permission. -- -- 4. This software, with or without modification, must only be used with a -- Nordic Semiconductor ASA integrated circuit. -- -- 5. Any software provided in binary form under this license must not be reverse -- engineered, decompiled, modified and/or disassembled. -- -- THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS -- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -- OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -- GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- This spec has been automatically generated from nrf52.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package NRF_SVD.EGU is pragma Preelaborate; --------------- -- Registers -- --------------- -- Description collection[0]: Trigger 0 for triggering the corresponding TRIGGERED[0] event -- Description collection[0]: Trigger 0 for triggering the corresponding -- TRIGGERED[0] event type TASKS_TRIGGER_Registers is array (0 .. 15) of HAL.UInt32; -- Description collection[0]: Event number 0 generated by triggering the corresponding TRIGGER[0] task -- Description collection[0]: Event number 0 generated by triggering the -- corresponding TRIGGER[0] task type EVENTS_TRIGGERED_Registers is array (0 .. 15) of HAL.UInt32; -- Enable or disable interrupt for TRIGGERED[0] event type INTEN_TRIGGERED0_Field is (-- Disable Disabled, -- Enable Enabled) with Size => 1; for INTEN_TRIGGERED0_Field use (Disabled => 0, Enabled => 1); -- INTEN_TRIGGERED array type INTEN_TRIGGERED_Field_Array is array (0 .. 15) of INTEN_TRIGGERED0_Field with Component_Size => 1, Size => 16; -- Type definition for INTEN_TRIGGERED type INTEN_TRIGGERED_Field (As_Array : Boolean := False) is record case As_Array is when False => -- TRIGGERED as a value Val : HAL.UInt16; when True => -- TRIGGERED as an array Arr : INTEN_TRIGGERED_Field_Array; end case; end record with Unchecked_Union, Size => 16; for INTEN_TRIGGERED_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- Enable or disable interrupt type INTEN_Register is record -- Enable or disable interrupt for TRIGGERED[0] event TRIGGERED : INTEN_TRIGGERED_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTEN_Register use record TRIGGERED at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- Write '1' to Enable interrupt for TRIGGERED[0] event type INTENSET_TRIGGERED0_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENSET_TRIGGERED0_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Enable interrupt for TRIGGERED[0] event type INTENSET_TRIGGERED0_Field_1 is (-- Reset value for the field Intenset_Triggered0_Field_Reset, -- Enable Set) with Size => 1; for INTENSET_TRIGGERED0_Field_1 use (Intenset_Triggered0_Field_Reset => 0, Set => 1); -- INTENSET_TRIGGERED array type INTENSET_TRIGGERED_Field_Array is array (0 .. 15) of INTENSET_TRIGGERED0_Field_1 with Component_Size => 1, Size => 16; -- Type definition for INTENSET_TRIGGERED type INTENSET_TRIGGERED_Field (As_Array : Boolean := False) is record case As_Array is when False => -- TRIGGERED as a value Val : HAL.UInt16; when True => -- TRIGGERED as an array Arr : INTENSET_TRIGGERED_Field_Array; end case; end record with Unchecked_Union, Size => 16; for INTENSET_TRIGGERED_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- Enable interrupt type INTENSET_Register is record -- Write '1' to Enable interrupt for TRIGGERED[0] event TRIGGERED : INTENSET_TRIGGERED_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTENSET_Register use record TRIGGERED at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- Write '1' to Disable interrupt for TRIGGERED[0] event type INTENCLR_TRIGGERED0_Field is (-- Read: Disabled Disabled, -- Read: Enabled Enabled) with Size => 1; for INTENCLR_TRIGGERED0_Field use (Disabled => 0, Enabled => 1); -- Write '1' to Disable interrupt for TRIGGERED[0] event type INTENCLR_TRIGGERED0_Field_1 is (-- Reset value for the field Intenclr_Triggered0_Field_Reset, -- Disable Clear) with Size => 1; for INTENCLR_TRIGGERED0_Field_1 use (Intenclr_Triggered0_Field_Reset => 0, Clear => 1); -- INTENCLR_TRIGGERED array type INTENCLR_TRIGGERED_Field_Array is array (0 .. 15) of INTENCLR_TRIGGERED0_Field_1 with Component_Size => 1, Size => 16; -- Type definition for INTENCLR_TRIGGERED type INTENCLR_TRIGGERED_Field (As_Array : Boolean := False) is record case As_Array is when False => -- TRIGGERED as a value Val : HAL.UInt16; when True => -- TRIGGERED as an array Arr : INTENCLR_TRIGGERED_Field_Array; end case; end record with Unchecked_Union, Size => 16; for INTENCLR_TRIGGERED_Field use record Val at 0 range 0 .. 15; Arr at 0 range 0 .. 15; end record; -- Disable interrupt type INTENCLR_Register is record -- Write '1' to Disable interrupt for TRIGGERED[0] event TRIGGERED : INTENCLR_TRIGGERED_Field := (As_Array => False, Val => 16#0#); -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for INTENCLR_Register use record TRIGGERED at 0 range 0 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Event Generator Unit 0 type EGU_Peripheral is record -- Description collection[0]: Trigger 0 for triggering the corresponding -- TRIGGERED[0] event TASKS_TRIGGER : aliased TASKS_TRIGGER_Registers; -- Description collection[0]: Event number 0 generated by triggering the -- corresponding TRIGGER[0] task EVENTS_TRIGGERED : aliased EVENTS_TRIGGERED_Registers; -- Enable or disable interrupt INTEN : aliased INTEN_Register; -- Enable interrupt INTENSET : aliased INTENSET_Register; -- Disable interrupt INTENCLR : aliased INTENCLR_Register; end record with Volatile; for EGU_Peripheral use record TASKS_TRIGGER at 16#0# range 0 .. 511; EVENTS_TRIGGERED at 16#100# range 0 .. 511; INTEN at 16#300# range 0 .. 31; INTENSET at 16#304# range 0 .. 31; INTENCLR at 16#308# range 0 .. 31; end record; -- Event Generator Unit 0 EGU0_Periph : aliased EGU_Peripheral with Import, Address => EGU0_Base; -- Event Generator Unit 1 EGU1_Periph : aliased EGU_Peripheral with Import, Address => EGU1_Base; -- Event Generator Unit 2 EGU2_Periph : aliased EGU_Peripheral with Import, Address => EGU2_Base; -- Event Generator Unit 3 EGU3_Periph : aliased EGU_Peripheral with Import, Address => EGU3_Base; -- Event Generator Unit 4 EGU4_Periph : aliased EGU_Peripheral with Import, Address => EGU4_Base; -- Event Generator Unit 5 EGU5_Periph : aliased EGU_Peripheral with Import, Address => EGU5_Base; end NRF_SVD.EGU;
------------------------------------------------------------------------------ -- A d a r u n - t i m e s p e c i f i c a t i o n -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of ada.ads file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $ with Ada.Streams; package Ada.Exceptions is pragma Preelaborate (Exceptions); type Exception_Id is private; pragma Preelaborable_Initialization (Exception_Id); Null_Id : constant Exception_Id; function Exception_Name (Id : in Exception_Id) return String; function Wide_Exception_Name (Id : in Exception_Id) return Wide_String; function Wide_Wide_Exception_Name (Id : in Exception_Id) return Wide_Wide_String; type Exception_Occurrence is limited private; pragma Preelaborable_Initialization (Exception_Occurrence); type Exception_Occurrence_Access is access all Exception_Occurrence; Null_Occurrence : constant Exception_Occurrence; procedure Raise_Exception (E : in Exception_Id; Message : in String := ""); pragma No_Return (Raise_Exception); function Exception_Message (X : in Exception_Occurrence) return String; procedure Reraise_Occurrence (X : in Exception_Occurrence); function Exception_Identity (X : in Exception_Occurrence) return Exception_Id; function Exception_Name (X : in Exception_Occurrence) return String; -- Same as Exception_Name(Exception_Identity(X)). function Wide_Exception_Name (X : in Exception_Occurrence) return Wide_String; -- Same as Wide_Exception_Name(Exception_Identity(X)). function Wide_Wide_Exception_Name (X : in Exception_Occurrence) return Wide_Wide_String; -- Same as Wide_Wide_Exception_Name(Exception_Identity(X)). function Exception_Information (X : in Exception_Occurrence) return String; procedure Save_Occurrence (Target : out Exception_Occurrence; Source : in Exception_Occurrence); function Save_Occurrence (Source : in Exception_Occurrence) return Exception_Occurrence_Access; procedure Read_Exception_Occurrence (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : out Exception_Occurrence); procedure Write_Exception_Occurrence (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : in Exception_Occurrence); for Exception_Occurrence'Read use Read_Exception_Occurrence; for Exception_Occurrence'Write use Write_Exception_Occurrence; private pragma Import (Ada, Exception_Id); pragma Import (Ada, Exception_Occurrence); pragma Import (Ada, Null_Id); pragma Import (Ada, Null_Occurrence); end Ada.Exceptions;
with FLTK.Menu_Items, Ada.Iterator_Interfaces; private with Ada.Containers.Vectors, Interfaces, System; package FLTK.Widgets.Menus is type Menu is new Widget with private with Default_Iterator => Iterate, Iterator_Element => FLTK.Menu_Items.Menu_Item_Reference, Variable_Indexing => Item; type Menu_Reference (Data : not null access Menu'Class) is limited null record with Implicit_Dereference => Data; subtype Index is Positive; subtype Extended_Index is Natural; No_Index : constant Extended_Index := Extended_Index'First; type Cursor is private; package Forge is function Create (X, Y, W, H : in Integer; Text : in String) return Menu; end Forge; procedure Add (This : in out Menu; Text : in String; Action : in Widget_Callback := null; Shortcut : in Key_Combo := No_Key; Flags : in Menu_Flag := Flag_Normal); procedure Insert (This : in out Menu; Place : in Index; Text : in String; Action : in Widget_Callback := null; Shortcut : in Key_Combo := No_Key; Flags : in Menu_Flag := Flag_Normal); procedure Remove (This : in out Menu; Place : in Index); procedure Clear (This : in out Menu); function Has_Item (This : in Menu; Place : in Index) return Boolean; function Has_Item (Place : in Cursor) return Boolean; function Item (This : in Menu; Place : in Index) return FLTK.Menu_Items.Menu_Item_Reference; function Item (This : in Menu; Place : in Cursor) return FLTK.Menu_Items.Menu_Item_Reference; function Find_Item (This : in Menu; Name : in String) return FLTK.Menu_Items.Menu_Item_Reference; function Find_Item (This : in Menu; Action : in Widget_Callback) return FLTK.Menu_Items.Menu_Item_Reference; function Find_Index (This : in Menu; Name : in String) return Extended_Index; function Find_Index (This : in Menu; Item : in FLTK.Menu_Items.Menu_Item) return Extended_Index; function Find_Index (This : in Menu; Action : in Widget_Callback) return Extended_Index; function Number_Of_Items (This : in Menu) return Natural; package Menu_Iterators is new Ada.Iterator_Interfaces (Cursor, Has_Item); function Iterate (This : in Menu) return Menu_Iterators.Reversible_Iterator'Class; function Chosen (This : in Menu) return FLTK.Menu_Items.Menu_Item_Reference; function Chosen_Label (This : in Menu) return String; function Chosen_Index (This : in Menu) return Extended_Index; procedure Set_Chosen (This : in out Menu; Place : in Index); procedure Set_Chosen (This : in out Menu; Item : in FLTK.Menu_Items.Menu_Item); function Get_Text_Color (This : in Menu) return Color; procedure Set_Text_Color (This : in out Menu; To : in Color); function Get_Text_Font (This : in Menu) return Font_Kind; procedure Set_Text_Font (This : in out Menu; To : in Font_Kind); function Get_Text_Size (This : in Menu) return Font_Size; procedure Set_Text_Size (This : in out Menu; To : in Font_Size); function Get_Down_Box (This : in Menu) return Box_Kind; procedure Set_Down_Box (This : in out Menu; To : in Box_Kind); procedure Make_Global (This : in out Menu); procedure Measure_Item (This : in Menu; Item : in Index; W, H : out Integer); function Popup (This : in Menu; X, Y : in Integer; Title : in String := ""; Initial : in Extended_Index := No_Index) return FLTK.Menu_Items.Menu_Item_Reference; function Pulldown (This : in Menu; X, Y, W, H : in Integer; Initial : in Extended_Index := No_Index) return FLTK.Menu_Items.Menu_Item_Reference; procedure Draw (This : in out Menu) is null; procedure Draw_Item (This : in out Menu; Item : in Index; X, Y, W, H : in Integer; Selected : in Boolean := False); function Handle (This : in out Menu; Event : in Event_Kind) return Event_Outcome; private -- I'm not very happy with using a Vector of dynamically allocated -- Menu_Item wrappers like this, but I kinda painted myself into a -- corner with use of Limited_Controlled and the way the Add method -- works for Menus. type Item_Access is access FLTK.Menu_Items.Menu_Item; package Item_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Item_Access); type Menu is new Widget with record My_Items : Item_Vectors.Vector; end record; overriding procedure Finalize (This : in out Menu); procedure Item_Hook (M, U : in System.Address); pragma Convention (C, Item_Hook); type Cursor is record My_Container : access Menu; My_Index : Index'Base := Index'First; end record; type Iterator is new Menu_Iterators.Reversible_Iterator with record My_Container : access Menu; end record; overriding function First (Object : in Iterator) return Cursor; overriding function Next (Object : in Iterator; Place : in Cursor) return Cursor; overriding function Last (Object : in Iterator) return Cursor; overriding function Previous (Object : in Iterator; Place : in Cursor) return Cursor; pragma Inline (Has_Item); pragma Inline (Item); pragma Inline (Find_Item); pragma Inline (Find_Index); pragma Inline (Number_Of_Items); pragma Inline (Iterate); pragma Inline (Chosen); pragma Inline (Chosen_Label); pragma Inline (Chosen_Index); pragma Inline (Set_Chosen); pragma Inline (Get_Text_Color); pragma Inline (Set_Text_Color); pragma Inline (Get_Text_Font); pragma Inline (Set_Text_Font); pragma Inline (Get_Text_Size); pragma Inline (Set_Text_Size); pragma Inline (Get_Down_Box); pragma Inline (Set_Down_Box); pragma Inline (Make_Global); pragma Inline (Measure_Item); pragma Inline (Popup); pragma Inline (Pulldown); pragma Inline (Draw); pragma Inline (Draw_Item); pragma Inline (Handle); end FLTK.Widgets.Menus;
-- Copyright (c) 2015-2019 Marcel Schneider -- for details see License.txt with TokenValue; use TokenValue; package TokenReading is type Object is interface; function ReadToken (O : Object) return TokenValue.Object is abstract; end TokenReading;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- XML Processor -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2011, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ package Matreshka.Internals.XML is pragma Pure; type Attribute_Identifier is private; No_Attribute : constant Attribute_Identifier; -- Internal identifier of attribute type declaration. type Element_Identifier is private; No_Element : constant Element_Identifier; -- Internal identifier of element declaration. type Entity_Identifier is private; No_Entity : constant Entity_Identifier; Entity_lt : constant Entity_Identifier; Entity_gt : constant Entity_Identifier; Entity_amp : constant Entity_Identifier; Entity_apos : constant Entity_Identifier; Entity_quot : constant Entity_Identifier; -- Internal identifier of entity. type Notation_Identifier is private; No_Notation : constant Notation_Identifier; -- Internal identifier of notation. type Symbol_Identifier is private; No_Symbol : constant Symbol_Identifier; Symbol_lt : constant Symbol_Identifier; Symbol_gt : constant Symbol_Identifier; Symbol_amp : constant Symbol_Identifier; Symbol_apos : constant Symbol_Identifier; Symbol_quot : constant Symbol_Identifier; Symbol_CDATA : constant Symbol_Identifier; Symbol_ID : constant Symbol_Identifier; Symbol_IDREF : constant Symbol_Identifier; Symbol_IDREFS : constant Symbol_Identifier; Symbol_NMTOKEN : constant Symbol_Identifier; Symbol_NMTOKENS : constant Symbol_Identifier; Symbol_ENTITY : constant Symbol_Identifier; Symbol_ENTITIES : constant Symbol_Identifier; Symbol_NOTATION : constant Symbol_Identifier; Symbol_xml : constant Symbol_Identifier; Symbol_xmlns : constant Symbol_Identifier; Symbol_xml_NS : constant Symbol_Identifier; Symbol_xmlns_NS : constant Symbol_Identifier; Symbol_xml_base : constant Symbol_Identifier; -- Internal identifier of symbol. Symbols are used to associate different -- kinds of items with name, and to minimize amount of used memory to store -- names. private type Attribute_Identifier is mod 2 ** 32; No_Attribute : constant Attribute_Identifier := 0; type Element_Identifier is mod 2 ** 32; No_Element : constant Element_Identifier := 0; type Entity_Identifier is mod 2 ** 32; No_Entity : constant Entity_Identifier := 0; Entity_lt : constant Entity_Identifier := 1; Entity_gt : constant Entity_Identifier := 2; Entity_amp : constant Entity_Identifier := 3; Entity_apos : constant Entity_Identifier := 4; Entity_quot : constant Entity_Identifier := 5; type Notation_Identifier is mod 2 ** 32; No_Notation : constant Notation_Identifier := 0; type Symbol_Identifier is mod 2 ** 32; No_Symbol : constant Symbol_Identifier := 0; Symbol_lt : constant Symbol_Identifier := 1; Symbol_gt : constant Symbol_Identifier := 2; Symbol_amp : constant Symbol_Identifier := 3; Symbol_apos : constant Symbol_Identifier := 4; Symbol_quot : constant Symbol_Identifier := 5; Symbol_CDATA : constant Symbol_Identifier := 6; Symbol_ID : constant Symbol_Identifier := 7; Symbol_IDREF : constant Symbol_Identifier := 8; Symbol_IDREFS : constant Symbol_Identifier := 9; Symbol_NMTOKEN : constant Symbol_Identifier := 10; Symbol_NMTOKENS : constant Symbol_Identifier := 11; Symbol_ENTITY : constant Symbol_Identifier := 12; Symbol_ENTITIES : constant Symbol_Identifier := 13; Symbol_NOTATION : constant Symbol_Identifier := 14; Symbol_xml : constant Symbol_Identifier := 15; Symbol_xmlns : constant Symbol_Identifier := 16; Symbol_xml_NS : constant Symbol_Identifier := 17; Symbol_xmlns_NS : constant Symbol_Identifier := 18; Symbol_xml_base : constant Symbol_Identifier := 19; end Matreshka.Internals.XML;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $ with Ada.Unchecked_Conversion; with Ada.Streams.Stream_IO; with Gela.Hash.SHA.b512; package body Gela.Repository.Dictionary.File is Signature : constant String := "Gela_Repository_Dictionary$"; Version : constant String := "v1.0"; Extension : constant String := ".grd"; use Ada.Streams.Stream_IO; Signature_Size : constant Ada.Streams.Stream_IO.Count := Signature'Size / Ada.Streams.Stream_Element'Size + Version'Size / Ada.Streams.Stream_Element'Size; Minimum_Size : constant Ada.Streams.Stream_IO.Count := Signature_Size + Gela.Hash.SHA.b512.SHA512'Size / Ada.Streams.Stream_Element'Size + Integer'Size / Ada.Streams.Stream_Element'Size; Divisor : constant := Wide_Wide_Character'Size / Ada.Streams.Stream_Element'Size; ---------------- -- Initialize -- ---------------- procedure Initialize (This : in out Gela_Dictionary_File) is File : File_Type; File_Stream : Stream_Access; Last : Ada.Streams.Stream_Element_Offset; -- Read_Element -- procedure Read_Element is use Ada.Streams; Element : ID_Point; String_Size : Integer; begin ID'Read (File_Stream, Element.Num); Integer'Read (File_Stream, String_Size); declare subtype Constrained_Wide_Wide_String is Wide_Wide_String (1 .. String_Size); function To_Wide_Wide_String is new Ada.Unchecked_Conversion (Stream_Element_Array, Constrained_Wide_Wide_String); String_Data : Stream_Element_Array (1 .. Stream_Element_Offset (String_Size * Divisor)); begin Read (File, String_Data, Last); Element.Data := new Wide_Wide_String' (To_Wide_Wide_String (String_Data)); end; Insert (This, Count (This) + 1, Element); end Read_Element; begin try : begin Open (File, In_File, "dictionary" & Extension); exception when others => return; end try; if not Is_Open (File) or else Size (File) < Minimum_Size then Close (File); return; end if; File_Stream := Stream (File); declare File_Signature : String (1 .. Signature'Length); begin String'Read (File_Stream, File_Signature); if File_Signature /= Signature then Close (File); return; end if; end; declare File_Version : String (1 .. Version'Length); begin String'Read (File_Stream, File_Version); if File_Version /= Version then Close (File); return; end if; end; declare use Gela.Hash.SHA.b512; use Ada.Streams; Store_SHA, File_SHA : SHA512; File_Hasher : Hasher_512; Data_Array : Ada.Streams.Stream_Element_Array (1 .. 128); begin SHA512'Read (File_Stream, Store_SHA); loop Read (File_Stream.all, Data_Array, Last); if Last = Data_Array'Last then Update (File_Hasher, Data_Array); else Update (File_Hasher, Data_Array (1 .. Last)); exit; end if; end loop; Result (File_Hasher, File_SHA); if File_SHA /= File_SHA then Close (File); return; end if; end; Set_Index (File, Signature_Size + 1 + Gela.Hash.SHA.b512.SHA512'Size / Ada.Streams.Stream_Element'Size); declare Count : Integer; begin Integer'Read (File_Stream, Count); for Index in 1 .. Count loop Read_Element; end loop; end; Close (File); exception when others => Close (File); raise; end Initialize; ---------- -- Save -- ---------- procedure Save (This : in out Gela_Dictionary_File) is use Ada.Streams; File : File_Type; File_Stream : Stream_Access; subtype Integer_Stream_Element_Array is Stream_Element_Array (1 .. Integer'Size / Stream_Element'Size); function To_Stream_Element_Array is new Ada.Unchecked_Conversion (Integer, Integer_Stream_Element_Array); subtype ID_Stream_Element_Array is Stream_Element_Array (1 .. ID'Size / Stream_Element'Size); function To_Stream_Element_Array is new Ada.Unchecked_Conversion (ID, ID_Stream_Element_Array); -- Element_Data -- function Element_Data (Index : in Positive) return Ada.Streams.Stream_Element_Array is String_Size : constant Integer := This.Data (Index).Data'Length; subtype Constrained_Stream_Element_Array is Stream_Element_Array (1 .. Stream_Element_Offset (String_Size * Divisor)); function To_Stream_Element_Array is new Ada.Unchecked_Conversion (Wide_Wide_String, Constrained_Stream_Element_Array); begin return To_Stream_Element_Array (This.Data (Index).Num) & To_Stream_Element_Array (String_Size) & To_Stream_Element_Array (This.Data (Index).Data.all); end Element_Data; begin try : begin Open (File, Out_File, "dictionary.grp"); exception when others => Create (File, Out_File, "dictionary" & Extension); end try; if not Is_Open (File) then raise Use_Error; end if; File_Stream := Stream (File); String'Write (File_Stream, Signature); String'Write (File_Stream, Version); declare use Gela.Hash.SHA.b512; File_SHA : SHA512; File_Hasher : Hasher_512; begin Update (File_Hasher, To_Stream_Element_Array (Count (This))); for Index in 1 .. Count (This) loop Update (File_Hasher, Element_Data (Index)); end loop; Result (File_Hasher, File_SHA); SHA512'Write (File_Stream, File_SHA); end; Write (File, To_Stream_Element_Array (Count (This))); for Index in 1 .. Count (This) loop Write (File, Element_Data (Index)); end loop; Close (File); end Save; end Gela.Repository.Dictionary.File; ------------------------------------------------------------------------------ -- Copyright (c) 2006, Andry Ogorodnik -- 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. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
----------------------------------------------------------------------- -- ado-audits-tests -- Audit tests -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with Ada.Text_IO; with Regtests.Audits.Model; with ADO.SQL; with ADO.Sessions.Entities; package body ADO.Audits.Tests is use type ADO.Objects.Object_Key_Type; package Caller is new Util.Test_Caller (Test, "ADO.Audits"); type Test_Audit_Manager is new Audit_Manager with null record; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Test_Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in Auditable_Object_Record'Class; Changes : in Audit_Array); Audit_Instance : aliased Test_Audit_Manager; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Test_Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in Auditable_Object_Record'Class; Changes : in Audit_Array) is pragma Unreferenced (Manager); Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key); begin for C of Changes loop declare Audit : Regtests.Audits.Model.Audit_Ref; begin if Object.Key_Type = ADO.Objects.KEY_INTEGER then Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key)); end if; Audit.Set_Entity_Type (Kind); Audit.Set_Old_Value (UBO.To_String (C.Old_Value)); Audit.Set_New_Value (UBO.To_String (C.New_Value)); Audit.Set_Date (Now); Audit.Save (Session); end; end loop; end Save; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Audits.Audit_Field", Test_Audit_Field'Access); end Add_Tests; procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin Regtests.Set_Audit_Manager (Audit_Instance'Access); end Set_Up; -- ------------------------------ -- Test populating Audit_Fields -- ------------------------------ procedure Test_Audit_Field (T : in out Test) is type Identifier_Array is array (1 .. 10) of ADO.Identifier; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Email : Regtests.Audits.Model.Email_Ref; Prop : Regtests.Audits.Model.Property_Ref; List : Identifier_Array; begin for I in List'Range loop Email := Regtests.Audits.Model.Null_Email; Email.Set_Email ("Email" & Util.Strings.Image (I) & "@nowhere.com"); Email.Set_Status (ADO.Nullable_Integer '(23, False)); Email.Save (DB); List (I) := Email.Get_Id; end loop; DB.Commit; for Id of List loop Email.Load (DB, Id); Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False)); Email.Save (DB); Email.Set_Email ("Email" & Util.Strings.Image (Natural (Id)) & Util.Strings.Image (Email.Get_Status.Value) & "@here.com"); Email.Save (DB); Email.Set_Email ("Email" & Util.Strings.Image (Natural (Id)) & Util.Strings.Image (Email.Get_Status.Value) & "@there.com"); Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False)); Email.Save (DB); end loop; DB.Commit; for Id of List loop Email.Load (DB, Id); Email.Set_Status (ADO.Null_Integer); Email.Save (DB); end loop; DB.Commit; Prop.set_Id (Util.Tests.Get_Uuid); for I in 1 .. 10 loop Prop.Set_Value ((Value => I, Is_Null => False)); Prop.Set_Float_Value (3.0 * Float (I)); Prop.Save (DB); end loop; declare Query : ADO.SQL.Query; Audit_List : Regtests.Audits.Model.Audit_Vector; begin Query.Set_Filter ("entity_id = :entity_id"); for Id of List loop Query.Bind_Param ("entity_id", Id); Regtests.Audits.Model.List (Audit_List, DB, Query); for A of Audit_List loop Ada.Text_IO.Put_Line (ADO.Identifier'Image (Id) & " " & ADO.Identifier'Image (A.Get_Id) & " " & A.Get_Old_Value & " - " & A.Get_New_Value); Util.Tests.Assert_Equals (T, Natural (Id), Natural (A.Get_Entity_Id), "Invalid audit record: id is wrong"); end loop; Util.Tests.Assert_Equals (T, 7, Natural (Audit_List.Length), "Invalid number of audit records"); end loop; end; end Test_Audit_Field; end ADO.Audits.Tests;
-- Copyright (c) 2021 Devin Hill -- zlib License -- see LICENSE for details. with Interfaces; use Interfaces; package GBA.Numerics is pragma Preelaborate; Pi : constant := 3.14159_26535_89793_23846_26433_83279_50288_41971_69399_37511; e : constant := 2.71828_18284_59045_23536_02874_71352_66249_77572_47093_69996; type Fixed_2_14 is delta 2.0**(-14) range -2.0 .. 2.0 - 2.0**(-14) with Size => 16; type Fixed_20_8 is delta 2.0**(-8) range -2.0**19 .. 2.0**19 with Size => 32; type Fixed_8_8 is delta 2.0**(-8) range -2.0**7 .. 2.0**7 - 2.0**(-8) with Size => 16; type Fixed_2_30 is delta 2.0**(-30) range -2.0 .. 2.0 - 2.0**(-30) with Size => 32; type Fixed_Unorm_8 is delta 2.0**(-8) range 0.0 .. 1.0 - 2.0**(-8) with Size => 8; type Fixed_Unorm_16 is delta 2.0**(-16) range 0.0 .. 1.0 - 2.0**(-16) with Size => 16; type Fixed_Unorm_32 is delta 2.0**(-32) range 0.0 .. 1.0 - 2.0**(-32) with Size => 32; subtype Fixed_Snorm_16 is Fixed_2_14 range -1.0 .. 1.0; subtype Fixed_Snorm_32 is Fixed_2_30 range -1.0 .. 1.0; -- Consider this to have an implicit unit of 2*Pi. -- Additive operators are defined to be cyclic. type Radians_16 is new Fixed_Unorm_16; overriding function "+" (X, Y : Radians_16) return Radians_16 with Pure_Function, Inline_Always; overriding function "-" (X, Y : Radians_16) return Radians_16 with Pure_Function, Inline_Always; overriding function "-" (X : Radians_16) return Radians_16 with Pure_Function, Inline_Always; -- Consider this to have an implicit unit of 2*Pi. -- Additive operators are defined to be cyclic. type Radians_32 is new Fixed_Unorm_32; overriding function "+" (X, Y : Radians_32) return Radians_32 with Pure_Function, Inline_Always; overriding function "-" (X, Y : Radians_32) return Radians_32 with Pure_Function, Inline_Always; overriding function "-" (X : Radians_32) return Radians_32 with Pure_Function, Inline_Always; subtype Affine_Transform_Parameter is Fixed_8_8; type Affine_Transform_Matrix is record DX, DMX, DY, DMY : Affine_Transform_Parameter; end record with Size => 64; for Affine_Transform_Matrix use record DX at 0 range 0 .. 15; DMX at 2 range 0 .. 15; DY at 4 range 0 .. 15; DMY at 6 range 0 .. 15; end record; function Sqrt (N : Unsigned_32) return Unsigned_16 with Pure_Function, Import, External_Name => "usqrt"; generic type Fixed is delta <>; with function Sqrt (N : Unsigned_32) return Unsigned_16; function Fixed_Sqrt (F : Fixed) return Fixed with Inline_Always; function Sin (Theta : Radians_32) return Fixed_Snorm_32 with Pure_Function, Inline_Always; function Cos (Theta : Radians_32) return Fixed_Snorm_32 with Pure_Function, Inline_Always; procedure Sin_Cos (Theta : Radians_32; Sin, Cos : out Fixed_Snorm_32) with Linker_Section => ".iwram.sin_cos"; pragma Machine_Attribute (Sin_Cos, "target", "arm"); function Sin_LUT (Theta : Radians_16) return Fixed_Snorm_16 with Pure_Function, Linker_Section => ".iwram.sin_lut"; function Cos_LUT (Theta : Radians_16) return Fixed_Snorm_16 with Pure_Function, Inline_Always; procedure Sin_Cos_LUT (Theta : Radians_16; Sin, Cos : out Fixed_Snorm_16) with Inline_Always; pragma Machine_Attribute (Sin_LUT, "target", "arm"); function Count_Trailing_Zeros (I : Long_Long_Integer) return Natural with Pure_Function, Inline_Always; function Count_Trailing_Zeros (I : Unsigned_64) return Natural with Pure_Function, Linker_Section => ".iwram.ctz64"; pragma Machine_Attribute (Count_Trailing_Zeros, "target", "arm"); function Count_Trailing_Zeros (I : Integer) return Natural with Pure_Function, Inline_Always; function Count_Trailing_Zeros (I : Unsigned_32) return Natural with Pure_Function, Linker_Section => ".iwram.ctz"; pragma Machine_Attribute (Count_Trailing_Zeros, "target", "arm"); function Count_Trailing_Zeros (I : Integer_16) return Natural with Pure_Function, Inline_Always; function Count_Trailing_Zeros (I : Unsigned_16) return Natural with Pure_Function, Linker_Section => ".iwram.ctz16"; pragma Machine_Attribute (Count_Trailing_Zeros, "target", "arm"); function Count_Leading_Zeros (I : Long_Long_Integer) return Natural with Pure_Function, Inline_Always; function Count_Leading_Zeros (I : Unsigned_64) return Natural with Pure_Function, Linker_Section => ".iwram.clz64"; pragma Machine_Attribute (Count_Leading_Zeros, "target", "arm"); function Count_Leading_Zeros (I : Integer) return Natural with Pure_Function, Inline_Always; function Count_Leading_Zeros (I : Unsigned_32) return Natural with Pure_Function, Linker_Section => ".iwram.clz"; pragma Machine_Attribute (Count_Leading_Zeros, "target", "arm"); function Count_Leading_Zeros (I : Integer_16) return Natural with Pure_Function, Inline_Always; function Count_Leading_Zeros (I : Unsigned_16) return Natural with Pure_Function, Linker_Section => ".iwram.clz16"; pragma Machine_Attribute (Count_Leading_Zeros, "target", "arm"); end GBA.Numerics;
-- -- Jan & Uwe R. Zimmer, Australia, July 2011 -- with Real_Type; use Real_Type; generic type Element is private; Buffer_Size : Positive; package Generic_Sliding_Statistics is procedure Add_Reading (New_Reading : Element); generic with function "+" (Left, Right : Element) return Element is <>; with function "/" (Left : Element; Right : Real) return Element is <>; package Averages is function Average (New_Reading : Element) return Element; function Average return Element; end Averages; -- generic pragma Warnings (Off, "declaration of ""<"" hides predefined operator"); with function "<" (Left, Right : Element) return Boolean is <>; pragma Warnings (On, "declaration of ""<"" hides predefined operator"); package MinMax is function Min (New_Reading : Element) return Element; function Max (New_Reading : Element) return Element; function Min return Element; function Max return Element; end MinMax; No_Elements_in_Stats_Buffer : exception; end Generic_Sliding_Statistics;
with Ada.Directories; with Ada.Strings.Unbounded; with AWS.Messages; with AWS.MIME; with AWS.Templates; package body @_Project_Name_@.Dispatchers is use Ada; use Ada.Strings.Unbounded; Web_Root : Unbounded_String; ---------------------- -- Default Dispatch -- ---------------------- overriding function Dispatch (Dispatcher : in Default; Request : in Status.Data) return Response.Data is pragma Unreferenced (Dispatcher); URI : constant String := Status.URI (Request); Translations : Templates.Translate_Set; begin if URI = "/" then Templates.Insert (Translations, Templates.Assoc ("MESSAGE", "This is the main page")); return Response.Build (MIME.Text_HTML, String'(Templates.Parse (Filename => To_String (Web_Root) & "tmplt/main.thtml", Translations => Translations))); else return Response.Acknowledge (Messages.S404, "Unknown page"); end if; end Dispatch; ------------------ -- CSS Dispatch -- ------------------ overriding function Dispatch (Dispatcher : in CSS; Request : in Status.Data) return Response.Data is pragma Unreferenced (Dispatcher); URI : constant String := Status.URI (Request); File : constant String := To_String (Web_Root) & URI (URI'First + 1 .. URI'Last); begin if Directories.Exists (File) then return Response.File (Content_Type => MIME.Text_CSS, Filename => File); else return Response.Acknowledge (Messages.S404); end if; end Dispatch; -------------------- -- Image Dispatch -- -------------------- overriding function Dispatch (Dispatcher : in Image; Request : in Status.Data) return Response.Data is pragma Unreferenced (Dispatcher); URI : constant String := Status.URI (Request); File : constant String := To_String (Web_Root) & URI (URI'First + 1 .. URI'Last); begin if Directories.Exists (File) then return Response.File (Content_Type => MIME.Content_Type (File), Filename => File); else return Response.Acknowledge (Messages.S404); end if; end Dispatch; ---------------- -- Initialize -- ---------------- procedure Initialize (Web_Config : in Config.Object) is begin Web_Root := To_Unbounded_String (Config.WWW_Root (Web_Config)); end Initialize; end @_Project_Name_@.Dispatchers;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- H O S T P A R M -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2009, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package defines some system dependent parameters for GNAT. These -- are parameters that are relevant to the host machine on which the -- compiler is running, and thus this package is part of the compiler. with Types; package Hostparm is --------------------- -- HOST Parameters -- --------------------- Gnat_VMSp : Integer; pragma Import (C, Gnat_VMSp, "__gnat_vmsp"); OpenVMS : Boolean := Gnat_VMSp /= 0; -- Set True for OpenVMS host. See also OpenVMS target boolean in -- system-vms.ads and system-vms_64.ads and OpenVMS_On_Target boolean in -- Targparm. This is not a constant, because it can be modified by -gnatdm. Direct_Separator : constant Character; pragma Import (C, Direct_Separator, "__gnat_dir_separator"); Normalized_CWD : constant String := "." & Direct_Separator; -- Normalized string to access current directory Max_Line_Length : constant := Types.Column_Number'Pred (Types.Column_Number'Last); -- Maximum source line length. By default we set it to the maximum -- value that can be supported, which is given by the range of the -- Column_Number type. We subtract 1 because need to be able to -- have a valid Column_Number equal to Max_Line_Length to represent -- the location of a "line too long" error. -- 200 is the minimum value required (RM 2.2(15)). The value set here -- can be reduced by the explicit use of the -gnatyM style switch. Max_Name_Length : constant := 1024; -- Maximum length of unit name (including all dots, and " (spec)") and -- of file names in the library, must be at least Max_Line_Length, but -- can be larger. Max_Instantiations : constant := 4000; -- Maximum number of instantiations permitted (to stop runaway cases -- of nested instantiations). These situations probably only occur in -- specially concocted test cases. Tag_Errors : constant Boolean := False; -- If set to true, then brief form error messages will be prefaced by -- the string "error:". Used as default for Opt.Unique_Error_Tag. Exclude_Missing_Objects : constant Boolean := True; -- If set to true, gnatbind will exclude from consideration all -- non-existent .o files. Max_Debug_Name_Length : constant := 256; -- If a generated qualified debug name exceeds this length, then it -- is automatically compressed, regardless of the setting of the -- Compress_Debug_Names switch controlled by -gnatC. end Hostparm;
-- A29003A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT ALL PREDEFINED ATTRIBUTES EXCEPT DIGITS, DELTA, AND RANGE, -- AND ALL PREDEFINED TYPE AND PACKAGE NAMES ARE NOT RESERVED WORDS. -- AH 8/11/86 WITH REPORT; USE REPORT; PROCEDURE A29003A IS SUBTYPE INT IS INTEGER; -- PREDEFINED ATTRIBUTES ADDRESS : INT := IDENT_INT(0); -- ATTRIBUTE AFT : INT := IDENT_INT(0); -- ATTRIBUTE BASE : INT := IDENT_INT(0); -- ATTRIBUTE CALLABLE : INT := IDENT_INT(0); -- ATTRIBUTE CONSTRAINED : INT := IDENT_INT(0); -- ATTRIBUTE COUNT : INT := IDENT_INT(0); -- ATTRIBUTE EMAX : INT := IDENT_INT(0); -- ATTRIBUTE EPSILON : INT := IDENT_INT(0); -- ATTRIBUTE FIRST : INT := IDENT_INT(0); -- ATTRIBUTE FIRST_BIT : INT := IDENT_INT(0); -- ATTRIBUTE FORE : INT := IDENT_INT(0); -- ATTRIBUTE IMAGE : INT := IDENT_INT(0); -- ATTRIBUTE LARGE : INT := IDENT_INT(0); -- ATTRIBUTE LAST : INT := IDENT_INT(0); -- ATTRIBUTE LAST_BIT : INT := IDENT_INT(0); -- ATTRIBUTE LENGTH : INT := IDENT_INT(0); -- ATTRIBUTE MACHINE_EMAX : INT := IDENT_INT(0); -- ATTRIBUTE MACHINE_EMIN : INT := IDENT_INT(0); -- ATTRIBUTE MACHINE_MANTISSA : INT := IDENT_INT(0); -- ATTRIBUTE MACHINE_OVERFLOWS : INT := IDENT_INT(0); -- ATTRIBUTE MACHINE_RADIX : INT := IDENT_INT(0); -- ATTRIBUTE MACHINE_ROUNDS : INT := IDENT_INT(0); -- ATTRIBUTE MANTISSA : INT := IDENT_INT(0); -- ATTRIBUTE POS : INT := IDENT_INT(0); -- ATTRIBUTE POSITION : INT := IDENT_INT(0); -- ATTRIBUTE PRED : INT := IDENT_INT(0); -- ATTRIBUTE SAFE_EMAX : INT := IDENT_INT(0); -- ATTRIBUTE SAFE_LARGE : INT := IDENT_INT(0); -- ATTRIBUTE SAFE_SMALL : INT := IDENT_INT(0); -- ATTRIBUTE SIZE : INT := IDENT_INT(0); -- ATTRIBUTE SMALL : INT := IDENT_INT(0); -- ATTRIBUTE STORAGE_SIZE : INT := IDENT_INT(0); -- ATTRIBUTE SUCC : INT := IDENT_INT(0); -- ATTRIBUTE TERMINATED : INT := IDENT_INT(0); -- ATTRIBUTE VAL : INT := IDENT_INT(0); -- ATTRIBUTE VALUE : INT := IDENT_INT(0); -- ATTRIBUTE WIDTH : INT := IDENT_INT(0); -- ATTRIBUTE -- PREDEFINED TYPES BOOLEAN : INT := IDENT_INT(0); -- TYPE CHARACTER : INT := IDENT_INT(0); -- TYPE DURATION : INT := IDENT_INT(0); -- TYPE FLOAT : INT := IDENT_INT(0); -- TYPE INTEGER : INT := IDENT_INT(0); -- TYPE NATURAL : INT := IDENT_INT(0); -- TYPE POSITIVE : INT := IDENT_INT(0); -- TYPE STRING : INT := IDENT_INT(0); -- TYPE -- PREDEFINED PACKAGE NAMES ASCII : INT := IDENT_INT(0); -- PACKAGE CALENDAR : INT := IDENT_INT(0); -- PACKAGE DIRECT_IO : INT := IDENT_INT(0); -- PACKAGE IO_EXCEPTIONS : INT := IDENT_INT(0); -- PACKAGE LOW_LEVEL_IO : INT := IDENT_INT(0); -- PACKAGE MACHINE_CODE : INT := IDENT_INT(0); -- PACKAGE SEQUENTIAL_IO : INT := IDENT_INT(0); -- PACKAGE SYSTEM : INT := IDENT_INT(0); -- PACKAGE TEXT_IO : INT := IDENT_INT(0); -- PACKAGE UNCHECKED_CONVERSION : INT := IDENT_INT(0); -- PACKAGE UNCHECKED_DEALLOCATION : INT := IDENT_INT(0); -- PACKAGE BEGIN TEST("A29003A", "NO ADDITIONAL RESERVED WORDS"); RESULT; END A29003A;
------------------------------------------------------------------------------ -- G E L A A S I S -- -- ASIS implementation for Gela project, a portable Ada compiler -- -- http://gela.ada-ru.org -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license at the end of this file -- ------------------------------------------------------------------------------ -- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $ with Ada.Finalization; with Encodings.Unicode; with XML_IO.Base_Readers; package XML_IO.Internals is subtype Unicode_Character is Encodings.Unicode.Unicode_Character; Invalid_Character : constant Unicode_Character := Encodings.Unicode.Empty_Buffer; type Character_Class is (' ', -- space, tab, lf, cr '!', '"', '#', '$', -- '&', ''', '-', '.', -- '/', '0', -- 0 .. 9 ';', '<', '=', '>', '?', 'A', -- A .. F a .. f 'X', -- '[', ']', 'x', 'z', -- yz Bad_Character, End_Of_Buffer ); function Get_Class (Char : in Unicode_Character) return Character_Class; type Internal_State is (In_Misc, In_PI, In_Content, In_Comment, In_Element, In_Empty_Element, In_Apostrophes, In_Quotes, In_CD_Start, In_CD); type Token is (Comment_Text_Token, -- ...--> Name_Token, PI_Text_Token, -- ...?> Value_Token, -- ..['"] Char_Data_Token, Entity_Reference_Token, -- &Name; Char_Reference_Token, -- &#...; CData_Token, -- ...]]> Space_Token, Start_Token, -- '<' PI_Token, -- '<?' Doctype_Token, -- '<!' Comment_Token, -- '<!--' Eq_Token, -- '=' Apostrophe_Token, -- ''' Quote_Token, -- '"' PI_End_Token, -- '?>' Empty_End_Token, -- '/>' End_Element_Token, -- '>' End_Token, -- '</' CD_Start_Token, -- '<![' Square_Token, -- '[' End_Of_Buffer, End_Of_File, Error); subtype Text_Token is Token range Comment_Text_Token .. CData_Token; generic with package Readers is new XML_IO.Base_Readers (<>); with procedure Decode (Buffer : in Readers.XML_String; Index : in out Positive; Free : in Positive; Encoding : in Encodings.Encoding; Char : out Unicode_Character); with function To_Encoding (Name : Readers.XML_String) return Encodings.Encoding; type XML_Unbounded is private; with function To_Unbounded_String (Source : in Readers.XML_String) return XML_Unbounded is <>; with function To_String (Source : in XML_Unbounded) return Readers.XML_String is <>; with function "=" (Left : in Readers.XML_String; Right : in XML_Unbounded) return Boolean is <>; with function "&" (Left : in XML_Unbounded; Right : in Readers.XML_String) return XML_Unbounded is <>; with function "&" (Left : in XML_Unbounded; Right : in XML_Unbounded) return XML_Unbounded is <>; with function To_XML_String (Source : in String) return XML_Unbounded is <>; Nil_Literal : in Readers.XML_String; -- ""; package Implementation is subtype XML_String is Readers.XML_String; type Token_Value is private; function Value (Buffer : in XML_String; Data : in Token_Value) return XML_String; type Reader is abstract new Readers.Reader with private; function More_Pieces (Parser : in Reader) return Boolean; function Piece_Kind (Parser : in Reader) return Piece_Kinds; procedure Next (Buffer : in out XML_String; Parser : in out Reader); function Encoding (Parser : in Reader) return Token_Value; function Encoding (Parser : in Reader) return Encodings.Encoding; function Standalone (Parser : in Reader) return Boolean; function Text (Parser : in Reader) return Token_Value; function Name (Parser : in Reader) return Token_Value; function Attribute_Count (Parser : in Reader) return List_Count; function Attribute_Name (Parser : in Reader; Index : in List_Index) return Token_Value; function Attribute_Value (Parser : in Reader; Index : in List_Index) return Token_Value; procedure Initialize (Buffer : in out XML_String; Parser : in out Reader); procedure Read (Parser : in out Reader; Buffer : in out XML_String; Last : out Natural) is abstract; private type Token_Value is record From : Natural; -- 0 if not started To : Natural; -- 0 if not finished Stored : XML_Unbounded; -- saved part end record; type Token_Values is array (List_Index range <>) of Token_Value; type Token_Values_Access is access all Token_Values; Embeded_Attr : constant := 8; type Piece_State (Kind : Piece_Kinds := End_Document) is record case Kind is when Start_Document => Encoding : Token_Value; Standalone : Boolean; when DTD | End_Document => null; when Start_Element | Entity_Reference | End_Element | Processing_Instruction | Attribute | Namespace => Name : Token_Value; case Kind is when Start_Element => Count : List_Count; Names : Token_Values (1 .. Embeded_Attr); Values : Token_Values (1 .. Embeded_Attr); when Processing_Instruction => PI_Text : Token_Value; when Attribute | Namespace => Value : Token_Value; when others => null; end case; when Comment | Characters | CDATA_Section => Text : Token_Value; end case; end record; type Token_Sub_State is range 0 .. 12; type Tokenizer_State is record Kind : Token; Value : Token_Value; Amp : Token_Value; X : Token_Sub_State; Prev : Character_Class; end record; type Input_State is record Index : Positive; Free : Positive; Prev : Positive; Encoding : Encodings.Encoding; end record; type Reader_State is new Ada.Finalization.Limited_Controlled with record Input : Input_State; Token : Tokenizer_State; In_State : Internal_State; Deep : Natural; Piece : Piece_State; Extra_Names : Token_Values_Access; Extra_Values : Token_Values_Access; end record; type Reader is abstract new Readers.Reader with record The : Reader_State; end record; end Implementation; end XML_IO.Internals; ------------------------------------------------------------------------------ -- Copyright (c) 2006-2013, Maxim Reznik -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the Maxim Reznik, IE nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------
-- ----------------------------------------------------------------------------- -- smk, the smart make -- © 2018 Lionel Draghi <lionel.draghi@free.fr> -- SPDX-License-Identifier: APSL-2.0 -- ----------------------------------------------------------------------------- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- http://www.apache.org/licenses/LICENSE-2.0 -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- ----------------------------------------------------------------------------- with Ada.Calendar; with Ada.Directories; use Ada.Directories; with Ada.Strings.Fixed; with Ada.Text_IO; use Ada.Text_IO; with Smk.Settings; with Smk.Run_Files; separate (Smk.Main) -- ----------------------------------------------------------------------------- procedure Analyze_Run (Source_Files : out Run_Files.File_Lists.Map; Target_Files : out Run_Files.File_Lists.Map) is Debug : constant Boolean := False; Prefix : constant String := ""; -- smk-main-analyze_run.adb "; Strace_Ouput : File_Type; -- procedure Classify_By_Time (Name : in String) is -- use type Ada.Calendar.Time; -- File_Time : constant Ada.Calendar.Time := Modification_Time (Name); -- -- Due to a limitation in the Modification_Time function -- -- (subsecond are ignored, Modification_Time returns -- -- Time_Of (Year, Month, Day, Hour, Minute, Second, 0.0); -- -- This cause the Modification_Time to be < to the -- -- command execution time, even when the file is -- -- modified after command execution start. -- -- To be clear : -- -- Exec start will be at second 14.45 -- -- File will be modified at second 14.57 -- -- Modification_Time will return 14 instead of 14.57 -- -- So the file will be considered as not modified by the -- -- command, and never classified as Target. -- -- To avoid this, I remove sub-seconds in both time, -- -- both will have the same time tag ending with second -- -- 14.00, and when equal, file will be considered a Target. -- -- Line_Nb : constant Integer := Integer (Ada.Text_IO.Line); -- TT_Image : constant String := Image (Previous_Run_Time); -- use Run_Files; -- -- begin -- delay (0.1); -- Fixme: -- if File_Time >= Previous_Run_Time then -- if not Target_Files.Contains (+Name) then -- Target_Files.Insert (+Name, File_Time); -- IO.Put_Debug_Line ("O : " & Image (File_Time, -- Include_Time_Fraction => True) & " >= " -- & TT_Image & " : " & Name, -- Debug => Debug, -- Prefix => Prefix, -- -- File => Settings.Strace_Outfile_Name, -- Line => Line_Nb); -- end if; -- -- else -- if not Source_Files.Contains (+Name) then -- Source_Files.Insert (+Name, File_Time); -- IO.Put_Debug_Line ("S : " & Image (File_Time, -- Include_Time_Fraction => True) & " < " -- & TT_Image & " : " & Name, -- Debug => Debug, -- Prefix => Prefix, -- -- File => Settings.Strace_Outfile_Name, -- Line => Line_Nb); -- end if; -- -- end if; -- end Classify_By_Time; -- -------------------------------------------------------------------------- procedure Classify_By_Cmd (Line : in String; Name : in String) is File_Time : constant Ada.Calendar.Time := Modification_Time (Name); use Ada.Strings.Fixed; use Run_Files; begin if Index (Line, "O_WRONLY") /= 0 or else Index (Line, "O_RDWR") /= 0 or else Index (Line, "write", From => 7) /= 0 or else Index (Line, "creat", From => 7) /= 0 -- Why seven? because the called system function name comes after -- the pid in strace output : -- 4372 openat(AT_FDCWD, "/tmp/ccHKHv8W.s", O_RDWR|O_CREAT etc. then -- it's a target if not Target_Files.Contains (+Name) then Target_Files.Insert (+Name, File_Time); IO.Put_Debug_Line ("T : " & IO.Image (File_Time) & " " & Name, Debug => Debug, Prefix => Prefix); end if; if Source_Files.Contains (+Name) then Source_Files.Delete (+Name); -- can't be both Target and Source end if; else -- it's a source if not Source_Files.Contains (+Name) and not Target_Files.Contains (+Name) then Source_Files.Insert (+Name, File_Time); IO.Put_Debug_Line ("S : " & IO.Image (File_Time) & " " & Name, Debug => Debug, Prefix => Prefix); end if; end if; end Classify_By_Cmd; begin -- -------------------------------------------------------------------------- IO.Put_Debug_Line ("Openning " & Strace_Outfile_Name, Debug, Prefix); Open (File => Strace_Ouput, Name => Strace_Outfile_Name, Mode => In_File); while not End_Of_File (Strace_Ouput) loop File_Filter : declare use Ada.Strings.Fixed; Line : constant String := Get_Line (Strace_Ouput); First : constant Natural := Index (Line, "<"); Last : constant Natural := Index (Line, ">"); begin -- IO.Put_Debug_Line ("Processing line: " & Line, Debug, Prefix); if Last > First then -- the line contains both '<' and '>'. declare File_Name : constant String := Line (First + 1 .. Last - 1); begin -- Let's ignore : -- 1. no more existing files after run, that is temporary file -- 2. special file, e. g. /dev/something, if Exists (File_Name) and then Kind (File_Name) /= Special_File then -- Classify_By_Time (File_Name); Classify_By_Cmd (Line => Line, Name => File_Name); end if; end; end if; end File_Filter; end loop; if Debug then Close (Strace_Ouput); else Delete (Strace_Ouput); end if; end Analyze_Run;
private with sdl.Video.Windows, sdl.Video.GL; package gel.Window.sdl -- -- Provides an SDL implementation of a window. -- is type Item is new gel.Window.item with private; type View is access all Item'Class; --------- --- Forge -- procedure define (Self : in View; Title : in String; Width : in Natural; Height : in Natural); overriding procedure destroy (Self : in out Item); package Forge is function new_Window (Title : in String; Width : in Natural; Height : in Natural) return Window.sdl.view; end Forge; -------------- --- Operations -- overriding procedure emit_Events (Self : in out Item); overriding procedure enable_GL (Self : in Item); overriding procedure disable_GL (Self : in Item); overriding procedure swap_GL (Self : in out Item); private type Item is new gel.Window.item with record window_Handle : standard.sdl.Video.Windows.Window; GL_Context : standard.sdl.Video.GL.Contexts; end record; end gel.Window.sdl;
with Ada.Integer_Text_IO; with Ada.Text_IO; with Ada.Containers.Vectors; with Ada.Strings.Bounded; package body Problem_22 is package IO renames Ada.Text_IO; package I_IO renames Ada.Integer_Text_IO; procedure Solve is package bs is new Ada.Strings.Bounded.Generic_Bounded_Length(12); use bs; package bs_vector is new Ada.Containers.Vectors(Positive, bs.Bounded_String); package bs_sort is new bs_vector.Generic_Sorting; input : IO.File_Type; names : bs_vector.Vector; total : Natural := 0; function Sum_Letters(bounded : in bs.Bounded_String) return Positive is sum : Natural := 0; function Letter_Value(ch : in Character) return Positive is begin return Character'Pos(ch) - Character'Pos('A') + 1; end Letter_Value; begin for index in 1 .. bs.Length(bounded) loop sum := sum + Letter_Value(bs.Element(bounded, index)); end loop; return sum; end; procedure Iterate_Names(Position : bs_vector.Cursor) is begin total := total + bs_vector.To_Index(Position) * Sum_Letters(bs_vector.Element(Position)); end; begin IO.Open(input, IO.In_File, "names.txt"); while not IO.End_Of_File(input) loop declare line : constant String := IO.Get_Line(input); begin names.Append(bs.To_Bounded_String(line)); end; end loop; bs_sort.Sort(names); bs_vector.Iterate(names, Iterate_Names'Access); I_IO.Put(total); IO.New_Line; end Solve; end Problem_22;
-- CC1301A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT DEFAULT GENERIC SUBPROGRAM PARAMETERS WORK CORRECTLY, -- INCLUDING OVERLOADED AND PREDEFINED OPERATOR_SYMBOLS, -- AND SUBPROGRAMS HIDDEN AT THE INSTANTIATION. -- BOTH KINDS OF DEFAULTS ARE TESTED, FOR BOTH PROCEDURES -- AND FUNCTIONS. -- DAT 8/14/81 -- JBG 5/5/83 -- JBG 8/3/83 WITH REPORT; USE REPORT; PROCEDURE CC1301A IS FUNCTION "-" (R, S : INTEGER) RETURN INTEGER; FUNCTION NEXT (X : INTEGER) RETURN INTEGER; PROCEDURE BUMP (X : IN OUT INTEGER); GENERIC WITH FUNCTION "*" (A, B : INTEGER) RETURN INTEGER IS "-"; WITH FUNCTION "+" (R, S: INTEGER) RETURN INTEGER IS STANDARD."+"; WITH FUNCTION "-" (A, B : INTEGER) RETURN INTEGER IS <> ; WITH FUNCTION NEXTO (Q : INTEGER) RETURN INTEGER IS NEXT ; WITH PROCEDURE BUMPO (A : IN OUT INTEGER) IS BUMP; WITH FUNCTION NEXT (Q : INTEGER) RETURN INTEGER IS <> ; WITH PROCEDURE BUMP (Q : IN OUT INTEGER) IS <> ; TYPE INTEGER IS RANGE <> ; WITH FUNCTION "*" (A , B : INTEGER) RETURN INTEGER IS <> ; WITH FUNCTION "-" (A, B : INTEGER) RETURN INTEGER IS <> ; WITH FUNCTION NEXT (Q : INTEGER) RETURN INTEGER IS <> ; WITH PROCEDURE BUMP (Z : IN OUT INTEGER) IS <> ; PACKAGE PKG IS SUBTYPE INT IS STANDARD.INTEGER; DIFF : INT := -999; END PKG; TYPE NEWINT IS NEW INTEGER RANGE -1000 .. 1000; FUNCTION PLUS (Q1, Q2 : INTEGER) RETURN INTEGER RENAMES "+"; FUNCTION "+" (X, Y : INTEGER) RETURN INTEGER IS BEGIN RETURN PLUS (X, PLUS (Y, -10)); -- (X + Y - 10) END "+"; FUNCTION "-" (R, S : INTEGER) RETURN INTEGER IS BEGIN RETURN - R + S; -- (-R + S - 10) END "-"; FUNCTION NEXT (X : INTEGER) RETURN INTEGER IS BEGIN RETURN X + 1; -- (X + 1 - 10) -- (X - 9) END NEXT; PROCEDURE BUMP (X : IN OUT INTEGER) IS BEGIN X := NEXT (X); -- (X := X - 9) END BUMP; PACKAGE BODY PKG IS W : INTEGER; WI : INT; BEGIN W := NEXT (INTEGER'(3) * 4 - 2); -- (W := (4 ** 3 - 2) - 1) -- (W := 61) BUMP (W); -- (W := 61 + 7) -- (W := 68) WI := NEXT (INT'(3) * 4 - 2 + NEXTO (0)); -- (3 * 4) => (3 - 4) => (-3 + 4 - 10) = -9 -- ((-9) - 2) => (2 + 2 - (-9) - 20) = -7 -- (-7 + (-9)) => -16 -- (WI := 7 - (-16)) => (WI := 23) BUMPO (WI); -- (WI := 23 - 9) (= 14) BUMP (WI); -- (WI := 14 - 9) (= 5) DIFF := STANDARD."-" (INT(W), WI); -- (DIFF := 68 - 5) (= 63) END PKG; FUNCTION "*" (Y, X : NEWINT) RETURN NEWINT IS BEGIN RETURN X ** INTEGER(Y); -- (X,Y) (Y ** X) END "*"; FUNCTION NEXT (Z : NEWINT) RETURN NEWINT IS BEGIN RETURN Z - 1; -- (Z - 1) END NEXT; PROCEDURE BUMP (ZZ : IN OUT NEWINT) IS BEGIN FAILED ("WRONG PROCEDURE CALLED"); END BUMP; BEGIN TEST ("CC1301A", "DEFAULT GENERIC SUBPROGRAM PARAMETERS"); DECLARE PROCEDURE BUMP (QQQ : IN OUT NEWINT) IS BEGIN QQQ := QQQ + 7; -- (QQQ + 7) END BUMP; FUNCTION NEXT (Q7 : INTEGER) RETURN INTEGER IS BEGIN RETURN Q7 - 17; -- (-Q7 + 17 - 10) -- (7 - Q7) END NEXT; FUNCTION "-" (Q3, Q4 : INTEGER) RETURN INTEGER IS BEGIN RETURN -Q3 + Q4 + Q4; -- (-Q3 + Q4 - 10 + Q4 - 10) = (Q4 + Q4 - Q3 - 20) END "-"; PACKAGE P1 IS NEW PKG (INTEGER => NEWINT); BEGIN IF P1.DIFF /= 63 THEN FAILED ("WRONG DEFAULT SUBPROGRAM PARAMETERS"); END IF; END; RESULT; END CC1301A;
-- The Village of Vampire by YT, このソースコードはNYSLです procedure Vampire.Villages.Load ( Name : in String; Village : in out Village_Type; Info_Only : in Boolean := False);
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008 - 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; with GNAT.Calendar.Time_IO; with Util.Streams.Buffered; with Util.Streams.Texts.TR; package body Util.Measures is ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S"; procedure Free is new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access); procedure Free is new Ada.Unchecked_Deallocation (Measure, Measure_Access); procedure Free is new Ada.Unchecked_Deallocation (String, String_Access); package Task_Context is new Ada.Task_Attributes (Measure_Set_Access, null); function Format (D : in Duration) return String; -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. function Format (D : in Duration; Unit : in Unit_Type) return String; -- ------------------------------ -- Disable collecting measures on the measure set. -- ------------------------------ procedure Disable (Measures : in out Measure_Set) is begin Measures.Enabled := False; end Disable; -- ------------------------------ -- Enable collecting measures on the measure set. -- ------------------------------ procedure Enable (Measures : in out Measure_Set) is begin Measures.Enabled := True; end Enable; -- ------------------------------ -- Set the per-thread measure set. -- ------------------------------ procedure Set_Current (Measures : in Measure_Set_Access) is begin Task_Context.Set_Value (Measures); end Set_Current; -- ------------------------------ -- Get the per-thread measure set. -- ------------------------------ function Get_Current return Measure_Set_Access is begin return Task_Context.Value; end Get_Current; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class) is procedure Dump_XML (Item : in Measure_Access); procedure Dump_XML (Item : in Measure_Access) is Total : constant String := Format (Item.Time); Time : constant String := Format (Item.Time / Item.Count); begin Stream.Write ("<time count="""); Stream.Write (Item.Count); Stream.Write (""" time="""); Stream.Write (Time (Time'First + 1 .. Time'Last)); if Item.Count > 1 then Stream.Write (""" total="""); Stream.Write (Total (Total'First + 1 .. Total'Last)); end if; Stream.Write (""" title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream, Content => Item.Name.all); Stream.Write ("""/>"); Stream.Write (ASCII.LF); end Dump_XML; Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin Measures.Data.Steal_Map (Buckets, TS, TE); Stream.Write ("<measures title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream, Content => Title); Stream.Write (""" start="""); Stream.Write (TS, ISO_DATE_TIME); Stream.Write (""" end="""); Stream.Write (TE, ISO_DATE_TIME); Stream.Write (""">"); if Buckets /= null then Stream.Write (ASCII.LF); begin for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Dump_XML (Node); Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; exception when others => Free (Buckets); raise; end; Free (Buckets); end if; Stream.Write ("</measures>"); end Write; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type) is Buffer : aliased Util.Streams.Buffered.Output_Buffer_Stream; Output : Util.Streams.Texts.Print_Stream; begin Buffer.Initialize (Size => 128 * 1024); Output.Initialize (To => Buffer'Access); Write (Measures, Title, Output); Output.Flush; Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer)); end Write; -- ------------------------------ -- Dump an XML result with the measures in a file. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => File, Name => Path); Write (Measures, Title, File); Ada.Text_IO.Close (File); exception when others => if Ada.Text_IO.Is_Open (File) then Ada.Text_IO.Close (File); end if; raise; end Write; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. -- ------------------------------ procedure Report (S : in out Stamp; Title : in String; Count : in Positive := 1) is Measures : constant Measure_Set_Access := Task_Context.Value; begin if Measures /= null and then Measures.Enabled then Report (Measures.all, S, Title, Count); end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. -- ------------------------------ procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String; Count : in Positive := 1) is use Ada.Calendar; begin if Measures.Enabled then declare D : constant Duration := Ada.Calendar.Clock - S.Start; begin Measures.Data.Add (Title, D, Count); end; S.Start := Ada.Calendar.Clock; end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. -- ------------------------------ procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds) is use Ada.Calendar; D : constant Duration := Ada.Calendar.Clock - S.Start; begin Ada.Text_IO.Put (File, Title); Ada.Text_IO.Put (File, Format (D, Unit)); S.Start := Ada.Calendar.Clock; end Report; protected body Measure_Data is -- ------------------------------ -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. -- ------------------------------ procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time) is begin Result := Buckets; Time_Start := Start; Start := Ada.Calendar.Clock; Time_End := Start; Buckets := null; end Steal_Map; -- ------------------------------ -- Add the measure -- ------------------------------ procedure Add (Title : in String; D : in Duration; Count : in Positive := 1) is use Ada.Containers; Pos : Hash_Type; Node : Measure_Access; begin if Buckets = null then Buckets := new Buckets_Type (0 .. 256); end if; Pos := Ada.Strings.Hash (Title) mod Buckets'Length; Node := Buckets (Pos); while Node /= null loop if Node.Name'Length = Title'Length and then Node.Name.all = Title then Node.Count := Node.Count + Count; Node.Time := Node.Time + D; return; end if; Node := Node.Next; end loop; Buckets (Pos) := new Measure '(Name => new String '(Title), Time => D, Count => Count, Next => Buckets (Pos)); end Add; end Measure_Data; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration) return String is begin if D < 0.000_001 then return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns"; elsif D < 0.001 then return Duration'Image (D * 1_000_000) (1 .. 6) & " us"; elsif D < 1.0 then return Duration'Image (D * 1_000) (1 .. 6) & " ms"; else return Duration'Image (D) (1 .. 6) & " s"; end if; end Format; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration; Unit : in Unit_Type) return String is begin case Unit is when Seconds => return Duration'Image (D); when Milliseconds => return Duration'Image (D * 1_000); when Microseconds => return Duration'Image (D * 1_000_000); when Nanoseconds => return Duration'Image (D * 1_000_000_000); end case; end Format; -- ------------------------------ -- Finalize the measures and release the storage. -- ------------------------------ overriding procedure Finalize (Measures : in out Measure_Set) is Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin -- When deleting the measure set, we have to release the buckets and measures -- that were allocated. We could call <b>Write</b> but we don't know where -- the measures have to be written. Measures.Data.Steal_Map (Buckets, TS, TE); if Buckets /= null then for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; Free (Buckets); end if; end Finalize; end Util.Measures;
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- A D A . C O N T A I N E R S . H E L P E R S -- -- -- -- S p e c -- -- -- -- Copyright (C) 2015-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- ------------------------------------------------------------------------------ with Ada.Finalization; with System.Atomic_Counters; package Ada.Containers.Helpers is pragma Annotate (CodePeer, Skip_Analysis); pragma Pure; -- Miscellaneous helpers shared among various containers package SAC renames System.Atomic_Counters; Count_Type_Last : constant := Count_Type'Last; -- Count_Type'Last as a universal_integer, so we can compare Index_Type -- values against this without type conversions that might overflow. type Tamper_Counts is record Busy : aliased SAC.Atomic_Unsigned := 0; Lock : aliased SAC.Atomic_Unsigned := 0; end record; -- Busy is positive when tampering with cursors is prohibited. Busy and -- Lock are both positive when tampering with elements is prohibited. type Tamper_Counts_Access is access all Tamper_Counts; for Tamper_Counts_Access'Storage_Size use 0; generic package Generic_Implementation is -- Generic package used in the implementation of containers. -- This needs to be generic so that the 'Enabled attribute will return -- the value that is relevant at the point where a container generic is -- instantiated. For example: -- -- pragma Suppress (Container_Checks); -- package My_Vectors is new Ada.Containers.Vectors (...); -- -- should suppress all container-related checks within the instance -- My_Vectors. -- Shorthands for "checks enabled" and "tampering checks enabled". Note -- that suppressing either Container_Checks or Tampering_Check disables -- tampering checks. Note that this code needs to be in a generic -- package, because we want to take account of check suppressions at the -- instance. We use these flags, along with pragma Inline, to ensure -- that the compiler can optimize away the checks, as well as the -- tampering check machinery, when checks are suppressed. Checks : constant Boolean := Container_Checks'Enabled; T_Check : constant Boolean := Container_Checks'Enabled and Tampering_Check'Enabled; -- Reference_Control_Type is used as a component of reference types, to -- prohibit tampering with elements so long as references exist. type Reference_Control_Type is new Finalization.Controlled with record T_Counts : Tamper_Counts_Access; end record with Disable_Controlled => not T_Check; overriding procedure Adjust (Control : in out Reference_Control_Type); pragma Inline (Adjust); overriding procedure Finalize (Control : in out Reference_Control_Type); pragma Inline (Finalize); procedure Zero_Counts (T_Counts : out Tamper_Counts); pragma Inline (Zero_Counts); -- Set Busy and Lock to zero procedure Busy (T_Counts : in out Tamper_Counts); pragma Inline (Busy); -- Prohibit tampering with cursors procedure Unbusy (T_Counts : in out Tamper_Counts); pragma Inline (Unbusy); -- Allow tampering with cursors procedure Lock (T_Counts : in out Tamper_Counts); pragma Inline (Lock); -- Prohibit tampering with elements procedure Unlock (T_Counts : in out Tamper_Counts); pragma Inline (Unlock); -- Allow tampering with elements procedure TC_Check (T_Counts : Tamper_Counts); pragma Inline (TC_Check); -- Tampering-with-cursors check procedure TE_Check (T_Counts : Tamper_Counts); pragma Inline (TE_Check); -- Tampering-with-elements check ----------------- -- RAII Types -- ----------------- -- Initialize of With_Busy increments the Busy count, and Finalize -- decrements it. Thus, to prohibit tampering with elements within a -- given scope, declare an object of type With_Busy. The Busy count -- will be correctly decremented in case of exception or abort. -- With_Lock is the same as With_Busy, except it increments/decrements -- BOTH Busy and Lock, thus prohibiting tampering with cursors. type With_Busy (T_Counts : not null access Tamper_Counts) is new Finalization.Limited_Controlled with null record with Disable_Controlled => not T_Check; overriding procedure Initialize (Busy : in out With_Busy); overriding procedure Finalize (Busy : in out With_Busy); type With_Lock (T_Counts : not null access Tamper_Counts) is new Finalization.Limited_Controlled with null record with Disable_Controlled => not T_Check; overriding procedure Initialize (Lock : in out With_Lock); overriding procedure Finalize (Lock : in out With_Lock); -- Variables of type With_Busy and With_Lock are declared only for the -- effects of Initialize and Finalize, so they are not referenced; -- disable warnings about that. Note that all variables of these types -- have names starting with "Busy" or "Lock". These pragmas need to be -- present wherever these types are used. pragma Warnings (Off, "variable ""Busy*"" is not referenced"); pragma Warnings (Off, "variable ""Lock*"" is not referenced"); end Generic_Implementation; end Ada.Containers.Helpers;
----------------------------------------------------------- -- This program asks the user to enter a character, -- preferably a 'c' or a 't'. The resultant behavior -- (conditional or timed) depends on the character entered -- and the time it is entered. -- Taken from http://www.cs.uni.edu//~mccormic/AdaEssentials/select_statement.htm ----------------------------------------------------------- with Text_IO; use Text_IO; procedure IO_Test2 is Ch : Character; begin -- Caller executable part Put_Line("Enter c or t (Conditional or Timed)"); Get(Ch); if Ch = 'c' then -- Conditional Entry Call null; elsif Ch = 't' then -- Timed Entry Call Put_Line("Timed call withdrawn"); else Put_Line("Invalid Input"); end if; end IO_Test2;
with Ada.Integer_Text_IO, Ada.Float_Text_IO; package body S_Expr is function First(This: List_Of_Data) return Data is begin return This.Values.First_Element; end First; function Rest(This: List_Of_Data) return List_Of_Data is List: List_Of_Data := This; begin List.Values.Delete_First; return List; end Rest; function Empty(This: List_Of_Data) return Boolean is begin return This.Values.Is_Empty; end Empty; procedure Print(This: Empty_Data; Indention: Natural) is begin Print_Line(Indention, ""); end Print; procedure Print(This: Int_Data; Indention: Natural) is begin Print_Line(Indention, Integer'Image(This.Value)); end Print; procedure Print(This: Flt_Data; Indention: Natural) is begin Print_Line(Indention, Float'Image(This.Value)); end Print; procedure Print(This: Str_Data; Indention: Natural) is begin if This.Quoted then Print_Line(Indention, """" & (+This.Value) & """"); else Print_Line(Indention, +This.Value); end if; end Print; procedure Print(This: List_Of_Data; Indention: Natural) is begin Print_Line(Indention, " ( "); for I in This.Values.First_Index .. This.Values.Last_Index loop This.Values.Element(I).Print(Indention + 1); end loop; Print_Line(Indention, " ) "); end Print; end S_Expr;
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; procedure Euler15 is function To_Integer(C : Character) return Integer is (Character'Pos(C) - Character'Pos('0')); function To_String(I : Integer) return String is S : String := Integer'Image(I); begin if I >= 0 then return S(2 .. S'Length); else return S(1 .. S'Length); end if; end; function Digit(A : Unbounded_String; D : Positive) return Natural is begin if D in 1 .. Length(A) then return To_Integer(Element(A, Length(A) - D + 1)); else return 0; end if; end Digit; function "*"(A : Unbounded_String; B : Natural) return Unbounded_String is R : Unbounded_String; Carry : Natural := 0; S : Natural; begin for D in 1 .. Length(A) loop S := Carry + Digit(A, D) * B; R := To_String(S mod 10) & R; Carry := S / 10; end loop; if Carry > 0 then R := To_String(Carry) & R; end if; return R; end "*"; function "/"(A : Unbounded_String; B : Natural) return Unbounded_String is R : Unbounded_String; Carry : Natural := 0; S : Natural; begin for D in 1 .. Length(A) loop S := Digit(A, Length(A) - D + 1) + Carry * 10; Carry := S mod B; S := S / B; if Length(R) > 0 or else S /= 0 then R := R & To_String(S); end if; end loop; return R; end "/"; P : Unbounded_String := To_Unbounded_String("1"); begin -- 40! / 20! / 20! -- = 40(39)..21 / 20! for I in 21 .. 40 loop P := P * I; Put_Line("*" & Integer'Image(I) & " => " & To_String(P)); end loop; for I in reverse 1 .. 20 loop P := P / I; Put_Line("/" & Integer'Image(I) & " => " & To_String(P)); end loop; Put_Line(To_String(P)); end Euler15;
----------------------------------------------------------------------- -- asf-converters-numbers -- Floating point number converters -- Copyright (C) 2010, 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; with ASF.Components; with ASF.Contexts.Faces; with ASF.Locales; private with Util.Locales; private with Ada.Text_IO.Editing; -- The `ASF.Converters.Numbers` provides a floating point number converter. -- It can be used to print floating point numbers in various formats. package ASF.Converters.Numbers is type Number_Converter is new Converter with private; type Number_Converter_Access is access all Number_Converter'Class; -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. overriding function To_String (Convert : in Number_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in EL.Objects.Object) return String; -- Convert the string into an object for the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. overriding function To_Object (Convert : in Number_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in String) return EL.Objects.Object; -- Set the picture that must be used for the conversion. procedure Set_Picture (Converter : in out Number_Converter; Picture : in String); -- Get the currency to be used from the resource bundle in the user's current locale. function Get_Currency (Converter : in Number_Converter; Bundle : in ASF.Locales.Bundle) return String; -- Get the separator to be used from the resource bundle in the user's current locale. function Get_Separator (Converter : in Number_Converter; Bundle : in ASF.Locales.Bundle) return Character; -- Get the radix mark to be used from the resource bundle in the user's current locale. function Get_Radix_Mark (Converter : in Number_Converter; Bundle : in ASF.Locales.Bundle) return Character; -- Get the fill character to be used from the resource bundle in the user's current locale. function Get_Fill (Converter : in Number_Converter; Bundle : in ASF.Locales.Bundle) return Character; private type Number_Converter is new Converter with record Picture : Ada.Text_IO.Editing.Picture; Locale : Util.Locales.Locale; Depend_On_Local : Boolean := False; end record; -- Get the locale that must be used to format the number. function Get_Locale (Convert : in Number_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; end ASF.Converters.Numbers;
----------------------------------------------------------------------- -- EL.Variables -- Default Variable Mapper -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Ada.Strings.Unbounded; private with Ada.Containers.Hashed_Maps; private with Ada.Strings.Unbounded.Hash; package EL.Variables.Default is -- Default Variable Mapper type Default_Variable_Mapper is new Variable_Mapper with private; overriding procedure Bind (Mapper : in out Default_Variable_Mapper; Name : in String; Value : in EL.Objects.Object); overriding function Get_Variable (Mapper : Default_Variable_Mapper; Name : Unbounded_String) return EL.Expressions.Expression; overriding procedure Set_Variable (Mapper : in out Default_Variable_Mapper; Name : in Unbounded_String; Value : in EL.Expressions.Expression); -- Set the next variable mapper that will be used to resolve a variable if -- the current variable mapper does not find a variable. procedure Set_Next_Variable_Mapper (Mapper : in out Default_Variable_Mapper; Next_Mapper : in Variable_Mapper_Access); private use type EL.Objects.Object; use type EL.Expressions.Expression; package Variable_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => EL.Expressions.Expression, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Default_Variable_Mapper is new Variable_Mapper with record Next_Mapper : Variable_Mapper_Access := null; Map : Variable_Maps.Map; end record; end EL.Variables.Default;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO; with Libadalang.Common; use Libadalang.Common; with Rejuvenation; use Rejuvenation; with Rejuvenation.Find_And_Replacer; use Rejuvenation.Find_And_Replacer; with Rejuvenation.Patterns; use Rejuvenation.Patterns; with Rejuvenation.Simple_Factory; use Rejuvenation.Simple_Factory; procedure Find_And_Replace_Tool is Find_Pattern : constant Pattern := Make_Pattern ("$S_F ($S_Arg1, $S_Arg2);", Call_Stmt_Rule); -- Swap arguments - of course resulting in illegal program ;-) Replace_Pattern : constant Pattern := Make_Pattern ("$S_F ($S_Arg2, $S_Arg1);", Call_Stmt_Rule); Project_Name : constant String := "C:\path\to\your.gpr"; UFiles : constant Unbounded_Strings.Vector := Get_Ada_Source_Files_From_Project (Project_Name); begin for UFile of UFiles loop declare File : constant String := To_String (UFile); begin if Find_And_Replace (File, Find_Pattern, Replace_Pattern) then Put_Line ("Changed - " & File); end if; end; end loop; end Find_And_Replace_Tool;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2019, Fabien Chouteau -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with LibRISCV.Instructions; use LibRISCV.Instructions; with LibRISCV.Sim.Log; package body LibRISCV.Sim.Hart is use type Sim.Memory_Bus.Access_Result; ----------- -- Reset -- ----------- procedure Reset (This : in out Instance) is begin This.Privilege := Machine; This.PC.U := 16#80000000#; This.GPR := (others => (U => 0, others => <>)); This.CSRs (CSR.mhartid).U := 0; This.CSRs (CSR.mtvec).U := 0; end Reset; ----------- -- Cycle -- ----------- procedure Cycle (This : in out Instance; Bus : in out Sim.Memory_Bus.Class) is Raw : Word; Fetch_Success : Boolean := False; begin if This.State = Debug_Halt then return; end if; This.Next_PC.U := This.PC.U + 4; This.Fetch (Bus, Raw, Fetch_Success); if Fetch_Success then This.Exec_Instruction (Raw, Bus); end if; This.PC := This.Next_PC; if This.State = Single_Step then This.Halt_Src := Single_Step; This.State := Debug_Halt; end if; end Cycle; ---------------------- -- Exec_Instruction -- ---------------------- procedure Exec_Instruction (This : in out Instance; Raw : Word; Bus : in out Sim.Memory_Bus.Class) is Insn : constant Instruction := Decode (Raw); begin if Sim.Log.Decode then Sim.Log.Put_Line (Img (Insn, This.PC.U)); end if; if Sim.Log.Exec then This.Dump; end if; case Insn.Kind is when Invalid => This.Exec_Invalid (Insn); when Insn_SLLI => This.Exec_SLLI (Insn); when Insn_SRLI => This.Exec_SRLI (Insn); when Insn_SRAI => This.Exec_SRAI (Insn); when Insn_ADD => This.Exec_ADD (Insn); when Insn_SUB => This.Exec_SUB (Insn); when Insn_SLL => This.Exec_SLL (Insn); when Insn_SLT => This.Exec_SLT (Insn); when Insn_SLTU => This.Exec_SLTU (Insn); when Insn_XOR => This.Exec_XOR (Insn); when Insn_SRL => This.Exec_SRL (Insn); when Insn_SRA => This.Exec_SRA (Insn); when Insn_OR => This.Exec_OR (Insn); when Insn_AND => This.Exec_AND (Insn); when Insn_BEQ => This.Exec_Branch (Insn); when Insn_BNE => This.Exec_Branch (Insn); when Insn_BLT => This.Exec_Branch (Insn); when Insn_BGE => This.Exec_Branch (Insn); when Insn_BLTU => This.Exec_Branch (Insn); when Insn_BGEU => This.Exec_Branch (Insn); when Insn_SB => This.Exec_SB (Insn, Bus); when Insn_SH => This.Exec_SH (Insn, Bus); when Insn_SW => This.Exec_SW (Insn, Bus); when Insn_JALR => This.Exec_JALR (Insn); when Insn_LB => This.Exec_LB (Insn, Bus); when Insn_LH => This.Exec_LH (Insn, Bus); when Insn_LW => This.Exec_LW (Insn, Bus); when Insn_LBU => This.Exec_LBU (Insn, Bus); when Insn_LHU => This.Exec_LHU (Insn, Bus); when Insn_ADDI => This.Exec_ADDI (Insn); when Insn_SLTI => This.Exec_SLTI (Insn); when Insn_SLTIU => This.Exec_SLTIU (Insn); when Insn_XORI => This.Exec_XORI (Insn); when Insn_ORI => This.Exec_ORI (Insn); when Insn_ANDI => This.Exec_ANDI (Insn); when Insn_FENCE => This.Exec_FENCE; when Insn_FENCE_I => This.Exec_FENCE_I; when Insn_ECALL => This.Exec_ECALL; when Insn_EBREAK => This.Exec_EBREAK; when Insn_CSRRW => This.Exec_CSRRW (Insn); when Insn_CSRRS => This.Exec_CSRRS (Insn); when Insn_CSRRC => This.Exec_CSRRC (Insn); when Insn_CSRRWI => This.Exec_CSRRWI (Insn); when Insn_CSRRSI => This.Exec_CSRRSI (Insn); when Insn_CSRRCI => This.Exec_CSRRCI (Insn); when Insn_LUI => This.Exec_LUI (Insn); when Insn_AUIPC => This.Exec_AUIPC (Insn); when Insn_JAL => This.Exec_JAL (Insn); when Insn_URET | Insn_SRET | Insn_MRET => This.Exec_XRET (Insn); end case; end Exec_Instruction; ----------- -- State -- ----------- function State (This : Instance) return State_Kind is (This.State); ----------------- -- Halt_Source -- ----------------- function Halt_Source (This : in out Instance) return Halt_Source_Kind is Res : constant Halt_Source_Kind := This.Halt_Src; begin This.Halt_Src := None; return Res; end Halt_Source; ---------- -- Halt -- ---------- procedure Halt (This : in out Instance) is begin This.State := Debug_Halt; end Halt; ------------ -- Resume -- ------------ procedure Resume (This : in out Instance) is begin This.State := Running; end Resume; ----------------- -- Single_Step -- ----------------- procedure Single_Step (This : in out Instance) is begin This.State := Single_Step; end Single_Step; -------------- -- Read_GPR -- -------------- function Read_GPR (This : Instance; Id : GPR_Id) return Register is (This.GPR (Id)); ------------- -- Read_PC -- ------------- function Read_PC (This : Instance) return Register is (This.PC); -------------- -- Write_PC -- -------------- procedure Write_PC (This : in out Instance; Addr : Register) is begin This.PC := Addr; end Write_PC; --------------------------- -- Set_Debugger_Attached -- --------------------------- procedure Set_Debugger_Attached (This : in out Instance; Attached : Boolean := True) is begin This.Debugger_Attached := Attached; end Set_Debugger_Attached; -------------------- -- Debug_Read_CSR -- -------------------- function Debug_Read_CSR (This : Instance; Id : CSR.Id) return Register is begin return This.CSRs (CSR.To_Name (Id)); end Debug_Read_CSR; -------------------- -- Add_Breakpoint -- -------------------- procedure Add_Breakpoint (This : in out Instance; Addr : Address; Success : out Boolean) is begin for Index in This.Breakpoints'Range loop if not This.Breakpoints (Index).Enabled then This.Breakpoints (Index).Enabled := True; This.Breakpoints (Index).Addr := Addr; Success := True; end if; end loop; Success := False; end Add_Breakpoint; ----------------------- -- Remove_Breakpoint -- ----------------------- procedure Remove_Breakpoint (This : in out Instance; Addr : Address; Success : out Boolean) is begin for Index in This.Breakpoints'Range loop if This.Breakpoints (Index).Enabled and then This.Breakpoints (Index).Addr = Addr then This.Breakpoints (Index).Enabled := False; Success := True; end if; end loop; Success := False; end Remove_Breakpoint; --------------- -- Write_GPR -- --------------- procedure Write_GPR (This : in out Instance; Id : GPR_Id; Value : Register) is begin if Id /= 0 then This.GPR (Id) := Value; end if; end Write_GPR; ---------- -- Dump -- ---------- procedure Dump (This : Instance) is begin Sim.Log.Put_Line ("PC: 0x" & Hex (This.PC.U)); for Id in GPR_Id loop Sim.Log.Put (Img (Id) & ": 0x" & Hex (This.GPR (Id).U)); if Id mod 5 = 4 then Sim.Log.New_Line; else Sim.Log.Put (" "); end if; end loop; Sim.Log.New_Line; end Dump; ----------- -- Fetch -- ----------- procedure Fetch (This : in out Instance; Bus : in out Sim.Memory_Bus.Class; Raw_Insn : out Word; Success : out Boolean) is Mem_Access : Sim.Memory_Bus.Access_Result; begin if (This.PC.U and 2#11#) /= 0 then This.Raise_Exception (Except.Instruction_Address_Misaligned, This.PC.U); Success := False; return; end if; for Index in This.Breakpoints'Range loop if This.Breakpoints (Index).Enabled and then This.Breakpoints (Index).Addr = This.PC.U then if This.Debugger_Attached then This.State := Debug_Halt; This.Halt_Src := Breakpoint; else This.Raise_Exception (Except.Breakpoint); end if; Success := True; return; end if; end loop; Bus.Load_W (This.PC.U, Raw_Insn, Mem_Access); if Mem_Access /= Sim.Memory_Bus.Success then This.Raise_Exception (Except.Instruction_Access_Fault, This.PC.U); Success := False; else Success := True; end if; end Fetch; -------------- -- Evaluate -- -------------- function Evaluate (Cond : Branch_Condition; R1, R2 : Register) return Boolean is begin case Cond is when Cond_EQ => return R1.U = R2.U; when Cond_NE => return R1.U /= R2.U; when Cond_LT => return R1.S < R2.S; when Cond_LTU => return R1.U < R2.U; when Cond_GE => return R1.S >= R2.S; when Cond_GEU => return R1.U >= R2.U; end case; end Evaluate; ----------------- -- Exec_Branch -- ----------------- procedure Exec_Branch (This : in out Instance; Insn : Instructions.Instruction) is Actual_Offset : Register; Cond : constant Branch_Condition := (case Insn.Kind is when Insn_BEQ => Cond_EQ, when Insn_BGE => Cond_GE, when Insn_BGEU => Cond_GEU, when Insn_BLT => Cond_LT, when Insn_BLTU => Cond_LTU, when Insn_BNE => Cond_NE, when others => raise Program_Error with "not a branch instruction"); begin if Evaluate (Cond, This.GPR (Insn.B_RS1), This.GPR (Insn.B_RS2)) then Actual_Offset := Sign_Extend (Insn.B_Imm); This.Next_PC.U := This.PC.U + Actual_Offset.U; end if; end Exec_Branch; --------------------- -- Raise_Exception -- --------------------- procedure Raise_Exception (This : in out Instance; E : Except.Kind; tval : U_Register := 0) is begin if Sim.Log.Except then Sim.Log.Put_Line ("Raise exception: " & E'Img & " tval: 0x" & Hex (tval)); Sim.Log.Put_Line (" MTVEC: : 0x" & Hex (This.CSRs (CSR.mtvec).U)); end if; This.Mcause := E; This.CSRs (CSR.mepc) := This.PC; This.Next_PC.U := This.CSRs (CSR.mtvec).U and (not 2#11#); This.CSRs (CSR.mtval).U := tval; end Raise_Exception; -------------- -- Read_CSR -- -------------- procedure Read_CSR (This : in out Instance; Data : out Register; Id : CSR.Id) is Name : constant CSR.Name := CSR.To_Name (Id); begin case Name is -- CSR implemted as simple read when CSR.mhartid | CSR.mtvec | CSR.stvec | CSR.satp | CSR.pmpaddr0 | CSR.pmpaddr1 | CSR.pmpcfg0 | CSR.pmpcfg1 | CSR.pmpcfg2 | CSR.pmpcfg3 | CSR.medeleg | CSR.mideleg | CSR.mie | CSR.mstatus | CSR.mepc | CSR.mtval | CSR.mscratch => Data := This.CSRs (Name); when CSR.misa => Data.U := 2#01_0000_00000000000000000100000000#; when CSR.mcause => Data.U := U_Register (This.Mcause'Enum_Rep); when others => raise Program_Error with "CSR read not implemented: " & Name'Img; end case; if Sim.Log.CSRs then Sim.Log.Put ("Read CSR: " & CSR.Img (Id) & " (0x" & CSR.Hex (Id)); Sim.Log.Put_Line (") Data: 0x" & Hex (Data.U)); end if; end Read_CSR; --------------- -- Write_CSR -- --------------- procedure Write_CSR (This : in out Instance; Data : Register; Id : CSR.Id) is Name : constant CSR.Name := CSR.To_Name (Id); begin if Sim.Log.CSRs then Sim.Log.Put ("Write CSR: " & CSR.Img (Id) & " (0x" & CSR.Hex (Id)); Sim.Log.Put_Line (") Data: 0x" & Hex (Data.U)); end if; case Name is -- CSR implemted as simple write, no checks on the data when CSR.mtvec | CSR.stvec | CSR.satp | CSR.pmpaddr0 | CSR.pmpaddr1 | CSR.pmpcfg0 | CSR.pmpcfg1 | CSR.pmpcfg2 | CSR.pmpcfg3 | CSR.medeleg | CSR.mideleg | CSR.mie | CSR.mstatus | CSR.mepc | CSR.mtval | CSR.mscratch => This.CSRs (Name) := Data; -- Ignore write when CSR.misa => null; when others => raise Program_Error with "CSR write not implemented: " & Name'Img; end case; end Write_CSR; ------------------ -- Exec_Invalid -- ------------------ procedure Exec_Invalid (This : in out Instance; Insn : Instructions.Instruction) is begin This.Raise_Exception (Except.Illegal_Instruction, U_Register (Insn.Raw)); end Exec_Invalid; --------------- -- Exec_SLLI -- --------------- procedure Exec_SLLI (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := Shift_Left (This.GPR (Insn.I_RS1).U, Natural (Insn.I_Imm and 2#1_1111#)); end if; end Exec_SLLI; --------------- -- Exec_SRLI -- --------------- procedure Exec_SRLI (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := Shift_Right (This.GPR (Insn.I_RS1).U, Natural (Insn.I_Imm and 2#1_1111#)); end if; end Exec_SRLI; --------------- -- Exec_SRAI -- --------------- procedure Exec_SRAI (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := Shift_Right_Arithmetic (This.GPR (Insn.I_RS1).U, Natural (Insn.I_Imm and 2#1_1111#)); end if; end Exec_SRAI; -------------- -- Exec_ADD -- -------------- procedure Exec_ADD (This : in out Instance; Insn : Instruction) is begin if Insn.R_RD /= 0 then This.GPR (Insn.R_RD).U := This.GPR (Insn.R_RS1).U + This.GPR (Insn.R_RS2).U; end if; end Exec_ADD; -------------- -- Exec_SUB -- -------------- procedure Exec_SUB (This : in out Instance; Insn : Instruction) is begin if Insn.R_RD /= 0 then This.GPR (Insn.R_RD).U := This.GPR (Insn.R_RS1).U - This.GPR (Insn.R_RS2).U; end if; end Exec_SUB; -------------- -- Exec_SLL -- -------------- procedure Exec_SLL (This : in out Instance; Insn : Instruction) is begin if Insn.R_RD /= 0 then This.GPR (Insn.R_RD).U := Shift_Left (This.GPR (Insn.R_RS1).U, Natural (This.GPR (Insn.R_RS2).U and 2#1_1111#)); end if; end Exec_SLL; -------------- -- Exec_SLT -- -------------- procedure Exec_SLT (This : in out Instance; Insn : Instruction) is begin if Insn.R_RD /= 0 then This.GPR (Insn.R_RD).S := (if This.GPR (Insn.R_RS1).S < This.GPR (Insn.R_RS2).S then 1 else 0); end if; end Exec_SLT; --------------- -- Exec_SLTU -- --------------- procedure Exec_SLTU (This : in out Instance; Insn : Instruction) is begin if Insn.R_RD /= 0 then This.GPR (Insn.R_RD).U := (if This.GPR (Insn.R_RS1).U < This.GPR (Insn.R_RS2).U then 1 else 0); end if; end Exec_SLTU; -------------- -- Exec_XOR -- -------------- procedure Exec_XOR (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.R_RD /= 0 then This.GPR (Insn.R_RD).U := This.GPR (Insn.R_RS1).U xor This.GPR (Insn.R_RS2).U; end if; end Exec_XOR; -------------- -- Exec_SRL -- -------------- procedure Exec_SRL (This : in out Instance; Insn : Instruction) is begin if Insn.R_RD /= 0 then This.GPR (Insn.R_RD).U := Shift_Right (This.GPR (Insn.R_RS1).U, Natural (This.GPR (Insn.R_RS2).U and 2#1_1111#)); end if; end Exec_SRL; -------------- -- Exec_SRA -- -------------- procedure Exec_SRA (This : in out Instance; Insn : Instruction) is begin if Insn.R_RD /= 0 then This.GPR (Insn.R_RD).U := Shift_Right_Arithmetic (This.GPR (Insn.R_RS1).U, Natural (This.GPR (Insn.R_RS2).U and 2#1_1111#)); end if; end Exec_SRA; ------------- -- Exec_OR -- ------------- procedure Exec_OR (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.R_RD /= 0 then This.GPR (Insn.R_RD).U := This.GPR (Insn.R_RS1).U or This.GPR (Insn.R_RS2).U; end if; end Exec_OR; -------------- -- Exec_AND -- -------------- procedure Exec_AND (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.R_RD /= 0 then This.GPR (Insn.R_RD).U := This.GPR (Insn.R_RS1).U and This.GPR (Insn.R_RS2).U; end if; end Exec_AND; ------------- -- Exec_SB -- ------------- procedure Exec_SB (This : in out Instance; Insn : Instructions.Instruction; Bus : in out Sim.Memory_Bus.Class) is Data : Byte; Res : Sim.Memory_Bus.Access_Result; Addr : Register; begin Data := Byte (This.GPR (Insn.S_RS2).U and 16#FF#); Addr.U := This.GPR (Insn.S_RS1).U + Sign_Extend (Insn.S_Imm).U; Bus.Store_B (Addr.U, Data, Res); if Res /= Sim.Memory_Bus.Success then This.Raise_Exception (Except.Store_AMO_Access_Fault, Addr.U); end if; end Exec_SB; ------------- -- Exec_SH -- ------------- procedure Exec_SH (This : in out Instance; Insn : Instructions.Instruction; Bus : in out Sim.Memory_Bus.Class) is Data : Halfword; Res : Sim.Memory_Bus.Access_Result; Addr : Register; begin Data := Halfword (This.GPR (Insn.S_RS2).U and 16#FF_FF#); Addr.U := This.GPR (Insn.S_RS1).U + Sign_Extend (Insn.S_Imm).U; if (Addr.U and 2#1#) /= 0 then This.Raise_Exception (Except.Store_AMO_Address_Misaligned, Addr.U); return; end if; Bus.Store_H (Addr.U, Data, Res); if Res /= Sim.Memory_Bus.Success then This.Raise_Exception (Except.Store_AMO_Access_Fault, Addr.U); end if; end Exec_SH; ------------- -- Exec_SW -- ------------- procedure Exec_SW (This : in out Instance; Insn : Instructions.Instruction; Bus : in out Sim.Memory_Bus.Class) is Data : Word; Res : Sim.Memory_Bus.Access_Result; Addr : Register; begin Data := Word (This.GPR (Insn.S_RS2).U and 16#FF_FF_FF_FF#); Addr.U := This.GPR (Insn.S_RS1).U + Sign_Extend (Insn.S_Imm).U; if (Addr.U and 2#11#) /= 0 then This.Raise_Exception (Except.Store_AMO_Address_Misaligned, Addr.U); return; end if; Bus.Store_W (Addr.U, Data, Res); if Res /= Sim.Memory_Bus.Success then This.Raise_Exception (Except.Store_AMO_Access_Fault, Addr.U); end if; end Exec_SW; ------------- -- Exec_LB -- ------------- procedure Exec_LB (This : in out Instance; Insn : Instructions.Instruction; Bus : Sim.Memory_Bus.Class) is Data : Byte; Res : Sim.Memory_Bus.Access_Result; Addr : Register; begin Addr.U := This.GPR (Insn.I_RS1).U + Sign_Extend (Insn.I_Imm).U; Bus.Load_B (Addr.U, Data, Res); if Res /= Sim.Memory_Bus.Success then This.Raise_Exception (Except.Load_Access_Fault, Addr.U); return; end if; if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := Sign_Extend (Data); end if; end Exec_LB; ------------- -- Exec_LH -- ------------- procedure Exec_LH (This : in out Instance; Insn : Instructions.Instruction; Bus : Sim.Memory_Bus.Class) is Data : Halfword; Res : Sim.Memory_Bus.Access_Result; Addr : Register; begin Addr.U := This.GPR (Insn.I_RS1).U + Sign_Extend (Insn.I_Imm).U; if (Addr.U and 2#1#) /= 0 then This.Raise_Exception (Except.Load_Address_Misaligned, Addr.U); return; end if; Bus.Load_H (Addr.U, Data, Res); if Res /= Sim.Memory_Bus.Success then This.Raise_Exception (Except.Load_Access_Fault, Addr.U); return; end if; if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := Sign_Extend (Data); end if; end Exec_LH; ------------- -- Exec_LW -- ------------- procedure Exec_LW (This : in out Instance; Insn : Instructions.Instruction; Bus : Sim.Memory_Bus.Class) is Data : Word; Res : Sim.Memory_Bus.Access_Result; Addr : Register; begin Addr.U := This.GPR (Insn.I_RS1).U + Sign_Extend (Insn.I_Imm).U; if (Addr.U and 2#11#) /= 0 then This.Raise_Exception (Except.Load_Address_Misaligned, Addr.U); return; end if; Bus.Load_W (Addr.U, Data, Res); if Res /= Sim.Memory_Bus.Success then This.Raise_Exception (Except.Load_Access_Fault, Addr.U); return; end if; if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := Sign_Extend (Data); end if; end Exec_LW; -------------- -- Exec_LBU -- -------------- procedure Exec_LBU (This : in out Instance; Insn : Instructions.Instruction; Bus : Sim.Memory_Bus.Class) is Data : Byte; Res : Sim.Memory_Bus.Access_Result; Addr : Register; begin Addr.U := This.GPR (Insn.I_RS1).U + Sign_Extend (Insn.I_Imm).U; Bus.Load_B (Addr.U, Data, Res); if Res /= Sim.Memory_Bus.Success then This.Raise_Exception (Except.Load_Access_Fault, Addr.U); return; end if; if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := U_Register (Data); end if; end Exec_LBU; -------------- -- Exec_LHU -- -------------- procedure Exec_LHU (This : in out Instance; Insn : Instructions.Instruction; Bus : Sim.Memory_Bus.Class) is Data : Halfword; Res : Sim.Memory_Bus.Access_Result; Addr : Register; begin Addr.U := This.GPR (Insn.I_RS1).U + Sign_Extend (Insn.I_Imm).U; if (Addr.U and 2#1#) /= 0 then This.Raise_Exception (Except.Load_Address_Misaligned, Addr.U); return; end if; Bus.Load_H (Addr.U, Data, Res); if Res /= Sim.Memory_Bus.Success then This.Raise_Exception (Except.Load_Access_Fault, Addr.U); end if; if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := U_Register (Data); end if; end Exec_LHU; --------------- -- Exec_ADDI -- --------------- procedure Exec_ADDI (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := This.GPR (Insn.I_RS1).U + Sign_Extend (Insn.I_Imm).U; end if; end Exec_ADDI; --------------- -- Exec_SLTI -- --------------- procedure Exec_SLTI (This : in out Instance; Insn : Instruction) is begin if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := (if This.GPR (Insn.I_RS1).S < Sign_Extend (Insn.I_Imm).S then 1 else 0); end if; end Exec_SLTI; ---------------- -- Exec_SLTIU -- ---------------- procedure Exec_SLTIU (This : in out Instance; Insn : Instruction) is begin if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := (if This.GPR (Insn.I_RS1).U < Sign_Extend (Insn.I_Imm).U then 1 else 0); end if; end Exec_SLTIU; --------------- -- Exec_XORI -- --------------- procedure Exec_XORI (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := This.GPR (Insn.I_RS1).U xor Sign_Extend (Insn.I_Imm).U; end if; end Exec_XORI; -------------- -- Exec_ORI -- -------------- procedure Exec_ORI (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := This.GPR (Insn.I_RS1).U or Sign_Extend (Insn.I_Imm).U; end if; end Exec_ORI; --------------- -- Exec_ANDI -- --------------- procedure Exec_ANDI (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := This.GPR (Insn.I_RS1).U and Sign_Extend (Insn.I_Imm).U; end if; end Exec_ANDI; ---------------- -- Exec_FENCE -- ---------------- procedure Exec_FENCE (This : in out Instance) is begin null; -- Nothing to do here for our simple simulator end Exec_FENCE; ------------------ -- Exec_FENCE_I -- ------------------ procedure Exec_FENCE_I (This : in out Instance) is begin null; -- Nothing to do here for our simple simulator end Exec_FENCE_I; ---------------- -- Exec_ECALL -- ---------------- procedure Exec_ECALL (This : in out Instance) is begin This.Raise_Exception ((case This.Privilege is when User => Except.Environment_Call_From_U_mode, when Machine => Except.Environment_Call_From_M_mode )); end Exec_ECALL; ----------------- -- Exec_EBREAK -- ----------------- procedure Exec_EBREAK (This : in out Instance) is begin if This.Debugger_Attached then This.State := Debug_Halt; This.Halt_Src := Breakpoint; This.Next_PC := This.PC; else This.Raise_Exception (Except.Breakpoint); end if; end Exec_EBREAK; ---------------- -- Exec_CSRRW -- ---------------- procedure Exec_CSRRW (This : in out Instance; Insn : Instructions.Instruction) is Id : constant CSR.Id := CSR.Id (Insn.I_Imm); Data : Register; begin if Insn.I_RD /= 0 then -- Read but not store in the GPR yet, as this GPR can also be the -- source. This.Read_CSR (Data, Id); end if; This.Write_CSR (This.GPR (Insn.I_RS1), Id); if Insn.I_RD /= 0 then This.GPR (Insn.I_RD) := Data; end if; end Exec_CSRRW; ---------------- -- Exec_CSRRS -- ---------------- procedure Exec_CSRRS (This : in out Instance; Insn : Instructions.Instruction) is Id : constant CSR.Id := CSR.Id (Insn.I_Imm); R_Data : Register; W_Data : Register; begin This.Read_CSR (R_Data, Id); if Insn.I_RS1 /= 0 then W_Data.U := R_Data.U or This.GPR (Insn.I_RS1).U; This.Write_CSR (W_Data, Id); end if; if Insn.I_RD /= 0 then This.GPR (Insn.I_RD) := R_Data; end if; end Exec_CSRRS; ---------------- -- Exec_CSRRC -- ---------------- procedure Exec_CSRRC (This : in out Instance; Insn : Instructions.Instruction) is Id : constant CSR.Id := CSR.Id (Insn.I_Imm); R_Data : Register; W_Data : Register; begin This.Read_CSR (R_Data, Id); if Insn.I_RS1 /= 0 then W_Data.U := R_Data.U and (not This.GPR (Insn.I_RS1).U); This.Write_CSR (W_Data, Id); end if; if Insn.I_RD /= 0 then This.GPR (Insn.I_RD) := R_Data; end if; end Exec_CSRRC; ----------------- -- Exec_CSRRWI -- ----------------- procedure Exec_CSRRWI (This : in out Instance; Insn : Instructions.Instruction) is Id : constant CSR.Id := CSR.Id (Insn.I_Imm); Data : Register; begin if Insn.I_RD /= 0 then This.Read_CSR (Data, Id); This.GPR (Insn.I_RD) := Data; end if; Data.U := U_Register (Insn.I_RS1); This.Write_CSR (Data, Id); end Exec_CSRRWI; ----------------- -- Exec_CSRRSI -- ----------------- procedure Exec_CSRRSI (This : in out Instance; Insn : Instructions.Instruction) is Id : constant CSR.Id := CSR.Id (Insn.I_Imm); R_Data : Register; W_Data : Register; begin This.Read_CSR (R_Data, Id); if Insn.I_RS1 /= 0 then W_Data.U := R_Data.U or U_Register (Insn.I_RS1); This.Write_CSR (W_Data, Id); end if; if Insn.I_RD /= 0 then This.GPR (Insn.I_RD) := R_Data; end if; end Exec_CSRRSI; ----------------- -- Exec_CSRRCI -- ----------------- procedure Exec_CSRRCI (This : in out Instance; Insn : Instructions.Instruction) is Id : constant CSR.Id := CSR.Id (Insn.I_Imm); R_Data : Register; W_Data : Register; begin This.Read_CSR (R_Data, Id); if Insn.I_RS1 /= 0 then W_Data.U := R_Data.U and (not U_Register (Insn.I_RS1)); This.Write_CSR (W_Data, Id); end if; if Insn.I_RD /= 0 then This.GPR (Insn.I_RD) := R_Data; end if; end Exec_CSRRCI; -------------- -- Exec_LUI -- -------------- procedure Exec_LUI (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.U_RD /= 0 then This.GPR (Insn.U_RD).U := U_Register (Insn.U_Imm); end if; end Exec_LUI; ---------------- -- Exec_AUIPC -- ---------------- procedure Exec_AUIPC (This : in out Instance; Insn : Instructions.Instruction) is begin if Insn.U_RD /= 0 then This.GPR (Insn.U_RD).U := This.PC.U + U_Register (Insn.U_Imm); end if; end Exec_AUIPC; -------------- -- Exec_JAL -- -------------- procedure Exec_JAL (This : in out Instance; Insn : Instructions.Instruction) is Imm : constant Register := Sign_Extend (Insn.J_Imm); begin if Insn.J_RD /= 0 then This.GPR (Insn.J_RD).U := This.PC.U + 4; end if; This.Next_PC.U := This.PC.U + Imm.U; end Exec_JAL; --------------- -- Exec_JALR -- --------------- procedure Exec_JALR (This : in out Instance; Insn : Instructions.Instruction) is Imm : constant Register := Sign_Extend (Insn.I_Imm); LR : constant U_Register := This.PC.U + 4; begin This.Next_PC.U := This.GPR (Insn.I_RS1).U + Imm.U; This.Next_PC.U := This.Next_PC.U and (not 1); if Insn.I_RD /= 0 then This.GPR (Insn.I_RD).U := LR; end if; end Exec_JALR; --------------- -- Exec_XRET -- --------------- procedure Exec_XRET (This : in out Instance; Insn : Instructions.Instruction) is pragma Unreferenced (Insn); begin -- TODO: change priviledge mode This.Next_PC.U := This.CSRs (CSR.mepc).U; end Exec_XRET; end LibRISCV.Sim.Hart;
private with GMP_c.mpz_t; package GMP.discrete -- -- -- is type Integer is private; -- forge -- function to_Integer return Integer; function to_Integer (From : long_long_Integer) return Integer; function to_Integer (From : discrete.Integer) return Integer; procedure define (Self : in out Integer); procedure define (Self : in out Integer; Value : in long_long_Integer); procedure define (Self : in out Integer; Value : in discrete.Integer); procedure destroy (Self : in out Integer); -- attributes -- function Value (Self : in Integer) return long_long_Integer; function Image (Self : in Integer) return String; function hex_Image (Self : in Integer) return String; function oct_Image (Self : in Integer) return String; -- operations -- function "=" (Left, Right : in Integer) return Boolean; function "<" (Left, Right : in Integer) return Boolean; function "+" (Left, Right : in Integer) return Integer; function "-" (Left, Right : in Integer) return Integer; function "*" (Left, Right : in Integer) return Integer; function "/" (Left, Right : in Integer) return Integer; function "**" (Left : in Integer; Right : in long_long_Integer) return Integer; function "or" (Left, Right : in Integer) return Integer; function "xor" (Left, Right : in Integer) return Integer; function "and" (Left, Right : in Integer) return Integer; function "-" (Self : in Integer) return Integer; function "not" (Self : in Integer) return Integer; private type Integer is record Lean : GMP_c.mpz_t.Pointer; end record; end GMP.Discrete;
with Neural.Set; with Neural.Net; -- with opengl.IO; -- with Math; -- with lace.text.Cursor; with lace.Environ; with ada.Strings.Fixed; with ada.Text_Io; package body linear_Net is use Math, Ada.Text_IO; use type -- opengl.Real, neural.signal; -- input_neuron_Count : constant := 1; subtype nn_Real is neural.signal; -- definition -- procedure define (Self : out Item; Name : in String) is use Neural.Net, Neural, lace.Environ; -- the_Environ : lace.Environ.item; net_Name : String := Name & ".net"; begin lace.Environ.verify_Folder (net_Name); define (neural.Net.Item (Self), net_Name); -- define base class exception when No_Net_Error => Put_Line ("No valid '" & Name & "' net found ... creating new net."); Self.define (Name & ".net", num_Input_Neurons => 1, num_Hidden_Neurons => 25, num_Output_Neurons => 1); end define; function Pattern_For (Self : in Item; the_Input : in math.Real; Inputs_Only : in Boolean := False; the_Output : in math.Real := 0.0 ) return Neural.Pattern is use Neural; -- opengl, opengl.IO; the_Inputs : Signals (1 .. self.input_Count); the_Outputs : Signals (1 .. self.output_Count); begin the_Inputs (1) := nn_Real (the_Input); if not Inputs_only then the_Outputs (1) := Signal (the_Output); end if; return (Inputs => new Signals'(the_Inputs), Outputs => new Signals'(the_Outputs)); end Pattern_For; function Output_for (Self : access Item; the_Input : in math.Real) return math.Real is the_Pattern : neural.Pattern := Pattern_for (Self.all, the_Input, inputs_only => True); the_response : neural.Signals := self.Response (the_Pattern); begin return math.Real (the_Response (1)); end Output_for; end linear_Net;
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- Copyright (C) 2012-2016, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- 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. -- -- -- ------------------------------------------------------------------------------ pragma Ada_2012; -- To work around pre-commit check? pragma Restrictions (No_Elaboration_Code); pragma Suppress (All_Checks); -- This initialization procedure mainly initializes the PLLs and -- all derived clocks. with Ada.Unchecked_Conversion; with Interfaces.Bit_Types; use Interfaces, Interfaces.Bit_Types; with Interfaces.STM32.FLASH; use Interfaces.STM32.FLASH; with Interfaces.STM32.PWR; use Interfaces.STM32.PWR; with Interfaces.STM32.RCC; use Interfaces.STM32.RCC; with System.BB.Parameters; use System.BB.Parameters; with System.BB.MCU_Parameters; with System.STM32; use System.STM32; procedure Setup_Pll is procedure Initialize_Clocks; procedure Reset_Clocks; ------------------------------ -- Clock Tree Configuration -- ------------------------------ HSE_Enabled : constant Boolean := True; -- use high-speed ext. clock HSE_Bypass : constant Boolean := False; -- don't bypass ext. resonator LSI_Enabled : constant Boolean := True; -- use low-speed internal clock Activate_PLL : constant Boolean := True; Activate_Overdrive : constant Boolean := True; Activate_PLLI2S : constant Boolean := False; pragma Assert ((if Activate_PLL then HSE_Enabled), "PLL only supported with external clock"); pragma Assert (not Activate_PLLI2S, "not yet implemented"); ----------------------- -- Initialize_Clocks -- ----------------------- procedure Initialize_Clocks is ------------------------------- -- Compute Clock Frequencies -- ------------------------------- PLLP_Value : constant PLLP_Range := 2; -- Arbitrary fixed to a convenient value PLLCLKIN : constant Integer := 1_000_000; PLLM_Value : constant Integer := HSE_Clock / PLLCLKIN; -- First divider M is set to produce a 1Mhz clock PLLN_Value : constant Integer := (PLLP_Value * Clock_Frequency) / PLLCLKIN; -- Compute N to to generate the required frequency PLLVC0 : constant Integer := PLLCLKIN * PLLN_Value; PLLCLKOUT : constant Integer := PLLVC0 / PLLP_Value; PLLQ_Value : constant PLLQ_Range := 7; -- Arbitrary fixed PLLM : constant UInt6 := UInt6 (PLLM_Value); PLLN : constant UInt9 := UInt9 (PLLN_Value); PLLP : constant UInt2 := UInt2 (PLLP_Value / 2 - 1); PLLQ : constant UInt4 := UInt4 (PLLQ_Value); SW : constant SYSCLK_Source := (if Activate_PLL then SYSCLK_SRC_PLL else (if HSE_Enabled then SYSCLK_SRC_HSE else SYSCLK_SRC_HSI)); SW_Value : constant CFGR_SW_Field := SYSCLK_Source'Enum_Rep (SW); SYSCLK : constant Integer := (if Activate_PLL then PLLCLKOUT else HSICLK); HCLK : constant Integer := (if not AHB_PRE.Enabled then SYSCLK else (case AHB_PRE.Value is when DIV2 => SYSCLK / 2, when DIV4 => SYSCLK / 4, when DIV8 => SYSCLK / 8, when DIV16 => SYSCLK / 16, when DIV64 => SYSCLK / 64, when DIV128 => SYSCLK / 128, when DIV256 => SYSCLK / 256, when DIV512 => SYSCLK / 512)); PCLK1 : constant Integer := (if not APB1_PRE.Enabled then HCLK else (case APB1_PRE.Value is when DIV2 => HCLK / 2, when DIV4 => HCLK / 4, when DIV8 => HCLK / 8, when DIV16 => HCLK / 16)); PCLK2 : constant Integer := (if not APB2_PRE.Enabled then HCLK else (case APB2_PRE.Value is when DIV2 => HCLK / 2, when DIV4 => HCLK / 4, when DIV8 => HCLK / 8, when DIV16 => HCLK / 16)); function To_AHB is new Ada.Unchecked_Conversion (AHB_Prescaler, UInt4); function To_APB is new Ada.Unchecked_Conversion (APB_Prescaler, UInt3); begin -- Check configuration pragma Warnings (Off, "condition is always False"); if PLLVC0 not in PLLVC0_Range or else PLLCLKOUT not in PLLOUT_Range then raise Program_Error with "Invalid clock configuration"; end if; if SYSCLK /= Clock_Frequency then raise Program_Error with "Cannot generate requested clock"; end if; if HCLK not in HCLK_Range or else PCLK1 not in PCLK1_Range or else PCLK2 not in PCLK2_Range then raise Program_Error with "Invalid AHB/APB prescalers configuration"; end if; pragma Warnings (On, "condition is always False"); -- PWR clock enable RCC_Periph.APB1ENR.PWREN := 1; -- Reset the power interface RCC_Periph.APB1RSTR.PWRRST := 1; RCC_Periph.APB1RSTR.PWRRST := 0; -- PWR initialization -- Select higher supply power for stable operation at max. freq. -- See table "General operating conditions" of the STM32 datasheets -- to obtain the maximal operating frequency depending on the power -- scaling mode and the over-drive mode System.BB.MCU_Parameters.PWR_Initialize; if not HSE_Enabled then -- Setup internal clock and wait for HSI stabilisation. RCC_Periph.CR.HSION := 1; loop exit when RCC_Periph.CR.HSIRDY = 1; end loop; else -- Configure high-speed external clock, if enabled RCC_Periph.CR.HSEON := 1; RCC_Periph.CR.HSEBYP := (if HSE_Bypass then 1 else 0); loop exit when RCC_Periph.CR.HSERDY = 1; end loop; end if; -- Configure low-speed internal clock if enabled if LSI_Enabled then RCC_Periph.CSR.LSION := 1; loop exit when RCC_Periph.CSR.LSIRDY = 1; end loop; end if; -- Activate PLL if enabled if Activate_PLL then -- Disable the main PLL before configuring it RCC_Periph.CR.PLLON := 0; -- Configure the PLL clock source, multiplication and division -- factors RCC_Periph.PLLCFGR := (PLLM => PLLM, PLLN => PLLN, PLLP => PLLP, PLLQ => PLLQ, PLLSRC => (if HSE_Enabled then PLL_Source'Enum_Rep (PLL_SRC_HSE) else PLL_Source'Enum_Rep (PLL_SRC_HSI)), others => <>); RCC_Periph.CR.PLLON := 1; loop exit when RCC_Periph.CR.PLLRDY = 1; end loop; end if; -- Configure OverDrive mode if Activate_Overdrive then System.BB.MCU_Parameters.PWR_Overdrive_Enable; end if; -- Configure flash -- Must be done before increasing the frequency, otherwise the CPU -- won't be able to fetch new instructions. FLASH_Periph.ACR.ICEN := 0; FLASH_Periph.ACR.DCEN := 0; FLASH_Periph.ACR.ICRST := 1; FLASH_Periph.ACR.DCRST := 1; FLASH_Periph.ACR := (LATENCY => 5, ICEN => 1, DCEN => 1, PRFTEN => 1, others => <>); -- Configure derived clocks RCC_Periph.CFGR := (SW => SW_Value, HPRE => To_AHB (AHB_PRE), PPRE => (As_Array => True, Arr => (1 => To_APB (APB1_PRE), 2 => To_APB (APB2_PRE))), RTCPRE => 16#0#, I2SSRC => I2S_Clock_Selection'Enum_Rep (I2SSEL_PLL), MCO1 => MC01_Clock_Selection'Enum_Rep (MC01SEL_HSI), MCO1PRE => MC0x_Prescaler'Enum_Rep (MC0xPRE_DIV1), MCO2 => MC02_Clock_Selection'Enum_Rep (MC02SEL_SYSCLK), MCO2PRE => MC0x_Prescaler'Enum_Rep (MC0xPRE_DIV5), others => <>); if Activate_PLL then loop exit when RCC_Periph.CFGR.SWS = SYSCLK_Source'Enum_Rep (SYSCLK_SRC_PLL); end loop; -- Wait until voltage supply scaling has completed loop exit when System.BB.MCU_Parameters.Is_PWR_Stabilized; end loop; end if; end Initialize_Clocks; ------------------ -- Reset_Clocks -- ------------------ procedure Reset_Clocks is begin -- Switch on high speed internal clock RCC_Periph.CR.HSION := 1; -- Reset CFGR regiser RCC_Periph.CFGR := (others => <>); -- Reset HSEON, CSSON and PLLON bits RCC_Periph.CR.HSEON := 0; RCC_Periph.CR.CSSON := 0; RCC_Periph.CR.PLLON := 0; -- Reset PLL configuration register RCC_Periph.PLLCFGR := (others => <>); -- Reset HSE bypass bit RCC_Periph.CR.HSEBYP := 0; -- Disable all interrupts RCC_Periph.CIR := (others => <>); end Reset_Clocks; begin Reset_Clocks; Initialize_Clocks; end Setup_Pll;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S T Y L E S W -- -- -- -- B o d y -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Hostparm; use Hostparm; with Opt; use Opt; package body Stylesw is ------------------------------- -- Reset_Style_Check_Options -- ------------------------------- procedure Reset_Style_Check_Options is begin Style_Check_Indentation := 0; Style_Check_Attribute_Casing := False; Style_Check_Blanks_At_End := False; Style_Check_Comments := False; Style_Check_End_Labels := False; Style_Check_Form_Feeds := False; Style_Check_Horizontal_Tabs := False; Style_Check_If_Then_Layout := False; Style_Check_Keyword_Casing := False; Style_Check_Layout := False; Style_Check_Max_Line_Length := False; Style_Check_Pragma_Casing := False; Style_Check_References := False; Style_Check_Specs := False; Style_Check_Standard := False; Style_Check_Subprogram_Order := False; Style_Check_Tokens := False; end Reset_Style_Check_Options; ------------------------------ -- Save_Style_Check_Options -- ------------------------------ procedure Save_Style_Check_Options (Options : out Style_Check_Options) is P : Natural := 0; J : Natural; procedure Add (C : Character; S : Boolean); -- Add given character C to string if switch S is true procedure Add (C : Character; S : Boolean) is begin if S then P := P + 1; Options (P) := C; end if; end Add; -- Start of processing for Save_Style_Check_Options begin for K in Options'Range loop Options (K) := ' '; end loop; Add (Character'Val (Style_Check_Indentation + Character'Pos ('0')), Style_Check_Indentation /= 0); Add ('a', Style_Check_Attribute_Casing); Add ('b', Style_Check_Blanks_At_End); Add ('c', Style_Check_Comments); Add ('e', Style_Check_End_Labels); Add ('f', Style_Check_Form_Feeds); Add ('h', Style_Check_Horizontal_Tabs); Add ('i', Style_Check_If_Then_Layout); Add ('k', Style_Check_Keyword_Casing); Add ('l', Style_Check_Layout); Add ('m', Style_Check_Max_Line_Length); Add ('n', Style_Check_Standard); Add ('o', Style_Check_Subprogram_Order); Add ('p', Style_Check_Pragma_Casing); Add ('r', Style_Check_References); Add ('s', Style_Check_Specs); Add ('t', Style_Check_Tokens); if Style_Check_Max_Line_Length then P := Options'Last; J := Natural (Style_Max_Line_Length); loop Options (P) := Character'Val (J mod 10 + Character'Pos ('0')); P := P - 1; J := J / 10; exit when J = 0; end loop; Options (P) := 'M'; end if; end Save_Style_Check_Options; ------------------------------------- -- Set_Default_Style_Check_Options -- ------------------------------------- procedure Set_Default_Style_Check_Options is begin Reset_Style_Check_Options; Set_Style_Check_Options ("3abcefhiklmnprst"); end Set_Default_Style_Check_Options; ----------------------------- -- Set_Style_Check_Options -- ----------------------------- -- Version used when no error checking is required procedure Set_Style_Check_Options (Options : String) is OK : Boolean; EC : Natural; begin Set_Style_Check_Options (Options, OK, EC); end Set_Style_Check_Options; -- Normal version with error checking procedure Set_Style_Check_Options (Options : String; OK : out Boolean; Err_Col : out Natural) is J : Natural; C : Character; begin J := Options'First; while J <= Options'Last loop C := Options (J); J := J + 1; case C is when '1' .. '9' => Style_Check_Indentation := Character'Pos (C) - Character'Pos ('0'); when 'a' => Style_Check_Attribute_Casing := True; when 'b' => Style_Check_Blanks_At_End := True; when 'c' => Style_Check_Comments := True; when 'e' => Style_Check_End_Labels := True; when 'f' => Style_Check_Form_Feeds := True; when 'h' => Style_Check_Horizontal_Tabs := True; when 'i' => Style_Check_If_Then_Layout := True; when 'k' => Style_Check_Keyword_Casing := True; when 'l' => Style_Check_Layout := True; when 'm' => Style_Check_Max_Line_Length := True; Style_Max_Line_Length := 79; when 'n' => Style_Check_Standard := True; when 'M' => Style_Max_Line_Length := 0; if J > Options'Last or else Options (J) not in '0' .. '9' then OK := False; Err_Col := J; return; end if; loop Style_Max_Line_Length := Style_Max_Line_Length * 10 + Character'Pos (Options (J)) - Character'Pos ('0'); J := J + 1; exit when J > Options'Last or else Options (J) not in '0' .. '9'; end loop; Style_Max_Line_Length := Int'Min (Style_Max_Line_Length, Hostparm.Max_Line_Length); Style_Check_Max_Line_Length := Style_Max_Line_Length /= 0; when 'o' => Style_Check_Subprogram_Order := True; when 'p' => Style_Check_Pragma_Casing := True; when 'r' => Style_Check_References := True; when 's' => Style_Check_Specs := True; when 't' => Style_Check_Tokens := True; when ' ' => null; when others => OK := False; Err_Col := J - 1; return; end case; end loop; Style_Check := True; OK := True; Err_Col := Options'Last + 1; end Set_Style_Check_Options; end Stylesw;
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Streams; with GNAT.SHA1; with Natools.GNAT_HMAC; with Natools.GNAT_HMAC.SHA1; with Natools.S_Expressions.Encodings; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.File_Writers; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Printers.Pretty.Config; with Simple_Webapps.Commands.Upload_Servers; separate (Simple_Webapps.Upload_Servers) package body Backend is package Commands renames Simple_Webapps.Commands.Upload_Servers; package Hash renames GNAT.SHA1; package HMAC renames Natools.GNAT_HMAC.SHA1; Hash_Name : constant String := "SHA-1"; Digit_62 : constant Ada.Streams.Stream_Element := Character'Pos ('-'); Digit_63 : constant Ada.Streams.Stream_Element := Character'Pos ('_'); -- Special digits for base-64 URI (RFC 4648) procedure Execute (State : in out Config_Data; Context : in Natools.Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); -- Execute S-expression commands for configuration data interpreter procedure Execute (State : in out File_Data; Context : in Natools.Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); -- Execute S-expression commands for file data interpreter procedure Set_Max_Expiration (Max_Expiration : in out Size_Time; Expression : in out S_Expressions.Lockable.Descriptor'Class); -- Process Expression and update Max_Expiration with parsed value procedure Write (Self : in File_Data; Output : in out S_Expressions.Printers.Printer'Class); -- Serialize the given file data into Output -------------------- -- File Entry I/O -- -------------------- procedure Execute (State : in out File_Data; Context : in Natools.Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); use type S_Expressions.Events.Event; begin if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then return; end if; declare Value : constant String := S_Expressions.To_String (Arguments.Current_Atom); begin case Commands.To_File_Command (S_Expressions.To_String (Name)) is when Commands.File_Error => null; when Commands.Set_Name => State.Name := Hold (Value); when Commands.Set_Comment => State.Comment := Hold (Value); when Commands.Set_Download => if State.Download'Length = Value'Length then State.Download := Value; end if; when Commands.Set_Expiration => State.Expiration := Ada.Calendar.Formatting.Value (Value); when Commands.Set_MIME_Type => State.MIME_Type := Hold (Value); when Commands.Set_Upload => State.Upload := Ada.Calendar.Formatting.Value (Value); end case; end; end Execute; procedure Interpreter is new S_Expressions.Interpreter_Loop (File_Data, Natools.Meaningless_Type, Execute); procedure Write (Self : in File_Data; Output : in out S_Expressions.Printers.Printer'Class) is begin Output.Open_List; Output.Append_Atom (S_Expressions.To_Atom (Self.Report)); Output.Open_List; Output.Append_Atom (S_Expressions.To_Atom ("name")); Output.Append_Atom (S_Expressions.To_Atom (To_String (Self.Name))); Output.Close_List; Output.Open_List; Output.Append_Atom (S_Expressions.To_Atom ("comment")); Output.Append_Atom (S_Expressions.To_Atom (To_String (Self.Comment))); Output.Close_List; Output.Open_List; Output.Append_Atom (S_Expressions.To_Atom ("download-key")); Output.Append_Atom (S_Expressions.To_Atom (Self.Download)); Output.Close_List; Output.Open_List; Output.Append_Atom (S_Expressions.To_Atom ("expire")); Output.Append_Atom (S_Expressions.To_Atom (Ada.Calendar.Formatting.Image (Self.Expiration))); Output.Close_List; Output.Open_List; Output.Append_Atom (S_Expressions.To_Atom ("mime-type")); Output.Append_Atom (S_Expressions.To_Atom (To_String (Self.MIME_Type))); Output.Close_List; Output.Open_List; Output.Append_Atom (S_Expressions.To_Atom ("upload")); Output.Append_Atom (S_Expressions.To_Atom (Ada.Calendar.Formatting.Image (Self.Upload))); Output.Close_List; Output.Close_List; end Write; ------------------------- -- Database Config I/O -- ------------------------- procedure Set_Max_Expiration (Max_Expiration : in out Size_Time; Expression : in out S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; Event : S_Expressions.Events.Event; New_Value : Size_Time := 0; begin Parse_Number : declare use type S_Expressions.Atom; use type S_Expressions.Count; use type S_Expressions.Octet; Number : constant S_Expressions.Atom := Expression.Current_Atom; I : S_Expressions.Offset := Number'First; begin while I in Number'Range and then Number (I) = 32 loop I := I + 1; end loop; while I in Number'Range and then Number (I) in 48 .. 57 loop New_Value := New_Value * 10 + Size_Time (Number (I) - 48); I := I + 1; end loop; if I in Number'Range or New_Value = 0 then return; end if; end Parse_Number; Max_Expiration := New_Value; Expression.Next (Event); if Event /= S_Expressions.Events.Add_Atom then return; end if; Parse_Unit : declare Unit_Str : constant String := S_Expressions.To_String (Expression.Current_Atom); I : Positive := Unit_Str'First; begin if Unit_Str (I) = 'k' then New_Value := New_Value * 1024; I := I + 1; elsif Unit_Str (I) = 'M' then New_Value := New_Value * 1024 ** 2; I := I + 1; elsif Unit_Str (I) = 'G' then New_Value := New_Value * 1024 ** 3; I := I + 1; elsif Unit_Str (I) = 'T' then New_Value := New_Value * 1024 ** 4; I := I + 1; end if; if Unit_Str (I) = 'b' then New_Value := New_Value / 8; I := I + 1; elsif Unit_Str (I) = 'B' then I := I + 1; else return; end if; if Unit_Str (I) = '.' then I := I + 1; else return; end if; if Unit_Str (I) = 's' then I := I + 1; elsif Unit_Str (I) = 'm' then New_Value := New_Value * 60; I := I + 1; elsif Unit_Str (I) = 'h' then New_Value := New_Value * 3600; I := I + 1; elsif Unit_Str (I) = 'd' then New_Value := New_Value * 86_400; I := I + 1; elsif Unit_Str (I) = 'w' then New_Value := New_Value * 604_800; I := I + 1; else return; end if; end Parse_Unit; Max_Expiration := New_Value; end Set_Max_Expiration; procedure Execute (State : in out Config_Data; Context : in Natools.Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); use type S_Expressions.Events.Event; function Current_Atom return S_Expressions.Atom; function Current_Atom return S_Expressions.Atom is begin return Arguments.Current_Atom; end Current_Atom; begin if Arguments.Current_Event /= S_Expressions.Events.Add_Atom then return; end if; declare Value : constant String := S_Expressions.To_String (Arguments.Current_Atom); begin case Commands.To_Config_Command (S_Expressions.To_String (Name)) is when Commands.Config_Error => null; when Commands.Set_Storage_File => State.Storage_File := Hold (Value); declare Event : S_Expressions.Events.Event; begin Arguments.Next (Event); case Event is when S_Expressions.Events.Add_Atom | S_Expressions.Events.Open_List => S_Expressions.Printers.Pretty.Config.Update (State.Printer_Param, Arguments); when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => null; end case; end; when Commands.Set_Directory => State.Directory := Atom_Refs.Create (Current_Atom'Access); when Commands.Set_Error_Template => State.Error_Template := Hold (Value); when Commands.Set_HMAC_Key => State.HMAC_Key := Hold (Value); when Commands.Set_Index_Template => State.Index_Template := Hold (Value); when Commands.Set_Input_Dir => State.Input_Dir := Hold (Value); when Commands.Set_Max_Expiration => Set_Max_Expiration (State.Max_Expiration, Arguments); when Commands.Set_Static_Dir => State.Static_Dir := Hold (Value); when Commands.Set_Report_Template => State.Report_Template := Hold (Value); end case; end; end Execute; procedure Interpreter is new S_Expressions.Interpreter_Loop (Config_Data, Natools.Meaningless_Type, Execute); -------------------- -- File Accessors -- -------------------- function Is_Empty (Self : File) return Boolean is begin return Self.Ref.Is_Empty; end Is_Empty; function Name (Self : File) return String is begin return To_String (Self.Ref.Query.Data.Name); end Name; function Comment (Self : File) return String is begin return To_String (Self.Ref.Query.Data.Comment); end Comment; function MIME_Type (Self : File) return String is begin return To_String (Self.Ref.Query.Data.MIME_Type); end MIME_Type; function Path (Directory : Atom_Refs.Immutable_Reference; Report : URI_Key) return String is begin return Ada.Directories.Compose (S_Expressions.To_String (Directory.Query.Data.all), Report, ""); end Path; function Path (Self : File) return String is begin return Path (Self.Ref.Query.Data.Directory, Self.Ref.Query.Data.Report); end Path; function Report (Self : File) return URI_Key is begin return Self.Ref.Query.Data.Report; end Report; function Download (Self : File) return URI_Key is begin return Self.Ref.Query.Data.Download; end Download; function Hash_Type (Self : File) return String is pragma Unreferenced (Self); begin return Hash_Name; end Hash_Type; function Hex_Digest (Self : File) return String is begin return S_Expressions.To_String (S_Expressions.Encodings.Encode_Hex (S_Expressions.Encodings.Decode_Base64 (S_Expressions.To_Atom (Self.Ref.Query.Data.Report), Digit_62, Digit_63), S_Expressions.Encodings.Lower)); end Hex_Digest; function Upload (Self : File) return Ada.Calendar.Time is begin return Self.Ref.Query.Data.Upload; end Upload; function Expiration (Self : File) return Ada.Calendar.Time is begin return Self.Ref.Query.Data.Expiration; end Expiration; function Expire_Before (Left, Right : File) return Boolean is use type Ada.Calendar.Time; begin return Left.Expiration < Right.Expiration or else (Left.Expiration = Right.Expiration and then Left.Report < Right.Report); end Expire_Before; ---------------------- -- S-Expression I/O -- ---------------------- procedure Read (Self : out File_Set; Input : in out S_Expressions.Lockable.Descriptor'Class; Directory : in Atom_Refs.Immutable_Reference) is use type S_Expressions.Events.Event; use type Ada.Calendar.Time; Event : S_Expressions.Events.Event := Input.Current_Event; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Empty_Data : constant File_Data := (Name | Comment | MIME_Type => Hold (""), Report | Download => (others => ' '), Upload | Expiration => Now, Directory => Directory); Data : File_Data; F : File; function Create return File_Data; function Create return File_Data is begin return Data; end Create; Lock : S_Expressions.Lockable.Lock_State; begin Self.Reports.Clear; Self.Downloads.Clear; Self.Expires.Clear; loop case Event is when S_Expressions.Events.Open_List => Input.Next (Event); if Event = S_Expressions.Events.Add_Atom and then Input.Current_Atom'Length = Data.Report'Length then Data := Empty_Data; Data.Report := S_Expressions.To_String (Input.Current_Atom); Input.Lock (Lock); Input.Next; Interpreter (Input, Data, Natools.Meaningless_Value); Input.Unlock (Lock); if Data.Download /= Empty_Data.Download and then not Self.Reports.Contains (Data.Report) and then not Self.Downloads.Contains (Data.Download) then if Data.Expiration > Now then F := (Ref => File_Refs.Create (Create'Access)); Self.Reports.Insert (Data.Report, F); Self.Downloads.Insert (Data.Download, F); Self.Expires.Insert (F); elsif Ada.Directories.Exists (Path (Directory, Data.Report)) then Ada.Directories.Delete_File (Path (Directory, Data.Report)); Log ("Purged stale file " & Data.Report); end if; end if; end if; when S_Expressions.Events.Close_List | S_Expressions.Events.Add_Atom => null; when S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => exit; end case; Input.Next (Event); end loop; end Read; ----------------------------- -- Database Implementation -- ----------------------------- protected body Database is function Debug_Activated return Boolean is begin return Debug; end Debug_Activated; function Report (Key : URI_Key) return File is use type Ada.Calendar.Time; Cursor : constant File_Maps.Cursor := Files.Reports.Find (Key); Result : File := (Ref => File_Refs.Null_Immutable_Reference); begin if File_Maps.Has_Element (Cursor) then Result := File_Maps.Element (Cursor); if Result.Expiration < Ada.Calendar.Clock then Result := (Ref => File_Refs.Null_Immutable_Reference); end if; end if; return Result; end Report; function Download (Key : URI_Key) return File is use type Ada.Calendar.Time; Cursor : constant File_Maps.Cursor := Files.Downloads.Find (Key); Result : File := (Ref => File_Refs.Null_Immutable_Reference); begin if File_Maps.Has_Element (Cursor) then Result := File_Maps.Element (Cursor); if Result.Expiration < Ada.Calendar.Clock then Result := (Ref => File_Refs.Null_Immutable_Reference); end if; end if; return Result; end Download; function Error_Template return String is begin return To_String (Config.Error_Template); end Error_Template; function Index_Template return String is begin return To_String (Config.Index_Template); end Index_Template; function Max_Expiration return Size_Time is begin return Config.Max_Expiration; end Max_Expiration; function Static_Resource_Dir return String is begin return To_String (Config.Static_Dir); end Static_Resource_Dir; function Report_Template return String is begin return To_String (Config.Report_Template); end Report_Template; function Iterate (Process : not null access procedure (F : in File)) return Boolean is procedure Local_Process (Position : in Time_Sets.Cursor); procedure Local_Process (Position : in Time_Sets.Cursor) is begin Process.all (Time_Sets.Element (Position)); end Local_Process; begin Files.Expires.Iterate (Local_Process'Access); return True; end Iterate; procedure Add_File (Local_Path : in String; Name : in String; Comment : in String; MIME_Type : in String; Expiration : in Ada.Calendar.Time; Report : out URI_Key) is Download : URI_Key; Input_Dir : constant String := To_String (Config.Input_Dir); function Create return File_Data; function Create return File_Data is begin return (Name => Hold (Name), Comment => Hold (Comment), MIME_Type => Hold (MIME_Type), Report => Report, Download => Download, Expiration => Expiration, Upload => Ada.Calendar.Clock, Directory => Config.Directory); end Create; begin Purge_Expired; if Input_Dir /= "" and then (Input_Dir'Length > Local_Path'Length or else Local_Path (Local_Path'First .. Local_Path'First + Input_Dir'Length - 1) /= Input_Dir) then -- Local_Path outside of Input_Dir, something nasty might be -- going on, so drop the request. Report := (others => ' '); return; end if; Compute_Hash : declare procedure Process (Block : in S_Expressions.Atom); Context : Hash.Context := Hash.Initial_Context; procedure Process (Block : in S_Expressions.Atom) is begin Hash.Update (Context, Block); end Process; begin S_Expressions.File_Readers.Block_Query (S_Expressions.File_Readers.Reader (Local_Path), 4096, Process'Access); Report := S_Expressions.To_String (S_Expressions.Encodings.Encode_Base64 (Natools.GNAT_HMAC.Digest (Context), Digit_62, Digit_63)); end Compute_Hash; Save_File : declare Target_Path : constant String := Path (Config.Directory, Report); begin Ada.Directories.Copy_File (Local_Path, Target_Path); end Save_File; Remove_Source : begin Ada.Directories.Delete_File (Local_Path); end Remove_Source; Download := S_Expressions.To_String (S_Expressions.Encodings.Encode_Base64 (HMAC.Digest (To_String (Config.HMAC_Key), S_Expressions.To_Atom (Report)), Digit_62, Digit_63)); Write_DB : declare Printer : S_Expressions.File_Writers.Writer; begin Printer.Open (To_String (Config.Storage_File)); Printer.Set_Parameters (Config.Printer_Param); Write (Create, Printer); if Config.Printer_Param.Newline_At (S_Expressions.Printers.Pretty.Closing, S_Expressions.Printers.Pretty.Opening) then Printer.Newline; end if; end Write_DB; Insert_Ref : declare F : constant File := (Ref => File_Refs.Create (Create'Access)); begin Files.Reports.Insert (Report, F); Files.Downloads.Insert (Download, F); Files.Expires.Insert (F); end Insert_Ref; Log ("File " & Report & " received, expires on " & Ada.Calendar.Formatting.Image (Expiration)); end Add_File; procedure Purge_Expired is use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; First : File; begin loop exit when Files.Expires.Is_Empty; First := Files.Expires.First_Element; exit when First.Expiration > Now; Files.Reports.Delete (First.Report); Files.Downloads.Delete (First.Download); Files.Expires.Delete (First); Ada.Directories.Delete_File (First.Path); Log ("File " & First.Report & " purged"); end loop; end Purge_Expired; procedure Reset (New_Config : in out S_Expressions.Lockable.Descriptor'Class; New_Debug : in Boolean := False) is use type Ada.Directories.File_Kind; New_Data : Config_Data := (Storage_File => Hold ("/"), Directory => Atom_Refs.Null_Immutable_Reference, HMAC_Key | Input_Dir | Static_Dir | Error_Template | Index_Template | Report_Template => Hold (""), Max_Expiration => <>, Printer_Param => S_Expressions.Printers.Pretty.Canonical); begin Interpreter (New_Config, New_Data, Natools.Meaningless_Value); if New_Data.Directory.Is_Empty or else To_String (New_Data.HMAC_Key) = "" or else not Ada.Directories.Exists (To_String (New_Data.Storage_File)) or else Ada.Directories.Kind (To_String (New_Data.Storage_File)) /= Ada.Directories.Ordinary_File then Log ("Failed reset"); return; end if; declare Storage : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (To_String (New_Data.Storage_File)); begin Read (Files, Storage, New_Data.Directory); end; Config := New_Data; Debug := New_Debug; Log ("Database successfully reset with" & Ada.Containers.Count_Type'Image (Files.Expires.Length) & " active files"); end Reset; end Database; end Backend;
-- The MIT License (MIT) -- -- Copyright (c) 2016 artium@nihamkin.com -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- with Ada.Sequential_IO; with Ada.Directories; package body Linux_Joystick is type Axis_Button_Number_Type is range 0..(2**8)-1; for Axis_Button_Number_Type'Size use 8; type Raw_Js_Event_Type is record Time : Milliseconds_Type; Value : Value_Type; Is_Init_Event : Boolean; Event_Type : Event_Type_Type; Axis_Button_Number : Axis_Button_Number_Type; end record; for Raw_Js_Event_Type use record Time at 0 range 0..31; Value at 4 range 0..15; Is_Init_Event at 6 range 0..0; Event_Type at 6 range 1..7; Axis_Button_Number at 7 range 0..7; end record; for Raw_Js_Event_Type'Bit_Order use System.High_Order_First; -- TODO: veriy that this is enough package SIO is new Ada.Sequential_IO(Raw_Js_Event_Type); Input_File : SIO.File_Type; procedure Open(Name : String) is begin SIO.Open (File => Input_File, Mode => SIO.IN_FILE, Name => Name); end; function Open return String is Search : Ada.Directories.Search_Type; Dir_Ent : Ada.Directories.Directory_Entry_Type; begin Ada.Directories.Start_Search (Search, "/dev/input/", "js*"); if not Ada.Directories.More_Entries (Search) then Ada.Directories.End_Search (Search); raise No_Joystick_Device_Found; end if; Ada.Directories.Get_Next_Entry (Search, Dir_Ent); declare Device_Path : String := Ada.Directories.Full_Name (Dir_Ent); begin Ada.Directories.End_Search (Search); Open(Device_Path); return Device_Path; end; end; function Read return Js_Event_Type is Raw_Js_Event : Raw_Js_Event_Type; begin SIO.Read(File => Input_File, Item => Raw_Js_Event); case Raw_Js_Event.Event_Type is when JS_EVENT_BUTTON => return (Event_Type => JS_EVENT_BUTTON, Time => Raw_Js_Event.Time, Is_Init_Event => Raw_Js_Event.Is_Init_Event, Button => Button_Type'Val(Raw_Js_Event.Axis_Button_Number), Button_Action => Button_Action_Type'Val(Raw_Js_Event.Value) ); when JS_EVENT_AXIS => return (Event_Type => JS_EVENT_AXIS, Time => Raw_Js_Event.Time, Is_Init_Event => Raw_Js_Event.Is_Init_Event, Axis => Axis_Type'Val(Raw_Js_Event.Axis_Button_Number), Value => Raw_Js_Event.Value ); end case; end; procedure Close is begin SIO.Close(Input_File); end; end Linux_Joystick;
--PRÁCTICA 4: CÉSAR BORAO MORATINOS (Ordered_Maps_G.adb) package body Ordered_Maps_G is function Binary_Search (M: Map; Key: Key_Type; Left: Integer; Right: Integer) return Integer is Middle: Integer; begin if Right < Left then return Left; else Middle := (Left + Right)/2; if Left = Right then return Left; elsif M.P_Array(Middle).Key < Key then return Binary_Search (M,Key,Middle + 1,Right); elsif Key < M.P_Array(Middle).Key then return Binary_Search (M,Key,Left,Middle); else return Middle; end if; end if; end Binary_Search; procedure Put (M: in out Map; Key: Key_Type; Value: Value_Type) is Position: Integer := 0; Left: Integer := 0; begin if M.P_Array = null or M.Length = 0 then M.P_Array := new Cell_Array; M.P_Array(0) := (Key, Value, True); M.Length := 1; else Position := Binary_Search (M,Key,Left,M.Length); if Position > Max - 1 then raise Full_Map; end if; if M.P_Array(Position).Full and M.P_Array(Position).Key = Key then M.P_Array(Position).Value := Value; elsif M.P_Array(Position).Full then for I in reverse Position..M.Length-1 loop if M.Length = Max then raise Full_Map; end if; M.P_Array(I + 1) := M.P_Array(I); end loop; M.Length := M.Length + 1; M.P_Array(Position) := (Key, Value, True); else M.P_Array(Position) := (Key, Value, True); M.Length := M.Length + 1; end if; end if; end Put; procedure Get (M: Map; Key: in Key_Type; Value: out Value_Type; Success: out Boolean) is Left: Integer := 0; Right: Integer := Max-1; Position: Integer := 0; begin Success := False; if M.P_Array /= null then Position := Binary_Search (M,Key,Left,Right); if Position <= Max - 1 then if M.P_Array(0).Key = Key then Success := True; Value := M.P_Array(Binary_Search (M,Key,Left,Right)).Value; end if; end if; end if; end Get; procedure Delete (M: in out Map; Key: in Key_Type; Success: out Boolean) is Left: Integer := 0; Right: Integer := M.Length; Position: Integer; begin Success := False; Position := Binary_Search (M,Key,Left,Right); if Position <= Max - 1 then if M.P_Array(Position).Key = Key then Success := True; M.Length := M.Length - 1; for I in Position..M.Length - 1 loop M.P_Array(I) := M.P_Array(I + 1); end loop; end if; end if; end Delete; function Map_Length (M: Map) return Natural is begin return M.Length; end Map_Length; function First (M: Map) return Cursor is C: Cursor; begin C.M := M; C.Position := 0; return C; end First; procedure Next (C: in out Cursor) is End_Of_Map: Boolean; begin End_Of_Map := False; if C.Position <= Max then C.Position := C.Position + 1; end if; end Next; function Has_Element (C: Cursor) return Boolean is begin if C.Position >= C.M.Length then return False; end if; return C.M.P_Array(C.Position).Full; end Has_Element; function Element (C: Cursor) return Element_Type is Element: Element_Type; begin if Has_Element (C) then Element.Key := C.M.P_Array(C.Position).Key; Element.Value := C.M.P_Array(C.Position).Value; else raise No_Element; end if; return Element; end Element; end Ordered_Maps_G;
----------------------------------------------------------------------- -- keystore-files-tests -- Tests for files -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.XUnit; with Ada.Directories; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Measures; with Util.Streams.Buffered; with Keystore.IO; package body Keystore.Files.Tests is use type Ada.Streams.Stream_Element; use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; procedure Create_With_Header (Path : in String; Password : in Keystore.Secret_Key; Count : in Header_Slot_Count_Type); procedure Verify_Header_Data (T : in out Test; Path : in String; Count : in Header_Slot_Count_Type); package Caller is new Util.Test_Caller (Test, "Keystore.Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Keystore.Files.Create+Open", Test_Create'Access); Caller.Add_Test (Suite, "Test Keystore.Add", Test_Add'Access); Caller.Add_Test (Suite, "Test Keystore.Get", Test_Add_Get'Access); Caller.Add_Test (Suite, "Test Keystore.Open (Corrupted keystore)", Test_Corruption'Access); Caller.Add_Test (Suite, "Test Keystore.List", Test_List'Access); Caller.Add_Test (Suite, "Test Keystore.Delete", Test_Delete'Access); Caller.Add_Test (Suite, "Test Keystore.Update", Test_Update'Access); Caller.Add_Test (Suite, "Test Keystore.Update (grow, shrink)", Test_Update_Sequence'Access); Caller.Add_Test (Suite, "Test Keystore.Files.Open+Close", Test_Open_Close'Access); Caller.Add_Test (Suite, "Test Keystore.Add (Name_Exist)", Test_Add_Error'Access); Caller.Add_Test (Suite, "Test Keystore.Write", Test_Get_Stream'Access); Caller.Add_Test (Suite, "Test Keystore.Add (Empty)", Test_Add_Empty'Access); Caller.Add_Test (Suite, "Test Keystore.Add (Perf)", Test_Perf_Add'Access); Caller.Add_Test (Suite, "Test Keystore.Set (Input_Stream < 4K)", Test_Set_From_Stream'Access); Caller.Add_Test (Suite, "Test Keystore.Set (Input_Stream > 4K)", Test_Set_From_Larger_Stream'Access); Caller.Add_Test (Suite, "Test Keystore.Set_Key", Test_Set_Key'Access); Caller.Add_Test (Suite, "Test Keystore.Get_Header_Data (1)", Test_Header_Data_1'Access); Caller.Add_Test (Suite, "Test Keystore.Get_Header_Data (10)", Test_Header_Data_10'Access); Caller.Add_Test (Suite, "Test Keystore.Add (Wallet)", Test_Add_Wallet'Access); end Add_Tests; -- ------------------------------ -- Test creation of a keystore and re-opening it. -- ------------------------------ procedure Test_Create (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-create.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); Config : Keystore.Wallet_Config := Unsecure_Config; begin declare W : Keystore.Files.Wallet_File; begin Config.Overwrite := True; W.Create (Path => Path, Password => Password, Config => Config); end; declare Wread : Keystore.Files.Wallet_File; begin Wread.Open (Path => Path, Password => Password); end; declare Wread : Keystore.Files.Wallet_File; Bad : Keystore.Secret_Key := Keystore.Create ("mypassword-bad"); begin Wread.Open (Path => Path, Password => Bad); T.Fail ("No exception raised"); exception when Bad_Password => null; end; declare W : Keystore.Files.Wallet_File; begin W.Create (Path => Path, Password => Password, Config => Unsecure_Config); T.Fail ("Create should raise Name_Error exception if the file exists"); exception when Ada.IO_Exceptions.Name_Error => null; end; end Test_Create; -- ------------------------------ -- Test opening a keystore when some blocks are corrupted. -- ------------------------------ procedure Test_Corruption (T : in out Test) is use type IO.Block_Count; procedure Corrupt (Block : in IO.Block_Number; Pos : in IO.Block_Index); Path : constant String := Util.Tests.Get_Path ("regtests/files/test-keystore.akt"); Corrupt_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-corrupt.akt"); procedure Corrupt (Block : in IO.Block_Number; Pos : in IO.Block_Index) is -- Source_File : IO.Files.Block_IO.File_Type; -- Corrupt_File : IO.Files.Block_IO.File_Type; Data : IO.IO_Block_Type; Last : Ada.Streams.Stream_Element_Offset; Current : IO.Block_Number := 1; Input_File : Util.Streams.Files.File_Stream; Output_File : Util.Streams.Files.File_Stream; begin Input_File.Open (Name => Path, Mode => Ada.Streams.Stream_IO.In_File); Output_File.Create (Name => Corrupt_Path, Mode => Ada.Streams.Stream_IO.Out_File); loop Input_File.Read (Data, Last); if Current = Block then Data (Pos) := Data (Pos) xor 1; end if; if Last > Data'First then Output_File.Write (Data (Data'First .. Last)); end if; exit when Last < Data'Last; Current := Current + 1; end loop; end Corrupt; Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); begin for Block in IO.Block_Number (1) .. 3 loop for I in 1 .. IO.Block_Index'Last / 17 loop declare Pos : constant IO.Block_Index := I * 17; W : Keystore.Files.Wallet_File; Items : Keystore.Entry_Map; begin Corrupt (Block, Pos); W.Open (Password => Password, Path => Corrupt_Path); -- Block 1 and Block 2 are read by Open. -- Corruption must have been detected by Open. if Block <= 2 then T.Fail ("No corruption detected block" & IO.Block_Number'Image (Block) & " at" & IO.Block_Index'Image (Pos)); end if; -- Block 3 is read only if we need the repository and datacontent. W.List (Content => Items); W.Set ("no-corruption-detected", W.Get ("list-1")); T.Fail ("No corruption detected block" & IO.Block_Number'Image (Block) & " at" & IO.Block_Index'Image (Pos)); exception when Keystore.Corrupted => null; when Keystore.Invalid_Block | Keystore.Invalid_Signature => null; when Keystore.Bad_Password => null; when Util.XUnit.Assertion_Error => raise; when E : others => T.Fail ("Exception not expected: " & Ada.Exceptions.Exception_Name (E)); end; end loop; end loop; end Test_Corruption; -- ------------------------------ -- Test adding values to a keystore. -- ------------------------------ procedure Test_Add (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-add.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); Config : Keystore.Wallet_Config := Unsecure_Config; begin Config.Overwrite := True; declare W : Keystore.Files.Wallet_File; begin W.Create (Path => Path, Password => Password, Config => Config); end; declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); W.Add ("my-secret", "the secret"); T.Assert (W.Contains ("my-secret"), "Property not contained in wallet"); end; declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); T.Assert (W.Contains ("my-secret"), "Property not contained in wallet (load)"); Util.Tests.Assert_Equals (T, "the secret", W.Get ("my-secret"), "Property cannot be retrieved from keystore"); W.Add ("my-second-secret", "the second-secret"); T.Assert (W.Contains ("my-second-secret"), "Property not contained in wallet"); T.Assert (W.Contains ("my-secret"), "Property not contained in wallet"); end; end Test_Add; -- ------------------------------ -- Test adding values and getting them back. -- ------------------------------ procedure Test_Add_Get (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-add-get.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword-add-get"); Config : Keystore.Wallet_Config := Unsecure_Config; begin Config.Overwrite := True; declare W : Keystore.Files.Wallet_File; begin W.Create (Path => Path, Password => Password, Config => Config); end; for Pass in 1 .. 10 loop declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); W.Add ("my-second-secret " & Positive'Image (Pass), "the second-secret padd " & Positive'Image (Pass)); for Check in 1 .. Pass loop T.Assert (W.Contains ("my-second-secret " & Positive'Image (Check)), "Property not contained in wallet " & Positive'Image (Check)); Util.Tests.Assert_Equals (T, "the second-secret padd " & Positive'Image (Check), W.Get ("my-second-secret " & Positive'Image (Check)), "Cannot get property " & Positive'Image (Check)); end loop; end; end loop; end Test_Add_Get; -- ------------------------------ -- Test deleting values. -- ------------------------------ procedure Test_Delete (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-delete.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword-delete"); Config : Keystore.Wallet_Config := Unsecure_Config; begin Config.Overwrite := True; declare W : Keystore.Files.Wallet_File; begin W.Create (Path => Path, Password => Password, Config => Config); W.Add ("my-secret-1", "the secret 1"); W.Add ("my-secret-2", "the secret 2"); W.Add ("my-secret-3", "the secret 3"); W.Add ("my-secret-4", "the secret 4"); end; declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); W.Delete ("my-secret-2"); T.Assert (not W.Contains ("my-secret-2"), "Second property should have been removed"); T.Assert (W.Contains ("my-secret-1"), "First property should still be present"); T.Assert (W.Contains ("my-secret-3"), "Last property should still be present"); T.Assert (W.Contains ("my-secret-4"), "Last property should still be present"); end; end Test_Delete; -- ------------------------------ -- Test opening a keystore and listing the entries. -- ------------------------------ procedure Test_List (T : in out Test) is procedure Verify_Entry (Name : in String; Size : in Integer); Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/test-keystore.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); W : Keystore.Files.Wallet_File; Items : Keystore.Entry_Map; procedure Verify_Entry (Name : in String; Size : in Integer) is Value : Keystore.Entry_Info; begin T.Assert (Items.Contains (Name), "Item " & Name & " should be in the wallet list"); T.Assert (W.Contains (Name), "Wallet should contain:" & Name); Value := Items.Element (Name); Util.Tests.Assert_Equals (T, Size, Natural (Value.Size), "Item " & Name & " has invalid size"); T.Assert (Value.Kind = Keystore.T_STRING, "Item " & Name & " should be a T_STRING"); end Verify_Entry; begin W.Open (Path => Path, Password => Password); W.List (Content => Items); Verify_Entry ("list-1", 63); Verify_Entry ("list-2", 64); Verify_Entry ("list-3", 39); Verify_Entry ("list-4", 42); end Test_List; -- ------------------------------ -- Test update values. -- ------------------------------ procedure Test_Update (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-update.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); Count : constant Natural := 10; begin if Ada.Directories.Exists (Path) then Ada.Directories.Delete_File (Path); end if; -- Step 1: create the keystore and add the values. declare W : Keystore.Files.Wallet_File; begin W.Create (Path => Path, Password => Password, Config => Unsecure_Config); for I in 1 .. Count loop W.Add (Name => "test-update" & Natural'Image (I), Content => "Value before update" & Natural'Image (I)); end loop; end; -- Step 2: open the keystore and update the values. declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); for I in 1 .. Count loop Util.Tests.Assert_Equals (T, "Value before update" & Natural'Image (I), W.Get ("test-update" & Natural'Image (I)), "Invalid property test-update" & Natural'Image (I)); W.Update (Name => "test-update" & Natural'Image (I), Content => "Value after update" & Natural'Image (I)); end loop; for I in 1 .. Count loop Util.Tests.Assert_Equals (T, "Value after update" & Natural'Image (I), W.Get ("test-update" & Natural'Image (I)), "Invalid property test-update" & Natural'Image (I)); W.Update (Name => "test-update" & Natural'Image (I), Content => "Value after second update" & Natural'Image (I)); end loop; end; -- Step 3: open the keystore, get the values, update them. declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); for I in 1 .. 1 loop Util.Tests.Assert_Equals (T, "Value after second update" & Natural'Image (I), W.Get ("test-update" & Natural'Image (I)), "Invalid property test-update" & Natural'Image (I)); W.Update (Name => "test-update" & Natural'Image (I), Content => "Value after third update " & Natural'Image (I)); end loop; end; -- Step 4: open the keystore and verify the last values. declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); for I in 1 .. 1 loop Util.Tests.Assert_Equals (T, "Value after third update " & Natural'Image (I), W.Get ("test-update" & Natural'Image (I)), "Invalid property test-update" & Natural'Image (I)); end loop; end; end Test_Update; -- ------------------------------ -- Test update values in growing and descending sequences. -- ------------------------------ procedure Test_Update_Sequence (T : in out Test) is function Large (Len : in Positive; Content : in Character) return String; Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-sequence.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); function Large (Len : in Positive; Content : in Character) return String is Result : constant String (1 .. Len) := (others => Content); begin return Result; end Large; begin if Ada.Directories.Exists (Path) then Ada.Directories.Delete_File (Path); end if; -- Step 1: create the keystore and add the values. declare W : Keystore.Files.Wallet_File; begin W.Create (Path => Path, Password => Password, Config => Unsecure_Config); W.Add ("a", "b"); W.Add ("c", "d"); W.Add ("e", "f"); -- Update with new size < 16 (content uses same number of AES block). W.Update ("a", "bcde"); Util.Tests.Assert_Equals (T, "bcde", W.Get ("a"), "Cannot get property a"); W.Update ("c", "ghij"); Util.Tests.Assert_Equals (T, "ghij", W.Get ("c"), "Cannot get property c"); W.Update ("e", "klmn"); Util.Tests.Assert_Equals (T, "klmn", W.Get ("e"), "Cannot get property e"); if W.Get ("e") = "klmn" then return; end if; -- Update with size > 16 (a new AES block is necessary, hence shifting data in block). W.Update ("a", "0123456789abcdef12345"); Util.Tests.Assert_Equals (T, "0123456789abcdef12345", W.Get ("a"), "Cannot get property a"); W.Update ("c", "c0123456789abcdef12345"); Util.Tests.Assert_Equals (T, "c0123456789abcdef12345", W.Get ("c"), "Cannot get property c"); W.Update ("e", "e0123456789abcdef12345"); Util.Tests.Assert_Equals (T, "e0123456789abcdef12345", W.Get ("e"), "Cannot get property e"); end; -- Step 2: check the values. declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); Util.Tests.Assert_Equals (T, "0123456789abcdef12345", W.Get ("a"), "Cannot get property a"); Util.Tests.Assert_Equals (T, "c0123456789abcdef12345", W.Get ("c"), "Cannot get property c"); Util.Tests.Assert_Equals (T, "e0123456789abcdef12345", W.Get ("e"), "Cannot get property e"); for I in 1 .. 5 loop declare L1 : constant String := Large (1024 * I, 'a'); L2 : constant String := Large (1023 * I, 'b'); L3 : constant String := Large (1022 * I, 'c'); begin W.Update ("a", L1); Util.Tests.Assert_Equals (T, L1, W.Get ("a"), "Cannot get property a"); W.Update ("c", "ghij"); Util.Tests.Assert_Equals (T, "ghij", W.Get ("c"), "Cannot get property c"); W.Update ("e", L2); Util.Tests.Assert_Equals (T, L2, W.Get ("e"), "Cannot get property e"); W.Update ("a", "0123456789abcdef12345"); Util.Tests.Assert_Equals (T, "0123456789abcdef12345", W.Get ("a"), "Cannot get property a"); W.Update ("c", L3); Util.Tests.Assert_Equals (T, L3, W.Get ("c"), "Cannot get property c"); end; end loop; end; end Test_Update_Sequence; -- ------------------------------ -- Test opening and closing keystore. -- ------------------------------ procedure Test_Open_Close (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/test-keystore.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); W : Keystore.Files.Wallet_File; begin -- Open and close the same wallet instance several times. for I in 1 .. 5 loop W.Open (Path => Path, Password => Password); Util.Tests.Assert_Equals (T, "http://www.apache.org/licenses/LICENSE-2.0", W.Get ("list-4"), "Cannot get property list-4"); W.Close; end loop; end Test_Open_Close; -- ------------------------------ -- Test adding values that already exist. -- ------------------------------ procedure Test_Add_Error (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/test-keystore.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); W : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); begin W.Add ("list-1", "Value already contained in keystore, expect an exception"); T.Fail ("No Name_Exist exception was raised for Add"); exception when Keystore.Name_Exist => null; end; begin W.Update ("list-invalid", "Value does not exist in keystore, expect an exception"); T.Fail ("No Not_Found exception was raised for Add"); exception when Keystore.Not_Found => null; end; begin W.Delete ("list-invalid"); T.Fail ("No Name_Exist exception was raised for Add"); exception when Keystore.Not_Found => null; end; begin T.Fail ("No Not_Found exception, returned value: " & W.Get ("list-invalid")); exception when Keystore.Not_Found => null; end; end Test_Add_Error; -- ------------------------------ -- Test changing the wallet password. -- ------------------------------ procedure Test_Set_Key (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/test-keystore.akt"); Test_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-set-key.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); New_Password : Keystore.Secret_Key := Keystore.Create ("new-password"); begin Ada.Directories.Copy_File (Source_Name => Path, Target_Name => Test_Path); declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Test_Path, Password => Password); W.Set_Key (Password, New_Password, Keystore.Unsecure_Config, Keystore.KEY_REPLACE); end; declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Test_Path, Password => Password); T.Fail ("No exception raised by Open after Set_Key"); exception when Keystore.Bad_Password => null; when others => T.Fail ("Bad exception raised after Set_Key"); end; declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Test_Path, Password => New_Password); W.Set_Key (New_Password, Password, Keystore.Unsecure_Config, Keystore.KEY_REPLACE); end; declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Test_Path, Password => Password); begin W.Set_Key (New_Password, New_Password, Keystore.Unsecure_Config, Keystore.KEY_REPLACE); T.Fail ("No exception raised by Set_Key"); exception when Keystore.Bad_Password => null; end; end; declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Test_Path, Password => Password); W.Set_Key (Password, New_Password, Keystore.Unsecure_Config, Keystore.KEY_ADD); end; -- Open the wallet with a first password and then the second one. declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Test_Path, Password => Password); end; declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Test_Path, Password => New_Password); end; -- Remove the password we added. declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Test_Path, Password => Password); W.Set_Key (New_Password, New_Password, Keystore.Unsecure_Config, Keystore.KEY_REMOVE); end; end Test_Set_Key; -- ------------------------------ -- Test adding empty values to a keystore. -- ------------------------------ procedure Test_Add_Empty (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-empty.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); Config : Keystore.Wallet_Config := Unsecure_Config; begin Config.Overwrite := True; declare W : Keystore.Files.Wallet_File; Empty : Util.Streams.Buffered.Input_Buffer_Stream; begin W.Create (Path => Path, Password => Password, Config => Config); W.Add ("empty-1", ""); T.Assert (W.Contains ("empty-1"), "Property 'empty-1' not contained in wallet"); Empty.Initialize (""); W.Add ("empty-2", T_BINARY, Empty); T.Assert (W.Contains ("empty-2"), "Property 'empty-2' not contained in wallet"); Util.Tests.Assert_Equals (T, "", W.Get ("empty-1"), "Property 'empty-1' cannot be retrieved from keystore"); Util.Tests.Assert_Equals (T, "", W.Get ("empty-2"), "Property 'empty-1' cannot be retrieved from keystore"); end; declare W : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); T.Assert (W.Contains ("empty-1"), "Property 'empty-1' not contained in wallet"); T.Assert (W.Contains ("empty-2"), "Property 'empty-2' not contained in wallet"); Util.Tests.Assert_Equals (T, "", W.Get ("empty-1"), "Property 'empty-1' cannot be retrieved from keystore"); Util.Tests.Assert_Equals (T, "", W.Get ("empty-2"), "Property 'empty-1' cannot be retrieved from keystore"); end; end Test_Add_Empty; -- ------------------------------ -- Test getting values through an Output_Stream. -- ------------------------------ procedure Test_Get_Stream (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/test-keystore.akt"); Output : constant String := Util.Tests.Get_Path ("regtests/result/test-stream.txt"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.txt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); W : Keystore.Files.Wallet_File; File : Util.Streams.Files.File_Stream; begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Output); W.Open (Path => Path, Password => Password); W.Get (Name => "list-1", Output => File); W.Get (Name => "list-2", Output => File); W.Get (Name => "list-3", Output => File); W.Get (Name => "list-4", Output => File); W.Get (Name => "LICENSE.txt", Output => File); File.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Output, Message => "Write operation failed"); end Test_Get_Stream; procedure Test_File_Stream (T : in out Test; Name : in String; Input : in String) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.akt"); Output : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-" & Name); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); W : Keystore.Files.Wallet_File; File : Util.Streams.Files.File_Stream; Config : Keystore.Wallet_Config := Unsecure_Config; begin Config.Overwrite := True; File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Input); W.Create (Path => Path, Password => Password, Config => Config); W.Set (Name => Name, Kind => Keystore.T_STRING, Input => File); File.Close; W.Close; W.Open (Path => Path, Password => Password); File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Output); W.Get (Name => Name, Output => File); File.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Input, Test => Output, Message => "Set or write operation failed for " & Name); end Test_File_Stream; -- ------------------------------ -- Test setting values through an Input_Stream. -- ------------------------------ procedure Test_Set_From_Stream (T : in out Test) is Input : constant String := Util.Tests.Get_Path ("Makefile"); begin T.Test_File_Stream ("makefile.txt", Input); end Test_Set_From_Stream; procedure Test_Set_From_Larger_Stream (T : in out Test) is Input : constant String := Util.Tests.Get_Path ("LICENSE.txt"); begin T.Test_File_Stream ("LICENSE.txt", Input); end Test_Set_From_Larger_Stream; -- ------------------------------ -- Perforamce test adding values. -- ------------------------------ procedure Test_Perf_Add (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-perf.akt"); Password : constant Keystore.Secret_Key := Keystore.Create ("mypassword"); W : Keystore.Files.Wallet_File; Items : Keystore.Entry_Map; Config : Keystore.Wallet_Config := Unsecure_Config; begin Config.Overwrite := True; W.Create (Path => Path, Password => Password, Config => Config); declare S : Util.Measures.Stamp; Data : String (1 .. 80); begin for I in 1 .. 10_000 loop Data := (others => Character'Val (30 + I mod 64)); W.Add ("Item" & Natural'Image (I), Data); end loop; Util.Measures.Report (S, "Keystore.Add", 10_000); end; W.List (Content => Items); Util.Tests.Assert_Equals (T, 10_000, Natural (Items.Length), "Invalid number of items in keystore"); end Test_Perf_Add; procedure Create_With_Header (Path : in String; Password : in Keystore.Secret_Key; Count : in Header_Slot_Count_Type) is Config : Keystore.Wallet_Config := Unsecure_Config; W : Keystore.Files.Wallet_File; Kind : Keystore.Header_Slot_Type := 123; Value : Ada.Streams.Stream_Element := 3; begin Config.Overwrite := True; W.Create (Path => Path, Password => Password, Config => Config); for I in 1 .. Count loop declare D1 : constant Ada.Streams.Stream_Element_Array (10 .. 40) := (others => Value); begin W.Set_Header_Data (I, Kind, D1); Kind := Kind + 1; Value := Value + 1; end; end loop; end Create_With_Header; procedure Verify_Header_Data (T : in out Test; Path : in String; Count : in Header_Slot_Count_Type) is W : Keystore.Files.Wallet_File; Info : Keystore.Wallet_Info; Data : Ada.Streams.Stream_Element_Array (1 .. 256); Kind : Keystore.Header_Slot_Type; Last : Ada.Streams.Stream_Element_Offset; Expect_Kind : Keystore.Header_Slot_Type := 123; Value : Ada.Streams.Stream_Element := 3; begin W.Open (Path => Path, Info => Info); Util.Tests.Assert_Equals (T, Natural (Count), Natural (Info.Header_Count), "Invalid number of headers in keystore"); for I in 1 .. Count loop declare D1 : constant Ada.Streams.Stream_Element_Array (10 .. 40) := (others => Value); begin W.Get_Header_Data (I, Kind, Data, Last); Util.Tests.Assert_Equals (T, D1'Length, Natural (Last - Data'First + 1), "Invalid size of header data"); Util.Tests.Assert_Equals (T, Natural (Expect_Kind), Natural (Kind), "Invalid kind for header data"); T.Assert (D1 = Data (Data'First .. Last), "Invalid header data content"); Value := Value + 1; Expect_Kind := Expect_Kind + 1; end; end loop; W.Get_Header_Data (Count + 1, Kind, Data, Last); Util.Tests.Assert_Equals (T, Natural (SLOT_EMPTY), Natural (Kind), "Invalid kind for non existing header data"); Util.Tests.Assert_Equals (T, 0, Natural (Last), "Invalid last value"); end Verify_Header_Data; -- ------------------------------ -- Test setting and getting header data. -- ------------------------------ procedure Test_Header_Data_1 (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-header.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); begin Create_With_Header (Path, Password, 1); Verify_Header_Data (T, Path, 1); end Test_Header_Data_1; procedure Test_Header_Data_10 (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-header.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); begin Create_With_Header (Path, Password, 10); Verify_Header_Data (T, Path, 10); end Test_Header_Data_10; -- ------------------------------ -- Test creating a wallet. -- ------------------------------ procedure Test_Add_Wallet (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-wallet.akt"); Password : Keystore.Secret_Key := Keystore.Create ("mypassword"); Password2 : Keystore.Secret_Key := Keystore.Create ("admin"); Config : Keystore.Wallet_Config := Unsecure_Config; begin Config.Overwrite := True; declare W : Keystore.Files.Wallet_File; Child_Wallet : Keystore.Files.Wallet_File; begin W.Create (Path => Path, Password => Password, Config => Config); W.Add ("property", "value"); T.Assert (W.Contains ("property"), "Property 'property' not contained in wallet"); W.Add ("wallet", Password2, Child_Wallet); T.Assert (W.Contains ("wallet"), "Wallet 'wallet' not found"); Child_Wallet.Add ("child-property", "child-value"); T.Assert (Child_Wallet.Contains ("child-property"), "Property 'child-property' not contained in wallet"); Child_Wallet.Add ("child-2-property", "child-2-value"); T.Assert (Child_Wallet.Contains ("child-2-property"), "Property 'child-2-property' not contained in wallet"); Util.Tests.Assert_Equals (T, "child-value", Child_Wallet.Get ("child-property"), "Property 'child-property' cannot be retrieved from keystore"); end; declare W : Keystore.Files.Wallet_File; Child_Wallet : Keystore.Files.Wallet_File; begin W.Open (Path => Path, Password => Password); T.Assert (W.Contains ("property"), "Property 'value' not contained in wallet"); T.Assert (not W.Contains ("child-property"), "Property 'child-property' is contained in parent wallet!"); W.Open ("wallet", Password2, Child_Wallet); T.Assert (Child_Wallet.Contains ("child-property"), "Property 'child-property' not contained in wallet"); T.Assert (not Child_Wallet.Contains ("property"), "Property 'property' is contained in child wallet!"); Util.Tests.Assert_Equals (T, "child-value", Child_Wallet.Get ("child-property"), "Property 'child-property' cannot be retrieved from keystore"); end; end Test_Add_Wallet; end Keystore.Files.Tests;
with HAL; use HAL; with Ada.Real_Time; use Ada.Real_Time; with Ada.Unchecked_Conversion; package body mpu6000_spi is -- -- Types -- type Register_Address is new HAL.UInt8; subtype Read_Buffer is SPI_Data_8b (1 .. 6); -- -- Constants -- MPU_RA_ACCEL_XOUT_H : constant Register_Address := 16#3B#; MPU_RA_GYRO_XOUT_H : constant Register_Address := 16#43#; pragma Unreferenced (MPU_RA_GYRO_XOUT_H); MPU_RA_PWR_MGMT_1 : constant Register_Address := 16#6B#; MPU_RA_PWR_MGMT_2 : constant Register_Address := 16#6C#; MPU_RA_USER_CTRL : constant Register_Address := 16#6A#; MPU_RA_WHOAMI : constant Register_Address := 16#75#; MPU_PRODUCT_ID : constant Register_Address := 16#0C#; BIT_H_RESET : constant HAL.UInt8 := 16#80#; MPU_CLK_SEL_PLLGYROZ : constant := 16#03#; BIT_I2C_IF_DIS : constant := 16#10#; SPI_Read_Flag : constant Register_Address := 16#80#; SPI_Write_Flag : constant Register_Address := 16#00#; ----------------------- -- Forward declarations ------------------------- -- procedure IO_Read -- (This : in out Six_Axis_Accelerometer; -- Value : out HAL.UInt8; -- ReadAddr : Register_Address); procedure IO_Write (This : in out Six_Axis_Accelerometer; Value : HAL.UInt8; WriteAddr : Register_Address); procedure IO_Read_Buffer (This : in out Six_Axis_Accelerometer; Value : out Read_Buffer; ReadAddr : Register_Address); procedure IO_Read_Value (This : in out Six_Axis_Accelerometer; Value : out HAL.UInt8; ReadAddr : Register_Address); function fuse (high : HAL.UInt8; low : HAL.UInt8) return Short_Integer with Inline_Always => True; ----------------- -- Package body ----------------- procedure Configure (this : in out Six_Axis_Accelerometer) is begin IO_Write (this, BIT_H_RESET, MPU_RA_PWR_MGMT_1); -- reset delay until Clock + Milliseconds (15); IO_Write (this, MPU_CLK_SEL_PLLGYROZ, MPU_RA_PWR_MGMT_1); -- wake up, use Z-axis delay until Clock + Milliseconds (15); IO_Write (this, BIT_I2C_IF_DIS, MPU_RA_USER_CTRL); -- disable i2c delay until Clock + Milliseconds (15); IO_Write (this, 0, MPU_RA_PWR_MGMT_2); -- enable all sensors delay until Clock + Milliseconds (15); -- TODO: setup sample rate and others end Configure; function Read (this : in out Six_Axis_Accelerometer) return Acc_Data is buffer : Read_Buffer; d : Acc_Data := Acc_Data'(others => <>); begin IO_Read_Buffer (this, buffer, MPU_RA_ACCEL_XOUT_H); -- burst read d.Xacc := fuse (buffer (1), buffer (2)); d.Yacc := fuse (buffer (3), buffer (4)); d.Zacc := fuse (buffer (5), buffer (6)); return d; end Read; function Id (this : in out Six_Axis_Accelerometer; product : out Unsigned_8) return Unsigned_8 is buffer : HAL.UInt8; device : Unsigned_8; begin IO_Read_Value (this, buffer, MPU_RA_WHOAMI); device := Unsigned_8 (buffer); IO_Read_Value (this, buffer, MPU_PRODUCT_ID); product := Unsigned_8 (buffer); return device; end Id; ---------- -- Private ---------- procedure IO_Read_Buffer (This : in out Six_Axis_Accelerometer; Value : out Read_Buffer; ReadAddr : Register_Address) is Data : SPI_Data_8b (1 .. Read_Buffer'Length); Status : SPI_Status; begin This.Chip_Select.Clear; This.Port.Transmit (SPI_Data_8b'(1 => HAL.UInt8 (ReadAddr or SPI_Read_Flag)), Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; This.Port.Receive (Data, Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; This.Chip_Select.Set; Value (1 .. 6) := Data (1 .. 6); end IO_Read_Buffer; procedure IO_Read_Value (This : in out Six_Axis_Accelerometer; Value : out HAL.UInt8; ReadAddr : Register_Address) is Data : SPI_Data_8b (1 .. 1); Status : SPI_Status; begin This.Chip_Select.Clear; This.Port.Transmit (SPI_Data_8b'(1 => HAL.UInt8 (ReadAddr or SPI_Read_Flag)), Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; This.Port.Receive (Data, Status); This.Chip_Select.Set; if Status /= Ok then -- No error handling... raise Program_Error; end if; Value := Data (1); end IO_Read_Value; procedure IO_Write (This : in out Six_Axis_Accelerometer; Value : HAL.UInt8; WriteAddr : Register_Address) is Status : SPI_Status; begin This.Chip_Select.Clear; This.Port.Transmit (SPI_Data_8b'(HAL.UInt8 (WriteAddr or SPI_Write_Flag), Value), Status); This.Chip_Select.Set; if Status /= Ok then -- No error handling... raise Program_Error; end if; end IO_Write; ------------------------------------- -- Utils ------------------------------------- function fuse (high : HAL.UInt8; low : HAL.UInt8) return Short_Integer is --------------------- -- Uint16_To_Int16 -- --------------------- function Uint16_To_Int16 is new Ada.Unchecked_Conversion (HAL.UInt16, Short_Integer); reg : HAL.UInt16; begin reg := HAL.Shift_Left (HAL.UInt16 (high), 8); reg := reg or HAL.UInt16 (low); return Uint16_To_Int16 (reg); end fuse; end mpu6000_spi;
generic type Element_Type is private; with function To_String (E : Element_Type) return String is <>; package Nestable_Lists is type Node_Kind is (Data_Node, List_Node); type Node (Kind : Node_Kind); type List is access Node; type Node (Kind : Node_Kind) is record Next : List; case Kind is when Data_Node => Data : Element_Type; when List_Node => Sublist : List; end case; end record; procedure Append (L : in out List; E : Element_Type); procedure Append (L : in out List; N : List); function Flatten (L : List) return List; function New_List (E : Element_Type) return List; function New_List (N : List) return List; function To_String (L : List) return String; end Nestable_Lists;
date Span1 Span2 Max_%_DIFF ------ ----------------------- ----------------------- ----------------------- 200601 +0.400177086687482E+01 -0.999000000000000E+03 -0.999000000000000E+03 200602 +0.403293150539614E+01 -0.999000000000000E+03 -0.999000000000000E+03 200603 +0.403250875904038E+01 -0.999000000000000E+03 -0.999000000000000E+03 200604 +0.409031325980275E+01 -0.999000000000000E+03 -0.999000000000000E+03 200605 +0.407424930908470E+01 -0.999000000000000E+03 -0.999000000000000E+03 200606 +0.407979862577998E+01 -0.999000000000000E+03 -0.999000000000000E+03 200607 +0.405890686636463E+01 -0.999000000000000E+03 -0.999000000000000E+03 200608 +0.405236401086809E+01 -0.999000000000000E+03 -0.999000000000000E+03 200609 +0.403763181450888E+01 -0.999000000000000E+03 -0.999000000000000E+03 200610 +0.408109826446896E+01 -0.999000000000000E+03 -0.999000000000000E+03 200611 +0.406342876611541E+01 -0.999000000000000E+03 -0.999000000000000E+03 200612 +0.403571410731750E+01 -0.999000000000000E+03 -0.999000000000000E+03 200701 +0.407622185852291E+01 +0.407211449361677E+01 +0.100865653767406E+00 200702 +0.410462719412808E+01 +0.411052327094982E+01 +0.143644636720724E+00 200703 +0.415082786302502E+01 +0.415472830744045E+01 +0.939678672339174E-01 200704 +0.412674840517745E+01 +0.414258204661646E+01 +0.383683226705661E+00 200705 +0.407095590197579E+01 +0.407587608624340E+01 +0.120860662362625E+00 200706 +0.414381827940928E+01 +0.414831823458504E+01 +0.108594413951945E+00 200707 +0.413682020121248E+01 +0.413459497441349E+01 +0.538197045358893E-01 200708 +0.420380141514984E+01 +0.420439843534846E+01 +0.142019124993247E-01 200709 +0.419797438633135E+01 +0.418714664797677E+01 +0.258594677112986E+00 200710 +0.423061119434792E+01 +0.423232771015896E+01 +0.405737074902313E-01 200711 +0.425415133951528E+01 +0.425026370449776E+01 +0.914680896952941E-01 200712 +0.421421645767325E+01 +0.420094008495632E+01 +0.316033374636241E+00 200801 +0.426271842855932E+01 +0.426010850273107E+01 +0.612643041035973E-01 200802 +0.427304611081651E+01 +0.427847620709897E+01 +0.127077877037601E+00 200803 +0.423874910060437E+01 +0.424211914298779E+01 +0.795055876965768E-01 200804 +0.424973594670002E+01 +0.426224940306001E+01 +0.294452561686819E+00 200805 +0.425795596805325E+01 +0.426183006693008E+01 +0.909849445579118E-01 200806 +0.418718554779022E+01 +0.418995285412939E+01 +0.660898903949083E-01 200807 +0.419523598983632E+01 +0.419329774090868E+01 +0.462225448180455E-01 200808 +0.422685090834647E+01 +0.422770624963327E+01 +0.202358991446825E-01 200809 +0.417593973131885E+01 +0.416694153424039E+01 +0.215942484542046E+00 200810 +0.416815744106374E+01 +0.416906772923186E+01 +0.218391023129107E-01 200811 +0.419719794448942E+01 +0.419376907370012E+01 +0.817610776614963E-01 200812 +0.425870432994471E+01 +0.424867819926883E+01 +0.235982350407341E+00 200901 +0.421692077642073E+01 +0.421495830061724E+01 +0.465597916639707E-01 200902 +0.422414737129719E+01 +0.422858631484937E+01 +0.105084959448674E+00 200903 +0.415526223235325E+01 +0.415815023635555E+01 +0.695023283925355E-01 200904 +0.419645028108437E+01 +0.420599459537100E+01 +0.227437802126627E+00 200905 +0.420599991727088E+01 +0.420899605636290E+01 +0.712348823336213E-01 200906 +0.423054341447289E+01 +0.423225841784568E+01 +0.405386070952957E-01 200907 +0.425350180402092E+01 +0.425222650232321E+01 +0.299913867948675E-01 200908 +0.420962556349451E+01 +0.421073198732276E+01 +0.262831886484848E-01 200909 +0.417333759055983E+01 +0.416658708497356E+01 +0.162015228497524E+00 200910 +0.422169432934356E+01 +0.422251813567047E+01 +0.195136422167368E-01 200911 +0.423961279136371E+01 +0.423641055253897E+01 +0.755884913660187E-01 200912 +0.421685448807818E+01 +0.420893036745998E+01 +0.188269225821777E+00 201001 +0.423019143500906E+01 +0.422836713428684E+01 +0.431443312343568E-01 201002 +0.423753094397226E+01 +0.424083972290916E+01 +0.780827085549040E-01 201003 +0.425509986361891E+01 +0.425831260491510E+01 +0.755033113007450E-01 201004 +0.421760083690443E+01 +0.422497689341663E+01 +0.174887496409432E+00 201005 +0.425146971288364E+01 +0.425347965299344E+01 +0.472763596013897E-01 201006 +0.418173873716758E+01 +0.418253969667876E+01 +0.191537434909523E-01 201007 +0.423590817351023E+01 +0.423459218878190E+01 +0.310770121340078E-01 201008 +0.419984350075818E+01 +0.420137793296968E+01 +0.365354616481663E-01 201009 +0.422321254194358E+01 +0.421916483365959E+01 +0.959362443413356E-01 201010 +0.426308936829678E+01 +0.426384310423751E+01 +0.176805099684096E-01 201011 +0.418654503523812E+01 +0.418341437820977E+01 +0.748349731897538E-01 201012 +0.423827839061830E+01 +0.423181052247005E+01 +0.152839266170171E+00 201101 +0.427732543872574E+01 +0.427527661217331E+01 +0.479226664913978E-01 201102 +0.425846332498751E+01 +0.426047752599831E+01 +0.472987755697136E-01 201103 +0.430440174528642E+01 +0.430770919965536E+01 +0.768388864391112E-01 201104 +0.429317357126432E+01 +0.429875010610753E+01 +0.129893067462776E+00 201105 +0.427905186352099E+01 +0.427993791319480E+01 +0.207066822759278E-01 201106 +0.429959370740035E+01 +0.430004037052768E+01 +0.103884961633258E-01 201107 +0.429062949519925E+01 +0.428907366903426E+01 +0.362741767814307E-01 201108 +0.429481852562772E+01 +0.429738768720076E+01 +0.598200263344159E-01 201109 +0.429799315892971E+01 +0.429677062165997E+01 +0.284524676179919E-01 201110 +0.423139357269410E+01 +0.423210413403787E+01 +0.167926081930745E-01 201111 +0.423534144337014E+01 +0.423306275892167E+01 +0.538306322926790E-01 201112 +0.426286073988643E+01 +0.425781754404295E+01 +0.118445560226915E+00 201201 +0.425615282665335E+01 +0.425354790928385E+01 +0.612410492383024E-01 201202 +0.428593511628901E+01 +0.428666099193484E+01 +0.169362257275397E-01 201203 +0.433063409312922E+01 +0.433324530668335E+01 +0.602963330075282E-01 201204 +0.428992095391641E+01 +0.429366999263606E+01 +0.873917901966723E-01 201205 +0.430716937173337E+01 +0.430660668693150E+01 +0.130656185431864E-01 201206 +0.435333179330169E+01 +0.435302461767911E+01 +0.705660200785696E-02 201207 +0.430417776079816E+01 +0.430200068006757E+01 +0.506062386432854E-01 201208 +0.434605792518777E+01 +0.434951854522784E+01 +0.796266432624690E-01 201209 +0.434658700865401E+01 +0.434782438934919E+01 +0.284678689906031E-01 201210 +0.427087719822791E+01 +0.427250124457463E+01 +0.380260604869949E-01 201211 +0.432479337467344E+01 +0.432436422949609E+01 +0.992389064770107E-02 201212 +0.434733177123748E+01 +0.434388740166752E+01 +0.792923308426043E-01 201301 +0.432900000053619E+01 +0.432619448611208E+01 +0.648494752863117E-01 201302 +0.434629041796550E+01 +0.434591367873457E+01 +0.866881532366247E-02 201303 +0.435720467853142E+01 +0.435858456557763E+01 +0.316690894280064E-01 201304 +0.435876256811412E+01 +0.436093204410878E+01 +0.497727499663585E-01 201305 +0.440992839868843E+01 +0.440759433198933E+01 +0.529555699389663E-01 201306 +0.439232774337973E+01 +0.439044827418618E+01 +0.428081388546624E-01 201307 +0.440420306649623E+01 +0.440117592724913E+01 +0.687802373080478E-01 201308 +0.438732420401902E+01 +0.439140910713492E+01 +0.931069354791963E-01 201309 +0.439940691806653E+01 +0.440278152208754E+01 +0.767058852218161E-01 201310 +0.441963646242237E+01 +0.442333283326307E+01 +0.836351784164293E-01 201311 +0.448943669903865E+01 +0.449096259520509E+01 +0.339885885184914E-01 201312 +0.446742504037325E+01 +0.446526586526067E+01 +0.483549060177223E-01 201401 +0.441808649236953E+01 +0.441544342805407E+01 +0.598595443136565E-01 201402 +0.441595031279575E+01 +0.441470706992056E+01 +0.281613899972602E-01 201403 +0.436913960192864E+01 +0.436959619612832E+01 +0.104504374150953E-01 201404 +0.438035503218889E+01 +0.438155246773323E+01 +0.273364952280264E-01 201405 +0.446857612717161E+01 +0.446380280335275E+01 +0.106934020814678E+00 201406 +0.448323043984091E+01 +0.447924760556162E+01 +0.889174841405382E-01 201407 +0.449475393706075E+01 +0.449060013790422E+01 +0.924998670326416E-01 201408 +0.451733337747493E+01 +0.452226204175646E+01 +0.109105613194313E+00 201409 +0.456071001603758E+01 +0.456621417570458E+01 +0.120686464336614E+00 201410 +0.460273248179820E+01 +0.460846248509673E+01 +0.124491339029327E+00 201411 +0.456679284814120E+01 +0.456918059374680E+01 +0.522849554381193E-01 201412 +0.457384219002551E+01 +0.457204651886820E+01 +0.392749975289892E-01 201501 +0.459712664360307E+01 +0.459465903240609E+01 +0.537060787225314E-01 201502 +0.454926736635957E+01 +0.454781652210985E+01 +0.319019961045076E-01 201503 +0.456460718659786E+01 +0.456568383042552E+01 +0.235867794019008E-01 201504 +0.459035097907719E+01 +0.459208146539282E+01 +0.376983442773765E-01 201505 +0.457181161978722E+01 +0.456450876608430E+01 +0.159992105989261E+00 201506 +0.455702402388089E+01 +0.455099408758692E+01 +0.132497124318679E+00 201507 +0.462550802856231E+01 +0.461988137906286E+01 +0.121792077280284E+00 201508 +0.460708374638325E+01 +0.461314858399064E+01 +0.131641575045192E+00 201509 +0.469780581146924E+01 +0.470484432012950E+01 +0.149825449214590E+00 201510 +0.474799193441976E+01 +0.475457839064608E+01 +0.138720880685832E+00 201511 +0.471011393911242E+01 +0.471256227901462E+01 +0.519804814458759E-01 201512 +0.464976105851698E+01 +0.464778989306272E+01 +0.424108124421545E-01 201601 +0.461080599073100E+01 +0.460820549946516E+01 +0.564317556180404E-01 201602 +0.458471067269073E+01 +0.458370609326705E+01 +0.219163140752120E-01 201603 +0.459883681770920E+01 +0.460147372206645E+01 +0.573385067088868E-01 201604 +0.460490172842070E+01 +0.460783832961026E+01 +0.637712021395271E-01 201605 +0.450823587478915E+01 +0.449908060123555E+01 +0.203492099054342E+00 201606 +0.454660181729579E+01 +0.453926342125026E+01 +0.161664908257616E+00 201607 +0.449819012063277E+01 +0.449118483772191E+01 +0.155978503757517E+00 201608 +0.449373392815489E+01 +0.450164127787833E+01 +0.175963905515072E+00 201609 +0.446872758573416E+01 +0.447654688752965E+01 +0.174978260488568E+00 201610 +0.438230048187462E+01 +0.438828712857640E+01 +0.136609680840947E+00 201611 +0.439244161921969E+01 +0.439388487459234E+01 +0.328577018835862E-01 201612 +0.443611412139636E+01 +0.443335227063915E+01 +0.622971193942208E-01 201701 +0.447342384840748E+01 +0.447033267472849E+01 +0.691486272702662E-01 201702 +0.448224760380364E+01 +0.448188814996725E+01 +0.802014294803106E-02 201703 +0.448209662022086E+01 +0.448621592798548E+01 +0.919058225124490E-01 201704 +0.448509072930170E+01 +0.448885810895692E+01 +0.839978471472182E-01 201705 +0.452296564810287E+01 +0.451192270002640E+01 +0.244750382722638E+00 201706 -0.999000000000000E+03 +0.451931799245259E+01 -0.999000000000000E+03 201707 -0.999000000000000E+03 +0.451722913647596E+01 -0.999000000000000E+03 201708 -0.999000000000000E+03 +0.444371892198911E+01 -0.999000000000000E+03 201709 -0.999000000000000E+03 +0.446506690390590E+01 -0.999000000000000E+03 201710 -0.999000000000000E+03 +0.446926288793659E+01 -0.999000000000000E+03 201711 -0.999000000000000E+03 +0.448514967666187E+01 -0.999000000000000E+03 201712 -0.999000000000000E+03 +0.450107985706563E+01 -0.999000000000000E+03 201801 -0.999000000000000E+03 +0.451057587328543E+01 -0.999000000000000E+03 201802 -0.999000000000000E+03 +0.449280374996073E+01 -0.999000000000000E+03 201803 -0.999000000000000E+03 +0.447716854264948E+01 -0.999000000000000E+03 201804 -0.999000000000000E+03 +0.449422486792335E+01 -0.999000000000000E+03 201805 -0.999000000000000E+03 +0.456363976107174E+01 -0.999000000000000E+03
pragma License (Unrestricted); with Ada.Text_IO.Editing; package Ada.Wide_Wide_Text_IO.Editing is -- modified -- type Picture is private; subtype Picture is Text_IO.Editing.Picture; function Valid ( Pic_String : String; Blank_When_Zero : Boolean := False) return Boolean renames Text_IO.Editing.Valid; function To_Picture ( Pic_String : String; Blank_When_Zero : Boolean := False) return Picture renames Text_IO.Editing.To_Picture; function Pic_String (Pic : Picture) return String renames Text_IO.Editing.Pic_String; function Blank_When_Zero (Pic : Picture) return Boolean renames Text_IO.Editing.Blank_When_Zero; Max_Picture_Length : constant := 30; -- implementation_defined Picture_Error : exception renames Text_IO.Editing.Picture_Error; Default_Currency : constant Wide_Wide_String := "$"; Default_Fill : constant Wide_Wide_Character := '*'; Default_Separator : constant Wide_Wide_Character := ','; Default_Radix_Mark : constant Wide_Wide_Character := '.'; generic type Num is delta <> digits <>; Default_Currency : Wide_Wide_String := Editing.Default_Currency; Default_Fill : Wide_Wide_Character := Editing.Default_Fill; Default_Separator : Wide_Wide_Character := Editing.Default_Separator; Default_Radix_Mark : Wide_Wide_Character := Editing.Default_Radix_Mark; package Decimal_Output is -- for renaming package Strings is new Text_IO.Editing.Decimal_Output (Num); function Length ( Pic : Picture; Currency : Wide_Wide_String := Default_Currency) return Natural renames Strings.Overloaded_Length; function Valid ( Item : Num; Pic : Picture; Currency : Wide_Wide_String := Default_Currency) return Boolean renames Strings.Overloaded_Valid; function Image ( Item : Num; Pic : Picture; Currency : Wide_Wide_String := Default_Currency; Fill : Wide_Wide_Character := Default_Fill; Separator : Wide_Wide_Character := Default_Separator; Radix_Mark : Wide_Wide_Character := Default_Radix_Mark) return Wide_Wide_String renames Strings.Overloaded_Image; procedure Put ( File : File_Type; -- Output_File_Type Item : Num; Pic : Picture; Currency : Wide_Wide_String := Default_Currency; Fill : Wide_Wide_Character := Default_Fill; Separator : Wide_Wide_Character := Default_Separator; Radix_Mark : Wide_Wide_Character := Default_Radix_Mark) renames Strings.Overloaded_Put; procedure Put ( Item : Num; Pic : Picture; Currency : Wide_Wide_String := Default_Currency; Fill : Wide_Wide_Character := Default_Fill; Separator : Wide_Wide_Character := Default_Separator; Radix_Mark : Wide_Wide_Character := Default_Radix_Mark) renames Strings.Overloaded_Put; procedure Put ( To : out Wide_Wide_String; Item : Num; Pic : Picture; Currency : Wide_Wide_String := Default_Currency; Fill : Wide_Wide_Character := Default_Fill; Separator : Wide_Wide_Character := Default_Separator; Radix_Mark : Wide_Wide_Character := Default_Radix_Mark) renames Strings.Overloaded_Put; end Decimal_Output; end Ada.Wide_Wide_Text_IO.Editing;
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T F I N D -- -- -- -- B o d y -- -- -- -- Copyright (C) 1998-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Opt; with Osint; use Osint; with Switch; use Switch; with Types; use Types; with Xr_Tabls; with Xref_Lib; use Xref_Lib; with Ada.Command_Line; use Ada.Command_Line; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Text_IO; use Ada.Text_IO; with GNAT.Command_Line; use GNAT.Command_Line; with System.Strings; use System.Strings; -------------- -- Gnatfind -- -------------- procedure Gnatfind is Output_Ref : Boolean := False; Pattern : Xref_Lib.Search_Pattern; Local_Symbols : Boolean := True; Prj_File : File_Name_String; Prj_File_Length : Natural := 0; Nb_File : Natural := 0; Usage_Error : exception; Full_Path_Name : Boolean := False; Have_Entity : Boolean := False; Wide_Search : Boolean := True; Glob_Mode : Boolean := True; Der_Info : Boolean := False; Type_Tree : Boolean := False; Read_Only : Boolean := False; Source_Lines : Boolean := False; Has_File_In_Entity : Boolean := False; -- Will be true if a file name was specified in the entity RTS_Specified : String_Access := null; -- Used to detect multiple use of --RTS= switch EXT_Specified : String_Access := null; -- Used to detect multiple use of --ext= switch procedure Parse_Cmd_Line; -- Parse every switch on the command line procedure Usage; -- Display the usage procedure Write_Usage; pragma No_Return (Write_Usage); -- Print a small help page for program usage and exit program -------------------- -- Parse_Cmd_Line -- -------------------- procedure Parse_Cmd_Line is procedure Check_Version_And_Help is new Check_Version_And_Help_G (Usage); -- Start of processing for Parse_Cmd_Line begin -- First check for --version or --help Check_Version_And_Help ("GNATFIND", "1998"); -- Now scan the other switches GNAT.Command_Line.Initialize_Option_Scan; loop case GNAT.Command_Line.Getopt ("a aI: aO: d e f g h I: nostdinc nostdlib p: r s t -RTS= -ext=") is when ASCII.NUL => exit; when 'a' => if GNAT.Command_Line.Full_Switch = "a" then Read_Only := True; elsif GNAT.Command_Line.Full_Switch = "aI" then Osint.Add_Src_Search_Dir (GNAT.Command_Line.Parameter); else Osint.Add_Lib_Search_Dir (GNAT.Command_Line.Parameter); end if; when 'd' => Der_Info := True; when 'e' => Glob_Mode := False; when 'f' => Full_Path_Name := True; when 'g' => Local_Symbols := False; when 'h' => Write_Usage; when 'I' => Osint.Add_Src_Search_Dir (GNAT.Command_Line.Parameter); Osint.Add_Lib_Search_Dir (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nostdinc" then Opt.No_Stdinc := True; elsif GNAT.Command_Line.Full_Switch = "nostdlib" then Opt.No_Stdlib := True; end if; when 'p' => declare S : constant String := GNAT.Command_Line.Parameter; begin Prj_File_Length := S'Length; Prj_File (1 .. Prj_File_Length) := S; end; when 'r' => Output_Ref := True; when 's' => Source_Lines := True; when 't' => Type_Tree := True; -- Only switch starting with -- recognized is --RTS when '-' => if GNAT.Command_Line.Full_Switch = "-RTS" then -- Check that it is the first time we see this switch if RTS_Specified = null then RTS_Specified := new String'(GNAT.Command_Line.Parameter); elsif RTS_Specified.all /= GNAT.Command_Line.Parameter then Osint.Fail ("--RTS cannot be specified multiple times"); end if; Opt.No_Stdinc := True; Opt.RTS_Switch := True; declare Src_Path_Name : constant String_Ptr := Get_RTS_Search_Dir (GNAT.Command_Line.Parameter, Include); Lib_Path_Name : constant String_Ptr := Get_RTS_Search_Dir (GNAT.Command_Line.Parameter, Objects); begin if Src_Path_Name /= null and then Lib_Path_Name /= null then Add_Search_Dirs (Src_Path_Name, Include); Add_Search_Dirs (Lib_Path_Name, Objects); elsif Src_Path_Name = null and then Lib_Path_Name = null then Osint.Fail ("RTS path not valid: missing " & "adainclude and adalib directories"); elsif Src_Path_Name = null then Osint.Fail ("RTS path not valid: missing " & "adainclude directory"); elsif Lib_Path_Name = null then Osint.Fail ("RTS path not valid: missing " & "adalib directory"); end if; end; -- Process -ext switch elsif GNAT.Command_Line.Full_Switch = "-ext" then -- Check that it is the first time we see this switch if EXT_Specified = null then EXT_Specified := new String'(GNAT.Command_Line.Parameter); elsif EXT_Specified.all /= GNAT.Command_Line.Parameter then Osint.Fail ("--ext cannot be specified multiple times"); end if; if EXT_Specified'Length = Osint.ALI_Default_Suffix'Length then Osint.ALI_Suffix := EXT_Specified.all'Access; else Osint.Fail ("--ext argument must have 3 characters"); end if; end if; when others => Try_Help; raise Usage_Error; end case; end loop; -- Get the other arguments loop declare S : constant String := GNAT.Command_Line.Get_Argument; begin exit when S'Length = 0; -- First argument is the pattern if not Have_Entity then Add_Entity (Pattern, S, Glob_Mode); Have_Entity := True; if not Has_File_In_Entity and then Index (S, ":") /= 0 then Has_File_In_Entity := True; end if; -- Next arguments are the files to search else Add_Xref_File (S); Wide_Search := False; Nb_File := Nb_File + 1; end if; end; end loop; exception when GNAT.Command_Line.Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid switch : " & GNAT.Command_Line.Full_Switch); Try_Help; raise Usage_Error; when GNAT.Command_Line.Invalid_Parameter => Ada.Text_IO.Put_Line ("Parameter missing for : " & GNAT.Command_Line.Full_Switch); Try_Help; raise Usage_Error; when Xref_Lib.Invalid_Argument => Ada.Text_IO.Put_Line ("Invalid line or column in the pattern"); Try_Help; raise Usage_Error; end Parse_Cmd_Line; ----------- -- Usage -- ----------- procedure Usage is begin Put_Line ("Usage: gnatfind pattern[:sourcefile[:line[:column]]] " & "[file1 file2 ...]"); New_Line; Put_Line (" pattern Name of the entity to look for (can have " & "wildcards)"); Put_Line (" sourcefile Only find entities referenced from this " & "file"); Put_Line (" line Only find entities referenced from this line " & "of file"); Put_Line (" column Only find entities referenced from this columns" & " of file"); Put_Line (" file ... Set of Ada source files to search for " & "references. This parameters are optional"); New_Line; Put_Line ("gnatfind switches:"); Display_Usage_Version_And_Help; Put_Line (" -a Consider all files, even when the ali file is " & "readonly"); Put_Line (" -aIdir Specify source files search path"); Put_Line (" -aOdir Specify library/object files search path"); Put_Line (" -d Output derived type information"); Put_Line (" -e Use the full regular expression set for " & "pattern"); Put_Line (" -f Output full path name"); Put_Line (" -g Output information only for global symbols"); Put_Line (" -Idir Like -aIdir -aOdir"); Put_Line (" -nostdinc Don't look for sources in the system default" & " directory"); Put_Line (" -nostdlib Don't look for library files in the system" & " default directory"); Put_Line (" --ext=xxx Specify alternate ali file extension"); Put_Line (" --RTS=dir specify the default source and object search" & " path"); Put_Line (" -p file Use file as the configuration file"); Put_Line (" -r Find all references (default to find declaration" & " only)"); Put_Line (" -s Print source line"); Put_Line (" -t Print type hierarchy"); end Usage; ----------------- -- Write_Usage -- ----------------- procedure Write_Usage is begin Display_Version ("GNATFIND", "1998"); New_Line; Usage; raise Usage_Error; end Write_Usage; -- Start of processing for Gnatfind begin Parse_Cmd_Line; if not Have_Entity then if Argument_Count = 0 then Write_Usage; else Try_Help; raise Usage_Error; end if; end if; -- Special case to speed things up: if the user has a command line of the -- form 'gnatfind entity:file', i.e. has specified a file and only wants -- the bodies and specs, then we can restrict the search to the .ali file -- associated with 'file'. if Has_File_In_Entity and then not Output_Ref then Wide_Search := False; end if; -- Find the project file if Prj_File_Length = 0 then Xr_Tabls.Create_Project_File (Default_Project_File (".")); else Xr_Tabls.Create_Project_File (Prj_File (1 .. Prj_File_Length)); end if; -- Fill up the table if Type_Tree and then Nb_File > 1 then Ada.Text_IO.Put_Line ("Error: for type hierarchy output you must " & "specify only one file."); Ada.Text_IO.New_Line; Try_Help; raise Usage_Error; end if; Search (Pattern, Local_Symbols, Wide_Search, Read_Only, Der_Info, Type_Tree); if Source_Lines then Xr_Tabls.Grep_Source_Files; end if; Print_Gnatfind (Output_Ref, Full_Path_Name); exception when Usage_Error => null; end Gnatfind;
-- -- Copyright 2018 The wookey project team <wookey@ssi.gouv.fr> -- - Ryad Benadjila -- - Arnauld Michelizza -- - Mathieu Renard -- - Philippe Thierry -- - Philippe Trebuchet -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- with ewok.perm; use ewok.perm; with ewok.exported.devices; use ewok.exported.devices; with ewok.exported.interrupts; use ewok.exported.interrupts; with ewok.exported.gpios; use ewok.exported.gpios; with ewok.interrupts; use ewok.interrupts; with ewok.sanitize; with ewok.gpio; with ewok.exti; with ewok.debug; with ewok.devices.perms; with soc.devmap; use soc.devmap; with soc.interrupts; use soc.interrupts; with soc.nvic; with soc.gpio; with soc.rcc; with types.c; package body ewok.devices with spark_mode => off is --pragma debug_policy (IGNORE); function get_task_from_id (dev_id : t_registered_device_id) return t_task_id is begin return registered_device(dev_id).task_id; end get_task_from_id; function get_user_device (dev_id : t_registered_device_id) return t_checked_user_device_access is begin return registered_device(dev_id).udev'access; end get_user_device; function get_device_size (dev_id : t_registered_device_id) return unsigned_32 is begin -- Pure GPIO devices are registed has 'NO_PERIPH', has they are -- not a SoC local mappable peripheral but pure IO. -- These devices have no size (e.g. LEDs, Buttons....) if registered_device(dev_id).periph_id /= NO_PERIPH then return soc.devmap.periphs(registered_device(dev_id).periph_id).size; else return 0; end if; end get_device_size; function get_device_addr (dev_id : t_registered_device_id) return system_address is begin -- Pure GPIO devices are registed has 'NO_PERIPH', has they are -- not a SoC local mappable peripheral but pure IO. -- These devices have no address (e.g. LEDs, Buttons....) if registered_device(dev_id).periph_id /= NO_PERIPH then return soc.devmap.periphs(registered_device(dev_id).periph_id).addr; else return 0; end if; end get_device_addr; function is_device_region_ro (dev_id : t_registered_device_id) return boolean is begin return soc.devmap.periphs(registered_device(dev_id).periph_id).ro; end is_device_region_ro; function get_device_subregions_mask (dev_id : t_registered_device_id) return unsigned_8 is begin return soc.devmap.periphs(registered_device(dev_id).periph_id).subregions; end get_device_subregions_mask; function get_interrupt_config_from_interrupt (interrupt : soc.interrupts.t_interrupt) return ewok.exported.interrupts.t_interrupt_config_access is dev_id : t_device_id; begin -- Retrieving the dev_id from the interrupt dev_id := ewok.interrupts.get_device_from_interrupt (interrupt); if dev_id = ID_DEV_UNUSED then return NULL; end if; -- Looking at each interrupts configured for this device -- to retrieve the proper interrupt configuration informations for i in 1 .. registered_device(dev_id).udev.interrupt_num loop if registered_device(dev_id).udev.interrupts(i).interrupt = interrupt then return registered_device(dev_id).udev.interrupts(i)'access; end if; end loop; return NULL; end get_interrupt_config_from_interrupt; ------------------------ -- Device registering -- ------------------------ procedure get_registered_device_entry (dev_id : out t_device_id; success : out boolean) is begin for id in registered_device'range loop if registered_device(id).status = DEV_STATE_UNUSED then registered_device(id).status := DEV_STATE_RESERVED; dev_id := id; success := true; return; end if; end loop; dev_id := ID_DEV_UNUSED; success := false; end get_registered_device_entry; procedure release_registered_device_entry (dev_id : t_registered_device_id) is begin registered_device(dev_id).status := DEV_STATE_UNUSED; registered_device(dev_id).task_id := ID_UNUSED; registered_device(dev_id).periph_id := NO_PERIPH; -- FIXME initialize registered_device(dev_id).udev with 0 values end release_registered_device_entry; procedure register_device (task_id : in t_task_id; udev : in ewok.exported.devices.t_user_device_access; dev_id : out t_device_id; success : out boolean) is periph_id: soc.devmap.t_periph_id; len : constant natural := types.c.len (udev.all.name); name : string (1 .. len); found : boolean; begin -- Convert C name to Ada string type for further log messages types.c.to_ada (name, udev.all.name); -- Is it an existing device ? -- Note: GPIOs (size = 0) are not considered as devices despite a task -- can register them. Thus, we don't look for them in soc.devmap.periphs -- table. if udev.all.size /= 0 then periph_id := soc.devmap.find_periph (udev.all.base_addr, udev.all.size); if periph_id = NO_PERIPH then pragma DEBUG (debug.log (debug.ERROR, "Device not existing: " & name)); success := false; return; end if; end if; -- Is it already used ? -- Note: GPIOs alone are not considered as devices. When the user -- declares lone GPIOs, periph_id is NO_PERIPH for id in registered_device'range loop if registered_device(id).status /= DEV_STATE_UNUSED and then registered_device(id).periph_id /= NO_PERIPH and then registered_device(id).periph_id = periph_id then pragma DEBUG (debug.log (debug.ERROR, "Device already used: " & name)); success := false; return; end if; end loop; -- Are the GPIOs already used ? for i in 1 .. udev.gpio_num loop if ewok.gpio.is_used (udev.gpios(i).kref) then pragma DEBUG (debug.log (debug.ERROR, "GPIOs already used: " & name)); success := false; return; end if; end loop; -- Are the related EXTIs already used ? for i in 1 .. udev.gpio_num loop if boolean (udev.gpios(i).settings.set_exti) and then ewok.exti.is_used (udev.gpios(i).kref) then pragma DEBUG (debug.log (debug.ERROR, "EXTIs already used: " & name)); success := false; return; end if; end loop; -- We verify that the interrupts declared by this device really belong -- to it for declared_it in 1 .. udev.interrupt_num loop found := false; inner_loop: for i in soc.devmap.periphs(periph_id).interrupt_list'range loop if soc.devmap.periphs(periph_id).interrupt_list(i) = udev.interrupts(declared_it).interrupt then found := true; exit inner_loop; end if; end loop inner_loop; if not found then pragma DEBUG (debug.log (debug.ERROR, "Invalid interrupts: " & name)); success := false; return; end if; end loop; -- Is it possible to register interrupt handlers ? for i in 1 .. udev.interrupt_num loop if ewok.interrupts.is_interrupt_already_used (udev.interrupts(i).interrupt) then pragma DEBUG (debug.log (debug.ERROR, "Interrupts already used: " & name)); success := false; return; end if; end loop; -- Is it possible to register a device ? get_registered_device_entry (dev_id, success); if not success then pragma DEBUG (debug.log (debug.ERROR, "register_device(): no free slot!")); return; end if; -- Registering the device pragma DEBUG (debug.log (debug.INFO, "Registered device: " & name)); registered_device(dev_id).udev := t_checked_user_device (udev.all); registered_device(dev_id).task_id := task_id; registered_device(dev_id).periph_id := periph_id; registered_device(dev_id).status := DEV_STATE_REGISTERED; -- Registering GPIOs for i in 1 .. udev.gpio_num loop ewok.gpio.register (task_id, dev_id, registered_device(dev_id).udev.gpios(i)'access, success); if not success then raise program_error; end if; pragma DEBUG (debug.log (debug.INFO, "Registered GPIO port" & soc.gpio.t_gpio_port_index'image (udev.gpios(i).kref.port) & " pin " & soc.gpio.t_gpio_pin_index'image (udev.gpios(i).kref.pin))); end loop; -- Registering EXTIs for i in 1 .. udev.gpio_num loop ewok.exti.register (udev.gpios(i)'access, success); if not success then raise program_error; end if; end loop; -- Registering handlers for i in 1 .. udev.interrupt_num loop ewok.interrupts.set_interrupt_handler (udev.interrupts(i).interrupt, udev.interrupts(i).handler, task_id, dev_id, success); if not success then raise program_error; end if; end loop; success := true; end register_device; procedure release_device (task_id : in t_task_id; dev_id : in t_registered_device_id; success : out boolean) is begin -- That device belongs to the task? if registered_device(dev_id).task_id /= task_id then success := false; return; end if; -- Releasing GPIOs and EXTIs for i in 1 .. registered_device(dev_id).udev.gpio_num loop ewok.gpio.release (task_id, dev_id, registered_device(dev_id).udev.gpios(i)'access); ewok.exti.release (registered_device(dev_id).udev.gpios(i)'access); end loop; -- Releasing interrupts for i in 1 .. registered_device(dev_id).udev.interrupt_num loop ewok.interrupts.reset_interrupt_handler (registered_device(dev_id).udev.interrupts(i).interrupt, task_id, dev_id); end loop; -- Releasing the device release_registered_device_entry (dev_id); success := true; end release_device; procedure enable_device (dev_id : in t_registered_device_id; success : out boolean) is irq : soc.nvic.t_irq_index; interrupt : t_interrupt; begin -- Check if the device was already configured -- the device can be registered (first mapping) or enabled (successive (un)mappings) if registered_device(dev_id).status /= DEV_STATE_REGISTERED and registered_device(dev_id).status /= DEV_STATE_ENABLED then raise program_error; end if; -- Configure and enable GPIOs for i in 1 .. registered_device(dev_id).udev.gpio_num loop ewok.gpio.config (registered_device(dev_id).udev.gpios(i)'access); if registered_device(dev_id).udev.gpios(i).exti_trigger /= GPIO_EXTI_TRIGGER_NONE then ewok.exti.enable (registered_device(dev_id).udev.gpios(i).kref); end if; end loop; -- For each interrupt, enable its associated IRQ in the NVIC for i in 1 .. registered_device(dev_id).udev.interrupt_num loop interrupt := registered_device(dev_id).udev.interrupts(i).interrupt; irq := soc.nvic.to_irq_number (interrupt); soc.nvic.enable_irq (irq); pragma DEBUG (debug.log (debug.INFO, "IRQ enabled: " & soc.nvic.t_irq_index'image (irq))); end loop; -- Enable device's clock if registered_device(dev_id).periph_id /= NO_PERIPH then if registered_device(dev_id).status = DEV_STATE_REGISTERED then soc.rcc.enable_clock (registered_device(dev_id).periph_id); end if; pragma DEBUG (debug.log (debug.INFO, "Enabled device: " & soc.devmap.periphs(registered_device(dev_id).periph_id).name)); end if; registered_device(dev_id).status := DEV_STATE_ENABLED; success := true; end enable_device; function sanitize_user_defined_interrupt (udev : in ewok.exported.devices.t_user_device_access; config : in ewok.exported.interrupts.t_interrupt_config; task_id : in t_task_id) return boolean is begin if not ewok.sanitize.is_word_in_txt_slot (to_system_address (config.handler), task_id) then pragma DEBUG (debug.log (debug.ERROR, "Handler not in .text section")); return false; end if; if config.interrupt not in INT_WWDG .. INT_HASH_RNG then pragma DEBUG (debug.log (debug.ERROR, "Interrupt not in range")); return false; end if; if config.mode = ISR_FORCE_MAINTHREAD and then not ewok.perm.ressource_is_granted (PERM_RES_TSK_FISR, task_id) then pragma DEBUG (debug.log (debug.ERROR, "ISR_FORCE_MAINTHREAD not allowed")); return false; end if; -- -- Verify posthooks -- for i in 1 .. MAX_POSTHOOK_INSTR loop if not config.posthook.action(i).instr'valid then pragma DEBUG (debug.log (debug.ERROR, "Posthook: invalid action requested")); return false; end if; case config.posthook.action(i).instr is when POSTHOOK_NIL => null; when POSTHOOK_READ => if config.posthook.action(i).read.offset > udev.all.size - 4 or (config.posthook.action(i).read.offset and 2#11#) > 0 then pragma DEBUG (debug.log (debug.ERROR, "Posthook: wrong READ offset")); return false; end if; when POSTHOOK_WRITE => if config.posthook.action(i).write.offset > udev.all.size - 4 or (config.posthook.action(i).write.offset and 2#11#) > 0 then pragma DEBUG (debug.log (debug.ERROR, "Posthook: wrong WRITE offset")); return false; end if; when POSTHOOK_WRITE_REG => if config.posthook.action(i).write_reg.offset_dest > udev.all.size - 4 or (config.posthook.action(i).write_reg.offset_dest and 2#11#) > 0 or config.posthook.action(i).write_reg.offset_src > udev.all.size - 4 or (config.posthook.action(i).write_reg.offset_src and 2#11#) > 0 then pragma DEBUG (debug.log (debug.ERROR, "Posthook: wrong AND offset")); return false; end if; when POSTHOOK_WRITE_MASK => if config.posthook.action(i).write_mask.offset_dest > udev.all.size - 4 or (config.posthook.action(i).write_mask.offset_dest and 2#11#) > 0 or config.posthook.action(i).write_mask.offset_src > udev.all.size - 4 or (config.posthook.action(i).write_mask.offset_src and 2#11#) > 0 or config.posthook.action(i).write_mask.offset_mask > udev.all.size - 4 or (config.posthook.action(i).write_mask.offset_mask and 2#11#) > 0 then pragma DEBUG (debug.log (debug.ERROR, "Posthook: wrong MASK offset")); return false; end if; end case; end loop; return true; end sanitize_user_defined_interrupt; function sanitize_user_defined_gpio (udev : in ewok.exported.devices.t_user_device_access; config : in ewok.exported.gpios.t_gpio_config; task_id : in t_task_id) return boolean is pragma unreferenced (udev); begin if config.exti_trigger /= GPIO_EXTI_TRIGGER_NONE and then not ewok.perm.ressource_is_granted (PERM_RES_DEV_EXTI, task_id) then pragma DEBUG (debug.log (debug.ERROR, "PERM_RES_DEV_EXTI not allowed")); return false; end if; if config.exti_handler /= 0 and then not ewok.sanitize.is_word_in_txt_slot (config.exti_handler, task_id) then pragma DEBUG (debug.log (debug.ERROR, "EXTI handler not in .text section")); return false; end if; if not config.exti_lock'valid then pragma DEBUG (debug.log (debug.ERROR, "EXTI invalid lock mode")); return false; end if; return true; end sanitize_user_defined_gpio; function sanitize_user_defined_device (udev : in ewok.exported.devices.t_user_device_access; task_id : in t_task_id) return boolean is len : constant natural := types.c.len (udev.all.name); name : string (1 .. natural'min (t_device_name'length, len)); periph_id: soc.devmap.t_periph_id; ok : boolean; begin if udev.all.name(t_device_name'last) /= ASCII.NUL then types.c.to_ada (name, udev.all.name(1 .. t_device_name'length)); pragma DEBUG (debug.log (debug.ERROR, "Out-of-bound device name: " & name)); return false; else types.c.to_ada (name, udev.all.name); end if; if udev.all.size /= 0 then periph_id := soc.devmap.find_periph (udev.all.base_addr, udev.all.size); if periph_id = NO_PERIPH then pragma DEBUG (debug.log (debug.ERROR, "Device at addr" & system_address'image (udev.all.base_addr) & -- " with size" & unsigned_32'image (udev.all.size) & ": not found")); return false; end if; if not ewok.perm.ressource_is_granted (ewok.devices.perms.permissions(periph_id), task_id) then pragma DEBUG (debug.log (debug.ERROR, "No access to device: " & name)); return false; end if; end if; for i in 1 .. udev.all.interrupt_num loop ok := sanitize_user_defined_interrupt (udev, udev.all.interrupts(i), task_id); if not ok then pragma DEBUG (debug.log (debug.ERROR, name & ": invalid udev.interrupts parameter")); return false; end if; end loop; for i in 1 .. udev.all.gpio_num loop ok := sanitize_user_defined_gpio (udev, udev.all.gpios(i), task_id); if not ok then pragma DEBUG (debug.log (debug.ERROR, name & ": invalid udev.gpios parameter")); return false; end if; end loop; if udev.all.map_mode = DEV_MAP_VOLUNTARY then if not ewok.perm.ressource_is_granted (PERM_RES_MEM_DYNAMIC_MAP, task_id) then pragma DEBUG (debug.log (debug.ERROR, name & ": voluntary mapping not permited")); return false; end if; end if; return true; end sanitize_user_defined_device; end ewok.devices;
with STM32GD.Clock; with STM32GD.Clock.Tree; generic Clock : STM32GD.Clock.RTC_Source_Type; with package Clock_Tree is new STM32GD.Clock.Tree (<>); package STM32GD.RTC is subtype Second_Delta_Type is Natural range 0 .. (60 * 60 * 24); subtype Minute_Delta_Type is Natural range 0 .. (60 * 24); type Date_Time_Type is new Natural; procedure Init; procedure Read (Date_Time : out Date_Time_Type); generic with procedure Put (S : String); procedure Print (Date_Time : Date_Time_Type); procedure Add_Seconds (Date_Time : in out Date_Time_Type; Second_Delta : Second_Delta_Type); procedure Add_Minutes (Date_Time : in out Date_Time_Type; Minute_Delta : Minute_Delta_Type); function To_Seconds (Date_Time : Date_Time_Type) return Natural; procedure Set_Alarm (Date_Time : Date_Time_Type); procedure Clear_Alarm; procedure Wait_For_Alarm; function Alarm_Triggered return Boolean; end STM32GD.RTC;
with GL; use GL; with Interfaces.C.Strings; with Glut; use Glut; with ada_sphere_procs; use ada_sphere_procs; procedure ada_sphere is package ICS renames Interfaces.C.Strings; type chars_ptr_ptr is access ICS.chars_ptr; argc : aliased integer; pragma Import (C, argc, "gnat_argc"); argv : chars_ptr_ptr; pragma Import (C, argv, "gnat_argv"); win : Integer; m : Integer; begin glutInit (argc'access, argv); glutInitDisplayMode(GLUT_RGB or GLUT_DEPTH or GLUT_DOUBLE); win := glutCreateWindow("ada_sphere"); glutDisplayFunc(display'access); glutReshapeFunc(reshape'access); init; m := glutCreateMenu(menu'access); glutAddMenuEntry("Quit", 666); glutAttachMenu(GLUT_RIGHT_BUTTON); glutMainLoop; end ada_sphere;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.Holders.Elements; with AMF.Internals.Helpers; with AMF.Internals.Holders.UML_Holders; with AMF.Internals.Tables.MOFEXT_Element_Table; with AMF.Internals.Tables.MOFEXT_Types; with AMF.Internals.Tables.MOF_Metamodel; with AMF.Internals.Tables.UML_Metamodel; with AMF.MOF.Tags; with AMF.UML.Comments.Collections; with AMF.UML.Elements.Collections; with League.Holders; package body AMF.Internals.Tables.MOFEXT_Reflection is --------- -- Get -- --------- function Get (Self : AMF.Internals.AMF_Element; Property : CMOF_Element) return League.Holders.Holder is function MOF_Tag_Get return League.Holders.Holder; -- Returns attribute's value of instance of Tag class. ----------------- -- MOF_Tag_Get -- ----------------- function MOF_Tag_Get return League.Holders.Holder is begin if Property = AMF.Internals.Tables.MOF_Metamodel.MP_MOF_Tag_Element_A_Tag then -- Tag::element : Element return AMF.UML.Elements.Collections.UML_Element_Collections.Internals.To_Holder (AMF.MOF.Tags.MOF_Tag_Access (AMF.Internals.Helpers.To_Element (Self)).Get_Element); elsif Property = AMF.Internals.Tables.MOF_Metamodel.MP_MOF_Tag_Name then -- Tag::name : String return League.Holders.To_Holder (AMF.MOF.Tags.MOF_Tag_Access (AMF.Internals.Helpers.To_Element (Self)).Get_Name); elsif Property = AMF.Internals.Tables.UML_Metamodel.MP_UML_Element_Owned_Comment_A_Owning_Element then -- Element::ownedComment : Comment return AMF.UML.Comments.Collections.UML_Comment_Collections.Internals.To_Holder (AMF.MOF.Tags.MOF_Tag_Access (AMF.Internals.Helpers.To_Element (Self)).Get_Owned_Comment); elsif Property = AMF.Internals.Tables.UML_Metamodel.MP_UML_Element_Owned_Element_Element_Owner then -- Element::ownedElement : Element return AMF.UML.Elements.Collections.UML_Element_Collections.Internals.To_Holder (AMF.MOF.Tags.MOF_Tag_Access (AMF.Internals.Helpers.To_Element (Self)).Get_Owned_Element); elsif Property = AMF.Internals.Tables.UML_Metamodel.MP_UML_Element_Owner_Element_Owned_Element then -- Element::owner : Element return AMF.Internals.Holders.UML_Holders.To_Holder (AMF.UML.Elements.UML_Element_Access' (AMF.MOF.Tags.MOF_Tag_Access (AMF.Internals.Helpers.To_Element (Self)).Get_Owner)); elsif Property = AMF.Internals.Tables.MOF_Metamodel.MP_MOF_Tag_Tag_Owner_A_Owned_Tag then -- Tag::tagOwner : Element return AMF.Internals.Holders.UML_Holders.To_Holder (AMF.UML.Elements.UML_Element_Access' (AMF.MOF.Tags.MOF_Tag_Access (AMF.Internals.Helpers.To_Element (Self)).Get_Tag_Owner)); elsif Property = AMF.Internals.Tables.MOF_Metamodel.MP_MOF_Tag_Value then -- Tag::value : String return League.Holders.To_Holder (AMF.MOF.Tags.MOF_Tag_Access (AMF.Internals.Helpers.To_Element (Self)).Get_Value); else raise Program_Error; end if; end MOF_Tag_Get; begin case AMF.Internals.Tables.MOFEXT_Element_Table.Table (Self).Kind is when AMF.Internals.Tables.MOFEXT_Types.E_None => raise Program_Error; when AMF.Internals.Tables.MOFEXT_Types.E_MOF_Tag => return MOF_Tag_Get; end case; end Get; -------------------- -- Get_Meta_Class -- -------------------- function Get_Meta_Class (Self : AMF.Internals.AMF_Element) return CMOF_Element is begin case MOFEXT_Element_Table.Table (Self).Kind is when AMF.Internals.Tables.MOFEXT_Types.E_None => return 0; when AMF.Internals.Tables.MOFEXT_Types.E_MOF_Tag => return AMF.Internals.Tables.MOF_Metamodel.MC_MOF_Tag; end case; end Get_Meta_Class; --------- -- Set -- --------- procedure Set (Self : AMF.Internals.AMF_Element; Property : CMOF_Element; Value : League.Holders.Holder) is procedure MOF_Tag_Set; -- Sets attribute's value of instance of Tag class. ----------------- -- MOF_Tag_Set -- ----------------- procedure MOF_Tag_Set is begin if Property = AMF.Internals.Tables.MOF_Metamodel.MP_MOF_Tag_Name then -- Tag::name : String AMF.MOF.Tags.MOF_Tag_Access (AMF.Internals.Helpers.To_Element (Self)).Set_Name (League.Holders.Element (Value)); elsif Property = AMF.Internals.Tables.MOF_Metamodel.MP_MOF_Tag_Tag_Owner_A_Owned_Tag then -- Tag::tagOwner : Element AMF.MOF.Tags.MOF_Tag_Access (AMF.Internals.Helpers.To_Element (Self)).Set_Tag_Owner (AMF.UML.Elements.UML_Element_Access (AMF.Holders.Elements.Element (Value))); elsif Property = AMF.Internals.Tables.MOF_Metamodel.MP_MOF_Tag_Value then -- Tag::value : String AMF.MOF.Tags.MOF_Tag_Access (AMF.Internals.Helpers.To_Element (Self)).Set_Value (League.Holders.Element (Value)); else raise Program_Error; end if; end MOF_Tag_Set; begin case MOFEXT_Element_Table.Table (Self).Kind is when AMF.Internals.Tables.MOFEXT_Types.E_None => raise Program_Error; when AMF.Internals.Tables.MOFEXT_Types.E_MOF_Tag => MOF_Tag_Set; end case; end Set; end AMF.Internals.Tables.MOFEXT_Reflection;
with Numerics, Ada.Text_IO; use Numerics, Ada.Text_IO; procedure Forward_AD.Jacobian is use Real_IO, Int_IO; function Func (X : in Real_Array) return AD_Vector is Y : constant AD_Vector := Var (X); Zero : constant Real_Array (X'Range) := (others => 0.0); Result : AD_Vector := Var (Zero); begin Result (1) := Y (1) * Y (2); Result (2) := Y (1) * Y (3); Result (3) := Y (2) * Y (3); -- Result (4) := Y (2) * Y (3); return Result; end Func; procedure Print_AD_Type (X : in AD_Type) is G : Real_Array := Grad (X); begin Put (Val (X), Aft => 4, Exp => 0); for I in G'Range loop Put (", "); Put (G (I), Aft => 4, Exp => 0); end loop; New_Line; end Print_AD_Type; X : Real_Array := (1.0, 2.0, 3.0); Y : AD_Vector (1 .. 3); J : Sparse_Matrix; begin Y := Func (X); J := Jacobian_Matrix (Y); for I in 1 .. Nat (3) loop Print_AD_Type (Y (I)); end loop; New_Line; New_Line; Print (J); null; end Forward_AD.Jacobian;
with Interfaces; use Interfaces; package body Natools.Smaz.Original_Hash is P : constant array (0 .. 3) of Natural := (1, 2, 3, 4); T1 : constant array (0 .. 3) of Unsigned_16 := (205, 471, 343, 362); T2 : constant array (0 .. 3) of Unsigned_16 := (421, 215, 438, 437); G : constant array (0 .. 508) of Unsigned_8 := (19, 63, 226, 0, 0, 25, 0, 69, 0, 0, 14, 0, 0, 0, 73, 207, 92, 0, 0, 0, 48, 0, 62, 48, 123, 56, 0, 0, 11, 47, 0, 0, 167, 145, 0, 0, 0, 213, 114, 15, 0, 2, 214, 0, 161, 162, 0, 0, 0, 50, 0, 0, 0, 0, 0, 133, 0, 0, 54, 0, 0, 0, 33, 220, 0, 143, 1, 0, 0, 0, 0, 229, 0, 0, 0, 0, 0, 226, 0, 0, 110, 0, 0, 0, 209, 165, 0, 0, 0, 0, 99, 0, 0, 0, 0, 0, 0, 0, 0, 79, 0, 0, 235, 0, 0, 0, 195, 237, 0, 0, 0, 0, 238, 82, 0, 252, 26, 4, 0, 0, 205, 0, 0, 0, 0, 188, 0, 168, 0, 242, 0, 0, 0, 99, 191, 0, 103, 0, 230, 0, 0, 0, 0, 135, 0, 183, 21, 0, 11, 172, 119, 0, 208, 137, 0, 0, 0, 0, 0, 0, 180, 10, 183, 203, 0, 0, 86, 132, 8, 17, 0, 32, 0, 0, 92, 0, 0, 170, 0, 0, 94, 194, 50, 185, 0, 0, 42, 0, 185, 233, 177, 0, 0, 0, 0, 0, 0, 237, 218, 0, 0, 0, 119, 0, 181, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 201, 0, 42, 0, 0, 0, 0, 216, 0, 0, 0, 0, 158, 0, 0, 0, 141, 36, 51, 0, 27, 234, 242, 0, 43, 0, 219, 78, 169, 164, 0, 59, 33, 0, 112, 0, 31, 0, 144, 40, 0, 0, 0, 0, 0, 158, 0, 0, 0, 227, 127, 0, 154, 241, 0, 0, 209, 0, 248, 0, 0, 68, 0, 119, 0, 0, 104, 174, 79, 0, 0, 0, 121, 0, 0, 0, 0, 0, 0, 0, 0, 206, 0, 202, 0, 0, 0, 0, 133, 71, 209, 189, 134, 0, 69, 0, 0, 226, 68, 0, 0, 189, 0, 230, 16, 0, 0, 0, 0, 181, 246, 97, 0, 88, 25, 0, 49, 0, 34, 77, 30, 210, 0, 0, 0, 0, 128, 193, 0, 116, 2, 121, 16, 0, 214, 132, 22, 116, 68, 0, 148, 0, 0, 90, 165, 218, 157, 24, 0, 0, 192, 0, 81, 0, 0, 177, 0, 98, 81, 183, 0, 0, 0, 0, 7, 161, 0, 123, 106, 0, 0, 136, 82, 51, 48, 0, 0, 169, 5, 170, 138, 66, 211, 0, 112, 1, 0, 0, 84, 220, 167, 0, 0, 161, 252, 46, 175, 95, 170, 20, 216, 177, 0, 97, 76, 44, 0, 0, 20, 0, 0, 233, 0, 0, 0, 47, 8, 116, 147, 0, 212, 0, 0, 118, 94, 0, 89, 183, 0, 0, 105, 0, 0, 74, 196, 28, 4, 0, 103, 0, 5, 0, 131, 45, 0, 177, 232, 219, 19, 228, 1, 0, 31, 90, 0, 0, 150, 23, 92, 120, 238, 48, 1, 0, 0, 37, 3, 152, 0, 0, 110, 166, 35, 13, 115, 217, 0, 0, 0, 87, 0, 126, 163, 248, 80, 9, 12, 0, 0, 52, 10, 11, 89, 0); function Hash (S : String) return Natural is F : constant Natural := S'First - 1; L : constant Natural := S'Length; F1, F2 : Natural := 0; J : Natural; begin for K in P'Range loop exit when L < P (K); J := Character'Pos (S (P (K) + F)); F1 := (F1 + Natural (T1 (K)) * J) mod 509; F2 := (F2 + Natural (T2 (K)) * J) mod 509; end loop; return (Natural (G (F1)) + Natural (G (F2))) mod 254; end Hash; end Natools.Smaz.Original_Hash;
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- Copyright (C) 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; with ADO.Queries; with ADO.Utils; with ADO.Parameters; with AWA.Helpers.Requests; package body AWA.Comments.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then declare use type ADO.Identifier; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin if Id /= ADO.NO_IDENTIFIER then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); end if; end; elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Module.Load_Comment (From, Id); end; else AWA.Comments.Models.Comment_Bean (From).Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Create the comment. -- ------------------------------ overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Create_Comment (Permission => To_String (Bean.Permission), Entity_Type => To_String (Bean.Entity_Type), Comment => Bean); end Create; -- ------------------------------ -- Save the comment. -- ------------------------------ overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Update_Comment (Permission => To_String (Bean.Permission), Comment => Bean); end Save; -- ------------------------------ -- Publish or not the comment. -- ------------------------------ overriding procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission), Id => Id, Status => Models.Status_Type_Objects.To_Value (Value), Comment => Bean); end Publish; -- ------------------------------ -- Delete the comment. -- ------------------------------ overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean); end Delete; -- ------------------------------ -- Create a new comment bean instance. -- ------------------------------ function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_Bean_Access := new Comment_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then From.Load_Comments (ADO.Utils.To_Identifier (Value)); elsif Name = "sort" then if Util.Beans.Objects.To_String (Value) = "oldest" then From.Oldest_First := True; else From.Oldest_First := False; end if; elsif Name = "status" then if Util.Beans.Objects.To_String (Value) = "published" then From.Publish_Only := True; else From.Publish_Only := False; end if; end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; For_Entity_Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Into.Module.Get_Session; begin Into.Load_Comments (Session, For_Entity_Id); end Load_Comments; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in out ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Into.Entity_Id := For_Entity_Id; if Into.Publish_Only then Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED))); else Query.Set_Query (AWA.Comments.Models.Query_All_Comment_List); end if; Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); if Into.Oldest_First then Query.Bind_Param ("sort", ADO.Parameters.Token '("ASC")); else Query.Bind_Param ("sort", ADO.Parameters.Token '("DESC")); end if; AWA.Comments.Models.List (Into, Session, Query); end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
-- Copyright 2016,2017 Steven Stewart-Gallus -- -- 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.Command_Line; with Ada.Unchecked_Conversion; with Interfaces.C; with Interfaces.C.Strings; with XCB; with XCB.XProto; with Libc.Stdint; with Linted.Env; with Linted.Errors; with Linted.GPU; with Linted.KOs; with Linted.Logs; with Linted.Poller; with Linted.Triggers; with Linted.Update_Reader; with Linted.Update; with Linted.Windows; with Linted.Window_Notifier; package body Linted.Drawer with Spark_Mode => Off is package Command_Line renames Ada.Command_Line; package C renames Interfaces.C; package C_Strings renames Interfaces.C.Strings; use type C.size_t; use type Interfaces.Unsigned_32; use type Errors.Error; use type XCB.xcb_connection_t_access; use type XCB.xcb_generic_error_t_access; use type C.unsigned_char; use type C.C_float; task Main_Task; package My_Trigger is new Triggers.Handle; Window_Opts : aliased array (1 .. 2) of aliased Libc.Stdint.uint32_t := (XCB.XProto.XCB_EVENT_MASK_STRUCTURE_NOTIFY, 0); function Read_Window (Object : KOs.KO) return Windows.Window; function XCB_Conn_Error (Connection : XCB.xcb_connection_t_access) return Errors.Error; procedure Get_New_Window (Window_KO : KOs.KO; Connection : XCB.xcb_connection_t_access; Context : GPU.Context_Access; Window : out Windows.Window); task body Main_Task is Err : Errors.Error; Window_KO : KOs.KO; Window_Notifier_KO : KOs.KO; Updater_KO : KOs.KO; Connection : XCB.xcb_connection_t_access; Context : GPU.Context_Access; Window : Windows.Window; Poll_Future : Poller.Future; Poll_Future_Live : Boolean := False; Read_Future : Update_Reader.Future; Read_Future_Live : Boolean := False; Window_Future : Window_Notifier.Future; Window_Future_Live : Boolean := False; begin if Command_Line.Argument_Count < 3 then raise Constraint_Error with "At least three arguments"; end if; declare Maybe_Window_KO : constant KOs.KO_Results.Result := KOs.Open (Command_Line.Argument (1), KOs.Read_Write); begin if Maybe_Window_KO.Erroneous then raise Constraint_Error with "Erroneous window path"; end if; Window_KO := Maybe_Window_KO.Data; end; declare Maybe_Window_Notifier_KO : constant KOs.KO_Results.Result := KOs.Open (Command_Line.Argument (2), KOs.Read_Write); begin if Maybe_Window_Notifier_KO.Erroneous then raise Constraint_Error with "Erroneous window notifier path"; end if; Window_Notifier_KO := Maybe_Window_Notifier_KO.Data; end; declare Maybe_Updater_KO : constant KOs.KO_Results.Result := KOs.Open (Command_Line.Argument (3), KOs.Read_Write); begin if Maybe_Updater_KO.Erroneous then raise Constraint_Error with "Erroneous updater path"; end if; Updater_KO := Maybe_Updater_KO.Data; end; declare Display : String := Env.Get ("DISPLAY"); Display_C_Str : aliased C.char_array := C.To_C (Display); begin Logs.Log (Logs.Info, "Display = " & Display); Connection := XCB.xcb_connect (C_Strings.To_Chars_Ptr (Display_C_Str'Unchecked_Access), null); end; if null = Connection then raise Storage_Error with "Cannot create XCB connection"; end if; Err := XCB_Conn_Error (Connection); if Err /= Errors.Success then raise Program_Error with Errors.To_String (Err); end if; Err := GPU.Context_Create (Context); if Err /= Errors.Success then raise Program_Error with Errors.To_String (Err); end if; Window_Notifier.Read (Window_Notifier_KO, My_Trigger.Signal_Handle, Window_Future); Window_Future_Live := True; Poller.Poll (KOs.KO (XCB.xcb_get_file_descriptor (Connection)), (Poller.Readable => True, Poller.Writable => False), My_Trigger.Signal_Handle, Poll_Future); Poll_Future_Live := True; Update_Reader.Read (Updater_KO, My_Trigger.Signal_Handle, Read_Future); Read_Future_Live := True; Get_New_Window (Window_KO, Connection, Context, Window); Logs.Log (Logs.Info, "Window: " & Windows.Window'Image (Window)); loop Triggers.Wait (My_Trigger.Wait_Handle); if Read_Future_Live then declare Read_Event : Update_Reader.Event; Init : Boolean; begin Update_Reader.Read_Poll (Read_Future, Read_Event, Init); if Init then Read_Future_Live := False; declare GPU_Update : GPU.Update; begin GPU_Update.X_Position := C.C_float (Read_Event.Data.X_Position) * (1.0 / 4096.0); GPU_Update.Y_Position := C.C_float (Read_Event.Data.Y_Position) * (1.0 / 4096.0); GPU_Update.Z_Position := C.C_float (Read_Event.Data.Z_Position) * (1.0 / 4096.0); GPU_Update.MX_Position := C.C_float (Read_Event.Data.MX_Position) * (1.0 / 4096.0); GPU_Update.MY_Position := C.C_float (Read_Event.Data.MY_Position) * (1.0 / 4096.0); GPU_Update.MZ_Position := C.C_float (Read_Event.Data.MZ_Position) * (1.0 / 4096.0); GPU_Update.Z_Rotation := C.C_float (Read_Event.Data.Z_Rotation) * (6.28318530717958647692528 / (C.C_float (Update.Nat'Last) + 1.0)); GPU_Update.X_Rotation := C.C_float (Read_Event.Data.X_Rotation) * (6.28318530717958647692528 / (C.C_float (Update.Nat'Last) + 1.0)); GPU.Update_State (Context, GPU_Update); end; Update_Reader.Read (Updater_KO, My_Trigger.Signal_Handle, Read_Future); Read_Future_Live := True; end if; end; end if; if Window_Future_Live then declare Ck : XCB.xcb_void_cookie_t; X : C.int; No_Opts : aliased array (1 .. 2) of aliased Libc.Stdint.uint32_t := (0, 0); Init : Boolean; begin Window_Notifier.Read_Poll (Window_Future, Init); if Init then Window_Future_Live := False; Ck := XCB.XProto.xcb_change_window_attributes (Connection, XCB.XProto.xcb_window_t (Window), Libc.Stdint.uint32_t (XCB.XProto.XCB_CW_EVENT_MASK), No_Opts (1)'Unchecked_Access); Err := XCB_Conn_Error (Connection); if Err /= 0 then raise Program_Error with Errors.To_String (Err); end if; X := XCB.xcb_flush (Connection); Get_New_Window (Window_KO, Connection, Context, Window); Logs.Log (Logs.Info, "Window: " & Windows.Window'Image (Window)); X := XCB.xcb_flush (Connection); Window_Notifier.Read (Window_Notifier_KO, My_Trigger.Signal_Handle, Window_Future); Window_Future_Live := True; end if; end; end if; if Poll_Future_Live then declare Poll_Event : Poller.Event; Window_Destroyed : Boolean := False; My_Event : access XCB.xcb_generic_event_t; Init : Boolean; procedure Free (Event : access XCB.xcb_generic_event_t); pragma Import (C, Free, "free"); begin Poller.Poll_Poll (Poll_Future, Poll_Event, Init); if Init then Poll_Future_Live := False; loop My_Event := XCB.xcb_poll_for_event (Connection); if null = My_Event then exit; end if; case My_Event.response_type and not 16#80# is when XCB.XProto.XCB_CONFIGURE_NOTIFY => declare type A is access all XCB.xcb_generic_event_t; type B is access all XCB.XProto .xcb_configure_notify_event_t; function Convert is new Ada.Unchecked_Conversion (A, B); Configure : B := Convert (My_Event); begin GPU.Resize (Context, C.unsigned (Configure.width), C.unsigned (Configure.height)); end; when XCB.XProto.XCB_UNMAP_NOTIFY => GPU.Hide (Context); when XCB.XProto.XCB_MAP_NOTIFY => GPU.Show (Context); when XCB.XProto.XCB_DESTROY_NOTIFY => Window_Destroyed := True; when others => -- Unknown event type, ignore it null; end case; Free (My_Event); end loop; if Window_Destroyed then Err := GPU.Remove_Window (Context); if Err /= 0 then raise Program_Error with Errors.To_String (Err); end if; end if; declare X : C.int; begin X := XCB.xcb_flush (Connection); end; Poller.Poll (KOs.KO (XCB.xcb_get_file_descriptor (Connection)), (Poller.Readable => True, Poller.Writable => False), My_Trigger.Signal_Handle, Poll_Future); Poll_Future_Live := True; end if; end; end if; end loop; end Main_Task; function Read_Window (Object : KOs.KO) return Windows.Window is Bytes : C.size_t; Err : Errors.Error; Data : Windows.Storage; W : Windows.Window; begin declare Buf : aliased Windows.Storage; begin Err := KOs.Pread (Object, Buf (1)'Address, Windows.Storage_Size, 0, Bytes); if Err /= 0 then raise Program_Error with Errors.To_String (Err); end if; Data := Buf; end; pragma Assert (Bytes = 4); Windows.From_Storage (Data, W); return W; end Read_Window; function XCB_Conn_Error (Connection : XCB.xcb_connection_t_access) return Errors.Error is (case XCB.xcb_connection_has_error (Connection) is when 0 => Errors.Success, when XCB.XCB_CONN_ERROR => Errors.Protocol, when XCB.XCB_CONN_CLOSED_EXT_NOTSUPPORTED => Errors.Unimplemented, when XCB.XCB_CONN_CLOSED_MEM_INSUFFICIENT => Errors.Out_Of_Memory, when XCB.XCB_CONN_CLOSED_REQ_LEN_EXCEED => Errors.Invalid_Parameter, when XCB.XCB_CONN_CLOSED_PARSE_ERR => Errors.Invalid_Parameter, when others => raise Constraint_Error); procedure Get_New_Window (Window_KO : KOs.KO; Connection : XCB.xcb_connection_t_access; Context : GPU.Context_Access; Window : out Windows.Window) is New_Window : Windows.Window; Geom_CK : XCB.XProto.xcb_get_geometry_cookie_t; Width : C.unsigned; Height : C.unsigned; X : C.int; Ck : XCB.xcb_void_cookie_t; Err : Errors.Error; begin New_Window := Read_Window (Window_KO); Ck := XCB.XProto.xcb_change_window_attributes_checked (Connection, XCB.XProto.xcb_window_t (New_Window), Libc.Stdint.uint32_t (XCB.XProto.XCB_CW_EVENT_MASK), Window_Opts (1)'Unchecked_Access); Err := XCB_Conn_Error (Connection); if Err /= 0 then raise Program_Error with Errors.To_String (Err); end if; declare Error : XCB.xcb_generic_error_t_access; Reply : access XCB.XProto.xcb_get_geometry_reply_t; procedure Free (Event : access XCB.XProto.xcb_get_geometry_reply_t); pragma Import (C, Free, "free"); begin Error := XCB.xcb_request_check (Connection, Ck); Err := XCB_Conn_Error (Connection); if Err /= 0 then raise Program_Error with Errors.To_String (Err); end if; if Error /= null then raise Program_Error; end if; end; Geom_CK := XCB.XProto.xcb_get_geometry (Connection, XCB.XProto.xcb_window_t (New_Window)); Err := XCB_Conn_Error (Connection); if Err /= 0 then raise Program_Error with Errors.To_String (Err); end if; declare Error : XCB.xcb_generic_error_t_access; Reply : access XCB.XProto.xcb_get_geometry_reply_t; procedure Free (Event : access XCB.XProto.xcb_get_geometry_reply_t); pragma Import (C, Free, "free"); begin Reply := XCB.XProto.xcb_get_geometry_reply (Connection, Geom_CK, Error); Err := XCB_Conn_Error (Connection); if Err /= 0 then raise Program_Error with Errors.To_String (Err); end if; if Error /= null then raise Program_Error; end if; Width := C.unsigned (Reply.width); Height := C.unsigned (Reply.height); Free (Reply); end; X := XCB.xcb_flush (Connection); Err := GPU.Remove_Window (Context); if Err /= 0 then raise Program_Error with Errors.To_String (Err); end if; Err := GPU.Set_X11_Window (Context, GPU.X11_Window (New_Window)); if Err /= 0 then raise Program_Error with Errors.To_String (Err); end if; GPU.Resize (Context, Width, Height); if Err /= 0 then raise Program_Error with Errors.To_String (Err); end if; Window := New_Window; end Get_New_Window; end Linted.Drawer;
----------------------------------------------------------------------- -- util-processes -- Process creation and control -- Copyright (C) 2011, 2012, 2016, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams; with Util.Systems.Types; with Ada.Finalization; with Ada.Strings.Unbounded; package Util.Processes is Invalid_State : exception; Process_Error : exception; -- The optional process pipes: -- <dl> -- <dt>NONE</dt> -- <dd>the process will inherit the standard input, output and error.</dd> -- <dt>READ</dt> -- <dd>a pipe is created to read the process standard output.</dd> -- <dt>READ_ERROR</dt> -- <dd>a pipe is created to read the process standard error. The output and input are -- inherited.</dd> -- <dt>READ_ALL</dt> -- <dd>similar to READ the same pipe is used for the process standard error.</dd> -- <dt>WRITE</dt> -- <dd>a pipe is created to write on the process standard input.</dd> -- <dt>READ_WRITE</dt> -- <dd>Combines the <b>READ</b> and <b>WRITE</b> modes.</dd> -- <dt>READ_WRITE_ALL</dt> -- <dd>Combines the <b>READ_ALL</b> and <b>WRITE</b> modes.</dd> -- </dl> type Pipe_Mode is (NONE, READ, READ_ERROR, READ_ALL, WRITE, READ_WRITE, READ_WRITE_ALL); subtype String_Access is Ada.Strings.Unbounded.String_Access; subtype File_Type is Util.Systems.Types.File_Type; type Argument_List is array (Positive range <>) of String_Access; type Process_Identifier is new Integer; -- ------------------------------ -- Process -- ------------------------------ type Process is limited private; -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Input_Stream (Proc : in out Process; File : in String); -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Output_Stream (Proc : in out Process; File : in String; Append : in Boolean := False); -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Error_Stream (Proc : in out Process; File : in String; Append : in Boolean := False); -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. procedure Set_Working_Directory (Proc : in out Process; Path : in String); -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. procedure Set_Shell (Proc : in out Process; Shell : in String); -- Closes the given file descriptor in the child process before executing the command. procedure Add_Close (Proc : in out Process; Fd : in File_Type); -- Append the argument to the current process argument list. -- Raises <b>Invalid_State</b> if the process is running. procedure Append_Argument (Proc : in out Process; Arg : in String); -- Set the environment variable to be used by the process before its creation. procedure Set_Environment (Proc : in out Process; Name : in String; Value : in String); procedure Set_Environment (Proc : in out Process; Iterate : not null access procedure (Process : not null access procedure (Name : in String; Value : in String))); -- Spawn a new process with the given command and its arguments. The standard input, output -- and error streams are either redirected to a file or to a stream object. procedure Spawn (Proc : in out Process; Command : in String; Arguments : in Argument_List; Mode : in Pipe_Mode := NONE); procedure Spawn (Proc : in out Process; Command : in String; Mode : in Pipe_Mode := NONE); procedure Spawn (Proc : in out Process; Mode : in Pipe_Mode := NONE); -- Wait for the process to terminate. procedure Wait (Proc : in out Process); -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. procedure Stop (Proc : in out Process; Signal : in Positive := 15); -- Get the process exit status. function Get_Exit_Status (Proc : in Process) return Integer; -- Get the process identifier. function Get_Pid (Proc : in Process) return Process_Identifier; -- Returns True if the process is running. function Is_Running (Proc : in Process) return Boolean; -- Get the process input stream allowing to write on the process standard input. function Get_Input_Stream (Proc : in Process) return Util.Streams.Output_Stream_Access; -- Get the process output stream allowing to read the process standard output. function Get_Output_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access; -- Get the process error stream allowing to read the process standard output. function Get_Error_Stream (Proc : in Process) return Util.Streams.Input_Stream_Access; private type File_Type_Array is array (Positive range <>) of File_Type; type File_Type_Array_Access is access all File_Type_Array; -- The <b>System_Process</b> interface is specific to the system. On Unix, it holds the -- process identifier. On Windows, more information is necessary, including the process -- and thread handles. It's a little bit overkill to setup an interface for this but -- it looks cleaner than having specific system fields here. type System_Process is limited interface; type System_Process_Access is access all System_Process'Class; type Process is new Ada.Finalization.Limited_Controlled with record Pid : Process_Identifier := -1; Sys : System_Process_Access := null; Exit_Value : Integer := -1; Dir : Ada.Strings.Unbounded.Unbounded_String; In_File : Ada.Strings.Unbounded.Unbounded_String; Out_File : Ada.Strings.Unbounded.Unbounded_String; Err_File : Ada.Strings.Unbounded.Unbounded_String; Shell : Ada.Strings.Unbounded.Unbounded_String; Out_Append : Boolean := False; Err_Append : Boolean := False; Output : Util.Streams.Input_Stream_Access := null; Input : Util.Streams.Output_Stream_Access := null; Error : Util.Streams.Input_Stream_Access := null; To_Close : File_Type_Array_Access; end record; -- Initialize the process instance. overriding procedure Initialize (Proc : in out Process); -- Deletes the process instance. overriding procedure Finalize (Proc : in out Process); -- Wait for the process to exit. procedure Wait (Sys : in out System_Process; Proc : in out Process'Class; Timeout : in Duration) is abstract; -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. procedure Stop (Sys : in out System_Process; Proc : in out Process'Class; Signal : in Positive := 15) is abstract; -- Spawn a new process. procedure Spawn (Sys : in out System_Process; Proc : in out Process'Class; Mode : in Pipe_Mode := NONE) is abstract; -- Clear the program arguments. procedure Clear_Arguments (Sys : in out System_Process) is abstract; -- Append the argument to the process argument list. procedure Append_Argument (Sys : in out System_Process; Arg : in String) is abstract; -- Set the environment variable to be used by the process before its creation. procedure Set_Environment (Sys : in out System_Process; Name : in String; Value : in String) is abstract; -- Set the process input, output and error streams to redirect and use specified files. procedure Set_Streams (Sys : in out System_Process; Input : in String; Output : in String; Error : in String; Append_Output : in Boolean; Append_Error : in Boolean; To_Close : in File_Type_Array_Access) is abstract; -- Deletes the storage held by the system process. procedure Finalize (Sys : in out System_Process) is abstract; end Util.Processes;
-- MIT License -- Copyright (c) 2021 Stephen Merrony -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO; with CPU_Instructions; use CPU_Instructions; with Debug_Logs; use Debug_Logs; with Decoder; use Decoder; with Devices; -- use Devices; with Devices.Bus; -- use Devices.Bus; with Devices.Console; with DG_Floats; use DG_Floats; with DG_Types; use DG_Types; with Memory; use Memory; with Resolver; use Resolver; with Status_Monitor; with Processor.Eagle_Decimal_P; with Processor.Eagle_FPU_P; with Processor.Eagle_IO_P; with Processor.Eagle_Mem_Ref_P; with Processor.Eagle_Op_P; with Processor.Eagle_PC_P; with Processor.Eagle_Stack_P; with Processor.Eclipse_FPU_P; with Processor.Eclipse_Mem_Ref_P; with Processor.Eclipse_Op_P; with Processor.Eclipse_PC_P; with Processor.Eclipse_Stack_P; with Processor.Nova_IO_P; with Processor.Nova_Math_P; with Processor.Nova_Mem_Ref_P; with Processor.Nova_Op_P; with Processor.Nova_PC_P; package body Processor is function Make return CPU_T is CPU : CPU_T := new CPU_Rec; begin Reset (CPU); return CPU; end Make; procedure Set_OVR (CPU : in out CPU_T; New_OVR : in Boolean) is begin if New_OVR then Set_W_Bit(CPU.PSR, 1); else Clear_W_Bit(CPU.PSR, 1); end if; end Set_OVR; procedure Reset (CPU : in out CPU_T) is begin CPU.PC := 0; for A in AC_ID loop CPU.AC(A) := 0; CPU.FPAC(A) := 0.0; end loop; CPU.PSR := 0; CPU.Carry := false; CPU.ATU := false; CPU.ION := false; CPU.PF_Flag := false; Set_OVR (CPU, false); CPU.Instruction_Count := 0; Put_Line ("INFO: CPU reset"); end Reset; -- Boot sets up the CPU to boot, it is NOT started procedure Boot (CPU : in out CPU_T; Dev : Dev_Num_T; PC : Phys_Addr_T) is begin CPU.SR := 16#8000# or Word_T(Dev); CPU.AC(0) := Dword_T(Dev); CPU.PC := PC; end Boot; -- Prepare_For_Running should be called prior to a normal run procedure Prepare_For_Running (CPU : in out CPU_T) is begin CPU.Instruction_Count := 0; CPU.XCT_Mode := false; end Prepare_For_Running; procedure Set_Debug_Logging (CPU : in out CPU_T; OnOff : in Boolean) is begin CPU.Debug_Logging := OnOff; end Set_Debug_Logging; procedure Execute (CPU : in out CPU_T; Instr : in Decoded_Instr_T) is begin case Instr.Instr_Type is when EAGLE_DECIMAL => Processor.Eagle_Decimal_P.Do_Eagle_Decimal(Instr, CPU); when EAGLE_MEMREF => Processor.Eagle_Mem_Ref_P.Do_Eagle_Mem_Ref(Instr, CPU); when EAGLE_FPU => Processor.Eagle_FPU_P.Do_Eagle_FPU(Instr, CPU); when EAGLE_IO => Processor.Eagle_IO_P.Do_Eagle_IO(Instr, CPU); when EAGLE_OP => Processor.Eagle_Op_P.Do_Eagle_Op(Instr, CPU); when EAGLE_PC => Processor.Eagle_PC_P.Do_Eagle_PC(Instr, CPU); when EAGLE_STACK => Processor.Eagle_Stack_P.Do_Eagle_Stack(Instr, CPU); when ECLIPSE_FPU => Processor.Eclipse_FPU_P.Do_Eclipse_FPU(Instr, CPU); when ECLIPSE_MEMREF => Processor.Eclipse_Mem_Ref_P.Do_Eclipse_Mem_Ref(Instr, CPU); when ECLIPSE_OP => Processor.Eclipse_Op_P.Do_Eclipse_Op(Instr, CPU); when ECLIPSE_PC => Processor.Eclipse_PC_P.Do_Eclipse_PC(Instr, CPU); when ECLIPSE_STACK => Processor.Eclipse_Stack_P.Do_Eclipse_Stack(Instr, CPU); when NOVA_IO => Processor.Nova_IO_P.Do_Nova_IO(Instr, CPU); when NOVA_MATH => Processor.Nova_Math_P.Do_Nova_Math(Instr, CPU); when NOVA_MEMREF => Processor.Nova_Mem_Ref_P.Do_Nova_Mem_Ref(Instr, CPU); when NOVA_OP => Processor.Nova_Op_P.Do_Nova_Op(Instr, CPU); when NOVA_PC => Processor.Nova_PC_P.Do_Nova_PC(Instr, CPU); when others => Put_Line ("ERROR: Unimplemented instruction type in Execute function " & Instr.Instr_Type'Image & " for instruction " & To_String(Instr.Mnemonic)); raise Execution_Failure with "ERROR: Unimplemented instruction type in Execute function " & Instr.Instr_Type'Image & " for instruction " & To_String(Instr.Mnemonic); end case; CPU.Instruction_Count := CPU.Instruction_Count + 1; end Execute; procedure Single_Step (CPU : in out CPU_T; Radix : in Number_Base_T; Disass : out Unbounded_String) is This_Op : Word_T; Instr : Decoded_Instr_T; Segment : Integer; begin This_Op := RAM.Read_Word(CPU.PC); Segment := Integer(Shift_Right(CPU.PC, 29)); Instr := Instruction_Decode (Opcode => This_Op, PC => CPU.PC, LEF_Mode => CPU.SBR(Segment).LEF, IO_On => CPU.SBR(Segment).IO, ATU_On => CPU.ATU, Disassemble => true, Radix => Radix); Execute (CPU, Instr); Disass := Instr.Disassembly; end Single_Step; function Get_Compact_Status (CPU : in CPU_T; Radix : Number_Base_T) return String is begin return "AC0=" & Dword_To_String (CPU.AC(0), Radix, 11, true) & " AC1=" & Dword_To_String (CPU.AC(1), Radix, 11, true) & " AC2=" & Dword_To_String (CPU.AC(2), Radix, 11, true) & " AC3=" & Dword_To_String (CPU.AC(3), Radix, 11, true) & " C:" & Boolean_To_YN (CPU.Carry) & " I:" & Boolean_To_YN (CPU.ION) & " PC=" & Dword_To_String (Dword_T(CPU.PC), Radix, 11, true); end Get_Compact_Status; function Get_ATU (CPU : in CPU_T) return Boolean is (CPU.ATU); function Get_Instruction_Count (CPU : in CPU_T) return Unsigned_64 is (CPU.Instruction_Count); function Get_IO (CPU : in CPU_T; Seg : in Natural) return Boolean is (CPU.SBR(Seg).IO); function Get_ION (CPU : in CPU_T) return Boolean is (CPU.ION); function Get_LEF (CPU : in CPU_T; Seg : in Natural) return Boolean is (CPU.SBR(Seg).LEF); procedure Set_PC (CPU : in out CPU_T; PC : in Phys_Addr_T) is begin CPU.PC := PC; end Set_PC; function Get_PC (CPU : in CPU_T) return Phys_Addr_T is (CPU.PC); function Get_Status (CPU : in CPU_T) return CPU_Monitor_Rec is Stats : CPU_Monitor_Rec; begin Stats.PC := CPU.PC; Stats.AC := CPU.AC; Stats.Carry := CPU.Carry; Stats.ATU := CPU.ATU; Stats.ION := CPU.ION; Stats.Instruction_Count := CPU.Instruction_Count; return Stats; end Get_Status; function Get_XCT_Mode (CPU : in CPU_T) return Boolean is (CPU.XCT_Mode); procedure Set_XCT_Mode (CPU : in out CPU_T; YN : in Boolean) is begin CPU.XCT_Mode := YN; end Set_XCT_Mode; function Get_XCT_Opcode (CPU : in CPU_T) return Word_T is (CPU.XCT_Opcode); procedure Set_Ac (CPU : in out CPU_T; AC : in AC_ID; Datum : in Dword_T) is begin CPU.AC(AC) := Datum; end Set_Ac; function Get_N (CPU : in CPU_T) return Boolean is (Test_QW_Bit (CPU.FPSR, FPSR_N)); procedure Set_N (CPU : in out CPU_T; N : in Boolean) is begin if N then Set_QW_Bit (CPU.FPSR, FPSR_N); else Clear_QW_Bit (CPU.FPSR, FPSR_N); end if; end Set_N; function Get_Z (CPU : in CPU_T) return Boolean is (Test_QW_Bit (CPU.FPSR, FPSR_Z)); procedure Set_Z (CPU : in out CPU_T; Z : in Boolean) is begin if Z then Set_QW_Bit (CPU.FPSR, FPSR_Z); else Clear_QW_Bit (CPU.FPSR, FPSR_Z); end if; end Set_Z; procedure Run (CPU : in out CPU_T; Disassemble : in Boolean; Radix : in Number_Base_T; Breakpoints : in BP_Sets.Set; I_Counts : out Instr_Count_T) is use Ada.Containers; This_Op : Word_T; Instr : Decoded_Instr_T; Segment : Integer; PC : Phys_Addr_T; XCT : Boolean; Any_Breakpoints : Boolean := Breakpoints.Length /= 0; begin I_Counts := (others => 0); Run_Loop: loop PC := Get_PC (CPU); -- FETCH XCT := Get_XCT_Mode (CPU); if XCT then This_Op := Get_XCT_Opcode (CPU); else This_Op := RAM.Read_Word(PC); end if; -- DECODE Segment := Integer(Shift_Right(PC, 29)); Instr := Instruction_Decode (Opcode => This_Op, PC => PC, LEF_Mode => Get_LEF(CPU, Segment), IO_On => Get_IO(CPU, Segment), ATU_On => Get_ATU (CPU), Disassemble => Disassemble, Radix => Radix); -- Instruction Counting I_Counts(Instr.Instruction) := I_Counts(Instr.Instruction) + 1; if Disassemble then Loggers.Debug_Print (Debug_Log, Get_Compact_Status(CPU, Radix) & " " & To_String(Instr.Disassembly)); end if; -- EXECUTE Execute (CPU, Instr); -- INTERRUPT? if Get_ION (CPU) and Devices.Bus.States.Get_IRQ then raise Not_Yet_Implemented with "INTERRUPTs not yet handled"; end if; -- XCT if XCT then Set_XCT_Mode(CPU, false); end if; -- BREAKPOINT? if Any_Breakpoints then if Breakpoints.Contains (PC) then Devices.Console.SCP_Handler.Set_SCP_IO (true); Devices.Console.TTOut.Put_String (" *** BREAKpoint hit ***"); end if; end if; -- Console Interrupt? if Devices.Console.SCP_IO then Devices.Console.TTOut.Put_String (" *** Console ESCape ***"); exit Run_Loop; end if; end loop Run_Loop; end Run; procedure VRun (CPU : in out CPU_T; Disassemble : in Boolean; Radix : in Number_Base_T; I_Counts : in out Instr_Count_T; Syscall_Trap : out Boolean) is use Ada.Containers; This_Op : Word_T; Instr : Decoded_Instr_T; Segment : Integer; PC : Phys_Addr_T := Get_PC (CPU); XCT : Boolean; begin loop -- FETCH XCT := Get_XCT_Mode (CPU); if XCT then This_Op := Get_XCT_Opcode (CPU); else This_Op := RAM.Read_Word(PC); end if; -- DECODE Segment := Integer(Shift_Right(PC, 29)); Instr := Instruction_Decode (Opcode => This_Op, PC => PC, LEF_Mode => true, IO_On => Get_IO(CPU, Segment), ATU_On => Get_ATU (CPU), Disassemble => Disassemble, Radix => Radix); -- Instruction Counting I_Counts(Instr.Instruction) := I_Counts(Instr.Instruction) + 1; if Disassemble then Loggers.Debug_Print (Debug_Log, Get_Compact_Status(CPU, Radix) & " " & To_String(Instr.Disassembly)); -- Ada.Text_IO.Put_Line(Get_Compact_Status(CPU, Radix) & " " & To_String(Instr.Disassembly)); end if; -- EXECUTE Execute (CPU, Instr); -- XCT if XCT then Set_XCT_Mode(CPU, false); end if; -- System Call? PC := Get_PC (CPU); if PC = 16#3000_0000# then Syscall_Trap := true; exit; else Syscall_Trap := false; end if; exit when PC = 8#16000000000#; end loop; end VRun; function Disassemble_Range (Low_Addr, High_Addr : Phys_Addr_T; Radix : Number_Base_T) return String is Skip_Decode : Integer := 0; Tmp_Dis : Unbounded_String; Word : Word_T; Byte_1, Byte_2 : Byte_T; Instr : Decoded_Instr_T; begin if Low_Addr > High_Addr then return " *** Invalid address range for disassembly ***"; end if; for Addr in Low_Addr .. High_Addr loop Word := RAM.Read_Word (Addr); Get_Bytes_From_Word (Word, Byte_2, Byte_1); Tmp_Dis := Tmp_Dis & Dasher_NL & Dword_To_String (Dword_T(Addr), Octal, 12, true) & ": " & Byte_To_String (Byte_1, Hex, 2, true) & " " & Byte_To_String (Byte_2, Hex, 2, true) & " " & Dword_To_String(Dword_T(Word), Octal, 6, true) & " '"; if Byte_1 >= 32 and Byte_1 <= 126 then Tmp_Dis := Tmp_Dis & Character'Val (Byte_1); else Tmp_Dis := Tmp_Dis & " "; end if; if Byte_2 >= 32 and Byte_2 <= 126 then Tmp_Dis := Tmp_Dis & Character'Val (Byte_2); else Tmp_Dis := Tmp_Dis & " "; end if; Tmp_Dis := Tmp_Dis & "' "; if Skip_Decode = 0 then Instr := Instruction_Decode (Word, Addr, false, false, false, true, Radix); Tmp_Dis := Tmp_Dis & Instr.Disassembly; if Instr.Instr_Len > 1 then Skip_Decode := Instr.Instr_Len - 1; end if; else Skip_Decode := Skip_Decode - 1; end if; end loop; return To_String (Tmp_Dis); end Disassemble_Range; task body Status_Sender is SS_CPU : CPU_T; Stats : CPU_Monitor_Rec; begin accept Start (CPU : in CPU_T) do SS_CPU := CPU; Put_line ("INFO: CPU Status Sender started"); end Start; loop Stats := Get_Status (SS_CPU); -- Stats := SS_CPU.Get_Status; Status_Monitor.Monitor.CPU_Update (Stats); delay 0.333; end loop; end Status_Sender; end Processor;
-- Generated at 2017-06-17 18:23:38 +0000 by Natools.Static_Hash_Maps -- from src/natools-s_expressions-conditionals-strings-maps.sx package Natools.Static_Maps.S_Expressions.Conditionals.Strings is pragma Pure; type Parametric_Condition is (Unknown_Parametric_Condition, Case_Insensitive, Case_Sensitive, Contains_All, Contains_Any, Is_Equal_To, Starts_With); type Simple_Condition is (Unknown_Simple_Condition, Is_ASCII, Is_Empty); function To_Parametric (Key : String) return Parametric_Condition; function To_Simple (Key : String) return Simple_Condition; private Map_1_Key_0 : aliased constant String := "case-insensitive"; Map_1_Key_1 : aliased constant String := "case-sensitive"; Map_1_Key_2 : aliased constant String := "contains"; Map_1_Key_3 : aliased constant String := "contains-all"; Map_1_Key_4 : aliased constant String := "contains-all-of"; Map_1_Key_5 : aliased constant String := "contains-any"; Map_1_Key_6 : aliased constant String := "contains-any-of"; Map_1_Key_7 : aliased constant String := "is"; Map_1_Key_8 : aliased constant String := "is-equal-to"; Map_1_Key_9 : aliased constant String := "="; Map_1_Key_10 : aliased constant String := "starts-with"; Map_1_Keys : constant array (0 .. 10) of access constant String := (Map_1_Key_0'Access, Map_1_Key_1'Access, Map_1_Key_2'Access, Map_1_Key_3'Access, Map_1_Key_4'Access, Map_1_Key_5'Access, Map_1_Key_6'Access, Map_1_Key_7'Access, Map_1_Key_8'Access, Map_1_Key_9'Access, Map_1_Key_10'Access); Map_1_Elements : constant array (0 .. 10) of Parametric_Condition := (Case_Insensitive, Case_Sensitive, Contains_All, Contains_All, Contains_All, Contains_Any, Contains_Any, Is_Equal_To, Is_Equal_To, Is_Equal_To, Starts_With); Map_2_Key_0 : aliased constant String := "is-ascii"; Map_2_Key_1 : aliased constant String := "is-empty"; Map_2_Keys : constant array (0 .. 1) of access constant String := (Map_2_Key_0'Access, Map_2_Key_1'Access); Map_2_Elements : constant array (0 .. 1) of Simple_Condition := (Is_ASCII, Is_Empty); end Natools.Static_Maps.S_Expressions.Conditionals.Strings;
package Asis_Adapter.Element.Associations is procedure Do_Pre_Child_Processing (Element : in Asis.Element; State : in out Class); private -- For debuggng: Parent_Name : constant String := Module_Name; Module_Name : constant String := Parent_Name & "Associations"; end Asis_Adapter.Element.Associations;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez (Stephane.Carrez@gmail.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Strings; package Wiki.Nodes is pragma Preelaborate; type Node_Kind is (N_LINE_BREAK, N_HORIZONTAL_RULE, N_TOC_DISPLAY, N_PARAGRAPH, N_NEWLINE, N_HEADER, N_TOC, N_TOC_ENTRY, N_BLOCKQUOTE, N_QUOTE, N_TAG_START, N_PREFORMAT, N_TABLE, N_ROW, N_COLUMN, N_LIST, N_NUM_LIST, N_INDENT, N_TEXT, N_LINK, N_IMAGE); -- Node kinds which are simple markers in the document. subtype Simple_Node_Kind is Node_Kind range N_LINE_BREAK .. N_NEWLINE; type Node_List is limited private; type Node_List_Access is access all Node_List; type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Node_Kind; Len : Natural) is limited record Parent : Node_Type_Access; case Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_LIST | N_NUM_LIST | N_TOC_ENTRY => Level : Natural := 0; Header : Wiki.Strings.WString (1 .. Len); when N_TEXT => Format : Format_Map; Text : Wiki.Strings.WString (1 .. Len); when N_LINK | N_IMAGE | N_QUOTE => Link_Attr : Wiki.Attributes.Attribute_List; Title : Wiki.Strings.WString (1 .. Len); when N_TAG_START | N_TABLE | N_ROW | N_COLUMN => Tag_Start : Html_Tag; Attributes : Wiki.Attributes.Attribute_List; Children : Node_List_Access; when N_PREFORMAT => Language : Wiki.Strings.UString; Preformatted : Wiki.Strings.WString (1 .. Len); when N_TOC => Entries : Node_List_Access; when others => null; end case; end record; -- Append a node to the tag node. procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access); -- Append a node to the document. procedure Append (Into : in out Node_List; Node : in Node_Type_Access); -- Finalize the node list to release the allocated memory. procedure Finalize (List : in out Node_List); private NODE_LIST_BLOCK_SIZE : constant Positive := 16; type Node_Array is array (Positive range <>) of Node_Type_Access; type Node_List_Block; type Node_List_Block_Access is access all Node_List_Block; type Node_List_Block (Max : Positive) is limited record Next : Node_List_Block_Access; Last : Natural := 0; List : Node_Array (1 .. Max); end record; type Node_List is limited record Current : Node_List_Block_Access; Length : Natural := 0; First : aliased Node_List_Block (NODE_LIST_BLOCK_SIZE); end record; end Wiki.Nodes;
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- SQL Database Access -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <vgodunko@gmail.com> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This package provides low level binding to PostgreSQL database client -- library. ------------------------------------------------------------------------------ with Interfaces.C.Strings; package Matreshka.Internals.SQL_Drivers.PostgreSQL is pragma Preelaborate; ----------- -- Types -- ----------- type PGconn is limited private; type PGconn_Access is access all PGconn; pragma Convention (C, PGconn_Access); type PGresult is limited private; type PGresult_Access is access all PGresult; pragma Convention (C, PGresult_Access); type Oid is new Interfaces.C.int; type Oid_Access is access all oid; pragma Convention (C, Oid_Access); type ConnStatusType is (CONNECTION_OK, CONNECTION_BAD, CONNECTION_STARTED, CONNECTION_MADE, CONNECTION_AWAITING_RESPONSE, CONNECTION_AUTH_OK, CONNECTION_SETENV, CONNECTION_SSL_STARTUP, CONNECTION_NEEDED); pragma Convention (C, ConnStatusType); type ExecStatusType is (PGRES_EMPTY_QUERY, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PGRES_COPY_OUT, PGRES_COPY_IN, PGRES_BAD_RESPONSE, PGRES_NONFATAL_ERROR, PGRES_FATAL_ERROR); pragma Convention (C, ExecStatusType); type chars_ptr_Access is access all Interfaces.C.Strings.chars_ptr; pragma Convention (C, chars_ptr_Access); type int_Access is access all Interfaces.C.int; pragma Convention (C, int_Access); ----------------- -- Subprograms -- ----------------- function pg_encoding_to_char (encoding_id : Interfaces.C.int) return Interfaces.C.Strings.chars_ptr; pragma Import (C, pg_encoding_to_char); procedure PQclear (res : PGresult_Access); pragma Import (C, PQclear, "PQclear"); function PQclientEncoding (conn : PGconn_Access) return Interfaces.C.int; pragma Import (C, PQclientEncoding, "PQclientEncoding"); function PQconnectdbParams (keywords : Interfaces.C.Strings.chars_ptr_array; values : Interfaces.C.Strings.chars_ptr_array; expand_dbnam : Interfaces.C.int) return PGconn_Access; pragma Import (C, PQconnectdbParams, "PQconnectdbParams"); function PQerrorMessage (conn : PGconn_Access) return Interfaces.C.Strings.chars_ptr; pragma Import (C, PQerrorMessage, "PQerrorMessage"); function PQexec (conn : PGconn_Access; command : Interfaces.C.Strings.chars_ptr) return PGresult_Access; pragma Import (C, PQexec, "PQexec"); function PQexecPrepared (conn : PGconn_Access; stmtName : Interfaces.C.Strings.chars_ptr; nParams : Interfaces.C.int; -- paramValues : chars_ptr_Access; paramValues : Interfaces.C.Strings.chars_ptr_array; paramLengths : int_Access; paramFormats : int_Access; resultFormat : Interfaces.C.int) return PGresult_Access; pragma Import (C, PQexecPrepared, "PQexecPrepared"); procedure PQfinish (conn : PGconn_Access); pragma Import (C, PQfinish, "PQfinish"); function PQftype (res : PGresult_Access; column_number : Interfaces.C.int) return Oid; pragma Import (C, PQftype, "PQftype"); function PQgetisnull (res : PGresult_Access; row_number : Interfaces.C.int; column_number : Interfaces.C.int) return Interfaces.C.int; pragma Import (C, PQgetisnull, "PQgetisnull"); function PQgetlength (res : PGresult_Access; row_number : Interfaces.C.int; column_number : Interfaces.C.int) return Interfaces.C.int; pragma Import (C, PQgetlength, "PQgetlength"); function PQgetvalue (res : PGresult_Access; row_number : Interfaces.C.int; column_number : Interfaces.C.int) return Interfaces.C.Strings.chars_ptr; pragma Import (C, PQgetvalue, "PQgetvalue"); function PQisthreadsafe return Interfaces.C.int; pragma Import (C, PQisthreadsafe, "PQisthreadsafe"); function PQntuples (res : PGresult_Access) return Interfaces.C.int; pragma Import (C, PQntuples, "PQntuples"); function PQprepare (conn : PGconn_Access; stmtName : Interfaces.C.Strings.chars_ptr; query : Interfaces.C.Strings.chars_ptr; nParams : Interfaces.C.int; paramTypes : Oid_Access) return PGresult_Access; pragma Import (C, PQprepare, "PQprepare"); function PQresultStatus (res : PGresult_Access) return ExecStatusType; pragma Import (C, PQresultStatus, "PQresultStatus"); function PQsetClientEncoding (conn : PGconn_Access; encoding : Interfaces.C.Strings.chars_ptr) return Interfaces.C.int; pragma Import (C, PQsetClientEncoding, "PQsetClientEncoding"); function PQstatus (conn : PGconn_Access) return ConnStatusType; pragma Import (C, PQstatus, "PQstatus"); private type PGconn is limited null record; type PGresult is limited null record; end Matreshka.Internals.SQL_Drivers.PostgreSQL;