repo_name
stringlengths 9
74
| language
stringclasses 1
value | length_bytes
int64 11
9.34M
| extension
stringclasses 2
values | content
stringlengths 11
9.34M
|
---|---|---|---|---|
rguilloteau/pok | Ada | 3,347 | ads | -- POK header
--
-- The following file is a part of the POK project. Any modification should
-- be made according to the POK licence. You CANNOT use this file or a part
-- of a file for your own project.
--
-- For more information on the POK licence, please see our LICENCE FILE
--
-- Please follow the coding guidelines described in doc/CODING_GUIDELINES
--
-- Copyright (c) 2007-2020 POK team
-- ---------------------------------------------------------------------------
-- --
-- QUEUING PORT constant and type definitions and management services --
-- --
-- ---------------------------------------------------------------------------
with APEX.Processes;
package APEX.Queuing_Ports is
Max_Number_Of_Queuing_Ports : constant :=
System_Limit_Number_Of_Queuing_Ports;
subtype Queuing_Port_Name_Type is Name_Type;
type Queuing_Port_Id_Type is private;
Null_Queuing_Port_Id : constant Queuing_Port_Id_Type;
type Queuing_Port_Status_Type is record
Nb_Message : Message_Range_Type;
Max_Nb_Message : Message_Range_Type;
Max_Message_Size : Message_Size_Type;
Port_Direction : Port_Direction_Type;
Waiting_Processes : APEX.Processes.Waiting_Range_Type;
end record;
procedure Create_Queuing_Port
(Queuing_Port_Name : in Queuing_Port_Name_Type;
Max_Message_Size : in Message_Size_Type;
Max_Nb_Message : in Message_Range_Type;
Port_Direction : in Port_Direction_Type;
Queuing_Discipline : in Queuing_Discipline_Type;
Queuing_Port_Id : out Queuing_Port_Id_Type;
Return_Code : out Return_Code_Type);
procedure Send_Queuing_Message
(Queuing_Port_Id : in Queuing_Port_Id_Type;
Message_Addr : in Message_Addr_Type;
Length : in Message_Size_Type;
Time_Out : in System_Time_Type;
Return_Code : out Return_Code_Type);
procedure Receive_Queuing_Message
(Queuing_Port_Id : in Queuing_Port_Id_Type;
Time_Out : in System_Time_Type;
Message_Addr : in Message_Addr_Type;
-- The message address is passed IN, although the respective message is
-- passed OUT
Length : out Message_Size_Type;
Return_Code : out Return_Code_Type);
procedure Get_Queuing_Port_Id
(Queuing_Port_Name : in Queuing_Port_Name_Type;
Queuing_Port_Id : out Queuing_Port_Id_Type;
Return_Code : out Return_Code_Type);
procedure Get_Queuing_Port_Status
(Queuing_Port_Id : in Queuing_Port_Id_Type;
Queuing_Port_Status : out Queuing_Port_Status_Type;
Return_Code : out Return_Code_Type);
private
type Queuing_Port_Id_Type is new APEX_Integer;
Null_Queuing_Port_Id : constant Queuing_Port_Id_Type := 0;
pragma Convention (C, Queuing_Port_Status_Type);
-- POK BINDINGS
pragma Import (C, Create_Queuing_Port, "CREATE_QUEUING_PORT");
pragma Import (C, Send_Queuing_Message, "SEND_QUEUING_PORT_MESSAGE");
pragma Import (C, Receive_Queuing_Message, "RECEIVE_QUEUING_MESSAGE");
pragma Import (C, Get_Queuing_Port_Id, "GET_QUEUING_PORT_ID");
pragma Import (C, Get_Queuing_Port_Status, "GET_QUEUING_PORT_STATUS");
-- END OF POK BINDINGS
end APEX.Queuing_Ports;
|
pvrego/adaino | Ada | 5,099 | adb | -- =============================================================================
-- Package body AVR.IMAGE
-- =============================================================================
package body IMAGE is
procedure U8_Img_Right (Data : Unsigned_8; Target : out AVR.USART.String_U8) is
D : Unsigned_8 := Data;
begin
for Index in Target'Range loop
Target (Index) := ' ';
end loop;
if D >= 100 then
Target (Target'First) := Character'Val (48 + (D / 100));
D := D rem 100;
else
Target (Target'First) := ' ';
end if;
if D >= 10 or else Data >= 100 then
Target (Target'First + 1) := Character'Val (48 + (D / 10));
else
Target (Target'First + 1) := ' ';
end if;
Target (Target'First + 2) := Character'Val (48 + (D rem 10));
exception
when others => null;
end U8_Img_Right;
function Unsigned_8_To_String_Simon (Input : Unsigned_8) return String_3 is
Result : String_3 := (others => ' ');
Digit : Unsigned_8;
Rest_Of_Number : Unsigned_8;
begin
Digit := Input mod 10;
Rest_Of_Number := Input / 10;
for J in reverse Result'Range loop
if Digit /= 0
or else Rest_Of_Number /= 0
or else J = Result'Last then
Result (J)
:= Character'Val (Character'Pos ('0') + Integer (Digit));
end if;
Digit := Rest_Of_Number mod 10;
Rest_Of_Number := Rest_Of_Number / 10;
-- could exit when Rest_Of_Number = 0
end loop;
return Result;
exception
when others => return " ";
end Unsigned_8_To_String_Simon;
function Unsigned_8_To_String_Shark8 (Input : Unsigned_8) return String_3 is
-- A temporary variable for manipulation, initialized to input.
Working : Unsigned_8 := Input;
begin
-- Extended return, we do not have to initialize any characters
-- because they will be in range '0'..'9' with leading zeros.
return Result : String_3 do
-- We assign the digit it's proper value, based on its
-- position within the string.
for Digit in reverse Result'Range loop
Result (Digit) := Character'Val (
-- We add the mod 10 value of working
-- to the value of '0' to get the proper
-- digit-character.
Natural (Working mod 10) + Character'Pos('0')
);
-- We adjust our working-variable, by dividing it by 10.
Working := Working / 10;
end loop;
end return;
exception
when others => return " ";
end Unsigned_8_To_String_Shark8;
function String_To_Unsigned_8 (Input : AVR.USART.String_U8) return Unsigned_8 is
Result : Unsigned_8 := 0;
begin
for Digit in Input'Range loop
Result := 10 * Result + (Character'Pos (Input (Digit)) - Character'Pos ('0'));
end loop;
return Result;
end String_To_Unsigned_8;
function String_To_Unsigned_32 (Input : AVR.USART.String_U8) return Unsigned_32 is
Result : Unsigned_32 := 0;
begin
for Digit in Input'Range loop
Result := 10 * Result + (Character'Pos (Input (Digit)) - Character'Pos ('0'));
end loop;
return Result;
end String_To_Unsigned_32;
function String_To_Unsigned_8_Shark8 (Input : String_3) return Unsigned_8 is
Working : String_3 := Input;
Index : Unsigned_8 := 1;
begin
-- Preprocessing string: spaces are treated as 0.
for C of Working loop
C := (if C = ' ' then '0' else C);
-- throw error if invalid characters exist.
if C not in Digit then
raise Numeric_Error;
end if;
-- Note a case statement might habe been
-- nore appropriate for this block.
end loop;
return Result : Unsigned_8 := 0 do
for C of reverse Working loop
-- We add the current character's value, multiplied
-- by its position, to modify result.
Result:= Result +
Index * (Character'Pos(C) - Character'Pos('0'));
-- The following works because wrap-around isn't an error.
-- If we weren't using Unsigned_8 we would need a cast.
Index:= Index * 10;
end loop;
end return;
exception
when others => return 0;
end String_To_Unsigned_8_Shark8;
function Compare_String_U8 (Left, Right : in AVR.USART.String_U8) return Boolean is
Return_Test : Boolean := True;
begin
if Left'Length /= Right'Length then
raise Constraint_Error;
end if;
for Index in Left'Range loop
if Left (Index) /= Right (Index) then
Return_Test := False;
exit;
end if;
end loop;
return Return_Test;
exception
when others => return False;
end Compare_String_U8;
end IMAGE;
|
reznikmm/matreshka | Ada | 3,398 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Web Framework --
-- --
-- Tools Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2015, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
package Properties is
pragma Pure;
end Properties;
|
zhmu/ananas | Ada | 8,329 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . E X P O N T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2022, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
package body System.Expont
with SPARK_Mode
is
-- Preconditions, postconditions, ghost code, loop invariants and
-- assertions in this unit are meant for analysis only, not for run-time
-- checking, as it would be too costly otherwise. This is enforced by
-- setting the assertion policy to Ignore.
pragma Assertion_Policy (Pre => Ignore,
Post => Ignore,
Ghost => Ignore,
Loop_Invariant => Ignore,
Assert => Ignore);
-- Local lemmas
procedure Lemma_Exp_Expand (A : Big_Integer; Exp : Natural)
with
Ghost,
Pre => A /= 0,
Post =>
(if Exp rem 2 = 0 then
A ** Exp = A ** (Exp / 2) * A ** (Exp / 2)
else
A ** Exp = A ** (Exp / 2) * A ** (Exp / 2) * A);
procedure Lemma_Exp_In_Range (A : Big_Integer; Exp : Positive)
with
Ghost,
Pre => In_Int_Range (A ** Exp * A ** Exp),
Post => In_Int_Range (A * A);
procedure Lemma_Exp_Not_Zero (A : Big_Integer; Exp : Natural)
with
Ghost,
Pre => A /= 0,
Post => A ** Exp /= 0;
procedure Lemma_Exp_Positive (A : Big_Integer; Exp : Natural)
with
Ghost,
Pre => A /= 0
and then Exp rem 2 = 0,
Post => A ** Exp > 0;
procedure Lemma_Mult_In_Range (X, Y, Z : Big_Integer)
with
Ghost,
Pre => Y /= 0
and then not (X = -Big (Int'First) and Y = -1)
and then X * Y = Z
and then In_Int_Range (Z),
Post => In_Int_Range (X);
-----------------------------
-- Local lemma null bodies --
-----------------------------
procedure Lemma_Exp_Not_Zero (A : Big_Integer; Exp : Natural) is null;
procedure Lemma_Mult_In_Range (X, Y, Z : Big_Integer) is null;
-----------
-- Expon --
-----------
function Expon (Left : Int; Right : Natural) return Int is
-- Note that negative exponents get a constraint error because the
-- subtype of the Right argument (the exponent) is Natural.
Result : Int := 1;
Factor : Int := Left;
Exp : Natural := Right;
Rest : Big_Integer with Ghost;
-- Ghost variable to hold Factor**Exp between Exp and Factor updates
begin
-- We use the standard logarithmic approach, Exp gets shifted right
-- testing successive low order bits and Factor is the value of the
-- base raised to the next power of 2.
-- Note: for compilation only, it is not worth special casing base
-- values -1, 0, +1 since the expander does this when the base is a
-- literal, and other cases will be extremely rare. But for proof,
-- special casing zero in both positions makes ghost code and lemmas
-- simpler, so we do it.
if Right = 0 then
return 1;
elsif Left = 0 then
return 0;
end if;
loop
pragma Loop_Invariant (Exp > 0);
pragma Loop_Invariant (Factor /= 0);
pragma Loop_Invariant
(Big (Result) * Big (Factor) ** Exp = Big (Left) ** Right);
pragma Loop_Variant (Decreases => Exp);
if Exp rem 2 /= 0 then
declare
pragma Unsuppress (Overflow_Check);
begin
pragma Assert
(Big (Factor) ** Exp
= Big (Factor) * Big (Factor) ** (Exp - 1));
Lemma_Exp_Positive (Big (Factor), Exp - 1);
Lemma_Mult_In_Range (Big (Result) * Big (Factor),
Big (Factor) ** (Exp - 1),
Big (Left) ** Right);
Result := Result * Factor;
end;
end if;
Lemma_Exp_Expand (Big (Factor), Exp);
Exp := Exp / 2;
exit when Exp = 0;
Rest := Big (Factor) ** Exp;
pragma Assert
(Big (Result) * (Rest * Rest) = Big (Left) ** Right);
declare
pragma Unsuppress (Overflow_Check);
begin
Lemma_Mult_In_Range (Rest * Rest,
Big (Result),
Big (Left) ** Right);
Lemma_Exp_In_Range (Big (Factor), Exp);
Factor := Factor * Factor;
end;
pragma Assert (Big (Factor) ** Exp = Rest * Rest);
end loop;
pragma Assert (Big (Result) = Big (Left) ** Right);
return Result;
end Expon;
----------------------
-- Lemma_Exp_Expand --
----------------------
procedure Lemma_Exp_Expand (A : Big_Integer; Exp : Natural) is
begin
if Exp rem 2 = 0 then
pragma Assert (Exp = Exp / 2 + Exp / 2);
else
pragma Assert (Exp = Exp / 2 + Exp / 2 + 1);
pragma Assert (A ** Exp = A ** (Exp / 2) * A ** (Exp / 2 + 1));
pragma Assert (A ** (Exp / 2 + 1) = A ** (Exp / 2) * A);
pragma Assert (A ** Exp = A ** (Exp / 2) * A ** (Exp / 2) * A);
end if;
end Lemma_Exp_Expand;
------------------------
-- Lemma_Exp_In_Range --
------------------------
procedure Lemma_Exp_In_Range (A : Big_Integer; Exp : Positive) is
begin
if A /= 0 and Exp /= 1 then
pragma Assert (A ** Exp = A * A ** (Exp - 1));
Lemma_Mult_In_Range
(A * A, A ** (Exp - 1) * A ** (Exp - 1), A ** Exp * A ** Exp);
end if;
end Lemma_Exp_In_Range;
------------------------
-- Lemma_Exp_Positive --
------------------------
procedure Lemma_Exp_Positive (A : Big_Integer; Exp : Natural) is
begin
if Exp = 0 then
pragma Assert (A ** Exp = 1);
else
pragma Assert (Exp = 2 * (Exp / 2));
pragma Assert (A ** Exp = A ** (Exp / 2) * A ** (Exp / 2));
pragma Assert (A ** Exp = (A ** (Exp / 2)) ** 2);
Lemma_Exp_Not_Zero (A, Exp / 2);
end if;
end Lemma_Exp_Positive;
end System.Expont;
|
reznikmm/matreshka | Ada | 3,651 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
with AMF.Elements.Generic_Hash;
function AMF.UML.Literal_Unlimited_Naturals.Hash is
new AMF.Elements.Generic_Hash (UML_Literal_Unlimited_Natural, UML_Literal_Unlimited_Natural_Access);
|
mfkiwl/ewok-kernel-security-OS | Ada | 4,925 | adb | --
-- Copyright 2018 The wookey project team <[email protected]>
-- - Ryad Benadjila
-- - Arnauld Michelizza
-- - Mathieu Renard
-- - Philippe Thierry
-- - Philippe Trebuchet
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
with ewok.tasks; use ewok.tasks;
with ewok.devices_shared; use ewok.devices_shared;
with ewok.dma_shared; use ewok.dma_shared;
with ewok.devices;
with ewok.dma;
with ewok.debug;
package body ewok.syscalls.exiting
with spark_mode => off
is
package TSK renames ewok.tasks;
procedure svc_exit
(caller_id : in ewok.tasks_shared.t_task_id;
mode : in ewok.tasks_shared.t_task_mode)
is
begin
if mode = TASK_MODE_ISRTHREAD then
#if CONFIG_SCHED_SUPPORT_FISR
declare
current_state : constant t_task_state :=
ewok.tasks.get_state (caller_id, TASK_MODE_MAINTHREAD);
begin
if current_state = TASK_STATE_RUNNABLE or
current_state = TASK_STATE_IDLE
then
ewok.tasks.set_state
(caller_id, TASK_MODE_MAINTHREAD, TASK_STATE_FORCED);
end if;
end;
#end if;
ewok.tasks.set_state
(caller_id, TASK_MODE_ISRTHREAD, TASK_STATE_ISR_DONE);
-- Main thread mode
else
-- FIXME: we should also clean resources (devices, DMA, IPCs, ISRs...)
-- This means:
-- * unlock task waiting for this task to respond to IPC, returning BUSY
-- * disabling all registered interrupts (NVIC)
-- * disabling all EXTIs
-- * cleaning DMA registered streams & reseting them
-- * deregistering devices
-- * deregistering GPIOs
-- * zeroing data regions
-- Most of those actions should be handled by each component unregister()
-- call (or equivalent)
-- All waiting events of the softirq input queue for this task should also be
-- cleaned (they also can be cleaned as they are treated by softirqd)
ewok.tasks.set_state
(caller_id, TASK_MODE_MAINTHREAD, TASK_STATE_FINISHED);
end if;
end svc_exit;
-- Deallocate registered devices and DMA streams in order
-- to avoid user ISRs (potentially faulty) triggered by
-- interrupts.
-- TODO: the appropriate action should be chosen at compile time
-- (ie. DO_NOTHING, RESET, FREEZE...)
procedure svc_panic
(caller_id : in ewok.tasks_shared.t_task_id)
is
dev_id : ewok.devices_shared.t_device_id;
ok : boolean;
begin
-- Release registered devices
for dev_descriptor in TSK.tasks_list(caller_id).devices'range loop
dev_id := TSK.tasks_list(caller_id).devices(dev_descriptor).device_id;
if dev_id /= ID_DEV_UNUSED then
-- Unmounting the device
if TSK.is_mounted (caller_id, dev_descriptor) then
TSK.unmount_device (caller_id, dev_descriptor, ok);
if not ok then
raise program_error; -- Should never happen
end if;
end if;
-- Removing it from the task's list of used devices
TSK.remove_device (caller_id, dev_descriptor);
-- Release GPIOs, EXTIs and interrupts
ewok.devices.release_device (caller_id, dev_id, ok);
if not ok then
raise program_error; -- Should never happen
end if;
end if;
end loop;
-- Release DMA streams
for dma_descriptor in TSK.tasks_list(caller_id).dma_id'range loop
if TSK.tasks_list(caller_id).dma_id(dma_descriptor) /= ID_DMA_UNUSED
then
ewok.dma.release_stream
(caller_id,
TSK.tasks_list(caller_id).dma_id(dma_descriptor),
ok);
if not ok then
raise program_error; -- Should never happen
end if;
end if;
end loop;
-- FIXME: maybe we should also clean IPCs ?
ewok.tasks.set_state
(caller_id, TASK_MODE_ISRTHREAD, TASK_STATE_ISR_DONE);
ewok.tasks.set_state
(caller_id, TASK_MODE_MAINTHREAD, TASK_STATE_FINISHED);
debug.log (debug.ALERT, ewok.tasks.tasks_list(caller_id).name & " voluntary panic!");
end svc_panic;
end ewok.syscalls.exiting;
|
MinimSecure/unum-sdk | Ada | 861 | ads | -- Copyright 2014-2016 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 Time_T is record
Secs : Integer;
end record;
procedure Do_Nothing (A : System.Address);
end Pck;
|
reznikmm/matreshka | Ada | 4,364 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- Simple entity resolver to be used to resolve entities in XMI documents.
--
-- XXX It can be removed once own default entity resolver will be provided by
-- SAX reader.
------------------------------------------------------------------------------
with XML.SAX.Entity_Resolvers;
with XML.SAX.Input_Sources;
package AMF.Internals.XMI_Entity_Resolvers is
type XMI_Entity_Resolver is
limited new XML.SAX.Entity_Resolvers.SAX_Entity_Resolver
with null record;
overriding function Error_String
(Self : XMI_Entity_Resolver)
return League.Strings.Universal_String;
overriding procedure Resolve_Entity
(Self : in out XMI_Entity_Resolver;
Name : League.Strings.Universal_String;
Public_Id : League.Strings.Universal_String;
Base_URI : League.Strings.Universal_String;
System_Id : League.Strings.Universal_String;
Source : out XML.SAX.Input_Sources.SAX_Input_Source_Access;
Success : in out Boolean);
end AMF.Internals.XMI_Entity_Resolvers;
|
SSOCsoft/Log_Reporter | Ada | 4,459 | ads | With
NSO.JSON,
Ada.Containers.Ordered_Maps,
Ada.Containers.Indefinite_Ordered_Maps,
Ada.Calendar,
Gnoga.Gui.Base,
Gnoga.Gui.Element.Form,
Gnoga.Gui.Element.Common;
Limited with
Report_Form;
Package NSO.Types.Report_Objects.Weather_Report with Elaborate_Body is
-----------------
-- CONSTANTS --
-----------------
Min_See : Constant := 1;
Max_See : Constant := 8;
Min_Wind : Constant := 0;
Max_Wind : Constant := 80;
Min_Temp : Constant := -40;
Max_Temp : Constant := 120;
----------------------
-- INTERNAL TYPES --
----------------------
Type Field is (Wind_Speed, Temperature, Seeing, Conditions, Wind_Direction);
Function "+"(Item : Field) return String;
Function "+"(Item : String) return Field;
Type Wind_Range is range Min_Wind..Max_Wind;
Function "-"( Input : String ) Return Wind_Range;
Function "+"( Input : Wind_Range ) Return String;
Type Temp_Range is range Min_Temp..Max_Temp;
Function "-"( Input : String ) Return Temp_Range;
Function "+"( Input : Temp_Range ) Return String;
Type See_Range is range Min_See..Max_See;
Function "-"( Input : String ) Return See_Range;
Function "+"( Input : See_Range ) Return String;
-------------------
-- REPORT DATA --
-------------------
Type Report_Data is record
Wind_Speed : Wind_Range:= Max_Wind;
Temperature : Temp_Range:= Max_Temp;
Seeing : See_Range := Max_See;
Conditions : Sky := Sky'Last;
Wind_Direction : Direction := Direction'Last;
Initalized : Bit_Vector(Natural'Pred(1)..Natural'Pred(5)):=
(Others => False);
End record;
------------------
-- REPORT MAP --
------------------
Package Report_Map is new Ada.Containers.Indefinite_Ordered_Maps(
--"=" => ,
"<" => Ada.Calendar."<",
Key_Type => Ada.Calendar.Time,
Element_Type => Report_Data
);
------------------------------------
-- WEATHER REPORT GNOGA ELEMENT --
------------------------------------
Type Weather_Report is new Abstract_Report with record
--Gnoga.Gui.Element.Common.DIV_Type with
-- record
Date : Gnoga.Gui.Element.Form.Date_Type;
Time : Gnoga.Gui.Element.Form.Time_Type;
Wind_Speed, Temperature, Seeing : Gnoga.Gui.Element.Form.Number_Type;
Conditions, Wind_Direction : Gnoga.Gui.Element.Form.Selection_Type;
end record;
overriding
procedure Create (Report : in out Weather_Report;
Parent : in out Gnoga.Gui.Base.Base_Type'Class;
Content : in String := "";
ID : in String := "" );
overriding
procedure Add_Self(
Self : in Weather_Report;
Form : in out Gnoga.Gui.Element.Form.Form_Type'Class
);
-- procedure Add_To_Form(
-- Self : in Weather_Report'Class;
-- Form : in out Gnoga.Gui.Element.Form.Form_Type'Class
-- );
Function Report( Object : in Weather_Report ) return String;
Function Report( Object : in Weather_Report ) return Reports;
Function Report( Data : in NSO.JSON.Instance'Class ) return Report_Map.Map;
--Function Report( Cursor : Report_Map.Cursor ) return String;
Function Report( Object : Report_Map.Map ) return String;
Private
Overriding Function Get_Name( Self : Weather_Report ) return String;
Function Report( Object : in Weather_Report ) return Reports is
(NSO.Types.Weather);
Function Report( Object : in Weather_Report ) return String is
( Reports'Image( Report(Object) ) );
Function "+"(Item : Field) return String renames Field'Image;
Function "+"(Item : String) return Field renames Field'Value;
Function "-"(Input : String) Return Wind_Range is (Wind_Range'Value(Input));
Function "-"(Input : String) Return Temp_Range is (Temp_Range'Value(Input));
Function "-"(Input : String) Return See_Range is (See_Range'Value(Input));
Function "+"( Input : Wind_Range ) Return String is (Wind_Range'Image(Input));
Function "+"( Input : Temp_Range ) Return String is (Temp_Range'image(Input));
Function "+"( Input : See_Range ) Return String is (See_Range'Image(Input));
End NSO.Types.Report_Objects.Weather_Report;
|
AdaCore/Ada_Drivers_Library | Ada | 3,027 | ads | ------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016-2020, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
package nRF.PPI is
subtype Channel_ID is Natural range 0 .. 15;
subtype Group_ID is Natural range 0 .. 5;
procedure Configure (Chan : Channel_ID;
Evt_EP : Event_Type;
Task_EP : Task_Type);
procedure Enable_Channel (Chan : Channel_ID);
procedure Disable_Channel (Chan : Channel_ID);
procedure Add_To_Group (Chan : Channel_ID;
Group : Group_ID);
procedure Remove_From_Group (Chan : Channel_ID;
Group : Group_ID);
procedure Enable_Group (Group : Group_ID);
procedure Disable_Group (Group : Group_ID);
end nRF.PPI;
|
stcarrez/ada-ado | Ada | 2,300 | ads | -----------------------------------------------------------------------
-- ado-mysql -- MySQL Database Drivers
-- Copyright (C) 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties;
-- === MySQL Database Driver ===
-- The MySQL database driver can be initialize explicitly by using the `ado_mysql`
-- GNAT project and calling the initialization procedure.
--
-- ADO.Mysql.Initialize ("db.properties");
--
-- The set of configuration properties can be set programatically and passed to the
-- `Initialize` operation.
--
-- Config : Util.Properties.Manager;
-- ...
-- Config.Set ("ado.database", "mysql://localhost:3306/ado_test");
-- Config.Set ("ado.queries.path", ".;db");
-- ADO.Mysql.Initialize (Config);
--
-- The MySQL database driver supports the following properties:
--
-- | Name | Description |
-- | ----------- | --------- |
-- | user | The user name to connect to the server |
-- | password | The user password to connect to the server |
-- | socket | The optional Unix socket path for a Unix socket base connection |
-- | encoding | The encoding to be used for the connection (ex: UTF-8) |
--
package ADO.Mysql is
-- Initialize the Mysql driver.
procedure Initialize;
-- Initialize the drivers and the library by reading the property file
-- and configure the runtime with it.
procedure Initialize (Config : in String);
-- Initialize the drivers and the library and configure the runtime with the given properties.
procedure Initialize (Config : in Util.Properties.Manager'Class);
end ADO.Mysql;
|
reznikmm/jwt | Ada | 4,640 | ads | -- Copyright (c) 2020 Maxim Reznik <[email protected]>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Streams;
with League.JSON.Objects;
with League.String_Vectors;
with League.Strings;
with League.Stream_Element_Vectors;
package JWS is
type JSON_Web_Signature is tagged private;
-- JSON Web Signature (JWS) represents content secured with digital
-- signatures or Message Authentication Codes (MACs) using JSON-based data
-- structures. The JWS cryptographic mechanisms provide integrity
-- protection for an arbitrary sequence of octets.
type JOSE_Header;
not overriding function Header
(Self : JSON_Web_Signature) return JOSE_Header;
type JOSE_Header is new League.JSON.Objects.JSON_Object with null record;
-- JSON Object Signing and Encryption Header
function Algorithm (Self : JOSE_Header'Class)
return League.Strings.Universal_String;
-- The "alg" (algorithm) Header Parameter identifies the cryptographic
-- algorithm used to secure the JWS.
procedure Set_Algorithm
(Self : in out JOSE_Header'Class;
Value : League.Strings.Universal_String);
function Critical (Self : JOSE_Header'Class)
return League.String_Vectors.Universal_String_Vector;
-- The "crit" (critical) Header Parameter indicates that extensions to this
-- specification and/or [JWA] are being used that MUST be understood and
-- processed.
procedure Set_Critical
(Self : in out JOSE_Header'Class;
Value : League.String_Vectors.Universal_String_Vector);
procedure Create
(Self : out JSON_Web_Signature'Class;
Header : JOSE_Header;
Payload : Ada.Streams.Stream_Element_Array;
Secret : Ada.Streams.Stream_Element_Array);
function Compact_Serialization
(Self : JSON_Web_Signature'Class) return League.Strings.Universal_String;
-- A representation of the JWS as a compact, URL-safe string.
procedure Validate_Compact_Serialization
(Self : out JSON_Web_Signature'Class;
Value : League.Strings.Universal_String;
Secret : Ada.Streams.Stream_Element_Array;
Valid : out Boolean);
-- Validate given compact serialization using Secret
function Flattened_Serialization
(Self : JSON_Web_Signature'Class) return League.JSON.Objects.JSON_Object;
-- A representation of the JWS using Flattened Serialization Syntax.
function Payload
(Self : JSON_Web_Signature'Class) return Ada.Streams.Stream_Element_Array;
-- Return the payload from given signature.
function Payload_Vector
(Self : JSON_Web_Signature'Class)
return League.Stream_Element_Vectors.Stream_Element_Vector;
-- Return the payload from given signature as Stream_Element vector.
function Payload_Object
(Self : JSON_Web_Signature'Class)
return League.JSON.Objects.JSON_Object;
-- Return the payload from given signature as JSON Object.
function Thumbprint
(Key : League.JSON.Objects.JSON_Object)
return Ada.Streams.Stream_Element_Array;
-- Return binary representation of the Key as described in RFC-7638.
-- Suppose the Key contains only required properties.
private
type JSON_Web_Signature is tagged record
Header : JOSE_Header;
Payload : League.Stream_Element_Vectors.Stream_Element_Vector;
Secret : League.Stream_Element_Vectors.Stream_Element_Vector;
end record;
function Compute_Signature
(Self : JOSE_Header'Class;
Data : League.Stream_Element_Vectors.Stream_Element_Vector;
Secret : Ada.Streams.Stream_Element_Array)
return League.Stream_Element_Vectors.Stream_Element_Vector;
function Validate_Signature
(Self : JOSE_Header'Class;
Data : League.Stream_Element_Vectors.Stream_Element_Vector;
Secret : Ada.Streams.Stream_Element_Array;
Value : League.Stream_Element_Vectors.Stream_Element_Vector)
return Boolean;
type Signature_Function is access
function
(Data : League.Stream_Element_Vectors.Stream_Element_Vector;
Secret : Ada.Streams.Stream_Element_Array)
return League.Stream_Element_Vectors.Stream_Element_Vector;
type Validate_Signature_Function is access
function
(Data : League.Stream_Element_Vectors.Stream_Element_Vector;
Secret : Ada.Streams.Stream_Element_Array;
Value : League.Stream_Element_Vectors.Stream_Element_Vector)
return Boolean;
RS256_Signature_Link : Signature_Function;
RS256_Validation_Link : Validate_Signature_Function;
end JWS;
|
charlie5/lace | Ada | 5,195 | ads | with
physics.Space,
physics.Joint,
physics.Object,
lace.Observer,
lace.Any,
ada.Tags;
package physics.Engine
--
-- Provides a task which evolves a physical space.
--
is
type Item is tagged limited private;
type View is access all Item'Class;
-- procedure start (Self : access Item; space_Kind : in physics.space_Kind);
procedure start (Self : access Item; the_Space : in Space.view);
procedure stop (Self : access Item);
procedure add (Self : access Item; the_Object : in Object.view);
procedure rid (Self : in out Item; the_Object : in Object.view);
procedure add (Self : in out Item; the_Joint : in Joint.view);
procedure rid (Self : in out Item; the_Joint : in Joint.view);
procedure update_Scale (Self : in out Item; of_Object : in Object.view;
To : in math.Vector_3);
procedure apply_Force (Self : in out Item; to_Object : in Object.view;
Force : in math.Vector_3);
procedure update_Site (Self : in out Item; of_Object : in Object.view;
To : in math.Vector_3);
procedure set_Speed (Self : in out Item; of_Object : in Object.view;
To : in math.Vector_3);
procedure set_Gravity (Self : in out Item; To : in math.Vector_3);
procedure set_xy_Spin (Self : in out Item; of_Object : in Object.view;
To : in math.Radians);
procedure update_Bounds (Self : in out Item; of_Object : in Object.view);
procedure set_local_Anchor (Self : in out Item; for_Joint : in Joint.view;
To : in math.Vector_3;
is_Anchor_A : in Boolean);
private
task
type Evolver (Self : access Engine.item'Class)
is
-- entry start (space_Kind : in physics.space_Kind);
entry start (the_Space : in Space.view);
entry stop;
entry reset_Age;
pragma Storage_Size (20_000_000);
end Evolver;
-- Engine Commands
--
type Any_limited_view is access all lace.Any.limited_item'Class;
type command_Kind is (add_Object, rid_Object,
scale_Object, destroy_Object,
update_Bounds, update_Site,
set_Speed, apply_Force,
set_xy_Spin,
add_Joint, rid_Joint,
set_Joint_local_Anchor,
free_Joint,
cast_Ray,
-- new_impact_Response,
set_Gravity);
type Command (Kind : command_Kind := command_Kind'First) is
record
Object : physics.Object.view;
case Kind
is
when add_Object =>
add_Children : Boolean;
-- Model : physics.Model.view;
when rid_Object =>
rid_Children : Boolean;
when update_Site =>
Site : math.Vector_3;
when scale_Object =>
Scale : math.Vector_3;
when apply_Force =>
Force : math.Vector_3;
when set_Speed =>
Speed : math.Vector_3;
when set_Gravity =>
Gravity : math.Vector_3;
when set_xy_Spin =>
xy_Spin : math.Radians;
when add_Joint | rid_Joint | free_Joint =>
Joint : physics.Joint.view;
when set_Joint_local_Anchor =>
anchor_Joint : physics.Joint.view;
is_Anchor_A : Boolean; -- When false, is anchor B.
local_Anchor : math.Vector_3;
when cast_Ray =>
From, To : math.Vector_3;
Observer : lace.Observer.view;
Context : Any_limited_view;
event_Kind : ada.Tags.Tag;
-- when new_impact_Response =>
-- Filter : impact_Filter;
-- Response : impact_Response;
when others =>
null;
end case;
end record;
type Commands is array (Positive range 1 .. 200_000) of Command;
protected
type safe_command_Set
is
function is_Empty return Boolean;
procedure add (the_Command : in Command);
procedure Fetch (To : out Commands;
Count : out Natural);
private
Set : Commands;
the_Count : Natural := 0;
end safe_command_Set;
type safe_command_Set_view is access all safe_command_Set;
type Item is tagged limited
record
Age : Duration := 0.0;
Space : physics.Space.view;
Commands : safe_command_Set_view := new safe_command_Set;
Evolver : engine.Evolver (Item'Access);
end record;
end physics.Engine;
|
zhmu/ananas | Ada | 4,521 | ads | ------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- G N A T . D E B U G _ U T I L I T I E S --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2022, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Debugging utilities
-- This package provides some useful utility subprograms for use in writing
-- routines that generate debugging output.
with System;
package GNAT.Debug_Utilities is
pragma Pure;
Address_64 : constant Boolean := Standard'Address_Size = 64;
-- Set true if 64 bit addresses (assumes only 32 and 64 are possible)
Address_Image_Length : constant := 13 + 10 * Boolean'Pos (Address_64);
-- Length of string returned by Image function for an address
subtype Image_String is String (1 .. Address_Image_Length);
-- Subtype returned by Image function for an address
Address_Image_C_Length : constant := 10 + 8 * Boolean'Pos (Address_64);
-- Length of string returned by Image_C function
subtype Image_C_String is String (1 .. Address_Image_C_Length);
-- Subtype returned by Image_C function
function Image (S : String) return String;
-- Returns a string image of S, obtained by prepending and appending
-- quote (") characters and doubling any quote characters in the string.
-- The maximum length of the result is thus 2 ** S'Length + 2.
function Image (A : System.Address) return Image_String;
-- Returns a string of the form 16#hhhh_hhhh# for 32-bit addresses
-- or 16#hhhh_hhhh_hhhh_hhhh# for 64-bit addresses. Hex characters
-- are in upper case.
function Image_C (A : System.Address) return Image_C_String;
-- Returns a string of the form 0xhhhhhhhh for 32 bit addresses or
-- 0xhhhhhhhhhhhhhhhh for 64-bit addresses. Hex characters are in
-- upper case.
function Value (S : String) return System.Address;
-- Given a valid integer literal in any form, including the form returned
-- by the Image function in this package, yields the corresponding address.
-- Note that this routine will handle any Ada integer format, and will
-- also handle hex constants in C format (0xhh..hhh). Constraint_Error
-- may be raised for obviously incorrect data, but the routine is fairly
-- permissive, and in particular, all underscores in whatever position
-- are simply ignored completely.
end GNAT.Debug_Utilities;
|
strenkml/EE368 | Ada | 3,942 | adb |
package body Memory.Option is
function Create_Option return Option_Pointer is
result : constant Option_Pointer := new Option_Type;
begin
return result;
end Create_Option;
function Clone(mem : Option_Type) return Memory_Pointer is
result : constant Option_Pointer := new Option_Type'(mem);
begin
return Memory_Pointer(result);
end Clone;
procedure Permute(mem : in out Option_Type;
generator : in Distribution_Type;
max_cost : in Cost_Type) is
begin
mem.index := Random(generator) mod (mem.memories.Last_Index + 1);
end Permute;
procedure Add_Memory(mem : in out Option_Type;
other : access Memory_Type'Class) is
begin
mem.memories.Append(Memory_Pointer(other));
end Add_Memory;
function Done(mem : Option_Type) return Boolean is
begin
return Done(mem.memories.Element(mem.index).all);
end Done;
procedure Reset(mem : in out Option_Type;
context : in Natural) is
begin
for i in mem.memories.First_Index .. mem.memories.Last_Index loop
Reset(mem.memories.Element(i).all, context);
end loop;
end Reset;
procedure Set_Port(mem : in out Option_Type;
port : in Natural;
ready : out Boolean) is
begin
Set_Port(mem.memories.Element(mem.index).all, port, ready);
end Set_Port;
procedure Read(mem : in out Option_Type;
address : in Address_Type;
size : in Positive) is
begin
Read(mem.memories.Element(mem.index).all, address, size);
end Read;
procedure Write(mem : in out Option_Type;
address : in Address_Type;
size : in Positive) is
begin
Write(mem.memories.Element(mem.index).all, address, size);
end Write;
procedure Idle(mem : in out Option_Type;
cycles : in Time_Type) is
begin
Idle(mem.memories.Element(mem.index).all, cycles);
end Idle;
function Get_Time(mem : Option_Type) return Time_Type is
begin
return Get_Time(mem.memories.Element(mem.index).all);
end Get_Time;
function Get_Writes(mem : Option_Type) return Long_Integer is
begin
return Get_Writes(mem.memories.Element(mem.index).all);
end Get_Writes;
function To_String(mem : Option_Type) return Unbounded_String is
begin
return To_String(mem.memories.Element(mem.index).all);
end To_String;
function Get_Cost(mem : Option_Type) return Cost_Type is
begin
return Get_Cost(mem.memories.Element(mem.index).all);
end Get_Cost;
function Get_Word_Size(mem : Option_Type) return Positive is
begin
return Get_Word_Size(mem.memories.Element(mem.index).all);
end Get_Word_Size;
procedure Generate(mem : in Option_Type;
sigs : in out Unbounded_String;
code : in out Unbounded_String) is
begin
Generate(mem.memories.Element(mem.index).all, sigs, code);
end Generate;
function Get_Ports(mem : Option_Type) return Port_Vector_Type is
begin
return Get_Ports(mem.memories.Element(mem.index).all);
end Get_Ports;
procedure Adjust(mem : in out Option_Type) is
begin
for i in mem.memories.First_Index .. mem.memories.Last_Index loop
declare
ptr : constant Memory_Pointer := mem.memories.Element(i);
begin
mem.memories.Replace_Element(i, Clone(ptr.all));
end;
end loop;
end Adjust;
procedure Finalize(mem : in out Option_Type) is
begin
for i in mem.memories.First_Index .. mem.memories.Last_Index loop
declare
ptr : Memory_Pointer := mem.memories.Element(i);
begin
Destroy(ptr);
end;
end loop;
end Finalize;
end Memory.Option;
|
reznikmm/matreshka | Ada | 5,797 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with AMF.Internals.UML_Elements;
with AMF.UML.Input_Pins;
with AMF.UML.Properties;
with AMF.UML.Qualifier_Values;
with AMF.Visitors;
package AMF.Internals.UML_Qualifier_Values is
type UML_Qualifier_Value_Proxy is
limited new AMF.Internals.UML_Elements.UML_Element_Proxy
and AMF.UML.Qualifier_Values.UML_Qualifier_Value with null record;
overriding function Get_Qualifier
(Self : not null access constant UML_Qualifier_Value_Proxy)
return AMF.UML.Properties.UML_Property_Access;
-- Getter of QualifierValue::qualifier.
--
-- Attribute representing the qualifier for which the value is to be
-- specified.
overriding procedure Set_Qualifier
(Self : not null access UML_Qualifier_Value_Proxy;
To : AMF.UML.Properties.UML_Property_Access);
-- Setter of QualifierValue::qualifier.
--
-- Attribute representing the qualifier for which the value is to be
-- specified.
overriding function Get_Value
(Self : not null access constant UML_Qualifier_Value_Proxy)
return AMF.UML.Input_Pins.UML_Input_Pin_Access;
-- Getter of QualifierValue::value.
--
-- Input pin from which the specified value for the qualifier is taken.
overriding procedure Set_Value
(Self : not null access UML_Qualifier_Value_Proxy;
To : AMF.UML.Input_Pins.UML_Input_Pin_Access);
-- Setter of QualifierValue::value.
--
-- Input pin from which the specified value for the qualifier is taken.
overriding procedure Enter_Element
(Self : not null access constant UML_Qualifier_Value_Proxy;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control);
-- Dispatch call to corresponding subprogram of visitor interface.
overriding procedure Leave_Element
(Self : not null access constant UML_Qualifier_Value_Proxy;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control);
-- Dispatch call to corresponding subprogram of visitor interface.
overriding procedure Visit_Element
(Self : not null access constant UML_Qualifier_Value_Proxy;
Iterator : in out AMF.Visitors.Abstract_Iterator'Class;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control);
-- Dispatch call to corresponding subprogram of iterator interface.
end AMF.Internals.UML_Qualifier_Values;
|
faelys/natools | Ada | 1,636 | ads | ------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Time_Statistics.Fine_Timer_Difference provides a difference --
-- function between real-time moments as a Duration value. --
------------------------------------------------------------------------------
with Ada.Real_Time;
function Natools.Time_Statistics.Fine_Timer_Difference
(Left, Right : Ada.Real_Time.Time)
return Duration;
|
onox/orka | Ada | 8,956 | adb | -- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Numerics.Generic_Elementary_Functions;
package body Orka.Transforms.SIMD_Matrices is
package EF is new Ada.Numerics.Generic_Elementary_Functions (Element_Type);
function T (Offset : Vectors.Point) return Matrix_Type is
Result : Matrix_Type := Identity_Matrix;
begin
Result (W) := Vector_Type (Offset);
return Result;
end T;
function T (Offset : Vector_Type) return Matrix_Type is
Result : Matrix_Type := Identity_Matrix;
begin
Result (W) := Offset;
Result (W) (W) := 1.0;
return Result;
end T;
function Rx (Angle : Element_Type) return Matrix_Type is
CA : constant Element_Type := EF.Cos (Angle);
SA : constant Element_Type := EF.Sin (Angle);
Result : Matrix_Type := Identity_Matrix;
begin
Result (Y) := (0.0, CA, SA, 0.0);
Result (Z) := (0.0, -SA, CA, 0.0);
return Result;
end Rx;
function Ry (Angle : Element_Type) return Matrix_Type is
CA : constant Element_Type := EF.Cos (Angle);
SA : constant Element_Type := EF.Sin (Angle);
Result : Matrix_Type := Identity_Matrix;
begin
Result (X) := (CA, 0.0, -SA, 0.0);
Result (Z) := (SA, 0.0, CA, 0.0);
return Result;
end Ry;
function Rz (Angle : Element_Type) return Matrix_Type is
CA : constant Element_Type := EF.Cos (Angle);
SA : constant Element_Type := EF.Sin (Angle);
Result : Matrix_Type := Identity_Matrix;
begin
Result (X) := (CA, SA, 0.0, 0.0);
Result (Y) := (-SA, CA, 0.0, 0.0);
return Result;
end Rz;
function R (Axis : Vector_Type; Angle : Element_Type) return Matrix_Type is
CA : constant Element_Type := EF.Cos (Angle);
SA : constant Element_Type := EF.Sin (Angle);
MCA : constant Element_Type := 1.0 - CA;
MCARXY : constant Element_Type := MCA * Axis (X) * Axis (Y);
MCARXZ : constant Element_Type := MCA * Axis (X) * Axis (Z);
MCARYZ : constant Element_Type := MCA * Axis (Y) * Axis (Z);
RXSA : constant Element_Type := Axis (X) * SA;
RYSA : constant Element_Type := Axis (Y) * SA;
RZSA : constant Element_Type := Axis (Z) * SA;
R11 : constant Element_Type := CA + MCA * Axis (X)**2;
R12 : constant Element_Type := MCARXY + RZSA;
R13 : constant Element_Type := MCARXZ - RYSA;
R21 : constant Element_Type := MCARXY - RZSA;
R22 : constant Element_Type := CA + MCA * Axis (Y)**2;
R23 : constant Element_Type := MCARYZ + RXSA;
R31 : constant Element_Type := MCARXZ + RYSA;
R32 : constant Element_Type := MCARYZ - RXSA;
R33 : constant Element_Type := CA + MCA * Axis (Z)**2;
Result : Matrix_Type;
begin
Result (X) := (R11, R12, R13, 0.0);
Result (Y) := (R21, R22, R23, 0.0);
Result (Z) := (R31, R32, R33, 0.0);
Result (W) := (0.0, 0.0, 0.0, 1.0);
return Result;
end R;
function R (Quaternion : Vector_Type) return Matrix_Type is
Result : Matrix_Type := Identity_Matrix;
Q_X : constant Element_Type := Quaternion (X);
Q_Y : constant Element_Type := Quaternion (Y);
Q_Z : constant Element_Type := Quaternion (Z);
Q_W : constant Element_Type := Quaternion (W);
S : constant := 2.0;
-- S = 2 / Norm (Quaternion)
begin
Result (X) (X) := 1.0 - S * (Q_Y * Q_Y + Q_Z * Q_Z);
Result (X) (Y) := S * (Q_X * Q_Y + Q_Z * Q_W);
Result (X) (Z) := S * (Q_X * Q_Z - Q_Y * Q_W);
Result (Y) (X) := S * (Q_X * Q_Y - Q_Z * Q_W);
Result (Y) (Y) := 1.0 - S * (Q_X * Q_X + Q_Z * Q_Z);
Result (Y) (Z) := S * (Q_Y * Q_Z + Q_X * Q_W);
Result (Z) (X) := S * (Q_X * Q_Z + Q_Y * Q_W);
Result (Z) (Y) := S * (Q_Y * Q_Z - Q_X * Q_W);
Result (Z) (Z) := 1.0 - S * (Q_X * Q_X + Q_Y * Q_Y);
return Result;
end R;
function R (From, To : Vector_Type) return Matrix_Type is
S : constant Vector4 := Vectors.Normalize (From);
T : constant Vector4 := Vectors.Normalize (To);
-- Equations 4.54 and 4.55 from chapter 4.3 Quaternions from
-- Real-Time Rendering (third edition, 2008)
V : constant Vector4 := Vectors.Cross (S, T);
E : constant Element_Type := Vectors.Dot (S, T);
H : constant Element_Type := 1.0 / (1.0 + E);
Result : Matrix_Type := Identity_Matrix;
begin
-- TODO Handle when From and To are near parallel: Norm (V) is approximately 0.0
Result (X) (X) := E + H * (V (X) ** 2);
Result (X) (Y) := H * V (X) * V (Y) + V (Z);
Result (X) (Z) := H * V (X) * V (Z) - V (Y);
Result (Y) (X) := H * V (X) * V (Y) - V (Z);
Result (Y) (Y) := E + H * (V (Y) ** 2);
Result (Y) (Z) := H * V (Y) * V (Z) + V (X);
Result (Z) (X) := H * V (X) * V (Z) + V (Y);
Result (Z) (Y) := H * V (Y) * V (Z) - V (X);
Result (Z) (Z) := E + H * (V (Z) ** 2);
return Result;
end R;
function S (Factors : Vector_Type) return Matrix_Type is
Result : Matrix_Type := Identity_Matrix;
begin
Result (X) (X) := Factors (X);
Result (Y) (Y) := Factors (Y);
Result (Z) (Z) := Factors (Z);
return Result;
end S;
function Euler (R : Matrix_Type) return Vector_Type is
Pitch : constant Element_Type := EF.Arcsin (R (Y) (Z));
begin
-- Equations 4.22 and 4.23 from section 4.2.2 from
-- Real-Time Rendering (third edition, 2008)
if R (Y) (Z) = -1.0 or R (Y) (Z) = 1.0 then
declare
Roll : constant Element_Type := EF.Arctan (-R (X) (Y), R (X) (X));
begin
return (0.0, Pitch, Roll, 0.0);
end;
else
declare
Yaw : constant Element_Type := EF.Arctan (-R (X) (Z), R (Z) (Z));
Roll : constant Element_Type := EF.Arctan (-R (Y) (X), R (Y) (Y));
begin
return (Yaw, Pitch, Roll, 0.0);
end;
end if;
end Euler;
----------------------------------------------------------------------------
function FOV (Width, Distance : Element_Type) return Element_Type is
(2.0 * EF.Arctan (Width / (2.0 * Distance)));
function Finite_Perspective (FOV, Aspect, Z_Near, Z_Far : Element_Type) return Matrix_Type is
F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV);
Result : Matrix_Type := Identity_Matrix;
begin
Result (X) (X) := F / Aspect;
Result (Y) (Y) := F;
-- Depth normalized to [0, 1] instead of [-1 , 1]
Result (Z) (Z) := Z_Far / (Z_Near - Z_Far);
Result (W) (Z) := (Z_Near * Z_Far) / (Z_Near - Z_Far);
Result (Z) (W) := Element_Type (-1.0);
Result (W) (W) := Element_Type (0.0);
return Result;
end Finite_Perspective;
function Infinite_Perspective (FOV, Aspect, Z_Near : Element_Type) return Matrix_Type is
F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV);
Result : Matrix_Type := Identity_Matrix;
begin
Result (X) (X) := F / Aspect;
Result (Y) (Y) := F;
-- Depth normalized to [0, 1] instead of [-1 , 1]
Result (Z) (Z) := Element_Type (-1.0);
Result (W) (Z) := -Z_Near;
Result (Z) (W) := Element_Type (-1.0);
Result (W) (W) := Element_Type (0.0);
return Result;
end Infinite_Perspective;
function Infinite_Perspective_Reversed_Z
(FOV, Aspect, Z_Near : Element_Type) return Matrix_Type
is
F : constant Element_Type := 1.0 / EF.Tan (0.5 * FOV);
Result : Matrix_Type := Identity_Matrix;
begin
Result (X) (X) := F / Aspect;
Result (Y) (Y) := F;
-- Depth normalized to [1, 0] instead of [-1 , 1]
Result (Z) (Z) := Element_Type (0.0);
Result (W) (Z) := Z_Near;
Result (Z) (W) := Element_Type (-1.0);
Result (W) (W) := Element_Type (0.0);
return Result;
end Infinite_Perspective_Reversed_Z;
function Orthographic (X_Mag, Y_Mag, Z_Near, Z_Far : Element_Type) return Matrix_Type is
Result : Matrix_Type := Identity_Matrix;
begin
Result (X) (X) := 2.0 / X_Mag;
Result (Y) (Y) := 2.0 / Y_Mag;
-- Depth normalized to [0, 1] instead of [-1, 1]
Result (Z) (Z) := -1.0 / (Z_Far - Z_Near);
Result (W) (Z) := -Z_Near / (Z_Far - Z_Near);
return Result;
end Orthographic;
end Orka.Transforms.SIMD_Matrices;
|
zhmu/ananas | Ada | 51,783 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- A D A . C O N T A I N E R S . F O R M A L _ O R D E R E D _ S E T S --
-- --
-- B o d y --
-- --
-- Copyright (C) 2010-2022, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
------------------------------------------------------------------------------
with Ada.Containers.Red_Black_Trees.Generic_Bounded_Operations;
pragma Elaborate_All
(Ada.Containers.Red_Black_Trees.Generic_Bounded_Operations);
with Ada.Containers.Red_Black_Trees.Generic_Bounded_Keys;
pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Bounded_Keys);
with Ada.Containers.Red_Black_Trees.Generic_Bounded_Set_Operations;
pragma Elaborate_All
(Ada.Containers.Red_Black_Trees.Generic_Bounded_Set_Operations);
with System; use type System.Address;
package body Ada.Containers.Formal_Ordered_Sets with
SPARK_Mode => Off
is
------------------------------
-- Access to Fields of Node --
------------------------------
-- These subprograms provide functional notation for access to fields
-- of a node, and procedural notation for modifiying these fields.
function Color (Node : Node_Type) return Red_Black_Trees.Color_Type;
pragma Inline (Color);
function Left_Son (Node : Node_Type) return Count_Type;
pragma Inline (Left_Son);
function Parent (Node : Node_Type) return Count_Type;
pragma Inline (Parent);
function Right_Son (Node : Node_Type) return Count_Type;
pragma Inline (Right_Son);
procedure Set_Color
(Node : in out Node_Type;
Color : Red_Black_Trees.Color_Type);
pragma Inline (Set_Color);
procedure Set_Left (Node : in out Node_Type; Left : Count_Type);
pragma Inline (Set_Left);
procedure Set_Right (Node : in out Node_Type; Right : Count_Type);
pragma Inline (Set_Right);
procedure Set_Parent (Node : in out Node_Type; Parent : Count_Type);
pragma Inline (Set_Parent);
-----------------------
-- Local Subprograms --
-----------------------
-- Comments needed???
procedure Assign
(Target : in out Tree_Types.Tree_Type;
Source : Tree_Types.Tree_Type);
generic
with procedure Set_Element (Node : in out Node_Type);
procedure Generic_Allocate
(Tree : in out Tree_Types.Tree_Type'Class;
Node : out Count_Type);
procedure Free (Tree : in out Set; X : Count_Type);
procedure Insert_Sans_Hint
(Container : in out Tree_Types.Tree_Type;
New_Item : Element_Type;
Node : out Count_Type;
Inserted : out Boolean);
procedure Insert_With_Hint
(Dst_Set : in out Tree_Types.Tree_Type;
Dst_Hint : Count_Type;
Src_Node : Node_Type;
Dst_Node : out Count_Type);
function Is_Greater_Element_Node
(Left : Element_Type;
Right : Node_Type) return Boolean;
pragma Inline (Is_Greater_Element_Node);
function Is_Less_Element_Node
(Left : Element_Type;
Right : Node_Type) return Boolean;
pragma Inline (Is_Less_Element_Node);
function Is_Less_Node_Node (L, R : Node_Type) return Boolean;
pragma Inline (Is_Less_Node_Node);
procedure Replace_Element
(Tree : in out Set;
Node : Count_Type;
Item : Element_Type);
--------------------------
-- Local Instantiations --
--------------------------
package Tree_Operations is
new Red_Black_Trees.Generic_Bounded_Operations
(Tree_Types,
Left => Left_Son,
Right => Right_Son);
use Tree_Operations;
package Element_Keys is
new Red_Black_Trees.Generic_Bounded_Keys
(Tree_Operations => Tree_Operations,
Key_Type => Element_Type,
Is_Less_Key_Node => Is_Less_Element_Node,
Is_Greater_Key_Node => Is_Greater_Element_Node);
package Set_Ops is
new Red_Black_Trees.Generic_Bounded_Set_Operations
(Tree_Operations => Tree_Operations,
Set_Type => Tree_Types.Tree_Type,
Assign => Assign,
Insert_With_Hint => Insert_With_Hint,
Is_Less => Is_Less_Node_Node);
---------
-- "=" --
---------
function "=" (Left, Right : Set) return Boolean is
Lst : Count_Type;
Node : Count_Type;
ENode : Count_Type;
begin
if Length (Left) /= Length (Right) then
return False;
end if;
if Is_Empty (Left) then
return True;
end if;
Lst := Next (Left.Content, Last (Left).Node);
Node := First (Left).Node;
while Node /= Lst loop
ENode := Find (Right, Left.Content.Nodes (Node).Element).Node;
if ENode = 0
or else Left.Content.Nodes (Node).Element /=
Right.Content.Nodes (ENode).Element
then
return False;
end if;
Node := Next (Left.Content, Node);
end loop;
return True;
end "=";
------------
-- Assign --
------------
procedure Assign
(Target : in out Tree_Types.Tree_Type;
Source : Tree_Types.Tree_Type)
is
procedure Append_Element (Source_Node : Count_Type);
procedure Append_Elements is
new Tree_Operations.Generic_Iteration (Append_Element);
--------------------
-- Append_Element --
--------------------
procedure Append_Element (Source_Node : Count_Type) is
SN : Node_Type renames Source.Nodes (Source_Node);
procedure Set_Element (Node : in out Node_Type);
pragma Inline (Set_Element);
function New_Node return Count_Type;
pragma Inline (New_Node);
procedure Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Unconditional_Insert_Sans_Hint is
new Element_Keys.Generic_Unconditional_Insert (Insert_Post);
procedure Unconditional_Insert_Avec_Hint is
new Element_Keys.Generic_Unconditional_Insert_With_Hint
(Insert_Post,
Unconditional_Insert_Sans_Hint);
procedure Allocate is new Generic_Allocate (Set_Element);
--------------
-- New_Node --
--------------
function New_Node return Count_Type is
Result : Count_Type;
begin
Allocate (Target, Result);
return Result;
end New_Node;
-----------------
-- Set_Element --
-----------------
procedure Set_Element (Node : in out Node_Type) is
begin
Node.Element := SN.Element;
end Set_Element;
-- Local variables
Target_Node : Count_Type;
-- Start of processing for Append_Element
begin
Unconditional_Insert_Avec_Hint
(Tree => Target,
Hint => 0,
Key => SN.Element,
Node => Target_Node);
end Append_Element;
-- Start of processing for Assign
begin
if Target'Address = Source'Address then
return;
end if;
if Target.Capacity < Source.Length then
raise Constraint_Error
with "Target capacity is less than Source length";
end if;
Tree_Operations.Clear_Tree (Target);
Append_Elements (Source);
end Assign;
procedure Assign (Target : in out Set; Source : Set) is
begin
Assign (Target.Content, Source.Content);
end Assign;
-------------
-- Ceiling --
-------------
function Ceiling (Container : Set; Item : Element_Type) return Cursor is
Node : constant Count_Type :=
Element_Keys.Ceiling (Container.Content, Item);
begin
if Node = 0 then
return No_Element;
end if;
return (Node => Node);
end Ceiling;
-----------
-- Clear --
-----------
procedure Clear (Container : in out Set) is
begin
Tree_Operations.Clear_Tree (Container.Content);
end Clear;
-----------
-- Color --
-----------
function Color (Node : Node_Type) return Red_Black_Trees.Color_Type is
begin
return Node.Color;
end Color;
------------------------
-- Constant_Reference --
------------------------
function Constant_Reference
(Container : aliased Set;
Position : Cursor) return not null access constant Element_Type
is
begin
if not Has_Element (Container, Position) then
raise Constraint_Error with "Position cursor has no element";
end if;
pragma Assert (Vet (Container.Content, Position.Node),
"bad cursor in Element");
return Container.Content.Nodes (Position.Node).Element'Access;
end Constant_Reference;
--------------
-- Contains --
--------------
function Contains
(Container : Set;
Item : Element_Type) return Boolean
is
begin
return Find (Container, Item) /= No_Element;
end Contains;
----------
-- Copy --
----------
function Copy (Source : Set; Capacity : Count_Type := 0) return Set is
Node : Count_Type;
N : Count_Type;
Target : Set (Count_Type'Max (Source.Capacity, Capacity));
begin
if 0 < Capacity and then Capacity < Source.Capacity then
raise Capacity_Error;
end if;
if Length (Source) > 0 then
Target.Content.Length := Source.Content.Length;
Target.Content.Root := Source.Content.Root;
Target.Content.First := Source.Content.First;
Target.Content.Last := Source.Content.Last;
Target.Content.Free := Source.Content.Free;
Node := 1;
while Node <= Source.Capacity loop
Target.Content.Nodes (Node).Element :=
Source.Content.Nodes (Node).Element;
Target.Content.Nodes (Node).Parent :=
Source.Content.Nodes (Node).Parent;
Target.Content.Nodes (Node).Left :=
Source.Content.Nodes (Node).Left;
Target.Content.Nodes (Node).Right :=
Source.Content.Nodes (Node).Right;
Target.Content.Nodes (Node).Color :=
Source.Content.Nodes (Node).Color;
Target.Content.Nodes (Node).Has_Element :=
Source.Content.Nodes (Node).Has_Element;
Node := Node + 1;
end loop;
while Node <= Target.Capacity loop
N := Node;
Free (Tree => Target, X => N);
Node := Node + 1;
end loop;
end if;
return Target;
end Copy;
------------
-- Delete --
------------
procedure Delete (Container : in out Set; Position : in out Cursor) is
begin
if not Has_Element (Container, Position) then
raise Constraint_Error with "Position cursor has no element";
end if;
pragma Assert (Vet (Container.Content, Position.Node),
"bad cursor in Delete");
Tree_Operations.Delete_Node_Sans_Free (Container.Content,
Position.Node);
Free (Container, Position.Node);
Position := No_Element;
end Delete;
procedure Delete (Container : in out Set; Item : Element_Type) is
X : constant Count_Type := Element_Keys.Find (Container.Content, Item);
begin
if X = 0 then
raise Constraint_Error with "attempt to delete element not in set";
end if;
Tree_Operations.Delete_Node_Sans_Free (Container.Content, X);
Free (Container, X);
end Delete;
------------------
-- Delete_First --
------------------
procedure Delete_First (Container : in out Set) is
X : constant Count_Type := Container.Content.First;
begin
if X /= 0 then
Tree_Operations.Delete_Node_Sans_Free (Container.Content, X);
Free (Container, X);
end if;
end Delete_First;
-----------------
-- Delete_Last --
-----------------
procedure Delete_Last (Container : in out Set) is
X : constant Count_Type := Container.Content.Last;
begin
if X /= 0 then
Tree_Operations.Delete_Node_Sans_Free (Container.Content, X);
Free (Container, X);
end if;
end Delete_Last;
----------------
-- Difference --
----------------
procedure Difference (Target : in out Set; Source : Set) is
begin
Set_Ops.Set_Difference (Target.Content, Source.Content);
end Difference;
function Difference (Left, Right : Set) return Set is
begin
if Left'Address = Right'Address then
return Empty_Set;
end if;
if Length (Left) = 0 then
return Empty_Set;
end if;
if Length (Right) = 0 then
return Copy (Left);
end if;
return S : Set (Length (Left)) do
Assign
(S.Content, Set_Ops.Set_Difference (Left.Content, Right.Content));
end return;
end Difference;
-------------
-- Element --
-------------
function Element (Container : Set; Position : Cursor) return Element_Type is
begin
if not Has_Element (Container, Position) then
raise Constraint_Error with "Position cursor has no element";
end if;
pragma Assert (Vet (Container.Content, Position.Node),
"bad cursor in Element");
return Container.Content.Nodes (Position.Node).Element;
end Element;
-------------------------
-- Equivalent_Elements --
-------------------------
function Equivalent_Elements (Left, Right : Element_Type) return Boolean is
begin
if Left < Right
or else Right < Left
then
return False;
else
return True;
end if;
end Equivalent_Elements;
---------------------
-- Equivalent_Sets --
---------------------
function Equivalent_Sets (Left, Right : Set) return Boolean is
function Is_Equivalent_Node_Node
(L, R : Node_Type) return Boolean;
pragma Inline (Is_Equivalent_Node_Node);
function Is_Equivalent is
new Tree_Operations.Generic_Equal (Is_Equivalent_Node_Node);
-----------------------------
-- Is_Equivalent_Node_Node --
-----------------------------
function Is_Equivalent_Node_Node (L, R : Node_Type) return Boolean is
begin
if L.Element < R.Element then
return False;
elsif R.Element < L.Element then
return False;
else
return True;
end if;
end Is_Equivalent_Node_Node;
-- Start of processing for Equivalent_Sets
begin
return Is_Equivalent (Left.Content, Right.Content);
end Equivalent_Sets;
-------------
-- Exclude --
-------------
procedure Exclude (Container : in out Set; Item : Element_Type) is
X : constant Count_Type := Element_Keys.Find (Container.Content, Item);
begin
if X /= 0 then
Tree_Operations.Delete_Node_Sans_Free (Container.Content, X);
Free (Container, X);
end if;
end Exclude;
----------
-- Find --
----------
function Find (Container : Set; Item : Element_Type) return Cursor is
Node : constant Count_Type :=
Element_Keys.Find (Container.Content, Item);
begin
if Node = 0 then
return No_Element;
end if;
return (Node => Node);
end Find;
-----------
-- First --
-----------
function First (Container : Set) return Cursor is
begin
if Length (Container) = 0 then
return No_Element;
end if;
return (Node => Container.Content.First);
end First;
-------------------
-- First_Element --
-------------------
function First_Element (Container : Set) return Element_Type is
Fst : constant Count_Type := First (Container).Node;
begin
if Fst = 0 then
raise Constraint_Error with "set is empty";
end if;
declare
N : Tree_Types.Nodes_Type renames Container.Content.Nodes;
begin
return N (Fst).Element;
end;
end First_Element;
-----------
-- Floor --
-----------
function Floor (Container : Set; Item : Element_Type) return Cursor is
begin
declare
Node : constant Count_Type :=
Element_Keys.Floor (Container.Content, Item);
begin
if Node = 0 then
return No_Element;
end if;
return (Node => Node);
end;
end Floor;
------------------
-- Formal_Model --
------------------
package body Formal_Model is
-------------------------
-- E_Bigger_Than_Range --
-------------------------
function E_Bigger_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Item : Element_Type) return Boolean
is
begin
for I in Fst .. Lst loop
if not (E.Get (Container, I) < Item) then
return False;
end if;
end loop;
return True;
end E_Bigger_Than_Range;
-------------------------
-- E_Elements_Included --
-------------------------
function E_Elements_Included
(Left : E.Sequence;
Right : E.Sequence) return Boolean
is
begin
for I in 1 .. E.Length (Left) loop
if not E.Contains (Right, 1, E.Length (Right), E.Get (Left, I))
then
return False;
end if;
end loop;
return True;
end E_Elements_Included;
function E_Elements_Included
(Left : E.Sequence;
Model : M.Set;
Right : E.Sequence) return Boolean
is
begin
for I in 1 .. E.Length (Left) loop
declare
Item : constant Element_Type := E.Get (Left, I);
begin
if M.Contains (Model, Item) then
if not E.Contains (Right, 1, E.Length (Right), Item) then
return False;
end if;
end if;
end;
end loop;
return True;
end E_Elements_Included;
function E_Elements_Included
(Container : E.Sequence;
Model : M.Set;
Left : E.Sequence;
Right : E.Sequence) return Boolean
is
begin
for I in 1 .. E.Length (Container) loop
declare
Item : constant Element_Type := E.Get (Container, I);
begin
if M.Contains (Model, Item) then
if not E.Contains (Left, 1, E.Length (Left), Item) then
return False;
end if;
else
if not E.Contains (Right, 1, E.Length (Right), Item) then
return False;
end if;
end if;
end;
end loop;
return True;
end E_Elements_Included;
---------------
-- E_Is_Find --
---------------
function E_Is_Find
(Container : E.Sequence;
Item : Element_Type;
Position : Count_Type) return Boolean
is
begin
for I in 1 .. Position - 1 loop
if Item < E.Get (Container, I) then
return False;
end if;
end loop;
if Position < E.Length (Container) then
for I in Position + 1 .. E.Length (Container) loop
if E.Get (Container, I) < Item then
return False;
end if;
end loop;
end if;
return True;
end E_Is_Find;
--------------------------
-- E_Smaller_Than_Range --
--------------------------
function E_Smaller_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Item : Element_Type) return Boolean
is
begin
for I in Fst .. Lst loop
if not (Item < E.Get (Container, I)) then
return False;
end if;
end loop;
return True;
end E_Smaller_Than_Range;
----------
-- Find --
----------
function Find
(Container : E.Sequence;
Item : Element_Type) return Count_Type
is
begin
for I in 1 .. E.Length (Container) loop
if Equivalent_Elements (Item, E.Get (Container, I)) then
return I;
end if;
end loop;
return 0;
end Find;
--------------
-- Elements --
--------------
function Elements (Container : Set) return E.Sequence is
Position : Count_Type := Container.Content.First;
R : E.Sequence;
begin
-- Can't use First, Next or Element here, since they depend on models
-- for their postconditions.
while Position /= 0 loop
R := E.Add (R, Container.Content.Nodes (Position).Element);
Position := Tree_Operations.Next (Container.Content, Position);
end loop;
return R;
end Elements;
----------------------------
-- Lift_Abstraction_Level --
----------------------------
procedure Lift_Abstraction_Level (Container : Set) is null;
-----------------------
-- Mapping_Preserved --
-----------------------
function Mapping_Preserved
(E_Left : E.Sequence;
E_Right : E.Sequence;
P_Left : P.Map;
P_Right : P.Map) return Boolean
is
begin
for C of P_Left loop
if not P.Has_Key (P_Right, C)
or else P.Get (P_Left, C) > E.Length (E_Left)
or else P.Get (P_Right, C) > E.Length (E_Right)
or else E.Get (E_Left, P.Get (P_Left, C)) /=
E.Get (E_Right, P.Get (P_Right, C))
then
return False;
end if;
end loop;
return True;
end Mapping_Preserved;
------------------------------
-- Mapping_Preserved_Except --
------------------------------
function Mapping_Preserved_Except
(E_Left : E.Sequence;
E_Right : E.Sequence;
P_Left : P.Map;
P_Right : P.Map;
Position : Cursor) return Boolean
is
begin
for C of P_Left loop
if C /= Position
and (not P.Has_Key (P_Right, C)
or else P.Get (P_Left, C) > E.Length (E_Left)
or else P.Get (P_Right, C) > E.Length (E_Right)
or else E.Get (E_Left, P.Get (P_Left, C)) /=
E.Get (E_Right, P.Get (P_Right, C)))
then
return False;
end if;
end loop;
return True;
end Mapping_Preserved_Except;
-------------------------
-- P_Positions_Shifted --
-------------------------
function P_Positions_Shifted
(Small : P.Map;
Big : P.Map;
Cut : Positive_Count_Type;
Count : Count_Type := 1) return Boolean
is
begin
for Cu of Small loop
if not P.Has_Key (Big, Cu) then
return False;
end if;
end loop;
for Cu of Big loop
declare
Pos : constant Positive_Count_Type := P.Get (Big, Cu);
begin
if Pos < Cut then
if not P.Has_Key (Small, Cu)
or else Pos /= P.Get (Small, Cu)
then
return False;
end if;
elsif Pos >= Cut + Count then
if not P.Has_Key (Small, Cu)
or else Pos /= P.Get (Small, Cu) + Count
then
return False;
end if;
else
if P.Has_Key (Small, Cu) then
return False;
end if;
end if;
end;
end loop;
return True;
end P_Positions_Shifted;
-----------
-- Model --
-----------
function Model (Container : Set) return M.Set is
Position : Count_Type := Container.Content.First;
R : M.Set;
begin
-- Can't use First, Next or Element here, since they depend on models
-- for their postconditions.
while Position /= 0 loop
R :=
M.Add
(Container => R,
Item => Container.Content.Nodes (Position).Element);
Position := Tree_Operations.Next (Container.Content, Position);
end loop;
return R;
end Model;
---------------
-- Positions --
---------------
function Positions (Container : Set) return P.Map is
I : Count_Type := 1;
Position : Count_Type := Container.Content.First;
R : P.Map;
begin
-- Can't use First, Next or Element here, since they depend on models
-- for their postconditions.
while Position /= 0 loop
R := P.Add (R, (Node => Position), I);
pragma Assert (P.Length (R) = I);
Position := Tree_Operations.Next (Container.Content, Position);
I := I + 1;
end loop;
return R;
end Positions;
end Formal_Model;
----------
-- Free --
----------
procedure Free (Tree : in out Set; X : Count_Type) is
begin
Tree.Content.Nodes (X).Has_Element := False;
Tree_Operations.Free (Tree.Content, X);
end Free;
----------------------
-- Generic_Allocate --
----------------------
procedure Generic_Allocate
(Tree : in out Tree_Types.Tree_Type'Class;
Node : out Count_Type)
is
procedure Allocate is
new Tree_Operations.Generic_Allocate (Set_Element);
begin
Allocate (Tree, Node);
Tree.Nodes (Node).Has_Element := True;
end Generic_Allocate;
------------------
-- Generic_Keys --
------------------
package body Generic_Keys with SPARK_Mode => Off is
-----------------------
-- Local Subprograms --
-----------------------
function Is_Greater_Key_Node
(Left : Key_Type;
Right : Node_Type) return Boolean;
pragma Inline (Is_Greater_Key_Node);
function Is_Less_Key_Node
(Left : Key_Type;
Right : Node_Type) return Boolean;
pragma Inline (Is_Less_Key_Node);
--------------------------
-- Local Instantiations --
--------------------------
package Key_Keys is
new Red_Black_Trees.Generic_Bounded_Keys
(Tree_Operations => Tree_Operations,
Key_Type => Key_Type,
Is_Less_Key_Node => Is_Less_Key_Node,
Is_Greater_Key_Node => Is_Greater_Key_Node);
-------------
-- Ceiling --
-------------
function Ceiling (Container : Set; Key : Key_Type) return Cursor is
Node : constant Count_Type :=
Key_Keys.Ceiling (Container.Content, Key);
begin
if Node = 0 then
return No_Element;
end if;
return (Node => Node);
end Ceiling;
--------------
-- Contains --
--------------
function Contains (Container : Set; Key : Key_Type) return Boolean is
begin
return Find (Container, Key) /= No_Element;
end Contains;
------------
-- Delete --
------------
procedure Delete (Container : in out Set; Key : Key_Type) is
X : constant Count_Type := Key_Keys.Find (Container.Content, Key);
begin
if X = 0 then
raise Constraint_Error with "attempt to delete key not in set";
end if;
Delete_Node_Sans_Free (Container.Content, X);
Free (Container, X);
end Delete;
-------------
-- Element --
-------------
function Element (Container : Set; Key : Key_Type) return Element_Type is
Node : constant Count_Type := Key_Keys.Find (Container.Content, Key);
begin
if Node = 0 then
raise Constraint_Error with "key not in set";
end if;
declare
N : Tree_Types.Nodes_Type renames Container.Content.Nodes;
begin
return N (Node).Element;
end;
end Element;
---------------------
-- Equivalent_Keys --
---------------------
function Equivalent_Keys (Left, Right : Key_Type) return Boolean is
begin
if Left < Right
or else Right < Left
then
return False;
else
return True;
end if;
end Equivalent_Keys;
-------------
-- Exclude --
-------------
procedure Exclude (Container : in out Set; Key : Key_Type) is
X : constant Count_Type := Key_Keys.Find (Container.Content, Key);
begin
if X /= 0 then
Delete_Node_Sans_Free (Container.Content, X);
Free (Container, X);
end if;
end Exclude;
----------
-- Find --
----------
function Find (Container : Set; Key : Key_Type) return Cursor is
Node : constant Count_Type := Key_Keys.Find (Container.Content, Key);
begin
return (if Node = 0 then No_Element else (Node => Node));
end Find;
-----------
-- Floor --
-----------
function Floor (Container : Set; Key : Key_Type) return Cursor is
Node : constant Count_Type := Key_Keys.Floor (Container.Content, Key);
begin
return (if Node = 0 then No_Element else (Node => Node));
end Floor;
------------------
-- Formal_Model --
------------------
package body Formal_Model is
-------------------------
-- E_Bigger_Than_Range --
-------------------------
function E_Bigger_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Key : Key_Type) return Boolean
is
begin
for I in Fst .. Lst loop
if not (Generic_Keys.Key (E.Get (Container, I)) < Key) then
return False;
end if;
end loop;
return True;
end E_Bigger_Than_Range;
---------------
-- E_Is_Find --
---------------
function E_Is_Find
(Container : E.Sequence;
Key : Key_Type;
Position : Count_Type) return Boolean
is
begin
for I in 1 .. Position - 1 loop
if Key < Generic_Keys.Key (E.Get (Container, I)) then
return False;
end if;
end loop;
if Position < E.Length (Container) then
for I in Position + 1 .. E.Length (Container) loop
if Generic_Keys.Key (E.Get (Container, I)) < Key then
return False;
end if;
end loop;
end if;
return True;
end E_Is_Find;
--------------------------
-- E_Smaller_Than_Range --
--------------------------
function E_Smaller_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Key : Key_Type) return Boolean
is
begin
for I in Fst .. Lst loop
if not (Key < Generic_Keys.Key (E.Get (Container, I))) then
return False;
end if;
end loop;
return True;
end E_Smaller_Than_Range;
----------
-- Find --
----------
function Find
(Container : E.Sequence;
Key : Key_Type) return Count_Type
is
begin
for I in 1 .. E.Length (Container) loop
if Equivalent_Keys
(Key, Generic_Keys.Key (E.Get (Container, I)))
then
return I;
end if;
end loop;
return 0;
end Find;
-----------------------
-- M_Included_Except --
-----------------------
function M_Included_Except
(Left : M.Set;
Right : M.Set;
Key : Key_Type) return Boolean
is
begin
for E of Left loop
if not Contains (Right, E)
and not Equivalent_Keys (Generic_Keys.Key (E), Key)
then
return False;
end if;
end loop;
return True;
end M_Included_Except;
end Formal_Model;
-------------------------
-- Is_Greater_Key_Node --
-------------------------
function Is_Greater_Key_Node
(Left : Key_Type;
Right : Node_Type) return Boolean
is
begin
return Key (Right.Element) < Left;
end Is_Greater_Key_Node;
----------------------
-- Is_Less_Key_Node --
----------------------
function Is_Less_Key_Node
(Left : Key_Type;
Right : Node_Type) return Boolean
is
begin
return Left < Key (Right.Element);
end Is_Less_Key_Node;
---------
-- Key --
---------
function Key (Container : Set; Position : Cursor) return Key_Type is
begin
if not Has_Element (Container, Position) then
raise Constraint_Error with
"Position cursor has no element";
end if;
pragma Assert (Vet (Container.Content, Position.Node),
"bad cursor in Key");
declare
N : Tree_Types.Nodes_Type renames Container.Content.Nodes;
begin
return Key (N (Position.Node).Element);
end;
end Key;
-------------
-- Replace --
-------------
procedure Replace
(Container : in out Set;
Key : Key_Type;
New_Item : Element_Type)
is
Node : constant Count_Type := Key_Keys.Find (Container.Content, Key);
begin
if not Has_Element (Container, (Node => Node)) then
raise Constraint_Error with
"attempt to replace key not in set";
else
Replace_Element (Container, Node, New_Item);
end if;
end Replace;
end Generic_Keys;
-----------------
-- Has_Element --
-----------------
function Has_Element (Container : Set; Position : Cursor) return Boolean is
begin
if Position.Node = 0 then
return False;
else
return Container.Content.Nodes (Position.Node).Has_Element;
end if;
end Has_Element;
-------------
-- Include --
-------------
procedure Include (Container : in out Set; New_Item : Element_Type) is
Position : Cursor;
Inserted : Boolean;
begin
Insert (Container, New_Item, Position, Inserted);
if not Inserted then
declare
N : Tree_Types.Nodes_Type renames Container.Content.Nodes;
begin
N (Position.Node).Element := New_Item;
end;
end if;
end Include;
------------
-- Insert --
------------
procedure Insert
(Container : in out Set;
New_Item : Element_Type;
Position : out Cursor;
Inserted : out Boolean)
is
begin
Insert_Sans_Hint (Container.Content, New_Item, Position.Node, Inserted);
end Insert;
procedure Insert
(Container : in out Set;
New_Item : Element_Type)
is
Position : Cursor;
Inserted : Boolean;
begin
Insert (Container, New_Item, Position, Inserted);
if not Inserted then
raise Constraint_Error with
"attempt to insert element already in set";
end if;
end Insert;
----------------------
-- Insert_Sans_Hint --
----------------------
procedure Insert_Sans_Hint
(Container : in out Tree_Types.Tree_Type;
New_Item : Element_Type;
Node : out Count_Type;
Inserted : out Boolean)
is
procedure Set_Element (Node : in out Node_Type);
function New_Node return Count_Type;
pragma Inline (New_Node);
procedure Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Conditional_Insert_Sans_Hint is
new Element_Keys.Generic_Conditional_Insert (Insert_Post);
procedure Allocate is new Generic_Allocate (Set_Element);
--------------
-- New_Node --
--------------
function New_Node return Count_Type is
Result : Count_Type;
begin
Allocate (Container, Result);
return Result;
end New_Node;
-----------------
-- Set_Element --
-----------------
procedure Set_Element (Node : in out Node_Type) is
begin
Node.Element := New_Item;
end Set_Element;
-- Start of processing for Insert_Sans_Hint
begin
Conditional_Insert_Sans_Hint
(Container,
New_Item,
Node,
Inserted);
end Insert_Sans_Hint;
----------------------
-- Insert_With_Hint --
----------------------
procedure Insert_With_Hint
(Dst_Set : in out Tree_Types.Tree_Type;
Dst_Hint : Count_Type;
Src_Node : Node_Type;
Dst_Node : out Count_Type)
is
Success : Boolean;
procedure Set_Element (Node : in out Node_Type);
function New_Node return Count_Type;
pragma Inline (New_Node);
procedure Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Insert_Sans_Hint is
new Element_Keys.Generic_Conditional_Insert (Insert_Post);
procedure Local_Insert_With_Hint is
new Element_Keys.Generic_Conditional_Insert_With_Hint
(Insert_Post, Insert_Sans_Hint);
procedure Allocate is new Generic_Allocate (Set_Element);
--------------
-- New_Node --
--------------
function New_Node return Count_Type is
Result : Count_Type;
begin
Allocate (Dst_Set, Result);
return Result;
end New_Node;
-----------------
-- Set_Element --
-----------------
procedure Set_Element (Node : in out Node_Type) is
begin
Node.Element := Src_Node.Element;
end Set_Element;
-- Start of processing for Insert_With_Hint
begin
Local_Insert_With_Hint
(Dst_Set,
Dst_Hint,
Src_Node.Element,
Dst_Node,
Success);
end Insert_With_Hint;
------------------
-- Intersection --
------------------
procedure Intersection (Target : in out Set; Source : Set) is
begin
Set_Ops.Set_Intersection (Target.Content, Source.Content);
end Intersection;
function Intersection (Left, Right : Set) return Set is
begin
if Left'Address = Right'Address then
return Copy (Left);
end if;
return S : Set (Count_Type'Min (Length (Left), Length (Right))) do
Assign (S.Content,
Set_Ops.Set_Intersection (Left.Content, Right.Content));
end return;
end Intersection;
--------------
-- Is_Empty --
--------------
function Is_Empty (Container : Set) return Boolean is
begin
return Length (Container) = 0;
end Is_Empty;
-----------------------------
-- Is_Greater_Element_Node --
-----------------------------
function Is_Greater_Element_Node
(Left : Element_Type;
Right : Node_Type) return Boolean
is
begin
-- Compute e > node same as node < e
return Right.Element < Left;
end Is_Greater_Element_Node;
--------------------------
-- Is_Less_Element_Node --
--------------------------
function Is_Less_Element_Node
(Left : Element_Type;
Right : Node_Type) return Boolean
is
begin
return Left < Right.Element;
end Is_Less_Element_Node;
-----------------------
-- Is_Less_Node_Node --
-----------------------
function Is_Less_Node_Node (L, R : Node_Type) return Boolean is
begin
return L.Element < R.Element;
end Is_Less_Node_Node;
---------------
-- Is_Subset --
---------------
function Is_Subset (Subset : Set; Of_Set : Set) return Boolean is
begin
return Set_Ops.Set_Subset (Subset.Content, Of_Set => Of_Set.Content);
end Is_Subset;
----------
-- Last --
----------
function Last (Container : Set) return Cursor is
begin
return (if Length (Container) = 0
then No_Element
else (Node => Container.Content.Last));
end Last;
------------------
-- Last_Element --
------------------
function Last_Element (Container : Set) return Element_Type is
begin
if Last (Container).Node = 0 then
raise Constraint_Error with "set is empty";
end if;
declare
N : Tree_Types.Nodes_Type renames Container.Content.Nodes;
begin
return N (Last (Container).Node).Element;
end;
end Last_Element;
--------------
-- Left_Son --
--------------
function Left_Son (Node : Node_Type) return Count_Type is
begin
return Node.Left;
end Left_Son;
------------
-- Length --
------------
function Length (Container : Set) return Count_Type is
begin
return Container.Content.Length;
end Length;
----------
-- Move --
----------
procedure Move (Target : in out Set; Source : in out Set) is
N : Tree_Types.Nodes_Type renames Source.Content.Nodes;
X : Count_Type;
begin
if Target'Address = Source'Address then
return;
end if;
if Target.Capacity < Length (Source) then
raise Constraint_Error with -- ???
"Source length exceeds Target capacity";
end if;
Clear (Target);
loop
X := Source.Content.First;
exit when X = 0;
Insert (Target, N (X).Element); -- optimize???
Tree_Operations.Delete_Node_Sans_Free (Source.Content, X);
Free (Source, X);
end loop;
end Move;
----------
-- Next --
----------
function Next (Container : Set; Position : Cursor) return Cursor is
begin
if Position = No_Element then
return No_Element;
end if;
if not Has_Element (Container, Position) then
raise Constraint_Error;
end if;
pragma Assert (Vet (Container.Content, Position.Node),
"bad cursor in Next");
return (Node => Tree_Operations.Next (Container.Content, Position.Node));
end Next;
procedure Next (Container : Set; Position : in out Cursor) is
begin
Position := Next (Container, Position);
end Next;
-------------
-- Overlap --
-------------
function Overlap (Left, Right : Set) return Boolean is
begin
return Set_Ops.Set_Overlap (Left.Content, Right.Content);
end Overlap;
------------
-- Parent --
------------
function Parent (Node : Node_Type) return Count_Type is
begin
return Node.Parent;
end Parent;
--------------
-- Previous --
--------------
function Previous (Container : Set; Position : Cursor) return Cursor is
begin
if Position = No_Element then
return No_Element;
end if;
if not Has_Element (Container, Position) then
raise Constraint_Error;
end if;
pragma Assert (Vet (Container.Content, Position.Node),
"bad cursor in Previous");
declare
Node : constant Count_Type :=
Tree_Operations.Previous (Container.Content, Position.Node);
begin
return (if Node = 0 then No_Element else (Node => Node));
end;
end Previous;
procedure Previous (Container : Set; Position : in out Cursor) is
begin
Position := Previous (Container, Position);
end Previous;
-------------
-- Replace --
-------------
procedure Replace (Container : in out Set; New_Item : Element_Type) is
Node : constant Count_Type :=
Element_Keys.Find (Container.Content, New_Item);
begin
if Node = 0 then
raise Constraint_Error with
"attempt to replace element not in set";
end if;
Container.Content.Nodes (Node).Element := New_Item;
end Replace;
---------------------
-- Replace_Element --
---------------------
procedure Replace_Element
(Tree : in out Set;
Node : Count_Type;
Item : Element_Type)
is
pragma Assert (Node /= 0);
function New_Node return Count_Type;
pragma Inline (New_Node);
procedure Local_Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Local_Insert_Sans_Hint is
new Element_Keys.Generic_Conditional_Insert (Local_Insert_Post);
procedure Local_Insert_With_Hint is
new Element_Keys.Generic_Conditional_Insert_With_Hint
(Local_Insert_Post,
Local_Insert_Sans_Hint);
NN : Tree_Types.Nodes_Type renames Tree.Content.Nodes;
--------------
-- New_Node --
--------------
function New_Node return Count_Type is
N : Node_Type renames NN (Node);
begin
N.Element := Item;
N.Color := Red;
N.Parent := 0;
N.Right := 0;
N.Left := 0;
return Node;
end New_Node;
Hint : Count_Type;
Result : Count_Type;
Inserted : Boolean;
-- Start of processing for Insert
begin
if Item < NN (Node).Element
or else NN (Node).Element < Item
then
null;
else
NN (Node).Element := Item;
return;
end if;
Hint := Element_Keys.Ceiling (Tree.Content, Item);
if Hint = 0 then
null;
elsif Item < NN (Hint).Element then
if Hint = Node then
NN (Node).Element := Item;
return;
end if;
else
pragma Assert (not (NN (Hint).Element < Item));
raise Program_Error with "attempt to replace existing element";
end if;
Tree_Operations.Delete_Node_Sans_Free (Tree.Content, Node);
Local_Insert_With_Hint
(Tree => Tree.Content,
Position => Hint,
Key => Item,
Node => Result,
Inserted => Inserted);
pragma Assert (Inserted);
pragma Assert (Result = Node);
end Replace_Element;
procedure Replace_Element
(Container : in out Set;
Position : Cursor;
New_Item : Element_Type)
is
begin
if not Has_Element (Container, Position) then
raise Constraint_Error with
"Position cursor has no element";
end if;
pragma Assert (Vet (Container.Content, Position.Node),
"bad cursor in Replace_Element");
Replace_Element (Container, Position.Node, New_Item);
end Replace_Element;
---------------
-- Right_Son --
---------------
function Right_Son (Node : Node_Type) return Count_Type is
begin
return Node.Right;
end Right_Son;
---------------
-- Set_Color --
---------------
procedure Set_Color
(Node : in out Node_Type;
Color : Red_Black_Trees.Color_Type)
is
begin
Node.Color := Color;
end Set_Color;
--------------
-- Set_Left --
--------------
procedure Set_Left (Node : in out Node_Type; Left : Count_Type) is
begin
Node.Left := Left;
end Set_Left;
----------------
-- Set_Parent --
----------------
procedure Set_Parent (Node : in out Node_Type; Parent : Count_Type) is
begin
Node.Parent := Parent;
end Set_Parent;
---------------
-- Set_Right --
---------------
procedure Set_Right (Node : in out Node_Type; Right : Count_Type) is
begin
Node.Right := Right;
end Set_Right;
--------------------------
-- Symmetric_Difference --
--------------------------
procedure Symmetric_Difference (Target : in out Set; Source : Set) is
begin
Set_Ops.Set_Symmetric_Difference (Target.Content, Source.Content);
end Symmetric_Difference;
function Symmetric_Difference (Left, Right : Set) return Set is
begin
if Left'Address = Right'Address then
return Empty_Set;
end if;
if Length (Right) = 0 then
return Copy (Left);
end if;
if Length (Left) = 0 then
return Copy (Right);
end if;
return S : Set (Length (Left) + Length (Right)) do
Assign
(S.Content,
Set_Ops.Set_Symmetric_Difference (Left.Content, Right.Content));
end return;
end Symmetric_Difference;
------------
-- To_Set --
------------
function To_Set (New_Item : Element_Type) return Set is
Node : Count_Type;
Inserted : Boolean;
begin
return S : Set (Capacity => 1) do
Insert_Sans_Hint (S.Content, New_Item, Node, Inserted);
pragma Assert (Inserted);
end return;
end To_Set;
-----------
-- Union --
-----------
procedure Union (Target : in out Set; Source : Set) is
begin
Set_Ops.Set_Union (Target.Content, Source.Content);
end Union;
function Union (Left, Right : Set) return Set is
begin
if Left'Address = Right'Address then
return Copy (Left);
end if;
if Length (Left) = 0 then
return Copy (Right);
end if;
if Length (Right) = 0 then
return Copy (Left);
end if;
return S : Set (Length (Left) + Length (Right)) do
Assign (S, Source => Left);
Union (S, Right);
end return;
end Union;
end Ada.Containers.Formal_Ordered_Sets;
|
apple-oss-distributions/old_ncurses | Ada | 7,123 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT ncurses Binding Samples --
-- --
-- ncurses --
-- --
-- B O D Y --
-- --
------------------------------------------------------------------------------
-- Copyright (c) 2000 Free Software Foundation, Inc. --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files (the --
-- "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, distribute with modifications, sublicense, and/or sell --
-- copies of the Software, and to permit persons to whom the Software is --
-- furnished to do so, subject to the following conditions: --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. --
-- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR --
-- THE USE OR OTHER DEALINGS IN THE SOFTWARE. --
-- --
-- Except as contained in this notice, the name(s) of the above copyright --
-- holders shall not be used in advertising or otherwise to promote the --
-- sale, use or other dealings in this Software without prior written --
-- authorization. --
------------------------------------------------------------------------------
-- Author: Eugene V. Melaragno <[email protected]> 2000
-- Version Control
-- $Revision: 1.1.1.1 $
-- Binding Version 01.00
------------------------------------------------------------------------------
-- A simplified version of the GNU getopt function
-- copyright Free Software Foundtion
with Ada.Strings.Fixed;
with Ada.Strings.Bounded;
with Ada.Text_IO; use Ada.Text_IO;
package body ncurses2.getopt is
opterr : Character := Character'Val (1);
optopt : Character := '?';
initialized : Boolean := False;
nextchar : Natural := 0;
-- Ncurses doesn't use the non option elements so we are spared
-- the job of computing those.
-- also the user is not allowed to modify argv or argc
-- Doing so is Erroneous execution.
-- longoptions are not handled.
procedure Qgetopt (retval : out Integer;
argc : Integer;
argv : stringfunc;
-- argv will be the Argument function.
optstring : String;
optind : in out Integer;
-- ignored for ncurses, must be initialized to 1 by
-- the caller
optarg : out stringa
-- a garbage colector would be useful here.
) is
package BS is new Ada.Strings.Bounded.Generic_Bounded_Length (200);
use BS;
optargx : Bounded_String;
begin
if argc < optind then
retval := -1;
return;
end if;
optargx := To_Bounded_String ("");
if nextchar = 0 then
if argv (optind) = "--" then
-- the rest are non-options, we ignore them
retval := -1;
return;
end if;
if argv (optind)(1) /= '-' or argv (optind)'Length = 1 then
optind := optind + 1;
Optarg := new String'(argv (optind));
retval := 1;
return;
end if;
nextchar := 2; -- skip the one hyphen.
end if;
-- Look at and handle the next short option-character.
declare
c : Character := argv (optind) (nextchar);
temp : Natural :=
Ada.Strings.Fixed.Index (optstring, String'(1 => c));
begin
if temp = 0 or c = ':' then
Put_Line (Standard_Error,
argv (optind) & ": invalid option -- " & c);
optopt := c;
c := '?';
return;
end if;
if optstring (temp + 1) = ':' then
if optstring (temp + 2) = ':' then
-- This is an option that accepts an argument optionally.
if nextchar /= argv (optind)'Length then
optargx := To_Bounded_String
(argv (optind) (nextchar .. argv (optind)'Length));
else
Optarg := null;
end if;
else
-- This is an option that requires an argument.
if nextchar /= argv (optind)'Length then
optargx := To_Bounded_String
(argv (optind) (nextchar .. argv (optind)'Length));
optind := optind + 1;
elsif optind = argc then
Put_Line (Standard_Error,
argv (optind) &
": option requires an argument -- " & c);
optopt := c;
if optstring (1) = ':' then
c := ':';
else
c := '?';
end if;
else
-- increment it again when taking next ARGV-elt as argument.
optind := optind + 1;
optargx := To_Bounded_String (argv (optind));
optind := optind + 1;
end if;
end if;
nextchar := 0;
else -- no argument for the option
if nextchar = argv (optind)'Length then
optind := optind + 1;
nextchar := 0;
else
nextchar := nextchar + 1;
end if;
end if;
retval := Character'Pos (c);
Optarg := new String'(To_String (optargx));
return;
end;
end Qgetopt;
end ncurses2.getopt;
|
AdaCore/Ada_Drivers_Library | Ada | 3,942 | adb | ------------------------------------------------------------------------------
-- --
-- Copyright (C) 2019, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
package body NeoPixel is
Stride : constant array (LED_Mode) of Positive :=
(RGBW => 4, others => 3);
------------
-- Create --
------------
function Create (Mode : LED_Mode; Count : Positive) return LED_Strip is
begin
return LED_Strip'(Mode => Mode,
Count => Count,
Buf_Last => Count * Stride (Mode) - 1,
Buffer => (others => 0));
end Create;
type Component_Indices is array (LED_Component) of Integer;
Mode_Indices : constant array (LED_Mode) of Component_Indices :=
(RGB => (LED_Red => 0, LED_Green => 1, LED_Blue => 2, LED_White => -1),
GRB => (LED_Red => 1, LED_Green => 0, LED_Blue => 2, LED_White => -1),
RGBW => (LED_Red => 0, LED_Green => 1, LED_Blue => 2, LED_White => 3));
---------------
-- Set_Color --
---------------
procedure Set_Color
(Strip : in out LED_Strip;
Index : Natural;
Color : LED_Values)
is
pragma Assert (Index < Strip.Count);
Base : constant Natural := Index * Stride (Strip.Mode);
Indices : constant Component_Indices := Mode_Indices (Strip.Mode);
begin
for J in LED_Red .. (if Strip.Mode = RGBW then LED_White else LED_Blue) loop
Strip.Buffer (Base + Indices (J)) := Color (J);
end loop;
end Set_Color;
----------
-- Show --
----------
procedure Show
(Strip : LED_Strip;
Write : access procedure (Buffer : UInt8_Array))
is
begin
Write (Strip.Buffer);
end Show;
end NeoPixel;
|
reznikmm/matreshka | Ada | 5,048 | adb | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Web Framework --
-- --
-- Tools Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2016-2018, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Asis.Elements;
with Properties.Tools;
package body Properties.Definitions.Modular is
---------------
-- Alignment --
---------------
function Alignment
(Engine : access Engines.Contexts.Context;
Element : Asis.Definition;
Name : Engines.Integer_Property) return Integer
is
pragma Unreferenced (Engine, Element, Name);
begin
return 1;
end Alignment;
----------
-- Size --
----------
function Size
(Engine : access Engines.Contexts.Context;
Element : Asis.Definition;
Name : Engines.Text_Property) return League.Strings.Universal_String
is
pragma Unreferenced (Name);
Result : League.Strings.Universal_String;
Size : constant Asis.Expression := Tools.Attribute_Definition
(Asis.Elements.Enclosing_Element (Element), "Size");
begin
if Asis.Elements.Is_Nil (Size) then
Result.Append ("8");
else
Result := Engine.Text.Get_Property (Size, Engines.Code);
end if;
return Result;
end Size;
---------------------------
-- Typed_Array_Item_Type --
---------------------------
function Typed_Array_Item_Type
(Engine : access Engines.Contexts.Context;
Element : Asis.Expression;
Name : Engines.Text_Property)
return League.Strings.Universal_String
is
pragma Unreferenced (Name);
Down : League.Strings.Universal_String;
Result : League.Strings.Universal_String;
begin
Down := Engine.Text.Get_Property (Element, Engines.Size);
Result.Append ("_u");
Result.Append (Down);
return Result;
end Typed_Array_Item_Type;
end Properties.Definitions.Modular;
|
stcarrez/ada-asf | Ada | 2,660 | adb | -----------------------------------------------------------------------
-- asf-lifecycles-invoke -- Invoke application phase
-- Copyright (C) 2010, 2011, 2012, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with ASF.Components.Root;
with ASF.Components.Base;
with ASF.Components.Core.Views;
with Util.Log.Loggers;
-- The <b>ASF.Lifecycles.Invoke</b> package defines the behavior
-- of the invoke application phase.
package body ASF.Lifecycles.Invoke is
use Ada.Exceptions;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Lifecycles.Invoke");
-- ------------------------------
-- Execute the invoke application phase.
-- ------------------------------
overriding
procedure Execute (Controller : in Invoke_Controller;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Controller);
View : constant Components.Root.UIViewRoot := Context.Get_View_Root;
Root : constant access Components.Base.UIComponent'Class := Components.Root.Get_Root (View);
procedure Process (Child : in Components.Base.UIComponent_Access);
procedure Process (Child : in Components.Base.UIComponent_Access) is
begin
if Child.all in Components.Core.Views.UIView'Class then
Components.Core.Views.UIView'Class (Child.all).Process_Application (Context);
end if;
end Process;
procedure Process_Application_Children is new Components.Base.Iterate (Process);
begin
if Root.all in Components.Core.Views.UIView'Class then
Process (Root.all'Unchecked_Access);
else
Process_Application_Children (Root.all);
end if;
exception
when E : others =>
Log.Error ("Error when invoking application on view {0}: {1}: {2}", "?",
Exception_Name (E), Exception_Message (E));
raise;
end Execute;
end ASF.Lifecycles.Invoke;
|
reznikmm/matreshka | Ada | 3,808 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012-2015, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
pragma Restrictions (No_Elaboration_Code);
-- GNAT: enforce generation of preinitialized data section instead of
-- generation of elaboration code.
package Matreshka.Internals.Unicode.Ucd.Core_00D8 is
pragma Preelaborate;
Group_00D8 : aliased constant Core_Second_Stage
:= (others =>
(Surrogate, Neutral,
Control, Other, Other, Surrogate,
(others => False)));
end Matreshka.Internals.Unicode.Ucd.Core_00D8;
|
stcarrez/ada-css | Ada | 1,297 | ads | -----------------------------------------------------------------------
-- css-analysis-rules-main -- Rule repository
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package CSS.Analysis.Rules.Main is
-- Analyze the CSS rules with their properties against the repository
-- definition and report any warning or error.
procedure Analyze (Sheet : in CSS.Core.Sheets.CSSStylesheet;
Report : in out CSS.Core.Errors.Error_Handler'Class);
-- Get the rule repository instance.
function Rule_Repository return access Repository_Type;
end CSS.Analysis.Rules.Main;
|
jrmarino/AdaBase | Ada | 3,604 | adb | with AdaBase;
with Connect;
with CommonText;
with Ada.Text_IO;
with AdaBase.Results.Sets;
with Spatial_Data;
procedure Spatial4 is
package CON renames Connect;
package TIO renames Ada.Text_IO;
package ARS renames AdaBase.Results.Sets;
package CT renames CommonText;
package SD renames Spatial_Data;
begin
CON.connect_database;
declare
use type SD.Geometric_Real;
my_point : SD.Geometry := SD.initialize_as_point ((3.2, 4.775));
my_linestr : SD.Geometry := SD.initialize_as_line
(((-0.034, 14.993), (5.0, 6.0), (-3.0, 19.0), (0.0, -7.1000009)));
wrk_poly : SD.Geometric_Polygon := SD.start_polygon
(((35.0, 10.0), (45.0, 45.0), (15.0, 40.0), (10.0, 20.0), (35.0, 10.0)));
my_polygon : SD.Geometry;
my_mpoly : SD.Geometry;
my_mpoint : SD.Geometry := SD.initialize_as_multi_point ((10.0, 10.0));
my_mline : SD.Geometry := SD.initialize_as_multi_line
(((5.0, 5.0), (0.0, 2.0), (-7.0, 13.0), (99.0, -1.0), (50.0, 50.0)));
my_mixture : SD.Geometry := SD.initialize_as_collection (my_linestr);
begin
SD.append_inner_ring (wrk_poly, ((20.0, 30.0), (35.0, 35.0), (30.0, 20.0), (20.0, 30.0)));
my_polygon := SD.initialize_as_polygon (wrk_poly);
SD.augment_multi_point (my_mpoint, (100.0, 200.0));
SD.augment_multi_point (my_mpoint, (-52.0, 250.0));
SD.augment_multi_line (my_mline, ((20.0, 10.0), (87.0, 88.0)));
my_mpoly := SD.initialize_as_multi_polygon (wrk_poly);
SD.augment_collection (my_mixture, my_polygon);
SD.augment_collection (my_mixture, my_mpoint);
SD.augment_collection (my_mixture, my_point);
SD.augment_collection (my_mixture, my_mline);
declare
template : String := "INSERT INTO spatial_plus " &
"(id, sp_point, sp_linestring, sp_polygon, sp_multi_point," &
" sp_multi_line_string, sp_multi_polygon, sp_geo_collection)" &
" VALUES (10, ST_GeomFromText (:pt, 4326)," &
" ST_GeomFromText (:line, 4326)," &
" ST_GeomFromText (:poly, 4326)," &
" ST_GeomFromText(:mpoint, 4326)," &
" ST_GeomFromText(:mline, 4326)," &
" ST_GeomFromText(:mpoly, 4326)," &
" ST_GeomFromText(:collset, 4326))";
stmt : CON.Stmt_Type := CON.DR.prepare (template);
begin
stmt.assign ("pt", SD.Well_Known_Text (my_point));
stmt.assign ("line", SD.Well_Known_Text (my_linestr));
stmt.assign ("poly", SD.Well_Known_Text (my_polygon));
stmt.assign ("mpoint", SD.Well_Known_Text (my_mpoint));
stmt.assign ("mline", SD.Well_Known_Text (my_mline));
stmt.assign ("mpoly", SD.Well_Known_Text (my_mpoly));
stmt.assign ("collset", SD.Well_Known_Text (my_mixture));
if not stmt.execute then
TIO.Put_Line (stmt.last_driver_message);
CON.DR.rollback;
return;
end if;
declare
row : ARS.Datarow;
s2 : CON.Stmt_Type := CON.DR.query
("SELECT * FROM spatial_plus WHERE id=10");
begin
loop
row := s2.fetch_next;
exit when row.data_exhausted;
for x in Natural range 1 .. row.count loop
TIO.Put (s2.column_name (x) & " : ");
TIO.Put_Line (row.column (x).as_string);
end loop;
end loop;
end;
CON.DR.rollback;
end;
end;
CON.DR.disconnect;
end Spatial4;
|
mgrojo/bingada | Ada | 3,189 | adb | --*****************************************************************************
--*
--* PROJECT: BingAda
--*
--* FILE: q_bingo_help.adb
--*
--* AUTHOR: Javier Fuica Fernandez
--*
--*****************************************************************************
with Gtk.About_Dialog;
with Gtk.Dialog;
package body Q_Bingo_Help is
use type Gtk.Dialog.Gtk_Response_Type;
--==================================================================
procedure P_Show_Window (V_Parent_Window : Gtk.Window.Gtk_Window) is
V_Dialog : Gtk.About_Dialog.Gtk_About_Dialog;
begin
Gtk.About_Dialog.Gtk_New (V_Dialog);
Gtk.About_Dialog.Set_Transient_For (V_Dialog, V_Parent_Window);
Gtk.About_Dialog.Set_Destroy_With_Parent (V_Dialog, True);
Gtk.About_Dialog.Set_Modal (V_Dialog, True);
Gtk.About_Dialog.Add_Credit_Section
(About => V_Dialog,
Section_Name => "Beta Testers : ",
People =>
(1 => new String'("Javier's Wife"),
2 => new String'("Javier's Sons")));
Gtk.About_Dialog.Set_Authors
(V_Dialog,
(1 => new String'("Javier Fuica Fernandez <[email protected]>"),
2 => new String'("Manuel Gomez <[email protected]>")));
Gtk.About_Dialog.Set_Comments (V_Dialog, "Bingo application in GTKAda");
Gtk.About_Dialog.Set_License
(V_Dialog,
"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: "
& ASCII.LF & ASCII.LF
& "The above copyright notice and this permission notice shall be included in all "
& "copies or substantial portions of the Software. "
& ASCII.LF & ASCII.LF
& "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");
Gtk.About_Dialog.Set_Wrap_License (V_Dialog, True);
Gtk.About_Dialog.Set_Program_Name (V_Dialog, "BingAda");
Gtk.About_Dialog.Set_Version (V_Dialog, "1.0");
if Gtk.About_Dialog.Run (V_Dialog) /= Gtk.Dialog.Gtk_Response_Close then
-- Dialog was destroyed by user, not closed through Close button
null;
end if;
Gtk.About_Dialog.Destroy (V_Dialog);
end P_Show_Window;
--==================================================================
end Q_Bingo_Help;
|
reznikmm/matreshka | Ada | 3,709 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with XML.DOM.Elements;
package ODF.DOM.Table_Data_Pilot_Table_Elements is
pragma Preelaborate;
type ODF_Table_Data_Pilot_Table is limited interface
and XML.DOM.Elements.DOM_Element;
type ODF_Table_Data_Pilot_Table_Access is
access all ODF_Table_Data_Pilot_Table'Class
with Storage_Size => 0;
end ODF.DOM.Table_Data_Pilot_Table_Elements;
|
egustafson/sandbox | Ada | 1,854 | adb | with Generic_Binary_Tree, Ada.Numerics.Discrete_Random;
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line;
use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line;
procedure Main is
Num_Insertions : Integer := 0;
Num_Queries : Integer;
Scratch : Boolean;
procedure Integer_Put( Item: Integer ) is
begin
Put( Item );
end Integer_Put;
package Int_Binary_Tree is
new Generic_Binary_Tree( Element_Type => Integer,
Less_Than => "<",
Greater_Than => ">",
Put => Integer_Put );
package Random_Int is new Ada.Numerics.Discrete_Random(Integer);
List : Int_Binary_Tree.T;
G : Random_Int.Generator;
procedure Print_Usage is
begin
New_Line;
Put("Usage: " & Command_Name & " <number of insertions> <number of queries>");
New_Line; New_Line;
end Print_Usage;
begin
if Argument_Count /= 2 then
Print_Usage;
else
begin
Num_Insertions := Positive'Value( Argument(1) );
Num_Queries := Natural'Value( Argument(2) );
exception
when Constraint_Error =>
Print_Usage;
raise;
when others =>
raise;
end;
end if;
if Num_Insertions > 0 then
-- Put("Inserting 2^(" & Integer'Image(Num_Insertions));
-- Put(") elements and then making 2^(" & Integer'Image(Num_Queries));
-- Put_Line(") queries.");
Random_Int.Reset(G);
for I in 1 .. 2**Num_Insertions loop
Int_Binary_Tree.Insert( List, Random_Int.Random(G) );
end loop;
for I in 1 .. 2**Num_Queries loop
Scratch := Int_Binary_Tree.Is_In_Tree( List, Random_Int.Random(G) );
end loop;
-- Put_Line("Done.");
end if;
end Main;
|
ekoeppen/STM32_Generic_Ada_Drivers | Ada | 645 | adb | with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler);
with Ada.Real_Time; use Ada.Real_Time;
with STM32GD.GPIO;
with STM32GD.GPIO.Pin;
with STM32_SVD.RCC;
procedure Main is
package GPIO renames STM32GD.GPIO;
package LED is new GPIO.Pin (Pin => GPIO.Pin_5, Port => GPIO.Port_A, Mode => GPIO.Mode_Out);
Next_Release : Time := Clock;
Period : constant Time_Span := Milliseconds (75); -- arbitrary
begin
STM32_SVD.RCC.RCC_Periph.AHBENR.IOPAEN := True;
LED.Init;
LED.Set;
loop
LED.Toggle;
Next_Release := Next_Release + Period;
delay until Next_Release;
end loop;
end Main;
|
sungyeon/drake | Ada | 6,465 | adb | with System.Storage_Elements;
package body System.Packed_Arrays is
pragma Suppress (All_Checks);
package body Ordering is
function memcmp (s1, s2 : Address; n : Storage_Elements.Storage_Count)
return Integer
with Import,
Convention => Intrinsic, External_Name => "__builtin_memcmp";
-- implementation
function Compare (
Left : Address;
Right : Address;
Left_Len : Natural;
Right_Len : Natural)
return Integer is
begin
if Element_Type'Size = Standard'Storage_Unit
and then Element_Type'Enum_Rep (Element_Type'First) = 0
then
declare
Result : constant Integer :=
memcmp (
Left,
Right,
Storage_Elements.Storage_Offset (
Integer'Min (Left_Len, Right_Len)));
begin
if Result /= 0 then
return Result;
end if;
end;
else
declare
pragma Compile_Time_Error (
Element_Type'Alignment /= 1,
"misaligned");
Min_Length : constant Integer :=
Integer'Min (Left_Len, Right_Len);
type Min_Array_Type is array (1 .. Min_Length) of Element_Type;
pragma Pack (Min_Array_Type);
pragma Suppress_Initialization (Min_Array_Type);
Left_All : Min_Array_Type;
for Left_All'Address use Left;
Right_All : Min_Array_Type;
for Right_All'Address use Right;
begin
for I in 1 .. Min_Length loop
if Left_All (I) < Right_All (I) then
return -1;
elsif Left_All (I) > Right_All (I) then
return 1;
end if;
end loop;
end;
end if;
if Left_Len < Right_Len then
return -1;
elsif Left_Len > Right_Len then
return 1;
else
return 0;
end if;
end Compare;
end Ordering;
package body Indexing is
subtype Rem_8 is Natural range 0 .. 7;
type Record_8_Units is record
E0, E1, E2, E3, E4, E5, E6, E7 : Element_Type;
end record;
for Record_8_Units'Alignment use 1;
pragma Pack (Record_8_Units);
pragma Suppress_Initialization (Record_8_Units);
function Get (Arr : Address; N : Natural) return Element_Type;
pragma Machine_Attribute (Get, "pure");
function Get (Arr : Address; N : Natural) return Element_Type is
Units : Record_8_Units;
for Units'Address use
Arr
+ Address (N / 8 * (Record_8_Units'Size / Standard'Storage_Unit));
begin
case Rem_8 (N rem 8) is
when 0 => return Units.E0;
when 1 => return Units.E1;
when 2 => return Units.E2;
when 3 => return Units.E3;
when 4 => return Units.E4;
when 5 => return Units.E5;
when 6 => return Units.E6;
when 7 => return Units.E7;
end case;
end Get;
procedure Set (Arr : Address; N : Natural; E : Element_Type);
procedure Set (Arr : Address; N : Natural; E : Element_Type) is
Units : Record_8_Units;
for Units'Address use
Arr
+ Address (N / 8 * (Record_8_Units'Size / Standard'Storage_Unit));
begin
case Rem_8 (N rem 8) is
when 0 => Units.E0 := E;
when 1 => Units.E1 := E;
when 2 => Units.E2 := E;
when 3 => Units.E3 := E;
when 4 => Units.E4 := E;
when 5 => Units.E5 := E;
when 6 => Units.E6 := E;
when 7 => Units.E7 := E;
end case;
end Set;
Reversed_Bit_Order : constant := 1 - Standard'Default_Bit_Order;
type Reversed_Record_8_Units is new Record_8_Units;
for Reversed_Record_8_Units'Bit_Order use
Bit_Order'Val (Reversed_Bit_Order);
for Reversed_Record_8_Units'Scalar_Storage_Order use
Bit_Order'Val (Reversed_Bit_Order);
pragma Suppress_Initialization (Reversed_Record_8_Units);
function Get_Reversed (Arr : Address; N : Natural) return Element_Type;
pragma Machine_Attribute (Get_Reversed, "pure");
function Get_Reversed (Arr : Address; N : Natural) return Element_Type is
Units : Reversed_Record_8_Units;
for Units'Address use
Arr
+ Address (N / 8 * (Record_8_Units'Size / Standard'Storage_Unit));
begin
case Rem_8 (N rem 8) is
when 0 => return Units.E0;
when 1 => return Units.E1;
when 2 => return Units.E2;
when 3 => return Units.E3;
when 4 => return Units.E4;
when 5 => return Units.E5;
when 6 => return Units.E6;
when 7 => return Units.E7;
end case;
end Get_Reversed;
procedure Set_Reversed (Arr : Address; N : Natural; E : Element_Type);
procedure Set_Reversed (Arr : Address; N : Natural; E : Element_Type) is
Units : Reversed_Record_8_Units;
for Units'Address use
Arr
+ Address (N / 8 * (Record_8_Units'Size / Standard'Storage_Unit));
begin
case Rem_8 (N rem 8) is
when 0 => Units.E0 := E;
when 1 => Units.E1 := E;
when 2 => Units.E2 := E;
when 3 => Units.E3 := E;
when 4 => Units.E4 := E;
when 5 => Units.E5 := E;
when 6 => Units.E6 := E;
when 7 => Units.E7 := E;
end case;
end Set_Reversed;
-- implementation
function Get (
Arr : Address;
N : Natural;
Rev_SSO : Boolean)
return Element_Type is
begin
if Rev_SSO then
return Get_Reversed (Arr, N);
else
return Get (Arr, N);
end if;
end Get;
procedure Set (
Arr : Address;
N : Natural;
E : Element_Type;
Rev_SSO : Boolean) is
begin
if Rev_SSO then
Set_Reversed (Arr, N, E);
else
Set (Arr, N, E);
end if;
end Set;
end Indexing;
end System.Packed_Arrays;
|
optikos/oasis | Ada | 5,233 | ads | -- Copyright (c) 2019 Maxim Reznik <[email protected]>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Program.Lexical_Elements;
with Program.Elements.Expressions;
with Program.Elements.Attribute_Definition_Clauses;
with Program.Element_Visitors;
package Program.Nodes.Attribute_Definition_Clauses is
pragma Preelaborate;
type Attribute_Definition_Clause is
new Program.Nodes.Node
and Program.Elements.Attribute_Definition_Clauses
.Attribute_Definition_Clause
and Program.Elements.Attribute_Definition_Clauses
.Attribute_Definition_Clause_Text
with private;
function Create
(For_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Name : not null Program.Elements.Expressions.Expression_Access;
Use_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Expression : not null Program.Elements.Expressions.Expression_Access;
Semicolon_Token : not null Program.Lexical_Elements
.Lexical_Element_Access)
return Attribute_Definition_Clause;
type Implicit_Attribute_Definition_Clause is
new Program.Nodes.Node
and Program.Elements.Attribute_Definition_Clauses
.Attribute_Definition_Clause
with private;
function Create
(Name : not null Program.Elements.Expressions
.Expression_Access;
Expression : not null Program.Elements.Expressions
.Expression_Access;
Is_Part_Of_Implicit : Boolean := False;
Is_Part_Of_Inherited : Boolean := False;
Is_Part_Of_Instance : Boolean := False)
return Implicit_Attribute_Definition_Clause
with Pre =>
Is_Part_Of_Implicit or Is_Part_Of_Inherited or Is_Part_Of_Instance;
private
type Base_Attribute_Definition_Clause is
abstract new Program.Nodes.Node
and Program.Elements.Attribute_Definition_Clauses
.Attribute_Definition_Clause
with record
Name : not null Program.Elements.Expressions.Expression_Access;
Expression : not null Program.Elements.Expressions.Expression_Access;
end record;
procedure Initialize
(Self : aliased in out Base_Attribute_Definition_Clause'Class);
overriding procedure Visit
(Self : not null access Base_Attribute_Definition_Clause;
Visitor : in out Program.Element_Visitors.Element_Visitor'Class);
overriding function Name
(Self : Base_Attribute_Definition_Clause)
return not null Program.Elements.Expressions.Expression_Access;
overriding function Expression
(Self : Base_Attribute_Definition_Clause)
return not null Program.Elements.Expressions.Expression_Access;
overriding function Is_Attribute_Definition_Clause_Element
(Self : Base_Attribute_Definition_Clause)
return Boolean;
overriding function Is_Representation_Clause_Element
(Self : Base_Attribute_Definition_Clause)
return Boolean;
overriding function Is_Clause_Element
(Self : Base_Attribute_Definition_Clause)
return Boolean;
type Attribute_Definition_Clause is
new Base_Attribute_Definition_Clause
and Program.Elements.Attribute_Definition_Clauses
.Attribute_Definition_Clause_Text
with record
For_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Use_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Semicolon_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
end record;
overriding function To_Attribute_Definition_Clause_Text
(Self : aliased in out Attribute_Definition_Clause)
return Program.Elements.Attribute_Definition_Clauses
.Attribute_Definition_Clause_Text_Access;
overriding function For_Token
(Self : Attribute_Definition_Clause)
return not null Program.Lexical_Elements.Lexical_Element_Access;
overriding function Use_Token
(Self : Attribute_Definition_Clause)
return not null Program.Lexical_Elements.Lexical_Element_Access;
overriding function Semicolon_Token
(Self : Attribute_Definition_Clause)
return not null Program.Lexical_Elements.Lexical_Element_Access;
type Implicit_Attribute_Definition_Clause is
new Base_Attribute_Definition_Clause
with record
Is_Part_Of_Implicit : Boolean;
Is_Part_Of_Inherited : Boolean;
Is_Part_Of_Instance : Boolean;
end record;
overriding function To_Attribute_Definition_Clause_Text
(Self : aliased in out Implicit_Attribute_Definition_Clause)
return Program.Elements.Attribute_Definition_Clauses
.Attribute_Definition_Clause_Text_Access;
overriding function Is_Part_Of_Implicit
(Self : Implicit_Attribute_Definition_Clause)
return Boolean;
overriding function Is_Part_Of_Inherited
(Self : Implicit_Attribute_Definition_Clause)
return Boolean;
overriding function Is_Part_Of_Instance
(Self : Implicit_Attribute_Definition_Clause)
return Boolean;
end Program.Nodes.Attribute_Definition_Clauses;
|
stcarrez/ada-util | Ada | 23,399 | adb | -----------------------------------------------------------------------
-- util-http-clients-curl -- HTTP Clients with CURL
-- Copyright (C) 2012, 2017, 2018, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Log.Loggers;
with Util.Http.Clients.Curl.Constants;
package body Util.Http.Clients.Curl is
use System;
pragma Linker_Options ("-lcurl");
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Curl");
function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access;
PUT_TOKEN : constant Chars_Ptr := Strings.New_String ("PUT");
PATCH_TOKEN : constant Chars_Ptr := Strings.New_String ("PATCH");
OPTIONS_TOKEN : constant Chars_Ptr := Strings.New_String ("OPTIONS");
DELETE_TOKEN : constant Chars_Ptr := Strings.New_String ("DELETE");
Manager : aliased Curl_Http_Manager;
-- ------------------------------
-- Register the CURL Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
-- ------------------------------
-- Check the CURL result code and report and exception and a log message if
-- the CURL code indicates an error.
-- ------------------------------
procedure Check_Code (Code : in CURL_Code;
Message : in String) is
begin
if Code /= CURLE_OK then
declare
Error : constant Chars_Ptr := Curl_Easy_Strerror (Code);
Msg : constant String := Interfaces.C.Strings.Value (Error);
begin
Log.Error ("{0}: {1}", Message, Msg);
raise Connection_Error with Msg;
end;
end if;
end Check_Code;
-- ------------------------------
-- Create a new HTTP request associated with the current request manager.
-- ------------------------------
overriding
procedure Create (Manager : in Curl_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
Request : Curl_Http_Request_Access;
Data : CURL;
begin
Data := Curl_Easy_Init;
if Data = System.Null_Address then
raise Storage_Error with "curl_easy_init cannot create the CURL instance";
end if;
Request := new Curl_Http_Request;
Request.Data := Data;
Http.Delegate := Request.all'Access;
end Create;
function Get_Request (Http : in Client'Class) return Curl_Http_Request_Access is
begin
return Curl_Http_Request'Class (Http.Delegate.all)'Access;
end Get_Request;
-- ------------------------------
-- This function is called by CURL when a response line was read.
-- ------------------------------
function Read_Response (Data : in System.Address;
Size : in Size_T;
Nmemb : in Size_T;
Response : in Curl_Http_Response_Access) return Size_T is
Total : constant Size_T := Size * Nmemb;
Last : Natural;
Line : String (1 .. Natural (Total));
for Line'Address use Data;
begin
if Response.Parsing_Body then
Response.Append_Body (Line);
elsif Total = 2 and then Line (1) = ASCII.CR and then Line (2) = ASCII.LF then
Response.Parsing_Body := True;
else
Last := Line'Last;
while Last > Line'First and then
(Line (Last) = ASCII.CR or else Line (Last) = ASCII.LF) loop
Last := Last - 1;
end loop;
Log.Debug ("RCV: {0}", Line (Line'First .. Last));
declare
Pos : constant Natural := Util.Strings.Index (Line, ':');
Start : Natural;
begin
if Pos > 0 then
Start := Pos + 1;
while Start <= Line'Last and then Line (Start) = ' ' loop
Start := Start + 1;
end loop;
Response.Add_Header (Name => Line (Line'First .. Pos - 1),
Value => Line (Start .. Last));
end if;
end;
end if;
return Total;
end Read_Response;
-- ------------------------------
-- Prepare to setup the headers in the request.
-- ------------------------------
procedure Set_Headers (Request : in out Curl_Http_Request) is
procedure Process (Name, Value : in String);
procedure Process (Name, Value : in String) is
S : Chars_Ptr := Strings.New_String (Name & ": " & Value);
begin
Request.Curl_Headers := Curl_Slist_Append (Request.Curl_Headers, S);
Interfaces.C.Strings.Free (S);
end Process;
begin
if Request.Curl_Headers /= null then
Curl_Slist_Free_All (Request.Curl_Headers);
Request.Curl_Headers := null;
end if;
Request.Iterate_Headers (Process'Access);
end Set_Headers;
overriding
procedure Do_Get (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
use Interfaces.C;
Req : constant Curl_Http_Request_Access := Get_Request (Http);
Result : CURL_Code;
Response : Curl_Http_Response_Access;
Status : aliased C.long;
begin
Log.Info ("GET {0}", URI);
Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION,
Read_Response'Access);
Check_Code (Result, "set callback");
Req.Set_Headers;
Interfaces.C.Strings.Free (Req.URL);
Req.URL := Strings.New_String (URI);
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HTTPGET, 1);
Check_Code (Result, "set http GET");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1);
Check_Code (Result, "set header");
Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers);
Check_Code (Result, "set http GET headers");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL);
Check_Code (Result, "set url");
Response := new Curl_Http_Response;
Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response);
Check_Code (Result, "set write data");
Reply.Delegate := Response.all'Access;
Result := Curl_Easy_Perform (Req.Data);
Check_Code (Result, "get request");
Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access);
Check_Code (Result, "get response code");
Response.Set_Status (Natural (Status));
end Do_Get;
overriding
procedure Do_Head (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
use Interfaces.C;
Req : constant Curl_Http_Request_Access := Get_Request (Http);
Result : CURL_Code;
Response : Curl_Http_Response_Access;
Status : aliased C.long;
begin
Log.Info ("HEAD {0}", URI);
Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION,
Read_Response'Access);
Check_Code (Result, "set callback");
Req.Set_Headers;
Interfaces.C.Strings.Free (Req.URL);
Req.URL := Strings.New_String (URI);
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_NOBODY, 1);
Check_Code (Result, "set http HEAD");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1);
Check_Code (Result, "set header");
Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers);
Check_Code (Result, "set http GET headers");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL);
Check_Code (Result, "set url");
Response := new Curl_Http_Response;
Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response);
Check_Code (Result, "set write data");
Reply.Delegate := Response.all'Access;
Result := Curl_Easy_Perform (Req.Data);
Check_Code (Result, "get request");
Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access);
Check_Code (Result, "get response code");
Response.Set_Status (Natural (Status));
end Do_Head;
overriding
procedure Do_Post (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
use Interfaces.C;
Req : constant Curl_Http_Request_Access := Get_Request (Http);
Result : CURL_Code;
Response : Curl_Http_Response_Access;
Status : aliased C.long;
begin
Log.Info ("POST {0}", URI);
Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION,
Read_Response'Access);
Check_Code (Result, "set callback");
Req.Set_Headers;
Interfaces.C.Strings.Free (Req.URL);
Req.URL := Strings.New_String (URI);
Interfaces.C.Strings.Free (Req.Content);
Req.Content := Strings.New_String (Data);
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1);
Check_Code (Result, "set http POST");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1);
Check_Code (Result, "set header");
Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers);
Check_Code (Result, "set http POST headers");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL);
Check_Code (Result, "set url");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content);
Check_Code (Result, "set post data");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length);
Check_Code (Result, "set post data");
Response := new Curl_Http_Response;
Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response);
Check_Code (Result, "set write data");
Reply.Delegate := Response.all'Access;
Result := Curl_Easy_Perform (Req.Data);
Check_Code (Result, "get request");
Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access);
Check_Code (Result, "get response code");
Response.Set_Status (Natural (Status));
if Req.Curl_Headers /= null then
Curl_Slist_Free_All (Req.Curl_Headers);
Req.Curl_Headers := null;
end if;
end Do_Post;
overriding
procedure Do_Put (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
use Interfaces.C;
Req : constant Curl_Http_Request_Access := Get_Request (Http);
Result : CURL_Code;
Response : Curl_Http_Response_Access;
Status : aliased C.long;
begin
Log.Info ("PUT {0}", URI);
Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION,
Read_Response'Access);
Check_Code (Result, "set callback");
Req.Set_Headers;
Interfaces.C.Strings.Free (Req.URL);
Req.URL := Strings.New_String (URI);
Interfaces.C.Strings.Free (Req.Content);
Req.Content := Strings.New_String (Data);
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1);
Check_Code (Result, "set http PUT");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1);
Check_Code (Result, "set header");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST, PUT_TOKEN);
Check_Code (Result, "set http PUT");
Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers);
Check_Code (Result, "set http PUT headers");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL);
Check_Code (Result, "set url");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content);
Check_Code (Result, "set put data");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length);
Check_Code (Result, "set put data");
Response := new Curl_Http_Response;
Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response);
Check_Code (Result, "set write data");
Reply.Delegate := Response.all'Access;
Result := Curl_Easy_Perform (Req.Data);
Check_Code (Result, "get request");
Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access);
Check_Code (Result, "get response code");
Response.Set_Status (Natural (Status));
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST,
Interfaces.C.Strings.Null_Ptr);
Check_Code (Result, "restore set http default");
if Req.Curl_Headers /= null then
Curl_Slist_Free_All (Req.Curl_Headers);
Req.Curl_Headers := null;
end if;
end Do_Put;
overriding
procedure Do_Patch (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
use Interfaces.C;
Req : constant Curl_Http_Request_Access := Get_Request (Http);
Result : CURL_Code;
Response : Curl_Http_Response_Access;
Status : aliased C.long;
begin
Log.Info ("PATCH {0}", URI);
Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION,
Read_Response'Access);
Check_Code (Result, "set callback");
Req.Set_Headers;
Interfaces.C.Strings.Free (Req.URL);
Req.URL := Strings.New_String (URI);
Interfaces.C.Strings.Free (Req.Content);
Req.Content := Strings.New_String (Data);
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1);
Check_Code (Result, "set http PATCH");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1);
Check_Code (Result, "set header");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST, PATCH_TOKEN);
Check_Code (Result, "set http PATCH");
Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers);
Check_Code (Result, "set http PATCH headers");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL);
Check_Code (Result, "set url");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content);
Check_Code (Result, "set patch data");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, Data'Length);
Check_Code (Result, "set patch data");
Response := new Curl_Http_Response;
Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response);
Check_Code (Result, "set write data");
Reply.Delegate := Response.all'Access;
Result := Curl_Easy_Perform (Req.Data);
Check_Code (Result, "get request");
Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access);
Check_Code (Result, "get response code");
Response.Set_Status (Natural (Status));
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST,
Interfaces.C.Strings.Null_Ptr);
Check_Code (Result, "restore set http default");
if Req.Curl_Headers /= null then
Curl_Slist_Free_All (Req.Curl_Headers);
Req.Curl_Headers := null;
end if;
end Do_Patch;
overriding
procedure Do_Delete (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
use Interfaces.C;
Req : constant Curl_Http_Request_Access := Get_Request (Http);
Result : CURL_Code;
Response : Curl_Http_Response_Access;
Status : aliased C.long;
begin
Log.Info ("DELETE {0}", URI);
Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION,
Read_Response'Access);
Check_Code (Result, "set callback");
Req.Set_Headers;
Interfaces.C.Strings.Free (Req.URL);
Req.URL := Strings.New_String (URI);
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1);
Check_Code (Result, "set http DELETE");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1);
Check_Code (Result, "set header");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST, DELETE_TOKEN);
Check_Code (Result, "set http DELETE");
Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers);
Check_Code (Result, "set http GET headers");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL);
Check_Code (Result, "set url");
-- Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_POSTFIELDS, Req.Content);
-- Check_Code (Result, "set post data");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, 0);
Check_Code (Result, "set post data");
Response := new Curl_Http_Response;
Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response);
Check_Code (Result, "set write data");
Reply.Delegate := Response.all'Access;
Result := Curl_Easy_Perform (Req.Data);
Check_Code (Result, "get request");
Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access);
Check_Code (Result, "get response code");
Response.Set_Status (Natural (Status));
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST,
Interfaces.C.Strings.Null_Ptr);
Check_Code (Result, "restore set http default");
end Do_Delete;
overriding
procedure Do_Options (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
use Interfaces.C;
Req : constant Curl_Http_Request_Access := Get_Request (Http);
Result : CURL_Code;
Response : Curl_Http_Response_Access;
Status : aliased C.long;
begin
Log.Info ("OPTIONS {0}", URI);
Result := Curl_Easy_Setopt_Write_Callback (Req.Data, Constants.CURLOPT_WRITEUNCTION,
Read_Response'Access);
Check_Code (Result, "set callback");
Req.Set_Headers;
Interfaces.C.Strings.Free (Req.URL);
Req.URL := Strings.New_String (URI);
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POST, 1);
Check_Code (Result, "set http OPTIONS");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_HEADER, 1);
Check_Code (Result, "set header");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST, OPTIONS_TOKEN);
Check_Code (Result, "set http OPTIONS");
Result := Curl_Easy_Setopt_Slist (Req.Data, Constants.CURLOPT_HTTPHEADER, Req.Curl_Headers);
Check_Code (Result, "set http OPTIONS headers");
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_URL, Req.URL);
Check_Code (Result, "set url");
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_POSTFIELDSIZE, 0);
Check_Code (Result, "set options data");
Response := new Curl_Http_Response;
Result := Curl_Easy_Setopt_Data (Req.Data, Constants.CURLOPT_WRITEDATA, Response);
Check_Code (Result, "set write data");
Reply.Delegate := Response.all'Access;
Result := Curl_Easy_Perform (Req.Data);
Check_Code (Result, "get request");
Result := Curl_Easy_Getinfo_Long (Req.Data, Constants.CURLINFO_RESPONSE_CODE, Status'Access);
Check_Code (Result, "get response code");
Response.Set_Status (Natural (Status));
Result := Curl_Easy_Setopt_String (Req.Data, Constants.CURLOPT_CUSTOMREQUEST,
Interfaces.C.Strings.Null_Ptr);
Check_Code (Result, "restore set http default");
end Do_Options;
-- ------------------------------
-- Set the timeout for the connection.
-- ------------------------------
overriding
procedure Set_Timeout (Manager : in Curl_Http_Manager;
Http : in Client'Class;
Timeout : in Duration) is
pragma Unreferenced (Manager);
Req : constant Curl_Http_Request_Access := Get_Request (Http);
Time : constant Interfaces.C.long := Interfaces.C.long (Timeout);
Result : CURL_Code;
begin
Result := Curl_Easy_Setopt_Long (Req.Data, Constants.CURLOPT_TIMEOUT, Time);
Check_Code (Result, "set timeout");
end Set_Timeout;
overriding
procedure Finalize (Request : in out Curl_Http_Request) is
begin
if Request.Data /= System.Null_Address then
Curl_Easy_Cleanup (Request.Data);
Request.Data := System.Null_Address;
end if;
if Request.Curl_Headers /= null then
Curl_Slist_Free_All (Request.Curl_Headers);
Request.Curl_Headers := null;
end if;
Interfaces.C.Strings.Free (Request.URL);
Interfaces.C.Strings.Free (Request.Content);
end Finalize;
end Util.Http.Clients.Curl;
|
zhmu/ananas | Ada | 25,378 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . S T R E A M _ A T T R I B U T E S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2022, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.IO_Exceptions;
with Ada.Streams; use Ada.Streams;
with Ada.Unchecked_Conversion;
with System.Stream_Attributes.XDR;
package body System.Stream_Attributes is
XDR_Stream : constant Integer;
pragma Import (C, XDR_Stream, "__gl_xdr_stream");
-- This imported value is used to determine whether the build had the
-- binder switch "-xdr" present which enables XDR streaming and sets this
-- flag to 1.
function XDR_Support return Boolean is (XDR_Stream = 1);
pragma Inline (XDR_Support);
-- Return True if XDR streaming should be used. Note that 128-bit integers
-- are not supported by the XDR protocol and will raise Device_Error.
Err : exception renames Ada.IO_Exceptions.End_Error;
-- Exception raised if insufficient data read (note that the RM implies
-- that Data_Error might be the appropriate choice, but AI95-00132
-- decides with a binding interpretation that End_Error is preferred).
SU : constant := System.Storage_Unit;
subtype SEA is Ada.Streams.Stream_Element_Array;
subtype SEO is Ada.Streams.Stream_Element_Offset;
generic function UC renames Ada.Unchecked_Conversion;
-- Subtypes used to define Stream_Element_Array values that map
-- into the elementary types, using unchecked conversion.
Thin_Pointer_Size : constant := System.Address'Size;
Fat_Pointer_Size : constant := System.Address'Size * 2;
subtype S_AD is SEA (1 .. (Fat_Pointer_Size + SU - 1) / SU);
subtype S_AS is SEA (1 .. (Thin_Pointer_Size + SU - 1) / SU);
subtype S_B is SEA (1 .. (Boolean'Size + SU - 1) / SU);
subtype S_C is SEA (1 .. (Character'Size + SU - 1) / SU);
subtype S_F is SEA (1 .. (Float'Size + SU - 1) / SU);
subtype S_I is SEA (1 .. (Integer'Size + SU - 1) / SU);
subtype S_I24 is SEA (1 .. (Integer_24'Size + SU - 1) / SU);
subtype S_LF is SEA (1 .. (Long_Float'Size + SU - 1) / SU);
subtype S_LI is SEA (1 .. (Long_Integer'Size + SU - 1) / SU);
subtype S_LLF is SEA (1 .. (Long_Long_Float'Size + SU - 1) / SU);
subtype S_LLI is SEA (1 .. (Long_Long_Integer'Size + SU - 1) / SU);
subtype S_LLLI is SEA (1 .. (Long_Long_Long_Integer'Size + SU - 1) / SU);
subtype S_LLLU is
SEA (1 .. (UST.Long_Long_Long_Unsigned'Size + SU - 1) / SU);
subtype S_LLU is SEA (1 .. (UST.Long_Long_Unsigned'Size + SU - 1) / SU);
subtype S_LU is SEA (1 .. (UST.Long_Unsigned'Size + SU - 1) / SU);
subtype S_SF is SEA (1 .. (Short_Float'Size + SU - 1) / SU);
subtype S_SI is SEA (1 .. (Short_Integer'Size + SU - 1) / SU);
subtype S_SSI is SEA (1 .. (Short_Short_Integer'Size + SU - 1) / SU);
subtype S_SSU is SEA (1 .. (UST.Short_Short_Unsigned'Size + SU - 1) / SU);
subtype S_SU is SEA (1 .. (UST.Short_Unsigned'Size + SU - 1) / SU);
subtype S_U is SEA (1 .. (UST.Unsigned'Size + SU - 1) / SU);
subtype S_U24 is SEA (1 .. (Unsigned_24'Size + SU - 1) / SU);
subtype S_WC is SEA (1 .. (Wide_Character'Size + SU - 1) / SU);
subtype S_WWC is SEA (1 .. (Wide_Wide_Character'Size + SU - 1) / SU);
-- Unchecked conversions from the elementary type to the stream type
function From_AD is new UC (Fat_Pointer, S_AD);
function From_AS is new UC (Thin_Pointer, S_AS);
function From_F is new UC (Float, S_F);
function From_I is new UC (Integer, S_I);
function From_I24 is new UC (Integer_24, S_I24);
function From_LF is new UC (Long_Float, S_LF);
function From_LI is new UC (Long_Integer, S_LI);
function From_LLF is new UC (Long_Long_Float, S_LLF);
function From_LLI is new UC (Long_Long_Integer, S_LLI);
function From_LLLI is new UC (Long_Long_Long_Integer, S_LLLI);
function From_LLLU is new UC (UST.Long_Long_Long_Unsigned, S_LLLU);
function From_LLU is new UC (UST.Long_Long_Unsigned, S_LLU);
function From_LU is new UC (UST.Long_Unsigned, S_LU);
function From_SF is new UC (Short_Float, S_SF);
function From_SI is new UC (Short_Integer, S_SI);
function From_SSI is new UC (Short_Short_Integer, S_SSI);
function From_SSU is new UC (UST.Short_Short_Unsigned, S_SSU);
function From_SU is new UC (UST.Short_Unsigned, S_SU);
function From_U is new UC (UST.Unsigned, S_U);
function From_U24 is new UC (Unsigned_24, S_U24);
function From_WC is new UC (Wide_Character, S_WC);
function From_WWC is new UC (Wide_Wide_Character, S_WWC);
-- Unchecked conversions from the stream type to elementary type
function To_AD is new UC (S_AD, Fat_Pointer);
function To_AS is new UC (S_AS, Thin_Pointer);
function To_F is new UC (S_F, Float);
function To_I is new UC (S_I, Integer);
function To_I24 is new UC (S_I24, Integer_24);
function To_LF is new UC (S_LF, Long_Float);
function To_LI is new UC (S_LI, Long_Integer);
function To_LLF is new UC (S_LLF, Long_Long_Float);
function To_LLI is new UC (S_LLI, Long_Long_Integer);
function To_LLLI is new UC (S_LLLI, Long_Long_Long_Integer);
function To_LLLU is new UC (S_LLLU, UST.Long_Long_Long_Unsigned);
function To_LLU is new UC (S_LLU, UST.Long_Long_Unsigned);
function To_LU is new UC (S_LU, UST.Long_Unsigned);
function To_SF is new UC (S_SF, Short_Float);
function To_SI is new UC (S_SI, Short_Integer);
function To_SSI is new UC (S_SSI, Short_Short_Integer);
function To_SSU is new UC (S_SSU, UST.Short_Short_Unsigned);
function To_SU is new UC (S_SU, UST.Short_Unsigned);
function To_U is new UC (S_U, UST.Unsigned);
function To_U24 is new UC (S_U24, Unsigned_24);
function To_WC is new UC (S_WC, Wide_Character);
function To_WWC is new UC (S_WWC, Wide_Wide_Character);
-----------------
-- Block_IO_OK --
-----------------
function Block_IO_OK return Boolean is
begin
return not XDR_Support;
end Block_IO_OK;
----------
-- I_AD --
----------
function I_AD (Stream : not null access RST) return Fat_Pointer is
T : S_AD;
L : SEO;
begin
if XDR_Support then
return XDR.I_AD (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_AD (T);
end if;
end I_AD;
----------
-- I_AS --
----------
function I_AS (Stream : not null access RST) return Thin_Pointer is
T : S_AS;
L : SEO;
begin
if XDR_Support then
return XDR.I_AS (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_AS (T);
end if;
end I_AS;
---------
-- I_B --
---------
function I_B (Stream : not null access RST) return Boolean is
T : S_B;
L : SEO;
begin
if XDR_Support then
return XDR.I_B (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return Boolean'Val (T (1));
end if;
end I_B;
---------
-- I_C --
---------
function I_C (Stream : not null access RST) return Character is
T : S_C;
L : SEO;
begin
if XDR_Support then
return XDR.I_C (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return Character'Val (T (1));
end if;
end I_C;
---------
-- I_F --
---------
function I_F (Stream : not null access RST) return Float is
T : S_F;
L : SEO;
begin
if XDR_Support then
return XDR.I_F (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_F (T);
end if;
end I_F;
---------
-- I_I --
---------
function I_I (Stream : not null access RST) return Integer is
T : S_I;
L : SEO;
begin
if XDR_Support then
return XDR.I_I (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_I (T);
end if;
end I_I;
-----------
-- I_I24 --
-----------
function I_I24 (Stream : not null access RST) return Integer_24 is
T : S_I24;
L : SEO;
begin
if XDR_Support then
return XDR.I_I24 (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_I24 (T);
end if;
end I_I24;
----------
-- I_LF --
----------
function I_LF (Stream : not null access RST) return Long_Float is
T : S_LF;
L : SEO;
begin
if XDR_Support then
return XDR.I_LF (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_LF (T);
end if;
end I_LF;
----------
-- I_LI --
----------
function I_LI (Stream : not null access RST) return Long_Integer is
T : S_LI;
L : SEO;
begin
if XDR_Support then
return XDR.I_LI (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_LI (T);
end if;
end I_LI;
-----------
-- I_LLF --
-----------
function I_LLF (Stream : not null access RST) return Long_Long_Float is
T : S_LLF;
L : SEO;
begin
if XDR_Support then
return XDR.I_LLF (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_LLF (T);
end if;
end I_LLF;
-----------
-- I_LLI --
-----------
function I_LLI (Stream : not null access RST) return Long_Long_Integer is
T : S_LLI;
L : SEO;
begin
if XDR_Support then
return XDR.I_LLI (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_LLI (T);
end if;
end I_LLI;
------------
-- I_LLLI --
------------
function I_LLLI (Stream : not null access RST) return Long_Long_Long_Integer
is
T : S_LLLI;
L : SEO;
begin
if XDR_Support then
raise Ada.IO_Exceptions.Device_Error;
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_LLLI (T);
end if;
end I_LLLI;
------------
-- I_LLLU --
------------
function I_LLLU
(Stream : not null access RST) return UST.Long_Long_Long_Unsigned
is
T : S_LLLU;
L : SEO;
begin
if XDR_Support then
raise Ada.IO_Exceptions.Device_Error;
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_LLLU (T);
end if;
end I_LLLU;
-----------
-- I_LLU --
-----------
function I_LLU
(Stream : not null access RST) return UST.Long_Long_Unsigned
is
T : S_LLU;
L : SEO;
begin
if XDR_Support then
return XDR.I_LLU (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_LLU (T);
end if;
end I_LLU;
----------
-- I_LU --
----------
function I_LU (Stream : not null access RST) return UST.Long_Unsigned is
T : S_LU;
L : SEO;
begin
if XDR_Support then
return XDR.I_LU (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_LU (T);
end if;
end I_LU;
----------
-- I_SF --
----------
function I_SF (Stream : not null access RST) return Short_Float is
T : S_SF;
L : SEO;
begin
if XDR_Support then
return XDR.I_SF (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_SF (T);
end if;
end I_SF;
----------
-- I_SI --
----------
function I_SI (Stream : not null access RST) return Short_Integer is
T : S_SI;
L : SEO;
begin
if XDR_Support then
return XDR.I_SI (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_SI (T);
end if;
end I_SI;
-----------
-- I_SSI --
-----------
function I_SSI (Stream : not null access RST) return Short_Short_Integer is
T : S_SSI;
L : SEO;
begin
if XDR_Support then
return XDR.I_SSI (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_SSI (T);
end if;
end I_SSI;
-----------
-- I_SSU --
-----------
function I_SSU
(Stream : not null access RST) return UST.Short_Short_Unsigned
is
T : S_SSU;
L : SEO;
begin
if XDR_Support then
return XDR.I_SSU (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_SSU (T);
end if;
end I_SSU;
----------
-- I_SU --
----------
function I_SU (Stream : not null access RST) return UST.Short_Unsigned is
T : S_SU;
L : SEO;
begin
if XDR_Support then
return XDR.I_SU (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_SU (T);
end if;
end I_SU;
---------
-- I_U --
---------
function I_U (Stream : not null access RST) return UST.Unsigned is
T : S_U;
L : SEO;
begin
if XDR_Support then
return XDR.I_U (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_U (T);
end if;
end I_U;
-----------
-- I_U24 --
-----------
function I_U24 (Stream : not null access RST) return Unsigned_24 is
T : S_U24;
L : SEO;
begin
if XDR_Support then
return XDR.I_U24 (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_U24 (T);
end if;
end I_U24;
----------
-- I_WC --
----------
function I_WC (Stream : not null access RST) return Wide_Character is
T : S_WC;
L : SEO;
begin
if XDR_Support then
return XDR.I_WC (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_WC (T);
end if;
end I_WC;
-----------
-- I_WWC --
-----------
function I_WWC (Stream : not null access RST) return Wide_Wide_Character is
T : S_WWC;
L : SEO;
begin
if XDR_Support then
return XDR.I_WWC (Stream);
end if;
Ada.Streams.Read (Stream.all, T, L);
if L < T'Last then
raise Err;
else
return To_WWC (T);
end if;
end I_WWC;
----------
-- W_AD --
----------
procedure W_AD (Stream : not null access RST; Item : Fat_Pointer) is
T : constant S_AD := From_AD (Item);
begin
if XDR_Support then
XDR.W_AD (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, T);
end W_AD;
----------
-- W_AS --
----------
procedure W_AS (Stream : not null access RST; Item : Thin_Pointer) is
T : constant S_AS := From_AS (Item);
begin
if XDR_Support then
XDR.W_AS (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, T);
end W_AS;
---------
-- W_B --
---------
procedure W_B (Stream : not null access RST; Item : Boolean) is
T : S_B;
begin
if XDR_Support then
XDR.W_B (Stream, Item);
return;
end if;
T (1) := Boolean'Pos (Item);
Ada.Streams.Write (Stream.all, T);
end W_B;
---------
-- W_C --
---------
procedure W_C (Stream : not null access RST; Item : Character) is
T : S_C;
begin
if XDR_Support then
XDR.W_C (Stream, Item);
return;
end if;
T (1) := Character'Pos (Item);
Ada.Streams.Write (Stream.all, T);
end W_C;
---------
-- W_F --
---------
procedure W_F (Stream : not null access RST; Item : Float) is
begin
if XDR_Support then
XDR.W_F (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_F (Item));
end W_F;
---------
-- W_I --
---------
procedure W_I (Stream : not null access RST; Item : Integer) is
begin
if XDR_Support then
XDR.W_I (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_I (Item));
end W_I;
-----------
-- W_I24 --
-----------
procedure W_I24 (Stream : not null access RST; Item : Integer_24) is
begin
if XDR_Support then
XDR.W_I24 (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_I24 (Item));
end W_I24;
----------
-- W_LF --
----------
procedure W_LF (Stream : not null access RST; Item : Long_Float) is
begin
if XDR_Support then
XDR.W_LF (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_LF (Item));
end W_LF;
----------
-- W_LI --
----------
procedure W_LI (Stream : not null access RST; Item : Long_Integer) is
begin
if XDR_Support then
XDR.W_LI (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_LI (Item));
end W_LI;
-----------
-- W_LLF --
-----------
procedure W_LLF (Stream : not null access RST; Item : Long_Long_Float) is
begin
if XDR_Support then
XDR.W_LLF (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_LLF (Item));
end W_LLF;
-----------
-- W_LLI --
-----------
procedure W_LLI (Stream : not null access RST; Item : Long_Long_Integer) is
begin
if XDR_Support then
XDR.W_LLI (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_LLI (Item));
end W_LLI;
------------
-- W_LLLI --
------------
procedure W_LLLI
(Stream : not null access RST; Item : Long_Long_Long_Integer) is
begin
if XDR_Support then
raise Ada.IO_Exceptions.Device_Error;
end if;
Ada.Streams.Write (Stream.all, From_LLLI (Item));
end W_LLLI;
------------
-- W_LLLU --
------------
procedure W_LLLU
(Stream : not null access RST; Item : UST.Long_Long_Long_Unsigned)
is
begin
if XDR_Support then
raise Ada.IO_Exceptions.Device_Error;
end if;
Ada.Streams.Write (Stream.all, From_LLLU (Item));
end W_LLLU;
-----------
-- W_LLU --
-----------
procedure W_LLU
(Stream : not null access RST; Item : UST.Long_Long_Unsigned)
is
begin
if XDR_Support then
XDR.W_LLU (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_LLU (Item));
end W_LLU;
----------
-- W_LU --
----------
procedure W_LU (Stream : not null access RST; Item : UST.Long_Unsigned) is
begin
if XDR_Support then
XDR.W_LU (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_LU (Item));
end W_LU;
----------
-- W_SF --
----------
procedure W_SF (Stream : not null access RST; Item : Short_Float) is
begin
if XDR_Support then
XDR.W_SF (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_SF (Item));
end W_SF;
----------
-- W_SI --
----------
procedure W_SI (Stream : not null access RST; Item : Short_Integer) is
begin
if XDR_Support then
XDR.W_SI (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_SI (Item));
end W_SI;
-----------
-- W_SSI --
-----------
procedure W_SSI
(Stream : not null access RST; Item : Short_Short_Integer)
is
begin
if XDR_Support then
XDR.W_SSI (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_SSI (Item));
end W_SSI;
-----------
-- W_SSU --
-----------
procedure W_SSU
(Stream : not null access RST; Item : UST.Short_Short_Unsigned)
is
begin
if XDR_Support then
XDR.W_SSU (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_SSU (Item));
end W_SSU;
----------
-- W_SU --
----------
procedure W_SU (Stream : not null access RST; Item : UST.Short_Unsigned) is
begin
if XDR_Support then
XDR.W_SU (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_SU (Item));
end W_SU;
---------
-- W_U --
---------
procedure W_U (Stream : not null access RST; Item : UST.Unsigned) is
begin
if XDR_Support then
XDR.W_U (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_U (Item));
end W_U;
-----------
-- W_U24 --
-----------
procedure W_U24 (Stream : not null access RST; Item : Unsigned_24) is
begin
if XDR_Support then
XDR.W_U24 (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_U24 (Item));
end W_U24;
----------
-- W_WC --
----------
procedure W_WC (Stream : not null access RST; Item : Wide_Character) is
begin
if XDR_Support then
XDR.W_WC (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_WC (Item));
end W_WC;
-----------
-- W_WWC --
-----------
procedure W_WWC
(Stream : not null access RST; Item : Wide_Wide_Character)
is
begin
if XDR_Support then
XDR.W_WWC (Stream, Item);
return;
end if;
Ada.Streams.Write (Stream.all, From_WWC (Item));
end W_WWC;
end System.Stream_Attributes;
|
JeremyGrosser/clock3 | Ada | 16,449 | ads | pragma Style_Checks (Off);
-- Copyright (c) 2018 Microchip Technology Inc.
--
-- SPDX-License-Identifier: Apache-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.
-- This spec has been automatically generated from ATSAMD21G18A.svd
pragma Restrictions (No_Elaboration_Code);
with HAL;
with System;
package SAMD21_SVD.PM is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- Idle Mode Configuration
type SLEEP_IDLESelect is
(-- The CPU clock domain is stopped
CPU,
-- The CPU and AHB clock domains are stopped
AHB,
-- The CPU, AHB and APB clock domains are stopped
APB)
with Size => 2;
for SLEEP_IDLESelect use
(CPU => 0,
AHB => 1,
APB => 2);
-- Sleep Mode
type PM_SLEEP_Register is record
-- Idle Mode Configuration
IDLE : SLEEP_IDLESelect := SAMD21_SVD.PM.CPU;
-- unspecified
Reserved_2_7 : HAL.UInt6 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for PM_SLEEP_Register use record
IDLE at 0 range 0 .. 1;
Reserved_2_7 at 0 range 2 .. 7;
end record;
-- CPU Prescaler Selection
type CPUSEL_CPUDIVSelect is
(-- Divide by 1
DIV1,
-- Divide by 2
DIV2,
-- Divide by 4
DIV4,
-- Divide by 8
DIV8,
-- Divide by 16
DIV16,
-- Divide by 32
DIV32,
-- Divide by 64
DIV64,
-- Divide by 128
DIV128)
with Size => 3;
for CPUSEL_CPUDIVSelect use
(DIV1 => 0,
DIV2 => 1,
DIV4 => 2,
DIV8 => 3,
DIV16 => 4,
DIV32 => 5,
DIV64 => 6,
DIV128 => 7);
-- CPU Clock Select
type PM_CPUSEL_Register is record
-- CPU Prescaler Selection
CPUDIV : CPUSEL_CPUDIVSelect := SAMD21_SVD.PM.DIV1;
-- unspecified
Reserved_3_7 : HAL.UInt5 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for PM_CPUSEL_Register use record
CPUDIV at 0 range 0 .. 2;
Reserved_3_7 at 0 range 3 .. 7;
end record;
-- APBA Prescaler Selection
type APBASEL_APBADIVSelect is
(-- Divide by 1
DIV1,
-- Divide by 2
DIV2,
-- Divide by 4
DIV4,
-- Divide by 8
DIV8,
-- Divide by 16
DIV16,
-- Divide by 32
DIV32,
-- Divide by 64
DIV64,
-- Divide by 128
DIV128)
with Size => 3;
for APBASEL_APBADIVSelect use
(DIV1 => 0,
DIV2 => 1,
DIV4 => 2,
DIV8 => 3,
DIV16 => 4,
DIV32 => 5,
DIV64 => 6,
DIV128 => 7);
-- APBA Clock Select
type PM_APBASEL_Register is record
-- APBA Prescaler Selection
APBADIV : APBASEL_APBADIVSelect := SAMD21_SVD.PM.DIV1;
-- unspecified
Reserved_3_7 : HAL.UInt5 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for PM_APBASEL_Register use record
APBADIV at 0 range 0 .. 2;
Reserved_3_7 at 0 range 3 .. 7;
end record;
-- APBB Prescaler Selection
type APBBSEL_APBBDIVSelect is
(-- Divide by 1
DIV1,
-- Divide by 2
DIV2,
-- Divide by 4
DIV4,
-- Divide by 8
DIV8,
-- Divide by 16
DIV16,
-- Divide by 32
DIV32,
-- Divide by 64
DIV64,
-- Divide by 128
DIV128)
with Size => 3;
for APBBSEL_APBBDIVSelect use
(DIV1 => 0,
DIV2 => 1,
DIV4 => 2,
DIV8 => 3,
DIV16 => 4,
DIV32 => 5,
DIV64 => 6,
DIV128 => 7);
-- APBB Clock Select
type PM_APBBSEL_Register is record
-- APBB Prescaler Selection
APBBDIV : APBBSEL_APBBDIVSelect := SAMD21_SVD.PM.DIV1;
-- unspecified
Reserved_3_7 : HAL.UInt5 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for PM_APBBSEL_Register use record
APBBDIV at 0 range 0 .. 2;
Reserved_3_7 at 0 range 3 .. 7;
end record;
-- APBC Prescaler Selection
type APBCSEL_APBCDIVSelect is
(-- Divide by 1
DIV1,
-- Divide by 2
DIV2,
-- Divide by 4
DIV4,
-- Divide by 8
DIV8,
-- Divide by 16
DIV16,
-- Divide by 32
DIV32,
-- Divide by 64
DIV64,
-- Divide by 128
DIV128)
with Size => 3;
for APBCSEL_APBCDIVSelect use
(DIV1 => 0,
DIV2 => 1,
DIV4 => 2,
DIV8 => 3,
DIV16 => 4,
DIV32 => 5,
DIV64 => 6,
DIV128 => 7);
-- APBC Clock Select
type PM_APBCSEL_Register is record
-- APBC Prescaler Selection
APBCDIV : APBCSEL_APBCDIVSelect := SAMD21_SVD.PM.DIV1;
-- unspecified
Reserved_3_7 : HAL.UInt5 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for PM_APBCSEL_Register use record
APBCDIV at 0 range 0 .. 2;
Reserved_3_7 at 0 range 3 .. 7;
end record;
-- AHB Mask
type PM_AHBMASK_Register is record
-- HPB0 AHB Clock Mask
HPB0 : Boolean := True;
-- HPB1 AHB Clock Mask
HPB1 : Boolean := True;
-- HPB2 AHB Clock Mask
HPB2 : Boolean := True;
-- DSU AHB Clock Mask
DSU : Boolean := True;
-- NVMCTRL AHB Clock Mask
NVMCTRL : Boolean := True;
-- DMAC AHB Clock Mask
DMAC : Boolean := True;
-- USB AHB Clock Mask
USB : Boolean := True;
-- unspecified
Reserved_7_31 : HAL.UInt25 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PM_AHBMASK_Register use record
HPB0 at 0 range 0 .. 0;
HPB1 at 0 range 1 .. 1;
HPB2 at 0 range 2 .. 2;
DSU at 0 range 3 .. 3;
NVMCTRL at 0 range 4 .. 4;
DMAC at 0 range 5 .. 5;
USB at 0 range 6 .. 6;
Reserved_7_31 at 0 range 7 .. 31;
end record;
-- APBA Mask
type PM_APBAMASK_Register is record
-- PAC0 APB Clock Enable
PAC0 : Boolean := True;
-- PM APB Clock Enable
PM : Boolean := True;
-- SYSCTRL APB Clock Enable
SYSCTRL : Boolean := True;
-- GCLK APB Clock Enable
GCLK : Boolean := True;
-- WDT APB Clock Enable
WDT : Boolean := True;
-- RTC APB Clock Enable
RTC : Boolean := True;
-- EIC APB Clock Enable
EIC : Boolean := True;
-- unspecified
Reserved_7_31 : HAL.UInt25 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PM_APBAMASK_Register use record
PAC0 at 0 range 0 .. 0;
PM at 0 range 1 .. 1;
SYSCTRL at 0 range 2 .. 2;
GCLK at 0 range 3 .. 3;
WDT at 0 range 4 .. 4;
RTC at 0 range 5 .. 5;
EIC at 0 range 6 .. 6;
Reserved_7_31 at 0 range 7 .. 31;
end record;
-- APBB Mask
type PM_APBBMASK_Register is record
-- PAC1 APB Clock Enable
PAC1 : Boolean := True;
-- DSU APB Clock Enable
DSU : Boolean := True;
-- NVMCTRL APB Clock Enable
NVMCTRL : Boolean := True;
-- PORT APB Clock Enable
PORT : Boolean := True;
-- DMAC APB Clock Enable
DMAC : Boolean := True;
-- USB APB Clock Enable
USB : Boolean := True;
-- HMATRIX APB Clock Enable
HMATRIX : Boolean := True;
-- unspecified
Reserved_7_31 : HAL.UInt25 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PM_APBBMASK_Register use record
PAC1 at 0 range 0 .. 0;
DSU at 0 range 1 .. 1;
NVMCTRL at 0 range 2 .. 2;
PORT at 0 range 3 .. 3;
DMAC at 0 range 4 .. 4;
USB at 0 range 5 .. 5;
HMATRIX at 0 range 6 .. 6;
Reserved_7_31 at 0 range 7 .. 31;
end record;
-- APBC Mask
type PM_APBCMASK_Register is record
-- PAC2 APB Clock Enable
PAC2 : Boolean := False;
-- EVSYS APB Clock Enable
EVSYS : Boolean := False;
-- SERCOM0 APB Clock Enable
SERCOM0 : Boolean := False;
-- SERCOM1 APB Clock Enable
SERCOM1 : Boolean := False;
-- SERCOM2 APB Clock Enable
SERCOM2 : Boolean := False;
-- SERCOM3 APB Clock Enable
SERCOM3 : Boolean := False;
-- SERCOM4 APB Clock Enable
SERCOM4 : Boolean := False;
-- SERCOM5 APB Clock Enable
SERCOM5 : Boolean := False;
-- TCC0 APB Clock Enable
TCC0 : Boolean := False;
-- TCC1 APB Clock Enable
TCC1 : Boolean := False;
-- TCC2 APB Clock Enable
TCC2 : Boolean := False;
-- TC3 APB Clock Enable
TC3 : Boolean := False;
-- TC4 APB Clock Enable
TC4 : Boolean := False;
-- TC5 APB Clock Enable
TC5 : Boolean := False;
-- unspecified
Reserved_14_15 : HAL.UInt2 := 16#0#;
-- ADC APB Clock Enable
ADC : Boolean := True;
-- AC APB Clock Enable
AC : Boolean := False;
-- DAC APB Clock Enable
DAC : Boolean := False;
-- PTC APB Clock Enable
PTC : Boolean := False;
-- I2S APB Clock Enable
I2S : Boolean := False;
-- unspecified
Reserved_21_31 : HAL.UInt11 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PM_APBCMASK_Register use record
PAC2 at 0 range 0 .. 0;
EVSYS at 0 range 1 .. 1;
SERCOM0 at 0 range 2 .. 2;
SERCOM1 at 0 range 3 .. 3;
SERCOM2 at 0 range 4 .. 4;
SERCOM3 at 0 range 5 .. 5;
SERCOM4 at 0 range 6 .. 6;
SERCOM5 at 0 range 7 .. 7;
TCC0 at 0 range 8 .. 8;
TCC1 at 0 range 9 .. 9;
TCC2 at 0 range 10 .. 10;
TC3 at 0 range 11 .. 11;
TC4 at 0 range 12 .. 12;
TC5 at 0 range 13 .. 13;
Reserved_14_15 at 0 range 14 .. 15;
ADC at 0 range 16 .. 16;
AC at 0 range 17 .. 17;
DAC at 0 range 18 .. 18;
PTC at 0 range 19 .. 19;
I2S at 0 range 20 .. 20;
Reserved_21_31 at 0 range 21 .. 31;
end record;
-- Interrupt Enable Clear
type PM_INTENCLR_Register is record
-- Clock Ready Interrupt Enable
CKRDY : Boolean := False;
-- unspecified
Reserved_1_7 : HAL.UInt7 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for PM_INTENCLR_Register use record
CKRDY at 0 range 0 .. 0;
Reserved_1_7 at 0 range 1 .. 7;
end record;
-- Interrupt Enable Set
type PM_INTENSET_Register is record
-- Clock Ready Interrupt Enable
CKRDY : Boolean := False;
-- unspecified
Reserved_1_7 : HAL.UInt7 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for PM_INTENSET_Register use record
CKRDY at 0 range 0 .. 0;
Reserved_1_7 at 0 range 1 .. 7;
end record;
-- Interrupt Flag Status and Clear
type PM_INTFLAG_Register is record
-- Clock Ready
CKRDY : Boolean := False;
-- unspecified
Reserved_1_7 : HAL.UInt7 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for PM_INTFLAG_Register use record
CKRDY at 0 range 0 .. 0;
Reserved_1_7 at 0 range 1 .. 7;
end record;
-- PM_RCAUSE_BOD array
type PM_RCAUSE_BOD_Field_Array is array (12 .. 13) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for PM_RCAUSE_BOD
type PM_RCAUSE_BOD_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- BOD as a value
Val : HAL.UInt2;
when True =>
-- BOD as an array
Arr : PM_RCAUSE_BOD_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for PM_RCAUSE_BOD_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- Reset Cause
type PM_RCAUSE_Register is record
-- Read-only. Power On Reset
POR : Boolean;
-- Read-only. Brown Out 12 Detector Reset
BOD : PM_RCAUSE_BOD_Field;
-- unspecified
Reserved_3_3 : HAL.Bit;
-- Read-only. External Reset
EXT : Boolean;
-- Read-only. Watchdog Reset
WDT : Boolean;
-- Read-only. System Reset Request
SYST : Boolean;
-- unspecified
Reserved_7_7 : HAL.Bit;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for PM_RCAUSE_Register use record
POR at 0 range 0 .. 0;
BOD at 0 range 1 .. 2;
Reserved_3_3 at 0 range 3 .. 3;
EXT at 0 range 4 .. 4;
WDT at 0 range 5 .. 5;
SYST at 0 range 6 .. 6;
Reserved_7_7 at 0 range 7 .. 7;
end record;
-----------------
-- Peripherals --
-----------------
-- Power Manager
type PM_Peripheral is record
-- Control
CTRL : aliased HAL.UInt8;
-- Sleep Mode
SLEEP : aliased PM_SLEEP_Register;
-- CPU Clock Select
CPUSEL : aliased PM_CPUSEL_Register;
-- APBA Clock Select
APBASEL : aliased PM_APBASEL_Register;
-- APBB Clock Select
APBBSEL : aliased PM_APBBSEL_Register;
-- APBC Clock Select
APBCSEL : aliased PM_APBCSEL_Register;
-- AHB Mask
AHBMASK : aliased PM_AHBMASK_Register;
-- APBA Mask
APBAMASK : aliased PM_APBAMASK_Register;
-- APBB Mask
APBBMASK : aliased PM_APBBMASK_Register;
-- APBC Mask
APBCMASK : aliased PM_APBCMASK_Register;
-- Interrupt Enable Clear
INTENCLR : aliased PM_INTENCLR_Register;
-- Interrupt Enable Set
INTENSET : aliased PM_INTENSET_Register;
-- Interrupt Flag Status and Clear
INTFLAG : aliased PM_INTFLAG_Register;
-- Reset Cause
RCAUSE : aliased PM_RCAUSE_Register;
end record
with Volatile;
for PM_Peripheral use record
CTRL at 16#0# range 0 .. 7;
SLEEP at 16#1# range 0 .. 7;
CPUSEL at 16#8# range 0 .. 7;
APBASEL at 16#9# range 0 .. 7;
APBBSEL at 16#A# range 0 .. 7;
APBCSEL at 16#B# range 0 .. 7;
AHBMASK at 16#14# range 0 .. 31;
APBAMASK at 16#18# range 0 .. 31;
APBBMASK at 16#1C# range 0 .. 31;
APBCMASK at 16#20# range 0 .. 31;
INTENCLR at 16#34# range 0 .. 7;
INTENSET at 16#35# range 0 .. 7;
INTFLAG at 16#36# range 0 .. 7;
RCAUSE at 16#38# range 0 .. 7;
end record;
-- Power Manager
PM_Periph : aliased PM_Peripheral
with Import, Address => PM_Base;
end SAMD21_SVD.PM;
|
ekoeppen/STM32_Generic_Ada_Drivers | Ada | 779 | adb | with STM32_SVD; use STM32_SVD;
with STM32_SVD.RCC; use STM32_SVD.RCC;
with STM32_SVD.PWR; use STM32_SVD.PWR;
with STM32GD.Startup;
package body STM32GD.Board is
procedure Init is
begin
Clocks.Init;
RCC_Periph.AHBENR.IOPAEN := 1;
RCC_Periph.AHBENR.IOPBEN := 1;
RCC_Periph.AHBENR.IOPCEN := 1;
RCC_Periph.APB2ENR.USART1EN := 1;
RCC_Periph.APB2ENR.SYSCFGEN := 1;
RCC_Periph.APB1ENR.PWREN := 1;
RCC_Periph.APB1ENR.I2C1EN := 1;
PWR_Periph.CR.DBP := 1;
RCC_Periph.BDCR.RTCSEL := 2#10#;
RCC_Periph.BDCR.RTCEN := 1;
BUTTON.Init;
LED.Init;
LED2.Init;
TX.Init;
RX.Init;
USART.Init;
RTC.Init;
I2C.Init;
SCL.Init;
SDA.Init;
end Init;
end STM32GD.Board;
|
faelys/natools | Ada | 4,200 | adb | ------------------------------------------------------------------------------
-- Copyright (c) 2013, 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. --
------------------------------------------------------------------------------
procedure Natools.Chunked_Strings.Tests.Memory
(Report : in out Natools.Tests.Reporter'Class)
is
function Allocated_Size (Source : in Chunked_String) return Natural;
-- Return the number of allocated characters in Source
function Allocated_Size (Source : in Chunked_String) return Natural is
begin
if Source.Data = null or else Source.Data'Last < 1 then
return 0;
end if;
return (Source.Data'Last - 1) * Source.Chunk_Size
+ Source.Data (Source.Data'Last)'Last;
end Allocated_Size;
package NT renames Natools.Tests;
begin
NT.Section (Report, "Extra tests for memory usage");
declare
Name : constant String := "Procedure Preallocate";
CS : Chunked_String;
Memory_Ref : Natural;
Repeats : constant Positive := 50;
begin
Preallocate (CS, Repeats * Name'Length);
Memory_Ref := Allocated_Size (CS);
for I in 1 .. Repeats loop
Append (CS, Name);
end loop;
if Memory_Ref /= Allocated_Size (CS) then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Memory after preallocation:"
& Natural'Image (Memory_Ref));
NT.Info (Report, "Memory after insertions:"
& Natural'Image (Allocated_Size (CS)));
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Procedure Free_Extra_Memory";
CS : Chunked_String;
Memory_Ref : Natural;
Repeats : constant Positive := 50;
begin
Preallocate (CS, Repeats * Name'Length);
Append (CS, Name);
Memory_Ref := Allocated_Size (CS);
Free_Extra_Memory (CS);
if Memory_Ref <= Allocated_Size (CS) then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Memory before:"
& Natural'Image (Memory_Ref));
NT.Info (Report, "Memory after:"
& Natural'Image (Allocated_Size (CS)));
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Procedure Free_Extra_Memory (empty)";
CS : Chunked_String;
Memory_Ref : Natural;
Repeats : constant Positive := 50;
begin
Preallocate (CS, Repeats * Name'Length);
Memory_Ref := Allocated_Size (CS);
Free_Extra_Memory (CS);
if Memory_Ref <= Allocated_Size (CS) then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Memory before:"
& Natural'Image (Memory_Ref));
NT.Info (Report, "Memory after:"
& Natural'Image (Allocated_Size (CS)));
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
Natools.Tests.End_Section (Report);
end Natools.Chunked_Strings.Tests.Memory;
|
zhmu/ananas | Ada | 3,418 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . V A L _ B O O L --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2022, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Ghost code, loop invariants and assertions in this unit are meant for
-- analysis only, not for run-time checking, as it would be too costly
-- otherwise. This is enforced by setting the assertion policy to Ignore.
pragma Assertion_Policy (Ghost => Ignore,
Loop_Invariant => Ignore,
Assert => Ignore);
with System.Val_Util; use System.Val_Util;
package body System.Val_Bool
with SPARK_Mode
is
-------------------
-- Value_Boolean --
-------------------
function Value_Boolean (Str : String) return Boolean is
F : Integer;
L : Integer;
S : String (Str'Range) := Str;
begin
Normalize_String (S, F, L);
pragma Assert (F = System.Val_Util.First_Non_Space_Ghost
(S, Str'First, Str'Last));
if S (F .. L) = "TRUE" then
return True;
elsif S (F .. L) = "FALSE" then
return False;
else
Bad_Value (Str);
end if;
end Value_Boolean;
end System.Val_Bool;
|
burratoo/Acton | Ada | 2,049 | adb | ------------------------------------------------------------------------------------------
-- --
-- OAK PROCESSOR SUPPORT PACKAGE --
-- ATMEL AT91SAM7S --
-- --
-- OAK.PROCESSOR_SUPPORT_PACKAGE.TIME --
-- --
-- Copyright (C) 2014-2021, Patrick Bernardi --
-- --
------------------------------------------------------------------------------------------
with Atmel; use Atmel;
with Atmel.AT91SAM7S; use Atmel.AT91SAM7S;
with Atmel.AT91SAM7S.AIC; use Atmel.AT91SAM7S.AIC;
with Atmel.AT91SAM7S.PIT; use Atmel.AT91SAM7S.PIT;
package body Oak.Processor_Support_Package.Time is
procedure Initialise_Clock is
begin
Interrupt_Disable_Command_Register.Interrupt :=
(P_SYSC => Disable,
others => No_Change);
PIT.Mode_Register :=
(Periodic_Interval_Value =>
Periodic_Interval (Clock_Speed / 16 / Ticks_Per_Second),
Period_Interval_Timer => Enable,
Periodic_Interval_Timer_Interrupt => Enable);
-- Attach interrupts
Fast_Forcing_Enable_Register.Interrupt :=
(P_SYSC => Enable, others => No_Change);
Interrupt_Enable_Command_Register.Interrupt :=
(P_FIQ => Enable,
P_SYSC => Enable,
others => No_Change);
end Initialise_Clock;
procedure Update_Alarm (To : in Oak.Core_Support_Package.Time.Oak_Time) is
begin
Alarm_Time := To;
Alarm_Armed := True;
end Update_Alarm;
end Oak.Processor_Support_Package.Time;
|
reznikmm/gela | Ada | 1,698 | ads | ------------------------------------------------------------------------------
-- G E L A G R A M M A R S --
-- Library for dealing with tests for for Gela project, --
-- a portable Ada compiler --
-- http://gela.ada-ru.org/ --
-- - - - - - - - - - - - - - - - --
-- Read copyright and license in gela.ads file --
------------------------------------------------------------------------------
with League.Strings;
private with Ada.Containers.Doubly_Linked_Lists;
package Gela.Test_Iterators.ACATS is
type Iterator is new Test_Iterators.Iterator with private;
function Create
(Command : League.Strings.Universal_String;
List_File : League.Strings.Universal_String;
ACATS : League.Strings.Universal_String;
Fixture : League.Strings.Universal_String)
return Iterator;
-- Create iterator for enumerating tests containing in Source directory.
-- Build point to directory where tests will be build.
procedure Start (Self : in out Iterator);
function Has_More_Tests (Self : Iterator) return Boolean;
procedure Next
(Self : in out Iterator;
Test : out Gela.Test_Cases.Test_Case_Access);
private
package Lists is new Ada.Containers.Doubly_Linked_Lists
(Gela.Test_Cases.Test_Case_Access,
Gela.Test_Cases."=");
type Iterator is new Gela.Test_Iterators.Iterator with record
List : Lists.List;
Next : Lists.Cursor;
end record;
end Gela.Test_Iterators.ACATS;
|
skill-lang/adaCommon | Ada | 2,497 | ads | -- ___ _ ___ _ _ --
-- / __| |/ (_) | | Common SKilL implementation --
-- \__ \ ' <| | | |__ implementation of builtin field types --
-- |___/_|\_\_|_|____| by: Timm Felden --
-- --
pragma Ada_2012;
with Ada.Containers.Hashed_Maps;
with Ada.Tags;
with Skill.Types;
with Skill.Hashes; use Skill.Hashes;
with Skill.Equals; use Skill.Equals;
with Skill.String_Pools;
with Skill.Streams.Reader;
with Skill.Streams.Writer;
with Ada.Unchecked_Deallocation;
package Skill.Field_Types.Builtin.String_Type_P is
pragma Warnings (Off);
package A1 is new Field_Types (Types.String_Access, 14);
package IDs is new Ada.Containers.Hashed_Maps
(Key_Type => Types.String_Access,
Element_Type => Types.Skill_ID_T,
Hash => Hash,
Equivalent_Keys => Skill.Equals.Equals,
"=" => "=");
-- we need to pass a pointer to the map around
type ID_Map is not null access all IDs.Map;
type Field_Type_T is new A1.Field_Type with record
Strings : Skill.String_Pools.Pool;
String_IDs : aliased IDs.Map;
end record;
type Field_Type is access all Field_Type_T;
function Make
(Strings : String_Pools.Pool) return String_Type_P.Field_Type is
(new Field_Type_T'(Strings, String_Type_P.Ids.Empty_Map));
function Boxed is new Ada.Unchecked_Conversion(Types.String_Access, Types.Box);
function Unboxed is new Ada.Unchecked_Conversion(Types.Box, Types.String_Access);
function Read_Box
(This : access Field_Type_T;
Input : Streams.Reader.Stream) return Types.Box is
(Boxed (This.Strings.Get (Input.V64)));
function Offset_Box
(This : access Field_Type_T;
Target : Types.Box) return Types.V64 is
(Offset_Single_V64(Types.V64(This.String_Ids.Element(Unboxed(Target)))));
procedure Write_Box
(This : access Field_Type_T;
Output : Streams.Writer.Sub_Stream; Target : Types.Box);
procedure Write_Single_Field
(THis : access Field_Type_T;
V : Types.String_Access;
Output : Skill.Streams.Writer.Sub_Stream);
function Get_Id_Map (THis : access Field_Type_T) return ID_Map;
overriding function To_String (This : Field_Type_T) return String is
("string");
end Skill.Field_Types.Builtin.String_Type_P;
|
KipodAfterFree/KAF-2019-FireHog | Ada | 14,085 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT ncurses Binding Samples --
-- --
-- Sample.Explanation --
-- --
-- B O D Y --
-- --
------------------------------------------------------------------------------
-- Copyright (c) 1998 Free Software Foundation, Inc. --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files (the --
-- "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, distribute with modifications, sublicense, and/or sell --
-- copies of the Software, and to permit persons to whom the Software is --
-- furnished to do so, subject to the following conditions: --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. --
-- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR --
-- THE USE OR OTHER DEALINGS IN THE SOFTWARE. --
-- --
-- Except as contained in this notice, the name(s) of the above copyright --
-- holders shall not be used in advertising or otherwise to promote the --
-- sale, use or other dealings in this Software without prior written --
-- authorization. --
------------------------------------------------------------------------------
-- Author: Juergen Pfeifer <[email protected]> 1996
-- Version Control
-- $Revision: 1.9 $
-- Binding Version 00.93
------------------------------------------------------------------------------
-- Poor mans help system. This scans a sequential file for key lines and
-- then reads the lines up to the next key. Those lines are presented in
-- a window as help or explanation.
--
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Unchecked_Deallocation;
with Terminal_Interface.Curses; use Terminal_Interface.Curses;
with Terminal_Interface.Curses.Panels; use Terminal_Interface.Curses.Panels;
with Sample.Keyboard_Handler; use Sample.Keyboard_Handler;
with Sample.Manifest; use Sample.Manifest;
with Sample.Function_Key_Setting; use Sample.Function_Key_Setting;
with Sample.Helpers; use Sample.Helpers;
package body Sample.Explanation is
Help_Keys : constant String := "HELPKEYS";
In_Help : constant String := "INHELP";
File_Name : String := "explain.msg";
F : File_Type;
type Help_Line;
type Help_Line_Access is access Help_Line;
pragma Controlled (Help_Line_Access);
type String_Access is access String;
pragma Controlled (String_Access);
type Help_Line is
record
Prev, Next : Help_Line_Access;
Line : String_Access;
end record;
procedure Explain (Key : in String;
Win : in Window);
procedure Release_String is
new Ada.Unchecked_Deallocation (String,
String_Access);
procedure Release_Help_Line is
new Ada.Unchecked_Deallocation (Help_Line,
Help_Line_Access);
function Search (Key : String) return Help_Line_Access;
procedure Release_Help (Root : in out Help_Line_Access);
procedure Explain (Key : in String)
is
begin
Explain (Key, Null_Window);
end Explain;
procedure Explain (Key : in String;
Win : in Window)
is
-- Retrieve the text associated with this key and display it in this
-- window. If no window argument is passed, the routine will create
-- a temporary window and use it.
function Filter_Key return Real_Key_Code;
procedure Unknown_Key;
procedure Redo;
procedure To_Window (C : in out Help_Line_Access;
More : in out Boolean);
Frame : Window := Null_Window;
W : Window := Win;
K : Real_Key_Code;
P : Panel;
Height : Line_Count;
Width : Column_Count;
Help : Help_Line_Access := Search (Key);
Current : Help_Line_Access;
Top_Line : Help_Line_Access;
Has_More : Boolean;
procedure Unknown_Key
is
begin
Add (W, "Help message with ID ");
Add (W, Key);
Add (W, " not found.");
Add (W, Character'Val (10));
Add (W, "Press the Function key labelled 'Quit' key to continue.");
end Unknown_Key;
procedure Redo
is
H : Help_Line_Access := Top_Line;
begin
if Top_Line /= null then
for L in 0 .. (Height - 1) loop
Add (W, L, 0, H.Line.all);
exit when H.Next = null;
H := H.Next;
end loop;
else
Unknown_Key;
end if;
end Redo;
function Filter_Key return Real_Key_Code
is
K : Real_Key_Code;
begin
loop
K := Get_Key (W);
if K in Special_Key_Code'Range then
case K is
when HELP_CODE =>
if not Find_Context (In_Help) then
Push_Environment (In_Help, False);
Explain (In_Help, W);
Pop_Environment;
Redo;
end if;
when EXPLAIN_CODE =>
if not Find_Context (Help_Keys) then
Push_Environment (Help_Keys, False);
Explain (Help_Keys, W);
Pop_Environment;
Redo;
end if;
when others => exit;
end case;
else
exit;
end if;
end loop;
return K;
end Filter_Key;
procedure To_Window (C : in out Help_Line_Access;
More : in out Boolean)
is
L : Line_Position := 0;
begin
loop
Add (W, L, 0, C.Line.all);
L := L + 1;
exit when C.Next = null or else L = Height;
C := C.Next;
end loop;
if C.Next /= null then
pragma Assert (L = Height);
More := True;
else
More := False;
end if;
end To_Window;
begin
if W = Null_Window then
Push_Environment ("HELP");
Default_Labels;
Frame := New_Window (Lines - 2, Columns, 0, 0);
if Has_Colors then
Set_Background (Win => Frame,
Ch => (Ch => ' ',
Color => Help_Color,
Attr => Normal_Video));
Set_Character_Attributes (Win => Frame,
Attr => Normal_Video,
Color => Help_Color);
Erase (Frame);
end if;
Box (Frame);
Set_Character_Attributes (Frame, (Reverse_Video => True,
others => False));
Add (Frame, Lines - 3, 2, "Cursor Up/Down scrolls");
Set_Character_Attributes (Frame); -- Back to default.
Window_Title (Frame, "Explanation");
W := Derived_Window (Frame, Lines - 4, Columns - 2, 1, 1);
Refresh_Without_Update (Frame);
Get_Size (W, Height, Width);
Set_Meta_Mode (W);
Set_KeyPad_Mode (W);
Allow_Scrolling (W, True);
Set_Echo_Mode (False);
P := Create (Frame);
Top (P);
Update_Panels;
else
Clear (W);
Refresh_Without_Update (W);
end if;
Current := Help; Top_Line := Help;
if null = Help then
Unknown_Key;
loop
K := Filter_Key;
exit when K = QUIT_CODE;
end loop;
else
To_Window (Current, Has_More);
if Has_More then
-- This means there are more lines available, so we have to go
-- into a scroll manager.
loop
K := Filter_Key;
if K in Special_Key_Code'Range then
case K is
when Key_Cursor_Down =>
if Current.Next /= null then
Move_Cursor (W, Height - 1, 0);
Scroll (W, 1);
Current := Current.Next;
Top_Line := Top_Line.Next;
Add (W, Current.Line.all);
end if;
when Key_Cursor_Up =>
if Top_Line.Prev /= null then
Move_Cursor (W, 0, 0);
Scroll (W, -1);
Top_Line := Top_Line.Prev;
Current := Current.Prev;
Add (W, Top_Line.Line.all);
end if;
when QUIT_CODE => exit;
when others => null;
end case;
end if;
end loop;
else
loop
K := Filter_Key;
exit when K = QUIT_CODE;
end loop;
end if;
end if;
Clear (W);
if Frame /= Null_Window then
Clear (Frame);
Delete (P);
Delete (W);
Delete (Frame);
Pop_Environment;
end if;
Update_Panels;
Update_Screen;
Release_Help (Help);
end Explain;
function Search (Key : String) return Help_Line_Access
is
Last : Natural;
Buffer : String (1 .. 256);
Root : Help_Line_Access := null;
Current : Help_Line_Access;
Tail : Help_Line_Access := null;
Save : String_Access;
function Next_Line return Boolean;
function Next_Line return Boolean
is
H_End : constant String := "#END";
begin
Get_Line (F, Buffer, Last);
if Last = H_End'Length and then H_End = Buffer (1 .. Last) then
return False;
else
return True;
end if;
end Next_Line;
begin
Reset (F);
Outer :
loop
exit when not Next_Line;
if Last = (1 + Key'Length) and then Key = Buffer (2 .. Last)
and then Buffer (1) = '#' then
loop
exit when not Next_Line;
exit when Buffer (1) = '#';
Current := new Help_Line'(null, null,
new String'(Buffer (1 .. Last)));
if Tail = null then
Release_Help (Root);
Root := Current;
else
Tail.Next := Current;
Current.Prev := Tail;
end if;
Tail := Current;
end loop;
exit Outer;
end if;
end loop Outer;
return Root;
end Search;
procedure Release_Help (Root : in out Help_Line_Access)
is
Next : Help_Line_Access;
begin
loop
exit when Root = null;
Next := Root.Next;
Release_String (Root.Line);
Release_Help_Line (Root);
Root := Next;
end loop;
end Release_Help;
procedure Explain_Context
is
begin
Explain (Context);
end Explain_Context;
procedure Notepad (Key : in String)
is
H : constant Help_Line_Access := Search (Key);
T : Help_Line_Access := H;
N : Line_Count := 1;
L : Line_Position := 0;
W : Window;
P : Panel;
begin
if H /= null then
loop
T := T.Next;
exit when T = null;
N := N + 1;
end loop;
W := New_Window (N + 2, Columns, Lines - N - 2, 0);
if Has_Colors then
Set_Background (Win => W,
Ch => (Ch => ' ',
Color => Notepad_Color,
Attr => Normal_Video));
Set_Character_Attributes (Win => W,
Attr => Normal_Video,
Color => Notepad_Color);
Erase (W);
end if;
Box (W);
Window_Title (W, "Notepad");
P := New_Panel (W);
T := H;
loop
Add (W, L + 1, 1, T.Line.all, Integer (Columns - 2));
L := L + 1;
T := T.Next;
exit when T = null;
end loop;
T := H;
Release_Help (T);
Refresh_Without_Update (W);
Notepad_To_Context (P);
end if;
end Notepad;
begin
Open (F, In_File, File_Name);
end Sample.Explanation;
|
persan/protobuf-ada | Ada | 2,129 | adb | pragma Ada_2012;
package body Google.Protobuf.Assertions is
-------------------
-- Generic_Equal --
-------------------
procedure Generic_Equal
(Expected : in Value_Type; Actual : in Value_Type;
Source_Info : in String := GNAT.Source_Info.File;
File_Info : in Natural := GNAT.Source_Info.Line)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True,
"Generic_Equal unimplemented");
raise Program_Error with "Unimplemented procedure Generic_Equal";
end Generic_Equal;
------------------
-- Assert_Equal --
------------------
procedure Assert_Equal
(Expected : in Google.Protobuf.Wire_Format.PB_String;
Actual : in Google.Protobuf.Wire_Format.PB_String;
Source_Info : in String := GNAT.Source_Info.File;
File_Info : in Natural := GNAT.Source_Info.Line)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True,
"Assert_Equal unimplemented");
raise Program_Error with "Unimplemented procedure Assert_Equal";
end Assert_Equal;
-----------------
-- Assert_True --
-----------------
procedure Assert_True
(Actual : in Boolean; Source_Info : in String := GNAT.Source_Info.File;
File_Info : in Natural := GNAT.Source_Info.Line)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Assert_True unimplemented");
raise Program_Error with "Unimplemented procedure Assert_True";
end Assert_True;
------------------
-- Assert_False --
------------------
procedure Assert_False
(Actual : in Boolean; Source_Info : in String := GNAT.Source_Info.File;
File_Info : in Natural := GNAT.Source_Info.Line)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True,
"Assert_False unimplemented");
raise Program_Error with "Unimplemented procedure Assert_False";
end Assert_False;
end Google.Protobuf.Assertions;
|
zhmu/ananas | Ada | 6,164 | ads | ------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- SYSTEM.INTERRUPT_MANAGEMENT.OPERATIONS --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2022, Free Software Foundation, Inc. --
-- --
-- GNARL is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNARL was developed by the GNARL team at Florida State University. --
-- Extensive contributions were provided by Ada Core Technologies, Inc. --
-- --
------------------------------------------------------------------------------
package System.Interrupt_Management.Operations is
procedure Thread_Block_Interrupt (Interrupt : Interrupt_ID);
pragma Inline (Thread_Block_Interrupt);
-- Mask the calling thread for the interrupt
procedure Thread_Unblock_Interrupt (Interrupt : Interrupt_ID);
pragma Inline (Thread_Unblock_Interrupt);
-- Unmask the calling thread for the interrupt
procedure Set_Interrupt_Mask (Mask : access Interrupt_Mask);
-- Set the interrupt mask of the calling thread
procedure Set_Interrupt_Mask
(Mask : access Interrupt_Mask;
OMask : access Interrupt_Mask);
pragma Inline (Set_Interrupt_Mask);
-- Set the interrupt mask of the calling thread while returning the
-- previous Mask.
procedure Get_Interrupt_Mask (Mask : access Interrupt_Mask);
pragma Inline (Get_Interrupt_Mask);
-- Get the interrupt mask of the calling thread
function Interrupt_Wait (Mask : access Interrupt_Mask) return Interrupt_ID;
pragma Inline (Interrupt_Wait);
-- Wait for the interrupts specified in Mask and return
-- the interrupt received. Return 0 upon error.
procedure Install_Default_Action (Interrupt : Interrupt_ID);
pragma Inline (Install_Default_Action);
-- Set the sigaction of the Interrupt to default (SIG_DFL)
procedure Install_Ignore_Action (Interrupt : Interrupt_ID);
pragma Inline (Install_Ignore_Action);
-- Set the sigaction of the Interrupt to ignore (SIG_IGN)
procedure Fill_Interrupt_Mask (Mask : access Interrupt_Mask);
pragma Inline (Fill_Interrupt_Mask);
-- Get a Interrupt_Mask with all the interrupt masked
procedure Empty_Interrupt_Mask (Mask : access Interrupt_Mask);
pragma Inline (Empty_Interrupt_Mask);
-- Get a Interrupt_Mask with all the interrupt unmasked
procedure Add_To_Interrupt_Mask
(Mask : access Interrupt_Mask;
Interrupt : Interrupt_ID);
pragma Inline (Add_To_Interrupt_Mask);
-- Mask the given interrupt in the Interrupt_Mask
procedure Delete_From_Interrupt_Mask
(Mask : access Interrupt_Mask;
Interrupt : Interrupt_ID);
pragma Inline (Delete_From_Interrupt_Mask);
-- Unmask the given interrupt in the Interrupt_Mask
function Is_Member
(Mask : access Interrupt_Mask;
Interrupt : Interrupt_ID) return Boolean;
pragma Inline (Is_Member);
-- See if a given interrupt is masked in the Interrupt_Mask
procedure Copy_Interrupt_Mask (X : out Interrupt_Mask; Y : Interrupt_Mask);
pragma Inline (Copy_Interrupt_Mask);
-- Assignment needed for limited private type Interrupt_Mask
procedure Interrupt_Self_Process (Interrupt : Interrupt_ID);
pragma Inline (Interrupt_Self_Process);
-- Raise an Interrupt process-level
procedure Setup_Interrupt_Mask;
-- Mask Environment task for all signals
-- This function should be called by the elaboration of System.Interrupt
-- to set up proper signal masking in all tasks.
-- The following objects serve as constants, but are initialized in the
-- body to aid portability. These should be in System.Interrupt_Management
-- but since Interrupt_Mask is private type we cannot have them declared
-- there.
-- Why not make these deferred constants that are initialized using
-- function calls in the private part???
Environment_Mask : aliased Interrupt_Mask;
-- This mask represents the mask of Environment task when this package is
-- being elaborated, except the signals being forced to be unmasked by RTS
-- (items in Keep_Unmasked)
All_Tasks_Mask : aliased Interrupt_Mask;
-- This is the mask of all tasks created in RTS. Only one task in RTS
-- is responsible for masking/unmasking signals (see s-interr.adb).
end System.Interrupt_Management.Operations;
|
onox/orka | Ada | 1,906 | ads | -- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Containers.Indefinite_Holders;
with GL.Objects.Shaders;
with Orka.Resources.Locations;
package Orka.Rendering.Programs.Modules is
pragma Preelaborate;
type Module is tagged private;
type Module_Array is array (Positive range <>) of aliased Module;
function Create_Module_From_Sources (VS, TCS, TES, GS, FS, CS : String := "")
return Module;
-- Create a module containing shaders that have a non-empty source text
function Create_Module
(Location : Resources.Locations.Location_Ptr;
VS, TCS, TES, GS, FS, CS : String := "") return Module;
-- Create a module containing shaders that have a non-empty file path
procedure Attach_Shaders (Modules : Module_Array; Program : in out Programs.Program);
procedure Detach_Shaders (Modules : Module_Array; Program : Programs.Program);
Shader_Compile_Error : exception;
private
use type GL.Objects.Shaders.Shader;
package Shader_Holder is new Ada.Containers.Indefinite_Holders
(Element_Type => GL.Objects.Shaders.Shader);
type Shader_Array is array (GL.Objects.Shaders.Shader_Type) of Shader_Holder.Holder;
type Module is tagged record
Shaders : Shader_Array;
end record;
end Orka.Rendering.Programs.Modules;
|
cborao/Ada-P3 | Ada | 1,377 | ads |
--PRÁCTICA 3: CÉSAR BORAO MORATINOS (Chat_Procedures.ads)
with Maps_G;
with Ada.Text_IO;
with Ada.Calendar;
with Lower_Layer_UDP;
with Ada.Command_Line;
with Ada.Strings.Unbounded;
package Chat_Procedures is
package ATI renames Ada.Text_IO;
package LLU renames Lower_Layer_UDP;
package ACL renames Ada.Command_Line;
package ASU renames Ada.Strings.Unbounded;
use type ASU.Unbounded_String;
type Data is record
Client_EP: LLU.End_Point_Type;
Time: Ada.Calendar.Time;
end record;
function Max_Valid (Max_Clients: Natural) return Boolean;
package Active_Clients is new Maps_G (Key_Type => ASU.Unbounded_String,
Value_Type => Data,
Max_Clients => Natural'Value(ACL.Argument(2)),
"=" => ASU."=");
package Old_Clients is new Maps_G (Key_Type => ASU.Unbounded_String,
Value_Type => Ada.Calendar.Time,
Max_Clients => 150,
"=" => ASU."=");
Active_Map: Active_Clients.Map;
Old_Map: Old_Clients.Map;
procedure Print_Active_Map;
procedure Print_Old_Map;
procedure Case_Init (I_Buffer: access LLU.Buffer_Type;
O_Buffer: access LLU.Buffer_Type);
procedure Case_Writer (I_Buffer: access LLU.Buffer_Type;
O_Buffer: access LLU.Buffer_Type);
procedure Case_Logout (I_Buffer: access LLU.Buffer_Type;
O_Buffer: access LLU.Buffer_Type);
end Chat_Procedures;
|
persan/AUnit-addons | Ada | 421 | adb | -- begin read only
separate (Tc)
overriding procedure Register_Tests (Test : in out Test_Case) is
use AUnit.Test_Cases.Registration;
begin
Register_Routine (Test, Test_Routine'Unrestricted_Access, "Test_Routine");
Register_Routine (Test, Test_Routine33'Unrestricted_Access, "Test_Routine33");
Register_Routine (Test, Test_Routine4'Unrestricted_Access, "Test_Routine4");
end Register_Tests;
-- end read only
|
tum-ei-rcs/StratoX | Ada | 71 | adb | with calc;
procedure main with SPARK_Mode is
begin
null;
end main;
|
optikos/oasis | Ada | 1,632 | ads | -- Copyright (c) 2019 Maxim Reznik <[email protected]>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Program.Scanner_States;
package Program.Source_Buffers is
pragma Pure;
type Source_Buffer is limited interface;
-- Source_Buffer provides an access to source text.
type Source_Buffer_Access is access all Source_Buffer'Class
with Storage_Size => 0;
type Span is record
From : Positive;
To : Natural;
end record;
not overriding function Text
(Self : Source_Buffer;
Span : Program.Source_Buffers.Span) return Program.Text is abstract;
-- Return text slice of Span, where Span is positions
-- in the source measured in encoded text element (such as bytes for UTF-8)
subtype Character_Length is Natural range 0 .. 6;
-- Length of one character in encoded text elements
type Character_Info is record
Length : Character_Length;
Class : Program.Scanner_States.Character_Class;
-- Class of character for scanner.
end record;
type Character_Info_Array is array (Positive range <>) of
Character_Info;
not overriding procedure Read
(Self : in out Source_Buffer;
Data : out Character_Info_Array;
Last : out Natural) is abstract;
-- Read next part of source starting from current position and decode
-- corresponding character classes and character lengths.
not overriding procedure Rewind (Self : in out Source_Buffer) is abstract;
-- Set reading position to begin of the buffer
end Program.Source_Buffers;
|
sparre/JSA | Ada | 1,184 | adb | with
Ada.Integer_Text_IO,
Ada.Text_IO;
with
JSA.Intermediate_Backups;
package body JSA.Tests.Intermediate_Backups is
overriding
procedure Initialize (T : in out Test) is
use Ahven.Framework;
begin
T.Set_Name ("Intermediate backups");
Add_Test_Routine (T, Run'Access, "Run");
end Initialize;
procedure Run is
Counter : Natural := 0;
procedure Save_Counter;
procedure Save_Counter is
begin
Ada.Text_IO.Put ("Backup of counter: ");
Ada.Integer_Text_IO.Put (Counter);
Ada.Text_IO.New_Line;
end Save_Counter;
package Backups is
new JSA.Intermediate_Backups (Fraction => 0.01,
Save_State => Save_Counter);
begin
Backups.Begin_Loop;
for I in 1 .. 1_000 loop
Counter := Counter + 1;
for J in 1 .. 100_000 loop
if J mod 2 = 0 then
Counter := Counter + 1;
else
Counter := Counter - 1;
end if;
end loop;
Backups.End_Of_Iteration;
end loop;
Backups.End_Loop;
end Run;
end JSA.Tests.Intermediate_Backups;
|
onox/orka | Ada | 6,101 | ads | -- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Interfaces.C.Strings;
with System;
with EGL.Errors;
with EGL.Loading;
with EGL.Objects.Contexts;
with EGL.Objects.Displays;
private package EGL.API is
pragma Preelaborate;
pragma Linker_Options ("-lEGL");
function Get_Proc_Address (Name : C.char_array) return System.Address
with Import, Convention => C, External_Name => "eglGetProcAddress";
function Get_Error return Errors.Error_Code
with Import, Convention => C, External_Name => "eglGetError";
package Debug_Message_Control is new Loading.Function_With_2_Params
("eglDebugMessageControlKHR", System.Address, Attribute_Array, Errors.Error_Code);
-----------------------------------------------------------------------------
-- Displays --
-----------------------------------------------------------------------------
package Get_Platform_Display is new Loading.Function_With_3_Params
("eglGetPlatformDisplayEXT", Objects.Displays.Platform_Kind, Void_Ptr, Int_Array, ID_Type);
function Initialize_Display
(Display : ID_Type;
Major, Minor : out Int) return Bool
with Import, Convention => C, External_Name => "eglInitialize";
function Terminate_Display (Display : ID_Type) return Bool
with Import, Convention => C, External_Name => "eglTerminate";
function Query_String
(No_Display : ID_Type;
Name : Display_Query_Param) return C.Strings.chars_ptr
with Import, Convention => C, External_Name => "eglQueryString";
-- Return a zero-terminated string with the properties of the EGL
-- client or the EGL display, or null if an error occurred
-----------------------------------------------------------------------------
-- Contexts --
-----------------------------------------------------------------------------
function Bind_API (API : Objects.Contexts.Client_API) return Bool
with Import, Convention => C, External_Name => "eglBindAPI";
function Create_Context
(Display : ID_Type;
Config : ID_Type;
Share : ID_Type;
Attributes : Int_Array) return ID_Type
with Import, Convention => C, External_Name => "eglCreateContext";
function Destroy_Context
(Display : ID_Type;
Context : ID_Type) return Bool
with Import, Convention => C, External_Name => "eglDestroyContext";
function Make_Current
(Display : ID_Type;
Draw : ID_Type;
Read : ID_Type;
Context : ID_Type) return Bool
with Import, Convention => C, External_Name => "eglMakeCurrent";
-----------------------------------------------------------------------------
-- Surfaces --
-----------------------------------------------------------------------------
-- eglSurfaceAttrib
function Query_Surface
(Display : ID_Type;
Surface : ID_Type;
Attribute : Surface_Query_Param;
Value : out Int) return Bool
with Import, Convention => C, External_Name => "eglQuerySurface";
function Query_Context
(Display : ID_Type;
Context : ID_Type;
Attribute : Context_Query_Param;
Value : out Objects.Contexts.Buffer_Kind) return Bool
with Import, Convention => C, External_Name => "eglQueryContext";
function Get_Current_Context return ID_Type
with Import, Convention => C, External_Name => "eglGetCurrentContext";
function Get_Config_Attrib
(Display : ID_Type;
Config : ID_Type;
Attribute : Int;
Value : out Int) return Bool
with Import, Convention => C, External_Name => "eglGetConfigAttrib";
function Choose_Config
(Display : ID_Type;
Attributes : Int_Array;
Configs : out ID_Array;
Max_Configs : Int;
Length : out Int) return Bool
with Import, Convention => C, External_Name => "eglChooseConfig";
package Create_Platform_Window_Surface is new Loading.Function_With_4_Params
("eglCreatePlatformWindowSurfaceEXT",
ID_Type, ID_Type, Native_Window_Ptr, Int_Array, ID_Type);
function Destroy_Surface
(Display : ID_Type;
Surface : ID_Type) return Bool
with Import, Convention => C, External_Name => "eglDestroySurface";
function Swap_Buffers
(Display : ID_Type;
Surface : ID_Type) return Bool
with Import, Convention => C, External_Name => "eglSwapBuffers";
function Swap_Interval
(Display : ID_Type;
Interval : Int) return Bool
with Import, Convention => C, External_Name => "eglSwapInterval";
-----------------------------------------------------------------------------
-- Devices --
-----------------------------------------------------------------------------
package Query_Device_String is new Loading.Function_With_2_Params
("eglQueryDeviceStringEXT", ID_Type, Device_Query_Param, C.Strings.chars_ptr);
-- Return the DRM name of a device or a list of device extensions
package Query_Display_Attrib is new Loading.Getter_With_3_Params
("eglQueryDisplayAttribEXT", ID_Type, Int, ID_Type, Bool);
-- Return the device of a display
package Query_Devices is new Loading.Array_Getter_With_3_Params
("eglQueryDevicesEXT", Int, ID_Type, ID_Array, Int, Bool);
end EGL.API;
|
zenharris/ada-bbs | Ada | 5,334 | adb | with Message.Reader; use Message.Reader;
package body Message.Post is
procedure Quote (Msgid : Unbounded_String) is
FileName, scratch : Unbounded_String;
File : File_Type;
Sender, HeaderType,HeaderText : Unbounded_String;
begin
FileName := "messages/"& Msgid &".msg";
Text_Buffer.Clear;
Open (File => File,
Mode => In_File,
Name => To_String(Filename));
scratch := SUIO.Get_Line(File);
while scratch /= "" loop
HeaderType := To_Unbounded_String(SU.Slice(scratch,1,SU.Index(scratch,":")-1));
HeaderText := To_Unbounded_String(SU.Slice(scratch,SU.Index(scratch,":")+2,SU.Length(scratch)));
if HeaderType = "Sender" then
Sender := HeaderText;
end if;
scratch := SUIO.Get_Line(File);
end loop;
Text_Buffer.Append("In reply to "& Sender);
scratch := SUIO.Get_Line(File);
loop
Text_Buffer.Append(" > "& scratch);
scratch := SUIO.Get_Line(File);
end loop;
exception
when End_Error =>
Close (File);
when Name_Error => null;
end Quote;
function Pad (InStr : String;PadWdth : Integer) return String is
padstr,tmpstr : Unbounded_String;
begin
tmpstr := To_Unbounded_String(SF.Trim(Instr,Ada.Strings.Left));
if SU.Length(tmpstr) < PadWdth then
for i in SU.Length(tmpstr) .. PadWdth-1 loop
padstr := padstr & '0';
end loop;
return To_String(padstr) & To_String(tmpstr);
else
return To_String(tmpstr);
end if;
end Pad;
function Generate_UID return Unbounded_String is
Now : Time := Clock;
Now_Year : Year_Number;
Now_Month : Month_Number;
Now_Day : Day_Number;
Now_Seconds : Day_Duration;
begin
Split (Now,
Now_Year,
Now_Month,
Now_Day,
Now_Seconds);
return To_Unbounded_String(SF.Trim(Year_Number'Image (Now_Year),Ada.Strings.Left) &
Pad(Month_Number'Image (Now_Month),2) &
Pad(Day_Number'Image (Now_Day),2) &
Pad(Duration'Image (Now_Seconds),16));
end Generate_UID;
procedure Post_Message (ReplyID : in Unbounded_String := To_Unbounded_String("");
ReplySubject : in Unbounded_String := To_Unbounded_String("")) is
-- FileName : Unbounded_String := To_Unbounded_String("messages/test.txt");
File : File_Type;
Nick, Subject, Msgid, FName : Unbounded_String;
PostDate : Time := Clock;
Cancelled : Boolean := False;
procedure Write_Line (Position : String_List.Cursor) is
begin
SUIO.Put_Line(File,String_List.Element(Position));
end Write_Line;
begin
if UserLoggedIn then
Clear;
Get_Size(Standard_Window,Number_Of_Lines => TermLnth,Number_Of_Columns => TermWdth);
TopLine := 4;
BottomLine := TermLnth - 4;
Nick := UserLoggedName;
Add (Line => 1,Column => 0,Str => "Nick : " & To_String(Nick));
if (SU.Length(ReplySubject) > 0) then
if SU.Index(ReplySubject,"Re.") = 1 then
Subject := ReplySubject;
else
Subject := "Re. " & ReplySubject;
end if;
end if;
Add (Line => 2,Column => 0,Str => "Subject : ");
loop
Texaco.Line_Editor(Standard_Window,
StartLine => 2,
StartColumn => 11,
Editlength => 60,
Edline => Subject,
MaxLength => 60);
exit when Subject /= "";
end loop;
Add (Line => 3,Column => 0, Str => "Enter your Message text. Esc to exit");
Refresh;
Texaco.Text_Editor(Standard_Window,TopLine => TopLine,BottomLine => BottomLine,MaxLines => 100);
if not Text_Buffer.Is_Empty then
if Texaco.Save then
Msgid := Generate_UID;
FName := "messages/" & Msgid & ".msg";
Create (File => File,
Mode => Out_File,
Name => To_String(FName));
SUIO.Put_Line(File,"Sender: " & Nick);
SUIO.Put_Line(File,"Subject: " & Subject);
SUIO.Put_Line(File,"PostDate: " & To_Unbounded_String(Image (PostDate)));
SUIO.Put_Line(File,"Msgid: " & Msgid);
if SU.Length(ReplyID) /= 0 then
SUIO.Put_Line(File,"ReplyTo: " & ReplyID);
end if;
SUIO.Put_Line(File,To_Unbounded_String(""));
Text_Buffer.Iterate(Write_Line'access);
Close (File);
Directory_Buffer.Append(New_Item => (To_Unbounded_String(Curr_Dir&"/"&To_String(FName)),
CharPad(Nick,15) & Subject) );
else
Display_Warning.Warning("Posting Cancelled");
end if;
end if;
else
Display_Warning.Warning("You Must be Logged In to Post");
end if;
end Post_Message;
end Message.Post;
|
AdaCore/libadalang | Ada | 187 | ads | package Test is
function Foo (A : Integer; B : Integer; C : Integer) return Positive;
function Foo (A : Integer; B, C: Natural) return Natural;
type A is (B, C, D);
end Test;
|
reznikmm/matreshka | Ada | 4,734 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
with AMF.Generic_Collections;
package AMF.DG.Lines.Collections is
pragma Preelaborate;
package DG_Line_Collections is
new AMF.Generic_Collections
(DG_Line,
DG_Line_Access);
type Set_Of_DG_Line is
new DG_Line_Collections.Set with null record;
Empty_Set_Of_DG_Line : constant Set_Of_DG_Line;
type Ordered_Set_Of_DG_Line is
new DG_Line_Collections.Ordered_Set with null record;
Empty_Ordered_Set_Of_DG_Line : constant Ordered_Set_Of_DG_Line;
type Bag_Of_DG_Line is
new DG_Line_Collections.Bag with null record;
Empty_Bag_Of_DG_Line : constant Bag_Of_DG_Line;
type Sequence_Of_DG_Line is
new DG_Line_Collections.Sequence with null record;
Empty_Sequence_Of_DG_Line : constant Sequence_Of_DG_Line;
private
Empty_Set_Of_DG_Line : constant Set_Of_DG_Line
:= (DG_Line_Collections.Set with null record);
Empty_Ordered_Set_Of_DG_Line : constant Ordered_Set_Of_DG_Line
:= (DG_Line_Collections.Ordered_Set with null record);
Empty_Bag_Of_DG_Line : constant Bag_Of_DG_Line
:= (DG_Line_Collections.Bag with null record);
Empty_Sequence_Of_DG_Line : constant Sequence_Of_DG_Line
:= (DG_Line_Collections.Sequence with null record);
end AMF.DG.Lines.Collections;
|
reznikmm/increment | Ada | 2,384 | ads | -- Copyright (c) 2015-2017 Maxim Reznik <[email protected]>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with League.String_Vectors;
with Incr.Documents;
with Incr.Nodes;
with Incr.Parsers.Incremental;
package Tests.Parser_Data is
package P renames Incr.Parsers.Incremental.Parser_Data_Providers;
type Provider (Document : Incr.Documents.Document_Access)
is new P.Parser_Data_Provider and P.Node_Factory with private;
overriding function Actions
(Self : Provider) return P.Action_Table_Access;
overriding function States
(Self : Provider) return P.State_Table_Access;
overriding function Part_Counts
(Self : Provider) return P.Parts_Count_Table_Access;
overriding function Kind_Image
(Self : Provider;
Kind : Incr.Nodes.Node_Kind) return Wide_Wide_String;
overriding procedure Create_Node
(Self : aliased in out Provider;
Prod : Incr.Parsers.Incremental.
Parser_Data_Providers.Production_Index;
Children : Incr.Nodes.Node_Array;
Node : out Incr.Nodes.Node_Access;
Kind : out Incr.Nodes.Node_Kind);
type Node_Kind_Array is array (P.Production_Index range <>) of
Incr.Nodes.Node_Kind;
private
package Constructors is
function Create
(Document : Incr.Documents.Document_Access;
NT : Node_Kind_Array;
Parts : P.Parts_Count_Table;
Names : League.String_Vectors.Universal_String_Vector;
Max_State : P.Parser_State;
Max_Term : Incr.Nodes.Token_Kind) return Provider;
end Constructors;
type Node_Kind_Array_Access is access all Node_Kind_Array;
type Action_Table_Access is access P.Action_Table;
type State_Table_Access is access P.State_Table;
type Parts_Count_Table_Access is access P.Parts_Count_Table;
type Provider
(Document : Incr.Documents.Document_Access)
is new P.Parser_Data_Provider and P.Node_Factory with record
Max_Term : Incr.Nodes.Token_Kind;
Max_NT : Incr.Nodes.Node_Kind;
Names : League.String_Vectors.Universal_String_Vector;
Actions : Action_Table_Access;
States : State_Table_Access;
NT : Node_Kind_Array_Access;
Parts : Parts_Count_Table_Access;
end record;
end Tests.Parser_Data;
|
AaronC98/PlaneSystem | Ada | 4,184 | adb | ------------------------------------------------------------------------------
-- Ada Web Server --
-- --
-- Copyright (C) 2000-2015, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify --
-- it under terms of the GNU General Public License as published by the --
-- Free Software Foundation; either version 3, or (at your option) any --
-- later version. This library is distributed in the hope that it will be --
-- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
------------------------------------------------------------------------------
with AWS.Containers.Key_Value;
with SOAP.Types;
package body SOAP.Message.Payload is
-----------
-- Build --
-----------
function Build
(Procedure_Name : String;
P_Set : SOAP.Parameters.List;
Name_Space : SOAP.Name_Space.Object := SOAP.Name_Space.AWS)
return Object
is
use AWS;
use type SOAP.Name_Space.Object;
Gen : Containers.Key_Value.Map;
begin
return O : Object do
O.Name_Space := Name_Space;
O.Wrapper_Name := To_Unbounded_String (Procedure_Name);
O.P := P_Set;
-- Add all the user's name-spaces for the given parameters
for K in 1 .. SOAP.Parameters.Argument_Count (P_Set) loop
declare
N : constant SOAP.Name_Space.Object :=
SOAP.Types.Name_Space
(SOAP.Parameters.Argument (P_Set, K));
begin
if N /= SOAP.Name_Space.No_Name_Space
and then not Gen.Contains (SOAP.Name_Space.Value (N))
then
O.Index := O.Index + 1;
O.Users_NS (O.Index) :=
SOAP.Name_Space.Create (SOAP.Name_Space.Name (N),
SOAP.Name_Space.Value (N));
Gen.Insert
(SOAP.Name_Space.Value (N),
SOAP.Name_Space.Name (N));
end if;
end;
end loop;
end return;
end Build;
--------------------
-- Procedure_Name --
--------------------
function Procedure_Name (P : Object'Class) return String is
begin
return Wrapper_Name (P);
end Procedure_Name;
------------------------
-- Set_Procedure_Name --
------------------------
procedure Set_Procedure_Name (P : in out Object'Class; Name : String) is
begin
Set_Wrapper_Name (P, Name);
end Set_Procedure_Name;
end SOAP.Message.Payload;
|
stcarrez/dynamo | Ada | 5,281 | ads | ------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T V S N --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2015, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package spec holds version information for the GNAT tools.
-- It is updated whenever the release number is changed.
package Gnatvsn is
Gnat_Static_Version_String : constant String := "GNU Ada";
-- Static string identifying this version, that can be used as an argument
-- to e.g. pragma Ident.
function Gnat_Version_String return String;
-- Version output when GNAT (compiler), or its related tools, including
-- GNATBIND, GNATCHOP, GNATFIND, GNATLINK, GNATMAKE, GNATXREF, are run
-- (with appropriate verbose option switch set).
type Gnat_Build_Type is (FSF, GPL);
-- See Build_Type below for the meaning of these values.
Build_Type : constant Gnat_Build_Type := FSF;
-- Kind of GNAT build:
--
-- FSF
-- GNAT FSF version. This version of GNAT is part of a Free Software
-- Foundation release of the GNU Compiler Collection (GCC). The bug
-- box generated by Comperr gives information on how to report bugs
-- and list the "no warranty" information.
--
-- GPL
-- GNAT GPL Edition. This is a special version of GNAT, released by
-- Ada Core Technologies and intended for academic users, and free
-- software developers. The bug box generated by the package Comperr
-- gives appropriate bug submission instructions that do not reference
-- customer number etc.
function Gnat_Free_Software return String;
-- Text to be displayed by the different GNAT tools when switch --version
-- is used. This text depends on the GNAT build type.
function Copyright_Holder return String;
-- Return the name of the Copyright holder to be displayed by the different
-- GNAT tools when switch --version is used.
Ver_Len_Max : constant := 256;
-- Longest possible length for Gnat_Version_String in this or any
-- other version of GNAT. This is used by the binder to establish
-- space to store any possible version string value for checks. This
-- value should never be decreased in the future, but it would be
-- OK to increase it if absolutely necessary. If it is increased,
-- be sure to increase GNAT.Compiler.Version.Ver_Len_Max as well.
Ver_Prefix : constant String := "GNAT Version: ";
-- Prefix generated by binder. If it is changed, be sure to change
-- GNAT.Compiler_Version.Ver_Prefix as well.
Library_Version : constant String := "5";
-- Library version. This value must be updated when the compiler
-- version number Gnat_Static_Version_String is updated.
--
-- Note: Makefile.in uses the library version string to construct the
-- soname value.
Verbose_Library_Version : constant String := "GNAT Lib v" & Library_Version;
-- Version string stored in e.g. ALI files
Current_Year : constant String := "2015";
-- Used in printing copyright messages
end Gnatvsn;
|
AdaDoom3/wayland_ada_binding | Ada | 2,750 | adb | ------------------------------------------------------------------------------
-- Copyright (C) 2016-2016, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY 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/>. --
-- --
------------------------------------------------------------------------------
pragma Ada_2012;
package body Conts.Properties.Indexed is
use Value_Vectors;
-----------
-- Clear --
-----------
procedure Clear (M : in out Map) is
begin
M.Values.Clear;
end Clear;
---------
-- Get --
---------
function Get (M : Map; K : Key_Type) return Element_Type is
begin
return M.Values.Element (Get_Index (K));
end Get;
---------
-- Set --
---------
procedure Set (M : in out Map; K : Key_Type; Val : Element_Type) is
Idx : constant Index_Type := Get_Index (K);
begin
-- ??? We should have such an operation in the vector directly
if not (Value_Vectors.Vectors.To_Count (Idx) <= M.Values.Length) then
M.Values.Resize
(Length => Value_Vectors.Vectors.To_Count (Idx),
Element => Default_Value);
end if;
M.Values.Replace_Element (Idx, Val);
end Set;
----------------
-- Create_Map --
----------------
function Create_Map (G : Container_Type) return Map is
begin
return M : Map do
M.Values.Reserve_Capacity (Length (G));
end return;
end Create_Map;
end Conts.Properties.Indexed;
|
ekoeppen/MSP430_Generic_Ada_Drivers | Ada | 346 | ads | with MSPGD;
package MSPGD.GPIO is
pragma Preelaborate;
type Alt_Func_Type is (IO, Primary, Secondary, Device_Specific, Analog, Comparator);
type Direction_Type is (Input, Output);
type Resistor_Type is (None, Up, Down);
subtype Pin_Type is Integer range 0 .. 7;
subtype Port_Type is Unsigned_8 range 1 .. 8;
end MSPGD.GPIO;
|
reznikmm/matreshka | Ada | 4,027 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with ODF.DOM.Style_Script_Asian_Attributes;
package Matreshka.ODF_Style.Script_Asian_Attributes is
type Style_Script_Asian_Attribute_Node is
new Matreshka.ODF_Style.Abstract_Style_Attribute_Node
and ODF.DOM.Style_Script_Asian_Attributes.ODF_Style_Script_Asian_Attribute
with null record;
overriding function Create
(Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters)
return Style_Script_Asian_Attribute_Node;
overriding function Get_Local_Name
(Self : not null access constant Style_Script_Asian_Attribute_Node)
return League.Strings.Universal_String;
end Matreshka.ODF_Style.Script_Asian_Attributes;
|
xeenta/learning-ada | Ada | 606 | adb | with Greeter; use Greeter;
with Ada.Text_IO; use Ada.Text_IO;
procedure Hello is
package Int_IO is new Ada.Text_IO.Integer_IO (Integer);
X : Integer := 2;
procedure Do_It
with Global => (Input => X);
procedure Do_It is
begin
if X > 20 then
Greeter.Greet ("Hello");
end if;
end Do_It;
begin
-- Put_Line (Greeter.Hello_Text);
Greeter.X := 10;
for I in Integer range 0 .. 25
loop
X := X + I;
Do_It;
end loop;
Put_Line (Integer'Image (Greeter.X));
Put_Line (Integer'Image (X));
Int_IO.Put (X); New_Line;
end Hello;
|
damaki/dw1000-rssi-tester | Ada | 5,205 | adb | -------------------------------------------------------------------------------
-- Copyright (c) 2017 Daniel King
--
-- Permission is hereby granted, free of charge, to any person obtaining a
-- copy of this software and associated documentation files (the "Software"),
-- to deal in the Software without restriction, including without limitation
-- the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Software, and to permit persons to whom the
-- Software is furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
with Ada.Real_Time; use Ada.Real_Time;
with Configurations;
with DecaDriver.Core; use DecaDriver.Core;
with DecaDriver.Tx;
with DW1000.Driver; use DW1000.Driver;
with DW1000.Types; use DW1000.Types;
with EVB1000_Tx_Power;
with EVB1000.LCD;
procedure Transmitter
is
Inter_Frame_Period : constant
array (DW1000.Driver.Data_Rates)
of Ada.Real_Time.Time_Span :=
(Data_Rate_110k => Microseconds (15_625), -- 64 pkt/s
Data_Rate_850k => Microseconds (5_000), -- 200 pkt/s
Data_Rate_6M8 => Microseconds (4_000)); -- 250 pkt/s
Tx_Packet : DW1000.Types.Byte_Array (1 .. 125);
Current_Config : DecaDriver.Core.Configuration_Type;
New_Config : DecaDriver.Core.Configuration_Type;
Next_Tx_Time : Ada.Real_Time.Time;
procedure Update_LCD
is
Channel_Number_Str : constant array (Positive range 1 .. 7) of Character :=
(1 => '1',
2 => '2',
3 => '3',
4 => '4',
5 => '5',
6 => '6',
7 => '7');
PRF_Str : constant array (PRF_Type) of String (1 .. 5) :=
(PRF_16MHz => "16MHz",
PRF_64MHz => "64MHz");
Data_Rate_Str : constant array (Data_Rates) of String (1 .. 4) :=
(Data_Rate_110k => "110K",
Data_Rate_850k => "850K",
Data_Rate_6M8 => "6.8M");
begin
EVB1000.LCD.Driver.Put
(Text_1 => ("Ch" & Channel_Number_Str (Positive (Current_Config.Channel))
& ' ' & PRF_Str (Current_Config.PRF)
& ' ' & Data_Rate_Str (Current_Config.Data_Rate)),
Text_2 => "");
end Update_LCD;
procedure Build_Packet
is
begin
Tx_Packet (1) := Bits_8 (Data_Rates'Pos (Current_Config.Data_Rate));
Tx_Packet (2) := Bits_8 (PRF_Type'Pos (Current_Config.PRF));
Tx_Packet (3) := Bits_8 (Current_Config.Channel);
Tx_Packet (4 .. 5) := (others => 0);
for I in 1 .. (Tx_Packet'Length / 5) loop
Tx_Packet (I * 5 .. I * 5 + 4) := Tx_Packet (1 .. 5);
end loop;
end Build_Packet;
begin
Configurations.Get_Switches_Config (Current_Config);
DecaDriver.Core.Driver.Initialize
(Load_Antenna_Delay => False,
Load_XTAL_Trim => True,
Load_UCode_From_ROM => True);
DecaDriver.Core.Driver.Configure (Current_Config);
DecaDriver.Tx.Transmitter.Configure_Tx_Power
(EVB1000_Tx_Power.Manual_Tx_Power_Table
(Positive (Current_Config.Channel), Current_Config.PRF));
DecaDriver.Core.Driver.Configure_LEDs
(Tx_LED_Enable => True,
Rx_LED_Enable => False,
Rx_OK_LED_Enable => False,
SFD_LED_Enable => False,
Test_Flash => True);
Update_LCD;
Next_Tx_Time := Ada.Real_Time.Clock;
loop
-- Check if the configuration has changed.
Configurations.Get_Switches_Config (New_Config);
if New_Config /= Current_Config then
-- Configuration has changed. Use new configuration.
Current_Config := New_Config;
DecaDriver.Core.Driver.Configure (New_Config);
DecaDriver.Tx.Transmitter.Configure_Tx_Power
(EVB1000_Tx_Power.Manual_Tx_Power_Table
(Positive (Current_Config.Channel), Current_Config.PRF));
Build_Packet;
DecaDriver.Tx.Transmitter.Set_Tx_Data
(Data => Tx_Packet,
Offset => 0);
Update_LCD;
end if;
delay until Next_Tx_Time;
Next_Tx_Time := Next_Tx_Time + Inter_Frame_Period (Current_Config.Data_Rate);
DecaDriver.Tx.Transmitter.Set_Tx_Frame_Length
(Length => Tx_Packet'Length + 2, -- 2 extra bytes for FCS
Offset => 0);
DecaDriver.Tx.Transmitter.Start_Tx_Immediate (Rx_After_Tx => False,
Auto_Append_FCS => True);
DecaDriver.Tx.Transmitter.Wait_For_Tx_Complete;
end loop;
end Transmitter;
|
tum-ei-rcs/StratoX | Ada | 6,525 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . L I B M _ D O U B L E . S Q R T --
-- --
-- B o d y --
-- --
-- Copyright (C) 2014-2015, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This is the Ada Cert Math specific implementation of sqrt (powerpc)
with Ada.Unchecked_Conversion;
with System.Machine_Code;
package body System.Libm_Double.Squareroot is
function Rsqrt (X : Long_Float) return Long_Float;
-- Compute the reciprocal square root. There are two reasons for computing
-- the reciprocal square root instead of computing directly the square
-- root: PowerPc provides an instruction (fsqrte) to compute an estimate of
-- the reciprocal (with 5 bits of precision), and the Newton-Raphson method
-- is more efficient on the reciprocal than on the direct root (because the
-- direct root needs divisions, while the reciprocal does not). Note that
-- PowerPc core e300 doesn't support the direct square root operation.
-----------
-- Rsqrt --
-----------
function Rsqrt (X : Long_Float) return Long_Float is
X_Half : constant Long_Float := X * 0.5;
Y, Y1 : Long_Float;
begin
if Standard'Target_Name = "powerpc-elf" then
-- On powerpc, the precision of fsqrte is at least 5 binary digits
System.Machine_Code.Asm ("frsqrte %0,%1",
Outputs => Long_Float'Asm_Output ("=f", Y),
Inputs => Long_Float'Asm_Input ("f", X));
else
-- Provide the exact result for 1.0
if X = 1.0 then
return X;
end if;
-- Use the method described in Fast Inverse Square Root article by
-- Chris Lomont (http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf),
-- although the code was known before that article.
declare
type Unsigned_Long is mod 2**64;
function To_Unsigned_Long is new Ada.Unchecked_Conversion
(Long_Float, Unsigned_Long);
function From_Unsigned_Long is new Ada.Unchecked_Conversion
(Unsigned_Long, Long_Float);
U : Unsigned_Long;
begin
U := To_Unsigned_Long (X);
U := 16#5fe6ec85_e7de30da# - (U / 2);
Y := From_Unsigned_Long (U);
-- Precision is about 4 digits
end;
end if;
-- Newton iterations: X <- X - F(X)/F'(X)
-- Here F(X) = 1/X^2 - A, so F'(X) = -2/X^3
-- So: X <- X - (1/X^2 - A) / (-2/X^3)
-- <- X + .5(X - A*X^3)
-- <- X + .5*X*(1 - A*X^2)
-- <- X (1 + .5 - .5*A*X^2)
-- <- X(1.5 - .5*A*X^2)
-- Precision is doubled at each iteration.
-- Refine: 10 digits (PowerPc) or 8 digits (fast method)
Y := Y * (1.5 - X_Half * Y * Y);
-- Refine: 20 digits (PowerPc) or 16 digits (fast method)
Y := Y * (1.5 - X_Half * Y * Y);
-- Refine: 40 digits (PowerPc) or 32 digits (fast method)
Y := Y * (1.5 - X_Half * Y * Y);
-- Refine (beyond the precision of Long_Float)
Y1 := Y * (1.5 - X_Half * Y * Y);
if Y = Y1 then
return Y1;
else
Y := Y1;
end if;
-- Empirical tests show the above iterations are inadequate in some
-- cases and that two more iterations are needed to converge. Other
-- algorithms may need to be explored. ???
Y1 := Y * (1.5 - X_Half * Y * Y);
if Y = Y1 then
return Y1;
else
Y := Y1;
end if;
Y := Y * (1.5 - X_Half * Y * Y);
-- This algorithm doesn't always provide exact results. For example,
-- Sqrt (25.0) /= 5.0 exactly (it's wrong in the last bit).
return Y;
end Rsqrt;
----------
-- Sqrt --
----------
function Sqrt (X : Long_Float) return Long_Float is
begin
if X <= 0.0 then
if X = 0.0 then
return X;
else
return NaN;
end if;
elsif not Long_Float'Machine_Overflows and then X = Infinity then
-- Note that if Machine_Overflow is True Infinity won't return.
-- But in that case, we can assume that X is not infinity.
return X;
else
return X * Rsqrt (X);
end if;
end Sqrt;
end System.Libm_Double.Squareroot;
|
jrcarter/Ada_GUI | Ada | 24,712 | ads | -- --
-- package Copyright (c) Dmitry A. Kazakov --
-- GNAT.Sockets.Connection_State_Machine Luebeck --
-- Interface Winter, 2012 --
-- --
-- Last revision : 18:41 01 Aug 2019 --
-- --
-- This library is free software; you can redistribute it and/or --
-- modify it under the terms of the GNU General Public License as --
-- published by the Free Software Foundation; either version 2 of --
-- the License, or (at your option) any later version. This library --
-- is distributed in the hope that it will be useful, but WITHOUT --
-- ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU --
-- General Public License for more details. You should have --
-- received a copy of the GNU General Public License along with --
-- this library; if not, write to the Free Software Foundation, --
-- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --
-- --
-- As a special exception, if other files instantiate generics from --
-- this unit, or you link this unit with other files to produce an --
-- executable, this unit does not by itself cause the resulting --
-- executable to be covered by the GNU General Public License. This --
-- exception does not however invalidate any other reasons why the --
-- executable file might be covered by the GNU Public License. --
--____________________________________________________________________--
--
-- This package provides an implementation of server's side connection
-- object that implements a state machine to receive packets from the
-- client side. The structure of a packet is described by the contents
-- of connection object itself. Fields of the object derived from a
-- special abstract type (Data_Item) fed with the input received from
-- the client in the order they are declared in the object. Once all
-- fields are received a primitive operation is called to process the
-- packet. After that the cycle repeats.
-- Enumeration of the fields (introspection) is based on Ada stream
-- attributes. See ARM 13.13.2(9) for the legality of the approach.
--
with Ada.Finalization; use Ada.Finalization;
with Ada.Streams; use Ada.Streams;
with GNAT.Sockets.Server; use GNAT.Sockets.Server;
with System.Storage_Elements; use System.Storage_Elements;
with Generic_Unbounded_Array;
with Interfaces;
with System.Storage_Pools;
package GNAT.Sockets.Connection_State_Machine is
--
-- State_Machine -- Connection client driven by the contents. This is
-- the base type to derive from. The derived type
-- should contain a set of fields with the types derived from Data_Item.
-- These objects will be read automatically in their order.
--
type State_Machine is abstract new Connection with private;
--
-- Connected -- Overrides Connections_Server...
--
-- If the derived type overrides this procedure, it should call this one
-- from new implemetation.
--
procedure Connected (Client : in out State_Machine);
--
-- Finalize -- Destruction
--
-- Client - The connection client
--
-- This procedure is to be called from implementation when overridden.
--
procedure Finalize (Client : in out State_Machine);
--
-- Received -- Overrides GNAT.Sockets.Server...
--
procedure Received
( Client : in out State_Machine;
Data : Stream_Element_Array;
Pointer : in out Stream_Element_Offset
);
--
-- Enumerate -- Fake stream I/O procedure
--
-- This procedure is used internally in order to enumerate the contents
-- of the record type.
--
procedure Enumerate
( Stream : access Root_Stream_Type'Class;
Item : State_Machine
);
for State_Machine'Write use Enumerate;
------------------------------------------------------------------------
--
-- Data_Item -- Base type of a data item to read
--
type Data_Item is abstract
new Ada.Finalization.Limited_Controlled with null record;
type Data_Item_Ptr is access all Data_Item'Class;
type Data_Item_Offset is new Integer;
subtype Data_Item_Address is
Data_Item_Offset range 1..Data_Item_Offset'Last;
type Data_Item_Ptr_Array is
array (Data_Item_Address range <>) of Data_Item_Ptr;
--
-- Feed -- Incoming data
--
-- Item - The data item
-- Data - The array of stream elements containing incoming data
-- Pointer - The first element in the array
-- Client - The connection client
-- State - Of the data item processing
--
-- This procedure is called when data become available to get item
-- contents. The stream elements are Data (Pointer..Data'Last). The
-- procedure consumes data and advances Pointer beyond consumed elements
-- The parameter State indicates processing state. It is initially 0.
-- When Item contents is read in full State is set to 0. When State is
-- not 0 then Pointer must be set to Data'Last + 1, indicating that more
-- data required. Feed will be called again on the item when new data
-- come with the value of State returned from the last call.
--
procedure Feed
( Item : in out Data_Item;
Data : Stream_Element_Array;
Pointer : in out Stream_Element_Offset;
Client : in out State_Machine'Class;
State : in out Stream_Element_Offset
) is abstract;
--
-- Freed -- Deallocation notification
--
-- Item - The data item
--
-- This procedure is called when the shared data item is about to
-- deallocate items allocated there. See External_String_Buffer. The
-- default implementation does nothing.
--
procedure Freed (Item : in out Data_Item);
--
-- Get_Children -- Get list of immediate children
--
-- Item - The data item
--
-- Returns :
--
-- The list of immediate children (nested) data items
--
-- Exceptions :
--
-- Use_Error - The data item is not initialized
--
function Get_Children (Item : Data_Item) return Data_Item_Ptr_Array;
--
-- Get_Size -- Size of the data item in data items
--
-- Item - The data item
--
-- Returns :
--
-- The default implementation returns 1
--
function Get_Size (Item : Data_Item) return Natural;
--
-- End_Of_Subsequence -- Completion of a subsequence
--
-- Item - The data item
-- Data - The array of stream elements containing incoming data
-- Pointer - The first element in the array (can be Data'Last + 1)
-- Client - The connection client
-- State - Of the data item processing
--
-- This procedure is called when a subsequence of data items has been
-- processed. Item is the data item which was active prior to sequence
-- start. It is called only if the data item was not completed, i.e.
-- State is not 0. When the implementation changes State to 0 processing
-- of the data item completes and the next item is fetched. Note that
-- differently to Feed Pointer may point beyond Data when all available
-- input has been processed. The default implementation does nothing.
--
procedure End_Of_Subsequence
( Item : in out Data_Item;
Data : Stream_Element_Array;
Pointer : Stream_Element_Offset;
Client : in out State_Machine'Class;
State : in out Stream_Element_Offset
);
--
-- Enumerate -- Fake stream I/O procedure
--
-- This procedure is used internally in order to enumerate the contents
-- of the record type, a descendant of Connection. The elements of the
-- record type derived from Data_Item are ones which will be fed with
-- data received from the socket.
--
procedure Enumerate
( Stream : access Root_Stream_Type'Class;
Item : Data_Item
);
for Data_Item'Write use Enumerate;
type Shared_Data_Item;
type Shared_Data_Item_Ptr is access all Shared_Data_Item'Class;
--
-- External_Initialize
--
-- Item - The data item
-- Shared - The shared items stack to use
--
-- This procedure is used to initialize an object when it is used
-- outside an instance of State_Machine.
--
procedure External_Initialize
( Item : Data_Item'Class;
Shared : Shared_Data_Item_Ptr := null
);
--
-- Shared_Data_Item -- Base type for shared items
--
type Shared_Data_Item is abstract new Data_Item with record
Initialized : Boolean := False;
Previous : Shared_Data_Item_Ptr; -- Stacked items
end record;
--
-- Enumerate -- Fake stream I/O procedure
--
procedure Enumerate
( Stream : access Root_Stream_Type'Class;
Item : Shared_Data_Item
);
for Shared_Data_Item'Write use Enumerate;
--
-- Feed -- Implementation, makes the shared item active
--
procedure Feed
( Item : in out Shared_Data_Item;
Data : Stream_Element_Array;
Pointer : in out Stream_Element_Offset;
Client : in out State_Machine'Class;
State : in out Stream_Element_Offset
);
------------------------------------------------------------------------
-- Data_Block -- Base type of a sequence of data items. Derived data
-- types contain fields derived from Data_Item.
--
type Data_Block is abstract new Data_Item with private;
--
-- Feed -- Implementation
--
procedure Feed
( Item : in out Data_Block;
Data : Stream_Element_Array;
Pointer : in out Stream_Element_Offset;
Client : in out State_Machine'Class;
State : in out Stream_Element_Offset
);
--
-- Enumerate -- Fake stream I/O procedure
--
procedure Enumerate
( Stream : access Root_Stream_Type'Class;
Item : Data_Block
);
for Data_Block'Write use Enumerate;
--
-- Finalize -- Destruction
--
-- Item - Being finalized
--
-- To be called the from derived type's Finalize if overridden
--
procedure Finalize (Item : in out Data_Block);
--
-- Get_Children -- Overriding
--
function Get_Children (Item : Data_Block) return Data_Item_Ptr_Array;
--
-- Get_Length -- The number of items contained by the block item
--
-- Item - The block item
--
-- Exceptions :
--
-- Use_Error - The block was not initialized yet
--
function Get_Length (Item : Data_Block) return Positive;
--
-- Get_Size -- Overriding
--
function Get_Size (Item : Data_Block) return Natural;
------------------------------------------------------------------------
-- Data_Null -- No data item, used where a data item is required
--
type Data_Null is new Data_Item with null record;
--
-- Feed -- Implementation
--
procedure Feed
( Item : in out Data_Null;
Data : Stream_Element_Array;
Pointer : in out Stream_Element_Offset;
Client : in out State_Machine'Class;
State : in out Stream_Element_Offset
);
------------------------------------------------------------------------
-- Data_Selector -- Base type of a list of data items selected
-- alternatively. A derived type has fields derived
-- from Data_Item. One of the fields is used at a time. So the type
-- acts as a variant record. The field to select is set by calling
-- Set_Alternative. Usually it is done from Feed of some descendant
-- derived from Data_Item, placed after the field controlling selection
-- of the alternative. When an alternative should enclose several fields
-- a Data_Block descendant is used.
--
type Data_Selector is new Data_Item with private;
--
-- Feed -- Implementation
--
procedure Feed
( Item : in out Data_Selector;
Data : Stream_Element_Array;
Pointer : in out Stream_Element_Offset;
Client : in out State_Machine'Class;
State : in out Stream_Element_Offset
);
--
-- Finalize -- Destruction
--
-- Item - Being finalized
--
-- To be called the from derived type's Finalize if overridden
--
procedure Finalize (Item : in out Data_Selector);
--
-- Get_Alternative -- The currently selected alternative
--
-- Item - Selector item
--
-- Returns :
--
-- The alternative number 1..
--
function Get_Alternative (Item : Data_Selector) return Positive;
--
-- Get_Alternatives_Number -- The number of alternatives
--
-- Item - Selector item
--
-- Returns :
--
-- The total number of alternatives
--
-- Exceptions :
--
-- Use_Error - The selector was not initialized yet
--
function Get_Alternatives_Number (Item : Data_Selector)
return Positive;
--
-- Get_Children -- Overriding
--
function Get_Children
( Item : Data_Selector
) return Data_Item_Ptr_Array;
--
-- Enumerate -- Fake stream I/O procedure
--
procedure Enumerate
( Stream : access Root_Stream_Type'Class;
Item : Data_Selector
);
for Data_Selector'Write use Enumerate;
--
-- Set_Alternative -- Select an alternative
--
-- Item - Selector item
-- Alternative - To select (number 1..Get_Alternatives_Number (Item))
--
-- Exceptions :
--
-- Constraint_Error - Invalid alternative number
-- Use_Error - The selector was not initialized yet
--
procedure Set_Alternative
( Item : in out Data_Selector;
Alternative : Positive
);
--
-- Get_Size -- Overriding
--
function Get_Size (Item : Data_Selector) return Natural;
------------------------------------------------------------------------
--
-- External_String_Buffer -- The arena buffer to keep bodies of strings
-- and dynamically allocated elements. This
-- buffer can be shared by multiple instances of Data_Item. For example:
--
-- type Alternatives_Record is new Choice_Data_Item with record
-- Text_1 : Implicit_External_String_Data_Item;
-- Text_2 : Implicit_External_String_Data_Item;
-- Text_3 : Implicit_External_String_Data_Item;
-- end record;
-- type Packet is new State_Machine ... with record
-- Buffer : External_String_Buffer (1024); -- Shared buffer
-- Choice : Alternatives_Record;
-- end record;
--
-- When several buffers appear the nearest one before the data item
-- object is used.
--
type External_String_Buffer;
type External_String_Buffer_Ptr is
access all External_String_Buffer'Class;
--
-- Arena_Pool -- The pool component of the External_String_Buffer that
-- allocates memory as substrings in the buffer.
--
-- Parent - The buffer to take memory from
--
type Arena_Pool
( Parent : access External_String_Buffer'Class
) is new System.Storage_Pools.Root_Storage_Pool with
null record;
--
-- Allocate -- Allocate memory
--
-- The memory is allocated in the string buffer as a string.
--
procedure Allocate
( Pool : in out Arena_Pool;
Address : out System.Address;
Size : Storage_Count;
Alignment : Storage_Count
);
--
-- Deallocate -- Free memory
--
-- This a null operation. The memory is freed by Erase
--
procedure Deallocate
( Pool : in out Arena_Pool;
Address : System.Address;
Size : Storage_Count;
Alignment : Storage_Count
);
function Storage_Size
( Pool : Arena_Pool
) return Storage_Count;
procedure Enumerate
( Stream : access Root_Stream_Type'Class;
Pool : Arena_Pool
);
for Arena_Pool'Write use Enumerate;
--
-- Allocator_Data -- The allocator's list. The users of the pool
-- register themselves in order to get notifications
-- upon erasing the buffer. They should finalize all objects then have
-- allocated in the pool.
--
type Allocator_Data;
type Allocator_Data_Ptr is access all Allocator_Data;
type Allocator_Data (Allocator : access Data_Item'Class) is record
Previous : Allocator_Data_Ptr; -- List of allocators
end record;
type External_String_Buffer (Size : Natural) is
new Shared_Data_Item with
record
Pool : Arena_Pool (External_String_Buffer'Access);
Length : Natural := 0;
Count : Natural := 0; -- Allocatied items
Allocators : Allocator_Data_Ptr; -- List of objects using the pool
Buffer : String (1..Size);
end record;
--
-- Erase -- Deallocate all elements and all strings
--
-- Buffer - The buffer
--
-- The implementation walks the list of allocators to notify them that
-- the allocated items will be freed. The callee must finalize its
-- elements if necessary.
--
procedure Erase (Buffer : in out External_String_Buffer);
--
-- Feed -- Implementation of the feed operation
--
-- The implementation erases the buffer.
--
procedure Feed
( Item : in out External_String_Buffer;
Data : Stream_Element_Array;
Pointer : in out Stream_Element_Offset;
Client : in out State_Machine'Class;
State : in out Stream_Element_Offset
);
--
-- Fnalize -- Destruction
--
-- Buffer - The buffer
--
-- The derived type must call this if it overrides it.
--
procedure Finalize (Buffer : in out External_String_Buffer);
------------------------------------------------------------------------
generic
with procedure Put (Text : String) is <>;
with procedure Put_Line (Line : String) is <>;
package Generic_Dump is
--
-- Put -- Allocator list
--
-- Buffer - The external string buffer
-- Prefix - Of the output lines
--
procedure Put
( Buffer : in out External_String_Buffer;
Prefix : String
);
--
-- Put -- List item structure recursively
--
-- Item - The data item
-- Prefix - Of the output lines
--
procedure Put
( Item : Data_Item'Class;
Prefix : String := ""
);
--
-- Put_Call_Stack -- List the call stack of the state machine
--
-- Client - The state machine
-- Prefix - Of the output lines
--
procedure Put_Call_Stack
( Client : State_Machine'Class;
Prefix : String := ""
);
--
-- Put_Stream -- Stream and dump the result list
--
-- Item - The data item
-- Prefix - Of the output lines
--
procedure Put_Stream
( Item : Data_Item'Class;
Prefix : String := ""
);
end Generic_Dump;
private
use Interfaces;
Out_Of_Bounds : constant String := "Pointer is out of bounds";
No_Room : constant String := "No room for output";
package Data_Item_Arrays is
new Generic_Unbounded_Array
( Index_Type => Data_Item_Address,
Object_Type => Data_Item_Ptr,
Object_Array_Type => Data_Item_Ptr_Array,
Null_Element => null
);
use Data_Item_Arrays;
type Data_Item_Ptr_Array_Ptr is access Data_Item_Ptr_Array;
procedure Free is
new Ada.Unchecked_Deallocation
( Data_Item_Ptr_Array,
Data_Item_Ptr_Array_Ptr
);
type Sequence;
type Sequence_Ptr is access all Sequence;
type Sequence (Length : Data_Item_Address) is record
Caller : Sequence_Ptr;
State : Stream_Element_Offset := 0; -- Saved caller's state
Current : Data_Item_Offset := 1;
List : Data_Item_Ptr_Array (1..Length);
end record;
procedure Free is
new Ada.Unchecked_Deallocation (Sequence, Sequence_Ptr);
type State_Type is (Feeding, Packet_Processing);
type State_Machine is abstract new Connection with record
State : Stream_Element_Offset := 0;
Start : Stream_Element_Offset := 0; -- Saved pointer
Fed : Unsigned_64 := 0; -- Running count of octets processed
Data : Sequence_Ptr;
end record;
procedure Call
( Client : in out State_Machine;
Pointer : Stream_Element_Offset;
Data : Sequence_Ptr;
State : Stream_Element_Offset := 0
);
type Shared_Data_Item_Ptr_Ptr is access all Shared_Data_Item_Ptr;
type Initialization_Stream is new Root_Stream_Type with record
Shared : aliased Shared_Data_Item_Ptr; -- The latest shared item
Parent : Shared_Data_Item_Ptr_Ptr;
Count : Data_Item_Offset := 0;
Ignore : Data_Item_Offset := 0;
Data : Unbounded_Array;
end record;
procedure Add
( Stream : in out Initialization_Stream;
Item : Data_Item'Class;
Nested : Data_Item_Offset := 0
);
procedure Read
( Stream : in out Initialization_Stream;
Item : out Stream_Element_Array;
Last : out Stream_Element_Offset
);
procedure Write
( Stream : in out Initialization_Stream;
Item : Stream_Element_Array
);
function Get_Prefix (Stream : Root_Stream_Type'Class) return String;
procedure Set_Prefix
( Stream : Root_Stream_Type'Class;
Prefix : Natural
);
procedure Check_Initialization_Stream
( Item : Data_Item'Class;
Stream : Root_Stream_Type'Class
);
function To_Integer (Value : Unsigned_8 ) return Integer_8;
function To_Integer (Value : Unsigned_16) return Integer_16;
function To_Integer (Value : Unsigned_32) return Integer_32;
function To_Integer (Value : Unsigned_64) return Integer_64;
pragma Inline (To_Integer);
function To_Unsigned (Value : Integer_8 ) return Unsigned_8;
function To_Unsigned (Value : Integer_16) return Unsigned_16;
function To_Unsigned (Value : Integer_32) return Unsigned_32;
function To_Unsigned (Value : Integer_64) return Unsigned_64;
pragma Inline (To_Unsigned);
function Self (Item : Data_Item'Class) return Data_Item_Ptr;
type Data_Block_Ptr is access all Data_Block'Class;
type Data_Block is new Data_Item with record
Data : Sequence_Ptr;
Initialized : Boolean := False;
end record;
function Self (Item : Data_Block'Class) return Data_Block_Ptr;
type Sequence_Array is array (Positive range <>) of Sequence_Ptr;
type Alternatives_List (Size : Natural) is record
List : Sequence_Array (1..Size);
end record;
type Alternatives_List_Ptr is access Alternatives_List;
type Data_Selector_Ptr is access all Data_Selector'Class;
type Data_Selector is new Data_Item with record
Alternatives : Alternatives_List_Ptr;
Current : Positive := 1;
Initialized : Boolean := False;
end record;
function Self (Item : Data_Selector'Class) return Data_Selector_Ptr;
function Self (Item : Shared_Data_Item'Class)
return Shared_Data_Item_Ptr;
generic
with procedure Put_Line (Line : String) is <>;
procedure Generic_Dump_Stream
( Stream : Initialization_Stream'Class;
Prefix : String := ""
);
end GNAT.Sockets.Connection_State_Machine;
|
AdaCore/training_material | Ada | 393 | adb | package body Surfaces is
function Row_Luminosity
(Surf : Surface_T; Row : Row_T) return Pixel_Component_Row_Array_T
is
Pix_Row : Pixel_Component_Row_Array_T (Surf'First (2) .. Surf'Last (2));
begin
for Col in Pix_Row'Range loop
Pix_Row (Col) := Pixels.Luminosity (Surf (Row, Col));
end loop;
return Pix_Row;
end Row_Luminosity;
end Surfaces;
|
reznikmm/matreshka | Ada | 3,654 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with XML.DOM.Elements;
package ODF.DOM.Form_Option_Elements is
pragma Preelaborate;
type ODF_Form_Option is limited interface
and XML.DOM.Elements.DOM_Element;
type ODF_Form_Option_Access is
access all ODF_Form_Option'Class
with Storage_Size => 0;
end ODF.DOM.Form_Option_Elements;
|
jorge-real/TTS-Runtime-Ravenscar | Ada | 12,276 | adb | with Ada.Real_Time; use Ada.Real_Time;
with Logging_Support;
with Ada.Text_IO; use Ada.Text_IO;
with System; use System;
with Epoch_Support; use Epoch_Support;
with XAda.Dispatching.TTS;
with TT_Utilities;
with TT_Patterns;
package body TTS_Example_A is
Number_Of_Work_Ids : constant := 6;
Number_Of_Sync_Ids : constant := 2;
package TTS is new XAda.Dispatching.TTS
(Number_Of_Work_Ids, Number_Of_Sync_Ids, Priority'Last - 1);
package TT_Util is new TT_Utilities (TTS);
use TT_Util;
package TT_Patt is new TT_Patterns (TTS);
use TT_Patt;
-- Variables incremented by two TT sequences of IMs-F tasks
Var_1, Var_2 : Natural := 0;
pragma Volatile (Var_1);
pragma Volatile (Var_2);
-- Auxiliary for printing times --
function Now (Current : Time) return String is
(Duration'Image ( To_Duration (Current - TTS.Get_First_Plan_Release) * 1000) & " ms " &
"|" & Duration'Image ( To_Duration (Current - TTS.Get_Last_Plan_Release) * 1000) & " ms ");
-- TT tasks --
type First_Init_Task is new Simple_Task_State with null record;
procedure Initialize (S : in out First_Init_Task) is null;
procedure Main_Code (S : in out First_Init_Task);
Wk1_Code : aliased First_Init_Task;
Wk1 : Simple_TT_Task
(Work_Id => 1,
Task_State => Wk1_Code'Access,
Synced_Init => False);
type First_IMF_Task is new Initial_Mandatory_Final_Task_State
with
record
Counter : Natural := 0;
end record;
procedure Initialize (S : in out First_IMF_Task) is null;
procedure Initial_Code (S : in out First_IMF_Task);
procedure Mandatory_Code (S : in out First_IMF_Task);
procedure Final_Code (S : in out First_IMF_Task);
Wk2_State : aliased First_IMF_Task;
Wk2 : InitialMandatorySliced_Final_TT_Task
(Work_Id => 2,
Task_State => Wk2_State'Access,
Synced_Init => False);
type Second_Init_Task is new Simple_Task_State with null record;
procedure Initialize (S : in out Second_Init_Task) is null;
procedure Main_Code (S : in out Second_Init_Task);
Wk3_Code : aliased Second_Init_Task;
Wk3 : Simple_TT_Task
(Work_Id => 3,
Task_State => Wk3_Code'Access,
Synced_Init => False);
type Second_IMF_Task is new Initial_Mandatory_Final_Task_State with
record
Counter : Natural := 0;
end record;
procedure Initialize (S : in out Second_IMF_Task) is null;
procedure Initial_Code (S : in out Second_IMF_Task);
procedure Mandatory_Code (S : in out Second_IMF_Task);
procedure Final_Code (S : in out Second_IMF_Task);
Wk4_Code : aliased Second_IMF_Task;
Wk4 : InitialMandatorySliced_Final_TT_Task
(Work_Id => 4,
Task_State => Wk4_Code'Access,
Synced_Init => False);
type End_Of_Plan_IF_Task is new Initial_Final_Task_State with null record;
procedure Initialize (S : in out End_Of_Plan_IF_Task) is null;
procedure Initial_Code (S : in out End_Of_Plan_IF_Task);
procedure Final_Code (S : in out End_Of_Plan_IF_Task);
Wk5_Code : aliased End_Of_Plan_IF_Task;
Wk5 : Initial_Final_TT_Task
(Work_Id => 5,
Task_State => Wk5_Code'Access,
Synced_Init => False);
type Synced_ET_Task is new Initial_OptionalFinal_Task_State with
record
Counter : Natural := 0;
end record;
procedure Initialize (S : in out Synced_ET_Task) is null;
procedure Initial_Code (S : in out Synced_ET_Task);
function Final_Is_Required (S : in out Synced_ET_Task) return Boolean;
procedure Final_Code (S : in out Synced_ET_Task);
Wk6_Code : aliased Synced_ET_Task;
Wk6 : SyncedInitial_OptionalFinal_ET_Task
(Sync_Id => 1,
Work_Id => 6,
Task_State => Wk6_Code'Access,
Synced_Init => False);
task type SyncedSporadic_ET_Task
(Sync_Id : TTS.TT_Sync_Id;
Offset : Natural)
with Priority => Priority'Last;
task body SyncedSporadic_ET_Task is
Release_Time : Time;
begin
loop
TTS.Wait_For_Sync (Sync_Id, Release_Time);
delay until Release_Time + Milliseconds (Offset);
Put_Line ("Sporadic task interrupting at " & Now (Clock));
end loop;
end SyncedSporadic_ET_Task;
Sp1 : SyncedSporadic_ET_Task
(Sync_Id => 2, Offset => 158);
ms : constant Time_Span := Milliseconds (1);
-- The TT plan
TT_Plan : aliased TTS.Time_Triggered_Plan :=
( TT_Slot (Regular, 50*ms, 1), -- #00 Single slot for 1st seq. start
TT_Slot (Empty, 150*ms ), -- #01
TT_Slot (Regular, 50*ms, 3), -- #02 Single slot for 2nd seq. start
TT_Slot (Sync, 150*ms, 2), -- #03 Sync point for sporadic task SP1
TT_Slot (Regular, 50*ms, 2), -- #04 Seq. 1, IMs part
TT_Slot (Regular, 50*ms, 4), -- #05 Seq. 2, IMs part
TT_Slot (Empty, 300*ms ), -- #06
TT_Slot (Continuation, 50*ms, 2), -- #07 Seq. 1, continuation of Ms part
TT_Slot (Empty, 150*ms ), -- #08
TT_Slot (Terminal, 100*ms, 4), -- #09 Seq. 2, terminal of Ms part
TT_Slot (Empty, 100*ms ), -- #10
TT_Slot (Terminal, 50*ms, 2), -- #11 Seq. 1, terminal of Ms part
TT_Slot (Sync, 150*ms, 1), -- #12 Sync Point for ET Task 1 + Empty
TT_Slot (Regular, 50*ms, 4), -- #13 Seq. 2, F part
TT_Slot (Empty, 100*ms ), -- #14
TT_Slot (Regular, 50*ms, 2), -- #15 Seq. 1, F part
TT_Slot (Empty, 80*ms ), -- #16
TT_Slot (Regular, 50*ms, 5), -- #17 I part of end of plan
TT_Slot (Empty, 70*ms ), -- #18
TT_Slot (Optional, 70*ms, 6), -- #19 F part of synced ET Task 1
TT_Slot (Regular, 50*ms, 5), -- #20 F part of end of plan
TT_Slot (Mode_Change, 80*ms) ); -- #21
-- Actions of sequence initialisations
procedure Main_Code (S : in out First_Init_Task) is -- Simple_TT task with ID = 1
Jitter : Time_Span := Clock - S.Release_Time;
begin
New_Line;
Put_Line ("------------------------");
Put_Line ("Starting plan!");
Put_Line ("------------------------");
New_Line;
-- Log --
Put_line( "Worker" & Integer (S.Work_Id)'Image & " Jitter = " &
Duration'Image (1000.0 * To_Duration (Jitter)) & " ms.");
-- Log --
Var_1 := 0;
Put_Line ("First_Init_Task.Main_Code ended at " & Now (Clock));
end Main_Code;
procedure Main_Code (S : in out Second_Init_Task) is -- Simple_TT task with ID = 3
Jitter : Time_Span := Clock - S.Release_Time;
begin
-- Log --
Put_line( "Worker" & Integer (S.Work_Id)'Image & " Jitter = " &
Duration'Image (1000.0 * To_Duration (Jitter)) & " ms.");
-- Log --
Var_2 := 0;
Put_Line ("Second_Init_Task.Main_Code ended at " & Now (Clock));
end Main_Code;
-- Actions of first sequence: IMs-F task with ID = 2
procedure Initial_Code (S : in out First_IMF_Task) is
Jitter : Time_Span := Clock - S.Release_Time;
begin
-- Log --
Put_line( "Worker" & Integer (S.Work_Id)'Image & " Jitter = " &
Duration'Image (1000.0 * To_Duration (Jitter)) & " ms.");
-- Log --
S.Counter := Var_1;
Put_Line ("First_IMF_Task.Initial_Code ended at " & Now (Clock));
end Initial_Code;
procedure Mandatory_Code (S : in out First_IMF_Task) is
begin
Put_Line ("First_IMF_Task.Mandatory_Code sliced started at " & Now (Clock));
while S.Counter < 250_000 loop
S.Counter := S.Counter + 1;
if S.Counter mod 20_000 = 0 then
Put_Line ("First_IMF_Task.Mandatory_Code sliced step " & Now (Clock));
end if;
end loop;
Put_Line ("First_IMF_Task.Mandatory_Code sliced ended at " & Now (Clock));
end Mandatory_Code;
procedure Final_Code (S : in out First_IMF_Task) is
Jitter : Time_Span := Clock - S.Release_Time;
begin
-- Log --
Put_line( "Worker" & Integer (S.Work_Id)'Image & " Jitter = " &
Duration'Image (1000.0 * To_Duration (Jitter)) & " ms.");
-- Log --
Var_1 := S.Counter;
Put_Line ("First_IMF_Task.Final_Code Seq. 1 with Var_1 =" & Var_1'Image & " at" & Now (Clock));
end Final_Code;
-- Actions of Second sequence: IMs-F task with ID = 4
procedure Initial_Code (S : in out Second_IMF_Task) is
Jitter : Time_Span := Clock - S.Release_Time;
begin
-- Log --
Put_line( "Worker" & Integer (S.Work_Id)'Image & " Jitter = " &
Duration'Image (1000.0 * To_Duration (Jitter)) & " ms.");
-- Log --
S.Counter := Var_2;
Put_Line ("Second_IMF_Task.Initial_Code ended at " & Now (Clock));
end Initial_Code;
procedure Mandatory_Code (S : in out Second_IMF_Task) is
begin
Put_Line ("Second_IMF_Task.Mandatory_Code sliced started at " & Now (Clock));
while S.Counter < 100_000 loop
S.Counter := S.Counter + 1;
if S.Counter mod 20_000 = 0 then
Put_Line ("Second_IMF_Task.Mandatory_Code sliced step " & Now (Clock));
end if;
end loop;
Put_Line ("Second_IMF_Task.Mandatory_Code sliced ended at " & Now (Clock));
end Mandatory_Code;
procedure Final_Code (S : in out Second_IMF_Task) is
Jitter : Time_Span := Clock - S.Release_Time;
begin
-- Log --
Put_line( "Worker" & Integer (S.Work_Id)'Image & " Jitter = " &
Duration'Image (1000.0 * To_Duration (Jitter)) & " ms.");
-- Log --
Var_2 := S.Counter;
Put_Line ("Second_IMF_Task.Final_Code Seq. 2 with Var_2 =" & Var_2'Image & " at" & Now (Clock));
end Final_Code;
-- End of plan actions: I-F task with ID = 4
procedure Initial_Code (S : in out End_Of_Plan_IF_Task) is
Jitter : Time_Span := Clock - S.Release_Time;
begin
-- Log --
Put_line( "Worker" & Integer (S.Work_Id)'Image & " Jitter = " &
Duration'Image (1000.0 * To_Duration (Jitter)) & " ms.");
-- Log --
Put_Line ("End_Of_Plan_IF_Task.Initial_Code at" & Now (Clock));
Put_Line ("Value of Var_1 =" & Var_1'Image);
Put_Line ("Value of Var_2 =" & Var_2'Image);
end Initial_Code;
procedure Final_Code (S : in out End_Of_Plan_IF_Task) is
Jitter : Time_Span := Clock - S.Release_Time;
begin
-- Log --
Put_line( "Worker" & Integer (S.Work_Id)'Image & " Jitter = " &
Duration'Image (1000.0 * To_Duration (Jitter)) & " ms.");
-- Log --
Put_Line ("End_Of_Plan_IF_Task.Final_Code at" & Now (Clock));
New_Line;
Put_Line ("------------------------");
Put_Line ("Starting all over again!");
Put_Line ("------------------------");
New_Line;
end Final_Code;
procedure Initial_Code (S : in out Synced_ET_Task) is
Jitter : Time_Span := Clock - S.Release_Time;
begin
-- Log --
Put_line( "Synced" & Integer (S.Sync_Id)'Image & " Jitter = " &
Duration'Image (1000.0 * To_Duration (Jitter)) & " ms.");
-- Log --
S.Counter := S.Counter + 1;
Put_Line ("Synced_ET_Task.Synced_Code with counter = " & S.Counter'Image & " at" & Now (Clock));
end Initial_Code;
function Final_Is_Required (S : in out Synced_ET_Task) return Boolean is
Condition : Boolean;
begin
Condition := (S.Counter mod 2 = 0);
Put_Line ("Synced_ET_Task.Final_Is_Required with condition = " & Condition'Image & " at" & Now (Clock));
return Condition;
end Final_Is_Required;
procedure Final_Code (S : in out Synced_ET_Task) is
Jitter : Time_Span := Clock - S.Release_Time;
begin
-- Log --
Put_line( "Worker" & Integer (S.Work_Id)'Image & " Jitter = " &
Duration'Image (1000.0 * To_Duration (Jitter)) & " ms.");
-- Log --
Put_Line ("Synced_ET_Task.Final_Code with counter = " & S.Counter'Image & " at" & Now (Clock));
end Final_Code;
----------
-- Main --
----------
procedure Main is
begin
delay until Epoch_Support.Epoch;
TTS.Set_Plan(TT_Plan'Access);
delay until Ada.Real_Time.Time_Last;
end Main;
end TTS_Example_A;
|
reznikmm/matreshka | Ada | 3,756 | adb | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2013, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with ODF.Constants;
package body Matreshka.ODF_Attributes.FO.Page_Width is
--------------------
-- Get_Local_Name --
--------------------
overriding function Get_Local_Name
(Self : not null access constant FO_Page_Width_Node)
return League.Strings.Universal_String is
begin
return ODF.Constants.Page_Width_Name;
end Get_Local_Name;
end Matreshka.ODF_Attributes.FO.Page_Width;
|
reznikmm/matreshka | Ada | 5,231 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Web Framework --
-- --
-- Testsuite Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
--
-- Test:T40
--
-- Description:
--
-- This test uses the literal format for IPv6 addresses in URIs.
--
-- Messages:
--
-- Message sent from Node A
--
-- <?xml version='1.0' ?>
-- <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
-- <env:Header>
-- <test:Unknown
-- xmlns:test="http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]/ts-tests"
-- env:role="http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver"
-- env:mustUnderstand="false">
-- foo
-- </test:Unknown>
-- </env:Header>
-- <env:Body>
-- </env:Body>
-- </env:Envelope>
--
-- Message sent from Node C
--
-- <?xml version='1.0' ?>
-- <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
-- <env:Body>
-- </env:Body>
-- </env:Envelope>
------------------------------------------------------------------------------
package SOAPConf.Testcases.Test_T40 is
Scenario : constant Testcase_Data
:= (League.Strings.To_Universal_String
("<?xml version='1.0'?>"
& "<env:Envelope"
& " xmlns:env='http://www.w3.org/2003/05/soap-envelope'>"
& "<env:Header>"
& "<test:Unknown"
& " xmlns:test='http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]/ts-tests'"
& " env:role='http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver'"
& " env:mustUnderstand='false'>"
& "foo"
& "</test:Unknown>"
& "</env:Header>"
& "<env:Body>"
& "</env:Body>"
& "</env:Envelope>"),
League.Strings.To_Universal_String
("<?xml version='1.0'?>"
& "<env:Envelope"
& " xmlns:env='http://www.w3.org/2003/05/soap-envelope'>"
& "<env:Body/>"
& "</env:Envelope>"));
end SOAPConf.Testcases.Test_T40;
|
reznikmm/matreshka | Ada | 6,948 | adb | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Matreshka.DOM_Documents;
with Matreshka.ODF_String_Constants;
with ODF.DOM.Iterators;
with ODF.DOM.Visitors;
package body Matreshka.ODF_Presentation.Header_Elements is
------------
-- Create --
------------
overriding function Create
(Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters)
return Presentation_Header_Element_Node is
begin
return Self : Presentation_Header_Element_Node do
Matreshka.ODF_Presentation.Constructors.Initialize
(Self'Unchecked_Access,
Parameters.Document,
Matreshka.ODF_String_Constants.Presentation_Prefix);
end return;
end Create;
----------------
-- Enter_Node --
----------------
overriding procedure Enter_Node
(Self : not null access Presentation_Header_Element_Node;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control) is
begin
if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then
ODF.DOM.Visitors.Abstract_ODF_Visitor'Class
(Visitor).Enter_Presentation_Header
(ODF.DOM.Presentation_Header_Elements.ODF_Presentation_Header_Access
(Self),
Control);
else
Matreshka.DOM_Elements.Abstract_Element_Node
(Self.all).Enter_Node (Visitor, Control);
end if;
end Enter_Node;
--------------------
-- Get_Local_Name --
--------------------
overriding function Get_Local_Name
(Self : not null access constant Presentation_Header_Element_Node)
return League.Strings.Universal_String
is
pragma Unreferenced (Self);
begin
return Matreshka.ODF_String_Constants.Header_Element;
end Get_Local_Name;
----------------
-- Leave_Node --
----------------
overriding procedure Leave_Node
(Self : not null access Presentation_Header_Element_Node;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control) is
begin
if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then
ODF.DOM.Visitors.Abstract_ODF_Visitor'Class
(Visitor).Leave_Presentation_Header
(ODF.DOM.Presentation_Header_Elements.ODF_Presentation_Header_Access
(Self),
Control);
else
Matreshka.DOM_Elements.Abstract_Element_Node
(Self.all).Leave_Node (Visitor, Control);
end if;
end Leave_Node;
----------------
-- Visit_Node --
----------------
overriding procedure Visit_Node
(Self : not null access Presentation_Header_Element_Node;
Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control) is
begin
if Iterator in ODF.DOM.Iterators.Abstract_ODF_Iterator'Class then
ODF.DOM.Iterators.Abstract_ODF_Iterator'Class
(Iterator).Visit_Presentation_Header
(Visitor,
ODF.DOM.Presentation_Header_Elements.ODF_Presentation_Header_Access
(Self),
Control);
else
Matreshka.DOM_Elements.Abstract_Element_Node
(Self.all).Visit_Node (Iterator, Visitor, Control);
end if;
end Visit_Node;
begin
Matreshka.DOM_Documents.Register_Element
(Matreshka.ODF_String_Constants.Presentation_URI,
Matreshka.ODF_String_Constants.Header_Element,
Presentation_Header_Element_Node'Tag);
end Matreshka.ODF_Presentation.Header_Elements;
|
BrickBot/Bound-T-H8-300 | Ada | 151,679 | adb | -- Programs.Execution (body)
--
-- A component of the Bound-T Worst-Case Execution Time Tool.
--
-------------------------------------------------------------------------------
-- Copyright (c) 1999 .. 2015 Tidorum Ltd
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- 1. Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- This software is provided by the copyright holders and contributors "as is" and
-- any express or implied warranties, including, but not limited to, the implied
-- warranties of merchantability and fitness for a particular purpose are
-- disclaimed. In no event shall the copyright owner or contributors be liable for
-- any direct, indirect, incidental, special, exemplary, or consequential damages
-- (including, but not limited to, procurement of substitute goods or services;
-- loss of use, data, or profits; or business interruption) however caused and
-- on any theory of liability, whether in contract, strict liability, or tort
-- (including negligence or otherwise) arising in any way out of the use of this
-- software, even if advised of the possibility of such damage.
--
-- Other modules (files) of this software composition should contain their
-- own copyright statements, which may have different copyright and usage
-- conditions. The above conditions apply to this file.
-------------------------------------------------------------------------------
--
-- $Revision: 1.56 $
-- $Date: 2015/10/24 20:05:51 $
--
-- $Log: programs-execution.adb,v $
-- Revision 1.56 2015/10/24 20:05:51 niklas
-- Moved to free licence.
--
-- Revision 1.55 2015/05/22 06:32:22 niklas
-- Corrected indentation.
--
-- Revision 1.54 2013/12/12 22:26:04 niklas
-- BT-CH-0262: Corrections to new value-origin analysis.
--
-- Revision 1.53 2013/12/08 22:05:57 niklas
-- BT-CH-0259: Storing value-origin analysis results in execution bounds.
--
-- Revision 1.52 2009-11-27 11:28:07 niklas
-- BT-CH-0184: Bit-widths, Word_T, failed modular analysis.
--
-- Revision 1.51 2009-10-07 19:26:10 niklas
-- BT-CH-0183: Cell-sets are a tagged-type class.
--
-- Revision 1.50 2009-04-16 16:29:23 niklas
-- BT-CH-0171: Stack pointers in call effects.
--
-- Revision 1.49 2009/04/09 19:24:34 niklas
-- Changed some Warnings to Faults, which they are.
--
-- Revision 1.48 2009/01/18 07:53:05 niklas
-- Removed unused context clauses and locals.
--
-- Revision 1.47 2008/11/09 21:43:05 niklas
-- BT-CH-0158: Output.Image (Time_T) replaces Programs.Execution.Image.
--
-- Revision 1.46 2008/09/24 08:38:53 niklas
-- BT-CH-0146: Assertions on "loop starts <bound> times".
-- BT-CH-0146: Loop-repeat assertions set both lower and upper bound.
-- BT-CH-0146: Report locations of contradictory "count" assertions.
-- BT-CH-0146: Contradictory "count" assertions imply infeasibility.
--
-- Revision 1.45 2008/07/28 19:23:45 niklas
-- BT-CH-0140: Detect contradictory execution-count bounds.
--
-- Revision 1.44 2008/07/23 09:07:16 niklas
-- BT-CH-0139: Fix recursion in Programs.Execution.Paths.
--
-- Revision 1.43 2008/07/20 06:31:38 niklas
-- BT-CH-0137: Cached Locus for subprograms and execution bounds.
--
-- Revision 1.42 2008/07/14 19:16:57 niklas
-- BT-CH-0135: Assertions on "instructions".
--
-- Revision 1.41 2008/02/27 19:25:19 niklas
-- BT-CH-0116: Call-specific time and stack assertions.
--
-- Revision 1.40 2008/02/23 13:34:04 niklas
-- BT-CH-0115: Wcet_Loop output and option -loop_time.
--
-- Revision 1.39 2008/02/18 13:24:10 niklas
-- BT-CH-0111: Processor-specific info in execution bounds.
--
-- Revision 1.38 2008/01/31 21:57:45 niklas
-- BT-CH-0108: Fixes to BT-CH-0098.
--
-- Revision 1.37 2007/12/21 13:31:08 niklas
-- Extended Input_Cells for better Locus in Fault message.
--
-- Revision 1.36 2007/12/17 13:54:40 niklas
-- BT-CH-0098: Assertions on stack usage and final stack height, etc.
--
-- Revision 1.35 2007/11/12 21:37:28 niklas
-- BT-CH-0097: Only arithmetic analysis marks boundable edge domain.
--
-- Revision 1.34 2007/08/27 16:10:14 niklas
-- Extended function Number_Of_Bounds (Bounds_Set) to return zero
-- for an uninitialized (null) bounds-set.
--
-- Revision 1.33 2007/08/17 14:44:00 niklas
-- BT-CH-0074: Stable and Unstable stacks.
--
-- Revision 1.32 2007/08/05 21:07:04 niklas
-- Extended Initialize_Bounds, when the Along context is not null, to
-- check that there are earlier bounds for the subprogram and that the
-- subprogram is the final callee in the context, and else emit Faults.
-- Extended Call_Bounds (Within Bounds_Ref) to check for null callee
-- bounds and emit a warning for such.
--
-- Revision 1.31 2007/08/02 11:23:18 niklas
-- Added the exception Undefined_Stub_Level to understand why
-- the Stub_Level function can be called with null Bounds.
--
-- Revision 1.30 2007/07/09 13:49:01 niklas
-- Added a variant of Add_Inputs_For_Unbounded_Calls that updates
-- a Cell_Set_T, instead of a Small_Cell_Set_T.
-- Extended Bound_Call_Input to trace the action, optionally.
--
-- Revision 1.29 2007/05/02 11:41:13 niklas
-- Added the helper procedure Add_Inputs_For to set the output locus
-- for the call being processed in Add_Inputs_For_Unbounded_Calls.
--
-- Revision 1.28 2007/03/18 12:50:39 niklas
-- BT-CH-0050.
--
-- Revision 1.27 2007/02/13 20:24:50 Niklas
-- BT-CH-0044.
--
-- Revision 1.26 2007/01/25 21:25:17 niklas
-- BT-CH-0043.
--
-- Revision 1.25 2007/01/21 19:31:47 niklas
-- BT-CH-0042.
--
-- Revision 1.24 2007/01/13 13:51:06 niklas
-- BT-CH-0041.
--
-- Revision 1.23 2006/12/05 18:48:37 niklas
-- BT-CH-0040.
--
-- Revision 1.22 2006/11/20 18:59:02 niklas
-- Added the function Bounds_For_Calls to give the universal bounds
-- for all calls from a given Subprogram, itself perhaps not bounded.
--
-- Revision 1.21 2006/11/01 21:27:26 niklas
-- BT-CH-0034.
--
-- Revision 1.20 2006/10/24 21:41:06 niklas
-- BT-CH-0030.
--
-- Revision 1.19 2006/08/22 12:51:23 niklas
-- Extended Set_Input_Cells and Set_Output_Cells to check for
-- No_Cell_Set and signal a fault in that case.
-- Updated function Basis to use Storage.Is_None instead of "=".
--
-- Revision 1.18 2006/05/27 21:39:52 niklas
-- BT-CH-0020.
--
-- Revision 1.17 2006/05/26 13:55:10 niklas
-- Added function Calling_Protocol, for RapiTime export.
--
-- Revision 1.16 2006/03/25 13:34:08 niklas
-- Added query functions Executed_Edges and Executed_Call_Bounds.
-- Added functions to compute the Total_Time of a set of nodes
-- or edges, or of all edges within some execution bounds (based
-- on the earlier private function Total_Time). Modified the
-- Total_Time functions for loops and calls accordingly.
--
-- Revision 1.15 2005/10/09 08:10:23 niklas
-- BT-CH-0013.
--
-- Revision 1.14 2005/09/20 09:57:46 niklas
-- Added function Flow_Graph (Bounds_Ref).
--
-- Revision 1.13 2005/08/24 10:29:51 niklas
-- Added stuff to support the Analysis Workbench, including
-- the functions Link (From Bounds Via Call), No_Links,
-- Counts_Set (Bounds), Count (Node), Count (Edge),
-- Start_Count (Loop), Head_Count (Loop), Neck_Count (Loop),
-- Repeat_Count (Loop), Call_Count (Call), Call_Count (Link),
-- Total_Time (Loop), Total_Time (Call) and Total_Time (Link).
-- Modified Node_Times_With_Call_Times to use the new function
-- Programs.Node (Call), making the local variable Graph useless
-- and removable.
--
-- Revision 1.12 2005/08/08 17:55:39 niklas
-- Added the function Bound_At to access execution bounds using the
-- program-wide unique index Bounds_Index_T. Added the component
-- Bounds_Set_Object_T.Indexed to support this function.
-- Added the functions Loop_Neck_Bound and Loop_Repeat_Bound to
-- query loop-bounds for a given loop (not all loops at once).
--
-- Revision 1.11 2005/06/29 19:35:30 niklas
-- Added Prune_Flow.
--
-- Revision 1.10 2005/06/29 12:54:34 niklas
-- Added the Locus function for loops.
--
-- Revision 1.9 2005/06/28 08:39:14 niklas
-- Extended Assert_Path_Specific_Time to provide the "stub" bounds
-- with a computation model (the "primitive" one). This avoids null
-- pointers in detailed output.
-- Changed function Node_Times to just Note when the times are
-- missing, instead of emitting a Fault. This helps detailed output.
--
-- Revision 1.8 2005/05/09 15:34:06 niklas
-- Added initial support for value-origin analysis, by adding the
-- operation Remove_From_Output.
--
-- Revision 1.7 2005/04/17 12:45:52 niklas
-- Extended Compute_Usage so that, for a callee with an undefined
-- stack-usage bound, it uses instead an unsafe lower bound computed
-- from the initial value of the local stack height for the callee.
-- Changed all Output.Unknown messages to Output.Error.
--
-- Revision 1.6 2005/02/23 09:05:20 niklas
-- BT-CH-0005.
--
-- Revision 1.5 2005/02/20 15:15:36 niklas
-- BT-CH-0004.
--
-- Revision 1.4 2005/02/16 21:11:47 niklas
-- BT-CH-0002.
--
-- Revision 1.3 2004/06/25 14:49:32 niklas
-- Improved Calls_With_Unbounded_Take_Off to work and return an
-- empty list even when Item.Take_Off_Limits is null (as happens
-- for a subprogram with an asserted time).
--
-- Revision 1.2 2004/05/01 09:51:07 niklas
-- First Tidorum version.
-- Taking Cell_T stuff from Storage, not Arithmetic.
-- Added Analysis_Level_T item Universally_Bounded.
-- Added description of analysis level: WCET assertion, constant
-- propagation, sublevels Paths_Bounded, Time_Bounded, Failed.
-- Added operations Assert_Universal_Time and Assert_Path_Specific_Time
-- to indicate that a time-bound is asserted and not computed.
-- Tolerate irreducible subprograms as one kind of unbounded paths.
-- Add concepts of links (Link_T) between execution bounds.
-- Add attributes for Program_T and Assertion_Map_T to Execution Bounds.
-- This reduces the number of parameters that must be passed around.
-- Add edge and node times as Execution Bounds attributes so that they
-- can depend on call path.
-- Major extensions to stack-usage analysis, including definition and
-- safety levels and the concept of take-off stack height. Separate
-- between analysis for time bounds and analysis for space bounds.
-- Warn of an attempt to set a negative stack limit and substitute a
-- zero limit.
-- Cache "boundedness" state for Execution Bounds to avoid repeated
-- traversal of a bounds graph.
-- Removed the function Lowest_WCET. It was used only in ERC32 floating
-- point blocking analysis and is no longer needed there.
-- Added optional Trace output to some operations.
-- Added a variant of the function Bounds_For to get the execution
-- bounds on a root call.
-- Corrected Initialize_Bounds to always create the Call_Bounds and
-- the new Take_Off_Limits even if there are no calls. Thus these
-- components will be valid accesses to null vectors, rather than
-- null accesses.
--
-- Revision 1.1 2003/03/11 08:28:28 holsti
-- First version split off from the parent package Programs.
--
with Arithmetic;
with Bags; -- From MW Components.
with Flow.Calls;
with Flow.Calls.Opt;
with Flow.Pruning.Opt;
with Loops.Show;
with Output;
with Programs.Execution.Opt;
with Storage.List_Cell_Sets;
with Unbounded_Vectors;
package body Programs.Execution is
use type Node_Times_Ref;
use type Step_Edge_Times_Ref;
--
--- More elements for execution bounds objects:
--
type Initial_Values_T is access Storage.Bounds.Cell_Interval_List_T;
--
-- Initial bounds on cell-values upon entry to a subprogram.
type Looping_Bounds_T (Number : Loops.Loop_Count_T) is record
Loop_Starts : Loop_Bounds_T (1 .. Number);
Loop_Neck : Loop_Bounds_T (1 .. Number);
Loop_Repeats : Loop_Bounds_T (1 .. Number);
end record;
--
-- Bounds on looping, for each loop in the subprogram.
--
-- Loop_Starts
-- Bounds on the number of times the loop-head is entered
-- from outside the loop, for each execution of the subprogram
-- that contains the loop.
--
-- Loop_Neck
-- Bounds on the number of times the loop-body is entered
-- from the loop-head, for each time the loop-head is entered
-- from outside the loop (= number of times the loop is started).
--
-- Loop_Repeats
-- Bounds on the number of execution of the repeat edges
-- (back edges) that return to the loop-head from the loop-body,
-- for each time the loop is started.
--
-- A given loop can have a neck bound or a repeat bound or
-- both or neither; the stricter bound will constrain the
-- worst-case path.
type Take_Off_Limits_T is
array (Call_Index_T range <>, Stack_Index_T range <>)
of Stack_Limit_T;
--
-- Limits on local stack-height (take-off height) for all stacks and
-- all calls in a subprogram.
type Stack_Usages_T is array (Stack_Index_T range <>) of Stack_Usage_T;
--
-- A usage limit for each stack in the program.
type Final_Stack_Heights_T is
array (Stack_Index_T range <>) of Final_Stack_Height_T;
--
-- Bounds on the final (local) height for each stack in the program.
--
--- Cell sets, as used here
--
package Cell_Sets renames Storage.List_Cell_Sets;
--
-- The implementation of cell sets that we use.
subtype Cell_Set_T is Cell_Sets.Set_T;
--
-- For various sets of cells involved in execution bounds.
--
--- Execution bounds objects:
--
type Bounds_Object_T (
Level : Bounding_Level_T;
Max_Node : Flow.Node_Index_T;
Num_Calls : Natural;
Num_Stacks : Natural;
Num_Loops : Loops.Loop_Count_T)
is record
-- Identification:
Caller_Bounds : Bounds_Ref;
Subprogram : Subprogram_T;
Call_Path : Call_Path_T (1 .. Level);
Program : Program_T;
Index : Bounds_Index_T;
Locus : Output.Locus_T;
-- Goals:
For_Time : Boolean;
For_Space : Boolean;
-- Processor-specific information:
Info : Processor.Execution.Info_T;
-- Computation model:
Computation : aliased Flow.Computation.Model_Ref;
All_Cells : Cell_Set_T;
Value_Origins : Flow.Origins.Map_Ref;
-- Assertions:
Assertion_Map : Assertions.Assertion_Map_T;
Enough_For_Time : Boolean := False;
-- Data flow results:
Input_Cells : Cell_Set_T;
Input_Cell_Tally : Natural;
Inputs_Defined : Boolean;
Initial : Initial_Values_T;
Call_Inputs : Storage.Bounds.Bounds_List_T (1 .. Num_Calls);
Basis : Cell_Set_T;
Output_Cells : Cell_Set_T;
Outputs_Defined : Boolean;
-- Bounds on callees:
Call_Bounds : Call_Bounds_List_T (1 .. Num_Calls);
Stub_Level : Calling.Stub_Level_T;
-- Time per edge and node:
Step_Edge_Times : Step_Edge_Times_Ref;
Node_Times : Node_Times_Ref;
-- Execution-flow bounds (asserted or computed):
Node_Bounds : Node_Bounds_T (1..Max_Node);
Loop_Bounds : Looping_Bounds_T (Num_Loops);
Void_Flow_Bounds : Boolean;
-- Execution path results:
Flow_Counts : Flow_Counts_Ref;
-- Execution time results:
Time_State : Time_State_T;
Time_Calculated : Boolean;
Time : Processor.Time_T;
-- Final stack height results:
Final_Stack_Height : Final_Stack_Heights_T (1 .. Num_Stacks);
-- Stack usage results:
Stack_Height : Stack_Limits_T (1 .. Num_Stacks);
Max_Stack_Usage : Stack_Usages_T (1 .. Num_Stacks);
Take_Off_Limits : Take_Off_Limits_T (1 .. Num_Calls, 1 .. Num_Stacks);
-- Mutability and cached knowledge:
Frozen : Boolean := False;
end record;
--
-- Execution bounds with attributes as follows:
--
-- Level
-- The bounding level at which the bounds have been stored.
-- See the function Level for further explanation.
--
-- Max_Node
-- The number of nodes in the subprogram's flow-graph.
--
-- Num_Calls, Num_Stacks, Num_Loops
-- The number of calls from the Subprogram, the number
-- of Loops in the Subprogram, and the number of Stacks
-- in the program.
--
-- Caller_Bounds
-- A reference to the execution bounds on the caller of
-- this Subprogram, when this Bounds_Object applies to a
-- specific call in or longer context (call-path).
-- Null for context-independent (universal) bounds.
--
-- Subprogram
-- The subprogram to which these bounds apply.
--
-- Call_Path
-- The call-path to which the execution bounds apply,
-- through parameter values and assertions collected from
-- the calls on the call-path.
--
-- Program
-- The program under analysis, that contains the Subprogram.
--
-- Index
-- A unique sequential number assigned to execution bounds
-- as they are created, This identifying index is used to
-- avoid repeated display or processing of bounds that are
-- referred to from several higher-level bounds. For example,
-- universal bounds for a subprogram that is called from
-- several places.
--
-- Locus
-- The output locus, computed from the Subprogram and the
-- the Call_Path when the bounds are created, and not changed
-- thereafter, even if the flow-graph of the Subprogram is
-- extended (because these bounds cannot then apply to the
-- extended flow-graph).
--
-- For_Time
-- Whether we are seeking bounds on execution time.
--
-- For_Space
-- Whether we are seeking bounds on (stack) memory space,
-- and the Program under analysis has some stacks.
--
-- Computation
-- The computation model that underlies these bounds. This
-- model can be updated in-place, through a Model_Handle_T,
-- wherefore it is aliased.
--
-- All_Cells
-- All the cells statically named in the Computation model
-- (including cells used or defined in the effect of steps,
-- cells used in the preconditions of edges, basis cells for
-- dynamic memory references, dynamic edges and dynamic calling
-- protocols) and input cells for unbounded calls.
--
-- Value_Origins
-- The results of a value-origin analysis of the Computation,
-- showing for each cell, at each program point, the origin of
-- the value(s) that the cell can hold at that point.
--
-- Assertion_Map
-- The connection between user assertions (statements in the
-- assertion file, structures in the assertion set) and parts
-- of the Subprogram such as loops or calls.
--
-- Enough_For_Time
-- Whether we shall assume (by assertion) that there are enough
-- asserted execution-count bounds on parts of the Subprogram
-- to bound the execution path, thus giving a bound on the
-- worst-case execution time.
--
-- Input_Cells
-- The subset of input cells for Subprogram that was used to
-- derive the bounds. If the bounds are not complete, these
-- cells are needed as inputs to complete the bounding.
-- Valid only if Inputs_Defined is True.
--
-- Input_Cell_Tally
-- The number of cells in Input_Cells.
-- Valid only if Inputs_Defined is True.
--
-- Inputs_Defined
-- Whether Input_Cells is a valid cell-set (otherwise,
-- Input_Cells is an uninitialized variable and should not
-- be accessed).
--
-- Initial
-- The known initial bounds on cell values on entry.
--
-- Call_Inputs
-- Bounds on the input cells for each call, from the analysis
-- of the caller or from assertions.
--
-- Basis
-- The cells used for arithmetic analysis. Undefined
-- (Storage.No_Cell_Set) if arithmetic analysis was not
-- used to derive these bounds.
--
-- Output_Cells
-- The output cells from the Subprogram's execution under these
-- bounds. A cell is an output cell if it is the target of a
-- feasible assignment in the Subprogram's computation model and
-- is not detected nor asserted to be invariant across the
-- Subprogram's execution in spite of the assignment.
--
-- Call_Bounds
-- Execution bounds for calls to lower-level subprograms.
-- For execution bounds on calls that have been created for
-- the present context (that is, in the context of this
-- Bounds_Object) the Caller_Bounds of the Call_Bounds refers
-- to this Bounds_Object. Otherwise, the Call_Bounds were
-- inherited from a less specific (shallower) context.
--
-- Stub_Level
-- The stub level of these execution bounds. This component
-- is valid only for Frozen bounds; otherwise the stub level
-- should be computed from the feasible Call_Bounds.
--
-- Step_Edge_Times
-- The worst-case execution time of each edge in the flow-graph.
-- This is the single reference to this heap object.
--
-- Node_Times
-- The worst-case execution time of each node in the flow-graph.
-- This is the single reference to this heap object.
--
-- Node_Bounds
-- Bounds on the flow of execution, expressed as bounds
-- on the number of times each flow-graph node can be
-- executed.
-- Similar bounds on the execution of the flow-graph edges
-- are not implemented in general, only through the loop-
-- bounds.
--
-- Loop_Bounds
-- Repetition bounds for the loops in the subprogram.
--
-- Void_Flow_Bounds
-- Whether the Loop_Bounds or Node_Bounds give a void (null,
-- infeasible, contradictory) set of execution-counts for
-- some node or edge. If so, there is no feasible execution
-- path through the subprogram, under these execution bounds.
--
-- Flow_Counts
-- The worst-case execution path(s), represented by the
-- execution counts of the nodes and edges.
--
-- Time_State
-- The state of knowledge about Time, our upper bound on
-- the worst-case execution time.
--
-- Time_Calculated
-- Whether the last phase of the execution-time analysis, that
-- of finding the worst-case path and calculating the worst-case
-- execution time, has been applied to these execution bounds
-- (and, by implication, also to all callee bounds linked to
-- these caller bounds).
--
-- Time
-- An upper bound on the WCET of the subprogram, as
-- qualified by Time_State.
--
-- Final_Stack_Height
-- Bounds on the final (local) stack height on return from
-- this subprogram. In other words, bounds on the change in
-- local stack height over one execution of this subprogram,
-- from the entry point to any return point, including the
-- effect, if any, of the return instruction itself.
-- For a Stable stack the bounds are set to [0,0] when the
-- stack is created and are never changed thereafter.
-- For an Unstable stack the bounds are set to the Net_Change
-- specified when the stack is created and may then be changed
-- with procedure Bound_Final_Stack_Height.
--
-- Stack_Height
-- Bounds on the stack height local to this subprogram.
-- The stack-usage of lower-level subprogram is excluded.
--
-- Max_Stack_Usage
-- Total stack usage of this subprogram and lower-level
-- subprograms called here.
--
-- Take_Off_Limits
-- Limits on the take-off stack-height for all calls from
-- this subprogram to lower-level subprograms. Some of the
-- limits may be unknown. The take-off stack-height is the
-- caller's local stack-height immediately before control
-- is transferred to the callee.
--
-- Frozen
-- Whether the bounds are frozen (fixing some attributes)
-- a result of being stored in a bounds-set.
package Bounds_Vectors is new Unbounded_Vectors (
Element_Type => Bounds_Ref,
Vector_Type => Bounds_List_T,
Deallocate => Opt.Deallocate);
--
-- For storing the execution bounds for one subprogram.
-- A linear storage is used, since the number of bounds per
-- subprogram is not expected to be very large, and the look-up
-- time thus insignificant.
-- The key field is the Call_Path.
type Bounds_Vector_T is new Bounds_Vectors.Unbounded_Vector;
--
-- A list of bounds, usually the bounds for one subprogram.
type Bounds_Store_T is record
Subprogram : Subprogram_T;
Bounds : Bounds_Vector_T;
end record;
--
-- Holds all the bounds found for a given subprogram.
type Bounds_Store_Ref is access Bounds_Store_T;
--
-- An access type makes it easier to update a Bounds_Store that
-- is held within a Bounds_Set.
function Entry_Address (Item : Bounds_Store_Ref)
return Processor.Code_Address_T
--
-- The entry address of the subprogram to which the
-- given bounds apply.
--
is
begin
return Entry_Address (Item.Subprogram);
end Entry_Address;
package Bounds_Bags is new Bags (
Key_Type => Processor.Code_Address_T,
Item_Type => Bounds_Store_Ref,
Key_Of => Entry_Address,
"<" => Processor."<", -- for Code_Address_T
"=" => Processor."=", -- for Code_Address_T
Count => Natural);
--
-- For storing bounds in a set of bounds.
subtype Bounds_Bag_T is
Bounds_Bags.Bag (Duplicate_Keys_Allowed => False);
--
-- A set of execution bounds, grouped by the subprogram to which
-- they apply (keyed on Entry_Address).
type Bounds_Set_Object_T is record
Program : Program_T;
For_Time : Boolean;
For_Space : Boolean;
Bounds : Bounds_Bag_T;
Indexed : Bounds_Vector_T;
Next_Index : Bounds_Index_T := Bounds_Index_T'First;
Num_Links : Natural := 0;
end record;
--
-- A set of execution bounds for some subprograms in a target
-- program.
--
-- Program
-- The target program that was analyzed to get these bounds.
--
-- For_Time, For_Space
-- Whether we seek bounds on execution time, (stack) memory
-- space or both. For_Space is False if the Program under
-- analysis has no stacks.
--
-- Bounds
-- Execution bounds grouped by the subprogram and call-path
-- to which they apply.
--
-- Indexed
-- Execution bounds accessible by Bounds_Index_T.
--
-- Next_Index
-- A counter for generating unique index values.
--
-- Num_Links
-- The total number of links between bounds, represented by
-- all the Call_Bounds components of the Bounds.
function Bounds_Store_For (
Sub : Subprogram_T;
Within : Bounds_Set_T)
return Bounds_Store_Ref
--
-- The store (container) for the execution bounds derived for the
-- given subprogram within the given bounds set.
-- If the bound-set has no entry for this subprogram, one is created.
--
is
Store : Bounds_Store_Ref;
-- The bounds-store for the subprogram, or null.
begin
-- Find the bounds for this subprogram, if any:
begin
Store :=
Bounds_Bags.Search (
Key => Entry_Address (Sub),
Within => Within.Bounds);
exception
when Bounds_Bags.Nonexistent_Key =>
Store := new Bounds_Store_T;
Store.Subprogram := Sub;
-- The list of bounds is null by default.
Bounds_Bags.Insert (
Item => Store,
Into => Within.Bounds);
end;
-- Return the store:
return Store;
end Bounds_Store_For;
function Bounds_For (
Sub : Subprogram_T;
Within : Bounds_Set_T)
return Bounds_List_T
--
-- All the execution bounds derived for the given subprogram
-- within the given bounds set.
-- If bound-set has no entry for this subprogram, one is created.
--
is
begin
return To_Vector (Bounds_Store_For (Sub, Within).Bounds);
end Bounds_For;
--
--- Stub levels
--
Undefined_Stub_Level : exception;
--
-- Temporarily defined to understand why the Stub_Level function (below)
-- may be called with a null Bounds parameter.
function Stub_Level (Bounds : Bounds_Ref) return Calling.Stub_Level_T
is
use type Flow.Edge_Resolution_T;
begin
if not Defined (Bounds) then
Output.Fault (
Location => "Programs.Execution.Stub_Level (Bounds)",
Text => "Null bounds");
raise Undefined_Stub_Level;
end if;
if Bounds.Frozen then
-- We already know it.
return Bounds.Stub_Level;
elsif Stub (Bounds.Subprogram) then
-- I yam what I yam, and that's all there is.
return 0;
elsif Dynamic_Flow (Bounds) /= Flow.Stable then
-- There may be calls to stubs.
return 1;
else
-- I'm not a stub, but some of my best callees may be.
return Stub_Level (Call_Bounds (Bounds));
--
-- Note that only feasible calls are included here.
end if;
end Stub_Level;
function Unknown_Effect (Bounds : Bounds_Ref) return Boolean
is
begin
return Stub_Level (Bounds) < Calling.Calls_No_Stub;
exception
when Undefined_Stub_Level =>
Output.Fault (
Location => "Programs.Execution.Unknown_Effect",
Text => "Null Bounds");
raise;
end Unknown_Effect;
--
--- Call bounds
--
function Stub_Level (Call : Call_Bounds_T) return Calling.Stub_Level_T
is
Callee_Level : constant Calling.Stub_Level_T := Stub_Level (Call.Bounds);
begin
if Callee_Level = Calling.Calls_No_Stub then
-- No stubs called there -- no stubs called here.
return Calling.Calls_No_Stub;
elsif Callee_Level + 1 /= Calling.Calls_No_Stub then
-- A stub call is further down -- but not infinitely deep.
return Callee_Level + 1;
else
-- A really deep call path.
Output.Fault (
Location => "Programs.Execution.Stub_Level (Call_Bounds)",
Locus => Locus (Call.Call),
Text => "Level overflow.");
return Callee_Level;
end if;
exception
when Undefined_Stub_Level =>
Output.Fault (
Location => "Programs.Execution.Stub_Level (Call)",
Locus => Locus (Call.Call),
Text => "Null Call.Bounds");
raise;
end Stub_Level;
function Calls_Of (List : Call_Bounds_List_T) return Call_List_T
is
Calls : Programs.Call_List_T (List'Range);
-- The result.
begin
for L in List'Range loop
Calls(L) := List(L).Call;
end loop;
return Calls;
end Calls_Of;
function Bounds_Of (List : Call_Bounds_List_T)
return Bounds_List_T
is
Bounds : Bounds_List_T (List'Range);
-- The result.
begin
for L in List'Range loop
Bounds(L) := List(L).Bounds;
end loop;
return Bounds;
end Bounds_Of;
function Stub_Level (List : Call_Bounds_List_T)
return Calling.Stub_Level_T
is
Min_Level : Calling.Stub_Level_T := Calling.Calls_No_Stub;
-- The minimum level of the List.
begin
for L in List'Range loop
begin
Min_Level := Calling.Stub_Level_T'Min (
Min_Level,
Stub_Level (List(L)));
exception
when Undefined_Stub_Level =>
Output.Fault (
Location => "Programs.Execution.Stub_Level (Call_Bounds_List)",
Locus => Locus (List(L).Call),
Text => "Null bounds");
end;
end loop;
return Min_Level;
end Stub_Level;
--
--- Links between bounds
--
function Link (
From : Bounds_Ref;
Via : Call_T)
return Link_T
is
begin
return (
Call => Via,
Caller => From,
Callee => Call_Bounds (On => Via, Within => From));
end Link;
function Caller_Bounds (Item : Link_T) return Bounds_Ref
is
begin
return Item.Caller;
end Caller_Bounds;
function Callee_Bounds (Item : Link_T) return Bounds_Ref
is
begin
return Item.Callee;
end Callee_Bounds;
function Call (Item : Link_T) return Call_T
is
begin
return Item.Call;
end Call;
function No_Links return Link_List_T
is
begin
return (1 .. 0 => (No_Call, No_Bounds, No_Bounds));
end No_Links;
function Locus (Item : Bounds_Ref)
return Output.Locus_T
is
begin
return Item.Locus;
end Locus;
function Locus (Luup : Loops.Loop_T; Within : Bounds_Ref)
return Output.Locus_T
is
begin
return Loops.Show.Locus (
Luup => Luup,
Within => Flow_Graph (Subprogram (Within)),
Source => Symbol_Table (Within));
end Locus;
function Locus (Call : Call_T; Within : Bounds_Ref)
return Output.Locus_T
is
use type Output.Locus_T;
Full_Path : constant Call_Path_T := Call_Path (Within) & Call;
-- The full call path, including the Call.
begin
if Subprogram (Within) /= Caller (Call) then
Output.Fault (
Location => "Programs.Execution.Locus (Call, Bounds)",
Text =>
"Bounds for "
& Name (Subprogram (Within))
& ", call from "
& Name (Caller (Call)));
end if;
return Locus (Within) & Locus (Full_Path);
end Locus;
--
--- Constructing and querying execution bounds sets
--
procedure Initialize_Bounds_Set (
Program : in Program_T;
For_Time : in Boolean;
For_Space : in Boolean;
Set : in out Bounds_Set_T)
is
begin
-- TBA deallocation of old value.
Set := new Bounds_Set_Object_T;
Set.Program := Program;
Set.For_Time := For_Time;
Set.For_Space := For_Space
and Number_Of_Stacks (Program) > 0;
end Initialize_Bounds_Set;
function Program (Item : Bounds_Set_T) return Program_T
is
begin
return Item.Program;
end Program;
function Number_Of_Bounds (Within : Bounds_Set_T)
return Bounds_Count_T
is
begin
if Within = null then
-- The bounds-set is not initialized.
return 0;
else
return Within.Next_Index - 1;
end if;
end Number_Of_Bounds;
function Number_Of_Bounds (
Sub : Subprogram_T;
Within : Bounds_Set_T)
return Natural
is
begin
return Last (Bounds_Store_For (Sub, Within).Bounds);
end Number_Of_Bounds;
function Bound_At (
Index : Bounds_Index_T;
Within : Bounds_Set_T)
return Bounds_Ref
is
begin
return Element (Vector => Within.Indexed, Index => Positive (Index));
end Bound_At;
procedure Check_Usage_Vs_Height (
Stack : in String;
Usage : in Stack_Usage_T;
Height : in Stack_Limit_T)
--
-- Checks that the upper bound on the local stack Height is
-- no larger than the upper bound on the total stack Usage.
--
is
use Storage.Bounds;
use type Arithmetic.Value_T;
begin
if (Bounded (Usage) and Known (Height.Max))
and then
Usage.Height < Value (Height.Max)
then
Output.Error (
"Local stack height "
& Arithmetic.Image (Value (Height.Max))
& " exceeds total stack usage "
& Arithmetic.Image (Usage.Height)
& " for "
& Stack);
end if;
end Check_Usage_Vs_Height;
procedure Store_Bounds (
Bounds : in Bounds_Ref;
Within : in Bounds_Set_T)
is
Subprogram : constant Subprogram_T := Execution.Subprogram (Bounds);
-- The subprogram to which the Bounds apply.
Store : constant Bounds_Store_Ref :=
Bounds_Store_For (Sub => Subprogram, Within => Within);
-- The bounds-store for this subprogram.
Autograph : constant String := "Programs.Execution.Store_Bounds";
-- For Faults.
Callee_Bounds : Bounds_Ref;
-- Bounds on a call.
begin
-- Verify that the goals are compatible:
if Within.For_Time and not Bounds.For_Time then
Output.Fault (
Location => Autograph,
Text => "New bounds are not for time.");
end if;
if Within.For_Space and not Bounds.For_Space then
Output.Fault (
Location => Autograph,
Text => "New bounds are not for space.");
end if;
-- Put the Bounds in the bag:
Append (
To => Store.Bounds,
Value => Bounds);
-- Update the number of links to include the calls in Bounds:
Within.Num_Links := Within.Num_Links + Bounds.Call_Bounds'Length;
-- Put the Bounds in the Indexed vector, padding unused indices
-- with nulls:
for I in Last (Within.Indexed) + 1 .. Positive (Bounds.Index) - 1 loop
Set (
Vector => Within.Indexed,
Index => I,
To => No_Bounds);
end loop;
Set (
Vector => Within.Indexed,
Index => Positive (Bounds.Index),
To => Bounds);
-- Check the state of bounding:
if Bounds.For_Time then
case Bounds.Time_State is
when Undefined =>
Output.Fault (
Location => Autograph,
Text =>
"Freezing bounds #"
& Bounds_Index_T'Image (Bounds.Index)
& " with time-state "
& Time_State_T'Image (Bounds.Time_State));
when others =>
null;
end case;
end if;
-- TBA Bounds.For_Space.
for S in 1 .. Bounds.Num_Stacks loop
Check_Usage_Vs_Height (
Stack => Stack_Name (S, Program (Bounds)),
Usage => Bounds.Max_Stack_Usage(S),
Height => Bounds.Stack_Height(S));
end loop;
-- Check that linked bounds on calls are stored:
for C in Bounds.Call_Bounds'Range loop
Callee_Bounds := Bounds.Call_Bounds(C).Bounds;
if not Callee_Bounds.Frozen then
Output.Fault (
Location => Autograph,
Text =>
"Freezing bounds #"
& Bounds_Index_T'Image (Bounds.Index)
& " with unfrozen call-bounds #"
& Bounds_Index_T'Image (Callee_Bounds.Index));
end if;
end loop;
-- Freeze the Bounds:
if Bounds.Frozen then
Output.Fault (
Location => Autograph,
Text =>
"Bounds #"
& Bounds_Index_T'Image (Bounds.Index)
& " are already Frozen.");
end if;
-- Record the final Stub Level:
Bounds.Stub_Level := Stub_Level (Bounds);
Output.Note (
Locus => Locus (Bounds),
Text =>
"Freezing bounds #"
& Bounds_Index_T'Image (Bounds.Index));
Bounds.Frozen := True;
end Store_Bounds;
function Bound_At (
Index : Positive;
Sub : Subprogram_T;
Within : Bounds_Set_T)
return Bounds_Ref
is
begin
return Element (Bounds_Store_For (Sub, Within).Bounds, Index);
end Bound_At;
function Bounds_For (
Root : Call_T;
Within : Bounds_Set_T)
return Bounds_Ref
is
begin
return Bounds_For (
Subprogram => Callee (Root),
Within => Within,
Along => (1 => Root));
end Bounds_For;
function Bounds_For (
Subprogram : Subprogram_T;
Within : Bounds_Set_T;
Along : Call_Path_T)
return Bounds_Ref
is
Bounds : constant Bounds_List_T :=
Bounds_For (
Sub => Subprogram,
Within => Within);
-- All the bounds known for the subprogram.
Best : Bounds_Ref := No_Bounds;
-- The best (most specific) bounds found so far.
-- Null if no applicable bounds found.
Best_Full : Boolean := False;
-- Whether the Best bounds are fully bounded.
Bounds_Full : Boolean;
-- Whether the bounds under consideration are fully bounded.
begin
for B in Bounds'Range loop
if Bounds(B).Call_Path <= Along then
-- These bounds are applicable.
Bounds_Full := Bounded (Bounds(B));
if Best = No_Bounds
-- First applicable bounds found, best so far.
or else (Bounds_Full and not Best_Full)
-- Full bounds are better.
or else ( Bounds_Full = Best_Full
and Bounds(B).Level > Best.Level)
-- More specific bounds are better.
then
Best := Bounds(B);
Best_Full := Bounds_Full;
end if;
end if;
end loop;
return Best;
end Bounds_For;
function Bounds_For_Calls (
From : Subprogram_T;
Within : Bounds_Set_T)
return Call_Bounds_List_T
is
Calls : constant Call_List_T := Programs.Calls_From (From);
-- All the calls from the subprogram.
Call : Call_T;
-- One of the Calls.
Bounds : Bounds_Ref;
-- Some bounds for the Call.
Call_Bounds : Call_Bounds_List_T (Calls'Range);
-- The result to be.
begin
for C in Calls'Range loop
Call := Calls(C);
Bounds := Bounds_For (
Subprogram => Callee (Call),
Within => Within,
Along => (1 => Call));
if Bounds = No_Bounds then
Output.Fault (
Location => "Programs.Execution.Bounds_For_Calls",
Locus => Locus (Call),
Text => "No execution bounds known.");
end if;
Call_Bounds(C) := (Call => Call, Bounds => Bounds);
end loop;
return Call_Bounds;
end Bounds_For_Calls;
function Root_Bounds (Within : Bounds_Set_T)
return Call_Bounds_List_T
is
Roots : constant Call_List_T := Root_Calls (Within.Program);
-- The root calls.
Result : Call_Bounds_List_T (Roots'Range);
-- The result: root calls with universal bounds.
begin
for R in Roots'Range loop
Result(R) := (
Call => Roots(R),
Bounds => Bounds_For (Roots(R), Within));
end loop;
return Result;
end Root_Bounds;
function Number_Of_Links (Within : Bounds_Set_T)
return Natural
is
begin
return Within.Num_Links;
end Number_Of_Links;
function All_Links (
From : Call_List_T;
Within : Bounds_Set_T)
return Link_List_T
is
Links : Link_List_T (1 .. Within.Num_Links);
Last : Natural := 0;
-- The result will be Links(1 .. Last).
Done : Bounds_Subset_T (Max_Size => Number_Of_Bounds (Within));
-- The bounds that have been scanned for links.
procedure Add_Links (From : in Bounds_Ref)
--
-- Adds all links represented by From.Call_Bounds to the
-- result, and proceeds recursively to lower calls.
-- No operation if From was already Done.
--
is
CB : Call_Bounds_T;
-- One of From's call-bounds.
begin
if (not Is_Member (From, Done))
and From.Call_Bounds'Length > 0
then
-- The From bounds need processing.
Add (Item => From, To => Done);
for C in From.Call_Bounds'Range loop
CB := From.Call_Bounds(C);
Last := Last + 1;
Links(Last) := (
Call => CB.Call,
Caller => From,
Callee => CB.Bounds);
Add_Links (From => CB.Bounds);
end loop;
end if;
end Add_Links;
begin -- All_Links
for F in From'Range loop
Add_Links (
From =>
Bounds_For (
Root => From(F),
Within => Within));
end loop;
return Links(1 .. Last);
end All_Links;
--
--- Constructing execution bounds
--
function To_Stack_Limit (Item : Storage.Bounds.Interval_T)
return Stack_Limit_T
is
begin
return Stack_Limit_T (Item);
end To_Stack_Limit;
Unlimited : constant Stack_Limit_T :=
To_Stack_Limit (Storage.Bounds.Universal_Interval);
--
-- Default value for all local stack-height limits.
procedure Create_Blank_Bounds (
Subprogram : in Subprogram_T;
Call_Path : in Call_Path_T;
Caller : in Bounds_Ref;
For_Time : in Boolean;
For_Space : in Boolean;
Within : in Bounds_Set_T;
Bounds : out Bounds_Ref)
--
-- Creates a blank set of execution bounds for this subprogram
-- and call-path. The bounds are not yet attached to the subprogram.
-- However, the bounds-index counter is incremented.
--
is
use type Output.Locus_T;
Stacks : constant Stacks_T := Programs.Stacks (Program (Within));
-- All the stacks in the program.
begin
Bounds := new Bounds_Object_T (
Level => Call_Path'Length,
Max_Node => Flow.Max_Node (Flow_Graph (Subprogram)),
Num_Calls => Number_Of_Calls_From (Subprogram),
Num_Loops => Number_Of_Loops (Subprogram),
Num_Stacks => Stacks'Length);
Bounds.Caller_Bounds := Caller;
Bounds.Subprogram := Subprogram;
Bounds.Call_Path := Call_Path;
Bounds.Program := Program (Within);
Bounds.Index := Within.Next_Index;
if Call_Path'Length = 0 then
Bounds.Locus := Locus (Subprogram);
else
Bounds.Locus :=
Output.Locus (Call_Path => Image (Call_Path))
& Locus (Subprogram);
end if;
Bounds.For_Time := For_Time;
Bounds.For_Space := For_Space and Bounds.Num_Stacks > 0;
-- Bounds.Computation is initialized by default to "none".
Bounds.All_Cells := Cell_Sets.Empty;
Bounds.Assertion_Map := Assertions.No_Map;
-- Bounds.Enough_For_Time is False by default.
Bounds.Input_Cells := Cell_Sets.Empty;
Bounds.Input_Cell_Tally := 0;
Bounds.Inputs_Defined := False;
-- Bounds.Initial is null by default.
Bounds.Call_Inputs := (others => Storage.Bounds.No_Bounds);
Bounds.Basis := Cell_Sets.Empty;
Bounds.Output_Cells := Cell_Sets.Empty;
Bounds.Outputs_Defined := False;
for C in 1 .. Bounds.Num_Calls loop
Bounds.Call_Bounds(C) := (
Call => Call (From => Subprogram, Index => C),
Bounds => null);
end loop;
Bounds.Stub_Level := Calling.Calls_No_Stub;
-- Dummy value, not valid until bounds are frozen.
Bounds.Step_Edge_Times := null;
Bounds.Node_Times := null;
Bounds.Node_Bounds := (
others => (Min => 0,
Max => Flow.Execution.Infinite));
Bounds.Loop_Bounds.Loop_Starts := (others => Flow.Execution.Unbounded);
Bounds.Loop_Bounds.Loop_Neck := (others => Flow.Execution.Unbounded);
Bounds.Loop_Bounds.Loop_Repeats := (others => Flow.Execution.Unbounded);
Bounds.Void_Flow_Bounds := False;
Bounds.Flow_Counts := null;
Bounds.Time_State := Undefined;
Bounds.Time_Calculated := False;
Bounds.Time := 0;
for S in Stacks'Range loop
Bounds.Final_Stack_Height(S) := To_Stack_Limit (
Storage.Bounds.One_Or_All (Net_Change (Stacks(S))));
Bounds.Stack_Height(S) := Unlimited;
end loop;
Bounds.Max_Stack_Usage := (others => (
State => Undefined,
Height => 0,
Call => No_Call));
Bounds.Take_Off_Limits := (others => (others => Unlimited));
-- Bounds.Frozen is False by default.
Within.Next_Index := Within.Next_Index + 1;
end Create_Blank_Bounds;
function Call_Invariants (
Call : Call_T;
Within : Bounds_Ref)
return Storage.Cell_List_T
--
-- The cells asserted as invariant for this Call, Within the
-- given execution bounds for the caller, or a null list if
-- no assertion map is known Within the caller's bounds.
--
is
use type Assertions.Assertion_Map_T;
begin
if Within.Assertion_Map = Assertions.No_Map then
return Storage.Null_Cell_List;
else
return Assertions.Call_Invariants (Call, Within.Assertion_Map);
end if;
end Call_Invariants;
procedure Compute_Effect (
Call_Bounds : in Call_Bounds_T;
Within : in Bounds_Ref;
Caller_Cells : in Storage.Cell_List_T)
--
-- Computes the effect of the Call on the computation Within the
-- caller's bounds. A Call with (partially) unknown effect (due to
-- stub callees) may change some of the Caller_Cells. We assume
-- that Caller_Cells already contains all the caller cells that may
-- be assigned by the Call, also the known outputs from the Call.
--
is
use type Storage.Cell_List_T;
Call : constant Call_T := Call_Bounds.Call;
-- For brevity.
Model : Flow.Computation.Model_Ref renames Within.Computation;
-- For brevity.
Protocol : constant Calling.Protocol_Ref :=
Flow.Computation.Calling_Protocol (Call, Model);
-- The calling protocol.
Effect : Arithmetic.Assignment_Set_T (
Max_Size => Caller_Cells'Length
+ Programs.Number_Of_Stacks (
Flow.Computation.Program (Model))
+ 1);
-- For collecting the effect.
-- The "+ 1" is to make the size positive.
Mark : Output.Nest_Mark_T;
-- Locus for the Call_Bounds.
begin
Mark := Output.Nest (Locus (Call_Bounds.Call));
-- The known outputs, except for invariant cells and
-- stack-pointer cells:
Flow.Calls.Add_Call_Effect (
Call => Call,
Protocol => Protocol.all,
Outputs => Output_Cells (Call_Bounds.Bounds),
Invariant => Call_Invariants (Call, Within)
& Stack_Pointer_Cells (Program (Within)),
To => Effect);
-- The net changes in local stack heights and stack pointers:
Arithmetic.Add (
To => Effect,
More => Final_Stack_Effect (Call_Bounds.Bounds));
-- The unknown outputs:
if Unknown_Effect (Call_Bounds.Bounds) then
-- Check which Caller_Cells may be affected by the
-- unknown effects of the callee.
Flow.Calls.Add_Unknown_Call_Effect (
Call => Call,
Protocol => Protocol.all,
Stub => Stub_Level (Call_Bounds.Bounds),
Upon => Caller_Cells,
To => Effect);
end if;
-- And there we have it:
Flow.Computation.Set_Effect (
Step => Step (Call),
To => Arithmetic.To_Effect_Ref (Effect),
Under => Model);
Output.Unnest (Mark);
exception
when others =>
Output.Unnest (Mark);
raise;
end Compute_Effect;
procedure Compute_Call_Effects (
Calls : in Call_Bounds_List_T;
Within : in Bounds_Ref)
--
-- Defines the effects of the call steps for the given Calls, Within
-- the given execution bounds of the caller.
--
-- The effect of a call (that is, the effect of the call step) is to
-- assign opaque values to all those cells, Within.All_Cells, that
-- may be altered by the execution of the call.
--
-- Precondition: Within.All_Cells is up to date.
--
is
All_Cells : constant Storage.Cell_List_T :=
Cell_Sets.To_List (Within.All_Cells);
-- All the cells referenced in the caller.
begin
for C in Calls'Range loop
Compute_Effect (
Call_Bounds => Calls(C),
Within => Within,
Caller_Cells => All_Cells);
end loop;
end Compute_Call_Effects;
procedure Initialize_Bounds (
For_Time : in Boolean;
For_Space : in Boolean;
Subprogram : in Subprogram_T;
Along : in Call_Path_T;
Caller : in Bounds_Ref;
Within : in Bounds_Set_T;
Bounds : out Bounds_Ref)
is
Earlier_Bounds : constant Bounds_Ref :=
Bounds_For (Subprogram, Within, Along);
-- The most relevant bounds known for this Subprogram and
-- this call-path. If such bounds exist, they are probably
-- incomplete (not fully bounded) and apply to a suffix of
-- the call-path, not to the whole call-path. If Along is
-- not null, at least "universal" earlier bounds should exist.
procedure Find_Call_Bounds (Call_Bounds : in out Call_Bounds_T)
--
-- Sets Call_Bounds.Bounds to the best bounds currently known
-- for Call_Bounds.Call in this context. Check if the call
-- can return to the caller, under these bounds.
--
is
Path : constant Call_Path_T := Along & Call_Bounds.Call;
-- The calling context.
Step : constant Flow.Step_T := Programs.Step (Call_Bounds.Call);
-- The call-step.
begin
Call_Bounds.Bounds := Bounds_For (
Subprogram => Callee (Call_Bounds.Call),
Within => Within,
Along => Path);
if not Flow.Computation.Is_Feasible (Step, Bounds.Computation) then
-- This call is already known to be infeasible, so we will
-- not worry if its bounds are undefined.
null;
elsif Call_Bounds.Bounds = No_Bounds then
Output.Fault (
Location =>
"Programs.Execution.Initialize_Bounds.Find_Call_Bounds",
Locus => Locus (Path),
Text => "No execution bounds known.");
else
if Opt.Trace_Bounds then
Output.Trace (
Locus => Locus (Bounds),
Text =>
"Link from bounds #"
& Bounds_Index_T'Image (Index (Bounds))
& " to bounds #"
& Bounds_Index_T'Image (Index (Call_Bounds.Bounds))
& " at "
& Image (Call_Bounds.Call));
end if;
if not Is_Feasible (Call_Bounds.Bounds) then
-- This callee cannot be executed under those call bounds,
-- so the call itself must be held infeasible.
if Flow.Pruning.Opt.Warn_Unreachable then
Output.Warning (
Locus => Locus (Path),
Text => "Callee is unused or infeasible.");
end if;
Flow.Computation.Mark_Infeasible (Step, Bounds.Computation);
elsif not Returns (Call_Bounds.Bounds) then
if Flow.Calls.Opt.Warn_No_Return then
Output.Warning (
Locus => Locus (Path),
Text => "Non-returning call.");
end if;
Flow.Computation.Mark_No_Return (
From => Call_Bounds.Call,
To => Bounds.Computation);
end if;
end if;
end Find_Call_Bounds;
begin -- Initialize_Bounds
if Along'Length > 0 then
-- We expect certain things:
if Callee (Along(Along'Last)) /= Subprogram then
Output.Fault (
Location => "Programs.Execution.Initialize_Bounds",
Locus => Locus (Along),
Text =>
"Last callee is not "
& Index_And_Name (Subprogram));
end if;
if Earlier_Bounds = null then
Output.Fault (
Location => "Programs.Execution.Initialize_Bounds",
Locus => Locus (Along),
Text =>
"No earlier bounds exist for "
& Index_And_Name (Subprogram));
end if;
end if;
-- Create blank bounds:
Create_Blank_Bounds (
For_Time => For_Time,
For_Space => For_Space,
Subprogram => Subprogram,
Call_Path => Along,
Caller => Caller,
Within => Within,
Bounds => Bounds);
if Opt.Trace_Bounds then
Output.Trace (
Locus => Locus (Bounds),
Text =>
"Created bounds #"
& Bounds_Index_T'Image (Index (Bounds))
& " with"
& Loops.Loop_Count_T'Image (Bounds.Num_Loops)
& " loops and"
& Natural'Image (Bounds.Num_Calls)
& " calls.");
if Caller /= null then
Output.Trace (
Locus => Locus (Bounds),
Text =>
"Called from bounds #"
& Bounds_Index_T'Image (Index (Caller)));
end if;
if Earlier_Bounds /= null then
Output.Trace (
Locus => Locus (Bounds),
Text =>
"Based on earlier bounds #"
& Bounds_Index_T'Image (Index (Earlier_Bounds))
& " for path "
& Image (Call_Path (Earlier_Bounds)));
end if;
end if;
-- Initialization depending on the earlier bounds if any:
if Earlier_Bounds = null then
-- There are no relevant earlier (more universal) bounds.
-- We start from the "primitive" computation model.
Flow.Computation.Refer_To_Primitive_Model (
Subprogram => Subprogram,
Model => Bounds.Computation);
--
-- Note that this model considers all calls to have a
-- new (changed) calling protocol, which means that the
-- effects of all calls will be computed in the next call
-- (below) of Note_Updated_Computation.
Bounds.All_Cells := Cell_Sets.Empty;
--
-- We compute this set later, when we know which calls
-- are unbounded and so can include their input cells.
-- See call of Note_Updated_Computation below.
-- We add the effects of the calls later below.
else
-- We have some earlier (more universal) bounds, so we
-- start from the computation model used in those bounds,
-- including the effects of the calls.
Flow.Computation.Refer (
From => Bounds.Computation,
To => Earlier_Bounds.Computation);
-- The same cells are used as in the earlier bounds:
Bounds.All_Cells := Earlier_Bounds.All_Cells;
-- Input bounds for calls are reused:
Bounds.Call_Inputs := Earlier_Bounds.Call_Inputs;
end if;
-- If the subprogram has some calls to lower-level subprograms,
-- we set up the bounds for these calls, using the best bounds
-- currently known for the callees in this context:
for C in Bounds.Call_Bounds'Range loop
Find_Call_Bounds (Bounds.Call_Bounds(C));
end loop;
-- If there are no earlier bounds, the effects of the calls
-- must be computed ab initio:
if Earlier_Bounds = null then
-- The Model did not inherit the effects of the Calls, so we
-- compute them now and add them to the computation model.
-- This also computes Bounds.All_Cells.
Note_Updated_Computation (Within => Bounds);
Flow.Computation.Mark_Clean (Bounds.Computation);
end if;
-- TBD inherit loop bounds from Earlier_Bounds?
end Initialize_Bounds;
procedure Initialize_Universal_Bounds (
Subprogram : in Subprogram_T;
Within : in Bounds_Set_T;
Bounds : out Bounds_Ref)
is
begin
Initialize_Bounds (
For_Time => Within.For_Time,
For_Space => Within.For_Space,
Subprogram => Subprogram,
Along => Null_Call_Path,
Caller => null,
Within => Within,
Bounds => Bounds);
end Initialize_Universal_Bounds;
procedure Adopt_To_Context (
Call : in Call_T;
Caller : in Bounds_Ref;
Within : in Bounds_Set_T;
Giving : out Bounds_Ref)
is
Original : constant Bounds_Ref :=
Call_Bounds (On => Call, Within => Caller);
-- The current execution bounds on the Call, within the Caller
-- bounds. Either inherited from a shallower context, or
-- already specialized to these Caller bounds.
Deeper : constant Call_List_T := Calls_Of (Call_Bounds (Original));
-- The calls from the callee to deeper subprograms.
Stack : Stack_T;
-- One of the stacks in the program.
Deep : Call_T;
-- One of the Deeper calls.
begin
if Original.Caller_Bounds = Caller then
-- Already context-specific to these Caller bounds.
Giving := Original;
else
-- The Original bounds are inherited from another context.
-- We must copy them before we can enter information
-- specific to this Caller context.
if Opt.Trace_Bounds then
Output.Trace (
"Adopting bounds #"
& Bounds_Index_T'Image (Index (Original))
& " into caller bounds #"
& Bounds_Index_T'Image (Index (Caller)));
end if;
Initialize_Bounds (
For_Time => For_Time (Original),
For_Space => For_Space (Original),
Subprogram => Subprogram (Original),
Along => Call_Path (Caller ) & Call,
Caller => Caller,
Within => Within,
Bounds => Giving);
-- Copy the path and execution-time bounds, if any:
case Time_State (Original) is
when Undefined =>
if For_Time (Original) then
Output.Fault (
Location => "Programs.Execution.Adopt_To_Context",
Locus => Locus (Call, Caller),
Text => "Callee Time State is UNDEFINED.");
end if;
when Depends | Unbounded | Failed =>
-- We can hope for better success in the new context.
-- Setting the state to Undefined allows a new start.
Set_Time_State (
To => Undefined,
Within => Giving);
when Vague | Infeasible =>
-- A new context cannot help.
Set_Time_State (
To => Time_State (Original),
Within => Giving);
when Time_Boundable_T =>
Giving.Node_Bounds := Original.Node_Bounds;
Giving.Loop_Bounds := Original.Loop_Bounds;
Giving.Void_Flow_Bounds := Original.Void_Flow_Bounds;
if Time_State (Original) in Time_Bounded_T then
Bound_Time (
Time => Time (Original),
State => Time_State (Original),
Within => Giving);
else
Set_Time_State (
To => Time_State (Original),
Within => Giving);
end if;
end case;
-- Copy the stack bounds, if any:
for S in 1 .. Original.Num_Stacks loop
Stack := Stack_By (Index => S, Within => Program (Original));
-- Local height:
if Stack_Height_Bounded (Stack, Original) then
Bound_Stack_Height (
Stack => Stack,
To => Stack_Height (Stack, Original),
Within => Giving,
Silent => True);
end if;
-- Usage:
Stack := Stack_By (Index => S, Within => Program (Original));
if Stack_Usage_Bounded (Stack, Original) then
Bound_Stack_Usage (
Stack => Stack,
To => Stack_Usage (Stack, Original),
Within => Giving,
Silent => True);
end if;
-- Final height:
if Final_Stack_Height_Known (Stack, Original) then
Bound_Final_Stack_Height (
Stack => Stack,
To => Final_Stack_Height (Stack, Original),
Within => Giving,
Silent => True);
end if;
-- Take-off height for deeper calls:
for D in Deeper'Range loop
Deep := Deeper(D);
if Take_Off_Height_Bounded (Stack, Deep, Original) then
Bound_Take_Off_Height (
Stack => Stack,
Before => Deep,
To => Take_Off_Height (Stack, Deep, Original),
Within => Giving,
Silent => True);
end if;
end loop;
end loop;
-- Copy the processor-specific info:
Set_Processor_Info (
To => Processor_Info (Original),
Within => Giving);
-- Copy the input and output cell-sets:
Set_Input_Cells (
To => Original.Input_Cells,
Within => Giving);
Set_Output_Cells (
To => Original.Output_Cells,
Within => Giving);
-- Copy the (reference to the) assertion map:
Giving.Assertion_Map := Original.Assertion_Map;
-- And these are the new bounds on the Call:
Bound_Call (
Call => Call,
Bounds => Giving,
Within => Caller);
end if;
end Adopt_To_Context;
procedure Set_Processor_Info (
To : in Processor.Execution.Info_T;
Within : in Bounds_Ref)
is
begin
Within.Info := To;
end Set_Processor_Info;
function All_Cells (Within : Bounds_Ref) return Storage.Cell_List_T
is
begin
return Cell_Sets.To_List (Within.All_Cells);
end All_Cells;
procedure Check_Mutability (Bounds : in Bounds_Ref)
--
-- Checks that the Bounds are not Frozen. Emits a Fault
-- message if they are Frozen.
--
is
begin
if Bounds.Frozen then
Output.Fault (
Location => "Programs.Execution.Check_Mutability",
Text =>
"Bounds #"
& Bounds_Index_T'Image (Bounds.Index)
& " are Frozen.");
end if;
end Check_Mutability;
function Computation_Changed (Within : Bounds_Ref)
return Boolean
is
begin
return Flow.Computation.Changed (Within.Computation);
end Computation_Changed;
procedure Note_Updated_Computation (Within : in Bounds_Ref)
is
use type Cell_Set_T;
Model : Flow.Computation.Model_Ref renames Within.Computation;
-- The updated computation model.
Calls : constant Call_Bounds_List_T := Call_Bounds (Within);
-- The feasible calls and their bounds, Within these caller bounds.
-- Some of these calls may become infeasible from later analysis
-- of the updated computation model.
Call : Programs.Call_T;
-- One of the Calls.
Calls_To_Compute : Call_Bounds_List_T (1 .. Calls'Length);
Last : Natural := 0;
-- The calls for which the effect must be recomputed will be
-- in Calls_To_Compute(1 .. Last).
New_All_Cells : Cell_Set_T;
-- The new set of referenced cells.
New_Inputs, New_Outputs : Cell_Set_T;
-- The new set of input and output cells for significant calls.
Cell_Set_Changed : Boolean;
-- Whether the set of referenced cells has changed.
begin
-- Update the set of all referenced cells:
-- First we find the currently known inputs of all unbounded calls,
-- using the current (possibly updated) calling protocols:
Add_Inputs_For_Unbounded_Calls (
Within => Within,
To => New_Inputs);
-- Next we find the currently known outputs of all (feasible)
-- calls, using the current (possibly updated) calling protocols:
for C in Calls'Range loop
Call := Calls(C).Call;
Cell_Sets.Add (
Cells => Flow.Calls.Output_Cells (
Call => Call,
Protocol => Flow.Computation.Calling_Protocol (Call, Model).all,
Outputs => Output_Cells (Calls(C).Bounds),
Invariant => Call_Invariants (Call, Within)),
To => New_Outputs);
end loop;
-- We then find the cells referenced in the real steps of
-- the computation, and ignore the existing (old and possibly
-- irrelevant) effects of call steps. Note that the new protocols
-- may have created entirely new cells (Cell_T); by initializing
-- our new Cell_Set_T here, it is sure to have space for these
-- new cells, too.
New_All_Cells := Cell_Sets.Copy (
Flow.Computation.Cells_In (
Model => Within.Computation,
Calls => False));
-- And finally we combine all of the above:
Cell_Sets.Add (
Cells => New_Inputs,
To => New_All_Cells);
Cell_Sets.Add (
Cells => New_Outputs,
To => New_All_Cells);
-- The lists of new inputs and outputs are no longer needed:
Cell_Sets.Erase (New_Inputs );
Cell_Sets.Erase (New_Outputs);
-- Check if the cell-set changed, and take the new cell-set:
Cell_Set_Changed := New_All_Cells /= Within.All_Cells;
Within.All_Cells := New_All_Cells;
-- Update the effects of all calls:
--
-- First we find the Calls where the effect should
-- be recomputed:
for C in Calls'Range loop
if Flow.Computation.Calling_Protocol_Changed (Calls(C).Call, Model)
or else (
Cell_Set_Changed
and then Unknown_Effect (Calls(C).Bounds))
then
-- The effect of this Call must be recomputed because either
-- its calling protocol was changed, or because the total set
-- of cells in the model changed and this Call has a (partially)
-- unknown effect so it can clobber some of the model cells.
Last := Last + 1;
Calls_To_Compute(Last) := Calls(C);
end if;
end loop;
-- Then we recompute the effects of these calls:
if Last > 0 then
Compute_Call_Effects (
Calls => Calls_To_Compute(1 .. Last),
Within => Within);
end if;
end Note_Updated_Computation;
procedure Mark_Computation_Clean (Within : in Bounds_Ref)
is
begin
Flow.Computation.Mark_Clean (Within.Computation);
end Mark_Computation_Clean;
procedure Bound_Computation (
Model : in Flow.Computation.Model_Ref;
Within : in Bounds_Ref)
is
begin
Check_Mutability (Within);
-- The computation model defines the feasibility of steps
-- and edges and thus affects the paths.
Flow.Computation.Refer (
From => Within.Computation,
To => Model);
Note_Updated_Computation (Within);
end Bound_Computation;
procedure Bound_Value_Origins (Within : in Bounds_Ref)
--
-- Computes or recomputes the value-origin map for the computation
-- model Within the given bounds. If a value-origin map already exists,
-- it is discarded before the new map is computed.
is
begin
Flow.Origins.Discard (Within.Value_Origins);
Flow.Origins.Analyse (
Computation => Within.Computation,
Giving => Within.Value_Origins);
end Bound_Value_Origins;
procedure Bound_Assertions (
Map : in Assertions.Assertion_Map_T;
Within : in Bounds_Ref)
is
begin
Check_Mutability (Within);
-- Some loops/calls may be asserted as infeasible.
-- TBA discard old map if any. Note that it can be referenced
-- from several Bounds_Objects; Adopt_To_Context copies the
-- reference and does not make a deep copy.
Within.Assertion_Map := Map;
Within.Enough_For_Time :=
Assertions.Subprogram_Enough_For_Time (
Subprogram => Within.Subprogram,
Asserts => Assertions.Set (Map));
end Bound_Assertions;
procedure Initialize_Asserted_Bounds (
Subprogram : in Subprogram_T;
Within : in Bounds_Set_T;
Bounds : out Bounds_Ref)
is
begin
Create_Blank_Bounds (
For_Time => Within.For_Time,
For_Space => Within.For_Space,
Subprogram => Subprogram,
Call_Path => Null_Call_Path,
Caller => null,
Within => Within,
Bounds => Bounds);
if Opt.Trace_Bounds then
Output.Trace (
Locus => Locus (Bounds),
Text =>
"Created bounds #"
& Bounds_Index_T'Image (Index (Bounds))
& " for asserted bounds.");
end if;
Flow.Computation.Refer_To_Primitive_Model (
Subprogram => Subprogram,
Model => Bounds.Computation);
Bounds.All_Cells := Cell_Sets.Empty;
Set_Input_Cells (
To => Cell_Sets.Empty,
Within => Bounds);
Set_Output_Cells (
To => Cell_Sets.Empty,
Within => Bounds);
Bounds.Time_State := Vague;
for S in Bounds.Max_Stack_Usage'Range loop
Bounds.Max_Stack_Usage(S).State := Vague;
end loop;
end Initialize_Asserted_Bounds;
procedure Set_Input_Cells (
To : in Storage.Cell_Set_T;
Within : in Bounds_Ref)
is
begin
Check_Mutability (Within);
-- The input cells do not directly affect the paths,
-- but there is no reason to change the input cells when
-- the paths are frozen.
Within.Input_Cells := Cell_Sets.Copy (To);
Within.Input_Cell_Tally := Storage.Card (To);
Within.Inputs_Defined := True;
end Set_Input_Cells;
procedure Set_Basis_Cells (
To : in Storage.Cell_Set_T;
Within : in Bounds_Ref)
is
begin
Check_Mutability (Within);
-- The basis cells do not directly affect the paths,
-- but there is no reason to change the basis cells when
-- the paths are frozen.
Within.Basis := Cell_Sets.Copy (To);
end Set_Basis_Cells;
procedure Set_Output_Cells (
To : in Storage.Cell_Set_T;
Within : in Bounds_Ref)
is
begin
Check_Mutability (Within);
-- The output cells do not directly affect the paths,
-- but there is no reason to change the output cells when
-- the paths are frozen.
Within.Output_Cells := Cell_Sets.Copy (To);
Within.Outputs_Defined := True;
end Set_Output_Cells;
procedure Remove_From_Output (
Cells : in Storage.Cell_List_T;
Within : in Bounds_Ref)
is
begin
Check_Mutability (Within);
if Within.Outputs_Defined then
Cell_Sets.Remove (
Cells => Cells,
From => Within.Output_Cells);
else
Output.Fault (
Location => "Programs.Execution.Remove_From_Output",
Text => "Output cells not yet defined.");
end if;
end Remove_From_Output;
procedure Bound_Initial_Values (
To : in Storage.Bounds.Cell_Interval_List_T;
Within : in Bounds_Ref)
is
begin
-- TBA discard the old Within.Initial.
Within.Initial := new Storage.Bounds.Cell_Interval_List_T'(To);
end Bound_Initial_Values;
procedure Bound_Call_Inputs (
To : in Storage.Bounds.Var_Interval_List_T;
From : in Bounds_Ref)
is
begin
for C in From.Call_Inputs'Range loop
From.Call_Inputs(C) :=
Storage.Bounds.Interval_Bounds (
From => To,
Point => Prime_Address (
Call (
From => Subprogram (From),
Index => C)));
end loop;
end Bound_Call_Inputs;
procedure Bound_Edge_Times (
Times : in Step_Edge_Times_T;
Within : in Bounds_Ref)
is
use type Flow.Step_Edge_Index_T;
Max_Index : constant Flow.Step_Edge_Count_T :=
Flow.Max_Step_Edge (Flow_Graph (Within.Subprogram));
-- The largest step-edge index in the subprogram, or zero if
-- the subprogram has only one step and no step-edges.
begin
if Times'First /= 1 or Times'Last /= Max_Index then
Output.Fault (
Location => "Programs.Execution.Bound_Edge_Times",
Text =>
"Times'Range = "
& Output.Image (Natural (Times'First))
& " .. "
& Output.Image (Natural (Times'Last ))
& " /= 1 .. "
& Output.Image (Natural (Max_Index )));
raise Program_Error;
end if;
Flow.Execution.Times.Discard (Within.Step_Edge_Times);
Within.Step_Edge_Times :=
new Flow.Execution.Times.Step_Edge_Times_T'(Times);
Flow.Execution.Times.Discard (Within.Node_Times);
-- The new edge-times imply new node-times.
case Within.Time_State is
when Undefined
| Vague
| Depends
| Computable
| Asserted
| Infeasible
| Unbounded =>
-- Changing the edge-times has no effect on the time-state.
null;
when Computed =>
-- The time has to be recomputed for the new edge-times.
Within.Time_State := Computable;
when Failed =>
-- We can hope that a new computation might succeed.
Within.Time_State := Computable;
end case;
end Bound_Edge_Times;
procedure Bound_Node_Times (
Times : in Node_Times_T;
Within : in Bounds_Ref)
is
use type Flow.Node_Index_T;
begin
if Times'First /= 1 or Times'Last /= Within.Max_Node then
Output.Fault (
Location => "Programs.Execution.Bound_Flow_Times",
Text =>
"Times'Range = "
& Output.Image (Natural (Times'First))
& " .. "
& Output.Image (Natural (Times'Last ))
& " /= 1 .. "
& Output.Image (Natural (Within.Max_Node)));
raise Program_Error;
end if;
Flow.Execution.Times.Discard (Within.Node_Times);
Within.Node_Times := new Flow.Execution.Times.Node_Times_T'(Times);
Within.Time_State := Undefined;
-- The new flow-times imply a new total time.
end Bound_Node_Times;
procedure Compute_Node_Times (Bounds : in Bounds_Ref)
is
begin
if Opt.Trace_Bounds then
Output.Trace (
Locus => Locus (Bounds),
Text =>
"Computing per-node execution times for bounds #"
& Bounds_Index_T'Image (Index (Bounds)));
end if;
Bound_Node_Times (
Times =>
Flow.Execution.Times.Node_Times (
Subprogram => Bounds.Subprogram,
Step_Edge_Times => Bounds.Step_Edge_Times.all,
Asserts => Bounds.Assertion_Map),
Within => Bounds);
end Compute_Node_Times;
procedure Compute_Node_Times (
Calls : in Call_Bounds_List_T;
Max_Index : in Bounds_Index_T)
is
-- We perform this computation bottom-up in the bounds
-- hierarchy. At the moment there is no pressing need to do
-- it this way, but later there may be some additional analysis
-- that causes a bottom-to-top dependency of node times.
--
-- The bottom-up process is implemented by post-order recursion
-- and a boolean marking of the processed bounds.
Computed : Bounds_Subset_T (Max_Size => Max_Index);
--
-- The subset of bounds objects for which node times have been
-- Computed. If a bounds object is a member of this set, so
-- are all its (directly or indirectly) nested callee bounds,
-- thanks to the bottom-up computation order.
-- Default initialized to the empty set.
procedure Compute_Times_For (Bounds : in Bounds_Ref);
--
-- Computes node-times for the given bounds and its nested
-- callee bounds.
procedure Compute_Times_For (Callee_Bounds : in Call_Bounds_List_T)
--
-- Computes node-times for all the lower-level callees.
--
is
begin
for C in Callee_Bounds'Range loop
Compute_Times_For (Callee_Bounds(C).Bounds);
end loop;
end Compute_Times_For;
procedure Compute_Times_For (
Bounds : in Bounds_Ref)
is
begin
if not Is_Member (Bounds, Computed)
and not Time_Asserted (Bounds)
then
Add (Item => Bounds, To => Computed);
Compute_Times_For (Call_Bounds (Bounds));
-- The node times have now been computed for all the
-- lower-level callees.
Compute_Node_Times (Bounds);
end if;
end Compute_Times_For;
begin -- Compute_Node_Times
for C in Calls'Range loop
Compute_Times_For (Calls(C).Bounds);
end loop;
end Compute_Node_Times;
procedure Bound_Flow_Counts (
Counts : in Flow.Execution.Counts_Ref;
Within : in Bounds_Ref)
is
begin
Within.Flow_Counts := Counts;
end Bound_Flow_Counts;
procedure Conjoin (
Also : in Flow.Execution.Bound_T;
To : in out Flow.Execution.Bound_T;
Within : in Bounds_Ref)
--
-- Conjoins a new bound To an existing bound, which means
-- that To requires Also the new bound. If the conjoined bounds
-- are void, the execution bounds are marked as having void
-- (contradictory) flow bounds.
--
is
use Flow.Execution;
begin
To := To and Also;
if Void (To) then
Within.Void_Flow_Bounds := True;
end if;
end Conjoin;
procedure Bound_Node_Count (
Node : in Flow.Node_T;
Count : in Flow.Execution.Bound_T;
Within : in Bounds_Ref)
is
use Flow.Execution;
Bound : Flow.Execution.Bound_T renames
Within.Node_Bounds(Flow.Index (Node));
-- The execution-count bounds on this Node.
begin
Conjoin (Also => Count, To => Bound, Within => Within);
if Bound.Max = 0 then
Flow.Computation.Mark_Infeasible (
Step => Flow.First_Step (Node),
Under => Within.Computation);
end if;
end Bound_Node_Count;
procedure Bound_Node_Counts (
By : in Flow.Execution.Node_Count_Bounds_T;
Within : in Bounds_Ref)
is
begin
for B in By'Range loop
Bound_Node_Count (
Node => By(B).Node,
Count => By(B).Count,
Within => Within);
end loop;
end Bound_Node_Counts;
procedure Bound_Call_Count (
Call : in Call_T;
Count : in Flow.Execution.Bound_T;
Within : in Bounds_Ref)
is
Caller : constant Subprogram_T := Programs.Caller (Call);
-- The caller of the call.
begin
if Caller = Subprogram (Within) then
-- Right, this Call is from Within these bounds.
Bound_Node_Count (
Node => Flow.Node_Containing (
Step => Step (Call),
Graph => Flow_Graph (Caller)),
Count => Count,
Within => Within);
else
-- This call is foreign. Ugh.
Output.Fault (
Location => "Programs.Execution.Bound_Call_Count",
Text => "Caller is " & Name (Caller));
end if;
end Bound_Call_Count;
procedure Bound_Loop_Starts (
Luup : in Loops.Loop_T;
Starts : in Flow.Execution.Bound_T;
Within : in Bounds_Ref)
is
begin
Conjoin (
Also => Starts,
To => Within.Loop_Bounds.Loop_Starts(Loops.Loop_Index (Luup)),
Within => Within);
end Bound_Loop_Starts;
procedure Bound_Loop_Neck (
Luup : in Loops.Loop_T;
Count : in Flow.Execution.Bound_T;
Within : in Bounds_Ref)
is
begin
Conjoin (
Also => Count,
To => Within.Loop_Bounds.Loop_Neck(Loops.Loop_Index (Luup)),
Within => Within);
end Bound_Loop_Neck;
procedure Bound_Loop_Repeats (
Luup : in Loops.Loop_T;
Repeats : in Flow.Execution.Bound_T;
Within : in Bounds_Ref)
is
begin
Conjoin (
Also => Repeats,
To => Within.Loop_Bounds.Loop_Repeats(Loops.Loop_Index (Luup)),
Within => Within);
end Bound_Loop_Repeats;
procedure Bound_Call_Input (
Call : in Call_T;
Bounds : in Storage.Bounds.Bounds_Ref;
Within : in Bounds_Ref)
is
begin
if Opt.Trace_Call_Input_Bounds then
Output.Trace (
Locus => Locus (Call),
Text =>
"Input bounds"
& Output.Field_Separator
& Storage.Bounds.Full_Image (Bounds.all));
end if;
Check_Mutability (Within);
-- There is no reason to change the call-input bounds after
-- the containing bounds are frozen.
Within.Call_Inputs(Index (Call)) := Bounds;
-- TBA discard the old Call_Inputs bounds (carefully...)
end Bound_Call_Input;
procedure Bound_Call (
Call : in Call_T;
Bounds : in Bounds_Ref;
Within : in Bounds_Ref)
is
begin
Check_Mutability (Within);
if Bounds.Caller_Bounds /= Within and (not Bounds.Frozen) then
-- If we are linking Bounds from a different (shallower)
-- context, Within the caller's bounds for a deeper
-- context, the Bounds on the call must be frozen so
-- that their essential properties are immutable.
Output.Fault (
Location => "Programs.Execution.Bound_Call",
Text =>
"Bounds #"
& Bounds_Index_T'Image (Bounds.Index)
& " are not Frozen.");
end if;
Within.Call_Bounds(Index (Call)).Bounds := Bounds;
-- TBA discard the old call-bounds (if not used elsewhere).
end Bound_Call;
procedure Bound_Final_Stack_Height (
Stack : in Stack_T;
To : in Final_Stack_Height_T;
Within : in Bounds_Ref;
Silent : in Boolean := False)
is
use type Storage.Bounds.Interval_T;
Stix : constant Stack_Index_T := Index (Stack);
Intval : Final_Stack_Height_T renames Within.Final_Stack_Height (Stix);
function Name_And_Bounds (Item : Final_Stack_Height_T)
return String
is
begin
return Output.Field_Separator
& Name (Stack)
& Output.Field_Separator
& Image (
Item => Item,
Name => Storage.Image (Height (Stack)));
end Name_And_Bounds;
begin -- Bound_Final_Stack_Height
Check_Mutability (Within);
case Stack.Kind is
when Stable =>
if To /= To_Stack_Limit (Storage.Bounds.Exactly_Zero) then
Output.Fault (
Location => "Programs.Execution.Bound_Final_Stack_Height",
Text =>
"Non-zero final-height bounds for Stable stack"
& Name_And_Bounds (To));
end if;
when Unstable =>
Intval := Intval and To;
if Opt.Trace_Stack_Bounds and not Silent then
Output.Trace (
"Final stack height"
& Name_And_Bounds (Intval));
end if;
if Void (Intval) then
Output.Fault (
Location => "Programs.Execution.Bound_Final_Stack_Height",
Text =>
"Void final-height bounds for Unstable stack"
& Name_And_Bounds (Intval));
end if;
end case;
end Bound_Final_Stack_Height;
procedure Bound_Stack_Height (
Stack : in Stack_T;
To : in Stack_Limit_T;
Within : in Bounds_Ref;
Silent : in Boolean := False)
is
begin
Check_Mutability (Within);
Within.Stack_Height(Index (Stack)) := To;
if Opt.Trace_Stack_Bounds and not Silent then
Output.Trace (
"Local stack height"
& Output.Field_Separator
& Name (Stack)
& Output.Field_Separator
& Image (To));
end if;
end Bound_Stack_Height;
procedure Bound_Take_Off_Height (
Stack : in Stack_T;
Before : in Call_T;
To : in Stack_Limit_T;
Within : in Bounds_Ref;
Silent : in Boolean := False)
is
begin
Check_Mutability (Within);
Within.Take_Off_Limits(Index (Before), Index (Stack)) := To;
if Opt.Trace_Stack_Bounds and not Silent then
Output.Trace (
Locus => Locus (Before),
Text =>
"Take-off stack height"
& Output.Field_Separator
& Name (Stack)
& Output.Field_Separator
& Image (To));
end if;
end Bound_Take_Off_Height;
Stack_Key : constant String := "Stack";
-- Key for "stack usage" in basic output line.
procedure Bound_Stack_Usage (
Stack : in Stack_T;
To : in Stack_Usage_T;
Within : in Bounds_Ref;
Silent : in Boolean := False)
is
begin
Check_Mutability (Within);
if To.State = Undefined then
Output.Fault (
Location => "Programs.Execution.Bound_Stack_Usage",
Text => "To.State is Undefined");
else
Within.Max_Stack_Usage(Index (Stack)) := To;
if Opt.Trace_Stack_Bounds and not Silent then
Output.Trace (
"Total stack usage"
& Output.Field_Separator
& Name (Stack)
& Output.Field_Separator
& Image (To.Call)
& Output.Field_Separator
& Value_Image (To));
end if;
if Bounded (To) and not Silent then
Output.Result (
Key => Stack_Key,
Locus => Locus (Within),
Text =>
Name (Stack)
& Output.Field_Separator
& Value_Image (To) );
end if;
end if;
end Bound_Stack_Usage;
procedure Bound_Time (
Time : in Processor.Time_T;
State : in Time_Bounded_T;
Within : in Bounds_Ref)
is
begin
Within.Time_State := State;
Within.Time := Time;
end Bound_Time;
procedure Set_Time_State (
To : in Time_State_T;
Within : in Bounds_Ref)
is
begin
if Within.Time_State not in Time_Bounded_T
and To in Time_Bounded_T
then
-- Claiming to have a time-bound where none exists.
Output.Fault (
Location => "Programs.Execution.Set_Time_State",
Text =>
"Changing Time_State from "
& Time_State_T'Image (Within.Time_State)
& " to "
& Time_State_T'Image (To));
end if;
Within.Time_State := To;
end Set_Time_State;
procedure Set_Time_Calculated (Within : in Bounds_Ref)
is
begin
if Within.Time_Calculated then
Output.Fault (
Location => "Programs.Execution.Set_Time_Calculated",
Text => "Already set.");
end if;
Within.Time_Calculated := True;
end Set_Time_Calculated;
--
--- Execution bound query operations:
--
-- Queries usually deliver all the accumulated bounds
-- of a specific types, in one batch.
function Defined (Item : Bounds_Ref) return Boolean
is
begin
return Item /= No_Bounds;
end Defined;
function Index (Item : Bounds_Ref)
return Bounds_Index_T
is
begin
return Item.Index;
end Index;
function Subprogram (Item : Bounds_Ref)
return Subprogram_T
is
begin
return Item.Subprogram;
end Subprogram;
function Flow_Graph (Item : Bounds_Ref)
return Flow.Graph_T
is
begin
return Flow_Graph (Subprogram (Item));
end Flow_Graph;
function Call_Path (Item : Bounds_Ref)
return Call_Path_T
is
begin
return Item.Call_Path;
end Call_Path;
function Level (Item : Bounds_Ref) return Bounding_Level_T
is
begin
if Item = No_Bounds then
return Indefinite;
else
return Item.Level;
end if;
end Level;
function Program (Item : Bounds_Ref) return Program_T
is
begin
if not Defined (Item) then
Output.Fault (
Location => "Programs.Execution.Program",
Text => "Bounds undefined.");
raise Program_Error;
end if;
return Item.Program;
end Program;
function Symbol_Table (Item : Bounds_Ref) return Symbols.Symbol_Table_T
is
begin
return Symbol_Table (Program (Item));
end Symbol_Table;
function For_Time (Bounds : Bounds_Ref) return Boolean
is
begin
return Bounds.For_Time;
end For_Time;
function For_Space (Bounds : Bounds_Ref) return Boolean
is
begin
return Bounds.For_Space;
end For_Space;
function Processor_Info (From : Bounds_Ref)
return Processor.Execution.Info_T
is
begin
return From.Info;
end Processor_Info;
function Computation (Item : Bounds_Ref)
return Flow.Computation.Model_Handle_T
is
begin
if not Defined (Item) then
Output.Fault (
Location => "Programs.Execution.Computation return Handle",
Text => "Bounds undefined.");
raise Program_Error;
end if;
return Item.Computation'access;
end Computation;
function Value_Origins_Defined (Item : Bounds_Ref)
return Boolean
is
begin
if not Defined (Item) then
Output.Fault (
Location => "Programs.Execution.Value_Origins_Defined",
Text => "Bounds undefined.");
raise Program_Error;
end if;
return Flow.Origins.Is_Valid (Item.Value_Origins);
end Value_Origins_Defined;
function Value_Origins (Item : Bounds_Ref)
return Flow.Origins.Map_Ref
is
begin
if not Defined (Item) then
Output.Fault (
Location => "Programs.Execution.Value_Origins",
Text => "Bounds undefined.");
raise Program_Error;
end if;
return Item.Value_Origins;
end Value_Origins;
function Is_Feasible (Item : Bounds_Ref) return Boolean
is
begin
return (not Unused (Subprogram (Item)))
and then Time_State (Item) /= Infeasible
and then Flow.Computation.Is_Feasible (Computation (Item).all);
end Is_Feasible;
function Returns (Item : Bounds_Ref) return Boolean
is
begin
return Returns (Subprogram (Item))
and then Flow.Computation.Returns (Computation (Item).all);
end Returns;
function Calling_Protocol (
Call : Call_T;
Within : Bounds_Ref)
return Calling.Protocol_Ref
is
begin
return Flow.Computation.Calling_Protocol (
Call => Call,
Under => Within.Computation);
end Calling_Protocol;
function Dynamic_Flow (Item : Bounds_Ref)
return Flow.Edge_Resolution_T
is
begin
return Flow.Computation.Dynamic_Flow (Item.Computation);
end Dynamic_Flow;
function Unstable_Dynamic_Edges (Item : Bounds_Ref)
return Flow.Dynamic_Edge_List_T
is
begin
return Flow.Computation.Unstable_Dynamic_Edges (Item.Computation);
end Unstable_Dynamic_Edges;
function Assertion_Map (Item : Bounds_Ref)
return Assertions.Assertion_Map_T
is
begin
if Defined (Item) then
return Item.Assertion_Map;
else
return Assertions.No_Map;
end if;
end Assertion_Map;
function Inputs_Defined (Item : Bounds_Ref)
return Boolean
is
begin
return Item.Inputs_Defined;
end Inputs_Defined;
function Input_Cells (Item : Bounds_Ref)
return Storage.Cell_List_T
is
begin
if not Item.Inputs_Defined then
Output.Fault (
Location => "Programs.Execution.Input_Cells",
Locus => Locus (Item),
Text => "Input-cell set undefined");
return Storage.Null_Cell_List;
else
return Cell_Sets.To_List (Item.Input_Cells);
end if;
end Input_Cells;
function Number_Of_Input_Cells (Item : Bounds_Ref)
return Natural
is
begin
if not Item.Inputs_Defined then
Output.Fault (
Location => "Programs.Execution.Number_Of_Input_Cells",
Locus => Locus (Item),
Text => "Input-cell set undefined");
return 0;
else
return Item.Input_Cell_Tally;
end if;
end Number_Of_Input_Cells;
function Input_Cells (
Call : Call_T;
Within : Bounds_Ref)
return Storage.Cell_List_T
is
begin
return Input_Cells (Call_Bounds (Call, Within));
end Input_Cells;
function Basis (Item : Bounds_Ref)
return Storage.Cell_List_T
is
begin
return Cell_Sets.To_List (Item.Basis);
end Basis;
function Initial (Item : Bounds_Ref)
return Storage.Bounds.Cell_Interval_List_T
is
begin
if Item.Initial /= null then
return Item.Initial.all;
else
return Storage.Bounds.Empty;
end if;
end Initial;
function Outputs_Defined (Item : Bounds_Ref)
return Boolean
is
begin
return Item.Outputs_Defined;
end Outputs_Defined;
function Output_Cells (Item : Bounds_Ref)
return Storage.Cell_List_T
is
begin
if not Item.Outputs_Defined then
Output.Fault (
Location => "Programs.Execution.Output_Cells",
Text => "Output-cell set undefined");
return Storage.Null_Cell_List;
else
return Cell_Sets.To_List (Item.Output_Cells);
end if;
end Output_Cells;
function Enough_For_Time (Item : Bounds_Ref) return Boolean
is
begin
return Item.Enough_For_Time;
end Enough_For_Time;
function Time_State (Item : Bounds_Ref) return Time_State_T
is
begin
if Defined (Item) then
return Item.Time_State;
else
return Undefined;
end if;
end Time_State;
function Time_Calculated (Within : Bounds_Ref) return Boolean
is
begin
return Within.Time_Calculated;
end Time_Calculated;
function Time_Bounded (Item : Bounds_Ref) return Boolean
is
begin
return Item.Time_State in Time_Bounded_T;
end Time_Bounded;
function Time_Asserted (Item : Bounds_Ref) return Boolean
is
begin
return Time_State (Item) = Asserted;
end Time_Asserted;
function Time (Item : Bounds_Ref) return Processor.Time_T
is
begin
if Time_Bounded (Item) then
return Item.Time;
else
Output.Fault (
Location => "Programs.Execution.Time",
Text =>
"Time for bounds #"
& Bounds_Index_T'Image (Index (Item))
& " is "
& Time_State_T'Image (Item.Time_State));
return 0;
end if;
end Time;
procedure Prune_Flow (Item : in Bounds_Ref)
is
begin
Check_Mutability (Item);
Flow.Computation.Prune (Item.Computation);
Mark_Flow_Pruned (Item);
end Prune_Flow;
procedure Mark_Flow_Pruned (Item : in Bounds_Ref)
is
begin
Check_Mutability (Item);
end Mark_Flow_Pruned;
procedure Mark_Infeasible (
Step : in Flow.Step_T;
Within : in Bounds_Ref)
is
begin
Check_Mutability (Within);
Flow.Computation.Mark_Infeasible (
Step => Step,
Under => Within.Computation);
Flow.Computation.Prune (Within.Computation);
end Mark_Infeasible;
procedure Mark_Infeasible (
Edges : in Flow.Edge_List_T;
Within : in Bounds_Ref)
is
begin
Check_Mutability (Within);
Flow.Computation.Mark_Infeasible (
Edges => Edges,
Under => Within.Computation);
Flow.Computation.Prune (Within.Computation);
end Mark_Infeasible;
procedure Mark_Infeasible (Bounds : in Bounds_Ref)
is
begin
Mark_Infeasible (
Step => Flow.Entry_Step (Flow_Graph (Bounds)),
Within => Bounds);
end Mark_Infeasible;
function Bounded (Bounds : Bounds_Ref)
return Boolean
is
Tied : Boolean := True;
-- The result. No problems yet.
begin
if Bounds.For_Time then
-- Check that time or paths are bounded:
Tied := Tied and then Time_State (Bounds) in Time_Boundable_T;
end if;
if Bounds.For_Space then
-- Check that space is bounded:
Tied := Tied and then Stack_Usage_Bounded (Bounds);
end if;
return Tied;
end Bounded;
function Bounded (
Luup : Loops.Loop_T;
Within : Bounds_Ref)
return Boolean
is
use Flow.Execution;
-- The Bounded function.
Index : constant Loops.Loop_Index_T := Loops.Loop_Index (Luup);
-- Yes, this is the index of the Luup.
begin
return Bounded (Within.Loop_Bounds.Loop_Neck (Index).Max)
or Bounded (Within.Loop_Bounds.Loop_Repeats(Index).Max);
end Bounded;
function Loop_Start_Bound (
Luup : Loops.Loop_T;
Within : Bounds_Ref)
return Flow.Execution.Bound_T
is
begin
return Within.Loop_Bounds.Loop_Starts(Loops.Loop_Index (Luup));
end Loop_Start_Bound;
function Loop_Neck_Bound (
Luup : Loops.Loop_T;
Within : Bounds_Ref)
return Flow.Execution.Bound_T
is
begin
return Within.Loop_Bounds.Loop_Neck(Loops.Loop_Index (Luup));
end Loop_Neck_Bound;
function Loop_Repeat_Bound (
Luup : Loops.Loop_T;
Within : Bounds_Ref)
return Flow.Execution.Bound_T
is
begin
return Within.Loop_Bounds.Loop_Repeats(Loops.Loop_Index (Luup));
end Loop_Repeat_Bound;
function Loop_Start_Bounds (Item : Bounds_Ref)
return Loop_Bounds_T
is
begin
return Item.Loop_Bounds.Loop_Starts;
end Loop_Start_Bounds;
function Loop_Neck_Bounds (Item : Bounds_Ref)
return Loop_Bounds_T
is
begin
return Item.Loop_Bounds.Loop_Neck;
end Loop_Neck_Bounds;
function Loop_Repeat_Bounds (Item : Bounds_Ref)
return Loop_Bounds_T
is
begin
return Item.Loop_Bounds.Loop_Repeats;
end Loop_Repeat_Bounds;
function Call_Input_Bounds (
On : Call_T;
Within : Bounds_Ref)
return Storage.Bounds.Bounds_Ref
is
begin
return Within.Call_Inputs(Index (On));
end Call_Input_Bounds;
function Call_Bounds (
On : Call_T;
Within : Bounds_Ref)
return Bounds_Ref
is
begin
-- Check for absence of bounds:
if not Defined (Within) then
Output.Fault (
Location => "Programs.Execution.Call_Bounds",
Text => "Undefined call bounds.");
return No_Bounds;
end if;
return Within.Call_Bounds(Index (On)).Bounds;
end Call_Bounds;
function Call_Bounds (Within : Bounds_Ref)
return Call_Bounds_List_T
is
List : Call_Bounds_List_T (1 .. Within.Call_Bounds'Length);
Last : Natural := 0;
-- The result is List(1 .. Last).
begin
for C in Within.Call_Bounds'Range loop
if Flow.Computation.Is_Feasible (
Call => Within.Call_Bounds(C).Call,
Under => Within.Computation)
then
Last := Last + 1;
List(Last) := Within.Call_Bounds(C);
if List(Last).Bounds = No_Bounds then
Output.Fault (
Location => "Programs.Execution.Call_Bounds (Bounds_Ref)",
Locus => Locus (List(Last).Call),
Text => "Null bounds on callee.");
Output.Fault (
Location => "Programs.Execution.Call_Bounds (Bounds_Ref)",
Locus => Locus (Within),
Text =>
"Null bounds on callee within bounds #"
& Bounds_Index_T'Image (Index (Within))
& '.');
end if;
end if;
end loop;
return List(1 .. Last);
end Call_Bounds;
function Unbounded_Loops (
Within : Bounds_Ref;
Eternal : Boolean)
return Loops.Loop_List_T
is
use Flow.Execution;
-- The Bounded function.
Luups : constant Loops.Loop_List_T :=
Flow.Computation.Loops_Of (Within.Computation);
-- Those loops in the subprogram that are feasible and
-- feasibly repeatable under this computation model.
-- Note that Luups is not indexed by Loops.Loop_Index_T.
Wild : Loops.Loop_List_T (1 .. Luups'Length);
Last : Natural := 0;
-- The feasible unbounded loops are collected in Wild (1 .. Last).
Luup : Loops.Loop_T;
-- One of the Luups.
X : Loops.Loop_Index_T;
-- The index of the Luup.
begin
for L in Luups'Range loop
Luup := Luups(L);
X := Loops.Index (Luup);
if not Bounded (Within.Loop_Bounds.Loop_Neck (X).Max)
and not Bounded (Within.Loop_Bounds.Loop_Repeats(X).Max)
and (Eternal
or else
not Flow.Computation.Is_Eternal (Luup, Within.Computation))
then
-- This loop is feasible but not bounded, and also
-- finite (not eternal) if eternal loops are excluded.
Last := Last + 1;
Wild(Last) := Luup;
end if;
end loop;
return Wild(1..Last);
end Unbounded_Loops;
function Dependent_Calls (
Within : Bounds_Ref;
Input : Boolean)
return Call_List_T
--
-- The Context_Dependent_Cells (when Input => False) or the
-- Input_Dependent_Cells (when Input => True).
--
is
Calls : constant Call_Bounds_List_T := Call_Bounds (Within);
-- All the feasible calls with their current execution bounds.
Time, Space : Boolean;
-- Whether a given Call has context-dependent execution time
-- or context-dependent stack space.
Inp : Boolean := True;
-- Whether a given Call satisfies the Input condition.
-- Initialized for Input = False and overridden otherwise.
Result : Call_List_T (1 .. Calls'Length);
Last : Natural := 0;
-- The result will be Result(1 .. Last).
begin
for C in Calls'Range loop
Time := Within.For_Time
and then Time_State (Calls(C).Bounds) = Depends;
Space := Within.For_Space
and then Space_State (Calls(C).Bounds) = Depends;
if Input then
-- Accept only calls with some input cells:
Inp := Calls(C).Bounds.Input_Cell_Tally > 0;
end if;
if (Time or Space) and Inp then
Last := Last + 1;
Result(Last) := Calls(C).Call;
end if;
end loop;
return Result(1 .. Last);
end Dependent_Calls;
function Context_Dependent_Calls (Within : Bounds_Ref)
return Call_List_T
is
begin
return Dependent_Calls (Within => Within, Input => False);
end Context_Dependent_Calls;
function Input_Dependent_Calls (Within : Bounds_Ref)
return Call_List_T
is
begin
return Dependent_Calls (Within => Within, Input => True);
end Input_Dependent_Calls;
function Unbounded_Calls (
Within : Bounds_Ref;
Irreducible : Boolean)
return Call_List_T
is
Calls : constant Call_Bounds_List_T := Call_Bounds (Within);
-- All the feasible calls with their current execution bounds.
Stacks : constant Stacks_T := Programs.Stacks (Program (Within));
-- All the stacks in the program (for which a take-off height
-- may still be unbounded).
Result : Call_List_T (1 .. Calls'Length);
Last : Natural := 0;
-- The result will be Result(1 .. Last).
Candidate : Call_Bounds_T;
-- A candidate from Calls.
Cand_Callee : Subprogram_T;
-- The callee of the Candidate.
Interesting : Boolean;
-- Whether the current call is interesting.
begin
for C in Calls'Range loop
Candidate := Calls(C);
Cand_Callee := Callee (Candidate.Call);
Interesting := False;
if (not Stub (Cand_Callee))
and (Irreducible or else Reducible (Cand_Callee))
then
-- This is a possibility.
if not Bounded (Bounds => Candidate.Bounds) then
Output.Note (
Locus => Locus (Candidate.Call),
Text => "Call is interesting; not fully bounded.");
Interesting := True;
end if;
if Within.For_Space then
-- Check the take-off heights.
for S in Stacks'Range loop
if not Take_Off_Height_Bounded (
Stack => Stacks(S),
Before => Candidate.Call,
Within => Within)
then
Output.Note (
Locus => Locus (Candidate.Call),
Text =>
"Call is interesting; take-off-height for "
& Name (Stacks (S))
& " is unbounded.");
Interesting := True;
end if;
end loop;
end if;
end if;
if Interesting then
Last := Last + 1;
Result(Last) := Candidate.Call;
end if;
end loop;
return Result(1 .. Last);
end Unbounded_Calls;
procedure Add_Caller_Cells (
From : in Flow.Calls.Parameter_Map_T;
To : in out Storage.Cell_Set_T)
--
-- Adds the caller-side cells From the given parameter map
-- To the given cell-set.
--
is
begin
for F in From'Range loop
Storage.Add (From(F).Caller, To);
end loop;
end Add_Caller_Cells;
procedure Add_Inputs_For (
Call : in Call_T;
Within : in Bounds_Ref;
To : in out Storage.Cell_Set_T)
--
-- Adds the caller-side input cells for the Call, Within the
-- given caller-bounds, To the cell-set.
--
is
Call_Mark : Output.Nest_Mark_T;
-- Locus for the Call.
Bounds : Bounds_Ref;
-- The not fully bounded bounds on the Call.
Protocol : Calling.Protocol_Ref;
-- The calling protocol in use for the Call.
begin
Call_Mark := Output.Nest (Locus => Locus (Call));
Protocol := Flow.Computation.Calling_Protocol (
Call => Call,
Under => Within.Computation);
Bounds := Call_Bounds (
On => Call,
Within => Within);
Add_Caller_Cells (
From => Flow.Calls.Input_Parameters (
Inputs => Input_Cells (Bounds),
Protocol => Protocol.all),
To => To);
Output.Unnest (Call_Mark);
exception
when X : others =>
Output.Exception_Info (
Text => "Programs.Execution.Add_Inputs_For",
Occurrence => X);
Output.Unnest (Call_Mark);
end Add_Inputs_For;
procedure Add_Inputs_For_Unbounded_Calls (
Within : in Bounds_Ref;
To : in out Storage.Cell_Set_T)
is
Calls : constant Call_List_T :=
Unbounded_Calls (Within => Within, Irreducible => True);
-- The unbounded calls.
begin
for C in Calls'Range loop
Add_Inputs_For (
Call => Calls(C),
Within => Within,
To => To);
end loop;
end Add_Inputs_For_Unbounded_Calls;
function Inputs_For_Unbounded_Calls (Within : Bounds_Ref)
return Storage.Cell_Set_T
is
Inputs : Cell_Set_T;
-- To hold the input cells.
-- Default initialized to the empty set.
begin
Add_Inputs_For_Unbounded_Calls (
Within => Within,
To => Inputs);
return Inputs;
end Inputs_For_Unbounded_Calls;
function Unbounded_Stack_Steps (Within : Bounds_Ref)
return Flow.Step_List_T
is
Stacks : constant Stacks_T := Programs.Stacks (Program (Within));
-- All the stacks.
Result : Flow.Bounded_Step_List_T (
Max_Length => Positive (
Flow.Computation.Max_Step (Within.Computation)));
-- To hold the result.
begin
if Within.For_Space then
-- Stacks should be bounded and there are some stacks.
for S in Stacks'Range loop
if Stack_Usage_Bounded (Stacks(S), Within)
-- The total stack usage is already bounded (by an
-- assertion so we do not need to find bounds on
-- the local stack height).
or Stack_Height_Bounded (Stacks(S), Within) then
-- We already have bounds on the local stack height
-- (from some earlier analysis), so we can use these
-- height-bonds to compute usage bounds.
null;
else
-- Stack usage and height bounds not yet known for
-- this stack, so we need to find bounds on the local
-- height from which we can compute bounds on the usage.
Flow.Add (
Steps => Flow.Computation.Steps_Defining (
Cell => Height (Stacks(S)),
Under => Within.Computation),
To => Result);
end if;
end loop;
end if;
if not Final_Stack_Heights_Known (Within) then
-- Some (Unstable) stack has no bounds on its final height.
Flow.Add (
Steps => Flow.Computation.Final_Steps (Within.Computation),
To => Result);
end if;
return Flow.To_List (Result);
end Unbounded_Stack_Steps;
function Calls_With_Unbounded_Take_Off (Item : Bounds_Ref)
return Call_List_T
is
Stacks : constant Stacks_T := Programs.Stacks (Program (Item));
-- All the stacks.
Loose : Call_List_T (1 .. Item.Take_Off_Limits'Length (1));
Last : Natural := 0;
-- Collects the unbounded Take_Off items in Loose(1 .. Last).
Candidate : Call_T;
-- One of the calls from the subprogram.
All_Bounded : Boolean;
-- Whether all take-off heights for the Candidate are bounded
-- except possibly for stacks that already have bounded usage.
begin
for C in 1 .. Number_Of_Calls_From (Item.Subprogram) loop
Candidate := Call (From => Item.Subprogram, Index => C);
if Flow.Computation.Is_Feasible (Candidate, Item.Computation) then
-- This call is feasible, so we check its take-off heights.
All_Bounded := True;
for S in Stacks'Range loop
if not Stack_Usage_Bounded (Stacks(S), Item) then
-- Since the total usage of this stack is not yet
-- bounded (by an assertion, for example), we need
-- to compute it and thus need the take-off height.
All_Bounded := All_Bounded
and Bounded (Item.Take_Off_Limits(C,S));
end if;
end loop;
if not All_Bounded then
-- The take-off height is not bounded, for some stacks
-- that have unbounded usage.
Last := Last + 1;
Loose(Last) := Candidate;
end if;
end if;
end loop;
return Loose(1 .. Last);
end Calls_With_Unbounded_Take_Off;
function Flow_Bounds_Feasible (Item : in Bounds_Ref)
return Boolean
is
begin
return not Item.Void_Flow_Bounds;
end Flow_Bounds_Feasible;
function Node_Bounds (Item : in Bounds_Ref)
return Node_Bounds_T
is
begin
return Item.Node_Bounds;
end Node_Bounds;
function Edge_Times_Bounded (Item : in Bounds_Ref)
return Boolean
is
begin
return Defined (Item) and then Item.Step_Edge_Times /= null;
end Edge_Times_Bounded;
function Step_Edge_Times (Item : in Bounds_Ref)
return Step_Edge_Times_T
is
Empty : Step_Edge_Times_T (1 .. 0);
begin
if not Edge_Times_Bounded (Item) then
-- No times exist.
Output.Fault (
Location => "Programs.Execution.Edge_Times",
Text => "Edge times not defined.");
return Empty;
else
return Item.Step_Edge_Times.all;
end if;
end Step_Edge_Times;
function Time (Edge : Flow.Step_Edge_T; From : Bounds_Ref)
return Processor.Time_T
is
begin
if Edge_Times_Bounded (From) then
return From.Step_Edge_Times(Flow.Index (Edge));
else
return 0;
end if;
end Time;
function Edge_Times (Item : in Bounds_Ref)
return Edge_Times_T
is
begin
return Flow.Execution.Times.Edge_Times (
Graph => Flow_Graph (Subprogram (Item)),
Step_Edge_Times => Step_Edge_Times (Item));
end Edge_Times;
function Time (Edge : Flow.Edge_T; From : Bounds_Ref)
return Processor.Time_T
is
begin
return Time (
Edge => Flow.Step_Edge (Edge),
From => From);
end Time;
function Node_Times_Bounded (Item : in Bounds_Ref)
return Boolean
is
begin
return Defined (Item) and then Item.Node_Times /= null;
end Node_Times_Bounded;
function Node_Times_With_Call_Times (From : Bounds_Ref)
return Node_Times_T
--
-- The per-node execution times From the given bounds, with
-- the time-bound of each callee included.
--
-- Preconditions:
-- Defined (From).
-- From.Node_Times defined (not null).
--
-- Emits a warning for any call that does not have a bound
-- on execution time but is not Infeasible; uses a zero time
-- for such calls.
--
is
use type Processor.Time_T;
Times : Node_Times_T (From.Node_Times'Range) :=
From.Node_Times.all;
-- The per-node times without call times.
Calls : constant Call_Bounds_List_T := Call_Bounds (From);
-- Bounds on the lower-level calls.
Call_Node : Flow.Node_Index_T;
-- A node that contains some lower-level call(s).
Call_Bounds : Bounds_Ref;
-- The bounds on the call.
begin
-- Add the time of lower-level calls to Times:
for C in Calls'Range loop
Call_Node := Flow.Index (Node (Calls(C).Call));
Call_Bounds := Calls(C).Bounds;
case Time_State (Call_Bounds) is
when Time_Bounded_T =>
Times(Call_Node) := Times(Call_Node) + Time (Call_Bounds);
when Infeasible =>
null;
when others =>
Output.Fault (
Location => "Programs.Execution.Node_Times_With_Call_Times",
Locus => Locus (From),
Text =>
"Time is not bounded for "
& Image (Calls(C).Call));
end case;
end loop;
return Times;
end Node_Times_With_Call_Times;
function Node_Times (
From : Bounds_Ref;
With_Calls : Boolean)
return Node_Times_T
is
Empty : Node_Times_T (1 .. 0);
begin
if not Node_Times_Bounded (From) then
-- No times exist.
Output.Note ("Node times not defined.");
return Empty;
elsif With_Calls then
-- Include time of calls to lower-level subprograms:
return Node_Times_With_Call_Times (From);
else
-- Just the local execution time:
return From.Node_Times.all;
end if;
end Node_Times;
function Call_Time (
Node : Flow.Node_T;
From : Bounds_Ref)
return Processor.Time_T
--
-- The total worst-case execution time of all calls from the
-- given Node, From the given bounds.
--
-- Emits a warning for any call that does not have a bound
-- on execution time but is not Infeasible; uses a zero time
-- for such calls.
--
is
use type Flow.Node_T;
use type Processor.Time_T;
Graph : constant Flow.Graph_T := Flow_Graph (From.Subprogram);
-- The graph of the subprogram in question (the caller).
Calls : constant Call_Bounds_List_T := Call_Bounds (From);
-- Bounds on the lower-level calls.
Total : Processor.Time_T := 0;
-- The total time of the calls in Node.
Call_Node : Flow.Node_T;
-- A node that contains some lower-level call.
Call_Bounds : Bounds_Ref;
-- The bounds on the call.
begin
-- Add the time of lower-level calls to Times:
for C in Calls'Range loop
Call_Node := Flow.Node_Containing (
Step => Step (Calls(C).Call),
Graph => Graph);
if Call_Node = Node then
Call_Bounds := Calls(C).Bounds;
case Time_State (Call_Bounds) is
when Time_Bounded_T =>
Total := Total + Time (Call_Bounds);
when Infeasible =>
null;
when others =>
Output.Fault (
Location => "Programs.Execution.Call_Time",
Locus => Locus (From),
Text =>
"Time is not bounded for "
& Image (Calls(C).Call));
end case;
end if;
end loop;
return Total;
end Call_Time;
function Time (
Node : Flow.Node_T;
From : Bounds_Ref;
With_Calls : Boolean)
return Processor.Time_T
is
use type Processor.Time_T;
Time : Processor.Time_T := 0;
-- The result.
begin
if Node_Times_Bounded (From) then
Time := From.Node_Times(Flow.Index (Node));
if With_Calls then
Time := Time + Call_Time (Node, From);
end if;
end if;
return Time;
end Time;
--
--- Execution counts of nodes, edges, etc
--
function Counts_Set (Item : in Bounds_Ref) return Boolean
is
use type Flow.Execution.Counts_Ref;
begin
return Defined (Item)
and then Item.Flow_Counts /= null;
end Counts_Set;
function Counts (Item : in Bounds_Ref)
return Flow_Counts_Ref
is
begin
if Defined (Item) then
return Item.Flow_Counts;
else
return null;
end if;
end Counts;
function Count (Node : Flow.Node_T; Within : Bounds_Ref)
return Flow.Execution.Count_T
is
begin
if Counts_Set (Within) then
return Within.Flow_Counts.Node(Flow.Index (Node));
else
return 0;
end if;
end Count;
function Count (Edge : Flow.Edge_T; Within : Bounds_Ref)
return Flow.Execution.Count_T
is
begin
if Counts_Set (Within) then
return Within.Flow_Counts.Edge(Flow.Index (Edge));
else
return 0;
end if;
end Count;
function Total_Count (
Nodes : Flow.Node_List_T;
Within : Bounds_Ref)
return Flow.Execution.Count_T
--
-- The total execution count of the Nodes, in the worst-case
-- execution path Within the bounds, or zero if no such path
-- is set.
--
is
begin
if Counts_Set (Within) then
return Flow.Execution.Total_Count (
Nodes => Nodes,
Within => Within.Flow_Counts.all);
else
return 0;
end if;
end Total_Count;
function Total_Count (
Edges : Flow.Edge_List_T;
Within : Bounds_Ref)
return Flow.Execution.Count_T
--
-- The total execution count of the Edges, in the worst-case
-- execution path Within the bounds, or zero if no such path
-- is set.
--
is
begin
if Counts_Set (Within) then
return Flow.Execution.Total_Count (
Edges => Edges,
Within => Within.Flow_Counts.all);
else
return 0;
end if;
end Total_Count;
function Start_Count (
Luup : Loops.Loop_T;
Within : Bounds_Ref)
return Flow.Execution.Count_T
is
begin
return Total_Count (
Edges => Loops.Entry_Edges (
Into => Luup,
Within => Flow_Graph (Subprogram (Within))),
Within => Within);
end Start_Count;
function Head_Count (
Luup : Loops.Loop_T;
Within : Bounds_Ref)
return Flow.Execution.Count_T
is
begin
return Total_Count (
Nodes => (1 => Loops.Head_Node (Luup)),
Within => Within);
end Head_Count;
function Neck_Count (
Luup : Loops.Loop_T;
Within : Bounds_Ref)
return Flow.Execution.Count_T
is
begin
return Total_Count (
Edges => Loops.Neck_Edges (
Into => Luup,
Within => Flow_Graph (Subprogram (Within))),
Within => Within);
end Neck_Count;
function Repeat_Count (
Luup : Loops.Loop_T;
Within : Bounds_Ref)
return Flow.Execution.Count_T
is
begin
return Total_Count (
Edges => Loops.Repeat_Edges (
Repeating => Luup,
Within => Flow_Graph (Subprogram (Within))),
Within => Within);
end Repeat_Count;
function Call_Count (
Call : Call_T;
Within : Bounds_Ref)
return Flow.Execution.Count_T
is
begin
return Total_Count (
Nodes => (1 => Node (Call)),
Within => Within);
end Call_Count;
function Call_Count (Link : Link_T)
return Flow.Execution.Count_T
is
begin
return Call_Count (
Call => Call (Link),
Within => Caller_Bounds (Link));
end Call_Count;
--
--- The nodes, edges etc that are executed on the worst-case path
--
function Executed_Edges (Within : Bounds_Ref)
return Flow.Edge_List_T
is
Graph : constant Flow.Graph_T := Flow_Graph (Within);
-- The underlying flow-graph.
Max_Edge : constant Flow.Edge_Count_T := Flow.Max_Edge (Graph);
-- The edges are indexed 1 .. Max_Edge.
List : Flow.Edge_List_T (1 .. Natural (Max_Edge));
Last : Natural := 0;
-- The result will be List(1 .. Last).
Edge : Flow.Edge_T;
-- The edge under consideration.
begin
for E in 1 .. Max_Edge loop
Edge := Flow.Edge_At (Index => E, Within => Graph);
if Count (Edge, Within) > 0 then
Last := Last + 1;
List(Last) := Edge;
end if;
end loop;
return List(1 .. Last);
end Executed_Edges;
function Executed_Call_Bounds (Within : Bounds_Ref)
return Call_Bounds_List_T
is
List : Call_Bounds_List_T (1 .. Within.Call_Bounds'Length);
Last : Natural := 0;
-- The result is List(1 .. Last).
begin
for C in Within.Call_Bounds'Range loop
if Call_Count (Within.Call_Bounds(C).Call, Within) > 0 then
Last := Last + 1;
List(Last) := Within.Call_Bounds(C);
end if;
end loop;
return List(1 .. Last);
end Executed_Call_Bounds;
--
--- Total execution time for (sets of) nodes, edges, loops, calls
--
function Total_Time (
Nodes : Flow.Node_List_T;
Within : Bounds_Ref;
With_Calls : Boolean)
return Processor.Time_T
is
use type Processor.Time_T;
Sum : Processor.Time_T := 0;
-- The total to be.
begin
if Counts_Set (Within)
and Node_Times_Bounded (Within)
then
for N in Nodes'Range loop
Sum := Sum
+ Processor.Time_T (Count (Nodes(N), Within))
* Time (Nodes(N), Within, With_Calls);
end loop;
end if;
return Sum;
end Total_Time;
function Total_Time (
Edges : Flow.Edge_List_T;
Within : Bounds_Ref)
return Processor.Time_T
is
use type Processor.Time_T;
Sum : Processor.Time_T := 0;
-- The total to be.
begin
if Counts_Set (Within)
and Edge_Times_Bounded (Within)
then
for E in Edges'Range loop
Sum := Sum
+ Processor.Time_T (Count (Edges(E), Within))
* Time (Edges(E), Within);
end loop;
end if;
return Sum;
end Total_Time;
function Total_Edge_Time (Within : Bounds_Ref)
return Time_Sum_T
is
use type Flow.Node_T;
use type Processor.Time_T;
Graph : constant Flow.Graph_T := Flow_Graph (Within);
-- The underlying control-flow graph.
Time : Step_Edge_Times_T renames Within.Step_Edge_Times.all;
-- The execution time of each step edge.
Count : Flow_Counts_T renames Within.Flow_Counts.all;
-- The execution count of nodes and node edges.
Total : Time_Sum_T := (
Num => 0,
Sum => 0,
Min => Processor.Time_T'Last,
Max => Processor.Time_T'First);
-- The result, initially neutral for adding more.
Edge : Flow.Step_Edge_T;
-- A step edge under consideration.
Source, Target : Flow.Node_T;
-- The source and target nodes of the Edge.
procedure Include (
Count : in Flow.Execution.Count_T;
Time : in Processor.Time_T)
--
-- Includes in the Total result an edge with the given
-- execution Count and Time, if Count > 0 and Time > 0.
--
is
begin
if Count > 0 and Time > 0 then
-- This edge is on the worst-case path and contributes
-- a nonzero amount to the execution time bound.
Total.Num := Total.Num + 1;
Total.Sum := Total.Sum + Count * Time;
Total.Min := Processor.Time_T'Min (Total.Min, Time);
Total.Max := Processor.Time_T'Max (Total.Max, Time);
end if;
end Include;
begin -- Total_Edge_Time
-- First, we scan all the step-edges, find the step-edges that
-- are internal to some node, and add up the execution time of
-- these edges, multiplying by the execution count of the node
-- in question.
--
-- Second, we scan all the node-edges and add up their execution
-- times, multiplying by the execution count of the edge itself.
-- Add up the intra-node (step-) edges:
for E in Time'Range loop
if Time(E) > 0 then
-- This edge may contribute to the Sum.
Edge := Flow.Edge_At (Index => E, Within => Graph);
Source := Flow.Node_Containing (Flow.Source (Edge), Graph);
Target := Flow.Node_Containing (Flow.Target (Edge), Graph);
if Source = Target then
-- An intra-node edge.
Include (
Count => Count.Node(Flow.Index (Source)),
Time => Time(E));
end if;
end if;
end loop;
-- Add up the inter-node (node-) edges:
for E in Count.Edge'Range loop
-- E is the index of a node-edge.
if Count.Edge(E) > 0 then
-- This edge may contribute to the Sum.
Edge := Flow.Step_Edge (Flow.Edge_At (E, Graph));
-- The step-edge corresponding to node-edge E.
Include (
Count => Count.Edge(E),
Time => Time(Flow.Index (Edge)));
end if;
end loop;
if Total.Num = 0 then
-- No edges contribute to the worst-case execution time bound.
Total.Min := 0;
Total.Max := 0;
end if;
return Total;
end Total_Edge_Time;
function Total_Time (
Luup : Loops.Loop_T;
Within : Bounds_Ref;
With_Calls : Boolean)
return Processor.Time_T
is
use type Flow.Edge_List_T;
use type Processor.Time_T;
Graph : Flow.Graph_T;
-- The flow-graph of the subprogram that contains the loop.
begin
Graph := Flow_Graph (Subprogram (Within));
-- Assumes Defined (Within).
return
Total_Time (
Nodes => Flow.To_List (
Set => Loops.Members (Luup).all,
From => Graph),
Within => Within,
With_Calls => With_Calls)
+ Total_Time (
Edges =>
Loops.Internal_Edges (Luup, Graph)
& Loops.Repeat_Edges (Luup, Graph),
Within => Within);
end Total_Time;
function Total_Time (
Call : Call_T;
Within : Bounds_Ref)
return Processor.Time_T
is
begin
return Total_Time (
Nodes => (1 => Node (Call)),
Within => Within,
With_Calls => True);
end Total_Time;
function Total_Time (Link : Link_T)
return Processor.Time_T
is
begin
return Total_Time (
Call => Call (Link),
Within => Caller_Bounds (Link));
end Total_Time;
function Total_Time (
Calls : Call_Bounds_List_T;
Within : Bounds_Ref)
return Processor.Time_T
is
use type Processor.Time_T;
Total : Processor.Time_T := 0;
-- The sum total.
CB : Call_Bounds_T;
-- One of the Calls.
begin
for C in Calls'Range loop
CB := Calls(C);
if Time_Bounded (CB.Bounds) then
Total := Total + Call_Count (CB.Call, Within) * Time (CB.Bounds);
end if;
end loop;
return Total;
end Total_Time;
function Callee_Time (Within : Bounds_Ref)
return Processor.Time_T
is
begin
return Total_Time (
Calls => Within.Call_Bounds,
Within => Within);
end Callee_Time;
--
-- Final stack height bounds
--
function Final_Stack_Height_Known (
Stack : Stack_T;
Within : Bounds_Ref)
return Boolean
is
begin
return (not Returns (Within))
or else Singular (Within.Final_Stack_Height(Index (Stack)));
end Final_Stack_Height_Known;
function Final_Stack_Heights_Known (Within : Bounds_Ref)
return Boolean
is
begin
if Returns (Within) then
for S in Within.Final_Stack_Height'Range loop
if not Singular (Within.Final_Stack_Height(S)) then
return False;
end if;
end loop;
end if;
return True;
end Final_Stack_Heights_Known;
function Final_Stack_Height (
Stack : Stack_T;
Within : Bounds_Ref)
return Final_Stack_Height_T
is
begin
return Within.Final_Stack_Height (Index (Stack));
end Final_Stack_Height;
function Loose_Final_Stack_Heights (Within : Bounds_Ref)
return Storage.Cell_List_T
is
Stacks : constant Stacks_T := Programs.Stacks (Program (Within));
-- All the stacks in this program.
Result : Storage.Cell_List_T (1 .. Stacks'Length);
Last : Natural := 0;
-- The result will be Result(1 .. Last).
Stack : Stack_T;
-- One of the Stacks.
begin
for S in Stacks'Range loop
Stack := Stacks(S);
if not Final_Stack_Height_Known (Stack, Within) then
Last := Last + 1;
Result(Last) := Height (Stack);
end if;
end loop;
return Result(1 .. Last);
end Loose_Final_Stack_Heights;
function Final_Stack_Effect (From : Bounds_Ref)
return Arithmetic.Effect_T
is
use Arithmetic;
use type Arithmetic.Value_T;
Stacks : constant Stacks_T := Programs.Stacks (Program (From));
-- All the stacks in the program.
Effect : Assignment_Set_T (Max_Size => 2 * Stacks'Length);
-- The assignments to the local-stack-height and stack-pointer
-- cells. Note that some such cells may not be assigned at all.
Final : Final_Stack_Height_T;
-- The bounds on the final stack height for one stack.
Final_Value : Arithmetic.Value_T;
-- The final stack height, if bounded to a single value.
Height_Var : Variable_T;
-- The variable that holds the local height of the stack.
Pointer_Var : Variable_T;
-- The variable that is the pointer for the stack,
-- or Unknown if the stack has no (known) pointer.
Set_Height : Assignment_T;
-- The assignment that updates the Height_Var.
begin
for S in Stacks'Range loop
Final := From.Final_Stack_Height(S);
Height_Var := Height (Stacks(S));
Pointer_Var := Pointer (Stacks(S));
if Singular (Final) then
-- A single known value (change in stack height).
Final_Value := Single_Value (Final);
if Final_Value /= 0 then
-- The stack height is changed.
Set_Height := Set (
Target => Height_Var,
Value => Height_Var
+ Const (
Value => Final_Value,
Width => Width_Of (Stacks(S)),
Signed => True));
Add (Effect, Set_Height);
if Pointer_Var /= Unknown then
-- The stack pointer changes too.
Algebra.Add_Coupled_Update (
Absolute => Set_Height,
Relative => Pointer_Var,
Coupling => Coupling (Stacks(S)),
To => Effect);
--
-- The roles of "absolute" and "relative" are a
-- little inverted here, but never mind, it works.
end if;
else
-- The Height_Var is not changed, but we add the silly
-- assignment Height_Var := Height_Var in order to shield
-- Height_Var from being veiled in the operation
-- Flow.Calls.Add_Unknown_Call_Effect.
-- TBM to a neater solution.
Add (Effect, Set (Height_Var, Height_Var));
if Pointer_Var /= Unknown then
Add (Effect, Set (Pointer_Var, Pointer_Var));
end if;
end if;
else
-- A range of values, perhaps effectively unbounded.
Add (Effect, Set (Target => Height_Var));
if Pointer_Var /= Unknown then
Add (Effect, Set (Target => Pointer_Var));
end if;
Output.Warning (
"Final effect on stack "
& Name (Stacks(S))
& " not exactly known"
& Output.Field_Separator
& Image (
Item => Final,
Name => Image (Height_Var)));
end if;
end loop;
return To_Effect (Effect);
end Final_Stack_Effect;
--
--- Stack limits
--
function Unbounded return Stack_Limit_T
is
begin
return Unlimited;
end Unbounded;
function Max (Left, Right : Stack_Limit_T)
return Stack_Limit_T
is
begin
return Left or Right;
end Max;
function Max (Left : Stack_Limit_T; Right : Arithmetic.Value_T)
return Stack_Limit_T
is
begin
return Left or Singleton (Right);
end Max;
function Value_Image (Item : Stack_Usage_T) return String
is
begin
case Item.State is
when Undefined => return "undefined";
when Vague => return "parts not bounded";
when Depends => return "context dependent";
when Space_Bounded_T => return Arithmetic.Image (Item.Height);
when Infeasible => return "infeasible";
when Unbounded => return "+inf";
end case;
end Value_Image;
function Brief_Image (Item : Stack_Usage_T) return String
is
begin
case Item.State is
when Undefined => return "??";
when Vague => return "?";
when Depends => return "ctxt";
when Space_Bounded_T => return Arithmetic.Image (Item.Height);
when Infeasible => return "-";
when Unbounded => return "inf";
end case;
end Brief_Image;
function Total_Usage (
Call : Call_T;
Take_Off : Stack_Limit_T;
Callee : Stack_Usage_T)
return Stack_Usage_T
is
use type Arithmetic.Value_T;
begin
case Callee.State is
when Space_Bounded_T =>
if Bounded (Take_Off) then
-- A bounded take-off plus a bounded callee, so
-- we have a Computed total usage.
return (
State => Computed,
Height => Max (Take_Off) + Callee.Height,
Call => Call);
else
-- The take-off is not yet bounded, but we hope that
-- it Depends on context and can be bounded later.
return (
State => Depends,
Height => 0,
Call => Call);
end if;
when Vague | Depends | Infeasible | Unbounded =>
return (
State => Callee.State,
Height => 0,
Call => Call);
when Undefined =>
Output.Fault (
Location => "Programs.Execution.Total_Usage",
Locus => Locus (Call),
Text => "Callee bounds Undefined.");
return (
State => Undefined,
Height => 0,
Call => Call);
end case;
end Total_Usage;
subtype Space_Fuzzy_T is Space_State_T range Undefined .. Depends;
--
-- A space-state that is not (yet) well defined.
function Max (Left, Right : Stack_Usage_T)
return Stack_Usage_T
is
use Storage;
use type Arithmetic.Value_T;
Result : Stack_Usage_T;
begin
if Left.State in Space_Bounded_T
and Right.State in Space_Bounded_T
then
-- We can compare Left and Right bounds quantitatively.
if Left.Height >= Right.Height then
Result := (
State => Computed,
Height => Left.Height,
Call => Left.Call);
else
Result := (
State => Computed,
Height => Right.Height,
Call => Right.Call);
end if;
elsif Left.State = Unbounded
or Right.State = Unbounded
then
Result := (
State => Unbounded,
Height => 0,
Call => No_Call);
elsif Left.State in Space_Fuzzy_T
or Right.State in Space_Fuzzy_T
then
Result := (
State => Space_State_T'Min (Left.State, Right.State),
Height => 0,
Call => No_Call);
elsif Left.State = Infeasible then
-- The Left code cannot be executed, so it has no effect
-- on the overall stack usage.
Result := Right;
elsif Right.State = Infeasible then
-- The Right code cannot be executed, so it has no effect
-- on the overall stack usage.
Result := Left;
else
Output.Fault (
Location => "Programs.Execution.Max (Stack_Usage_T)",
Text => "Unhandled combination of states.");
Result := (
State => Undefined,
Height => 0,
Call => No_Call);
end if;
return Result;
end Max;
function Bounded (Item : Stack_Limit_T) return Boolean
is
begin
return Storage.Bounds.Known (Item.Max);
end Bounded;
function Exact (Item : Stack_Limit_T) return Boolean
is
begin
return Singular (Item);
end Exact;
function Bounded (Item : Stack_Usage_T) return Boolean
is
begin
return Item.State in Space_Bounded_T;
end Bounded;
function Space_Bounded (Item : in Bounds_Ref)
return Boolean
is
begin
return Stack_Usage_Bounded (Item);
end Space_Bounded;
function Stack_Height_Bounded (
Stack : Stack_T;
Within : in Bounds_Ref)
return Boolean
is
begin
if not Defined (Within) then
-- Huh. Should not happen.
Output.Fault (
Location => "Programs.Execution.Stack_Height_Bounded",
Text => "Null bounds!");
return False;
end if;
return Bounded (Within.Stack_Height(Index (Stack)));
end Stack_Height_Bounded;
function Stack_Height (
Stack : Stack_T;
Within : Bounds_Ref)
return Stack_Limit_T
is
begin
return Within.Stack_Height(Index (Stack));
end Stack_Height;
function Stack_Usage_Bounded (
Stack : Stack_T;
Within : Bounds_Ref)
return Boolean
is
begin
return Bounded (Within.Max_Stack_Usage(Index (Stack)));
end Stack_Usage_Bounded;
function Stack_Usage_Bounded (Item : in Bounds_Ref)
return Boolean
is
All_Bounded : Boolean := True;
-- Whether all stack usage is bounded.
-- We ain't seen anything to the contrary yet.
begin
if not Defined (Item) then
-- Huh. Should not happen.
Output.Fault (
Location => "Programs.Execution.Stack_Usage_Bounded",
Text => "Null bounds!");
return False;
end if;
for S in 1 .. Item.Num_Stacks loop
All_Bounded := All_Bounded
and Bounded (Item.Max_Stack_Usage(S));
end loop;
return All_Bounded;
end Stack_Usage_Bounded;
function Stack_Usage (
Stack : Stack_T;
Within : Bounds_Ref)
return Stack_Usage_T
is
begin
return Within.Max_Stack_Usage(Index (Stack));
end Stack_Usage;
function Space_State (
Stack : Stack_T;
Within : Bounds_Ref)
return Space_State_T
is
begin
return Within.Max_Stack_Usage(Index (Stack)).State;
end Space_State;
function Space_State (Within : Bounds_Ref)
return Space_State_T
is
Any : array (Space_State_T) of Boolean := (others => False);
-- Whether any stack is a given state.
begin
-- Collect all states:
for M in Within.Max_Stack_Usage'Range loop
Any(Within.Max_Stack_Usage(M).State) := True;
end loop;
-- Check in order:
if Any(Infeasible) then return Infeasible;
elsif Any(Depends ) then return Depends ;
elsif Any(Vague ) then return Vague ;
elsif Any(Undefined ) then return Undefined ;
elsif Any(Unbounded ) then return Unbounded ;
elsif Any(Computed ) then return Computed ;
else return Asserted ;
end if;
end Space_State;
function Loose_Stack_Heights (Within : Bounds_Ref)
return Storage.Cell_List_T
is
Stacks : constant Stacks_T := Programs.Stacks (Program (Within));
-- All the stacks in this program.
Result : Storage.Cell_List_T (1 .. Stacks'Length);
Last : Natural := 0;
-- The result will be Result(1 .. Last).
Stack : Stack_T;
-- One of the Stacks.
begin
for S in Stacks'Range loop
Stack := Stacks(S);
if not Stack_Usage_Bounded (Stack, Within) then
Last := Last + 1;
Result(Last) := Height (Stack);
end if;
end loop;
return Result(1 .. Last);
end Loose_Stack_Heights;
function Take_Off_Height_Bounded (
Stack : Stack_T;
Before : Call_T;
Within : Bounds_Ref)
return Boolean
is
begin
return Bounded (Take_Off_Height (Stack, Before, Within));
end Take_Off_Height_Bounded;
function Take_Off_Height (
Stack : Stack_T;
Before : Call_T;
Within : Bounds_Ref)
return Stack_Limit_T
is
begin
if not Defined (Within) then
Output.Fault (
Location => "Programs.Execution.Take_Off_Height",
Text => "Undefined bounds");
return Unlimited;
end if;
return Within.Take_Off_Limits(Index (Before), Index (Stack));
end Take_Off_Height;
function Max_Image (Item : Stack_Limit_T) return String
is
use Storage.Bounds;
Max_Limit : constant Limit_T := Item.Max;
-- The upper bound.
begin
if Known (Max_Limit) then
return Arithmetic.Image (Value (Max_Limit));
else
return "+inf";
end if;
end Max_Image;
--
--- Bounds_Subset_T operations
--
procedure Erase (Subset : in out Bounds_Subset_T)
is
begin
Subset.Members := (others => False);
end Erase;
function Is_Member (
Index : Bounds_Index_T;
Of_Set : Bounds_Subset_T)
return Boolean
is
begin
return Index in Of_Set.Members'Range and then Of_Set.Members(Index);
end Is_Member;
function Is_Member (
Item : Bounds_Ref;
Of_Set : Bounds_Subset_T)
return Boolean
is
begin
return Is_Member (Index(Item), Of_Set);
end Is_Member;
procedure Add (
Item : in Bounds_Ref;
To : in out Bounds_Subset_T)
is
begin
if Index (Item) in To.Members'Range then
To.Members(Index (Item)) := True;
else
Output.Fault (
Location => "Programs.Execution.Add (Bounds to Subset)",
Text =>
"Bounds #"
& Bounds_Index_T'Image (Index (Item))
& " cannot be added, max subset size is"
& Bounds_Count_T'Image (To.Max_Size));
end if;
end Add;
end Programs.Execution;
|
Fabien-Chouteau/GESTE | Ada | 3,305 | adb | with Ada.Real_Time;
with Render;
with Keyboard;
with Levels;
with Player;
with GESTE;
with GESTE.Text;
with GESTE_Config;
with GESTE_Fonts.FreeMono5pt7b;
package body Game is
package RT renames Ada.Real_Time;
use type RT.Time;
use type RT.Time_Span;
Text : aliased GESTE.Text.Instance
(GESTE_Fonts.FreeMono5pt7b.Font,
15, 1,
Render.Black,
GESTE_Config.Transparent);
Frame_Counter : Natural := 0;
Next_FPS_Update : RT.Time := RT.Clock + RT.Seconds (1);
Period : constant RT.Time_Span := RT.Seconds (1) / 60;
Next_Release : RT.Time := RT.Clock + Period;
Lvl : Levels.Level_Id := Levels.Lvl_1;
---------------
-- Game_Loop --
---------------
procedure Game_Loop is
begin
loop
if Player.Position.X > 320 - 3 then
case Lvl is
when Levels.Lvl_1 =>
Levels.Leave (Levels.Lvl_1);
Levels.Enter (Levels.Lvl_2);
Lvl := Levels.Lvl_2;
Player.Move ((3, 125));
when Levels.Lvl_2 =>
Levels.Leave (Levels.Lvl_2);
Levels.Enter (Levels.Lvl_3);
Lvl := Levels.Lvl_3;
Player.Move ((3, 183));
when Levels.Lvl_3 =>
Levels.Leave (Levels.Lvl_3);
Levels.Enter (Levels.Lvl_1);
Lvl := Levels.Lvl_1;
Player.Move ((3, 142));
end case;
elsif Player.Position.X < 2 then
case Lvl is
when Levels.Lvl_1 =>
Levels.Leave (Levels.Lvl_1);
Levels.Enter (Levels.Lvl_3);
Lvl := Levels.Lvl_3;
Player.Move ((320 - 4, 183));
when Levels.Lvl_2 =>
Levels.Leave (Levels.Lvl_2);
Levels.Enter (Levels.Lvl_1);
Lvl := Levels.Lvl_1;
Player.Move ((320 - 4, 120));
when Levels.Lvl_3 =>
Levels.Leave (Levels.Lvl_3);
Levels.Enter (Levels.Lvl_2);
Lvl := Levels.Lvl_2;
Player.Move ((320 - 4, 25));
end case;
end if;
Keyboard.Update;
if Keyboard.Pressed (Keyboard.Up) then
Player.Jump;
end if;
if Keyboard.Pressed (Keyboard.Left) then
Player.Move_Left;
end if;
if Keyboard.Pressed (Keyboard.Right) then
Player.Move_Right;
end if;
if Keyboard.Pressed (Keyboard.Esc) then
return;
end if;
Player.Update;
Frame_Counter := Frame_Counter + 1;
if Next_FPS_Update <= RT.Clock then
Next_FPS_Update := RT.Clock + RT.Seconds (1);
Text.Clear;
Text.Cursor (1, 1);
Text.Put ("FPS:" & Frame_Counter'Img);
Frame_Counter := 0;
end if;
Render.Render_Dirty (Render.Dark_Cyan);
delay until Next_Release;
Next_Release := RT.Clock + Period;
end loop;
end Game_Loop;
begin
Levels.Enter (Levels.Lvl_1);
Player.Move ((3, 142));
Text.Move ((0, 0));
GESTE.Add (Text'Access, 10);
Render.Render_All (Render.Dark_Cyan);
end Game;
|
reznikmm/matreshka | Ada | 3,679 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with XML.DOM.Attributes;
package ODF.DOM.Fo_Color_Attributes is
pragma Preelaborate;
type ODF_Fo_Color_Attribute is limited interface
and XML.DOM.Attributes.DOM_Attribute;
type ODF_Fo_Color_Attribute_Access is
access all ODF_Fo_Color_Attribute'Class
with Storage_Size => 0;
end ODF.DOM.Fo_Color_Attributes;
|
reznikmm/matreshka | Ada | 28,860 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with AMF.Internals.UML_Named_Elements;
with AMF.String_Collections;
with AMF.UML.Behaviors;
with AMF.UML.Classifiers.Collections;
with AMF.UML.Connection_Point_References.Collections;
with AMF.UML.Constraints.Collections;
with AMF.UML.Dependencies.Collections;
with AMF.UML.Element_Imports.Collections;
with AMF.UML.Final_States;
with AMF.UML.Named_Elements.Collections;
with AMF.UML.Namespaces;
with AMF.UML.Package_Imports.Collections;
with AMF.UML.Packageable_Elements.Collections;
with AMF.UML.Packages.Collections;
with AMF.UML.Pseudostates.Collections;
with AMF.UML.Redefinable_Elements.Collections;
with AMF.UML.Regions.Collections;
with AMF.UML.State_Machines;
with AMF.UML.States;
with AMF.UML.String_Expressions;
with AMF.UML.Transitions.Collections;
with AMF.UML.Triggers.Collections;
with AMF.Visitors;
package AMF.Internals.UML_Final_States is
type UML_Final_State_Proxy is
limited new AMF.Internals.UML_Named_Elements.UML_Named_Element_Proxy
and AMF.UML.Final_States.UML_Final_State with null record;
overriding function Get_Connection
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Connection_Point_References.Collections.Set_Of_UML_Connection_Point_Reference;
-- Getter of State::connection.
--
-- The entry and exit connection points used in conjunction with this
-- (submachine) state, i.e. as targets and sources, respectively, in the
-- region with the submachine state. A connection point reference
-- references the corresponding definition of a connection point
-- pseudostate in the statemachine referenced by the submachinestate.
overriding function Get_Connection_Point
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Pseudostates.Collections.Set_Of_UML_Pseudostate;
-- Getter of State::connectionPoint.
--
-- The entry and exit pseudostates of a composite state. These can only be
-- entry or exit Pseudostates, and they must have different names. They
-- can only be defined for composite states.
overriding function Get_Deferrable_Trigger
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Triggers.Collections.Set_Of_UML_Trigger;
-- Getter of State::deferrableTrigger.
--
-- A list of triggers that are candidates to be retained by the state
-- machine if they trigger no transitions out of the state (not consumed).
-- A deferred trigger is retained until the state machine reaches a state
-- configuration where it is no longer deferred.
overriding function Get_Do_Activity
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Behaviors.UML_Behavior_Access;
-- Getter of State::doActivity.
--
-- An optional behavior that is executed while being in the state. The
-- execution starts when this state is entered, and stops either by
-- itself, or when the state is exited, whichever comes first.
overriding procedure Set_Do_Activity
(Self : not null access UML_Final_State_Proxy;
To : AMF.UML.Behaviors.UML_Behavior_Access);
-- Setter of State::doActivity.
--
-- An optional behavior that is executed while being in the state. The
-- execution starts when this state is entered, and stops either by
-- itself, or when the state is exited, whichever comes first.
overriding function Get_Entry
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Behaviors.UML_Behavior_Access;
-- Getter of State::entry.
--
-- An optional behavior that is executed whenever this state is entered
-- regardless of the transition taken to reach the state. If defined,
-- entry actions are always executed to completion prior to any internal
-- behavior or transitions performed within the state.
overriding procedure Set_Entry
(Self : not null access UML_Final_State_Proxy;
To : AMF.UML.Behaviors.UML_Behavior_Access);
-- Setter of State::entry.
--
-- An optional behavior that is executed whenever this state is entered
-- regardless of the transition taken to reach the state. If defined,
-- entry actions are always executed to completion prior to any internal
-- behavior or transitions performed within the state.
overriding function Get_Exit
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Behaviors.UML_Behavior_Access;
-- Getter of State::exit.
--
-- An optional behavior that is executed whenever this state is exited
-- regardless of which transition was taken out of the state. If defined,
-- exit actions are always executed to completion only after all internal
-- activities and transition actions have completed execution.
overriding procedure Set_Exit
(Self : not null access UML_Final_State_Proxy;
To : AMF.UML.Behaviors.UML_Behavior_Access);
-- Setter of State::exit.
--
-- An optional behavior that is executed whenever this state is exited
-- regardless of which transition was taken out of the state. If defined,
-- exit actions are always executed to completion only after all internal
-- activities and transition actions have completed execution.
overriding function Get_Is_Composite
(Self : not null access constant UML_Final_State_Proxy)
return Boolean;
-- Getter of State::isComposite.
--
-- A state with isComposite=true is said to be a composite state. A
-- composite state is a state that contains at least one region.
overriding function Get_Is_Orthogonal
(Self : not null access constant UML_Final_State_Proxy)
return Boolean;
-- Getter of State::isOrthogonal.
--
-- A state with isOrthogonal=true is said to be an orthogonal composite
-- state. An orthogonal composite state contains two or more regions.
overriding function Get_Is_Simple
(Self : not null access constant UML_Final_State_Proxy)
return Boolean;
-- Getter of State::isSimple.
--
-- A state with isSimple=true is said to be a simple state. A simple state
-- does not have any regions and it does not refer to any submachine state
-- machine.
overriding function Get_Is_Submachine_State
(Self : not null access constant UML_Final_State_Proxy)
return Boolean;
-- Getter of State::isSubmachineState.
--
-- A state with isSubmachineState=true is said to be a submachine state.
-- Such a state refers to a state machine (submachine).
overriding function Get_Redefined_State
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.States.UML_State_Access;
-- Getter of State::redefinedState.
--
-- The state of which this state is a redefinition.
overriding procedure Set_Redefined_State
(Self : not null access UML_Final_State_Proxy;
To : AMF.UML.States.UML_State_Access);
-- Setter of State::redefinedState.
--
-- The state of which this state is a redefinition.
overriding function Get_Redefinition_Context
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Classifiers.UML_Classifier_Access;
-- Getter of State::redefinitionContext.
--
-- References the classifier in which context this element may be
-- redefined.
overriding function Get_Region
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Regions.Collections.Set_Of_UML_Region;
-- Getter of State::region.
--
-- The regions owned directly by the state.
overriding function Get_State_Invariant
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Constraints.UML_Constraint_Access;
-- Getter of State::stateInvariant.
--
-- Specifies conditions that are always true when this state is the
-- current state. In protocol state machines, state invariants are
-- additional conditions to the preconditions of the outgoing transitions,
-- and to the postcondition of the incoming transitions.
overriding procedure Set_State_Invariant
(Self : not null access UML_Final_State_Proxy;
To : AMF.UML.Constraints.UML_Constraint_Access);
-- Setter of State::stateInvariant.
--
-- Specifies conditions that are always true when this state is the
-- current state. In protocol state machines, state invariants are
-- additional conditions to the preconditions of the outgoing transitions,
-- and to the postcondition of the incoming transitions.
overriding function Get_Submachine
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.State_Machines.UML_State_Machine_Access;
-- Getter of State::submachine.
--
-- The state machine that is to be inserted in place of the (submachine)
-- state.
overriding procedure Set_Submachine
(Self : not null access UML_Final_State_Proxy;
To : AMF.UML.State_Machines.UML_State_Machine_Access);
-- Setter of State::submachine.
--
-- The state machine that is to be inserted in place of the (submachine)
-- state.
overriding function Get_Is_Leaf
(Self : not null access constant UML_Final_State_Proxy)
return Boolean;
-- Getter of RedefinableElement::isLeaf.
--
-- Indicates whether it is possible to further redefine a
-- RedefinableElement. If the value is true, then it is not possible to
-- further redefine the RedefinableElement. Note that this property is
-- preserved through package merge operations; that is, the capability to
-- redefine a RedefinableElement (i.e., isLeaf=false) must be preserved in
-- the resulting RedefinableElement of a package merge operation where a
-- RedefinableElement with isLeaf=false is merged with a matching
-- RedefinableElement with isLeaf=true: the resulting RedefinableElement
-- will have isLeaf=false. Default value is false.
overriding procedure Set_Is_Leaf
(Self : not null access UML_Final_State_Proxy;
To : Boolean);
-- Setter of RedefinableElement::isLeaf.
--
-- Indicates whether it is possible to further redefine a
-- RedefinableElement. If the value is true, then it is not possible to
-- further redefine the RedefinableElement. Note that this property is
-- preserved through package merge operations; that is, the capability to
-- redefine a RedefinableElement (i.e., isLeaf=false) must be preserved in
-- the resulting RedefinableElement of a package merge operation where a
-- RedefinableElement with isLeaf=false is merged with a matching
-- RedefinableElement with isLeaf=true: the resulting RedefinableElement
-- will have isLeaf=false. Default value is false.
overriding function Get_Redefined_Element
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Redefinable_Elements.Collections.Set_Of_UML_Redefinable_Element;
-- Getter of RedefinableElement::redefinedElement.
--
-- The redefinable element that is being redefined by this element.
overriding function Get_Redefinition_Context
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Classifiers.Collections.Set_Of_UML_Classifier;
-- Getter of RedefinableElement::redefinitionContext.
--
-- References the contexts that this element may be redefined from.
overriding function Get_Client_Dependency
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Dependencies.Collections.Set_Of_UML_Dependency;
-- Getter of NamedElement::clientDependency.
--
-- Indicates the dependencies that reference the client.
overriding function Get_Name_Expression
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.String_Expressions.UML_String_Expression_Access;
-- Getter of NamedElement::nameExpression.
--
-- The string expression used to define the name of this named element.
overriding procedure Set_Name_Expression
(Self : not null access UML_Final_State_Proxy;
To : AMF.UML.String_Expressions.UML_String_Expression_Access);
-- Setter of NamedElement::nameExpression.
--
-- The string expression used to define the name of this named element.
overriding function Get_Namespace
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Namespaces.UML_Namespace_Access;
-- Getter of NamedElement::namespace.
--
-- Specifies the namespace that owns the NamedElement.
overriding function Get_Qualified_Name
(Self : not null access constant UML_Final_State_Proxy)
return AMF.Optional_String;
-- Getter of NamedElement::qualifiedName.
--
-- A name which allows the NamedElement to be identified within a
-- hierarchy of nested Namespaces. It is constructed from the names of the
-- containing namespaces starting at the root of the hierarchy and ending
-- with the name of the NamedElement itself.
overriding function Get_Element_Import
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Element_Imports.Collections.Set_Of_UML_Element_Import;
-- Getter of Namespace::elementImport.
--
-- References the ElementImports owned by the Namespace.
overriding function Get_Imported_Member
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element;
-- Getter of Namespace::importedMember.
--
-- References the PackageableElements that are members of this Namespace
-- as a result of either PackageImports or ElementImports.
overriding function Get_Member
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element;
-- Getter of Namespace::member.
--
-- A collection of NamedElements identifiable within the Namespace, either
-- by being owned or by being introduced by importing or inheritance.
overriding function Get_Owned_Member
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element;
-- Getter of Namespace::ownedMember.
--
-- A collection of NamedElements owned by the Namespace.
overriding function Get_Owned_Rule
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Constraints.Collections.Set_Of_UML_Constraint;
-- Getter of Namespace::ownedRule.
--
-- Specifies a set of Constraints owned by this Namespace.
overriding function Get_Package_Import
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Package_Imports.Collections.Set_Of_UML_Package_Import;
-- Getter of Namespace::packageImport.
--
-- References the PackageImports owned by the Namespace.
overriding function Get_Container
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Regions.UML_Region_Access;
-- Getter of Vertex::container.
--
-- The region that contains this vertex.
overriding procedure Set_Container
(Self : not null access UML_Final_State_Proxy;
To : AMF.UML.Regions.UML_Region_Access);
-- Setter of Vertex::container.
--
-- The region that contains this vertex.
overriding function Get_Incoming
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Transitions.Collections.Set_Of_UML_Transition;
-- Getter of Vertex::incoming.
--
-- Specifies the transitions entering this vertex.
overriding function Get_Outgoing
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Transitions.Collections.Set_Of_UML_Transition;
-- Getter of Vertex::outgoing.
--
-- Specifies the transitions departing from this vertex.
overriding function Containing_State_Machine
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.State_Machines.UML_State_Machine_Access;
-- Operation State::containingStateMachine.
--
-- The query containingStateMachine() returns the state machine that
-- contains the state either directly or transitively.
overriding function Is_Composite
(Self : not null access constant UML_Final_State_Proxy)
return Boolean;
-- Operation State::isComposite.
--
-- A composite state is a state with at least one region.
overriding function Is_Consistent_With
(Self : not null access constant UML_Final_State_Proxy;
Redefinee : AMF.UML.Redefinable_Elements.UML_Redefinable_Element_Access)
return Boolean;
-- Operation State::isConsistentWith.
--
-- The query isConsistentWith() specifies that a redefining state is
-- consistent with a redefined state provided that the redefining state is
-- an extension of the redefined state: A simple state can be redefined
-- (extended) to become a composite state (by adding a region) and a
-- composite state can be redefined (extended) by adding regions and by
-- adding vertices, states, and transitions to inherited regions. All
-- states may add or replace entry, exit, and 'doActivity' actions.
overriding function Is_Orthogonal
(Self : not null access constant UML_Final_State_Proxy)
return Boolean;
-- Operation State::isOrthogonal.
--
-- An orthogonal state is a composite state with at least 2 regions
overriding function Is_Redefinition_Context_Valid
(Self : not null access constant UML_Final_State_Proxy;
Redefined : AMF.UML.States.UML_State_Access)
return Boolean;
-- Operation State::isRedefinitionContextValid.
--
-- The query isRedefinitionContextValid() specifies whether the
-- redefinition contexts of a state are properly related to the
-- redefinition contexts of the specified state to allow this element to
-- redefine the other. The containing region of a redefining state must
-- redefine the containing region of the redefined state.
overriding function Is_Simple
(Self : not null access constant UML_Final_State_Proxy)
return Boolean;
-- Operation State::isSimple.
--
-- A simple state is a state without any regions.
overriding function Is_Submachine_State
(Self : not null access constant UML_Final_State_Proxy)
return Boolean;
-- Operation State::isSubmachineState.
--
-- Only submachine states can have a reference statemachine.
overriding function Redefinition_Context
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Classifiers.UML_Classifier_Access;
-- Operation State::redefinitionContext.
--
-- The redefinition context of a state is the nearest containing
-- statemachine.
overriding function Is_Redefinition_Context_Valid
(Self : not null access constant UML_Final_State_Proxy;
Redefined : AMF.UML.Redefinable_Elements.UML_Redefinable_Element_Access)
return Boolean;
-- Operation RedefinableElement::isRedefinitionContextValid.
--
-- The query isRedefinitionContextValid() specifies whether the
-- redefinition contexts of this RedefinableElement are properly related
-- to the redefinition contexts of the specified RedefinableElement to
-- allow this element to redefine the other. By default at least one of
-- the redefinition contexts of this element must be a specialization of
-- at least one of the redefinition contexts of the specified element.
overriding function All_Owning_Packages
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Packages.Collections.Set_Of_UML_Package;
-- Operation NamedElement::allOwningPackages.
--
-- The query allOwningPackages() returns all the directly or indirectly
-- owning packages.
overriding function Is_Distinguishable_From
(Self : not null access constant UML_Final_State_Proxy;
N : AMF.UML.Named_Elements.UML_Named_Element_Access;
Ns : AMF.UML.Namespaces.UML_Namespace_Access)
return Boolean;
-- Operation NamedElement::isDistinguishableFrom.
--
-- The query isDistinguishableFrom() determines whether two NamedElements
-- may logically co-exist within a Namespace. By default, two named
-- elements are distinguishable if (a) they have unrelated types or (b)
-- they have related types but different names.
overriding function Namespace
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Namespaces.UML_Namespace_Access;
-- Operation NamedElement::namespace.
--
-- Missing derivation for NamedElement::/namespace : Namespace
overriding function Exclude_Collisions
(Self : not null access constant UML_Final_State_Proxy;
Imps : AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element)
return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element;
-- Operation Namespace::excludeCollisions.
--
-- The query excludeCollisions() excludes from a set of
-- PackageableElements any that would not be distinguishable from each
-- other in this namespace.
overriding function Get_Names_Of_Member
(Self : not null access constant UML_Final_State_Proxy;
Element : AMF.UML.Named_Elements.UML_Named_Element_Access)
return AMF.String_Collections.Set_Of_String;
-- Operation Namespace::getNamesOfMember.
--
-- The query getNamesOfMember() takes importing into account. It gives
-- back the set of names that an element would have in an importing
-- namespace, either because it is owned, or if not owned then imported
-- individually, or if not individually then from a package.
-- The query getNamesOfMember() gives a set of all of the names that a
-- member would have in a Namespace. In general a member can have multiple
-- names in a Namespace if it is imported more than once with different
-- aliases. The query takes account of importing. It gives back the set of
-- names that an element would have in an importing namespace, either
-- because it is owned, or if not owned then imported individually, or if
-- not individually then from a package.
overriding function Import_Members
(Self : not null access constant UML_Final_State_Proxy;
Imps : AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element)
return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element;
-- Operation Namespace::importMembers.
--
-- The query importMembers() defines which of a set of PackageableElements
-- are actually imported into the namespace. This excludes hidden ones,
-- i.e., those which have names that conflict with names of owned members,
-- and also excludes elements which would have the same name when imported.
overriding function Imported_Member
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element;
-- Operation Namespace::importedMember.
--
-- The importedMember property is derived from the ElementImports and the
-- PackageImports. References the PackageableElements that are members of
-- this Namespace as a result of either PackageImports or ElementImports.
overriding function Members_Are_Distinguishable
(Self : not null access constant UML_Final_State_Proxy)
return Boolean;
-- Operation Namespace::membersAreDistinguishable.
--
-- The Boolean query membersAreDistinguishable() determines whether all of
-- the namespace's members are distinguishable within it.
overriding function Owned_Member
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element;
-- Operation Namespace::ownedMember.
--
-- Missing derivation for Namespace::/ownedMember : NamedElement
overriding function Incoming
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Transitions.Collections.Set_Of_UML_Transition;
-- Operation Vertex::incoming.
--
-- Missing derivation for Vertex::/incoming : Transition
overriding function Outgoing
(Self : not null access constant UML_Final_State_Proxy)
return AMF.UML.Transitions.Collections.Set_Of_UML_Transition;
-- Operation Vertex::outgoing.
--
-- Missing derivation for Vertex::/outgoing : Transition
overriding procedure Enter_Element
(Self : not null access constant UML_Final_State_Proxy;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control);
-- Dispatch call to corresponding subprogram of visitor interface.
overriding procedure Leave_Element
(Self : not null access constant UML_Final_State_Proxy;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control);
-- Dispatch call to corresponding subprogram of visitor interface.
overriding procedure Visit_Element
(Self : not null access constant UML_Final_State_Proxy;
Iterator : in out AMF.Visitors.Abstract_Iterator'Class;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control);
-- Dispatch call to corresponding subprogram of iterator interface.
end AMF.Internals.UML_Final_States;
|
AdaCore/gpr | Ada | 22 | ads | package Pkg2 is end;
|
stcarrez/swagger-ada | Ada | 2,094 | ads | -----------------------------------------------------------------------
-- openapi-tests -- Unit tests for REST clients
-- Copyright (C) 2018, 2022, 2023 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Tests;
with OpenAPI.Clients;
with OpenAPI.Credentials.OAuth;
package OpenAPI.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with record
Server : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding
procedure Set_Up (T : in out Test);
procedure Configure (T : in out Test;
Client : in out OpenAPI.Clients.Client_Type'Class);
procedure Authenticate (T : in out Test;
Cred : in out OpenAPI.Credentials.OAuth.OAuth2_Credential_Type);
-- Test unauthorized operations.
procedure Test_Unauthorized (T : in out Test);
-- Test authorized operations.
procedure Test_Authorized (T : in out Test);
-- Test API that uses text/plain response.
procedure Test_Text_Response (T : in out Test);
-- Test API that uses image/png response.
procedure Test_Binary_Response (T : in out Test);
-- Test API that uses an external data type.
procedure Test_External_Data (T : in out Test);
-- Test API that uses a struct with various numbers.
procedure Test_Struct_Numbers (T : in out Test);
end OpenAPI.Tests;
|
ZinebZaad/ENSEEIHT | Ada | 1,863 | adb | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
-- Piloter un drone au moyen d'un menu textuel.
procedure Drone is
Demarrage: Boolean; -- True si le drone est demarré
Altitude: Integer; -- Valeur de l'altitude
Choix: Character; -- Choix de l'utilisateur
begin
Altitude := 0;
loop
Put("Altitude : ");
Put(Altitude, 1);
New_Line;
New_Line;
Put_Line("Que faire ?");
Put_Line(" d -- Démarrer");
Put_Line(" m -- Monter");
Put_Line(" s -- Descendre");
Put_Line(" q -- Quitter");
Put("Votre choix : ");
Get(Choix);
if Choix = 'd' or Choix = 'D' then
Demarrage := True;
elsif Choix = 'm' or Choix = 'M' then
if Demarrage then
Altitude := Altitude + 1;
else
Put_Line("Le drone n'est pas démarré.");
end if;
elsif Choix = 's' or Choix = 'S' then
if Demarrage then
if Altitude = 0 then
Put_Line("Le drone est déjà posé.");
else
Altitude := Altitude - 1;
end if;
else
Put_Line("Le drone n'est pas démarré.");
end if;
elsif Choix = 'q' or Choix = 'Q' then
exit;
else
Put_Line("Je n'ai pas compris !");
end if;
if Altitude > 4 then
New_Line;
Put_Line("Le drone est hors de portée... et donc perdu !");
return;
end if;
New_Line;
end loop;
New_Line;
if Demarrage then
Put_Line("Au revoir...");
else
Put_Line("Vous n'avez pas réussi à le mettre en route ?");
end if;
end Drone;
|
stcarrez/ada-util | Ada | 2,845 | ads | -----------------------------------------------------------------------
-- util-commands-consoles-text -- Text console interface
-- Copyright (C) 2014, 2017, 2018, 2021, 2022, 2023 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
generic
with package IO is new Util.Commands.IO (<>);
with function To_String (Input : in Input_Type) return String is <>;
package Util.Commands.Consoles.Text is
type Console_Type is new Util.Commands.Consoles.Console_Type with private;
-- Report an error message.
overriding
procedure Error (Console : in out Console_Type;
Message : in Input_Type);
-- Report a notice message.
overriding
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in Input_Type);
-- Print the field value for the given field.
overriding
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Input_Type;
Justify : in Justify_Type := J_LEFT);
-- Print the title for the given field.
overriding
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in Input_Type;
Justify : in Justify_Type := J_LEFT);
-- Start a new title in a report.
overriding
procedure Start_Title (Console : in out Console_Type);
-- Finish a new title in a report.
overriding
procedure End_Title (Console : in out Console_Type);
-- Start a new row in a report.
overriding
procedure Start_Row (Console : in out Console_Type);
-- Finish a new row in a report.
overriding
procedure End_Row (Console : in out Console_Type);
private
type Console_Type is new Util.Commands.Consoles.Console_Type with record
Cur_Col : Positive := 1;
end record;
procedure Set_Col (Console : in out Console_Type;
Col : in Positive);
procedure Put (Console : in out Console_Type;
Content : in Input_Type);
end Util.Commands.Consoles.Text;
|
charlie5/lace | Ada | 222 | adb | with
gel_demo_Server;
package body gel_demo_Services
is
function World return gel.remote.World.view
is
begin
return gel_demo_Server.the_server_World.all'access;
end World;
end gel_demo_Services;
|
zhmu/ananas | Ada | 16,732 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . R E S P O N S E _ F I L E --
-- --
-- B o d y --
-- --
-- Copyright (C) 2007-2022, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with System.OS_Lib; use System.OS_Lib;
package body System.Response_File is
type File_Rec;
type File_Ptr is access File_Rec;
type File_Rec is record
Name : String_Access;
Next : File_Ptr;
Prev : File_Ptr;
end record;
-- To build a stack of response file names
procedure Free is new Ada.Unchecked_Deallocation (File_Rec, File_Ptr);
type Argument_List_Access is access Argument_List;
procedure Free is new Ada.Unchecked_Deallocation
(Argument_List, Argument_List_Access);
-- Free only the allocated Argument_List, not allocated String components
--------------------
-- Arguments_From --
--------------------
function Arguments_From
(Response_File_Name : String;
Recursive : Boolean := False;
Ignore_Non_Existing_Files : Boolean := False)
return Argument_List
is
First_File : File_Ptr := null;
Last_File : File_Ptr := null;
-- The stack of response files
Arguments : Argument_List_Access := new Argument_List (1 .. 4);
Last_Arg : Natural := 0;
procedure Add_Argument (Arg : String);
-- Add argument Arg to argument list Arguments, increasing Arguments
-- if necessary.
procedure Recurse (File_Name : String);
-- Get the arguments from the file and call itself recursively if one of
-- the arguments starts with character '@'.
------------------
-- Add_Argument --
------------------
procedure Add_Argument (Arg : String) is
begin
if Last_Arg = Arguments'Last then
declare
New_Arguments : constant Argument_List_Access :=
new Argument_List (1 .. Arguments'Last * 2);
begin
New_Arguments (Arguments'Range) := Arguments.all;
Arguments.all := (others => null);
Free (Arguments);
Arguments := New_Arguments;
end;
end if;
Last_Arg := Last_Arg + 1;
Arguments (Last_Arg) := new String'(Arg);
end Add_Argument;
-------------
-- Recurse --
-------------
procedure Recurse (File_Name : String) is
-- Open the response file. If not found, fail or report a warning,
-- depending on the value of Ignore_Non_Existing_Files.
FD : constant File_Descriptor := Open_Read (File_Name, Text);
Buffer_Size : constant := 1500;
Buffer : String (1 .. Buffer_Size);
Buffer_Length : Natural;
Buffer_Cursor : Natural;
End_Of_File_Reached : Boolean;
Line : String (1 .. Max_Line_Length + 1);
Last : Natural;
First_Char : Positive;
-- Index of the first character of an argument in Line
Last_Char : Natural;
-- Index of the last character of an argument in Line
In_String : Boolean;
-- True when inside a quoted string
Arg : Positive;
function End_Of_File return Boolean;
-- True when the end of the response file has been reached
procedure Get_Buffer;
-- Read one buffer from the response file
procedure Get_Line;
-- Get one line from the response file
-----------------
-- End_Of_File --
-----------------
function End_Of_File return Boolean is
begin
return End_Of_File_Reached and then Buffer_Cursor > Buffer_Length;
end End_Of_File;
----------------
-- Get_Buffer --
----------------
procedure Get_Buffer is
begin
Buffer_Length := Read (FD, Buffer (1)'Address, Buffer'Length);
End_Of_File_Reached := Buffer_Length < Buffer'Length;
Buffer_Cursor := 1;
end Get_Buffer;
--------------
-- Get_Line --
--------------
procedure Get_Line is
Ch : Character;
begin
Last := 0;
if End_Of_File then
return;
end if;
loop
Ch := Buffer (Buffer_Cursor);
exit when Ch = ASCII.CR or else
Ch = ASCII.LF or else
Ch = ASCII.FF;
Last := Last + 1;
Line (Last) := Ch;
if Last = Line'Last then
return;
end if;
Buffer_Cursor := Buffer_Cursor + 1;
if Buffer_Cursor > Buffer_Length then
Get_Buffer;
if End_Of_File then
return;
end if;
end if;
end loop;
loop
Ch := Buffer (Buffer_Cursor);
exit when Ch /= ASCII.HT and then
Ch /= ASCII.LF and then
Ch /= ASCII.FF;
Buffer_Cursor := Buffer_Cursor + 1;
if Buffer_Cursor > Buffer_Length then
Get_Buffer;
if End_Of_File then
return;
end if;
end if;
end loop;
end Get_Line;
-- Start of processing for Recurse
begin
Last_Arg := 0;
if FD = Invalid_FD then
if Ignore_Non_Existing_Files then
return;
else
raise File_Does_Not_Exist;
end if;
end if;
-- Put the response file name on the stack
if First_File = null then
First_File :=
new File_Rec'
(Name => new String'(File_Name),
Next => null,
Prev => null);
Last_File := First_File;
else
declare
Current : File_Ptr := First_File;
begin
loop
if Current.Name.all = File_Name then
raise Circularity_Detected;
end if;
Current := Current.Next;
exit when Current = null;
end loop;
Last_File.Next :=
new File_Rec'
(Name => new String'(File_Name),
Next => null,
Prev => Last_File);
Last_File := Last_File.Next;
end;
end if;
End_Of_File_Reached := False;
Get_Buffer;
-- Read the response file line by line
Line_Loop :
while not End_Of_File loop
Get_Line;
if Last = Line'Last then
raise Line_Too_Long;
end if;
First_Char := 1;
-- Get each argument on the line
Arg_Loop :
loop
-- First, skip any white space
while First_Char <= Last loop
exit when Line (First_Char) /= ' ' and then
Line (First_Char) /= ASCII.HT;
First_Char := First_Char + 1;
end loop;
exit Arg_Loop when First_Char > Last;
Last_Char := First_Char;
In_String := False;
-- Get the character one by one
Character_Loop :
while Last_Char <= Last loop
-- Inside a string, check only for '"'
if In_String then
if Line (Last_Char) = '"' then
-- Remove the '"'
Line (Last_Char .. Last - 1) :=
Line (Last_Char + 1 .. Last);
Last := Last - 1;
-- End of string is end of argument
if Last_Char > Last or else
Line (Last_Char) = ' ' or else
Line (Last_Char) = ASCII.HT
then
In_String := False;
Last_Char := Last_Char - 1;
exit Character_Loop;
else
-- If there are two consecutive '"', the quoted
-- string is not closed
In_String := Line (Last_Char) = '"';
if In_String then
Last_Char := Last_Char + 1;
end if;
end if;
else
Last_Char := Last_Char + 1;
end if;
elsif Last_Char = Last then
-- An opening '"' at the end of the line is an error
if Line (Last) = '"' then
raise No_Closing_Quote;
else
-- The argument ends with the line
exit Character_Loop;
end if;
elsif Line (Last_Char) = '"' then
-- Entering a quoted string: remove the '"'
In_String := True;
Line (Last_Char .. Last - 1) :=
Line (Last_Char + 1 .. Last);
Last := Last - 1;
else
-- Outside quoted strings, white space ends the argument
exit Character_Loop
when Line (Last_Char + 1) = ' ' or else
Line (Last_Char + 1) = ASCII.HT;
Last_Char := Last_Char + 1;
end if;
end loop Character_Loop;
-- It is an error to not close a quoted string before the end
-- of the line.
if In_String then
raise No_Closing_Quote;
end if;
-- Add the argument to the list
declare
Arg : String (1 .. Last_Char - First_Char + 1);
begin
Arg := Line (First_Char .. Last_Char);
Add_Argument (Arg);
end;
-- Next argument, if line is not finished
First_Char := Last_Char + 1;
end loop Arg_Loop;
end loop Line_Loop;
Close (FD);
-- If Recursive is True, check for any argument starting with '@'
if Recursive then
Arg := 1;
while Arg <= Last_Arg loop
if Arguments (Arg)'Length > 0 and then
Arguments (Arg) (1) = '@'
then
-- Ignore argument '@' with no file name
if Arguments (Arg)'Length = 1 then
Arguments (Arg .. Last_Arg - 1) :=
Arguments (Arg + 1 .. Last_Arg);
Last_Arg := Last_Arg - 1;
else
-- Save the current arguments and get those in the new
-- response file.
declare
Inc_File_Name : constant String :=
Arguments (Arg) (2 .. Arguments (Arg)'Last);
Current_Arguments : constant Argument_List :=
Arguments (1 .. Last_Arg);
begin
Recurse (Inc_File_Name);
-- Insert the new arguments where the new response
-- file was imported.
declare
New_Arguments : constant Argument_List :=
Arguments (1 .. Last_Arg);
New_Last_Arg : constant Positive :=
Current_Arguments'Length +
New_Arguments'Length - 1;
begin
-- Grow Arguments if it is not large enough
if Arguments'Last < New_Last_Arg then
Last_Arg := Arguments'Last;
Free (Arguments);
while Last_Arg < New_Last_Arg loop
Last_Arg := Last_Arg * 2;
end loop;
Arguments := new Argument_List (1 .. Last_Arg);
end if;
Last_Arg := New_Last_Arg;
Arguments (1 .. Last_Arg) :=
Current_Arguments (1 .. Arg - 1) &
New_Arguments &
Current_Arguments
(Arg + 1 .. Current_Arguments'Last);
Arg := Arg + New_Arguments'Length;
end;
end;
end if;
else
Arg := Arg + 1;
end if;
end loop;
end if;
-- Remove the response file name from the stack
if First_File = Last_File then
System.Strings.Free (First_File.Name);
Free (First_File);
First_File := null;
Last_File := null;
else
System.Strings.Free (Last_File.Name);
Last_File := Last_File.Prev;
Free (Last_File.Next);
end if;
exception
when others =>
Close (FD);
raise;
end Recurse;
-- Start of processing for Arguments_From
begin
-- The job is done by procedure Recurse
Recurse (Response_File_Name);
-- Free Arguments before returning the result
declare
Result : constant Argument_List := Arguments (1 .. Last_Arg);
begin
Free (Arguments);
return Result;
end;
exception
when others =>
-- When an exception occurs, deallocate everything
Free (Arguments);
while First_File /= null loop
Last_File := First_File.Next;
System.Strings.Free (First_File.Name);
Free (First_File);
First_File := Last_File;
end loop;
raise;
end Arguments_From;
end System.Response_File;
|
vivianjia123/Password-Manager | Ada | 5,175 | adb | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers; use Ada.Containers;
with Ada.Characters; use Ada.Characters;
with PIN;
with PasswordDatabase;
package body PasswordManager with SPARK_Mode is
-- Initiates the Password Manager
procedure Init(Pin_Input : in String;
Manager_Information : out Information) is
begin
-- Sets the Master Pin and Password Manager state to Locked
-- also initates the database
Manager_Information.Master_Pin := PIN.From_String(Pin_Input);
Manager_Information.Is_Locked := True;
PasswordDatabase.Init(Manager_Information.Master_Database);
end;
-- Determines current lock status of Password Manager
function Lock_Status(Manager_Information: in Information) return Boolean is
begin
if(Manager_Information.Is_Locked = True) then
return True;
end if;
return False;
end;
-- Only executes Unlock_Manager if the current state is unlocked
procedure Execute_Unlock(Manager_Information : in out Information;
Pin_Input : in PIN.PIN) is
begin
if (PIN."="(Manager_Information.Master_Pin,Pin_Input)
and Manager_Information.Is_Locked) then
Unlock_Manager(Manager_Information, Pin_Input);
end if;
end;
-- Changes Password Manager State to Unlocked
procedure Unlock_Manager(Manager_Information : in out Information;
Pin_Input : in PIN.PIN) is
begin
-- Password Manager is unlocked
Manager_Information.Is_Locked := False;
end;
-- Only executes Lock_Manager if the current state is unlocked
procedure Execute_Lock(Manager_Information : in out Information;
Pin_Input : in PIN.PIN) is
begin
if (Manager_Information.Is_Locked= False) then
Lock_Manager(Manager_Information, Pin_Input);
end if;
end;
-- Changes Password Manager State to Locked
procedure Lock_Manager(Manager_Information : in out Information;
Pin_Input : in PIN.PIN) is
begin
-- Password Manager is set to locked and MasterPin is set to
-- Pin supplied by user
Manager_Information.Master_Pin := Pin_Input;
Manager_Information.Is_Locked := True;
end;
-- Only executes Get Command if requirements are met
procedure Execute_Get_Command(Manager_Information : in Information;
Input_Url : in PasswordDatabase.URL) is
begin
-- If Password Manager is unlocked and Database contains entry
-- for the Url then call Put Command
if (PasswordDatabase.Has_Password_For
(Manager_Information.Master_Database,Input_Url) and
Manager_Information.Is_Locked = False) then
Get_Database(Manager_Information, Input_Url);
end if;
end;
-- Carries out Get Command
procedure Get_Database(Manager_Information : in Information;
Input_Url : in PasswordDatabase.URL) is
begin
-- Returns associated password
Put_Line (PasswordDatabase.To_String
(PasswordDatabase.Get
(Manager_Information.Master_Database,Input_Url)));
end;
-- Only executes Put Command if requirements are met
procedure Execute_Put_Command(Manager_Information : in out Information;
Input_Url : in PasswordDatabase.URL;
Input_Pwd : in PasswordDatabase.Password) is
begin
-- If Password Manager is unlocked and entries are
-- within maximum entry range then store entry to Database
if (Manager_Information.Is_Locked = False
and StoredDatabaseLength(Manager_Information)
< PasswordDatabase.Max_Entries) then
Put_Database(Manager_Information, Input_Url, Input_Pwd);
end if;
end;
-- Carries out Put Command
procedure Put_Database(Manager_Information : in out Information;
Input_Url : in PasswordDatabase.URL;
Input_Pwd : in PasswordDatabase.Password) is
begin
-- Put associated entry into database
PasswordDatabase.Put(Manager_Information.Master_Database,
Input_Url, Input_Pwd);
end;
-- Only executes Rem Command if requirements are met
procedure Execute_Rem_Command(Manager_Information : in out Information;
Input_Url : in PasswordDatabase.URL) is
begin
-- If Password Manager is unlocked and Database contains entry
-- for the Url then call Rem Command
if (PasswordDatabase.Has_Password_For
(Manager_Information.Master_Database, Input_Url) and
Manager_Information.Is_Locked = False) then
Rem_Database(Manager_Information, Input_Url);
end if;
end;
-- Carries out Rem Command
procedure Rem_Database(Manager_Information : in out Information;
Input_Url : in PasswordDatabase.URL) is
begin
-- Remove the associated entry
PasswordDatabase.Remove(Manager_Information.Master_Database, Input_Url);
end;
end PasswordManager;
|
reznikmm/matreshka | Ada | 3,844 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2013, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
package Matreshka.ODF_Attributes.Style.Use_Window_Font_Color is
type Style_Use_Window_Font_Color_Node is
new Matreshka.ODF_Attributes.Style.Style_Node_Base with null record;
type Style_Use_Window_Font_Color_Access is
access all Style_Use_Window_Font_Color_Node'Class;
overriding function Get_Local_Name
(Self : not null access constant Style_Use_Window_Font_Color_Node)
return League.Strings.Universal_String;
end Matreshka.ODF_Attributes.Style.Use_Window_Font_Color;
|
micahwelf/FLTK-Ada | Ada | 3,283 | adb |
with
Interfaces.C.Strings,
System;
use type
System.Address;
package body FLTK.Widgets.Valuators.Sliders.Hor_Nice is
procedure hor_nice_slider_set_draw_hook
(W, D : in System.Address);
pragma Import (C, hor_nice_slider_set_draw_hook, "hor_nice_slider_set_draw_hook");
pragma Inline (hor_nice_slider_set_draw_hook);
procedure hor_nice_slider_set_handle_hook
(W, H : in System.Address);
pragma Import (C, hor_nice_slider_set_handle_hook, "hor_nice_slider_set_handle_hook");
pragma Inline (hor_nice_slider_set_handle_hook);
function new_fl_hor_nice_slider
(X, Y, W, H : in Interfaces.C.int;
Text : in Interfaces.C.char_array)
return System.Address;
pragma Import (C, new_fl_hor_nice_slider, "new_fl_hor_nice_slider");
pragma Inline (new_fl_hor_nice_slider);
procedure free_fl_hor_nice_slider
(D : in System.Address);
pragma Import (C, free_fl_hor_nice_slider, "free_fl_hor_nice_slider");
pragma Inline (free_fl_hor_nice_slider);
procedure fl_hor_nice_slider_draw
(W : in System.Address);
pragma Import (C, fl_hor_nice_slider_draw, "fl_hor_nice_slider_draw");
pragma Inline (fl_hor_nice_slider_draw);
function fl_hor_nice_slider_handle
(W : in System.Address;
E : in Interfaces.C.int)
return Interfaces.C.int;
pragma Import (C, fl_hor_nice_slider_handle, "fl_hor_nice_slider_handle");
pragma Inline (fl_hor_nice_slider_handle);
procedure Finalize
(This : in out Hor_Nice_Slider) is
begin
if This.Void_Ptr /= System.Null_Address and then
This in Hor_Nice_Slider'Class
then
free_fl_hor_nice_slider (This.Void_Ptr);
This.Void_Ptr := System.Null_Address;
end if;
Finalize (Slider (This));
end Finalize;
package body Forge is
function Create
(X, Y, W, H : in Integer;
Text : in String)
return Hor_Nice_Slider is
begin
return This : Hor_Nice_Slider do
This.Void_Ptr := new_fl_hor_nice_slider
(Interfaces.C.int (X),
Interfaces.C.int (Y),
Interfaces.C.int (W),
Interfaces.C.int (H),
Interfaces.C.To_C (Text));
fl_widget_set_user_data
(This.Void_Ptr,
Widget_Convert.To_Address (This'Unchecked_Access));
hor_nice_slider_set_draw_hook (This.Void_Ptr, Draw_Hook'Address);
hor_nice_slider_set_handle_hook (This.Void_Ptr, Handle_Hook'Address);
end return;
end Create;
end Forge;
procedure Draw
(This : in out Hor_Nice_Slider) is
begin
fl_hor_nice_slider_draw (This.Void_Ptr);
end Draw;
function Handle
(This : in out Hor_Nice_Slider;
Event : in Event_Kind)
return Event_Outcome is
begin
return Event_Outcome'Val
(fl_hor_nice_slider_handle (This.Void_Ptr, Event_Kind'Pos (Event)));
end Handle;
end FLTK.Widgets.Valuators.Sliders.Hor_Nice;
|
Componolit/libsparkcrypto | Ada | 18,189 | adb | -------------------------------------------------------------------------------
-- This file is part of libsparkcrypto.
--
-- Copyright (C) 2011, Alexander Senier and Stefan Berghofer
-- Copyright (C) 2011, secunet Security Networks AG
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- * Neither the name of the author nor the names of its contributors may be
-- used to endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
-- BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
with LSC.Internal.Types;
with LSC.Internal.Bignum;
with OpenSSL;
with AUnit.Assertions; use AUnit.Assertions;
pragma Style_Checks ("-s");
pragma Warnings (Off, "formal parameter ""T"" is not referenced");
use type LSC.Internal.Bignum.Big_Int;
package body LSC_Internal_Test_Bignum
is
Window_Size : constant := 5;
subtype Mod_Range_Small is Natural range 0 .. 63;
subtype Mod_Range is Natural range 0 .. 127;
subtype Pub_Exp_Range is Natural range 0 .. 0;
subtype Window_Aux_Range is Natural range 0 .. 128 * (2 ** Window_Size) - 1;
subtype LInt_Small is LSC.Internal.Bignum.Big_Int (Mod_Range_Small);
subtype LInt is LSC.Internal.Bignum.Big_Int (Mod_Range);
subtype SInt is LSC.Internal.Bignum.Big_Int (Pub_Exp_Range);
subtype Window_Aux is LSC.Internal.Bignum.Big_Int (Window_Aux_Range);
Pub_Exp : constant SInt := SInt'(0 => 16#00010001#);
-- 2048 bit
Modulus_Small : constant LInt_Small := LInt_Small'
(16#e3855b7b#, 16#695e1d0c#, 16#2f3a389f#, 16#e4e8cfbc#, 16#366c3c0b#,
16#07f34b0d#, 16#a92ff519#, 16#566a909a#, 16#d79ecc36#, 16#e392c334#,
16#dbbb737f#, 16#80c97ddd#, 16#812a798c#, 16#0fdf31b2#, 16#c9c3978b#,
16#f526906b#, 16#cf23d190#, 16#ea1e08a2#, 16#08cf9c02#, 16#b3b794fb#,
16#7855c403#, 16#49b10dd8#, 16#6ca17d12#, 16#b069b1ab#, 16#b8d28b35#,
16#a08d0a13#, 16#1a1bf74d#, 16#30ca19b3#, 16#29e5abd7#, 16#4ccb0a06#,
16#7bae2533#, 16#fc040833#, 16#2c1c80c5#, 16#ea729a13#, 16#ac5ffd04#,
16#a2dcc2f9#, 16#c1f9c72c#, 16#f466adf6#, 16#ea152c47#, 16#42d76640#,
16#8b5c067a#, 16#8c870d16#, 16#d3dacf2f#, 16#df33c327#, 16#fdddf873#,
16#592c3110#, 16#a94e6415#, 16#6b0f63f4#, 16#84919783#, 16#da1672d1#,
16#6d2b736e#, 16#3c02711d#, 16#eba01b1d#, 16#04463ba8#, 16#a8f0f41b#,
16#d41c9a16#, 16#2e0a1c54#, 16#e8340e9b#, 16#0194cdee#, 16#4beacec6#,
16#e23ee4a4#, 16#ec602901#, 16#079751bd#, 16#Dad31766#);
Priv_Exp_Small : constant LInt_Small := LInt_Small'
(16#3fd9f299#, 16#64a02913#, 16#780db9d7#, 16#164c83cd#, 16#70ac88cc#,
16#14e9bfcc#, 16#bff4fa46#, 16#a2956db0#, 16#d5952d92#, 16#d8e23b1b#,
16#d252925c#, 16#f63f2570#, 16#1232a957#, 16#0ecdf6fc#, 16#23356dd5#,
16#6dfd8463#, 16#b88e9193#, 16#3e337443#, 16#c30bd004#, 16#f86471bc#,
16#26836b1f#, 16#36792ee7#, 16#fd7774c3#, 16#e947afe5#, 16#403e454e#,
16#60886c2f#, 16#7da04cab#, 16#0006c1c8#, 16#87bfa8cc#, 16#c644e026#,
16#8eea8cce#, 16#beca39f9#, 16#60c3808d#, 16#2faf499f#, 16#c81d0c50#,
16#ef2e6e1b#, 16#ae3dbc3f#, 16#54a6e7b8#, 16#efdc4e55#, 16#e0ed4e41#,
16#6ddee985#, 16#2c988959#, 16#2bdbffad#, 16#ec9c5635#, 16#a6ad3fef#,
16#5df1f2a6#, 16#e4ec57d3#, 16#1c823145#, 16#eecff08e#, 16#51b9f682#,
16#c8ec37a1#, 16#1212a615#, 16#9265aeed#, 16#4b4e2491#, 16#2b29d53a#,
16#2bd57be9#, 16#ffd21ce0#, 16#bccc6401#, 16#e2d6c019#, 16#c98b2771#,
16#4d4cde01#, 16#d507d875#, 16#886bab53#, 16#7cac4629#);
-- 4096 bit
Modulus : constant LInt := LInt'
(16#27a3f371#, 16#f66dc29e#, 16#2c4cf251#, 16#0aa490b7#, 16#2eabfddb#,
16#4e6d1cc7#, 16#e67fc1bb#, 16#be3cc1e1#, 16#4338d3ae#, 16#372d809a#,
16#b9d33026#, 16#e3d05bff#, 16#886580b8#, 16#020b3b03#, 16#55c15179#,
16#a3c026b2#, 16#3e550dcb#, 16#821fcfee#, 16#4f44c3f9#, 16#25c8b0a5#,
16#30612a20#, 16#8c970432#, 16#32e395aa#, 16#1337a822#, 16#3db2c677#,
16#35a256d5#, 16#fcbf1cfc#, 16#6354fbe1#, 16#8d0874a2#, 16#a017fe19#,
16#07f415fc#, 16#e0a45678#, 16#c3e2f1c3#, 16#4b73d538#, 16#962f1c1c#,
16#448f15fb#, 16#d4ba9b05#, 16#9f6cc819#, 16#f36d2a06#, 16#d1c1d04a#,
16#efb31b76#, 16#c7cae1cf#, 16#e61520e4#, 16#984ec779#, 16#56f79b73#,
16#2f8ca314#, 16#a0c4e830#, 16#2e3eba5b#, 16#f739a437#, 16#7852b71e#,
16#aab09aa6#, 16#3d8dcdc3#, 16#f16ab197#, 16#8b3753d1#, 16#ec52c4e1#,
16#f70e4f7d#, 16#b4af5c60#, 16#82ae6ca4#, 16#fa6a8a1d#, 16#5655c33d#,
16#5096b17f#, 16#71c61b6a#, 16#28c84e83#, 16#07a0f985#, 16#b5523b0c#,
16#d31e75f6#, 16#c8139152#, 16#c94fb87f#, 16#d0d092c4#, 16#b5bae11d#,
16#3ebaa999#, 16#599cd667#, 16#a156c841#, 16#88a90d02#, 16#73e10c30#,
16#56b72050#, 16#1cb3c2d9#, 16#abef5973#, 16#8f42b61a#, 16#e54c7b3c#,
16#0b93bb83#, 16#5ca62bc2#, 16#1a9996a5#, 16#26b48d1b#, 16#98f932d1#,
16#3f56babe#, 16#dab5a0eb#, 16#4e0de31d#, 16#4bbe26d4#, 16#2812c4f8#,
16#f6d1866c#, 16#6800ef71#, 16#49cca290#, 16#aa1bbdee#, 16#ee8a75ea#,
16#4fc8516b#, 16#242c7f52#, 16#96df15ea#, 16#eaac1b33#, 16#c533d8fa#,
16#a649ef23#, 16#7d29eebb#, 16#8342ce68#, 16#36abe9c0#, 16#82adff4d#,
16#8fcc54b0#, 16#89144572#, 16#09dfcece#, 16#bcc22be3#, 16#b2184072#,
16#cf2cf6c3#, 16#dbb62eeb#, 16#9c44b29b#, 16#08dea7eb#, 16#8a92c57e#,
16#4ed90ea9#, 16#a73379d1#, 16#20767c8f#, 16#bcc1a56d#, 16#6fa7e726#,
16#d74d548d#, 16#ec21f388#, 16#a2344841#, 16#8b08a316#, 16#c99b8d76#,
16#d670befe#, 16#31a09763#, 16#d0055749#);
Priv_Exp : constant LInt := LInt'
(16#2e274601#, 16#8fab5c50#, 16#48b5239e#, 16#5a37865c#, 16#5670b41d#,
16#2da87796#, 16#3a82b988#, 16#7a7ce911#, 16#bd4e57b1#, 16#8f6d3da4#,
16#8669e6a0#, 16#3314c3e7#, 16#36248f99#, 16#4b3e25a7#, 16#600a6f7f#,
16#04eafed8#, 16#45050c07#, 16#f32daf96#, 16#6b6b4f21#, 16#cd177764#,
16#e4d13b46#, 16#80f34af3#, 16#1f601841#, 16#65bf67b8#, 16#33729106#,
16#56b14c9d#, 16#267c46be#, 16#d4acf88c#, 16#fc8ec97e#, 16#06d4df7e#,
16#198ec5fb#, 16#a098a033#, 16#c7dcc150#, 16#dc980d3f#, 16#29778f62#,
16#29f4cbca#, 16#e6d86584#, 16#9e366a7a#, 16#b39ab77a#, 16#1a956df3#,
16#da64c05b#, 16#6f4183a2#, 16#452ad7db#, 16#84d1f44e#, 16#88c4a697#,
16#d272546e#, 16#c0f5da10#, 16#dca7e68b#, 16#2316a1e5#, 16#93305fcd#,
16#10a0897b#, 16#e203fc89#, 16#163ef9fa#, 16#a3625c15#, 16#9719bace#,
16#c5bd6a66#, 16#466893e9#, 16#eb33cb36#, 16#ff6854e6#, 16#f8cf002f#,
16#5c84f1a6#, 16#f9d89029#, 16#a42c2f21#, 16#7c29e8b3#, 16#07188900#,
16#37a9da54#, 16#672715c3#, 16#ab9b69ac#, 16#2a32533c#, 16#592932ba#,
16#90843f00#, 16#4f540d7d#, 16#44f04b78#, 16#efeab1d4#, 16#bc5e76db#,
16#cd5bd78b#, 16#0eb2723f#, 16#bd633630#, 16#90bf30be#, 16#0023372e#,
16#5d50308b#, 16#4cbf539a#, 16#1abb5b44#, 16#30cc98de#, 16#869b24e0#,
16#78bda399#, 16#25e6f54c#, 16#96dac865#, 16#8db1dc73#, 16#770a4d97#,
16#31123fee#, 16#139ea6d0#, 16#786e32b2#, 16#f3998ab6#, 16#5fd4f43b#,
16#ae506344#, 16#797f633d#, 16#81682a87#, 16#9b5cb744#, 16#a40a97e5#,
16#e788eed8#, 16#5c2b1448#, 16#90780722#, 16#77af3218#, 16#66114d4f#,
16#8857c6c0#, 16#9899ef8a#, 16#dea4d612#, 16#f5986865#, 16#41b3caca#,
16#ebace112#, 16#1678338c#, 16#34e40889#, 16#3291e166#, 16#3f855200#,
16#e81eddcb#, 16#b08e2e77#, 16#238ac815#, 16#d2442787#, 16#bb20cea2#,
16#c4ae4e94#, 16#b575336a#, 16#cd55d286#, 16#e7387f77#, 16#a780f030#,
16#46526c31#, 16#0e4752a9#, 16#9b036fe1#);
---------------------------------------------------------------------------
procedure Test_RSA2048 (T : in out Test_Cases.Test_Case'Class)
is
Aux1, Aux2, Aux3, R : LInt;
M_Inv : LSC.Internal.Types.Word32;
Aux4 : Window_Aux;
Plain1_Small, OpenSSL_Plain1_Small : LInt_Small;
Plain2_Small, Plain3_Small, OpenSSL_Plain2_Small : LInt_Small;
Cipher1_Small, Cipher2_Small, OpenSSL_Cipher_Small : LInt_Small;
OpenSSL_Modulus_Small, OpenSSL_Priv_Exp_Small : LInt_Small;
OpenSSL_Pub_Exp : SInt;
Success_Enc, Success_Dec : Boolean;
begin
LSC.Internal.Bignum.Native_To_BE
(Pub_Exp, Pub_Exp'First, Pub_Exp'Last,
OpenSSL_Pub_Exp, OpenSSL_Pub_Exp'First);
-- Create original data
for I in Natural range Modulus_Small'Range
loop
Plain1_Small (I) := LSC.Internal.Types.Word32 (I);
end loop;
-- Convert modulus, exponent and plaintext to format expected by OpenSSL
LSC.Internal.Bignum.Native_To_BE
(Priv_Exp_Small, Priv_Exp_Small'First, Priv_Exp_Small'Last,
OpenSSL_Priv_Exp_Small, OpenSSL_Priv_Exp_Small'First);
LSC.Internal.Bignum.Native_To_BE
(Modulus_Small, Modulus_Small'First, Modulus_Small'Last,
OpenSSL_Modulus_Small, OpenSSL_Modulus_Small'First);
LSC.Internal.Bignum.Native_To_BE
(Plain1_Small, Plain1_Small'First, Plain1_Small'Last,
OpenSSL_Plain1_Small, OpenSSL_Plain1_Small'First);
OpenSSL.RSA_Public_Encrypt
(OpenSSL_Modulus_Small,
OpenSSL_Pub_Exp,
OpenSSL_Plain1_Small,
OpenSSL_Cipher_Small,
Success_Enc);
OpenSSL.RSA_Private_Decrypt
(OpenSSL_Modulus_Small,
OpenSSL_Pub_Exp,
OpenSSL_Priv_Exp_Small,
OpenSSL_Cipher_Small,
OpenSSL_Plain2_Small,
Success_Dec);
LSC.Internal.Bignum.Native_To_BE
(OpenSSL_Cipher_Small, OpenSSL_Cipher_Small'First, OpenSSL_Cipher_Small'Last,
Cipher2_Small, Cipher2_Small'First);
LSC.Internal.Bignum.Native_To_BE
(OpenSSL_Plain2_Small, OpenSSL_Plain2_Small'First, OpenSSL_Plain2_Small'Last,
Plain3_Small, Plain3_Small'First);
-- Precompute R^2 mod m
LSC.Internal.Bignum.Size_Square_Mod
(M => Modulus_Small,
M_First => Modulus_Small'First,
M_Last => Modulus_Small'Last,
R => R,
R_First => R'First);
-- Precompute inverse
M_Inv := LSC.Internal.Bignum.Word_Inverse (Modulus_Small (Modulus_Small'First));
-- Encrypt
LSC.Internal.Bignum.Mont_Exp_Window
(A => Cipher1_Small,
A_First => Cipher1_Small'First,
A_Last => Cipher1_Small'Last,
X => Plain1_Small,
X_First => Plain1_Small'First,
E => Pub_Exp,
E_First => Pub_Exp'First,
E_Last => Pub_Exp'Last,
M => Modulus_Small,
M_First => Modulus_Small'First,
K => Window_Size,
Aux1 => Aux1,
Aux1_First => Aux1'First,
Aux2 => Aux2,
Aux2_First => Aux2'First,
Aux3 => Aux3,
Aux3_First => Aux3'First,
Aux4 => Aux4,
Aux4_First => Aux4'First,
R => R,
R_First => R'First,
M_Inv => M_Inv);
-- Decrypt
LSC.Internal.Bignum.Mont_Exp_Window
(A => Plain2_Small,
A_First => Plain2_Small'First,
A_Last => Plain2_Small'Last,
X => Cipher1_Small,
X_First => Cipher1_Small'First,
E => Priv_Exp_Small,
E_First => Priv_Exp_Small'First,
E_Last => Priv_Exp_Small'Last,
M => Modulus_Small,
M_First => Modulus_Small'First,
K => Window_Size,
Aux1 => Aux1,
Aux1_First => Aux1'First,
Aux2 => Aux2,
Aux2_First => Aux2'First,
Aux3 => Aux3,
Aux3_First => Aux3'First,
Aux4 => Aux4,
Aux4_First => Aux4'First,
R => R,
R_First => R'First,
M_Inv => M_Inv);
Assert (Success_Enc, "encryption failed");
Assert (Success_Dec, "decryption failed");
Assert (Cipher1_Small = Cipher2_Small, "cipher texts differ");
Assert (Plain1_Small = Plain2_Small, "Plain1 /= Plain2");
Assert (Plain2_Small = Plain3_Small, "Plain2 /= Plain3");
end Test_RSA2048;
---------------------------------------------------------------------------
procedure Test_RSA4096 (T : in out Test_Cases.Test_Case'Class)
is
Plain1, OpenSSL_Plain1 : LInt;
Plain2, Plain3, OpenSSL_Plain2 : LInt;
Cipher1, Cipher2, OpenSSL_Cipher : LInt;
OpenSSL_Modulus, OpenSSL_Priv_Exp : LInt;
OpenSSL_Pub_Exp : SInt;
Aux1, Aux2, Aux3, R : LInt;
Aux4 : Window_Aux;
M_Inv : LSC.Internal.Types.Word32;
Success_Enc, Success_Dec : Boolean;
begin
LSC.Internal.Bignum.Native_To_BE
(Pub_Exp, Pub_Exp'First, Pub_Exp'Last,
OpenSSL_Pub_Exp, OpenSSL_Pub_Exp'First);
-- Create original data
for I in Natural range Modulus'Range
loop
Plain1 (I) := LSC.Internal.Types.Word32 (I);
end loop;
-- Convert modulus, exponent and plaintext to format expected by OpenSSL
LSC.Internal.Bignum.Native_To_BE
(Priv_Exp, Priv_Exp'First, Priv_Exp'Last,
OpenSSL_Priv_Exp, OpenSSL_Priv_Exp'First);
LSC.Internal.Bignum.Native_To_BE
(Modulus, Modulus'First, Modulus'Last,
OpenSSL_Modulus, OpenSSL_Modulus'First);
LSC.Internal.Bignum.Native_To_BE
(Plain1, Plain1'First, Plain1'Last,
OpenSSL_Plain1, OpenSSL_Plain1'First);
OpenSSL.RSA_Public_Encrypt
(OpenSSL_Modulus,
OpenSSL_Pub_Exp,
OpenSSL_Plain1,
OpenSSL_Cipher,
Success_Enc);
OpenSSL.RSA_Private_Decrypt
(OpenSSL_Modulus,
OpenSSL_Pub_Exp,
OpenSSL_Priv_Exp,
OpenSSL_Cipher,
OpenSSL_Plain2,
Success_Dec);
LSC.Internal.Bignum.Native_To_BE
(OpenSSL_Cipher, OpenSSL_Cipher'First, OpenSSL_Cipher'Last,
Cipher2, Cipher2'First);
LSC.Internal.Bignum.Native_To_BE
(OpenSSL_Plain2, OpenSSL_Plain2'First, OpenSSL_Plain2'Last,
Plain3, Plain3'First);
-- Precompute R^2 mod m
LSC.Internal.Bignum.Size_Square_Mod
(M => Modulus,
M_First => Modulus'First,
M_Last => Modulus'Last,
R => R,
R_First => R'First);
-- Precompute inverse
M_Inv := LSC.Internal.Bignum.Word_Inverse (Modulus (Modulus'First));
-- Encrypt
LSC.Internal.Bignum.Mont_Exp_Window
(A => Cipher1,
A_First => Cipher1'First,
A_Last => Cipher1'Last,
X => Plain1,
X_First => Plain1'First,
E => Pub_Exp,
E_First => Pub_Exp'First,
E_Last => Pub_Exp'Last,
M => Modulus,
M_First => Modulus'First,
K => Window_Size,
Aux1 => Aux1,
Aux1_First => Aux1'First,
Aux2 => Aux2,
Aux2_First => Aux2'First,
Aux3 => Aux3,
Aux3_First => Aux3'First,
Aux4 => Aux4,
Aux4_First => Aux4'First,
R => R,
R_First => R'First,
M_Inv => M_Inv);
-- Decrypt
LSC.Internal.Bignum.Mont_Exp_Window
(A => Plain2,
A_First => Plain2'First,
A_Last => Plain2'Last,
X => Cipher1,
X_First => Cipher1'First,
E => Priv_Exp,
E_First => Priv_Exp'First,
E_Last => Priv_Exp'Last,
M => Modulus,
M_First => Modulus'First,
K => Window_Size,
Aux1 => Aux1,
Aux1_First => Aux1'First,
Aux2 => Aux2,
Aux2_First => Aux2'First,
Aux3 => Aux3,
Aux3_First => Aux3'First,
Aux4 => Aux4,
Aux4_First => Aux4'First,
R => R,
R_First => R'First,
M_Inv => M_Inv);
Assert (Success_Enc, "encryption failed");
Assert (Success_Dec, "decryption failed");
Assert (Cipher1 = Cipher2, "cipher texts differ");
Assert (Plain1 = Plain2, "Plain1 /= Plain2");
Assert (Plain2 = Plain3, "Plain2 /= Plain3");
end Test_RSA4096;
---------------------------------------------------------------------------
procedure Register_Tests (T : in out Test_Case) is
use AUnit.Test_Cases.Registration;
begin
Register_Routine (T, Test_RSA2048'Access, "Insecure RSA 2048 (encrypt/decrypt)");
Register_Routine (T, Test_RSA4096'Access, "Insecure RSA 4096 (encrypt/decrypt)");
end Register_Tests;
---------------------------------------------------------------------------
function Name (T : Test_Case) return Test_String is
begin
return Format ("Bignum");
end Name;
end LSC_Internal_Test_Bignum;
|
reznikmm/matreshka | Ada | 4,576 | adb | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Matreshka.DOM_Documents;
with Matreshka.ODF_String_Constants;
with ODF.DOM.Iterators;
with ODF.DOM.Visitors;
package body Matreshka.ODF_Table.End_X_Attributes is
------------
-- Create --
------------
overriding function Create
(Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters)
return Table_End_X_Attribute_Node is
begin
return Self : Table_End_X_Attribute_Node do
Matreshka.ODF_Table.Constructors.Initialize
(Self'Unchecked_Access,
Parameters.Document,
Matreshka.ODF_String_Constants.Table_Prefix);
end return;
end Create;
--------------------
-- Get_Local_Name --
--------------------
overriding function Get_Local_Name
(Self : not null access constant Table_End_X_Attribute_Node)
return League.Strings.Universal_String
is
pragma Unreferenced (Self);
begin
return Matreshka.ODF_String_Constants.End_X_Attribute;
end Get_Local_Name;
begin
Matreshka.DOM_Documents.Register_Attribute
(Matreshka.ODF_String_Constants.Table_URI,
Matreshka.ODF_String_Constants.End_X_Attribute,
Table_End_X_Attribute_Node'Tag);
end Matreshka.ODF_Table.End_X_Attributes;
|
reznikmm/matreshka | Ada | 4,251 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with ODF.DOM.Table_Search_Criteria_Must_Apply_To_Whole_Cell_Attributes;
package Matreshka.ODF_Table.Search_Criteria_Must_Apply_To_Whole_Cell_Attributes is
type Table_Search_Criteria_Must_Apply_To_Whole_Cell_Attribute_Node is
new Matreshka.ODF_Table.Abstract_Table_Attribute_Node
and ODF.DOM.Table_Search_Criteria_Must_Apply_To_Whole_Cell_Attributes.ODF_Table_Search_Criteria_Must_Apply_To_Whole_Cell_Attribute
with null record;
overriding function Create
(Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters)
return Table_Search_Criteria_Must_Apply_To_Whole_Cell_Attribute_Node;
overriding function Get_Local_Name
(Self : not null access constant Table_Search_Criteria_Must_Apply_To_Whole_Cell_Attribute_Node)
return League.Strings.Universal_String;
end Matreshka.ODF_Table.Search_Criteria_Must_Apply_To_Whole_Cell_Attributes;
|
pombredanne/ravenadm | Ada | 9,265 | adb | -- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with GNAT.OS_Lib;
with Ada.Text_IO;
with Parameters;
with System;
package body Unix is
package OSL renames GNAT.OS_Lib;
package TIO renames Ada.Text_IO;
package PM renames Parameters;
--------------------------------------------------------------------------------------------
-- process_status
--------------------------------------------------------------------------------------------
function process_status (pid : pid_t) return process_exit
is
result : constant uInt8 := nohang_waitpid (pid);
begin
case result is
when 0 => return still_running;
when 1 => return exited_normally;
when others => return exited_with_error;
end case;
end process_status;
--------------------------------------------------------------------------------------------
-- screen_attached
--------------------------------------------------------------------------------------------
function screen_attached return Boolean is
begin
return CSM.isatty (handle => CSM.fileno (CSM.stdin)) = 1;
end screen_attached;
--------------------------------------------------------------------------------------------
-- cone_of_silence
--------------------------------------------------------------------------------------------
procedure cone_of_silence (deploy : Boolean)
is
result : uInt8;
begin
if not screen_attached then
return;
end if;
if deploy then
result := silent_control;
if result > 0 then
TIO.Put_Line ("Notice: tty echo+control OFF command failed");
end if;
else
result := chatty_control;
if result > 0 then
TIO.Put_Line ("Notice: tty echo+control ON command failed");
end if;
end if;
end cone_of_silence;
--------------------------------------------------------------------------------------------
-- ignore_background_tty
--------------------------------------------------------------------------------------------
procedure ignore_background_tty
is
result : uInt8;
begin
result := ignore_tty_write;
if result > 0 then
TIO.Put_Line ("Notice: ignoring background tty write signal failed");
end if;
result := ignore_tty_read;
if result > 0 then
TIO.Put_Line ("Notice: ignoring background tty read signal failed");
end if;
end ignore_background_tty;
--------------------------------------------------------------------------------------------
-- kill_process_tree
--------------------------------------------------------------------------------------------
procedure kill_process_tree (process_group : pid_t)
is
use type IC.int;
result : constant IC.int := signal_runaway (process_group);
begin
if result /= 0 then
TIO.Put_Line ("Notice: failed to signal pid " & process_group'Img);
end if;
end kill_process_tree;
--------------------------------------------------------------------------------------------
-- external_command
--------------------------------------------------------------------------------------------
function external_command (command : String) return Boolean
is
Args : OSL.Argument_List_Access;
Exit_Status : Integer;
begin
Args := OSL.Argument_String_To_List (command);
Exit_Status := OSL.Spawn (Program_Name => Args (Args'First).all,
Args => Args (Args'First + 1 .. Args'Last));
OSL.Free (Args);
return Exit_Status = 0;
end external_command;
--------------------------------------------------------------------------------------------
-- fork_failed
--------------------------------------------------------------------------------------------
function fork_failed (pid : pid_t) return Boolean is
begin
if pid < 0 then
return True;
end if;
return False;
end fork_failed;
--------------------------------------------------------------------------------------------
-- launch_process
--------------------------------------------------------------------------------------------
function launch_process (command : String) return pid_t
is
procid : OSL.Process_Id;
Args : OSL.Argument_List_Access;
begin
Args := OSL.Argument_String_To_List (command);
procid := OSL.Non_Blocking_Spawn
(Program_Name => Args (Args'First).all,
Args => Args (Args'First + 1 .. Args'Last));
OSL.Free (Args);
return pid_t (OSL.Pid_To_Integer (procid));
end launch_process;
--------------------------------------------------------------------------------------------
-- env_variable_defined
--------------------------------------------------------------------------------------------
function env_variable_defined (variable : String) return Boolean
is
test : String := OSL.Getenv (variable).all;
begin
return (test /= "");
end env_variable_defined;
--------------------------------------------------------------------------------------------
-- env_variable_value
--------------------------------------------------------------------------------------------
function env_variable_value (variable : String) return String is
begin
return OSL.Getenv (variable).all;
end env_variable_value;
--------------------------------------------------------------------------------------------
-- pipe_close
--------------------------------------------------------------------------------------------
function pipe_close (OpenFile : CSM.FILEs) return Integer
is
res : constant CSM.int := pclose (FileStream => OpenFile);
u16 : Interfaces.Unsigned_16;
begin
u16 := Interfaces.Shift_Right (Interfaces.Unsigned_16 (res), 8);
if Integer (u16) > 0 then
return Integer (u16);
end if;
return Integer (res);
end pipe_close;
--------------------------------------------------------------------------------------------
-- piped_command
--------------------------------------------------------------------------------------------
function piped_command
(command : String;
status : out Integer)
return HT.Text
is
redirect : constant String := " 2>&1";
filestream : CSM.FILEs;
result : HT.Text;
begin
filestream := popen (IC.To_C (command & redirect), IC.To_C ("re"));
result := pipe_read (OpenFile => filestream);
status := pipe_close (OpenFile => filestream);
return result;
end piped_command;
--------------------------------------------------------------------------------------------
-- piped_mute_command
--------------------------------------------------------------------------------------------
function piped_mute_command
(command : String;
abnormal : out HT.Text) return Boolean
is
redirect : constant String := " 2>&1";
filestream : CSM.FILEs;
status : Integer;
begin
filestream := popen (IC.To_C (command & redirect), IC.To_C ("re"));
abnormal := pipe_read (OpenFile => filestream);
status := pipe_close (OpenFile => filestream);
return status = 0;
end piped_mute_command;
--------------------------------------------------------------------------------------------
-- pipe_read
--------------------------------------------------------------------------------------------
function pipe_read (OpenFile : CSM.FILEs) return HT.Text
is
-- Allocate 2kb at a time
buffer : String (1 .. 2048) := (others => ' ');
result : HT.Text := HT.blank;
charbuf : CSM.int;
marker : Natural := 0;
begin
loop
charbuf := CSM.fgetc (OpenFile);
if charbuf = CSM.EOF then
if marker >= buffer'First then
HT.SU.Append (result, buffer (buffer'First .. marker));
end if;
exit;
end if;
if marker = buffer'Last then
HT.SU.Append (result, buffer);
marker := buffer'First;
else
marker := marker + 1;
end if;
buffer (marker) := Character'Val (charbuf);
end loop;
return result;
end pipe_read;
--------------------------------------------------------------------------------------------
-- true_path
--------------------------------------------------------------------------------------------
function true_path (provided_path : String) return String
is
use type ICS.chars_ptr;
buffer : IC.char_array (0 .. 1024) := (others => IC.nul);
result : ICS.chars_ptr;
path : IC.char_array := IC.To_C (provided_path);
begin
if provided_path = "" then
return "";
end if;
result := realpath (pathname => path, resolved_path => buffer);
if result = ICS.Null_Ptr then
return "";
end if;
return ICS.Value (result);
exception
when others => return "";
end true_path;
end Unix;
|
BrickBot/Bound-T-H8-300 | Ada | 3,339 | ads | -- Programs.Execution.Paths.Opt (decl)
--
-- Command-line options for the calculation of the maximal or
-- minimal execution paths.
--
-- A component of the Bound-T Worst-Case Execution Time Tool.
--
-------------------------------------------------------------------------------
-- Copyright (c) 1999 .. 2015 Tidorum Ltd
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- 1. Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- This software is provided by the copyright holders and contributors "as is" and
-- any express or implied warranties, including, but not limited to, the implied
-- warranties of merchantability and fitness for a particular purpose are
-- disclaimed. In no event shall the copyright owner or contributors be liable for
-- any direct, indirect, incidental, special, exemplary, or consequential damages
-- (including, but not limited to, procurement of substitute goods or services;
-- loss of use, data, or profits; or business interruption) however caused and
-- on any theory of liability, whether in contract, strict liability, or tort
-- (including negligence or otherwise) arising in any way out of the use of this
-- software, even if advised of the possibility of such damage.
--
-- Other modules (files) of this software composition should contain their
-- own copyright statements, which may have different copyright and usage
-- conditions. The above conditions apply to this file.
-------------------------------------------------------------------------------
--
-- $Revision: 1.3 $
-- $Date: 2015/10/24 19:36:51 $
--
-- $Log: programs-execution-paths-opt.ads,v $
-- Revision 1.3 2015/10/24 19:36:51 niklas
-- Moved to free licence.
--
-- Revision 1.2 2011-08-31 04:23:34 niklas
-- BT-CH-0222: Option registry. Option -dump. External help files.
--
-- Revision 1.1 2008/07/23 09:07:16 niklas
-- BT-CH-0139: Fix recursion in Programs.Execution.Paths.
--
with Options.Bool;
package Programs.Execution.Paths.Opt is
pragma Elaborate_Body;
--
-- To register the options.
Split_Time_Opt : aliased Options.Bool.Option_T (Default => False);
--
-- Whether to display the execution time bound for a subprogram also
-- as the "self" part and the "callees" part.
--
Split_Time : Boolean renames Split_Time_Opt.Value;
Loop_Times_Opt : aliased Options.Bool.Option_T (Default => False);
--
-- Whether to emit "Wcet_Loop" lines to show the WCET bound
-- for each loop, possibly split into "self" and "callees".
--
Loop_Times : Boolean renames Loop_Times_Opt.Value;
Trace_Callee_Bounds_Opt : aliased Options.Bool.Option_T (Default => False);
--
-- Whether to trace on standard output the state of the execution
-- bounds of the callees, when computing the extreme paths for
-- the caller.
--
Trace_Callee_Bounds : Boolean renames Trace_Callee_Bounds_Opt.Value;
end Programs.Execution.Paths.Opt;
|
reznikmm/matreshka | Ada | 6,802 | adb | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Matreshka.DOM_Documents;
with Matreshka.ODF_String_Constants;
with ODF.DOM.Iterators;
with ODF.DOM.Visitors;
package body Matreshka.ODF_Office.Image_Elements is
------------
-- Create --
------------
overriding function Create
(Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters)
return Office_Image_Element_Node is
begin
return Self : Office_Image_Element_Node do
Matreshka.ODF_Office.Constructors.Initialize
(Self'Unchecked_Access,
Parameters.Document,
Matreshka.ODF_String_Constants.Office_Prefix);
end return;
end Create;
----------------
-- Enter_Node --
----------------
overriding procedure Enter_Node
(Self : not null access Office_Image_Element_Node;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control) is
begin
if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then
ODF.DOM.Visitors.Abstract_ODF_Visitor'Class
(Visitor).Enter_Office_Image
(ODF.DOM.Office_Image_Elements.ODF_Office_Image_Access
(Self),
Control);
else
Matreshka.DOM_Elements.Abstract_Element_Node
(Self.all).Enter_Node (Visitor, Control);
end if;
end Enter_Node;
--------------------
-- Get_Local_Name --
--------------------
overriding function Get_Local_Name
(Self : not null access constant Office_Image_Element_Node)
return League.Strings.Universal_String
is
pragma Unreferenced (Self);
begin
return Matreshka.ODF_String_Constants.Image_Element;
end Get_Local_Name;
----------------
-- Leave_Node --
----------------
overriding procedure Leave_Node
(Self : not null access Office_Image_Element_Node;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control) is
begin
if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then
ODF.DOM.Visitors.Abstract_ODF_Visitor'Class
(Visitor).Leave_Office_Image
(ODF.DOM.Office_Image_Elements.ODF_Office_Image_Access
(Self),
Control);
else
Matreshka.DOM_Elements.Abstract_Element_Node
(Self.all).Leave_Node (Visitor, Control);
end if;
end Leave_Node;
----------------
-- Visit_Node --
----------------
overriding procedure Visit_Node
(Self : not null access Office_Image_Element_Node;
Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control) is
begin
if Iterator in ODF.DOM.Iterators.Abstract_ODF_Iterator'Class then
ODF.DOM.Iterators.Abstract_ODF_Iterator'Class
(Iterator).Visit_Office_Image
(Visitor,
ODF.DOM.Office_Image_Elements.ODF_Office_Image_Access
(Self),
Control);
else
Matreshka.DOM_Elements.Abstract_Element_Node
(Self.all).Visit_Node (Iterator, Visitor, Control);
end if;
end Visit_Node;
begin
Matreshka.DOM_Documents.Register_Element
(Matreshka.ODF_String_Constants.Office_URI,
Matreshka.ODF_String_Constants.Image_Element,
Office_Image_Element_Node'Tag);
end Matreshka.ODF_Office.Image_Elements;
|
SayCV/rtems-addon-packages | Ada | 17,097 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT ncurses Binding Samples --
-- --
-- ncurses2.trace_set --
-- --
-- B O D Y --
-- --
------------------------------------------------------------------------------
-- Copyright (c) 2000-2008,2011 Free Software Foundation, Inc. --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files (the --
-- "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, distribute with modifications, sublicense, and/or sell --
-- copies of the Software, and to permit persons to whom the Software is --
-- furnished to do so, subject to the following conditions: --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. --
-- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR --
-- THE USE OR OTHER DEALINGS IN THE SOFTWARE. --
-- --
-- Except as contained in this notice, the name(s) of the above copyright --
-- holders shall not be used in advertising or otherwise to promote the --
-- sale, use or other dealings in this Software without prior written --
-- authorization. --
------------------------------------------------------------------------------
-- Author: Eugene V. Melaragno <[email protected]> 2000
-- Version Control
-- $Revision$
-- $Date$
-- Binding Version 01.00
------------------------------------------------------------------------------
with ncurses2.util; use ncurses2.util;
with Terminal_Interface.Curses; use Terminal_Interface.Curses;
with Terminal_Interface.Curses.Trace; use Terminal_Interface.Curses.Trace;
with Terminal_Interface.Curses.Menus; use Terminal_Interface.Curses.Menus;
with Ada.Strings.Bounded;
-- interactively set the trace level
procedure ncurses2.trace_set is
function menu_virtualize (c : Key_Code) return Key_Code;
function subset (super, sub : Trace_Attribute_Set) return Boolean;
function trace_or (a, b : Trace_Attribute_Set) return Trace_Attribute_Set;
function trace_num (tlevel : Trace_Attribute_Set) return String;
function tracetrace (tlevel : Trace_Attribute_Set) return String;
function run_trace_menu (m : Menu; count : Integer) return Boolean;
function menu_virtualize (c : Key_Code) return Key_Code is
begin
case c is
when Character'Pos (newl) | Key_Exit =>
return Menu_Request_Code'Last + 1; -- MAX_COMMAND? TODO
when Character'Pos ('u') =>
return M_ScrollUp_Line;
when Character'Pos ('d') =>
return M_ScrollDown_Line;
when Character'Pos ('b') | Key_Next_Page =>
return M_ScrollUp_Page;
when Character'Pos ('f') | Key_Previous_Page =>
return M_ScrollDown_Page;
when Character'Pos ('n') | Key_Cursor_Down =>
return M_Next_Item;
when Character'Pos ('p') | Key_Cursor_Up =>
return M_Previous_Item;
when Character'Pos (' ') =>
return M_Toggle_Item;
when Key_Mouse =>
return c;
when others =>
Beep;
return c;
end case;
end menu_virtualize;
type string_a is access String;
type tbl_entry is record
name : string_a;
mask : Trace_Attribute_Set;
end record;
t_tbl : constant array (Positive range <>) of tbl_entry :=
(
(new String'("Disable"),
Trace_Disable),
(new String'("Times"),
Trace_Attribute_Set'(Times => True, others => False)),
(new String'("Tputs"),
Trace_Attribute_Set'(Tputs => True, others => False)),
(new String'("Update"),
Trace_Attribute_Set'(Update => True, others => False)),
(new String'("Cursor_Move"),
Trace_Attribute_Set'(Cursor_Move => True, others => False)),
(new String'("Character_Output"),
Trace_Attribute_Set'(Character_Output => True, others => False)),
(new String'("Ordinary"),
Trace_Ordinary),
(new String'("Calls"),
Trace_Attribute_Set'(Calls => True, others => False)),
(new String'("Virtual_Puts"),
Trace_Attribute_Set'(Virtual_Puts => True, others => False)),
(new String'("Input_Events"),
Trace_Attribute_Set'(Input_Events => True, others => False)),
(new String'("TTY_State"),
Trace_Attribute_Set'(TTY_State => True, others => False)),
(new String'("Internal_Calls"),
Trace_Attribute_Set'(Internal_Calls => True, others => False)),
(new String'("Character_Calls"),
Trace_Attribute_Set'(Character_Calls => True, others => False)),
(new String'("Termcap_TermInfo"),
Trace_Attribute_Set'(Termcap_TermInfo => True, others => False)),
(new String'("Maximium"),
Trace_Maximum)
);
package BS is new Ada.Strings.Bounded.Generic_Bounded_Length (300);
function subset (super, sub : Trace_Attribute_Set) return Boolean is
begin
if
(super.Times or not sub.Times) and
(super.Tputs or not sub.Tputs) and
(super.Update or not sub.Update) and
(super.Cursor_Move or not sub.Cursor_Move) and
(super.Character_Output or not sub.Character_Output) and
(super.Calls or not sub.Calls) and
(super.Virtual_Puts or not sub.Virtual_Puts) and
(super.Input_Events or not sub.Input_Events) and
(super.TTY_State or not sub.TTY_State) and
(super.Internal_Calls or not sub.Internal_Calls) and
(super.Character_Calls or not sub.Character_Calls) and
(super.Termcap_TermInfo or not sub.Termcap_TermInfo) and
True then
return True;
else
return False;
end if;
end subset;
function trace_or (a, b : Trace_Attribute_Set) return Trace_Attribute_Set is
retval : Trace_Attribute_Set := Trace_Disable;
begin
retval.Times := (a.Times or b.Times);
retval.Tputs := (a.Tputs or b.Tputs);
retval.Update := (a.Update or b.Update);
retval.Cursor_Move := (a.Cursor_Move or b.Cursor_Move);
retval.Character_Output := (a.Character_Output or b.Character_Output);
retval.Calls := (a.Calls or b.Calls);
retval.Virtual_Puts := (a.Virtual_Puts or b.Virtual_Puts);
retval.Input_Events := (a.Input_Events or b.Input_Events);
retval.TTY_State := (a.TTY_State or b.TTY_State);
retval.Internal_Calls := (a.Internal_Calls or b.Internal_Calls);
retval.Character_Calls := (a.Character_Calls or b.Character_Calls);
retval.Termcap_TermInfo := (a.Termcap_TermInfo or b.Termcap_TermInfo);
return retval;
end trace_or;
-- Print the hexadecimal value of the mask so
-- users can set it from the command line.
function trace_num (tlevel : Trace_Attribute_Set) return String is
result : Integer := 0;
m : Integer := 1;
begin
if tlevel.Times then
result := result + m;
end if;
m := m * 2;
if tlevel.Tputs then
result := result + m;
end if;
m := m * 2;
if tlevel.Update then
result := result + m;
end if;
m := m * 2;
if tlevel.Cursor_Move then
result := result + m;
end if;
m := m * 2;
if tlevel.Character_Output then
result := result + m;
end if;
m := m * 2;
if tlevel.Calls then
result := result + m;
end if;
m := m * 2;
if tlevel.Virtual_Puts then
result := result + m;
end if;
m := m * 2;
if tlevel.Input_Events then
result := result + m;
end if;
m := m * 2;
if tlevel.TTY_State then
result := result + m;
end if;
m := m * 2;
if tlevel.Internal_Calls then
result := result + m;
end if;
m := m * 2;
if tlevel.Character_Calls then
result := result + m;
end if;
m := m * 2;
if tlevel.Termcap_TermInfo then
result := result + m;
end if;
m := m * 2;
return result'Img;
end trace_num;
function tracetrace (tlevel : Trace_Attribute_Set) return String is
use BS;
buf : Bounded_String := To_Bounded_String ("");
begin
-- The C version prints the hexadecimal value of the mask, we
-- won't do that here because this is Ada.
if tlevel = Trace_Disable then
Append (buf, "Trace_Disable");
else
if subset (tlevel,
Trace_Attribute_Set'(Times => True, others => False)) then
Append (buf, "Times");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(Tputs => True, others => False)) then
Append (buf, "Tputs");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(Update => True, others => False)) then
Append (buf, "Update");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(Cursor_Move => True,
others => False)) then
Append (buf, "Cursor_Move");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(Character_Output => True,
others => False)) then
Append (buf, "Character_Output");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Ordinary) then
Append (buf, "Ordinary");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(Calls => True, others => False)) then
Append (buf, "Calls");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(Virtual_Puts => True,
others => False)) then
Append (buf, "Virtual_Puts");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(Input_Events => True,
others => False)) then
Append (buf, "Input_Events");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(TTY_State => True,
others => False)) then
Append (buf, "TTY_State");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(Internal_Calls => True,
others => False)) then
Append (buf, "Internal_Calls");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(Character_Calls => True,
others => False)) then
Append (buf, "Character_Calls");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Attribute_Set'(Termcap_TermInfo => True,
others => False)) then
Append (buf, "Termcap_TermInfo");
Append (buf, ", ");
end if;
if subset (tlevel,
Trace_Maximum) then
Append (buf, "Maximium");
Append (buf, ", ");
end if;
end if;
if To_String (buf) (Length (buf) - 1) = ',' then
Delete (buf, Length (buf) - 1, Length (buf));
end if;
return To_String (buf);
end tracetrace;
function run_trace_menu (m : Menu; count : Integer) return Boolean is
i, p : Item;
changed : Boolean;
c, v : Key_Code;
begin
loop
changed := (count /= 0);
c := Getchar (Get_Window (m));
v := menu_virtualize (c);
case Driver (m, v) is
when Unknown_Request =>
return False;
when others =>
i := Current (m);
if i = Menus.Items (m, 1) then -- the first item
for n in t_tbl'First + 1 .. t_tbl'Last loop
if Value (i) then
Set_Value (i, False);
changed := True;
end if;
end loop;
else
for n in t_tbl'First + 1 .. t_tbl'Last loop
p := Menus.Items (m, n);
if Value (p) then
Set_Value (Menus.Items (m, 1), False);
changed := True;
exit;
end if;
end loop;
end if;
if not changed then
return True;
end if;
end case;
end loop;
end run_trace_menu;
nc_tracing, mask : Trace_Attribute_Set;
pragma Import (C, nc_tracing, "_nc_tracing");
items_a : constant Item_Array_Access :=
new Item_Array (t_tbl'First .. t_tbl'Last + 1);
mrows : Line_Count;
mcols : Column_Count;
menuwin : Window;
menu_y : constant Line_Position := 8;
menu_x : constant Column_Position := 8;
ip : Item;
m : Menu;
count : Integer;
newtrace : Trace_Attribute_Set;
begin
Add (Line => 0, Column => 0, Str => "Interactively set trace level:");
Add (Line => 2, Column => 0,
Str => " Press space bar to toggle a selection.");
Add (Line => 3, Column => 0,
Str => " Use up and down arrow to move the select bar.");
Add (Line => 4, Column => 0,
Str => " Press return to set the trace level.");
Add (Line => 6, Column => 0, Str => "(Current trace level is ");
Add (Str => tracetrace (nc_tracing) & " numerically: " &
trace_num (nc_tracing));
Add (Ch => ')');
Refresh;
for n in t_tbl'Range loop
items_a.all (n) := New_Item (t_tbl (n).name.all);
end loop;
items_a.all (t_tbl'Last + 1) := Null_Item;
m := New_Menu (items_a);
Set_Format (m, 16, 2);
Scale (m, mrows, mcols);
Switch_Options (m, (One_Valued => True, others => False), On => False);
menuwin := New_Window (mrows + 2, mcols + 2, menu_y, menu_x);
Set_Window (m, menuwin);
Set_KeyPad_Mode (menuwin, SwitchOn => True);
Box (menuwin);
Set_Sub_Window (m, Derived_Window (menuwin, mrows, mcols, 1, 1));
Post (m);
for n in t_tbl'Range loop
ip := Items (m, n);
mask := t_tbl (n).mask;
if mask = Trace_Disable then
Set_Value (ip, nc_tracing = Trace_Disable);
elsif subset (sub => mask, super => nc_tracing) then
Set_Value (ip, True);
end if;
end loop;
count := 1;
while run_trace_menu (m, count) loop
count := count + 1;
end loop;
newtrace := Trace_Disable;
for n in t_tbl'Range loop
ip := Items (m, n);
if Value (ip) then
mask := t_tbl (n).mask;
newtrace := trace_or (newtrace, mask);
end if;
end loop;
Trace_On (newtrace);
Trace_Put ("trace level interactively set to " &
tracetrace (nc_tracing));
Move_Cursor (Line => Lines - 4, Column => 0);
Add (Str => "Trace level is ");
Add (Str => tracetrace (nc_tracing));
Add (Ch => newl);
Pause; -- was just Add(); Getchar
Post (m, False);
-- menuwin has subwindows I think, which makes an error.
declare begin
Delete (menuwin);
exception when Curses_Exception => null; end;
-- free_menu(m);
-- free_item()
end ncurses2.trace_set;
|
aeszter/lox-spark | Ada | 1,700 | adb | with Ada.Strings.Hash;
package body L_Strings with SPARK_Mode is
function "=" (Left, Right : L_String) return Boolean is
begin
return Left.Length = Right.Length and then
Left.Data = Right.Data;
end "=";
function "=" (Left : L_String; Right : String) return Boolean is
begin
return Left.Length = Right'Length and then
Left.Data (Left.Data'First .. Left.Data'First + Right'Length - 1) = Right;
end "=";
function Hash (S : L_String) return Ada.Containers.Hash_Type is
begin
if S.Length = 0 then
return Ada.Strings.Hash ("");
else
return Ada.Strings.Hash (S.Data (1 .. Positive (S.Length)));
end if;
end Hash;
procedure Init (S : out L_String) is
begin
S.Data := (others => ' ');
S.Length := 0;
end Init;
function To_Bounded_String
(Source : String;
Drop : Truncation := Right)
return L_String
is
Result : L_String;
Len : constant Natural := Source'Length;
begin
Init (Result);
if Len <= Max then
Result.Data (1 .. Len) := Source;
Result.Length := Length_T (Len);
elsif Drop = Left then
Result.Data := Source (Source'Last - Max + 1 .. Source'Last);
Result.Length := Length_T (Max);
elsif Drop = Right then
Result.Data := Source (Source'First .. Source'First + Max - 1);
Result.Length := Length_T (Max);
else
raise Program_Error;
end if;
return Result;
end To_Bounded_String;
function To_String (Source : L_String) return String is
begin
return Source.Data (1 .. Natural (Source.Length));
end To_String;
end L_Strings;
|
stcarrez/ada-awa | Ada | 1,982 | adb | -----------------------------------------------------------------------
-- jobs-tests -- Unit tests for AWA jobs
-- Copyright (C) 2012, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with AWA.Jobs.Services.Tests;
package body AWA.Jobs.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Jobs.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register",
Test_Register'Access);
end Add_Tests;
-- ------------------------------
-- Test the job factory.
-- ------------------------------
procedure Test_Register (T : in out Test) is
M : AWA.Jobs.Modules.Job_Module;
begin
M.Register (Definition => Services.Tests.Test_Definition.Factory);
Util.Tests.Assert_Equals (T, 1, Integer (M.Factory.Length), "Invalid factory length");
M.Register (Definition => Services.Tests.Work_1_Definition.Factory);
Util.Tests.Assert_Equals (T, 2, Integer (M.Factory.Length), "Invalid factory length");
M.Register (Definition => Services.Tests.Work_2_Definition.Factory);
Util.Tests.Assert_Equals (T, 3, Integer (M.Factory.Length), "Invalid factory length");
end Test_Register;
end AWA.Jobs.Modules.Tests;
|
dan76/Amass | Ada | 4,381 | ads | -- Copyright © by Jeff Foley 2017-2023. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
-- SPDX-License-Identifier: Apache-2.0
name = "TeamCymru"
type = "misc"
function asn(ctx, addr, asn)
if (addr == "") then return end
local result = origin(ctx, addr)
if (result == nil or result.asn == 0) then return end
result['netblocks'] = result.prefix
local desc = get_desc(ctx, result.asn)
if (desc == "") then return end
result['desc'] = desc
new_asn(ctx, result)
end
function origin(ctx, addr)
local name = ""
local arpa = ".origin.asn.cymru.com"
if is_ipv4(addr) then
name = reverse_ipv4(addr)
else
name = ipv6_nibble(addr)
arpa = ".origin6.asn.cymru.com"
end
if (name == "") then return nil end
local n = name .. arpa
local resp, err = resolve(ctx, n, "TXT", false)
if ((err ~= nil and err ~= "") or #resp == 0) then
log(ctx, "failed to resolve the TXT record for " .. n .. ": " .. err)
return nil
end
local fields = split(resp[1].rrdata, "|")
return {
['addr']=addr,
['asn']=tonumber(trim_space(fields[1])),
['prefix']=trim_space(fields[2]),
['registry']=trim_space(fields[4]),
['cc']=trim_space(fields[3]),
}
end
function get_desc(ctx, asn)
local name = "AS" .. tostring(asn) .. ".asn.cymru.com"
local resp, err = resolve(ctx, name, "TXT", false)
if ((err ~= nil and err ~= "") or #resp == 0) then
log(ctx, "failed to resolve the TXT record for " .. name .. ": " .. err)
return ""
end
local fields = split(resp[1].rrdata, "|")
if (#fields < 5) then return "" end
return trim_space(fields[5])
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 _, match in pairs(matches) do
table.insert(result, match)
end
return result
end
function trim_space(s)
return s:match( "^%s*(.-)%s*$" )
end
function is_ipv4(addr)
local octets = { addr:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$") }
if (#octets == 4) then
for _, v in pairs(octets) do
if tonumber(v) > 255 then return false end
end
return true
end
return false
end
function reverse_ipv4(addr)
local octets = { addr:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$") }
local ip = ""
for i, o in pairs(octets) do
local n = o
if (i ~= 1) then n = n .. "." end
ip = n .. ip
end
return ip
end
function ipv6_nibble(addr)
local ip = expand_ipv6(addr)
if (ip == "") then return ip end
local parts = split(ip, ":")
-- padding
local mask = "0000"
for i, part in ipairs(parts) do
parts[i] = mask:sub(1, #mask - #part) .. part
end
-- 32 parts from 8
local temp = {}
for i, hdt in ipairs(parts) do
for part in hdt:gmatch("%x") do
temp[#temp+1] = part
end
end
parts = temp
local reverse = {}
for i = #parts, 1, -1 do
table.insert(reverse, parts[i])
end
return table.concat(reverse, ".")
end
function expand_ipv6(addr)
-- preserve ::
addr = string.gsub(addr, "::", ":z:")
-- get a table of each hexadectet
local hexadectets = {}
for hdt in string.gmatch(addr, "[%.z%x]+") do
hexadectets[#hexadectets+1] = hdt
end
-- deal with :: and check for invalid address
local z_done = false
for index, value in ipairs(hexadectets) do
if value == "z" and z_done then
-- can't have more than one ::
return ""
elseif value == "z" and not z_done then
z_done = true
hexadectets[index] = "0"
local bound = 8 - #hexadectets
for i = 1, bound, 1 do
table.insert(hexadectets, index+i, "0")
end
elseif tonumber(value, 16) > 65535 then
-- more than FFFF!
return ""
end
end
-- make sure we have exactly 8 hexadectets
if (#hexadectets > 8) then return "" end
while (#hexadectets < 8) do
hexadectets[#hexadectets+1] = "0"
end
return (table.concat(hexadectets, ":"))
end
|
charlie5/lace | Ada | 884 | ads |
with Math;
package physics.Motor.spring.angular is
-- a spring which operates in 3 degrees of rotational motion to keep a Solid in a desired attitude.
use type math.Real;
type Item is new physics.Motor.spring.item with
record
desiredForward : math.Vector_3 := (0.0, 0.0, -1.0); -- the Motor's desired forward direction, part of the desired orientation.
desiredUp : math.Vector_3 := (0.0, 1.0, 0.0); -- the Motor's desired up direction.
desiredRight : math.Vector_3 := (1.0, 0.0, 0.0); -- the Motor's desired right direction.
angularKd : math.Real := 0.000_1; -- the damping constant for angular mode.
angularKs : math.Real := 1.0; -- the spring constant for angular mode.
end record;
procedure update (Self : in out Item);
end physics.Motor.spring.angular;
|
reznikmm/matreshka | Ada | 4,616 | adb | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Matreshka.DOM_Documents;
with Matreshka.ODF_String_Constants;
with ODF.DOM.Iterators;
with ODF.DOM.Visitors;
package body Matreshka.ODF_Table.Date_Value_Attributes is
------------
-- Create --
------------
overriding function Create
(Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters)
return Table_Date_Value_Attribute_Node is
begin
return Self : Table_Date_Value_Attribute_Node do
Matreshka.ODF_Table.Constructors.Initialize
(Self'Unchecked_Access,
Parameters.Document,
Matreshka.ODF_String_Constants.Table_Prefix);
end return;
end Create;
--------------------
-- Get_Local_Name --
--------------------
overriding function Get_Local_Name
(Self : not null access constant Table_Date_Value_Attribute_Node)
return League.Strings.Universal_String
is
pragma Unreferenced (Self);
begin
return Matreshka.ODF_String_Constants.Date_Value_Attribute;
end Get_Local_Name;
begin
Matreshka.DOM_Documents.Register_Attribute
(Matreshka.ODF_String_Constants.Table_URI,
Matreshka.ODF_String_Constants.Date_Value_Attribute,
Table_Date_Value_Attribute_Node'Tag);
end Matreshka.ODF_Table.Date_Value_Attributes;
|
KipodAfterFree/KAF-2019-FireHog | Ada | 3,347 | ads | ------------------------------------------------------------------------------
-- --
-- GNAT ncurses Binding Samples --
-- --
-- Sample.Header_Handler --
-- --
-- S P E C --
-- --
------------------------------------------------------------------------------
-- Copyright (c) 1998 Free Software Foundation, Inc. --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files (the --
-- "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, distribute with modifications, sublicense, and/or sell --
-- copies of the Software, and to permit persons to whom the Software is --
-- furnished to do so, subject to the following conditions: --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. --
-- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR --
-- THE USE OR OTHER DEALINGS IN THE SOFTWARE. --
-- --
-- Except as contained in this notice, the name(s) of the above copyright --
-- holders shall not be used in advertising or otherwise to promote the --
-- sale, use or other dealings in this Software without prior written --
-- authorization. --
------------------------------------------------------------------------------
-- Author: Juergen Pfeifer <[email protected]> 1996
-- Version Control
-- $Revision: 1.5 $
-- Binding Version 00.93
------------------------------------------------------------------------------
with Terminal_Interface.Curses; use Terminal_Interface.Curses;
-- This package handles the painting of the header line of the screen.
--
package Sample.Header_Handler is
procedure Init_Header_Handler;
-- Initialize the handler for the headerlines.
procedure Update_Header_Window;
-- Update the information in the header window
end Sample.Header_Handler;
|
sebsgit/textproc | Ada | 5,767 | adb | with PixelArray; use PixelArray;
with Ada.Text_IO;
with Ada.Containers.Indefinite_Ordered_Maps;
with Ada.Containers.Generic_Sort;
use Ada.Containers;
-- keep track of (min, max) coords for each label
--
package body ImageRegions is
function toString(r: Rect) return String is
begin
return r.x'Image & ", " & r.y'Image & "; " & r.width'Image & "x" & r.height'Image;
end toString;
type Bounds is tagged record
minX, minY, maxX, maxY: Natural;
end record;
function toRect(bound: Bounds) return Rect is
result: Rect;
begin
result.x := bound.minX;
result.y := bound.minY;
result.width := bound.maxX - bound.minX;
result.height := bound.maxY - bound.minY;
return result;
end toRect;
type RegionTempData is tagged record
box: Bounds;
pixelCount: Natural;
sumX, sumY: Natural;
end record;
function fromPoint(x, y: Natural) return RegionTempData is
begin
return RegionTempData'(box => Bounds'(minX => x, maxX => x, minY => y, maxY => y), pixelCount => 1, sumX => x, sumY => y);
end fromPoint;
procedure includePoint(d: in out RegionTempData; x, y: Natural) is
begin
d.box.minX := Natural'Min(x, d.box.minX);
d.box.maxX := Natural'Max(x, d.box.maxX);
d.box.minY := Natural'Min(y, d.box.minY);
d.box.maxY := Natural'Max(y, d.box.maxY);
d.pixelCount := d.pixelCount + 1;
d.sumX := d.sumX + x;
d.sumY := d.sumY + y;
end includePoint;
package LabelMapPkg is new Ada.Containers.Indefinite_Ordered_Maps(Key_Type => RegionLabel, Element_Type => RegionTempData);
use LabelMapPkg;
procedure assignLabel(image: in out PixelArray.ImagePlane; x, y: Natural; label: RegionLabel; labelData: in out LabelMapPkg.Map) is
begin
if image.isInside(x, y) then
if image.get(x, y) = 0 then
image.set(x, y, PixelArray.Pixel(label));
if not labelData.Contains(label) then
labelData.Include(label, fromPoint(x, y));
else
includePoint(labelData(label), x, y);
end if;
assignLabel(image, x, y + 1, label, labelData);
assignLabel(image, x, y - 1, label, labelData);
assignLabel(image, x + 1, y, label, labelData);
assignLabel(image, x - 1, y, label, labelData);
end if;
end if;
end assignLabel;
procedure assignLabels(image: in out PixelArray.ImagePlane; labelData: in out LabelMapPkg.Map) is
label: RegionLabel;
begin
label := 1;
for y in 0 .. image.height - 1 loop
for x in 0 .. image.width - 1 loop
if image.get(x, y) = 0 then
assignLabel(image, x, y, label, labelData);
label := label + 1;
end if;
end loop;
end loop;
end assignLabels;
procedure drawCross(image: out PixelArray.ImagePlane; x, y: Natural; color: PixelArray.Pixel; size: Positive) is
begin
for px in x - size .. x + size loop
image.set(px, y, color);
end loop;
for py in y - size .. y + size loop
image.set(x, py, color);
end loop;
end drawCross;
procedure drawBox(image: out PixelArray.ImagePlane; box: Rect; color: PixelArray.Pixel) is
begin
for px in box.x .. box.x + box.width loop
image.set(px, box.y, color);
image.set(px, box.y + box.height, color);
end loop;
for py in box.y .. box.y + box.height loop
image.set(box.x, py, color);
image.set(box.x + box.width, py, color);
end loop;
end drawBox;
function detectRegions(image: in out PixelArray.ImagePlane) return RegionVector.Vector is
result: RegionVector.Vector;
labelData: LabelMapPkg.Map;
begin
assignLabels(image, labelData);
for it in labelData.Iterate loop
declare
newRegion: Region;
data: RegionTempData;
begin
data := labelData(it);
newRegion.label := Key(it);
newRegion.area := data.box.toRect;
newRegion.pixelCount := data.pixelCount;
newRegion.center := Centroid'(x => Float(data.sumX) / Float(data.pixelCount),
y => Float(data.sumY) / Float(data.pixelCount));
if newRegion.pixelCount > New_Region_Pixel_Threshold then
result.Append(newRegion);
end if;
end;
end loop;
return result;
end detectRegions;
procedure markRegions(image: in out PixelArray.ImagePlane; color: PixelArray.Pixel) is
allRegions: RegionVector.Vector;
begin
allRegions := detectRegions(image);
for r of allRegions loop
drawBox(image => image,
box => r.area,
color => color);
end loop;
end markRegions;
procedure sortRegions(input: in out RegionVector.Vector) is
function regionBefore(i1, i2: Natural) return Boolean is
begin
if input(i1).area.x = input(i2).area.x then
return input(i1).area.y < input(i2).area.y;
end if;
return input(i1).area.x < input(i2).area.x;
end regionBefore;
procedure regionSwap(i1, i2: Natural) is
tmp: ImageRegions.Region;
begin
tmp := input(i1);
input(i1) := input(i2);
input(i2) := tmp;
end regionSwap;
procedure doTheSorting is new Ada.Containers.Generic_Sort(Index_Type => Natural,
Before => regionBefore,
Swap => regionSwap);
begin
doTheSorting(0, Integer(input.Length - 1));
end sortRegions;
end ImageRegions;
|
ZinebZaad/ENSEEIHT | Ada | 1,166 | ads |
-- Définition de structures de données sous forme d'une liste chaînée (LC).
generic
type T_Cle is private;
type T_Donnee is private;
package LC is
type T_LC is limited private;
-- Initialiser une Sda. La Sda est vide.
procedure Initialiser(Sda: out T_LC) with
Post => Est_Vide (Sda);
-- Est-ce qu'une Sda est vide ?
function Est_Vide (Sda : T_LC) return Boolean;
-- Obtenir le nombre d'éléments d'une Sda.
function Taille (Sda : in T_LC) return Integer with
Post => Taille'Result >= 0
and (Taille'Result = 0) = Est_Vide (Sda);
-- Ajoute une Donnée associée à une Clé dans une Sda.
procedure Ajouter (Sda : in out T_LC ; Cle : in T_Cle ; Donnee : in T_Donnee);
-- Supprimer tous les éléments d'une Sda.
procedure Vider (Sda : in out T_LC) with
Post => Est_Vide (Sda);
-- Appliquer un traitement (Traiter) pour chaque couple d'une Sda.
generic
with procedure Traiter (Cle : in T_Cle; Donnee: in T_Donnee);
procedure Pour_Chaque (Sda : in T_LC);
private
type T_Cellule;
type T_LC is access T_Cellule;
type T_Cellule is record
Cle : T_Cle;
Donnee : T_Donnee;
Suivant : T_LC;
end record;
end LC;
|
tum-ei-rcs/StratoX | Ada | 2,916 | ads | ------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . F A T _ S F L T --
-- --
-- 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. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains an instantiation of the floating-point attribute
-- runtime routines for the type Short_Float.
with System.Fat_Gen;
package System.Fat_SFlt is
pragma Pure;
-- Note the only entity from this package that is accessed by Rtsfind
-- is the name of the package instantiation. Entities within this package
-- (i.e. the individual floating-point attribute routines) are accessed
-- by name using selected notation.
package Attr_Short_Float is new System.Fat_Gen (Short_Float);
end System.Fat_SFlt;
|
onox/orka | Ada | 1,907 | adb | -- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2013 - 2014 Felix Krause <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.API;
with GL.Enums.Getter;
package body GL.Rasterization is
procedure Set_Provoking_Vertex (Value : Vertex_Convention) is
begin
API.Provoking_Vertex.Ref
(case Value is
when First_Vertex => Enums.First_Vertex_Convention,
when Last_Vertex => Enums.Last_Vertex_Convention);
end Set_Provoking_Vertex;
procedure Set_Polygon_Mode (Value : Polygon_Mode_Type) is
begin
API.Polygon_Mode.Ref (Front_And_Back, Value);
end Set_Polygon_Mode;
function Polygon_Mode return Polygon_Mode_Type is
Ret : Polygon_Mode_Type := Fill;
begin
API.Get_Polygon_Mode.Ref (Enums.Getter.Polygon_Mode, Ret);
return Ret;
end Polygon_Mode;
procedure Set_Polygon_Offset (Factor, Units : Single; Clamp : Single := 0.0) is
begin
API.Polygon_Offset_Clamp.Ref (Factor, Units, Clamp);
end Set_Polygon_Offset;
-----------------------------------------------------------------------------
procedure Set_Front_Face (Face : Orientation) is
begin
API.Front_Face.Ref (Face);
end Set_Front_Face;
procedure Set_Cull_Face (Selector : Face_Selector) is
begin
API.Cull_Face.Ref (Selector);
end Set_Cull_Face;
end GL.Rasterization;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.