content stringlengths 23 1.05M |
|---|
with MSP430_SVD.USCI_A0_SPI_MODE; use MSP430_SVD.USCI_A0_SPI_MODE;
with MSP430_SVD.USCI_B0_SPI_MODE; use MSP430_SVD.USCI_B0_SPI_MODE;
with MSP430_SVD.SPECIAL_FUNCTION; use MSP430_SVD.SPECIAL_FUNCTION;
package body MSPGD.SPI.Peripheral is
procedure Init is
use MSPGD.Clock;
Baud_Rate_Div : constant UInt32 := UInt32 (Clock.Frequency) / Speed;
begin
case Module is
when USCI_A =>
USCI_A0_SPI_MODE_Periph.UCA0CTL1_SPI.UCSWRST := 1;
case Clock.Source is
when ACLK => USCI_A0_SPI_MODE_Periph.UCA0CTL1_SPI.UCSSEL := UCSSEL_1;
when SMCLK => USCI_A0_SPI_MODE_Periph.UCA0CTL1_SPI.UCSSEL := UCSSEL_2;
when others => null;
end case;
USCI_A0_SPI_MODE_Periph.UCA0BR0_SPI := Byte (Baud_Rate_Div mod 256);
USCI_A0_SPI_MODE_Periph.UCA0BR1_SPI := Byte ((Baud_Rate_Div / 256) mod 256);
USCI_A0_SPI_MODE_Periph.UCA0CTL0_SPI := (
UCMSB => 1,
UCMST => 1,
UCSYNC => 1,
UCCKPH => (if Mode = Mode_0 or else Mode = Mode_2 then 1 else 0),
UCCKPL => (if Mode = Mode_1 or else Mode = Mode_3 then 1 else 0),
UCMODE => Ucmode_0,
others => 0
);
USCI_A0_SPI_MODE_Periph.UCA0CTL1_SPI.UCSWRST := 0;
when USCI_B =>
USCI_B0_SPI_MODE_Periph.UCB0CTL1_SPI.UCSWRST := 1;
case Clock.Source is
when ACLK => USCI_B0_SPI_MODE_Periph.UCB0CTL1_SPI.UCSSEL := UCSSEL_1;
when SMCLK => USCI_B0_SPI_MODE_Periph.UCB0CTL1_SPI.UCSSEL := UCSSEL_2;
when others => null;
end case;
USCI_B0_SPI_MODE_Periph.UCB0BR0_SPI := Byte (Baud_Rate_Div mod 256);
USCI_B0_SPI_MODE_Periph.UCB0BR1_SPI := Byte ((Baud_Rate_Div / 256) mod 256);
USCI_B0_SPI_MODE_Periph.UCB0CTL0_SPI := (
UCMSB => 1,
UCMST => 1,
UCSYNC => 1,
UCCKPH => (if Mode = Mode_0 or else Mode = Mode_2 then 1 else 0),
UCCKPL => (if Mode = Mode_1 or else Mode = Mode_3 then 1 else 0),
UCMODE => Ucmode_0,
others => 0
);
USCI_B0_SPI_MODE_Periph.UCB0CTL1_SPI.UCSWRST := 0;
end case;
end Init;
procedure Wait_For_TX_Complete is
begin
case Module is
when USCI_A => while SPECIAL_FUNCTION_Periph.IFG2.UCA0TXIFG = 0 loop null; end loop;
when USCI_B => while SPECIAL_FUNCTION_Periph.IFG2.UCB0TXIFG = 0 loop null; end loop;
end case;
end Wait_For_TX_Complete;
procedure Wait_For_RX_Complete is
begin
case Module is
when USCI_A => while SPECIAL_FUNCTION_Periph.IFG2.UCA0RXIFG = 0 loop null; end loop;
when USCI_B => while SPECIAL_FUNCTION_Periph.IFG2.UCB0RXIFG = 0 loop null; end loop;
end case;
end Wait_For_RX_Complete;
procedure Transfer (Data : in out Unsigned_8) is
begin
Wait_For_TX_Complete;
case Module is
when USCI_A => USCI_A0_SPI_MODE_Periph.UCA0TXBUF_SPI := Byte (Data);
when USCI_B => USCI_B0_SPI_MODE_Periph.UCB0TXBUF_SPI := Byte (Data);
end case;
Wait_For_RX_Complete;
case Module is
when USCI_A => Data := Unsigned_8 (USCI_A0_SPI_MODE_Periph.UCA0RXBUF_SPI);
when USCI_B => Data := Unsigned_8 (USCI_B0_SPI_MODE_Periph.UCB0RXBUF_SPI);
end case;
end Transfer;
procedure Transfer (Data : in out Buffer_Type) is
begin
for I in Data'Range loop
Transfer (Data (I));
end loop;
end Transfer;
procedure Send (Data : in Unsigned_8) is
D : Unsigned_8 := Data;
begin
Transfer (D);
end Send;
procedure Send (Data : in Buffer_Type) is
begin
for D of Data loop
Send (D);
end loop;
end Send;
procedure Receive (Data : out Unsigned_8) is
D : Unsigned_8 := 0;
begin
Transfer (D);
Data := D;
end Receive;
procedure Receive (Data : out Buffer_Type) is
begin
for I in Data'Range loop
Receive (Data (I));
end loop;
end Receive;
end MSPGD.SPI.Peripheral;
|
-- This package has been generated automatically by GNATtest.
-- Do not edit any part of it, see GNATtest documentation for more details.
-- begin read only
with Gnattest_Generated;
package Statistics.Test_Data.Tests is
type Test is new GNATtest_Generated.GNATtest_Standard.Statistics.Test_Data
.Test with
null record;
procedure Test_UpdateDestroyedShips_708ec3_001497(Gnattest_T: in out Test);
-- statistics.ads:92:4:UpdateDestroyedShips:Test_UpdateDestroyedShips
procedure Test_ClearGameStats_97edec_dc3936(Gnattest_T: in out Test);
-- statistics.ads:101:4:ClearGameStats:Test_ClearGameStats
procedure Test_UpdateFinishedGoals_9c0615_51796d(Gnattest_T: in out Test);
-- statistics.ads:112:4:UpdateFinishedGoals:Test_UpdateFinishedGoals
procedure Test_UpdateFinishedMissions_cda9ad_a624ba
(Gnattest_T: in out Test);
-- statistics.ads:123:4:UpdateFinishedMissions:Test_UpdateFinishedMissions
procedure Test_UpdateCraftingOrders_24cc96_7fc6ac(Gnattest_T: in out Test);
-- statistics.ads:134:4:UpdateCraftingOrders:Test_UpdateCraftingOrders
procedure Test_UpdateKilledMobs_0403d9_0ca136(Gnattest_T: in out Test);
-- statistics.ads:146:4:UpdateKilledMobs:Test_UpdateKilledMobs
procedure Test_GetGamePoints_e274aa_4eed1d(Gnattest_T: in out Test);
-- statistics.ads:158:4:GetGamePoints:Test_GetGamePoints
end Statistics.Test_Data.Tests;
-- end read only
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
with AMF.CMOF.Associations;
with AMF.CMOF.Classes;
with AMF.CMOF.Comments;
with AMF.CMOF.Constraints;
with AMF.CMOF.Data_Types;
with AMF.CMOF.Element_Imports;
with AMF.CMOF.Enumeration_Literals;
with AMF.CMOF.Enumerations;
with AMF.CMOF.Expressions;
with AMF.CMOF.Opaque_Expressions;
with AMF.CMOF.Operations;
with AMF.CMOF.Package_Imports;
with AMF.CMOF.Package_Merges;
with AMF.CMOF.Packages;
with AMF.CMOF.Parameters;
with AMF.CMOF.Primitive_Types;
with AMF.CMOF.Properties;
with AMF.CMOF.Tags;
package AMF.Visitors.CMOF_Visitors is
pragma Preelaborate;
type CMOF_Visitor is limited interface and AMF.Visitors.Abstract_Visitor;
not overriding procedure Enter_Association
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Associations.CMOF_Association_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Association
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Associations.CMOF_Association_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Class
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Classes.CMOF_Class_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Class
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Classes.CMOF_Class_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Comment
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Comments.CMOF_Comment_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Comment
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Comments.CMOF_Comment_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Constraint
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Constraints.CMOF_Constraint_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Constraint
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Constraints.CMOF_Constraint_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Data_Type
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Data_Types.CMOF_Data_Type_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Data_Type
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Data_Types.CMOF_Data_Type_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Element_Import
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Element_Imports.CMOF_Element_Import_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Element_Import
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Element_Imports.CMOF_Element_Import_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Enumeration
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Enumerations.CMOF_Enumeration_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Enumeration
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Enumerations.CMOF_Enumeration_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Enumeration_Literal
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Enumeration_Literals.CMOF_Enumeration_Literal_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Enumeration_Literal
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Enumeration_Literals.CMOF_Enumeration_Literal_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Expression
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Expressions.CMOF_Expression_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Expression
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Expressions.CMOF_Expression_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Opaque_Expression
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Opaque_Expressions.CMOF_Opaque_Expression_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Opaque_Expression
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Opaque_Expressions.CMOF_Opaque_Expression_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Operation
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Operations.CMOF_Operation_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Operation
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Operations.CMOF_Operation_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Package
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Packages.CMOF_Package_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Package
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Packages.CMOF_Package_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Package_Import
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Package_Imports.CMOF_Package_Import_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Package_Import
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Package_Imports.CMOF_Package_Import_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Package_Merge
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Package_Merges.CMOF_Package_Merge_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Package_Merge
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Package_Merges.CMOF_Package_Merge_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Parameter
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Parameters.CMOF_Parameter_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Parameter
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Parameters.CMOF_Parameter_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Primitive_Type
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Primitive_Types.CMOF_Primitive_Type_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Primitive_Type
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Primitive_Types.CMOF_Primitive_Type_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Property
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Properties.CMOF_Property_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Property
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Properties.CMOF_Property_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Enter_Tag
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Tags.CMOF_Tag_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
not overriding procedure Leave_Tag
(Self : in out CMOF_Visitor;
Element : not null AMF.CMOF.Tags.CMOF_Tag_Access;
Control : in out AMF.Visitors.Traverse_Control) is null;
end AMF.Visitors.CMOF_Visitors;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, 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 STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file l3gd20.c --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief This file provides a set of functions needed to manage the --
-- L3GD20, ST MEMS motion sensor, 3-axis digital output --
-- gyroscope. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with System;
package body L3GD20 is
-- the following are per Table 4 of the L3GD20 Datasheet, pg 9.
-- the values are millidegrees per second, so we scale accordingly
Sensitivity_250dps : constant := 8.75 * 0.001; -- mdps/digit
Sensitivity_500dps : constant := 17.5 * 0.001; -- mdps/digit
Sensitivity_2000dps : constant := 70.0 * 0.001; -- mdps/digit
ReadWrite_CMD : constant := 16#80#;
MultiUInt8_CMD : constant := 16#40#;
-- bit definitions for the CTRL_REG3 register
INT1_Interrupt_Enable : constant := 2#1000_0000#;
Interrupt_Pin_Mode_Bit : constant := 2#0001_0000#;
INT2_Data_Ready_Interrupt_Enable : constant := 2#0000_1000#;
INT2_Watermark_Interrupt_Enable : constant := 2#0000_0100#;
INT2_Overrun_Interrupt_Enable : constant := 2#0000_0010#;
INT2_FIFO_Empty_Interrupt_Enable : constant := 2#0000_0001#;
-- bit definitions for the CTRL_REG4 register
Endian_Selection_Mask : constant := 2#0100_0000#;
Fullscale_Selection_Bits : constant := 2#0011_0000#;
-- bit definitions for the CTRL_REG5 register
Boot_Bit : constant := 2#1000_0000#;
FIFO_Enable_Bit : constant := 2#0100_0000#;
HighPass_Filter_Enable : constant := 2#0001_0000#;
LowPass_Filter_Enable : constant := 2#0000_0010#;
-- bit definitions for the FIFO_CTRL register
FIFO_Mode_Bits : constant := 2#1110_0000#;
Watermark_Threshold_Bits : constant := 2#0001_1111#;
-- bit definitions for the FIFO_SRC register
Watermark_Status_Bit : constant := 2#1000_0000#;
FIFO_Overrun_Bit : constant := 2#0100_0000#;
FIFO_Empty_Bit : constant := 2#0010_0000#;
FIFO_Depth_Bits : constant := 2#0001_1111#;
-- bit definitions for the INT1_CFG register
Logically_And_Or_Events_Bit : constant := 2#1000_0000#;
Int1_Latch_Enable_Bit : constant := 2#0100_0000#;
Axes_Interrupt_Enablers : constant array (Axes_Interrupts) of UInt8 :=
(Z_High_Interrupt => 2#0010_0000#,
Z_Low_Interrupt => 2#0001_0000#,
Y_High_Interrupt => 2#0000_1000#,
Y_Low_Interrupt => 2#0000_0100#,
X_High_Interrupt => 2#0000_0010#,
X_Low_Interrupt => 2#0000_0001#);
function As_UInt8 is new Ada.Unchecked_Conversion
(Source => High_Pass_Filter_Mode, Target => UInt8);
function As_UInt8 is new Ada.Unchecked_Conversion
(Source => High_Pass_Cutoff_Frequency, Target => UInt8);
function As_UInt8 is new Ada.Unchecked_Conversion
(Source => Power_Mode_Selection, Target => UInt8);
function As_UInt8 is new Ada.Unchecked_Conversion
(Source => Output_Data_Rate_Selection, Target => UInt8);
function As_UInt8 is new Ada.Unchecked_Conversion
(Source => Axes_Selection, Target => UInt8);
function As_UInt8 is new Ada.Unchecked_Conversion
(Source => Bandwidth_Selection, Target => UInt8);
function As_UInt8 is new Ada.Unchecked_Conversion
(Source => Block_Data_Update_Selection, Target => UInt8);
function As_UInt8 is new Ada.Unchecked_Conversion
(Source => Endian_Data_Selection, Target => UInt8);
function As_UInt8 is new Ada.Unchecked_Conversion
(Source => Full_Scale_Selection, Target => UInt8);
type Angle_Rate_Pointer is access all Angle_Rate with Storage_Size => 0;
function As_Angle_Rate_Pointer is new Ada.Unchecked_Conversion
(Source => System.Address, Target => Angle_Rate_Pointer);
-- So that we can treat the address of a UInt8 as a pointer to a two-UInt8
-- sequence representing a signed integer quantity.
procedure Swap2 (Location : System.Address) with Inline;
-- Swaps the two UInt8s at Location and Location+1
procedure SPI_Mode (This : Three_Axis_Gyroscope; Enabled : Boolean);
-- Enable or disable SPI mode communication with the device. This is named
-- "chip select" in other demos/examples.
----------------
-- Initialize --
----------------
procedure Initialize
(This : in out Three_Axis_Gyroscope;
Port : Any_SPI_Port;
Chip_Select : Any_GPIO_Point)
is
begin
This.Port := Port;
This.CS := Chip_Select;
SPI_Mode (This, Enabled => False);
end Initialize;
-----------------
-- SPI_Mode --
-----------------
procedure SPI_Mode (This : Three_Axis_Gyroscope; Enabled : Boolean) is
-- When the pin is low (cleared), the device is in SPI mode.
-- When the pin is high (set), the device is in I2C mode.
-- We want SPI mode communication, so Enabled, when True,
-- means we must drive the pin low.
begin
if Enabled then
This.CS.Clear;
else
This.CS.Set;
end if;
end SPI_Mode;
-----------
-- Write --
-----------
procedure Write (This : Three_Axis_Gyroscope; Addr : Register; Data : UInt8)
is
Status : SPI_Status;
begin
SPI_Mode (This, Enabled => True);
This.Port.Transmit (SPI_Data_8b'(1 => UInt8 (Addr)), Status);
if Status /= Ok then
raise Program_Error;
end if;
This.Port.Transmit (SPI_Data_8b'(1 => Data), Status);
if Status /= Ok then
raise Program_Error;
end if;
SPI_Mode (This, Enabled => False);
end Write;
----------
-- Read --
----------
procedure Read
(This : Three_Axis_Gyroscope;
Addr : Register;
Data : out UInt8)
is
Status : SPI_Status;
Tmp_Data : SPI_Data_8b (1 .. 1);
begin
SPI_Mode (This, Enabled => True);
This.Port.Transmit (SPI_Data_8b'(1 => UInt8 (Addr) or ReadWrite_CMD),
Status);
if Status /= Ok then
raise Program_Error;
end if;
This.Port.Receive (Tmp_Data, Status);
if Status /= Ok then
raise Program_Error;
end if;
Data := Tmp_Data (Tmp_Data'First);
SPI_Mode (This, Enabled => False);
end Read;
----------------
-- Read_UInt8s --
----------------
procedure Read_UInt8s
(This : Three_Axis_Gyroscope;
Addr : Register;
Buffer : out SPI_Data_8b;
Count : Natural)
is
Index : Natural := Buffer'First;
Status : SPI_Status;
Tmp_Data : SPI_Data_8b (1 .. 1);
begin
SPI_Mode (This, Enabled => True);
This.Port.Transmit
(SPI_Data_8b'(1 => UInt8 (Addr) or ReadWrite_CMD or MultiUInt8_CMD),
Status);
if Status /= Ok then
raise Program_Error;
end if;
for K in 1 .. Count loop
This.Port.Receive (Tmp_Data, Status);
if Status /= Ok then
raise Program_Error;
end if;
Buffer (Index) := Tmp_Data (Tmp_Data'First);
Index := Index + 1;
end loop;
SPI_Mode (This, Enabled => False);
end Read_UInt8s;
---------------
-- Configure --
---------------
procedure Configure
(This : in out Three_Axis_Gyroscope;
Power_Mode : Power_Mode_Selection;
Output_Data_Rate : Output_Data_Rate_Selection;
Axes_Enable : Axes_Selection;
Bandwidth : Bandwidth_Selection;
BlockData_Update : Block_Data_Update_Selection;
Endianness : Endian_Data_Selection;
Full_Scale : Full_Scale_Selection)
is
Ctrl1 : UInt8;
Ctrl4 : UInt8;
begin
Ctrl1 := As_UInt8 (Power_Mode) or
As_UInt8 (Output_Data_Rate) or
As_UInt8 (Axes_Enable) or
As_UInt8 (Bandwidth);
Ctrl4 := As_UInt8 (BlockData_Update) or
As_UInt8 (Endianness) or
As_UInt8 (Full_Scale);
Write (This, CTRL_REG1, Ctrl1);
Write (This, CTRL_REG4, Ctrl4);
end Configure;
-----------
-- Sleep --
-----------
procedure Sleep (This : in out Three_Axis_Gyroscope) is
Ctrl1 : UInt8;
Sleep_Mode : constant := 2#1000#; -- per the Datasheet, Table 22, pg 32
begin
Read (This, CTRL_REG1, Ctrl1);
Ctrl1 := Ctrl1 or Sleep_Mode;
Write (This, CTRL_REG1, Ctrl1);
end Sleep;
--------------------------------
-- Configure_High_Pass_Filter --
--------------------------------
procedure Configure_High_Pass_Filter
(This : in out Three_Axis_Gyroscope;
Mode_Selection : High_Pass_Filter_Mode;
Cutoff_Frequency : High_Pass_Cutoff_Frequency)
is
Ctrl2 : UInt8;
begin
-- note that the two high-order bits must remain zero, per the datasheet
Ctrl2 := As_UInt8 (Mode_Selection) or As_UInt8 (Cutoff_Frequency);
Write (This, CTRL_REG2, Ctrl2);
end Configure_High_Pass_Filter;
-----------------------------
-- Enable_High_Pass_Filter --
-----------------------------
procedure Enable_High_Pass_Filter (This : in out Three_Axis_Gyroscope) is
Ctrl5 : UInt8;
begin
Read (This, CTRL_REG5, Ctrl5);
-- set HPen bit
Ctrl5 := Ctrl5 or HighPass_Filter_Enable;
Write (This, CTRL_REG5, Ctrl5);
end Enable_High_Pass_Filter;
------------------------------
-- Disable_High_Pass_Filter --
------------------------------
procedure Disable_High_Pass_Filter (This : in out Three_Axis_Gyroscope) is
Ctrl5 : UInt8;
begin
Read (This, CTRL_REG5, Ctrl5);
-- clear HPen bit
Ctrl5 := Ctrl5 and (not HighPass_Filter_Enable);
Write (This, CTRL_REG5, Ctrl5);
end Disable_High_Pass_Filter;
----------------------------
-- Enable_Low_Pass_Filter --
----------------------------
procedure Enable_Low_Pass_Filter (This : in out Three_Axis_Gyroscope) is
Ctrl5 : UInt8;
begin
Read (This, CTRL_REG5, Ctrl5);
Ctrl5 := Ctrl5 or LowPass_Filter_Enable;
Write (This, CTRL_REG5, Ctrl5);
end Enable_Low_Pass_Filter;
-----------------------------
-- Disable_Low_Pass_Filter --
-----------------------------
procedure Disable_Low_Pass_Filter (This : in out Three_Axis_Gyroscope) is
Ctrl5 : UInt8;
begin
Read (This, CTRL_REG5, Ctrl5);
-- clear HPen bit
Ctrl5 := Ctrl5 and (not LowPass_Filter_Enable);
Write (This, CTRL_REG5, Ctrl5);
end Disable_Low_Pass_Filter;
---------------------
-- Reference_Value --
---------------------
function Reference_Value (This : Three_Axis_Gyroscope) return UInt8 is
Result : UInt8;
begin
Read (This, Reference, Result);
return Result;
end Reference_Value;
-------------------
-- Set_Reference --
-------------------
procedure Set_Reference (This : in out Three_Axis_Gyroscope; Value : UInt8) is
begin
Write (This, Reference, Value);
end Set_Reference;
-----------------
-- Data_Status --
-----------------
function Data_Status (This : Three_Axis_Gyroscope) return Gyro_Data_Status is
Result : UInt8;
function As_Gyro_Data_Status is
new Ada.Unchecked_Conversion (Source => UInt8,
Target => Gyro_Data_Status);
begin
Read (This, Status, Result);
return As_Gyro_Data_Status (Result);
end Data_Status;
---------------
-- Device_Id --
---------------
function Device_Id (This : Three_Axis_Gyroscope) return UInt8 is
Result : UInt8;
begin
Read (This, Who_Am_I, Result);
return Result;
end Device_Id;
-----------------
-- Temperature --
-----------------
function Temperature (This : Three_Axis_Gyroscope) return UInt8 is
Result : UInt8;
begin
Read (This, OUT_Temp, Result);
return Result;
end Temperature;
------------
-- Reboot --
------------
procedure Reboot (This : Three_Axis_Gyroscope) is
Ctrl5 : UInt8;
begin
Read (This, CTRL_REG5, Ctrl5);
-- set the boot bit
Ctrl5 := Ctrl5 or Boot_Bit;
Write (This, CTRL_REG5, Ctrl5);
end Reboot;
----------------------------
-- Full_Scale_Sensitivity --
----------------------------
function Full_Scale_Sensitivity (This : Three_Axis_Gyroscope) return Float is
Ctrl4 : UInt8;
Result : Float;
Fullscale_Selection : UInt8;
begin
Read (This, CTRL_REG4, Ctrl4);
Fullscale_Selection := Ctrl4 and Fullscale_Selection_Bits;
if Fullscale_Selection = L3GD20_Fullscale_250'Enum_Rep then
Result := Sensitivity_250dps;
elsif Fullscale_Selection = L3GD20_Fullscale_500'Enum_Rep then
Result := Sensitivity_500dps;
else
Result := Sensitivity_2000dps;
end if;
return Result;
end Full_Scale_Sensitivity;
-------------------------
-- Get_Raw_Angle_Rates --
-------------------------
procedure Get_Raw_Angle_Rates
(This : Three_Axis_Gyroscope;
Rates : out Angle_Rates)
is
Ctrl4 : UInt8;
UInt8s_To_Read : constant Integer := 6; -- ie, three 2-UInt8 integers
-- the number of UInt8s in an Angle_Rates record object
Received : SPI_Data_8b (1 .. UInt8s_To_Read);
begin
Read (This, CTRL_REG4, Ctrl4);
Read_UInt8s (This, OUT_X_L, Received, UInt8s_To_Read);
-- The above has the effect of separate reads, as follows:
-- Read (This, OUT_X_L, Received (1));
-- Read (This, OUT_X_H, Received (2));
-- Read (This, OUT_Y_L, Received (3));
-- Read (This, OUT_Y_H, Received (4));
-- Read (This, OUT_Z_L, Received (5));
-- Read (This, OUT_Z_H, Received (6));
if (Ctrl4 and Endian_Selection_Mask) = L3GD20_Big_Endian'Enum_Rep then
Swap2 (Received (1)'Address);
Swap2 (Received (3)'Address);
Swap2 (Received (5)'Address);
end if;
Rates.X := As_Angle_Rate_Pointer (Received (1)'Address).all;
Rates.Y := As_Angle_Rate_Pointer (Received (3)'Address).all;
Rates.Z := As_Angle_Rate_Pointer (Received (5)'Address).all;
end Get_Raw_Angle_Rates;
--------------------------
-- Configure_Interrupt1 --
--------------------------
procedure Configure_Interrupt1
(This : in out Three_Axis_Gyroscope;
Triggers : Threshold_Event_List;
Latched : Boolean := False;
Active_Edge : Interrupt1_Active_Edge := L3GD20_Interrupt1_High_Edge;
Combine_Events : Boolean := False;
Sample_Count : Sample_Counter := 0)
is
Config : UInt8;
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 and 16#DF#;
Ctrl3 := Ctrl3 or Active_Edge'Enum_Rep;
Ctrl3 := Ctrl3 or INT1_Interrupt_Enable;
Write (This, CTRL_REG3, Ctrl3);
if Sample_Count > 0 then
Set_Duration_Counter (This, Sample_Count);
end if;
Config := 0;
if Latched then
Config := Config or Int1_Latch_Enable_Bit;
end if;
if Combine_Events then
Config := Config or Logically_And_Or_Events_Bit;
end if;
for Event of Triggers loop
Config := Config or Axes_Interrupt_Enablers (Event.Axis);
end loop;
Write (This, INT1_CFG, Config);
for Event of Triggers loop
Set_Threshold (This, Event.Axis, Event.Threshold);
end loop;
end Configure_Interrupt1;
----------------------------
-- Set_Interrupt_Pin_Mode --
----------------------------
procedure Set_Interrupt_Pin_Mode
(This : in out Three_Axis_Gyroscope;
Mode : Pin_Modes)
is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 and (not Interrupt_Pin_Mode_Bit);
Ctrl3 := Ctrl3 or Mode'Enum_Rep;
Write (This, CTRL_REG3, Ctrl3);
end Set_Interrupt_Pin_Mode;
-----------------------
-- Enable_Interrupt1 --
-----------------------
procedure Enable_Interrupt1 (This : in out Three_Axis_Gyroscope) is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 or INT1_Interrupt_Enable;
Write (This, CTRL_REG3, Ctrl3);
end Enable_Interrupt1;
------------------------
-- Disable_Interrupt1 --
------------------------
procedure Disable_Interrupt1 (This : in out Three_Axis_Gyroscope) is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 and (not INT1_Interrupt_Enable);
Write (This, CTRL_REG3, Ctrl3);
end Disable_Interrupt1;
-----------------------
-- Interrupt1_Status --
-----------------------
function Interrupt1_Source (This : Three_Axis_Gyroscope) return Interrupt1_Sources is
Result : UInt8;
function As_Interrupt_Source is new Ada.Unchecked_Conversion
(Source => UInt8, Target => Interrupt1_Sources);
begin
Read (This, INT1_SRC, Result);
return As_Interrupt_Source (Result);
end Interrupt1_Source;
--------------------------
-- Set_Duration_Counter --
--------------------------
procedure Set_Duration_Counter
(This : in out Three_Axis_Gyroscope;
Value : Sample_Counter)
is
Wait_Bit : constant := 2#1000_0000#;
begin
Write (This, INT1_Duration, UInt8 (Value) or Wait_Bit);
end Set_Duration_Counter;
------------------
-- Enable_Event --
------------------
procedure Enable_Event
(This : in out Three_Axis_Gyroscope;
Event : Axes_Interrupts)
is
Config : UInt8;
begin
Read (This, INT1_CFG, Config);
Config := Config or Axes_Interrupt_Enablers (Event);
Write (This, INT1_CFG, Config);
end Enable_Event;
-------------------
-- Disable_Event --
-------------------
procedure Disable_Event
(This : in out Three_Axis_Gyroscope;
Event : Axes_Interrupts)
is
Config : UInt8;
begin
Read (This, INT1_CFG, Config);
Config := Config and (not Axes_Interrupt_Enablers (Event));
Write (This, INT1_CFG, Config);
end Disable_Event;
-------------------
-- Set_Threshold --
-------------------
procedure Set_Threshold
(This : in out Three_Axis_Gyroscope;
Event : Axes_Interrupts;
Value : Axis_Sample_Threshold)
is
begin
case Event is
when Z_High_Interrupt | Z_Low_Interrupt =>
Write (This, INT1_TSH_ZL, UInt8 (Value));
Write (This, INT1_TSH_ZH, UInt8 (Shift_Right (Value, 8)));
when Y_High_Interrupt | Y_Low_Interrupt =>
Write (This, INT1_TSH_YL, UInt8 (Value));
Write (This, INT1_TSH_YH, UInt8 (Shift_Right (Value, 8)));
when X_High_Interrupt | X_Low_Interrupt =>
Write (This, INT1_TSH_XL, UInt8 (Value));
Write (This, INT1_TSH_XH, UInt8 (Shift_Right (Value, 8)));
end case;
end Set_Threshold;
-------------------
-- Set_FIFO_Mode --
-------------------
procedure Set_FIFO_Mode
(This : in out Three_Axis_Gyroscope;
Mode : FIFO_Modes)
is
FIFO : UInt8;
begin
Read (This, FIFO_CTRL, FIFO);
FIFO := FIFO and (not FIFO_Mode_Bits); -- clear the current bits
FIFO := FIFO or Mode'Enum_Rep;
Write (This, FIFO_CTRL, FIFO);
end Set_FIFO_Mode;
-----------------
-- Enable_FIFO --
-----------------
procedure Enable_FIFO (This : in out Three_Axis_Gyroscope) is
Ctrl5 : UInt8;
begin
Read (This, CTRL_REG5, Ctrl5);
Ctrl5 := Ctrl5 or FIFO_Enable_Bit;
Write (This, CTRL_REG5, Ctrl5);
end Enable_FIFO;
------------------
-- Disable_FIFO --
------------------
procedure Disable_FIFO (This : in out Three_Axis_Gyroscope) is
Ctrl5 : UInt8;
begin
Read (This, CTRL_REG5, Ctrl5);
Ctrl5 := Ctrl5 and (not FIFO_Enable_Bit);
Write (This, CTRL_REG5, Ctrl5);
end Disable_FIFO;
------------------------
-- Set_FIFO_Watermark --
------------------------
procedure Set_FIFO_Watermark
(This : in out Three_Axis_Gyroscope;
Level : FIFO_Level)
is
Value : UInt8;
begin
Read (This, FIFO_CTRL, Value);
Value := Value and (not Watermark_Threshold_Bits); -- clear the bits
Value := Value or UInt8 (Level);
Write (This, FIFO_CTRL, Value);
end Set_FIFO_Watermark;
------------------------------
-- Get_Raw_Angle_Rates_FIFO --
------------------------------
procedure Get_Raw_Angle_Rates_FIFO
(This : in out Three_Axis_Gyroscope;
Buffer : out Angle_Rates_FIFO_Buffer)
is
Ctrl4 : UInt8;
Angle_Rate_Size : constant Integer := 6; -- UInt8s
UInt8s_To_Read : constant Integer := Buffer'Length * Angle_Rate_Size;
Received : SPI_Data_8b (0 .. UInt8s_To_Read - 1)
with Alignment => 2;
begin
Read (This, CTRL_REG4, Ctrl4);
Read_UInt8s (This, OUT_X_L, Received, UInt8s_To_Read);
if (Ctrl4 and Endian_Selection_Mask) = L3GD20_Big_Endian'Enum_Rep then
declare
J : Integer := 0;
begin
for K in Received'First .. Received'Last / 2 loop
Swap2 (Received (J)'Address);
J := J + 2;
end loop;
end;
end if;
declare
J : Integer := 0;
begin
for K in Buffer'Range loop
Buffer (K).X := As_Angle_Rate_Pointer (Received (J)'Address).all;
J := J + 2;
Buffer (K).Y := As_Angle_Rate_Pointer (Received (J)'Address).all;
J := J + 2;
Buffer (K).Z := As_Angle_Rate_Pointer (Received (J)'Address).all;
J := J + 2;
end loop;
end;
end Get_Raw_Angle_Rates_FIFO;
------------------------
-- Current_FIFO_Depth --
------------------------
function Current_FIFO_Depth (This : Three_Axis_Gyroscope) return FIFO_Level is
Result : UInt8;
begin
Read (This, FIFO_SRC, Result);
Result := Result and FIFO_Depth_Bits;
return FIFO_Level (Result);
end Current_FIFO_Depth;
--------------------------
-- FIFO_Below_Watermark --
--------------------------
function FIFO_Below_Watermark (This : Three_Axis_Gyroscope) return Boolean is
Result : UInt8;
begin
Read (This, FIFO_SRC, Result);
Result := Result and Watermark_Status_Bit;
return Result = 0;
end FIFO_Below_Watermark;
----------------
-- FIFO_Empty --
----------------
function FIFO_Empty (This : Three_Axis_Gyroscope) return Boolean is
Result : UInt8;
begin
Read (This, FIFO_SRC, Result);
Result := Result and FIFO_Empty_Bit;
return Result = FIFO_Empty_Bit;
end FIFO_Empty;
------------------
-- FIFO_Overrun --
------------------
function FIFO_Overrun (This : Three_Axis_Gyroscope) return Boolean is
Result : UInt8;
begin
Read (This, FIFO_SRC, Result);
Result := Result and FIFO_Overrun_Bit;
return Result = FIFO_Overrun_Bit;
end FIFO_Overrun;
---------------------------------
-- Enable_Data_Ready_Interrupt --
---------------------------------
procedure Enable_Data_Ready_Interrupt (This : in out Three_Axis_Gyroscope) is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 or INT2_Data_Ready_Interrupt_Enable;
Write (This, CTRL_REG3, Ctrl3);
end Enable_Data_Ready_Interrupt;
----------------------------------
-- Disable_Data_Ready_Interrupt --
----------------------------------
procedure Disable_Data_Ready_Interrupt (This : in out Three_Axis_Gyroscope) is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 and (not INT2_Data_Ready_Interrupt_Enable);
Write (This, CTRL_REG3, Ctrl3);
end Disable_Data_Ready_Interrupt;
-------------------------------------
-- Enable_FIFO_Watermark_Interrupt --
-------------------------------------
procedure Enable_FIFO_Watermark_Interrupt (This : in out Three_Axis_Gyroscope) is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 or INT2_Watermark_Interrupt_Enable;
Write (This, CTRL_REG3, Ctrl3);
end Enable_FIFO_Watermark_Interrupt;
-----------------------------
-- Disable_Int1_Interrupts --
-----------------------------
procedure Disable_Int1_Interrupts (This : in out Three_Axis_Gyroscope) is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 and 2#0001_1111#;
Write (This, CTRL_REG3, Ctrl3);
end Disable_Int1_Interrupts;
-----------------------------
-- Disable_Int2_Interrupts --
-----------------------------
procedure Disable_Int2_Interrupts (This : in out Three_Axis_Gyroscope) is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 and 2#1111_0000#;
Write (This, CTRL_REG3, Ctrl3);
end Disable_Int2_Interrupts;
--------------------------------------
-- Disable_FIFO_Watermark_Interrupt --
--------------------------------------
procedure Disable_FIFO_Watermark_Interrupt
(This : in out Three_Axis_Gyroscope)
is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 and (not INT2_Watermark_Interrupt_Enable);
Write (This, CTRL_REG3, Ctrl3);
end Disable_FIFO_Watermark_Interrupt;
-----------------------------------
-- Enable_FIFO_Overrun_Interrupt --
-----------------------------------
procedure Enable_FIFO_Overrun_Interrupt
(This : in out Three_Axis_Gyroscope)
is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 or INT2_Overrun_Interrupt_Enable;
Write (This, CTRL_REG3, Ctrl3);
end Enable_FIFO_Overrun_Interrupt;
------------------------------------
-- Disable_FIFO_Overrun_Interrupt --
------------------------------------
procedure Disable_FIFO_Overrun_Interrupt
(This : in out Three_Axis_Gyroscope)
is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 and (not INT2_Overrun_Interrupt_Enable);
Write (This, CTRL_REG3, Ctrl3);
end Disable_FIFO_Overrun_Interrupt;
---------------------------------
-- Enable_FIFO_Empty_Interrupt --
---------------------------------
procedure Enable_FIFO_Empty_Interrupt
(This : in out Three_Axis_Gyroscope)
is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 or INT2_FIFO_Empty_Interrupt_Enable;
Write (This, CTRL_REG3, Ctrl3);
end Enable_FIFO_Empty_Interrupt;
----------------------------------
-- Disable_FIFO_Empty_Interrupt --
----------------------------------
procedure Disable_FIFO_Empty_Interrupt
(This : in out Three_Axis_Gyroscope)
is
Ctrl3 : UInt8;
begin
Read (This, CTRL_REG3, Ctrl3);
Ctrl3 := Ctrl3 and (not INT2_FIFO_Empty_Interrupt_Enable);
Write (This, CTRL_REG3, Ctrl3);
end Disable_FIFO_Empty_Interrupt;
-----------
-- Swap2 --
-----------
procedure Swap2 (Location : System.Address) is
X : UInt16;
for X'Address use Location;
function Bswap_16 (X : UInt16) return UInt16;
pragma Import (Intrinsic, Bswap_16, "__builtin_bswap16");
begin
X := Bswap_16 (X);
end Swap2;
-----------
-- Reset --
-----------
procedure Reset (This : in out Three_Axis_Gyroscope) is
begin
-- per the Datasheet, Table 17, pg 29
Write (This, CTRL_REG1, 2#0000_0111#);
Write (This, CTRL_REG2, 0);
Write (This, CTRL_REG3, 0);
Write (This, CTRL_REG4, 0);
Write (This, CTRL_REG5, 0);
Write (This, Reference, 0);
Write (This, FIFO_CTRL, 0);
Write (This, INT1_CFG, 0);
Write (This, INT1_TSH_ZL, 0);
Write (This, INT1_TSH_ZH, 0);
Write (This, INT1_TSH_YL, 0);
Write (This, INT1_TSH_YH, 0);
Write (This, INT1_TSH_XL, 0);
Write (This, INT1_TSH_XH, 0);
Write (This, INT1_Duration, 0);
end Reset;
end L3GD20;
|
package SPARKNaCl.Debug
with SPARK_Mode => On
is
-- as per Boolean'Image (B) but does not violate the
-- No_Enumeration_Maps restriction
function Img (B : in Boolean) return String is
(if B then "TRUE" else "FALSE");
procedure DH (S : in String; D : in Byte_Seq);
procedure DH (S : in String; D : in Boolean);
procedure DH (S : in String; D : in I64);
-- Same but output in hex
procedure DHH (S : in String; D : in I64);
end SPARKNaCl.Debug;
|
-- { dg-do compile }
with Pack10_Pkg; use Pack10_Pkg;
package Pack10 is
type Boolean_Vector is array (Positive range <>) of Boolean;
type Packed_Boolean_Vector is new Boolean_Vector;
pragma Pack (Packed_Boolean_Vector);
procedure My_Proc is new Proc (Packed_Boolean_Vector);
end Pack10;
|
package discriminant_specification is
type Buffer(Size : Integer := 100) is
record
Pos : Integer := 0;
Value : String(1 .. Size);
end record;
end discriminant_specification;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Barriers;
with GL.Types;
with Orka.Transforms.Doubles.Vectors;
with Orka.Transforms.Doubles.Vector_Conversions;
with Orka.Rendering.Drawing;
package body Orka.Resources.Models is
function Create_Group
(Object : aliased in out Model;
Culler : Culling.Culler_Ptr;
Capacity : Positive) return Group_Access
is
Shapes_Count : constant Natural := Object.Scene.Shapes.Element'Length;
begin
return new Model_Group'
(Model => Object'Access,
Instances => Model_Instances.Create_Manager
(Capacity => Capacity, Parts => Shapes_Count),
Cull_Instance => Culling.Create_Instance
(Culler, Transforms => Capacity * Shapes_Count, Commands => Shapes_Count),
others => <>);
end Create_Group;
procedure Add_Instance
(Object : access Model_Group;
Instance : in out Model_Instance_Ptr) is
begin
if Instance.Group /= null then
raise Program_Error;
end if;
Instance.Group := Object;
Instance.Scene := Object.Model.Scene.Scene;
Instance.Instance := Object.Instances.Add_Instance;
end Add_Instance;
procedure Remove_Instance
(Object : in out Model_Group;
Instance : in out Model_Instance_Ptr) is
begin
if Instance.Group = null then
raise Program_Error;
end if;
Instance.Group := null;
Object.Instances.Remove_Instance (Instance.Instance);
end Remove_Instance;
-----------------------------------------------------------------------------
procedure Cull (Object : in out Model_Group) is
begin
Object.Cull_Instance.Cull
(Transforms => Object.Instances.Transforms,
Bounds => Object.Model.Bounds,
Commands => Object.Model.Batch.Commands.Buffer,
Compacted_Transforms => Object.Compacted_Transforms,
Compacted_Commands => Object.Compacted_Commands,
Instances => Object.Instances.Length);
end Cull;
procedure Render (Object : in out Model_Group) is
use all type Rendering.Buffers.Indexed_Buffer_Target;
begin
Object.Model.Batch.Data.Bind (Shader_Storage, 1);
Object.Compacted_Transforms.Bind (Shader_Storage, 0);
GL.Barriers.Memory_Barrier ((Shader_Storage | Command => True, others => False));
Rendering.Drawing.Draw_Indexed_Indirect
(GL.Types.Triangles, Object.Model.Batch.Indices.Buffer, Object.Compacted_Commands);
end Render;
procedure After_Render (Object : in out Model_Group) is
begin
Object.Instances.Complete_Frame;
end After_Render;
-----------------------------------------------------------------------------
procedure Update_Transforms
(Object : in out Model_Instance;
View_Position : Behaviors.Vector4)
is
use Transforms;
use Orka.Transforms.Doubles.Vectors;
use Orka.Transforms.Doubles.Vector_Conversions;
pragma Assert (Object.Group /= null);
Position : Behaviors.Vector4
renames Behaviors.Behavior'Class (Object).Position;
procedure Write_Transforms (Cursors : Cursor_Array) is
begin
for Index in Cursors'Range loop
Object.Group.Instances.Set_Transform
(Value => Object.Scene.World_Transform (Cursors (Index)),
Instance => Object.Instance,
Part => Index - Cursors'First);
end loop;
end Write_Transforms;
begin
-- Compute the world transforms by multiplying the local transform
-- of each node with the world transform of its parent. Also updates
-- the visibility of each node.
Object.Scene.Update_Tree (T (Convert (Position - View_Position)));
-- Write the world transform of the leaf nodes to the persistent mapped buffer
Object.Group.Model.Scene.Shapes.Query_Element (Write_Transforms'Access);
-- Note: This requires that the structure of the model's scene tree is
-- identical to the instance's scene so that we can re-use the cursors
end Update_Transforms;
end Orka.Resources.Models;
|
-----------------------------------------------------------------------
-- el -- Evaluate an EL expression
-- Copyright (C) 2009, 2010 Free Software Foundation, Inc.
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- This file is part of ASF.
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 2,
-- 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; see the file COPYING. If not, write to
-- the Free Software Foundation, 59 Temple Place - Suite 330,
-- Boston, MA 02111-1307, USA.
-----------------------------------------------------------------------
with EL.Expressions;
with EL.Objects;
with EL.Contexts.Default;
with Ada.Text_IO;
with Bean;
procedure Variables is
use Bean;
Joe : Person_Access := Create_Person ("Joe", "Smith", 12);
Bill : Person_Access := Create_Person ("Bill", "Johnson", 42);
Ctx : EL.Contexts.Default.Default_Context;
E : EL.Expressions.Expression;
VE : EL.Expressions.Value_Expression;
Result : EL.Objects.Object;
begin
E := EL.Expressions.Create_Expression ("#{user.firstName} #{user.lastName}", Ctx);
-- Bind the context to 'Joe' and evaluate
Ctx.Set_Variable ("user", Joe);
Result := E.Get_Value (Ctx);
Ada.Text_IO.Put_Line ("User name is " & EL.Objects.To_String (Result));
-- Bind the context to 'Bill' and evaluate
Ctx.Set_Variable ("user", Bill);
Result := E.Get_Value (Ctx);
Ada.Text_IO.Put_Line ("User name is " & EL.Objects.To_String (Result));
-- Create a value expression to change the user firstName property.
VE := EL.Expressions.Create_Expression ("#{user.firstName}", Ctx);
-- Change the user first name by setting the value expression.
VE.Set_Value (Context => Ctx, Value => EL.Objects.To_Object (String '("Harold")));
Result := E.Get_Value (Ctx);
Ada.Text_IO.Put_Line ("User name is " & EL.Objects.To_String (Result));
Free (Joe);
Free (Bill);
end Variables;
|
-----------------------------------------------------------------------
-- servlet-servlets-mappers -- Read servlet configuration files
-- Copyright (C) 2011, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Beans.Objects.Vectors;
with EL.Contexts;
-- The <b>Servlet.Core.Mappers</b> package defines an XML mapper that can be used
-- to read the servlet configuration files.
--
-- The servlet configuration used by Servlet is a subset of the servlet deployment descriptor
-- defined in JSR 315 - Java Servlet Specification Version 3.0. It includes:
--
-- <ul>
-- <li>Definition of filter mapping (<b>filter-mapping</b> tag)</li>
-- <li>Definition of servlet mapping (<b>servlet-mapping</b> tag)</li>
-- <li>Definition of context parameters (<b>context-param</b> tag)</li>
-- <li>Definition of mime types (<b>mime-mapping</b> tag)</li>
-- <li>Definition of error pages (<b>error-page</b> tag)</li>
-- </ul>
--
-- Other configurations are ignored by the mapper.
--
-- Note: several JSR 315 configuration parameters do not makes sense in the Servlet world
-- because we cannot create a servlet or a filter through the configuration file.
package Servlet.Core.Mappers is
type Servlet_Fields is (FILTER_MAPPING, FILTER_NAME, SERVLET_NAME,
URL_PATTERN, SERVLET_MAPPING,
CONTEXT_PARAM, PARAM_NAME, PARAM_VALUE,
MIME_MAPPING, MIME_TYPE, EXTENSION,
ERROR_PAGE, ERROR_CODE, LOCATION);
-- ------------------------------
-- Servlet Config Reader
-- ------------------------------
-- When reading and parsing the servlet configuration file, the <b>Servlet_Config</b> object
-- is populated by calls through the <b>Set_Member</b> procedure. The data is
-- collected and when the end of an element (FILTER_MAPPING, SERVLET_MAPPING, CONTEXT_PARAM)
-- is reached, the definition is updated in the servlet registry.
type Servlet_Config is limited record
Filter_Name : Util.Beans.Objects.Object;
Servlet_Name : Util.Beans.Objects.Object;
URL_Patterns : Util.Beans.Objects.Vectors.Vector;
Param_Name : Util.Beans.Objects.Object;
Param_Value : Util.Beans.Objects.Object;
Mime_Type : Util.Beans.Objects.Object;
Extension : Util.Beans.Objects.Object;
Error_Code : Util.Beans.Objects.Object;
Location : Util.Beans.Objects.Object;
Handler : Servlet_Registry_Access;
Context : EL.Contexts.ELContext_Access;
Override_Context : Boolean := True;
end record;
type Servlet_Config_Access is access all Servlet_Config;
-- Save in the servlet config object the value associated with the given field.
-- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field
-- is reached, insert the new configuration rule in the servlet registry.
procedure Set_Member (N : in out Servlet_Config;
Field : in Servlet_Fields;
Value : in Util.Beans.Objects.Object);
-- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>,
-- <b>filter-mapping</b> and <b>servlet-mapping</b>.
generic
Mapper : in out Util.Serialize.Mappers.Processing;
Handler : in Servlet_Registry_Access;
Context : in EL.Contexts.ELContext_Access;
package Reader_Config is
Config : aliased Servlet_Config;
end Reader_Config;
private
package Servlet_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Servlet_Config,
Element_Type_Access => Servlet_Config_Access,
Fields => Servlet_Fields,
Set_Member => Set_Member);
end Servlet.Core.Mappers;
|
with mundo, Ada.Text_IO;
use mundo, Ada.Text_IO;
procedure mundo_aspiradora_main is
m : t_mundo;
c : Character;
begin
m.inicializar_mundo;
for i in 1 .. 20 loop
Put ("ITERACION ");
Put_Line (Integer'Image (i));
m.ejecutar_iteracion;
New_Line;
end loop;
Put_Line ("El programa ha finalizado.");
Get_Immediate (c);
end mundo_aspiradora_main;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUNTIME COMPONENTS --
-- --
-- A D A . S T R I N G S . S E A R C H --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992,1993,1994,1995,1996 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Note: This code is derived from the ADAR.CSH public domain Ada 83
-- versions of the Appendix C string handling packages (code extracted
-- from Ada.Strings.Fixed). A significant change is that we optimize the
-- case of identity mappings for Count and Index, and also Index_Non_Blank
-- is specialized (rather than using the general Index routine).
with Ada.Strings.Maps; use Ada.Strings.Maps;
package body Ada.Strings.Search is
-----------------------
-- Local Subprograms --
-----------------------
function Belongs
(Element : Character;
Set : Maps.Character_Set;
Test : Membership)
return Boolean;
pragma Inline (Belongs);
-- Determines if the given element is in (Test = Inside) or not in
-- (Test = Outside) the given character set.
-------------
-- Belongs --
-------------
function Belongs
(Element : Character;
Set : Maps.Character_Set;
Test : Membership)
return Boolean
is
begin
if Test = Inside then
return Is_In (Element, Set);
else
return not Is_In (Element, Set);
end if;
end Belongs;
-----------
-- Count --
-----------
function Count
(Source : in String;
Pattern : in String;
Mapping : in Maps.Character_Mapping := Maps.Identity)
return Natural
is
N : Natural;
J : Natural;
Mapped_Source : String (Source'Range);
begin
for J in Source'Range loop
Mapped_Source (J) := Value (Mapping, Source (J));
end loop;
if Pattern = "" then
raise Pattern_Error;
end if;
N := 0;
J := Source'First;
while J <= Source'Last - (Pattern'Length - 1) loop
if Mapped_Source (J .. J + (Pattern'Length - 1)) = Pattern then
N := N + 1;
J := J + Pattern'Length;
else
J := J + 1;
end if;
end loop;
return N;
end Count;
function Count
(Source : in String;
Pattern : in String;
Mapping : in Maps.Character_Mapping_Function)
return Natural
is
Mapped_Source : String (Source'Range);
N : Natural;
J : Natural;
begin
if Pattern = "" then
raise Pattern_Error;
end if;
-- We make sure Access_Check is unsuppressed so that the Mapping.all
-- call will generate a friendly Constraint_Error if the value for
-- Mapping is uninitialized (and hence null).
declare
pragma Unsuppress (Access_Check);
begin
for J in Source'Range loop
Mapped_Source (J) := Mapping.all (Source (J));
end loop;
end;
N := 0;
J := Source'First;
while J <= Source'Last - (Pattern'Length - 1) loop
if Mapped_Source (J .. J + (Pattern'Length - 1)) = Pattern then
N := N + 1;
J := J + Pattern'Length;
else
J := J + 1;
end if;
end loop;
return N;
end Count;
function Count
(Source : in String;
Set : in Maps.Character_Set)
return Natural
is
N : Natural := 0;
begin
for J in Source'Range loop
if Is_In (Source (J), Set) then
N := N + 1;
end if;
end loop;
return N;
end Count;
----------------
-- Find_Token --
----------------
procedure Find_Token
(Source : in String;
Set : in Maps.Character_Set;
Test : in Membership;
First : out Positive;
Last : out Natural)
is
begin
for J in Source'Range loop
if Belongs (Source (J), Set, Test) then
First := J;
for K in J + 1 .. Source'Last loop
if not Belongs (Source (K), Set, Test) then
Last := K - 1;
return;
end if;
end loop;
-- Here if J indexes 1st char of token, and all chars
-- after J are in the token
Last := Source'Last;
return;
end if;
end loop;
-- Here if no token found
First := Source'First;
Last := 0;
end Find_Token;
-----------
-- Index --
-----------
function Index
(Source : in String;
Pattern : in String;
Going : in Direction := Forward;
Mapping : in Maps.Character_Mapping := Maps.Identity)
return Natural
is
Cur_Index : Natural;
Mapped_Source : String (Source'Range);
begin
if Pattern = "" then
raise Pattern_Error;
end if;
for J in Source'Range loop
Mapped_Source (J) := Value (Mapping, Source (J));
end loop;
-- Forwards case
if Going = Forward then
for J in 1 .. Source'Length - Pattern'Length + 1 loop
Cur_Index := Source'First + J - 1;
if Pattern = Mapped_Source
(Cur_Index .. Cur_Index + Pattern'Length - 1)
then
return Cur_Index;
end if;
end loop;
-- Backwards case
else
for J in reverse 1 .. Source'Length - Pattern'Length + 1 loop
Cur_Index := Source'First + J - 1;
if Pattern = Mapped_Source
(Cur_Index .. Cur_Index + Pattern'Length - 1)
then
return Cur_Index;
end if;
end loop;
end if;
-- Fall through if no match found. Note that the loops are skipped
-- completely in the case of the pattern being longer than the source.
return 0;
end Index;
function Index (Source : in String;
Pattern : in String;
Going : in Direction := Forward;
Mapping : in Maps.Character_Mapping_Function)
return Natural
is
Mapped_Source : String (Source'Range);
Cur_Index : Natural;
begin
if Pattern = "" then
raise Pattern_Error;
end if;
-- We make sure Access_Check is unsuppressed so that the Mapping.all
-- call will generate a friendly Constraint_Error if the value for
-- Mapping is uninitialized (and hence null).
declare
pragma Unsuppress (Access_Check);
begin
for J in Source'Range loop
Mapped_Source (J) := Mapping.all (Source (J));
end loop;
end;
-- Forwards case
if Going = Forward then
for J in 1 .. Source'Length - Pattern'Length + 1 loop
Cur_Index := Source'First + J - 1;
if Pattern = Mapped_Source
(Cur_Index .. Cur_Index + Pattern'Length - 1)
then
return Cur_Index;
end if;
end loop;
-- Backwards case
else
for J in reverse 1 .. Source'Length - Pattern'Length + 1 loop
Cur_Index := Source'First + J - 1;
if Pattern = Mapped_Source
(Cur_Index .. Cur_Index + Pattern'Length - 1)
then
return Cur_Index;
end if;
end loop;
end if;
return 0;
end Index;
function Index
(Source : in String;
Set : in Maps.Character_Set;
Test : in Membership := Inside;
Going : in Direction := Forward)
return Natural
is
begin
-- Forwards case
if Going = Forward then
for J in Source'Range loop
if Belongs (Source (J), Set, Test) then
return J;
end if;
end loop;
-- Backwards case
else
for J in reverse Source'Range loop
if Belongs (Source (J), Set, Test) then
return J;
end if;
end loop;
end if;
-- Fall through if no match
return 0;
end Index;
---------------------
-- Index_Non_Blank --
---------------------
function Index_Non_Blank
(Source : in String;
Going : in Direction := Forward)
return Natural
is
begin
if Going = Forward then
for J in Source'Range loop
if Source (J) /= ' ' then
return J;
end if;
end loop;
else -- Going = Backward
for J in reverse Source'Range loop
if Source (J) /= ' ' then
return J;
end if;
end loop;
end if;
-- Fall through if no match
return 0;
end Index_Non_Blank;
end Ada.Strings.Search;
|
package TLSF.Proof.Test.Util with SPARK_Mode is
procedure Test_Util;
end TLSF.Proof.Test.Util;
|
with Ada.Numerics;
with Math_2D.Types;
generic
with package Types is new Math_2D.Types (<>);
package Math_2D.Trigonometry is
use type Types.Real_Type'Base;
type Degrees_t is new Types.Real_Type'Base range 0.0 .. 360.0;
type Radians_t is new Types.Real_Type'Base range 0.0 .. 360.0 * (Ada.Numerics.Pi / 180.0);
function To_Radians (Degrees : in Degrees_t) return Radians_t;
pragma Inline (To_Radians);
function To_Degrees (Radians : in Radians_t) return Degrees_t;
pragma Inline (To_Degrees);
end Math_2D.Trigonometry;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2012 Felix Krause <contact@flyx.org>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Unchecked_Conversion;
with System;
with GL.API;
with GL.Enums.Getter;
with GL.Pixels;
package body GL.Objects.Buffers is
function Minimum_Alignment return Types.Size is
Ret : Types.Size := 64;
begin
API.Get_Size.Ref (Enums.Getter.Min_Map_Buffer_Alignment, Ret);
return Ret;
end Minimum_Alignment;
use type Enums.Buffer_Kind;
type Format_Data is record
Internal_Format : GL.Pixels.Internal_Format_Buffer_Texture;
Format : GL.Pixels.Format;
Data_Type : GL.Pixels.Data_Type;
end record;
function Get_Format_Data (Kind : Numeric_Type; Length : Natural) return Format_Data is
use GL.Pixels;
type Format_Array is array (1 .. 4) of Format;
Float_Formats : constant Format_Array := (Red, RG, RGB, RGBA);
Integer_Formats : constant Format_Array :=
(Red_Integer, RG_Integer, RGB_Integer, RGBA_Integer);
type Internal_Format_Array is array (1 .. 4) of Internal_Format_Buffer_Texture;
Internal_Formats : Internal_Format_Array;
begin
return Result : Format_Data do
-- For certain data types, OpenGL does not provide a sized
-- internal format [for buffer textures] that has three components
case Kind is
when Byte_Type =>
Result.Data_Type := Pixels.Byte;
Internal_Formats := (R8I, RG8I, R8I, RGBA8I);
-- Third position invalid
when UByte_Type =>
Result.Data_Type := Pixels.Unsigned_Byte;
Internal_Formats := (R8UI, RG8UI, R8UI, RGBA8UI);
-- Third position invalid
when Short_Type =>
Result.Data_Type := Pixels.Short;
Internal_Formats := (R16I, RG16I, R16I, RGBA16I);
-- Third position invalid
when UShort_Type =>
Result.Data_Type := Pixels.Unsigned_Short;
Internal_Formats := (R16UI, RG16UI, R16UI, RGBA16UI);
-- Third position invalid
when Int_Type =>
Result.Data_Type := Pixels.Int;
Internal_Formats := (R32I, RG32I, RGB32I, RGBA32I);
when UInt_Type =>
Result.Data_Type := Pixels.Unsigned_Int;
Internal_Formats := (R32UI, RG32UI, RGB32UI, RGBA32UI);
when Half_Type =>
Result.Data_Type := Pixels.Half_Float;
Internal_Formats := (R16F, RG16F, R16F, RGBA16F);
-- Third position invalid
when Single_Type =>
Result.Data_Type := Pixels.Float;
Internal_Formats := (R32F, RG32F, RGB32F, RGBA32F);
when Double_Type =>
raise Constraint_Error;
end case;
Result.Internal_Format := Internal_Formats (Length);
case Kind is
when Byte_Type .. UInt_Type =>
Result.Format := Integer_Formats (Length);
when Half_Type | Single_Type =>
Result.Format := Float_Formats (Length);
when Double_Type =>
raise Constraint_Error;
end case;
end return;
end Get_Format_Data;
function Kind (Target : Buffer_Target) return Indexed_Buffer_Target is
(case Target.Kind is
when Enums.Shader_Storage_Buffer => Shader_Storage,
when Enums.Uniform_Buffer => Uniform,
when Enums.Atomic_Counter_Buffer => Atomic_Counter,
when others => raise Constraint_Error);
procedure Bind (Target : Buffer_Target; Object : Buffer'Class) is
begin
API.Bind_Buffer.Ref (Target.Kind, Object.Reference.GL_Id);
end Bind;
procedure Bind_Base (Target : Buffer_Target; Object : Buffer'Class; Index : Natural) is
begin
API.Bind_Buffer_Base.Ref (Target.Kind, UInt (Index), Object.Reference.GL_Id);
end Bind_Base;
procedure Allocate_Storage
(Object : in out Buffer;
Length : Long;
Kind : Numeric_Type;
Flags : Storage_Bits)
is
use type Low_Level.Bitfield;
function Convert is new Ada.Unchecked_Conversion
(Source => Storage_Bits, Target => Low_Level.Bitfield);
Raw_Bits : constant Low_Level.Bitfield :=
Convert (Flags) and 2#0000001111000011#;
Number_Of_Bytes : Long;
begin
case Kind is
when Half_Type =>
Number_Of_Bytes := Length * Half'Size / System.Storage_Unit;
when Single_Type =>
Number_Of_Bytes := Length * Single'Size / System.Storage_Unit;
when Double_Type =>
Number_Of_Bytes := Length * Double'Size / System.Storage_Unit;
when UInt_Type =>
Number_Of_Bytes := Length * UInt'Size / System.Storage_Unit;
when UByte_Type =>
Number_Of_Bytes := Length * UByte'Size / System.Storage_Unit;
when UShort_Type =>
Number_Of_Bytes := Length * UShort'Size / System.Storage_Unit;
when Int_Type =>
Number_Of_Bytes := Length * Int'Size / System.Storage_Unit;
when Byte_Type =>
Number_Of_Bytes := Length * Byte'Size / System.Storage_Unit;
when Short_Type =>
Number_Of_Bytes := Length * Short'Size / System.Storage_Unit;
end case;
API.Named_Buffer_Storage.Ref
(Object.Reference.GL_Id, Low_Level.SizeIPtr (Number_Of_Bytes),
System.Null_Address, Raw_Bits);
Object.Allocated := True;
end Allocate_Storage;
function Allocated (Object : Buffer) return Boolean is (Object.Allocated);
function Mapped (Object : Buffer) return Boolean is (Object.Mapped);
overriding procedure Initialize_Id (Object : in out Buffer) is
New_Id : UInt := 0;
begin
API.Create_Buffers.Ref (1, New_Id);
Object.Reference.GL_Id := New_Id;
end Initialize_Id;
overriding procedure Delete_Id (Object : in out Buffer) is
Arr : constant Low_Level.UInt_Array := (1 => Object.Reference.GL_Id);
begin
API.Delete_Buffers.Ref (1, Arr);
Object.Reference.GL_Id := 0;
end Delete_Id;
procedure Unmap (Object : in out Buffer) is
begin
API.Unmap_Named_Buffer.Ref (Object.Reference.GL_Id);
Object.Mapped := False;
end Unmap;
procedure Invalidate_Data (Object : in out Buffer) is
begin
API.Invalidate_Buffer_Data.Ref (Object.Reference.GL_Id);
end Invalidate_Data;
package body Buffer_Pointers is
package Map_Named_Buffer_Range is new API.Loader.Function_With_4_Params
("glMapNamedBufferRange", UInt, Low_Level.IntPtr, Low_Level.SizeIPtr,
Low_Level.Bitfield, Pointers.Pointer);
package Get_Named_Buffer_Sub_Data is new API.Loader.Getter_With_4_Params
("glGetNamedBufferSubData", UInt, Low_Level.IntPtr,
Low_Level.SizeIPtr, Pointers.Element_Array);
Element_In_Bytes : constant Int := Pointers.Element'Size / System.Storage_Unit;
procedure Bind_Range
(Target : Buffer_Target;
Object : Buffer'Class;
Index : Natural;
Offset, Length : Types.Size)
is
Offset_In_Bytes : constant Int := Offset * Element_In_Bytes;
Number_Of_Bytes : constant Int := Length * Element_In_Bytes;
begin
API.Bind_Buffer_Range.Ref
(Target.Kind, UInt (Index), Object.Reference.GL_Id,
Low_Level.IntPtr (Offset_In_Bytes),
Low_Level.SizeIPtr (Number_Of_Bytes));
end Bind_Range;
procedure Allocate_And_Load_From_Data
(Object : in out Buffer;
Data : Pointers.Element_Array;
Flags : Storage_Bits)
is
use type Low_Level.Bitfield;
function Convert is new Ada.Unchecked_Conversion
(Source => Storage_Bits, Target => Low_Level.Bitfield);
Raw_Bits : constant Low_Level.Bitfield :=
Convert (Flags) and 2#0000001111000011#;
Number_Of_Bytes : constant Int := Data'Length * Element_In_Bytes;
begin
API.Named_Buffer_Storage.Ref
(Object.Reference.GL_Id, Low_Level.SizeIPtr (Number_Of_Bytes),
Data (Data'First)'Address, Raw_Bits);
Object.Allocated := True;
end Allocate_And_Load_From_Data;
procedure Map_Range
(Object : in out Buffer;
Flags : Access_Bits;
Offset, Length : Types.Size;
Pointer : out Pointers.Pointer)
is
use type Low_Level.Bitfield;
use type Pointers.Pointer;
function Convert is new Ada.Unchecked_Conversion
(Source => Access_Bits, Target => Low_Level.Bitfield);
Raw_Bits : constant Low_Level.Bitfield :=
Convert (Flags) and 2#0000000011111111#;
Offset_In_Bytes : constant Int := Offset * Element_In_Bytes;
Number_Of_Bytes : constant Int := Length * Element_In_Bytes;
begin
Pointer := Map_Named_Buffer_Range.Ref
(Object.Reference.GL_Id,
Low_Level.IntPtr (Offset_In_Bytes),
Low_Level.SizeIPtr (Number_Of_Bytes),
Raw_Bits);
Object.Mapped := Pointer /= null;
end Map_Range;
function Get_Mapped_Data
(Pointer : not null Pointers.Pointer;
Offset, Length : Types.Size) return Pointers.Element_Array
is
package IC renames Interfaces.C;
use type Pointers.Pointer;
begin
return Pointers.Value (Pointer + IC.ptrdiff_t (Offset), IC.ptrdiff_t (Length));
end Get_Mapped_Data;
procedure Set_Mapped_Data
(Pointer : not null Pointers.Pointer;
Offset : Types.Size;
Data : Pointers.Element_Array)
is
package IC renames Interfaces.C;
use type Pointers.Pointer;
subtype Data_Array is Pointers.Element_Array (Data'Range);
type Data_Access is access Data_Array;
function Convert is new Ada.Unchecked_Conversion
(Source => Pointers.Pointer, Target => Data_Access);
begin
Convert (Pointer + IC.ptrdiff_t (Offset)).all := Data;
end Set_Mapped_Data;
procedure Set_Mapped_Data
(Pointer : not null Pointers.Pointer;
Offset : Types.Size;
Value : Pointers.Element)
is
package IC renames Interfaces.C;
use type Pointers.Pointer;
Offset_Pointer : constant Pointers.Pointer := Pointer + IC.ptrdiff_t (Offset);
begin
Offset_Pointer.all := Value;
end Set_Mapped_Data;
procedure Flush_Buffer_Range (Object : in out Buffer;
Offset, Length : Types.Size)
is
Offset_In_Bytes : constant Int := Offset * Element_In_Bytes;
Number_Of_Bytes : constant Int := Length * Element_In_Bytes;
begin
API.Flush_Mapped_Named_Buffer_Range.Ref
(Object.Reference.GL_Id,
Low_Level.IntPtr (Offset_In_Bytes),
Low_Level.SizeIPtr (Number_Of_Bytes));
end Flush_Buffer_Range;
procedure Clear_Sub_Data
(Object : Buffer;
Kind : Numeric_Type;
Offset, Length : Types.Size;
Data : in out Pointers.Element_Array)
is
Offset_In_Bytes : constant Int := Offset * Element_In_Bytes;
Length_In_Bytes : constant Int := Length * Element_In_Bytes;
Format_Info : constant Format_Data :=
Get_Format_Data (Kind, Natural'Max (1, Data'Length));
begin
API.Clear_Named_Buffer_Sub_Data.Ref
(Object.Reference.GL_Id, Format_Info.Internal_Format,
Low_Level.IntPtr (Offset_In_Bytes), Low_Level.SizeIPtr (Length_In_Bytes),
Format_Info.Format, Format_Info.Data_Type,
(if Data'Length = 0 then System.Null_Address else Data (Data'First)'Address));
end Clear_Sub_Data;
procedure Copy_Sub_Data
(Object, Target_Object : Buffer;
Read_Offset, Write_Offset, Length : Types.Size)
is
Read_Offset_In_Bytes : constant Int := Read_Offset * Element_In_Bytes;
Write_Offset_In_Bytes : constant Int := Write_Offset * Element_In_Bytes;
Number_Of_Bytes : constant Int := Length * Element_In_Bytes;
begin
API.Copy_Named_Buffer_Sub_Data.Ref
(Object.Reference.GL_Id, Target_Object.Reference.GL_Id,
Low_Level.IntPtr (Read_Offset_In_Bytes),
Low_Level.IntPtr (Write_Offset_In_Bytes),
Low_Level.SizeIPtr (Number_Of_Bytes));
end Copy_Sub_Data;
procedure Set_Sub_Data (Object : Buffer;
Offset : Types.Size;
Data : Pointers.Element_Array)
is
Offset_In_Bytes : constant Int := Offset * Element_In_Bytes;
Number_Of_Bytes : constant Int := Data'Length * Element_In_Bytes;
begin
API.Named_Buffer_Sub_Data.Ref
(Object.Reference.GL_Id,
Low_Level.IntPtr (Offset_In_Bytes), Low_Level.SizeIPtr (Number_Of_Bytes),
Data (Data'First)'Address);
end Set_Sub_Data;
procedure Get_Sub_Data (Object : Buffer;
Offset : Types.Size;
Data : out Pointers.Element_Array)
is
Offset_In_Bytes : constant Int := Offset * Element_In_Bytes;
Number_Of_Bytes : constant Int := Data'Length * Element_In_Bytes;
begin
Get_Named_Buffer_Sub_Data.Ref
(Object.Reference.GL_Id,
Low_Level.IntPtr (Offset_In_Bytes),
Low_Level.SizeIPtr (Number_Of_Bytes),
Data);
end Get_Sub_Data;
procedure Invalidate_Sub_Data (Object : Buffer;
Offset, Length : Types.Size)
is
Offset_In_Bytes : constant Int := Offset * Element_In_Bytes;
Number_Of_Bytes : constant Int := Length * Element_In_Bytes;
begin
API.Invalidate_Buffer_Sub_Data.Ref
(Object.Reference.GL_Id,
Low_Level.IntPtr (Offset_In_Bytes),
Low_Level.SizeIPtr (Number_Of_Bytes));
end Invalidate_Sub_Data;
end Buffer_Pointers;
end GL.Objects.Buffers;
|
pragma Style_Checks (Off);
-- This spec has been automatically generated from STM32G474xx.svd
pragma Restrictions (No_Elaboration_Code);
with HAL;
with System;
package STM32_SVD.NVIC is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- IPR_IPR_N array element
subtype IPR_IPR_N_Element is HAL.UInt8;
-- IPR_IPR_N array
type IPR_IPR_N_Field_Array is array (0 .. 3) of IPR_IPR_N_Element
with Component_Size => 8, Size => 32;
-- Interrupt Priority Register
type IPR_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- IPR_N as a value
Val : HAL.UInt32;
when True =>
-- IPR_N as an array
Arr : IPR_IPR_N_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for IPR_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
subtype STIR_INTID_Field is HAL.UInt9;
-- Software trigger interrupt register
type STIR_Register is record
-- Software generated interrupt ID
INTID : STIR_INTID_Field := 16#0#;
-- unspecified
Reserved_9_31 : HAL.UInt23 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for STIR_Register use record
INTID at 0 range 0 .. 8;
Reserved_9_31 at 0 range 9 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Nested Vectored Interrupt Controller
type NVIC_Peripheral is record
-- Interrupt Set-Enable Register
ISER0 : aliased HAL.UInt32;
-- Interrupt Set-Enable Register
ISER1 : aliased HAL.UInt32;
-- Interrupt Set-Enable Register
ISER2 : aliased HAL.UInt32;
-- Interrupt Set-Enable Register
ISER3 : aliased HAL.UInt32;
-- Interrupt Clear-Enable Register
ICER0 : aliased HAL.UInt32;
-- Interrupt Clear-Enable Register
ICER1 : aliased HAL.UInt32;
-- Interrupt Clear-Enable Register
ICER2 : aliased HAL.UInt32;
-- Interrupt Clear-Enable Register
ICER3 : aliased HAL.UInt32;
-- Interrupt Set-Pending Register
ISPR0 : aliased HAL.UInt32;
-- Interrupt Set-Pending Register
ISPR1 : aliased HAL.UInt32;
-- Interrupt Set-Pending Register
ISPR2 : aliased HAL.UInt32;
-- Interrupt Set-Pending Register
ISPR3 : aliased HAL.UInt32;
-- Interrupt Clear-Pending Register
ICPR0 : aliased HAL.UInt32;
-- Interrupt Clear-Pending Register
ICPR1 : aliased HAL.UInt32;
-- Interrupt Clear-Pending Register
ICPR2 : aliased HAL.UInt32;
-- Interrupt Clear-Pending Register
ICPR3 : aliased HAL.UInt32;
-- Interrupt Active Bit Register
IABR0 : aliased HAL.UInt32;
-- Interrupt Active Bit Register
IABR1 : aliased HAL.UInt32;
-- Interrupt Active Bit Register
IABR2 : aliased HAL.UInt32;
-- Interrupt Active Bit Register
IABR3 : aliased HAL.UInt32;
-- Interrupt Priority Register
IPR0 : aliased IPR_Register;
-- Interrupt Priority Register
IPR1 : aliased IPR_Register;
-- Interrupt Priority Register
IPR2 : aliased IPR_Register;
-- Interrupt Priority Register
IPR3 : aliased IPR_Register;
-- Interrupt Priority Register
IPR4 : aliased IPR_Register;
-- Interrupt Priority Register
IPR5 : aliased IPR_Register;
-- Interrupt Priority Register
IPR6 : aliased IPR_Register;
-- Interrupt Priority Register
IPR7 : aliased IPR_Register;
-- Interrupt Priority Register
IPR8 : aliased IPR_Register;
-- Interrupt Priority Register
IPR9 : aliased IPR_Register;
-- Interrupt Priority Register
IPR10 : aliased IPR_Register;
-- Interrupt Priority Register
IPR11 : aliased IPR_Register;
-- Interrupt Priority Register
IPR12 : aliased IPR_Register;
-- Interrupt Priority Register
IPR13 : aliased IPR_Register;
-- Interrupt Priority Register
IPR14 : aliased IPR_Register;
-- Interrupt Priority Register
IPR15 : aliased IPR_Register;
-- Interrupt Priority Register
IPR16 : aliased IPR_Register;
-- Interrupt Priority Register
IPR17 : aliased IPR_Register;
-- Interrupt Priority Register
IPR18 : aliased IPR_Register;
-- Interrupt Priority Register
IPR19 : aliased IPR_Register;
-- Interrupt Priority Register
IPR20 : aliased IPR_Register;
-- Interrupt Priority Register
IPR21 : aliased HAL.UInt32;
-- Interrupt Priority Register
IPR22 : aliased HAL.UInt32;
-- Interrupt Priority Register
IPR23 : aliased HAL.UInt32;
-- Interrupt Priority Register
IPR24 : aliased HAL.UInt32;
-- Interrupt Priority Register
IPR25 : aliased HAL.UInt32;
end record
with Volatile;
for NVIC_Peripheral use record
ISER0 at 16#0# range 0 .. 31;
ISER1 at 16#4# range 0 .. 31;
ISER2 at 16#8# range 0 .. 31;
ISER3 at 16#C# range 0 .. 31;
ICER0 at 16#80# range 0 .. 31;
ICER1 at 16#84# range 0 .. 31;
ICER2 at 16#88# range 0 .. 31;
ICER3 at 16#8C# range 0 .. 31;
ISPR0 at 16#100# range 0 .. 31;
ISPR1 at 16#104# range 0 .. 31;
ISPR2 at 16#108# range 0 .. 31;
ISPR3 at 16#10C# range 0 .. 31;
ICPR0 at 16#180# range 0 .. 31;
ICPR1 at 16#184# range 0 .. 31;
ICPR2 at 16#188# range 0 .. 31;
ICPR3 at 16#18C# range 0 .. 31;
IABR0 at 16#200# range 0 .. 31;
IABR1 at 16#204# range 0 .. 31;
IABR2 at 16#208# range 0 .. 31;
IABR3 at 16#20C# range 0 .. 31;
IPR0 at 16#300# range 0 .. 31;
IPR1 at 16#304# range 0 .. 31;
IPR2 at 16#308# range 0 .. 31;
IPR3 at 16#30C# range 0 .. 31;
IPR4 at 16#310# range 0 .. 31;
IPR5 at 16#314# range 0 .. 31;
IPR6 at 16#318# range 0 .. 31;
IPR7 at 16#31C# range 0 .. 31;
IPR8 at 16#320# range 0 .. 31;
IPR9 at 16#324# range 0 .. 31;
IPR10 at 16#328# range 0 .. 31;
IPR11 at 16#32C# range 0 .. 31;
IPR12 at 16#330# range 0 .. 31;
IPR13 at 16#334# range 0 .. 31;
IPR14 at 16#338# range 0 .. 31;
IPR15 at 16#33C# range 0 .. 31;
IPR16 at 16#340# range 0 .. 31;
IPR17 at 16#344# range 0 .. 31;
IPR18 at 16#348# range 0 .. 31;
IPR19 at 16#34C# range 0 .. 31;
IPR20 at 16#350# range 0 .. 31;
IPR21 at 16#354# range 0 .. 31;
IPR22 at 16#358# range 0 .. 31;
IPR23 at 16#35C# range 0 .. 31;
IPR24 at 16#360# range 0 .. 31;
IPR25 at 16#364# range 0 .. 31;
end record;
-- Nested Vectored Interrupt Controller
NVIC_Periph : aliased NVIC_Peripheral
with Import, Address => NVIC_Base;
-- Nested vectored interrupt controller
type NVIC_STIR_Peripheral is record
-- Software trigger interrupt register
STIR : aliased STIR_Register;
end record
with Volatile;
for NVIC_STIR_Peripheral use record
STIR at 0 range 0 .. 31;
end record;
-- Nested vectored interrupt controller
NVIC_STIR_Periph : aliased NVIC_STIR_Peripheral
with Import, Address => NVIC_STIR_Base;
end STM32_SVD.NVIC;
|
------------------------------------------------------------------------------
-- --
-- Ada User Repository Annex (AURA) --
-- ANNEXI-STRAYLINE Reference Implementation --
-- --
-- Command Line Interface --
-- --
-- ------------------------------------------------------------------------ --
-- --
-- Copyright (C) 2020, ANNEXI-STRAYLINE Trans-Human Ltd. --
-- All rights reserved. --
-- --
-- Original Contributors: --
-- * Richard Wai (ANNEXI-STRAYLINE) --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- --
-- * Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A --
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Ada.Assertions;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Unit_Names.Sets;
with Workers.Reporting;
separate (Validation)
package body VSD_Orders is
package UBS renames Ada.Strings.Unbounded;
New_Line: Character renames Workers.Reporting.New_Line;
-----------
-- Image --
-----------
function Image (Order: Validate_Subsystem_Dependencies_Order)
return String
is
Image_String: Bounded_String := UBS.To_Unbounded_String
( "[Validate_Subsystem_Dependencies_Order] (Validation)" & New_Line
& "Subsystems to be checked:");
procedure Append (Source : in out UBS.Unbounded_String := Image_String;
New_Item: in String)
renames UBS.Append;
begin
for SS of Order.Check_Subset loop
Append (New_Line & "- " & SS.Name.To_UTF8_String);
end loop;
return UBS.To_String (Image_String);
end Image;
-------------
-- Execute --
-------------
procedure Execute (Order: in out Validate_Subsystem_Dependencies_Order) is
use Repositories;
use Registrar.Subsystems;
Dependencies: constant Subsystem_Sets.Set
:= Registrar.Queries.Subsystem_Dependencies (Order.Target);
Failed_Set: Subsystem_Sets.Set;
procedure Fail is
Fail_Message: UBS.Bounded_String := UBS.To_Unbounded_String
( "Subsystem """ & Order.Target.Name.To_UTF8_String & """ "
& " was checked out from a " & New_Line
& " System Repository (Repository"
& Repository_Index'Image (Order.Target.Source_Repository)
& "). Subsystems checked-out from System Repositories"
& New_Line
& "must only depend on other subsystems from the same repository."
& New_Line
& "The offending dependencies, and their repository index, "
& "are as follows: ");
procedure Append (Source : in out UBS.Unbounded_String := Fail_Message;
New_Item: in String)
renames UBS.Append;
function Trim (Souce: in Sting;
Side : in Ada.Strings.Trim_End := Ada.Strings.Both)
return String
renames Ada.Strings.Fixed.Trim;
begin
for SS of Failed_Set loop
Append (SS.Name.To_UTF8_String
& " ("
& Trim (Repository_Index'Image (SS.Source_Repository))
& ')' & New_Line);
end loop;
raise Ada.Assertions.Assertion_Error with
UBS.To_String (Fail_Message);
end Fail;
begin
for SS of Dependencies loop
if SS.Source_Repository /= Order.Target.Source_Repository then
Failed_Set.Insert (SS);
end if;
end loop;
if not Failed_Set.Is_Empty then Fail; end if;
end Execute;
end VSD_Orders;
|
pragma License (Unrestricted);
-- extended unit
private with System.Native_Text_IO;
package Ada.Text_IO.Terminal is
-- Additional terminal handling subprograms.
function Is_Terminal (
File : File_Type) -- Open_File_Type
return Boolean;
pragma Inline (Is_Terminal);
-- size of screen buffer and view port
type Size_Type is record
Line_Length : Count;
Page_Length : Count;
end record;
pragma Suppress_Initialization (Size_Type);
procedure Set_Size (
File : File_Type; -- Output_File_Type
Size : Size_Type);
procedure Set_Size (
File : File_Type; -- Output_File_Type
Line_Length, Page_Length : Count);
function Size (
File : File_Type) -- Output_File_Type
return Size_Type;
procedure Size (
File : File_Type; -- Output_File_Type
Line_Length, Page_Length : out Count);
type View_Type is record
Left : Positive_Count;
Top : Positive_Count;
Right : Count;
Bottom : Count;
end record;
pragma Suppress_Initialization (View_Type);
function View (
File : File_Type) -- Output_File_Type
return View_Type;
procedure View (
File : File_Type; -- Output_File_Type
Left, Top : out Positive_Count;
Right, Bottom : out Count);
-- cursor position
type Position_Type is record
Col : Positive_Count;
Line : Positive_Count;
end record;
pragma Suppress_Initialization (Position_Type);
procedure Set_Position (
File : File_Type; -- Output_File_Type
Position : Position_Type);
procedure Set_Position (
File : File_Type; -- Output_File_Type
Col, Line : Positive_Count);
procedure Set_Col (
File : File_Type; -- Output_File_Type
To : Positive_Count);
function Position (
File : File_Type) -- Output_File_Type
return Position_Type;
procedure Position (
File : File_Type; -- Output_File_Type
Col, Line : out Positive_Count);
-- save and reset current position and colors
type Output_State is private;
procedure Save_State (
File : File_Type; -- Output_File_Type
To_State : out Output_State);
procedure Reset_State (
File : File_Type; -- Output_File_Type
From_State : Output_State);
private
type Output_State is new System.Native_Text_IO.Output_State;
end Ada.Text_IO.Terminal;
|
-----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017, 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with ASF.Applications;
with ADO;
with Wiki.Strings;
with AWA.Events;
with AWA.Modules;
with AWA.Blogs.Models;
with AWA.Counters.Definition;
with AWA.Blogs.Servlets;
with Security.Permissions;
-- == Integration ==
-- To be able to use the `Blogs` module, you will need to add the following line in your
-- GNAT project file:
--
-- with "awa_blogs";
--
-- The `Blog_Module` type manages the creation, update, removal of blog posts in an application.
-- It provides operations that are used by the blog beans or other services to create and update
-- posts. An instance of the `Blog_Module` must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- with AWA.Blogs.Modules;
-- ...
-- type Application is new AWA.Applications.Application with record
-- Blog_Module : aliased AWA.Blogs.Modules.Blog_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Blogs.Modules.NAME,
-- URI => "blogs",
-- Module => App.Blog_Module'Access);
--
package AWA.Blogs.Modules is
NAME : constant String := "blogs";
-- The configuration parameter that defines the image link prefix in rendered HTML content.
PARAM_IMAGE_PREFIX : constant String := "image_prefix";
-- Define the permissions.
package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create");
package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete");
package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post");
package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post");
package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post");
-- Definition the events.
package Post_Publish_Event is new AWA.Events.Definition (Name => "blog-post-publish");
-- Define the read post counter.
package Read_Counter is new AWA.Counters.Definition (Models.POST_TABLE, "read_count");
Not_Found : exception;
type Blog_Module is new AWA.Modules.Module with private;
type Blog_Module_Access is access all Blog_Module'Class;
-- Initialize the blog module.
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config);
-- Get the blog module instance associated with the current application.
function Get_Blog_Module return Blog_Module_Access;
-- Get the image prefix that was configured for the Blog module.
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString;
-- Create a new blog for the user workspace.
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier);
-- Create a new post associated with the given blog identifier.
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Summary : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier);
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
Summary : in String;
URI : in String;
Text : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Publish_Date : in ADO.Nullable_Time;
Status : in AWA.Blogs.Models.Post_Status_Type);
-- Delete the post identified by the given identifier.
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier);
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
private
type Blog_Module is new AWA.Modules.Module with record
Image_Prefix : Wiki.Strings.UString;
Image_Servlet : aliased AWA.Blogs.Servlets.Image_Servlet;
end record;
end AWA.Blogs.Modules;
|
-- This package has been generated automatically by GNATtest.
-- You are allowed to add your code to the bodies of test routines.
-- Such changes will be kept during further regeneration of this file.
-- All code placed outside of test routine bodies will be lost. The
-- code intended to set up and tear down the test environment should be
-- placed into Tk.Menu.Menu_Options_Test_Data.
with AUnit.Assertions; use AUnit.Assertions;
with System.Assertions;
-- begin read only
-- id:2.2/00/
--
-- This section can be used to add with clauses if necessary.
--
-- end read only
with Ada.Environment_Variables; use Ada.Environment_Variables;
-- begin read only
-- end read only
package body Tk.Menu.Menu_Options_Test_Data.Menu_Options_Tests is
-- begin read only
-- id:2.2/01/
--
-- This section can be used to add global variables and other elements.
--
-- end read only
-- begin read only
-- end read only
-- begin read only
function Wrap_Test_Create_32e405_e2d532
(Path_Name: Tk_Path_String; Options: Menu_Options;
Interpreter: Tcl_Interpreter := Get_Interpreter) return Tk_Menu is
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(tk-menu.ads:0):Test_Create_Menu1 test requirement violated");
end;
declare
Test_Create_32e405_e2d532_Result: constant Tk_Menu :=
GNATtest_Generated.GNATtest_Standard.Tk.Menu.Create
(Path_Name, Options, Interpreter);
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(tk-menu.ads:0:):Test_Create_Menu1 test commitment violated");
end;
return Test_Create_32e405_e2d532_Result;
end;
end Wrap_Test_Create_32e405_e2d532;
-- end read only
-- begin read only
procedure Test_1_Create_test_create_menu1
(Gnattest_T: in out Test_Menu_Options);
procedure Test_Create_32e405_e2d532
(Gnattest_T: in out Test_Menu_Options) renames
Test_1_Create_test_create_menu1;
-- id:2.2/32e405543423d7b8/Create/1/0/test_create_menu1/
procedure Test_1_Create_test_create_menu1
(Gnattest_T: in out Test_Menu_Options) is
function Create
(Path_Name: Tk_Path_String; Options: Menu_Options;
Interpreter: Tcl_Interpreter := Get_Interpreter)
return Tk_Menu renames
Wrap_Test_Create_32e405_e2d532;
-- end read only
pragma Unreferenced(Gnattest_T);
Menu: Tk_Menu;
begin
if Value("DISPLAY", "")'Length = 0 then
Assert(True, "No display, can't test");
return;
end if;
Menu := Create(".mymenu", Menu_Options'(others => <>));
Assert(Menu /= Null_Widget, "Failed to create (function) a new menu.");
Destroy(Menu);
-- begin read only
end Test_1_Create_test_create_menu1;
-- end read only
-- begin read only
procedure Wrap_Test_Create_ebbdc1_7e498b
(Menu_Widget: out Tk_Menu; Path_Name: Tk_Path_String;
Options: Menu_Options;
Interpreter: Tcl_Interpreter := Get_Interpreter) is
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(tk-menu.ads:0):Test_Create_Menu2 test requirement violated");
end;
GNATtest_Generated.GNATtest_Standard.Tk.Menu.Create
(Menu_Widget, Path_Name, Options, Interpreter);
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(tk-menu.ads:0:):Test_Create_Menu2 test commitment violated");
end;
end Wrap_Test_Create_ebbdc1_7e498b;
-- end read only
-- begin read only
procedure Test_2_Create_test_create_menu2
(Gnattest_T: in out Test_Menu_Options);
procedure Test_Create_ebbdc1_7e498b
(Gnattest_T: in out Test_Menu_Options) renames
Test_2_Create_test_create_menu2;
-- id:2.2/ebbdc1934f0fa33d/Create/0/0/test_create_menu2/
procedure Test_2_Create_test_create_menu2
(Gnattest_T: in out Test_Menu_Options) is
procedure Create
(Menu_Widget: out Tk_Menu; Path_Name: Tk_Path_String;
Options: Menu_Options;
Interpreter: Tcl_Interpreter := Get_Interpreter) renames
Wrap_Test_Create_ebbdc1_7e498b;
-- end read only
pragma Unreferenced(Gnattest_T);
Menu: Tk_Menu;
begin
if Value("DISPLAY", "")'Length = 0 then
Assert(True, "No display, can't test");
return;
end if;
Create(Menu, ".mymenu", Menu_Options'(others => <>));
Assert(Menu /= Null_Widget, "Failed to create (procedure) a new menu.");
Destroy(Menu);
-- begin read only
end Test_2_Create_test_create_menu2;
-- end read only
-- begin read only
function Wrap_Test_Get_Options_ded36e_7f3252
(Menu_Widget: Tk_Menu) return Menu_Options is
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(tk-menu.ads:0):Test_Get_Options_Menu test requirement violated");
end;
declare
Test_Get_Options_ded36e_7f3252_Result: constant Menu_Options :=
GNATtest_Generated.GNATtest_Standard.Tk.Menu.Get_Options
(Menu_Widget);
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(tk-menu.ads:0:):Test_Get_Options_Menu test commitment violated");
end;
return Test_Get_Options_ded36e_7f3252_Result;
end;
end Wrap_Test_Get_Options_ded36e_7f3252;
-- end read only
-- begin read only
procedure Test_Get_Options_test_get_options_menu
(Gnattest_T: in out Test_Menu_Options);
procedure Test_Get_Options_ded36e_7f3252
(Gnattest_T: in out Test_Menu_Options) renames
Test_Get_Options_test_get_options_menu;
-- id:2.2/ded36e34d54c20f9/Get_Options/1/0/test_get_options_menu/
procedure Test_Get_Options_test_get_options_menu
(Gnattest_T: in out Test_Menu_Options) is
function Get_Options(Menu_Widget: Tk_Menu) return Menu_Options renames
Wrap_Test_Get_Options_ded36e_7f3252;
-- end read only
pragma Unreferenced(Gnattest_T);
Menu: Tk_Menu;
Options: Menu_Options;
begin
if Value("DISPLAY", "")'Length = 0 then
Assert(True, "No display, can't test");
return;
end if;
Create(Menu, ".mymenu", Menu_Options'(Tear_Off => FALSE, others => <>));
Options := Get_Options(Menu);
Assert(Options.Tear_Off = FALSE, "Failed to get options of a menu.");
Destroy(Menu);
-- begin read only
end Test_Get_Options_test_get_options_menu;
-- end read only
-- begin read only
procedure Wrap_Test_Configure_0076be_2b53be
(Menu_Widget: Tk_Menu; Options: Menu_Options) is
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(tk-menu.ads:0):Test_Configure_Menu test requirement violated");
end;
GNATtest_Generated.GNATtest_Standard.Tk.Menu.Configure
(Menu_Widget, Options);
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(tk-menu.ads:0:):Test_Configure_Menu test commitment violated");
end;
end Wrap_Test_Configure_0076be_2b53be;
-- end read only
-- begin read only
procedure Test_Configure_test_configure_menu
(Gnattest_T: in out Test_Menu_Options);
procedure Test_Configure_0076be_2b53be
(Gnattest_T: in out Test_Menu_Options) renames
Test_Configure_test_configure_menu;
-- id:2.2/0076be6725db0897/Configure/1/0/test_configure_menu/
procedure Test_Configure_test_configure_menu
(Gnattest_T: in out Test_Menu_Options) is
procedure Configure(Menu_Widget: Tk_Menu; Options: Menu_Options) renames
Wrap_Test_Configure_0076be_2b53be;
-- end read only
pragma Unreferenced(Gnattest_T);
Menu: Tk_Menu;
Options, Options2: Menu_Options;
begin
if Value("DISPLAY", "")'Length = 0 then
Assert(True, "No display, can't test");
return;
end if;
Create(Menu, ".mymenu", Menu_Options'(Tear_Off => FALSE, others => <>));
Options := (Tear_Off => TRUE, others => <>);
Configure(Menu, Options);
Options2 := Get_Options(Menu);
Assert
(Options.Tear_Off = Options2.Tear_Off,
"Failed to set options of a menu.");
Destroy(Menu);
-- begin read only
end Test_Configure_test_configure_menu;
-- end read only
-- begin read only
-- id:2.2/02/
--
-- This section can be used to add elaboration code for the global state.
--
begin
-- end read only
null;
-- begin read only
-- end read only
end Tk.Menu.Menu_Options_Test_Data.Menu_Options_Tests;
|
with Ada.Text_Io; use Ada.Text_IO;
package body Shapes.Circles is
-----------
-- Print --
-----------
procedure Print (Item : Circle) is
begin
Put_line("Circle");
end Print;
----------
-- Setx --
----------
function Setx (Item : Circle; Val : Integer) return Circle is
begin
return (Val, Item.Y, Item.R);
end Setx;
----------
-- Sety --
----------
function Sety (Item : Circle; Val : Integer) return Circle is
Temp : Circle := Item;
begin
Temp.Y := Val;
return Temp;
end Sety;
----------
-- Setr --
----------
function Setr (Item : Circle; Val : Integer) return Circle is
begin
return (Item.X, Item.Y, Val);
end Setr;
----------
-- Getr --
----------
function Getr (Item : Circle) return Integer is
begin
return Item.R;
end Getr;
------------
-- Create --
------------
function Create (P : Point) return Circle is
begin
return (P.X, P.Y, 0);
end Create;
------------
-- Create --
------------
function Create (P : Point; R : Integer) return Circle is
begin
return (P.X, P.Y, R);
end Create;
------------
-- Create --
------------
function Create (X : Integer) return Circle is
begin
return (X, 0, 0);
end Create;
------------
-- Create --
------------
function Create (X : Integer; Y : Integer) return Circle is
begin
return (X, Y, 0);
end Create;
------------
-- Create --
------------
function Create (X : Integer; Y : Integer; R : Integer) return Circle is
begin
return (X, Y, R);
end Create;
------------
-- Create --
------------
function Create return Circle is
begin
return (0, 0, 0);
end Create;
end Shapes.Circles;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, 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 STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_dma.h --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief Header file of DMA HAL module. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides definitions for the DMA controllers on the STM32F4 (ARM
-- Cortex M4F) microcontrollers from ST Microelectronics.
-- See Application Note AN4031: "Using the STM32F2 and STM32F4 DMA controller"
-- and Reference Manual RM0090: "STM32F405xx/07xx, STM32F415xx/17xx,
-- STM32F42xxx and STM32F43xxx advanced ARM-based 32-bit MCUs" In the
-- application note, see especially section four, titled "Tips and
-- warnings while programming the DMA controller"
-- The basic call sequence, given a Controller and a Stream, is as follows:
-- 1) Configure
-- Configures the Controller and Stream per application requirements. This
-- is the primary setup call, specifying the static characteristics of all
-- the transfers to be performed on the stream, such as the direction, the
-- channel, and so forth. The Controller is disabled after the call.
-- 2) Configure_Data_Flow
-- Sets the dynamic parameters of a given transfer, i.e., the source and
-- destination addresses and the number of data items to transfer.
-- 3) Enable
-- Enables transfers on the Controller and Stream. Transfers will begin
-- immediately unless programmed otherwise.
-- You can enable some or all DMA interrupts prior to the call to Enable, if
-- required by your usage.
-- Ensure all the status flags are cleared prior to the call to Enable, since
-- a transfer will then begin. This can be accomplished by relying on the fact
-- that the board has just powered-up, by a call to Reset, or by a call to
-- Clear_All_Status.
-- Note that there are convenience routines that do steps two and three:
-- Start_Transfer
-- Start_Transfer_with_Interrupts
pragma Restrictions (No_Elaboration_Code);
with System; use System;
with Ada.Real_Time; use Ada.Real_Time;
private with STM32_SVD.DMA;
package body STM32.DMA with SPARK_Mode => Off is
procedure Enable
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
is
begin
null;
end Enable;
-- Before enabling a stream to start a new transfer, the event status flags
-- corresponding to the stream must be cleared. Note that the unit may not
-- be enabled by the time the call returns.
procedure Disable
(This : in out DMA_Controller;
Channel : DMA_Channel_Selector) is
begin
case Channel is
when Channel_1 =>
This.CCR1.EN := False;
when Channel_2 =>
This.CCR2.EN := False;
when Channel_3 =>
This.CCR3.EN := False;
when Channel_4 =>
This.CCR4.EN := False;
when Channel_5 =>
This.CCR5.EN := False;
when Channel_6 =>
This.CCR6.EN := False;
when Channel_7 =>
This.CCR7.EN := False;
end case;
end Disable;
function Enabled
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return Boolean is
begin
return False;
end Enabled;
procedure Reset
(This : in out DMA_Controller;
Channel : DMA_Channel_Selector) is
begin
null;
end Reset;
procedure Configure_Data_Flow
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Source : Address;
Destination : Address;
Data_Count : UInt16) is
begin
null;
end Configure_Data_Flow;
procedure Start_Transfer
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Source : Address;
Destination : Address;
Data_Count : UInt16) is
begin
null;
end Start_Transfer;
procedure Start_Transfer_with_Interrupts
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Source : Address;
Destination : Address;
Data_Count : UInt16;
Enabled_Interrupts : Interrupt_Selections := (others => True)) is
begin
null;
end Start_Transfer_with_Interrupts;
procedure Abort_Transfer
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Result : out DMA_Error_Code) is
begin
-- Disables the specified stream and then waits until the request is
-- effective. If a stream is disabled while a data transfer is ongoing, the
-- current datum will be transferred and the stream will be disabled only
-- after the transfer of this single datum completes.
null;
end Abort_Transfer;
procedure Poll_For_Completion
(This : in out DMA_Controller;
Channel : DMA_Channel_Selector;
Expected_Level : DMA_Transfer_Level;
Timeout : Time_Span;
Result : out DMA_Error_Code) is
begin
null;
end Poll_For_Completion;
procedure Set_NDT
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Data_Count : UInt16) is
begin
null;
end Set_NDT;
-- Sets the number of data items to be transferred on the stream.
-- The Data_Count parameter specifies the number of data items to be
-- transferred (from 0 to 65535) on the next transfer. The value is
-- as described for procedure Configure_Data_Flow.
function Items_Transferred
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return UInt16 is
-- returns the number of items transferred
begin
return 0;
end Items_Transferred;
function Current_NDT
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return UInt16 is
begin
return 0;
end Current_NDT;
function Circular_Mode
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return Boolean is
begin
return False;
end Circular_Mode;
procedure Enable_Interrupt
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Source : DMA_Interrupt) is
-- The postcondition should not be relied upon completely because it is
-- possible, under just the wrong conditions, for the interrupt to be
-- disabled immediately, prior to return from this routine
begin
null;
end Enable_Interrupt;
procedure Disable_Interrupt
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Source : DMA_Interrupt) is
begin
null;
end Disable_Interrupt;
function Interrupt_Enabled
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Source : DMA_Interrupt)
return Boolean is
begin
return False;
end Interrupt_Enabled;
procedure Clear_Status
(This : in out DMA_Controller;
Channel : DMA_Channel_Selector;
Flag : DMA_Status_Flag) is
begin
null;
end Clear_Status;
procedure Clear_All_Status
(This : in out DMA_Controller;
Channel : DMA_Channel_Selector) is
begin
null;
end Clear_All_Status;
function Status
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Flag : DMA_Status_Flag)
return Boolean is
begin
return False;
end Status;
function Selected_Channel
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return DMA_Channel_Selector is
begin
return Channel; -- !!!
end Selected_Channel;
function Transfer_Direction
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return DMA_Data_Transfer_Direction is
begin
return Memory_To_Memory; -- !!!
end Transfer_Direction;
function Peripheral_Data_Width
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return DMA_Data_Transfer_Widths is
begin
return Words; -- !!!
end Peripheral_Data_Width;
function Memory_Data_Width
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return DMA_Data_Transfer_Widths is
begin
return Words; -- !!!
end Memory_Data_Width;
function Operating_Mode
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return DMA_Mode is
begin
return Normal_Mode; -- !!!
end Operating_Mode;
function Priority
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return DMA_Priority_Level is
begin
return Priority_Low; -- !!!
end Priority;
function Current_Memory_Buffer
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return Memory_Buffer_Target is
begin
return Memory_Buffer_0; -- !!!
end Current_Memory_Buffer;
procedure Select_Current_Memory_Buffer
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Buffer : Memory_Buffer_Target) is
begin
null;
end Select_Current_Memory_Buffer;
procedure Set_Memory_Buffer
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Buffer : Memory_Buffer_Target;
To : System.Address) is
begin
null;
end Set_Memory_Buffer;
procedure Configure_Double_Buffered_Mode
(This : DMA_Controller;
Channel : DMA_Channel_Selector;
Buffer_0_Value : Address;
Buffer_1_Value : Address;
First_Buffer_Used : Memory_Buffer_Target) is
begin
null;
end Configure_Double_Buffered_Mode;
procedure Enable_Double_Buffered_Mode
(This : DMA_Controller;
Channel : DMA_Channel_Selector) is
begin
null;
end Enable_Double_Buffered_Mode;
procedure Disable_Double_Buffered_Mode
(This : DMA_Controller;
Channel : DMA_Channel_Selector) is
begin
null;
end Disable_Double_Buffered_Mode;
function Double_Buffered
(This : DMA_Controller;
Channel : DMA_Channel_Selector)
return Boolean is
begin
return False;
end Double_Buffered;
procedure Configure
(This : in out DMA_Controller;
Channel : DMA_Channel_Selector;
Config : DMA_Channel_Configuration)
is
Req : UInt4;
begin
Disable (This, Channel);
-- Setup the request
-- Config.Request
Req := 0;
case Channel is
when Channel_1 =>
This.CSELR.C1S := Req;
when Channel_2 =>
This.CSELR.C2S := Req;
when Channel_3 =>
This.CSELR.C3S := Req;
when Channel_4 =>
This.CSELR.C4S := Req;
when Channel_5 =>
This.CSELR.C5S := Req;
when Channel_6 =>
This.CSELR.C6S := Req;
when Channel_7 =>
This.CSELR.C7S := Req;
end case;
end Configure;
function Aligned
(This : Address;
Width : DMA_Data_Transfer_Widths) return Boolean is
begin
return False;
end Aligned;
end STM32.DMA;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . T R A C E B A C K --
-- --
-- B o d y --
-- --
-- Copyright (C) 1999-2021, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- It is now maintained by Ada Core Technologies Inc (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
-- This is the bare board version of this package for ARM EABI targets, using
-- unwind tables.
with Ada.Unchecked_Conversion;
package body System.Traceback is
use System.Traceback_Entries;
type Unwind_Reason_Code is
(URC_OK,
URC_FOREIGN_EXCEPTION_CAUGHT,
URC_END_OF_STACK,
URC_HANDLER_FOUND,
URC_INSTALL_CONTEXT,
URC_CONTINUE_UNWIND,
URC_FAILURE);
pragma Convention (C, Unwind_Reason_Code);
-- The _Unwind_Reason_Code enum defined by ARM EHABI document
pragma Unreferenced (URC_FOREIGN_EXCEPTION_CAUGHT,
URC_END_OF_STACK,
URC_HANDLER_FOUND,
URC_INSTALL_CONTEXT,
URC_CONTINUE_UNWIND);
type Unwind_Context_Type is null record;
type Unwind_Context_Acc is access Unwind_Context_Type;
pragma Convention (C, Unwind_Context_Acc);
-- Access to the opaque _Unwind_Context type
type Unwind_Trace_Fn is access
function (UC : Unwind_Context_Acc; Data : System.Address)
return Unwind_Reason_Code;
pragma Convention (C, Unwind_Trace_Fn);
-- The _Unwind_Trace_Fn function (used for the callback)
function Unwind_Backtrace
(Func : Unwind_Trace_Fn;
Data : System.Address) return Unwind_Reason_Code;
pragma Import (C, Unwind_Backtrace, "_Unwind_Backtrace");
-- The _Unwind_Backtrace function that calls Func with Data for each frame
function Unwind_VRS_Get
(UC : Unwind_Context_Acc;
Reg_Class : Integer;
Reg_Num : Integer;
Data_Rep : Integer;
Addr : System.Address) return Integer;
pragma Import (C, Unwind_VRS_Get, "_Unwind_VRS_Get");
-- The _Unwind_VRS_Get function to extract a register from the unwind
-- context UC.
UVRSR_OK : constant Integer := 0;
-- Success return status for Unwind_VRS_Get
UVRSC_CORE : constant Integer := 0;
-- Core register class for Unwind_VRS_Get
UVRSD_UINT32 : constant Integer := 0;
-- Unsigned int 32 data representation for Unwind_VRS_Get
type Tracebacks_Array_Ptr is access Tracebacks_Array (Positive);
type Callback_Params_Type is record
Tracebacks : Tracebacks_Array_Ptr;
Max_Len : Natural;
Len : Natural;
Exclude_Min : System.Address;
Exclude_Max : System.Address;
Skip_Frames : Natural;
end record;
-- This record contains the parameters for Call_Chain to be passed to
-- the callback. We could have used a nested subprogram, but as we are
-- interfacing with C (in bare board context), we prefer to use an
-- explicit mechanism.
type Callback_Params_Acc is access all Callback_Params_Type;
function Backtrace_Callback
(UC : Unwind_Context_Acc;
Data : System.Address) return Unwind_Reason_Code;
pragma Convention (C, Backtrace_Callback);
-- The callback for _Unwind_Backtrace, which is called for each frame
------------------------
-- Backtrace_Callback --
------------------------
function Backtrace_Callback
(UC : Unwind_Context_Acc;
Data : System.Address) return Unwind_Reason_Code
is
function To_Callback_Params is new Ada.Unchecked_Conversion
(System.Address, Callback_Params_Acc);
Params : constant Callback_Params_Acc := To_Callback_Params (Data);
-- The parameters of Call_Chain
PC : System.Address;
begin
-- Exclude Skip_Frames frames from the traceback.
if Params.Skip_Frames > 0 then
Params.Skip_Frames := Params.Skip_Frames - 1;
return URC_OK;
end if;
-- If the backtrace is full, simply discard new entries
if Params.Len >= Params.Max_Len then
return URC_OK;
end if;
-- Extract the PC (register 15)
if Unwind_VRS_Get (UC, UVRSC_CORE, 15, UVRSD_UINT32, PC'Address) /=
UVRSR_OK
then
return URC_FAILURE;
end if;
-- Discard exluded values
if PC in Params.Exclude_Min .. Params.Exclude_Max then
return URC_OK;
end if;
-- Append an entry
Params.Len := Params.Len + 1;
Params.Tracebacks (Params.Len) := PC;
return URC_OK;
end Backtrace_Callback;
----------------
-- Call_Chain --
----------------
procedure Call_Chain
(Traceback : in out System.Traceback_Entries.Tracebacks_Array;
Max_Len : Natural;
Len : out Natural;
Exclude_Min : System.Address := System.Null_Address;
Exclude_Max : System.Address := System.Null_Address;
Skip_Frames : Natural := 1)
is
function To_Tracebacks_Array_Ptr is new Ada.Unchecked_Conversion
(System.Address, Tracebacks_Array_Ptr);
Params : aliased Callback_Params_Type;
Res : Unwind_Reason_Code;
pragma Unreferenced (Res);
begin
-- Copy parameters; add 1 to Skip_Frames to ignore the caller of
-- Call_Chain.
Params := (Tracebacks => To_Tracebacks_Array_Ptr (Traceback'Address),
Len => 0,
Max_Len => Max_Len,
Exclude_Min => Exclude_Min,
Exclude_Max => Exclude_Max,
Skip_Frames => Skip_Frames + 1);
-- Call the unwinder
Res := Unwind_Backtrace (Backtrace_Callback'Access, Params'Address);
-- Copy the result
Len := Params.Len;
end Call_Chain;
end System.Traceback;
|
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
with GNAT.IO; use GNAT.IO;
package body Yeison_Single is
------------
-- To_Int --
------------
function To_Int (Img : String) return Any is
begin
return To_Holder (Inner_Int'(Value => Integer'Value (Img)));
end To_Int;
-------------
-- To_Real --
-------------
function To_Real (Img : String) return Any is
begin
return To_Holder (Inner_Real'(Value => Float'Value (Img)));
end To_Real;
---------------
-- To_String --
---------------
function To_String (Img : Wide_Wide_String) return Any is
begin
return To_Holder (Inner_Str'(Value => new Text'(Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode (Img))));
end To_String;
------------------------
-- Constant_Reference --
------------------------
function Constant_Reference
(This : Any; Pos : Positive) return access constant Any
is
begin
raise Constraint_Error;
return Constant_Reference (This, Pos);
end Constant_Reference;
------------------------
-- Constant_Reference --
------------------------
function Constant_Reference
(This : Any; Key : String) return access constant Any
is
begin
pragma Compile_Time_Warning
(Standard.True, "Constant_Reference unimplemented");
return
raise Program_Error with "Unimplemented function Constant_Reference";
end Constant_Reference;
-----------
-- Empty --
-----------
function Empty return Any is
begin
return To_Holder (Inner_Map'(Value => <>));
end Empty;
------------
-- Insert --
------------
procedure Insert (This : in out Any; Key : String; Val : Any) is
Inner : Inner_Map renames Inner_Map (This.Reference.Element.all);
begin
Inner.Value.Insert (Key, Val.Element);
end Insert;
----------
-- True --
----------
function True return Any is
begin
return To_Holder (Inner_Bool'(Value => True));
end True;
-----------
-- False --
-----------
function False return Any is
begin
return To_Holder (Inner_Bool'(Value => False));
end False;
-----------
-- Image --
-----------
overriding function Image (This : Inner_Map) Return String is
use Inner_Maps;
Result : Unbounded_String;
begin
Result := Result & "(";
for I in This.Value.Iterate loop
Result := Result & Key (I) & " => " & Element (I).Image;
if I /= This.Value.Last then
Result := Result & ", ";
end if;
end loop;
Result := Result & ")";
return To_String (Result);
end Image;
-----------
-- Image --
-----------
overriding function Image (This : Inner_Vec) return String is
use Inner_Vectors;
Result : Unbounded_String;
begin
Result := Result & "(";
for I in This.Value.Iterate loop
Result := Result & Element (I).Image;
if I /= This.Value.Last then
Result := Result & ", ";
end if;
end loop;
Result := Result & ")";
return To_String (Result);
end Image;
function Empty return Vec_Aux
is (Value => (Value => Inner_Vectors.Empty_Vector));
procedure Append (This : in out Vec_Aux; Val : Any) is
begin
This.Value.Value.Append (Val.Element);
end Append;
package body Operators is
function "+" (This : Vec_Aux) return Any is
begin
return To_Holder (This.Value);
end "+";
end Operators;
end Yeison_Single;
|
package DDS.Request_Reply.connext_c_log is
type RTILogMessage is private;
type RTILogBitmap is private;
--
-- #define SUBMODULE_XMQ_DUMMY (0 << 10)
-- #define SUBMODULE_XMQ_REQUESTREPLY (1 << 10)
SUBMODULE_XMQ_DUMMY : constant := 0;
SUBMODULE_XMQ_REQUESTREPLY : constant := 2#1_000_000_000#;
--
-- #define XMQ_SUBMODULE_MASK_DUMMY (0x0001)
XMQ_SUBMODULE_MASK_DUMMY : constant := 16#0001#;
--
-- #define XMQ_SUBMODULE_MASK_REQUESTREPLY (0x0002)
XMQ_SUBMODULE_MASK_REQUESTREPLY : constant := 16#0001#;
--
--
-- #define XMQ_SUBMODULE_MASK_ALL (0xFFFFFF)
XMQ_SUBMODULE_MASK_ALL : constant := 16#FF_FF_FF#;
--
-- extern XMQCDllExport void
-- XMQLog_getBitmaps(RTILogBitmap *submoduleMask,
-- RTILogBitmap *instrumentationMask);
procedure XMQLog_GetBitmaps (SubmoduleMask : out RTILogBitmap;
InstrumentationMask : out RTILogBitmap);
-- extern XMQCDllExport void
-- XMQLog_setBitmaps(RTILogBitmap submoduleMask,
-- RTILogBitmap instrumentationMask);
procedure XMQLog_SetBitmaps (SubmoduleMask : RTILogBitmap;
InstrumentationMask : RTILogBitmap);
-- extern XMQCDllExport
-- void XMQLog_setVerbosity(RTILogBitmap submoduleMask, int verbosity);
procedure XMQLog_setVerbosity (SubmoduleMask : RTILogBitmap;
Verbosity : Integer);
-- extern XMQCDllVariable const struct RTILogMessage XMQ_LOG_REPLIER_SEND_ERROR_d;
private
type RTILogMessage is new Integer;
type RTILogBitmap is new Integer;
XMQ_LOG_REPLIER_SEND_ERROR_D : RTILogMessage := 1;
end DDS.Request_Reply.connext_c_log;
|
--
-- Copyright 2018 The wookey project team <wookey@ssi.gouv.fr>
-- - Ryad Benadjila
-- - Arnauld Michelizza
-- - Mathieu Renard
-- - Philippe Thierry
-- - Philippe Trebuchet
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
with soc.rcc;
-- About SPARK:
-- In this driver implementation, there is no such
-- complex algorithmic requiring effective SPARK prove,
-- as the package body is only composed on registers
-- fields setters and getters. Using SPARK in this
-- package body would be mostly useless in this very
-- case
package body soc.gpio
with spark_mode => off
is
-- Here we choose to use local accessors instead of
-- a full switch case, in order to:
-- 1) reduce the generated asm
-- 2) avoid writting errors in switch/case write which
-- can't be detected through SPARK rules
type t_GPIO_port_access is access all t_GPIO_port;
GPIOx : constant array (t_gpio_port_index) of t_GPIO_port_access :=
(GPIOA'access, GPIOB'access, GPIOC'access, GPIOD'access, GPIOE'access,
GPIOF'access, GPIOG'access, GPIOH'access, GPIOI'access);
-- FIXME - Should be in soc.rcc package
procedure enable_clock
(port : in t_gpio_port_index)
is
begin
case port is
when GPIO_PA => soc.rcc.RCC.AHB1ENR.GPIOAEN := true;
when GPIO_PB => soc.rcc.RCC.AHB1ENR.GPIOBEN := true;
when GPIO_PC => soc.rcc.RCC.AHB1ENR.GPIOCEN := true;
when GPIO_PD => soc.rcc.RCC.AHB1ENR.GPIODEN := true;
when GPIO_PE => soc.rcc.RCC.AHB1ENR.GPIOEEN := true;
when GPIO_PF => soc.rcc.RCC.AHB1ENR.GPIOFEN := true;
when GPIO_PG => soc.rcc.RCC.AHB1ENR.GPIOGEN := true;
when GPIO_PH => soc.rcc.RCC.AHB1ENR.GPIOHEN := true;
when GPIO_PI => soc.rcc.RCC.AHB1ENR.GPIOIEN := true;
end case;
end enable_clock;
procedure set_mode
(port : in t_gpio_port_index;
pin : in t_gpio_pin_index;
mode : in t_pin_mode)
with
refined_global => (output => (gpio_a, gpio_b, gpio_c,
gpio_d, gpio_e, gpio_f,
gpio_g, gpio_h, gpio_i))
is
begin
GPIOx(port).all.MODER.pin(pin) := mode;
end set_mode;
procedure set_type
(port : in t_gpio_port_index;
pin : in t_gpio_pin_index;
otype : in t_pin_output_type)
with
refined_global => (output => (gpio_a, gpio_b, gpio_c,
gpio_d, gpio_e, gpio_f,
gpio_g, gpio_h, gpio_i))
is
begin
GPIOx(port).all.OTYPER.pin(pin) := otype;
end set_type;
procedure set_speed
(port : in t_gpio_port_index;
pin : in t_gpio_pin_index;
ospeed : in t_pin_output_speed)
with
refined_global => (output => (gpio_a, gpio_b, gpio_c,
gpio_d, gpio_e, gpio_f,
gpio_g, gpio_h, gpio_i))
is
begin
GPIOx(port).all.OSPEEDR.pin(pin) := ospeed;
end set_speed;
procedure set_pupd
(port : in t_gpio_port_index;
pin : in t_gpio_pin_index;
pupd : in t_pin_pupd)
with
refined_global => (output => (gpio_a, gpio_b, gpio_c,
gpio_d, gpio_e, gpio_f,
gpio_g, gpio_h, gpio_i))
is
begin
GPIOx(port).all.PUPDR.pin(pin) := pupd;
end set_pupd;
procedure set_bsr_r
(port : in t_gpio_port_index;
pin : in t_gpio_pin_index;
bsr_r : in types.bit)
with
refined_global => (output => (gpio_a, gpio_b, gpio_c,
gpio_d, gpio_e, gpio_f,
gpio_g, gpio_h, gpio_i))
is
begin
GPIOx(port).all.BSRR.BR(pin) := bsr_r;
end set_bsr_r;
procedure set_bsr_s
(port : in t_gpio_port_index;
pin : in t_gpio_pin_index;
bsr_s : in types.bit)
with
refined_global => (output => (gpio_a, gpio_b, gpio_c,
gpio_d, gpio_e, gpio_f,
gpio_g, gpio_h, gpio_i))
is
begin
GPIOx(port).all.BSRR.BS(pin) := bsr_s;
end set_bsr_s;
procedure set_lck
(port : in t_gpio_port_index;
pin : in t_gpio_pin_index;
lck : in t_pin_lock)
with
refined_global => (output => (gpio_a, gpio_b, gpio_c,
gpio_d, gpio_e, gpio_f,
gpio_g, gpio_h, gpio_i))
is
begin
GPIOx(port).all.LCKR.pin(pin) := lck;
end set_lck;
procedure set_af
(port : in t_gpio_port_index;
pin : in t_gpio_pin_index;
af : in t_pin_alt_func)
with
refined_global => (output => (gpio_a, gpio_b, gpio_c,
gpio_d, gpio_e, gpio_f,
gpio_g, gpio_h, gpio_i))
is
begin
if pin < 8 then
GPIOx(port).all.AFRL.pin(pin) := af;
else
GPIOx(port).all.AFRH.pin(pin) := af;
end if;
end set_af;
procedure write_pin
(port : in t_gpio_port_index;
pin : in t_gpio_pin_index;
value : in bit)
with
refined_global => (in_out => (gpio_a, gpio_b, gpio_c,
gpio_d, gpio_e, gpio_f,
gpio_g, gpio_h, gpio_i))
is
begin
GPIOx(port).all.ODR.pin (pin) := value;
end write_pin;
procedure read_pin
(port : in t_gpio_port_index;
pin : in t_gpio_pin_index;
value : out bit)
with
refined_global => (in_out => (gpio_a, gpio_b, gpio_c,
gpio_d, gpio_e, gpio_f,
gpio_g, gpio_h, gpio_i))
is
begin
value := GPIOx(port).all.IDR.pin (pin);
end read_pin;
end soc.gpio;
|
with Unchecked_Conversion;
package Loop_Optimization18_Pkg is
type Arr is array (Integer range <>) of Natural;
type Rec (UB : Integer) is record
L : Arr (1 .. UB);
end record;
type Byte_Array_Type is new String (1..4);
function Conv is new Unchecked_Conversion (Byte_Array_Type, Integer);
end Loop_Optimization18_Pkg;
|
procedure Goto_Test is
begin
Stuff;
goto The_Mother_Ship; -- You can do this if you really must!
Stuff;
if condition then
Stuff;
<<Jail>>
Stuff;
end if;
Stuff;
-- Ada does not permit any of the following
goto Jail;
goto The_Sewer;
goto The_Morgue;
Stuff;
case condition is
when Arm1 =>
Stuff;
goto The_Gutter; -- Cant do this either
Stuff;
when Arm2 =>
Stuff;
<<The_Gutter>>
Stuff;
<<The_Sewer>>
Stuff;
end case;
Stuff;
for I in Something'Range loop
Stuff;
<<The_Morgue>>
if You_Are_In_Trouble then
goto The_Mother_Ship;
-- This is the usual use of a goto.
end if;
Stuff;
end loop;
Stuff;
<<The_Mother_Ship>>
Stuff;
end Goto_Test;
|
-- Institution: Technische Universitaet Muenchen
-- Department: Realtime Computer Systems (RCS)
-- Project: StratoX
--
-- Authors: Emanuel Regnath (emanuel.regnath@tum.de)
with HIL.Devices;
-- @summary
-- Target-independent specification for HIL of UART
package HIL.UART with
Spark_Mode
is
BUFFER_MAX : constant := 200;
subtype Device_ID_Type is HIL.Devices.Device_Type_UART;
type Baudrates_Type is range 9_600 .. 1_500_000
with Static_Predicate => Baudrates_Type in 9_600 | 19_200 | 38_400 | 57_600 | 115_200 | 1_500_000;
subtype Data_Type is Byte_Array;
procedure configure;
procedure write (Device : in Device_ID_Type; Data : in Data_Type);
procedure read (Device : in Device_ID_Type; Data : out Data_Type; n_read : out Natural);
function toData_Type (Message : String) return Data_Type;
end HIL.UART;
|
with Numworks.Keyboard; use Numworks.Keyboard;
package body Keyboard is
------------
-- Update --
------------
procedure Update is
begin
Numworks.Keyboard.Scan;
end Update;
-------------
-- Pressed --
-------------
function Pressed (Key : Key_Kind) return Boolean is
begin
return (case Key is
when Esc => False,
when Up => Pressed (A2) or Pressed (A5),
when Down => Pressed (A3) or Pressed (A6),
when Left => Pressed (A1),
when Right => Pressed (A4)
);
end Pressed;
end Keyboard;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test is
procedure P(X: in out Integer) is begin new_line; end;
type r is record a: integer; end record;
function f return access r is begin return new r; end;
begin
P(f.a);
end;
|
------------------------------------------------------------------------------
-- --
-- Giza --
-- --
-- Copyright (C) 2015 Fabien Chouteau (chouteau@adacore.com) --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Real_Time.Timing_Events; use Ada.Real_Time.Timing_Events;
with Giza.GUI; use Giza.GUI;
with System;
package body Giza.Timers is
type Wrapper;
type Wrapper_Access is access all Wrapper;
type Wrapper is record
Event : Timer_Event_Not_Null_Ref;
Timeout : Time;
Next : Wrapper_Access := null;
end record;
procedure Free is new Ada.Unchecked_Deallocation
(Object => Wrapper, Name => Wrapper_Access);
TE : Timing_Event;
----------
-- Sync --
----------
protected Sync is
pragma Priority (System.Interrupt_Priority'Last);
entry Wait;
procedure Wakeup (Event : in out Timing_Event);
procedure Insert (Item : Wrapper_Access);
function Next_Timeout return Time;
procedure Pop (Item : out Wrapper_Access);
private
Triggered : Boolean := False;
List : Wrapper_Access := null;
end Sync;
----------
-- Sync --
----------
protected body Sync is
entry Wait when Triggered is
begin
Triggered := False;
end Wait;
procedure Wakeup (Event : in out Timing_Event) is
pragma Unreferenced (Event);
begin
Triggered := True;
end Wakeup;
procedure Insert (Item : Wrapper_Access) is
Prev, Curr : Wrapper_Access := null;
begin
if List = null or else List.Timeout >= Item.Timeout then
Item.Next := List;
List := Item;
Set_Handler (Event => TE,
At_Time => List.Timeout,
Handler => Sync.Wakeup'Access);
else
Prev := List;
Curr := List;
while Curr /= null and then Curr.Timeout < Item.Timeout loop
Prev := Curr;
Curr := Curr.Next;
end loop;
Prev.Next := Item;
Item.Next := Curr;
end if;
end Insert;
function Next_Timeout return Time is
begin
return (if List /= null then
List.Timeout
else
Time_Last);
end Next_Timeout;
procedure Pop (Item : out Wrapper_Access) is
begin
-- Remove from list
Item := List;
List := List.Next;
end Pop;
end Sync;
---------------
-- Set_Timer --
---------------
procedure Set_Timer
(Timer : Timer_Event_Not_Null_Ref;
Timeout : Time)
is
Item : constant Wrapper_Access :=
new Wrapper'(Event => Timer, Timeout => Timeout, Next => null);
begin
Sync.Insert (Item);
end Set_Timer;
----------------
-- Timer_Task --
----------------
task Timer_Task is
end Timer_Task;
task body Timer_Task is
Now : Time;
Tmp : Wrapper_Access;
begin
loop
Sync.Wait;
-- back from timeout
Now := Clock;
while Sync.Next_Timeout < Now loop
Sync.Pop (Tmp);
if Tmp /= null then
Emit (Event_Not_Null_Ref (Tmp.Event));
-- Destroy wrapper
Free (Tmp);
end if;
end loop;
Set_Handler (Event => TE,
At_Time => Sync.Next_Timeout,
Handler => Sync.Wakeup'Access);
end loop;
end Timer_Task;
end Giza.Timers;
|
-- -*- Mode: Ada -*-
-- Filename : ether-requests.ads
-- Description : Interface to the request objects.
-- Author : Luke A. Guest
-- Created On : Sun Jul 4 19:11:27 2010
with Ada.Strings.Hash;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Unbounded;
with GNAT.Sockets;
with Unicode.CES;
package Ether.Requests is
type Request is private;
-- These will be queried from the request object.
type Header is (Auth_Type,
Content_Length, -- Same as HTTP_Content_Length?
Content_Type, -- Same as HTTP_Content_Type?
Document_Root,
Gateway_Interface,
HTTP_Accept,
HTTP_Accept_Language,
HTTP_Accept_Encoding,
HTTP_Accept_Charset,
HTTP_Connection,
HTTP_Cookie,
HTTP_Host,
HTTP_Keep_Alive,
HTTP_User_Agent,
HTTP_Referer,
Path_Info,
Path_Translated,
Query_String,
Remote_Addr,
Remote_Host,
Remote_Ident,
Remote_Port,
Remote_User,
Request_Method,
Request_URI,
Script_Name,
Server_Addr,
Server_Admin,
Server_Name,
Server_Port,
Server_Protocol,
Server_Signature,
Server_Software,
SCGI);
type Form_Data_Method is (Get, Put);
SCGI_Error : exception;
Request_Error : exception;
-- Read in the request from some socket and store the data in the request
-- object.
-- Raises Request_Error.
procedure Receive
(Object : in out Request;
Input : in GNAT.Sockets.Stream_Access);
-- Clean up the request object, i.e. at the end of it's use.
procedure Clean(Object : in out Request);
-- Check to see if this is a real SCGI request.
-- Raises SCGI_Error.
function Is_Valid(Object : Request) return Boolean;
function Value(Object : Request; Item : Header) return String;
function Value(Object : Request; Item : String) return String;
function Cookie(Object : Request; Item : String) return String;
function Form(Object : Request; Item : String) return Unicode.CES.Byte_Sequence;--Unicode.UTF8_String;
-- function Content(Object : Request) return String;
-- Get the length of the content.
-- Raises Request_Error.
function Content_Length (Object : Request) return Natural;
function Get_Content_Type (Object : Request) return String;
function Form_Data_Method_Is (Object : in Request) return Form_Data_Method;
private
package US renames Ada.Strings.Unbounded;
function Hash(Key : Header) return Ada.Containers.Hash_Type;
package Variable_Map is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => String,
Element_Type => String,
Hash => Ada.Strings.Hash,
Equivalent_Keys => Standard."=",
"=" => Standard."=");
package Cookie_Map is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => String,
Element_Type => String,
Hash => Ada.Strings.Hash,
Equivalent_Keys => Standard."=",
"=" => Standard."=");
Package Form_Map is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => String,
Element_Type => Unicode.CES.Byte_Sequence,--Unicode.UTF8_String,
Hash => Ada.Strings.Hash,
Equivalent_Keys => Standard."=",
"=" => Standard."=");
type Request is
record
Environment : Variable_Map.Map := Variable_Map.Empty_Map;
Cookies : Cookie_Map.Map := Cookie_Map.Empty_Map;
Form : Form_Map.Map := Form_Map.Empty_Map;
-- Form : URIs.Parameter_Map.Map := URIs.Parameter_Map.Empty_Map;
-- Content : access Content_String := "";
end record;
end Ether.Requests;
|
-----------------------------------------------------------------------
-- awa-settings-modules -- Module awa-settings
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Sessions;
with ADO.Queries;
with AWA.Services.Contexts;
with AWA.Settings.Models;
with AWA.Modules.Get;
with AWA.Users.Models;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Beans.Basic;
package body AWA.Settings.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Settings.Module");
package ASC renames AWA.Services.Contexts;
-- Load the setting value for the current user.
-- Return the default value if there is no such setting.
procedure Load (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String);
-- Save the setting value for the current user.
procedure Save (Name : in String;
Value : in String);
-- ------------------------------
-- Set the user setting with the given name in the setting manager cache
-- and in the database.
-- ------------------------------
procedure Set (Manager : in out Setting_Manager;
Name : in String;
Value : in String) is
begin
Manager.Data.Set (Name, Value);
end Set;
-- ------------------------------
-- Get the user setting with the given name from the setting manager cache.
-- Load the user setting from the database if necessary.
-- ------------------------------
procedure Get (Manager : in out Setting_Manager;
Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
begin
Manager.Data.Get (Name, Default, Value);
end Get;
-- ------------------------------
-- Get the current setting manager for the current user.
-- ------------------------------
function Current return Setting_Manager_Access is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Obj : Util.Beans.Objects.Object := Ctx.Get_Session_Attribute (SESSION_ATTR_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Obj);
begin
if Bean = null or else not (Bean.all in Setting_Manager'Class) then
declare
Mgr : constant Setting_Manager_Access := new Setting_Manager;
begin
Obj := Util.Beans.Objects.To_Object (Mgr.all'Access);
Ctx.Set_Session_Attribute (SESSION_ATTR_NAME, Obj);
return Mgr;
end;
else
return Setting_Manager'Class (Bean.all)'Unchecked_Access;
end if;
end Current;
-- ------------------------------
-- Initialize the settings module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Setting_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the settings module");
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the settings module.
-- ------------------------------
function Get_Setting_Module return Setting_Module_Access is
function Get is new AWA.Modules.Get (Setting_Module, Setting_Module_Access, NAME);
begin
return Get;
end Get_Setting_Module;
-- ------------------------------
-- Load the setting value for the current user.
-- Return the default value if there is no such setting.
-- ------------------------------
procedure Load (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
Setting : AWA.Settings.Models.User_Setting_Ref;
Found : Boolean;
begin
Query.Set_Join ("INNER JOIN awa_setting AS a ON o.setting_id = a.id ");
Query.Set_Filter ("a.name = :name AND o.user_id = :user");
Query.Bind_Param ("name", Name);
Query.Bind_Param ("user", User.Get_Id);
Setting.Find (DB, Query, Found);
if not Found then
Value := Ada.Strings.Unbounded.To_Unbounded_String (Default);
else
Value := Setting.Get_Value;
end if;
end Load;
-- Save the setting value for the current user.
procedure Save (Name : in String;
Value : in String) is
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Setting : AWA.Settings.Models.User_Setting_Ref;
Query : ADO.Queries.Context;
Found : Boolean;
begin
Ctx.Start;
Query.Set_Join ("INNER JOIN awa_setting AS a ON o.setting_id = a.id ");
Query.Set_Filter ("a.name = :name AND o.user_id = :user");
Query.Bind_Param ("name", Name);
Query.Bind_Param ("user", User.Get_Id);
Setting.Find (DB, Query, Found);
if not Found then
declare
Setting_Def : AWA.Settings.Models.Setting_Ref;
begin
Query.Clear;
Query.Set_Filter ("o.name = :name");
Query.Bind_Param ("name", Name);
Setting_Def.Find (DB, Query, Found);
if not Found then
Setting_Def.Set_Name (Name);
Setting_Def.Save (DB);
end if;
Setting.Set_Setting (Setting_Def);
end;
Setting.Set_User (User);
end if;
Setting.Set_Value (Value);
Setting.Save (DB);
Ctx.Commit;
end Save;
procedure Free is new Ada.Unchecked_Deallocation (Object => Setting_Data,
Name => Setting_Data_Access);
use Ada.Strings.Unbounded;
protected body Settings is
procedure Get (Name : in String;
Default : in String;
Value : out Ada.Strings.Unbounded.Unbounded_String) is
Item : Setting_Data_Access := First;
Previous : Setting_Data_Access := null;
begin
while Item /= null loop
if Item.Name = Name then
Value := Item.Value;
if Previous /= null then
Previous.Next_Setting := Item.Next_Setting;
First := Item;
end if;
return;
end if;
Previous := Item;
Item := Item.Next_Setting;
end loop;
Load (Name, Default, Value);
Item := new Setting_Data;
Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
Item.Value := Value;
Item.Next_Setting := First;
First := Item;
end Get;
procedure Set (Name : in String;
Value : in String) is
Item : Setting_Data_Access := First;
Previous : Setting_Data_Access := null;
begin
while Item /= null loop
if Item.Name = Name then
if Previous /= null then
Previous.Next_Setting := Item.Next_Setting;
First := Item;
end if;
if Item.Value = Value then
return;
end if;
Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value);
Save (Name, Value);
return;
end if;
Previous := Item;
Item := Item.Next_Setting;
end loop;
Item := new Setting_Data;
Item.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
Item.Value := Ada.Strings.Unbounded.To_Unbounded_String (Value);
Item.Next_Setting := First;
First := Item;
Save (Name, Value);
end Set;
procedure Clear is
begin
while First /= null loop
declare
Item : Setting_Data_Access := First;
begin
First := Item.Next_Setting;
Free (Item);
end;
end loop;
end Clear;
end Settings;
end AWA.Settings.Modules;
|
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with AUnit.Assertions; use AUnit.Assertions;
with Rejuvenation.String_Utils; use Rejuvenation.String_Utils;
package body Test_String_Utils is
Prefix : constant String := "Prefix";
New_Prefix : constant String := "New_Prefix";
Remainder : constant String := "Remainder";
Empty : constant String := "";
procedure TestCase (Prefix, New_Prefix, Remainder : String);
procedure TestCase (Prefix, New_Prefix, Remainder : String) is
begin
Assert
(Actual =>
Replace_Prefix
(String_With_Prefix => Prefix & Remainder,
Prefix => Prefix,
New_Prefix => New_Prefix),
Expected => New_Prefix & Remainder,
Message =>
"Substitution failed with" & ASCII.LF &
"Prefix => " & Prefix & ASCII.LF &
"New_Prefix => " & New_Prefix & ASCII.LF &
"Remainder => " & Remainder & ASCII.LF);
end TestCase;
procedure Test_example (T : in out Test_Case'Class);
procedure Test_example (T : in out Test_Case'Class) is
pragma Unreferenced (T);
begin
TestCase (Prefix, New_Prefix, Remainder);
end Test_example;
procedure Test_new_prefix_same_size
(T : in out Test_Case'Class);
procedure Test_new_prefix_same_size
(T : in out Test_Case'Class)
is
pragma Unreferenced (T);
Same_Size_Prefix : constant String := Prefix'Length * "A";
begin
Assert
(Condition => Same_Size_Prefix'Length = Prefix'Length,
Message => "Test precondition not realized");
TestCase (Prefix, Same_Size_Prefix, Remainder);
end Test_new_prefix_same_size;
procedure Test_new_prefix_longer
(T : in out Test_Case'Class);
procedure Test_new_prefix_longer (T : in out Test_Case'Class)
is
pragma Unreferenced (T);
Longer_Prefix : constant String := "Longer_Prefix";
begin
Assert
(Condition => Longer_Prefix'Length > Prefix'Length,
Message => "Test precondition not realized");
TestCase (Prefix, Longer_Prefix, Remainder);
end Test_new_prefix_longer;
procedure Test_new_prefix_shorter
(T : in out Test_Case'Class);
procedure Test_new_prefix_shorter
(T : in out Test_Case'Class)
is
pragma Unreferenced (T);
Shorter_Prefix : constant String := "SP"; -- Shorter Prefix
begin
Assert
(Condition => Shorter_Prefix'Length < Prefix'Length,
Message => "Test precondition not realized");
TestCase (Prefix, Shorter_Prefix, Remainder);
end Test_new_prefix_shorter;
procedure Test_slices (T : in out Test_Case'Class);
procedure Test_slices (T : in out Test_Case'Class) is
pragma Unreferenced (T);
begin
TestCase (Prefix (3 .. 5), New_Prefix (6 .. 8), Remainder (2 .. 4));
end Test_slices;
procedure Test_empty_prefix (T : in out Test_Case'Class);
procedure Test_empty_prefix (T : in out Test_Case'Class) is
pragma Unreferenced (T);
begin
TestCase (Empty, New_Prefix, Remainder);
end Test_empty_prefix;
procedure Test_empty_new_prefix
(T : in out Test_Case'Class);
procedure Test_empty_new_prefix (T : in out Test_Case'Class)
is
pragma Unreferenced (T);
begin
TestCase (Prefix, Empty, Remainder);
end Test_empty_new_prefix;
procedure Test_empty_remainder (T : in out Test_Case'Class);
procedure Test_empty_remainder (T : in out Test_Case'Class)
is
pragma Unreferenced (T);
begin
TestCase (Prefix, New_Prefix, Empty);
end Test_empty_remainder;
procedure Test_empty_prefix_and_new_prefix
(T : in out Test_Case'Class);
procedure Test_empty_prefix_and_new_prefix
(T : in out Test_Case'Class)
is
pragma Unreferenced (T);
begin
TestCase (Empty, Empty, Remainder);
end Test_empty_prefix_and_new_prefix;
procedure Test_empty_prefix_and_remainder
(T : in out Test_Case'Class);
procedure Test_empty_prefix_and_remainder
(T : in out Test_Case'Class)
is
pragma Unreferenced (T);
begin
TestCase (Empty, New_Prefix, Empty);
end Test_empty_prefix_and_remainder;
procedure Test_empty_new_prefix_and_remainder
(T : in out Test_Case'Class);
procedure Test_empty_new_prefix_and_remainder
(T : in out Test_Case'Class)
is
pragma Unreferenced (T);
begin
TestCase (Prefix, Empty, Empty);
end Test_empty_new_prefix_and_remainder;
procedure Test_all_empty (T : in out Test_Case'Class);
procedure Test_all_empty (T : in out Test_Case'Class)
is
pragma Unreferenced (T);
begin
TestCase (Empty, Empty, Empty);
end Test_all_empty;
-- Test plumbing
overriding function Name
(T : String_Utils_Test_Case) return AUnit.Message_String
is
pragma Unreferenced (T);
begin
return AUnit.Format ("String Utils");
end Name;
overriding procedure Register_Tests (T : in out String_Utils_Test_Case) is
begin
Registration.Register_Routine
(T, Test_example'Access, "Example");
Registration.Register_Routine
(T, Test_new_prefix_same_size'Access,
"New Prefix Same Size");
Registration.Register_Routine
(T, Test_new_prefix_longer'Access, "New Prefix Longer");
Registration.Register_Routine
(T, Test_new_prefix_shorter'Access,
"New Prefix Shorter");
Registration.Register_Routine
(T, Test_slices'Access, "Slices");
Registration.Register_Routine
(T, Test_empty_prefix'Access, "Empty Prefix");
Registration.Register_Routine
(T, Test_empty_new_prefix'Access, "Empty New Prefix");
Registration.Register_Routine
(T, Test_empty_remainder'Access, "Empty Remainder");
Registration.Register_Routine
(T, Test_empty_prefix_and_new_prefix'Access,
"Empty Prefix and New Prefix");
Registration.Register_Routine
(T, Test_empty_prefix_and_remainder'Access,
"Empty Prefix and Remainder");
Registration.Register_Routine
(T, Test_empty_new_prefix_and_remainder'Access,
"Empty New Prefix and Remainder");
Registration.Register_Routine
(T, Test_all_empty'Access, "All Empty");
end Register_Tests;
end Test_String_Utils;
|
with Commands; use Commands;
with Ada.Unchecked_Deallocation;
package body Algorithm is
procedure Process (Self : in out Pong_Algorithm;
Port : in Serial_Port;
Sensors : in Sensor_Collection)
is
begin
case Self.State is
when Drive =>
Send_Command (Port => Port,
Rec => Construct_Drive_Special (Special => Straight,
V => Default_Velocity));
Self.State := Passive_Driving;
when Passive_Driving =>
if Self.Detect_Collision (Sensors => Sensors) then
Self.State := Collision;
end if;
when Collision =>
Send_Command (Port => Port,
Rec => Construct_Drive_Special (Special => Straight,
V => 0));
Self.State := Recover;
when Recover =>
case Self.Last_Turn is
when False =>
Send_Command (Port => Port,
Rec => Construct_Drive_Special
(Special => CW,
V => 250));
when True =>
Send_Command (Port => Port,
Rec => Construct_Drive_Special
(Special => CCW,
V => 250));
end case;
Self.Last_Turn := not Self.Last_Turn;
Self.State := Passive_Recover;
Self.Reported_Angle := 0;
when Passive_Recover =>
Self.Reported_Angle := Self.Reported_Angle + abs Sensors.Ang.Value;
if Self.Reported_Angle >= 180 then
Self.State := Drive;
end if;
end case;
end Process;
function Detect_Collision (Self : in Pong_Algorithm;
Sensors : in Sensor_Collection)
return Boolean
is
Ret : Boolean := False;
begin
if Sensors.Bumps_And_Wheel_Drops.Bump_Right or else
Sensors.Bumps_And_Wheel_Drops.Bump_Left or else
Sensors.Wall or else
Sensors.Virtual_Wall or else
Sensors.Light_Bumper.LT_Bump_Left or else
Sensors.Light_Bumper.LT_Bump_Front_Left or else
Sensors.Light_Bumper.LT_Bump_Center_Left or else
Sensors.Light_Bumper.LT_Bump_Center_Right or else
Sensors.Light_Bumper.LT_Bump_Front_Right or else
Sensors.Light_Bumper.LT_Bump_Right
then
Ret := True;
end if;
return Ret;
end Detect_Collision;
procedure Safety_Check (Self : in Pong_Algorithm;
Sensors : in Sensor_Collection)
is
begin
if Sensors.Bumps_And_Wheel_Drops.Wheel_Drop_Right or else
Sensors.Bumps_And_Wheel_Drops.Wheel_Drop_Left or else
Sensors.Cliff_Left or else
Sensors.Cliff_Front_Left or else
Sensors.Cliff_Front_Right or else
Sensors.Cliff_Right or else
Sensors.Wheel_Overcurrents.Side_Brush_OC or else
Sensors.Wheel_Overcurrents.Main_Brush_OC or else
Sensors.Wheel_Overcurrents.Right_Wheel_OC or else
Sensors.Wheel_Overcurrents.Left_Wheel_OC
then
raise Safety_Exception with "Stopping robot.";
end if;
end Safety_Check;
end Algorithm;
|
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, not taking more than you give.
--
package body Configs is
function "<" (Left, Right : in Config_Record) return Boolean
is
use type Rules.Dot_Type;
use type Rules.Index_Number;
begin
if Left.Rule.Index < Right.Rule.Index then
return True;
elsif Left.Rule.Index = Right.Rule.Index then
return False;
else
return Left.Dot < Right.Dot;
end if;
end "<";
function "<" (Left, Right : in Config_Access) return Boolean is
(Left.all < Right.all);
end Configs;
|
-- Test Jacobi Eigendecomposition of real valued square matrices.
-- Uses Intel's 18 digit Real to estimate eigval err in 15 digit real,
-- so not very portable.
with Jacobi_Eigen;
with Test_Matrices;
with Text_IO; use Text_IO;
procedure jacobi_eigen_tst_2 is
type Index is range 1 .. 138;
-- the test matrix is square-shaped matrix on: Index x Index.
-- eg Hilbert's matrix is a square matrix with unique elements on the range
-- Index'First .. Index'Last. However, you have the option or using any
-- diagonal sub-block of the matrix defined by Index x Index
Starting_Col : constant Index := Index'First + 0;
Final_Col : constant Index := Index'Last - 0;
-- Can't change:
Final_Row : constant Index := Final_Col;
type Real is digits 18;
type Matrix is array(Index, Index) of Real;
--pragma Convention (Fortran, Matrix); --No! prefers Ada convention.
package Eig is new Jacobi_Eigen
(Real => Real,
Index => Index,
Matrix => Matrix);
use Eig;
-- Eig exports Col_Vector
package rio is new Float_IO(Real);
use rio;
type Real_15 is digits 15;
type Matrix_15 is array(Index, Index) of Real_15;
A : Matrix_15;
--pragma Convention (Fortran, Matrix); --No! prefers Ada convention.
package Eig_15 is new Jacobi_Eigen
(Real => Real_15,
Index => Index,
Matrix => Matrix_15);
-- Eig exports Eig_15.Col_Vector
package Make_Square_Matrix is new Test_Matrices (Real_15, Index, Matrix_15);
use Make_Square_Matrix;
Eig_vals_15 : Col_Vector := (others => 0.0);
procedure d15
(A : in Matrix_15;
Eigval : out Col_Vector) is
Q_tr, A_tmp : Matrix_15;
Eigenvalues : Eig_15.Col_Vector := (others => 0.0);
No_of_Sweeps_Done, No_of_Rotations : Natural;
begin
A_tmp := A;
Eig_15.Eigen_Decompose
(A => A_tmp, -- A_tmp is destroyed
Q_tr => Q_tr,
Eigenvals => Eigenvalues,
No_of_Sweeps_Performed => No_of_Sweeps_Done,
Total_No_of_Rotations => No_of_Rotations,
Final_Col => Final_Col,
Start_Col => Starting_Col,
Eigenvectors_Desired => True);
Eig_15.Sort_Eigs
(Eigenvals => Eigenvalues,
Q_tr => Q_tr,
Start_Col => Starting_Col,
Final_Col => Final_Col,
Sort_Eigvecs_Also => True);
for i in Starting_Col .. Final_Col loop
Eigval(i) := Real (Eigenvalues(i));
end loop;
end d15;
Zero : constant Real := +0.0;
B, Q_tr : Matrix := (others => (others => Zero));
Eigenvals : Col_Vector;
Err, Ave_Err, Max_Err, Max_Val : Real;
Min_Allowed_Real : constant Real := +2.0 **(Real'Machine_Emin + 32);
No_of_Sweeps_Done, No_of_Rotations : Natural;
-----------
-- Pause --
-----------
procedure Pause (s0,s1,s2,s3,s4,s5,s6,s7,s8,s9 : string := "") is
Continue : Character := ' ';
begin
new_line;
if S0 /= "" then put_line (S0); end if;
if S1 /= "" then put_line (S1); end if;
if S2 /= "" then put_line (S2); end if;
if S3 /= "" then put_line (S3); end if;
if S4 /= "" then put_line (S4); end if;
if S5 /= "" then put_line (S5); end if;
if S6 /= "" then put_line (S6); end if;
if S7 /= "" then put_line (S7); end if;
if S8 /= "" then put_line (S8); end if;
if S9 /= "" then put_line (S9); end if;
new_line;
begin
put ("Type a character to continue: ");
get_immediate (Continue);
exception
when others => null;
end;
end pause;
begin
Pause (
"The test uses Intel's 18 digit Reals to estimate eigenval error in the",
"15 digit calculation, so only works on Intel/AMD hardware."
);
for Pass_id in 1 .. 2 loop
for Chosen_Matrix in Matrix_Id loop
Init_Matrix (A, Chosen_Matrix, Starting_Col, Final_Col);
-- Usually A is not symmetric. Eigen_Decompose doesn't care about
-- that. It uses the upper triangle of A, and pretends that A is
-- symmetric. But for subsequent analysis, we symmetrize:
if Pass_id = 1 then -- use lower triangle of A to make a fully symmetric A:
for Col in Starting_Col .. Final_Col loop
for Row in Col .. Final_Row loop
A(Col, Row) := A(Row, Col); -- write lower triangle of A to upper triangle
end loop;
end loop;
else -- use upper triangle of A to make a fully symmetric A:
for Col in Starting_Col .. Final_Col loop
for Row in Starting_Col .. Col loop
A(Col, Row) := A(Row, Col); -- write lower triangle of A to upper triangle
end loop;
end loop;
end if;
d15 (A, Eig_vals_15);
for i in Starting_Col .. Final_Col loop
for j in Starting_Col .. Final_Row loop
B(i,j) := Real (A(i,j));
end loop;
end loop;
Eigen_Decompose
(A => B,
Q_tr => Q_tr,
Eigenvals => Eigenvals,
No_of_Sweeps_Performed => No_of_Sweeps_Done,
Total_No_of_Rotations => No_of_Rotations,
Final_Col => Final_Col,
Start_Col => Starting_Col,
Eigenvectors_Desired => True);
Sort_Eigs
(Eigenvals => Eigenvals,
Q_tr => Q_tr,
Start_Col => Starting_Col,
Final_Col => Final_Col,
Sort_Eigvecs_Also => True);
Max_Err := Zero;
Ave_Err := Zero;
for I in Starting_Col .. Final_Col loop
Err := Abs (Eigenvals(I) - Eig_vals_15(I));
if Err > Max_Err then Max_Err := Err; end if;
Ave_Err := Ave_Err + Err;
end loop;
Max_Val := Zero;
for I in Starting_Col .. Final_Col loop
if Abs (Eigenvals(I)) > Max_Val then Max_Val := Abs (Eigenvals(I)); end if;
end loop;
new_line;
put("For matrix A of type "); put(Matrix_id'Image(Chosen_Matrix));
new_line;
put(" Max err:");
put(Max_Err / (Max_Val + Min_Allowed_Real));
put(" Ave err:");
put(Ave_Err / ((Real(Final_Col)-Real(Starting_Col)+1.0)*(Max_Val+Min_Allowed_Real)));
end loop;
end loop;
end;
|
-- A string set is just a weaker form of regular expression. A string
-- set is a finite set of strings where each character belongs to a set.
--
-- A string set can be represented by a regex of the form
--
-- [...][...][...]
--
-- that is, as a concatenation of character sets.
--
-- This is convenient choice when you do not need the full "weight" of
-- usual regexs.
with Ada.Strings.Maps; use Ada.Strings.Maps;
package String_Sets is
type Set_String (<>) is private;
function To_Set_String (X : String) return Set_String;
-- Create a string set that contains only X
function "&" (X, Y : Set_String) return Set_String;
function "&" (X : String; Y : Character_Set) return Set_String;
function Match (X : String; Pattern : Set_String) return Boolean;
private
type Basic_Set_String is array (Positive range <>) of Character_Set;
type Set_String is new Basic_Set_String;
function "&" (X, Y : Set_String) return Set_String
is (Set_String(Basic_Set_String (X) & Basic_Set_String (Y)));
function "&" (X : String; Y : Character_Set) return Set_String
is (To_Set_String (X) & Set_String'(1 => Y));
end String_Sets;
|
with ada.text_io, ada.integer_text_io;
use ada.text_io, ada.integer_text_io;
with ada.text_io, ada.integer_text_io;
use ada.text_io, ada.integer_text_io;
with divisores;
procedure prueba_divisores is
n1, divisor:integer:=0;
begin
-- caso de prueba 1:
n1:=4;
put("El resultado deberia de ser 1 2 4:");
new_line;
put("Y tu programa dice que:");
divisores(n1);
new_line;
-- caso de prueba 2:
n1:=20;
put("El resultado deberia de ser 1 2 4 5 10 20:");
new_line;
put("Y tu programa dice que:");
divisores(n1);
new_line;
-- caso de prueba 3:
n1:=1;
put("El resultado deberia de ser 1:");
new_line;
put("Y tu programa dice que:");
divisores(n1);
new_line;
-- caso de prueba 4:
n1:=11;
put("El resultado deberia de ser 1 11:");
new_line;
put("Y tu programa dice que:");
divisores(n1);
new_line;
end prueba_divisores;
|
with System;
with GMP.Z.Inside;
with C.string;
package body GMP.Q is
use type C.signed_int;
use type C.size_t;
procedure memcpy (dst, src : System.Address; n : C.size_t)
with Import, Convention => Intrinsic, External_Name => "__builtin_memcpy";
-- implementation
function Num (X : MP_Rational) return Z.MP_Integer is
begin
return Result : Z.MP_Integer do
C.gmp.mpz_set (
Z.Inside.Reference (Result),
Controlled.Constant_Reference (X).mp_num'Access);
end return;
end Num;
function Den (X : MP_Rational) return Z.MP_Integer is
begin
return Result : Z.MP_Integer do
C.gmp.mpz_set (
Z.Inside.Reference (Result),
Controlled.Constant_Reference (X).mp_den'Access);
end return;
end Den;
function Image (Value : MP_Rational; Base : Number_Base := 10) return String is
Raw_Value : constant not null access constant C.gmp.mpq_struct :=
Controlled.Constant_Reference (Value);
Buffer_Size : constant C.size_t :=
C.gmp.mpz_sizeinbase (Raw_Value.mp_num'Access, C.signed_int (Base))
+ C.gmp.mpz_sizeinbase (Raw_Value.mp_den'Access, C.signed_int (Base))
+ 2;
Buffer : aliased C.char_array (0 .. Buffer_Size);
Dummy : C.char_ptr;
begin
Dummy :=
C.gmp.mpq_get_str (
Buffer (Buffer'First)'Access,
C.signed_int (Base),
Raw_Value);
declare
Length : constant Natural :=
Natural (C.string.strlen (Buffer (Buffer'First)'Access));
Result : String (1 .. Length);
for Result'Address use Buffer'Address;
begin
return Result;
end;
end Image;
function Value (Image : String; Base : Number_Base := 10) return MP_Rational is
Image_Length : constant C.size_t := Image'Length;
C_Image : C.char_array (0 .. Image_Length); -- NUL
begin
memcpy (C_Image'Address, Image'Address, Image_Length);
C_Image (Image_Length) := C.char'Val (0);
return Result : MP_Rational do
declare
Raw_Result : constant not null access C.gmp.mpq_struct :=
Controlled.Reference (Result);
begin
if C.gmp.mpq_set_str (
Raw_Result,
C_Image (C_Image'First)'Access,
C.signed_int (Base)) < 0
then
raise Constraint_Error;
end if;
C.gmp.mpq_canonicalize (Raw_Result);
end;
end return;
end Value;
function "=" (Left, Right : MP_Rational) return Boolean is
begin
return C.gmp.mpq_cmp (
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right)) = 0;
end "=";
function "<" (Left, Right : MP_Rational) return Boolean is
begin
return C.gmp.mpq_cmp (
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right)) < 0;
end "<";
function ">" (Left, Right : MP_Rational) return Boolean is
begin
return C.gmp.mpq_cmp (
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right)) > 0;
end ">";
function "<=" (Left, Right : MP_Rational) return Boolean is
begin
return C.gmp.mpq_cmp (
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right)) <= 0;
end "<=";
function ">=" (Left, Right : MP_Rational) return Boolean is
begin
return C.gmp.mpq_cmp (
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right)) >= 0;
end ">=";
function "+" (Right : MP_Rational) return MP_Rational is
begin
return Right;
end "+";
function "-" (Right : MP_Rational) return MP_Rational is
begin
return Result : MP_Rational do
C.gmp.mpq_neg (
Controlled.Reference (Result),
Controlled.Constant_Reference (Right));
end return;
end "-";
function "+" (Left, Right : MP_Rational) return MP_Rational is
begin
return Result : MP_Rational do
C.gmp.mpq_add (
Controlled.Reference (Result),
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right));
end return;
end "+";
function "-" (Left, Right : MP_Rational) return MP_Rational is
begin
return Result : MP_Rational do
C.gmp.mpq_sub (
Controlled.Reference (Result),
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right));
end return;
end "-";
function "*" (Left, Right : MP_Rational) return MP_Rational is
begin
return Result : MP_Rational do
C.gmp.mpq_mul (
Controlled.Reference (Result),
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right));
end return;
end "*";
function "/" (Left, Right : MP_Rational) return MP_Rational is
begin
return Result : MP_Rational do
C.gmp.mpq_div (
Controlled.Reference (Result),
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right));
end return;
end "/";
function "/" (Left, Right : Long_Long_Integer) return MP_Rational is
Numerator : Long_Long_Integer renames Left;
Denominator : Long_Long_Integer renames Right;
begin
return Result : MP_Rational do
declare
Raw_Result : constant not null access C.gmp.mpq_struct :=
Controlled.Reference (Result);
begin
mpz_set_Long_Long_Integer (Raw_Result.mp_num'Access, Numerator);
mpz_set_Long_Long_Integer (Raw_Result.mp_den'Access, Denominator);
C.gmp.mpq_canonicalize (Raw_Result);
end;
end return;
end "/";
function "/" (Left, Right : Z.MP_Integer) return MP_Rational is
Numerator : Z.MP_Integer renames Left;
Denominator : Z.MP_Integer renames Right;
begin
return Result : MP_Rational do
declare
Raw_Result : constant not null access C.gmp.mpq_struct :=
Controlled.Reference (Result);
begin
C.gmp.mpz_set (
Raw_Result.mp_num'Access,
Z.Inside.Constant_Reference (Numerator));
C.gmp.mpz_set (
Raw_Result.mp_den'Access,
Z.Inside.Constant_Reference (Denominator));
C.gmp.mpq_canonicalize (Raw_Result);
end;
end return;
end "/";
function "**" (Left : MP_Rational; Right : Integer) return MP_Rational is
begin
return Result : MP_Rational do
declare
Raw_Result : constant not null access C.gmp.mpq_struct :=
Controlled.Reference (Result);
Raw_Left : constant not null access constant C.gmp.mpq_struct :=
Controlled.Constant_Reference (Left);
begin
if Right >= 0 then
declare
E : constant C.unsigned_long := C.unsigned_long'Mod (Right);
begin
C.gmp.mpz_pow_ui (Raw_Result.mp_num'Access, Raw_Left.mp_num'Access, E);
C.gmp.mpz_pow_ui (Raw_Result.mp_den'Access, Raw_Left.mp_den'Access, E);
end;
else
declare
E : constant C.unsigned_long := C.unsigned_long'Mod (-Right);
begin
C.gmp.mpz_pow_ui (Raw_Result.mp_num'Access, Raw_Left.mp_den'Access, E);
C.gmp.mpz_pow_ui (Raw_Result.mp_den'Access, Raw_Left.mp_num'Access, E);
end;
end if;
C.gmp.mpq_canonicalize (Raw_Result);
end;
end return;
end "**";
package body Controlled is
function View_Reference (Item : in out MP_Rational)
return not null access C.gmp.mpq_struct;
pragma Inline (View_Reference);
function View_Reference (Item : in out MP_Rational)
return not null access C.gmp.mpq_struct is
begin
return Item.Raw (0)'Unchecked_Access;
end View_Reference;
-- implementation
function Reference (Item : in out Q.MP_Rational)
return not null access C.gmp.mpq_struct is
begin
return View_Reference (MP_Rational (Item)); -- view conversion
end Reference;
function Constant_Reference (Item : Q.MP_Rational)
return not null access constant C.gmp.mpq_struct is
begin
return MP_Rational (Item).Raw (0)'Unchecked_Access;
end Constant_Reference;
overriding procedure Initialize (Object : in out MP_Rational) is
begin
C.gmp.mpq_init (Object.Raw (0)'Access);
end Initialize;
overriding procedure Adjust (Object : in out MP_Rational) is
Source : constant C.gmp.mpq_t := Object.Raw;
begin
C.gmp.mpq_init (Object.Raw (0)'Access);
C.gmp.mpq_set (Object.Raw (0)'Access, Source (0)'Access);
end Adjust;
overriding procedure Finalize (Object : in out MP_Rational) is
begin
C.gmp.mpq_clear (Object.Raw (0)'Access);
end Finalize;
end Controlled;
procedure Read (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Item : out MP_Rational)
is
Raw_Item : constant not null access C.gmp.mpq_struct :=
Controlled.Reference (Item);
begin
C.gmp.mpq_clear (Raw_Item);
Z.Inside.Read (Stream, Raw_Item.mp_num'Access);
Z.Inside.Read (Stream, Raw_Item.mp_den'Access);
end Read;
procedure Write (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Item : in MP_Rational)
is
Raw_Item : constant not null access constant C.gmp.mpq_struct :=
Controlled.Constant_Reference (Item);
begin
Z.Inside.Write (Stream, Raw_Item.mp_num'Access);
Z.Inside.Write (Stream, Raw_Item.mp_den'Access);
end Write;
end GMP.Q;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Binomial is
function Binomial (N, K : Natural) return Natural is
Result : Natural := 1;
M : Natural;
begin
if N < K then
raise Constraint_Error;
end if;
if K > N/2 then -- Use symmetry
M := N - K;
else
M := K;
end if;
for I in 1..M loop
Result := Result * (N - M + I) / I;
end loop;
return Result;
end Binomial;
begin
for N in 0..17 loop
for K in 0..N loop
Put (Integer'Image (Binomial (N, K)));
end loop;
New_Line;
end loop;
end Test_Binomial;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2018, 2019, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Wiki.Helpers;
with Wiki.Nodes.Lists;
package body Wiki.Render.Html is
-- ------------------------------
-- Set the output stream.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the link renderer.
-- ------------------------------
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Wiki.Render.Links.Link_Renderer_Access) is
begin
Engine.Links := Links;
end Set_Link_Renderer;
-- ------------------------------
-- Set the render TOC flag that controls the TOC rendering.
-- ------------------------------
procedure Set_Render_TOC (Engine : in out Html_Renderer;
State : in Boolean) is
begin
Engine.Enable_Render_TOC := State;
end Set_Render_TOC;
-- ------------------------------
-- Set the no-newline mode to avoid emitting newlines (disabled by default).
-- ------------------------------
procedure Set_No_Newline (Engine : in out Html_Renderer;
Enable : in Boolean) is
begin
Engine.No_Newline := Enable;
end Set_No_Newline;
-- ------------------------------
-- Get the current section number.
-- ------------------------------
function Get_Section_Number (Engine : in Html_Renderer;
Prefix : in Wiki.Strings.WString;
Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString is
Result : Wiki.Strings.UString;
Value : Natural;
Empty : Boolean := True;
begin
if Engine.Section_Level = 0 then
return "";
end if;
Wiki.Strings.Append (Result, Prefix);
for I in 1 .. Engine.Section_Level loop
Value := Engine.Current_Section (I);
if Value > 0 or not Empty then
declare
N : constant Strings.WString := Positive'Wide_Wide_Image (Value);
begin
if not Empty then
Wiki.Strings.Append (Result, Separator);
end if;
Empty := False;
Wiki.Strings.Append (Result, N (N'First + 1 .. N'Last));
end;
end if;
end loop;
return Wiki.Strings.To_WString (Result);
end Get_Section_Number;
-- ------------------------------
-- Returns true if the HTML element being included is already contained in a paragraph.
-- This include: a, em, strong, small, b, i, u, s, span, ins, del, sub, sup.
-- ------------------------------
function Has_Html_Paragraph (Engine : in Html_Renderer) return Boolean is
begin
return Engine.Html_Tag = Wiki.SPAN_TAG
or Engine.Html_Tag = Wiki.A_TAG
or Engine.Html_Tag = Wiki.EM_TAG
or Engine.Html_Tag = Wiki.STRONG_TAG
or Engine.Html_Tag = Wiki.SMALL_TAG
or Engine.Html_Tag = Wiki.B_TAG
or Engine.Html_Tag = Wiki.I_TAG
or Engine.Html_Tag = Wiki.U_TAG
or Engine.Html_Tag = Wiki.S_TAG
or Engine.Html_Tag = Wiki.SUB_TAG
or Engine.Html_Tag = Wiki.SUP_TAG
or Engine.Html_Tag = Wiki.INS_TAG
or Engine.Html_Tag = Wiki.DEL_TAG;
end Has_Html_Paragraph;
-- ------------------------------
-- Render the node instance from the document.
-- ------------------------------
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type) is
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
if Node.Level > 6 then
Engine.Render_Header (Doc => Doc,
Header => Node.Header,
Level => 6);
else
Engine.Render_Header (Doc => Doc,
Header => Node.Header,
Level => Node.Level);
end if;
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Output.Write ("<br>");
when Wiki.Nodes.N_NEWLINE =>
if not Engine.No_Newline then
Engine.Output.Write_Wide_Text (Wiki.Helpers.LF & "");
end if;
when Wiki.Nodes.N_HORIZONTAL_RULE =>
if Engine.Html_Level = 0 or not Engine.Has_Html_Paragraph then
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
end if;
Engine.Output.Write ("<hr>");
when Wiki.Nodes.N_PARAGRAPH =>
-- Close the paragraph and start a new one except if the current HTML
-- element is within a paragraph (ex: a, b, i, u, span, ...).
if Engine.Html_Level = 0 or not Engine.Has_Html_Paragraph then
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
end if;
when Wiki.Nodes.N_PREFORMAT =>
Engine.Render_Preformatted (Node.Preformatted,
Strings.To_WString (Node.Language));
when Wiki.Nodes.N_INDENT =>
null;
when Wiki.Nodes.N_LIST =>
Engine.Render_List_Item (Node.Level, False);
when Wiki.Nodes.N_NUM_LIST =>
Engine.Render_List_Item (Node.Level, True);
when Wiki.Nodes.N_TEXT =>
Engine.Add_Text (Text => Node.Text,
Format => Node.Format);
when Wiki.Nodes.N_QUOTE =>
Engine.Render_Quote (Doc, Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_LINK =>
Engine.Render_Link (Doc, Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_IMAGE =>
Engine.Render_Image (Doc, Node.Title, Node.Link_Attr);
when Wiki.Nodes.N_BLOCKQUOTE =>
Engine.Add_Blockquote (Node.Level);
when Wiki.Nodes.N_TAG_START =>
Engine.Render_Tag (Doc, Node);
when Wiki.Nodes.N_TOC =>
Engine.Render_TOC (Doc, Node.Level);
when Wiki.Nodes.N_TOC_ENTRY =>
null;
when Wiki.Nodes.N_TOC_DISPLAY =>
Engine.Render_TOC (Doc, 3);
when Wiki.Nodes.N_TABLE =>
Engine.Render_Table (Doc, Node, "table");
when Wiki.Nodes.N_ROW =>
Engine.Render_Table (Doc, Node, "tr");
when Wiki.Nodes.N_COLUMN =>
Engine.Render_Table (Doc, Node, "td");
end case;
end Render;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type) is
Name : constant Wiki.String_Access := Wiki.Get_Tag_Name (Node.Tag_Start);
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes);
Previous_Tag : constant Wiki.Html_Tag := Engine.Html_Tag;
Prev_Para : Boolean := Engine.Has_Paragraph;
begin
if Node.Tag_Start = Wiki.P_TAG then
Engine.Has_Paragraph := True;
Engine.Need_Paragraph := False;
elsif Node.Tag_Start = Wiki.UL_TAG
or Node.Tag_Start = Wiki.OL_TAG
or Node.Tag_Start = Wiki.DL_TAG
or Node.Tag_Start = Wiki.DT_TAG
or Node.Tag_Start = Wiki.DD_TAG
or Node.Tag_Start = Wiki.LI_TAG
or Node.Tag_Start = Wiki.H1_TAG
or Node.Tag_Start = Wiki.H2_TAG
or Node.Tag_Start = Wiki.H3_TAG
or Node.Tag_Start = Wiki.H4_TAG
or Node.Tag_Start = Wiki.H5_TAG
or Node.Tag_Start = Wiki.H6_TAG
or Node.Tag_Start = Wiki.DIV_TAG
or Node.Tag_Start = Wiki.TABLE_TAG
then
Engine.Close_Paragraph;
Engine.Need_Paragraph := False;
Engine.Has_Paragraph := False;
Engine.Open_Paragraph;
elsif Node.Tag_Start = Wiki.B_TAG
or Node.Tag_Start = Wiki.I_TAG
or Node.Tag_Start = Wiki.SPAN_TAG
or Node.Tag_Start = Wiki.INS_TAG
or Node.Tag_Start = Wiki.DEL_TAG
or Node.Tag_Start = Wiki.A_TAG
then
Engine.Open_Paragraph;
Prev_Para := Engine.Has_Paragraph;
elsif Node.Tag_Start = Wiki.BR_TAG then
Engine.Output.Write ("<br>");
return;
elsif Node.Tag_Start = Wiki.HR_TAG then
Engine.Output.Write ("<hr>");
return;
else
Engine.Has_Paragraph := False;
Engine.Need_Paragraph := False;
Engine.Open_Paragraph;
end if;
Engine.Output.Start_Element (Name.all);
while Wiki.Attributes.Has_Element (Iter) loop
Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
Engine.Html_Tag := Node.Tag_Start;
Engine.Html_Level := Engine.Html_Level + 1;
Engine.Render (Doc, Node.Children);
Engine.Html_Tag := Previous_Tag;
Engine.Html_Level := Engine.Html_Level - 1;
if Node.Tag_Start = Wiki.P_TAG then
Engine.Has_Paragraph := False;
Engine.Need_Paragraph := True;
elsif Node.Tag_Start = Wiki.UL_TAG
or Node.Tag_Start = Wiki.OL_TAG
or Node.Tag_Start = Wiki.DL_TAG
or Node.Tag_Start = Wiki.DT_TAG
or Node.Tag_Start = Wiki.DD_TAG
or Node.Tag_Start = Wiki.LI_TAG
or Node.Tag_Start = Wiki.H1_TAG
or Node.Tag_Start = Wiki.H2_TAG
or Node.Tag_Start = Wiki.H3_TAG
or Node.Tag_Start = Wiki.H4_TAG
or Node.Tag_Start = Wiki.H5_TAG
or Node.Tag_Start = Wiki.H6_TAG
or Node.Tag_Start = Wiki.DIV_TAG
or Node.Tag_Start = Wiki.TABLE_TAG
then
Engine.Close_Paragraph;
Engine.Has_Paragraph := False;
Engine.Need_Paragraph := True;
elsif not Engine.Has_Html_Paragraph then
-- Leaving the HTML text-element, restore the previous paragraph state.
Engine.Has_Paragraph := Prev_Para;
end if;
Engine.Output.End_Element (Name.all);
end Render_Tag;
-- ------------------------------
-- Render a section header in the document.
-- ------------------------------
procedure Render_Header (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Positive) is
Tag : String_Access;
begin
if Engine.Enable_Render_TOC and not Engine.TOC_Rendered and not Doc.Is_Using_TOC
and Doc.Is_Visible_TOC
then
Engine.Render_TOC (Doc, 3);
end if;
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
Engine.Current_Section (Level) := Engine.Current_Section (Level) + 1;
for I in Level + 1 .. Engine.Current_Section'Last loop
Engine.Current_Section (I) := 0;
end loop;
Engine.Section_Level := Level;
case Level is
when 1 =>
Tag := Get_Tag_Name (H1_TAG);
when 2 =>
Tag := Get_Tag_Name (H2_TAG);
when 3 =>
Tag := Get_Tag_Name (H3_TAG);
when 4 =>
Tag := Get_Tag_Name (H4_TAG);
when 5 =>
Tag := Get_Tag_Name (H5_TAG);
when others =>
Tag := Get_Tag_Name (H6_TAG);
end case;
Engine.Output.Start_Element (Tag.all);
if Engine.Enable_Render_TOC then
Engine.Output.Write_Wide_Attribute ("id", Engine.Get_Section_Number ("section_", '_'));
end if;
Engine.Output.Write_Wide_Text (Header);
Engine.Output.End_Element (Tag.all);
end Render_Header;
-- ------------------------------
-- Render the table of content.
-- ------------------------------
procedure Render_TOC (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Level : in Natural) is
procedure Render_Entry (Node : in Wiki.Nodes.Node_Type);
procedure Set_Current_Level (New_Level : in Natural);
use Wiki.Nodes;
procedure Set_Current_Level (New_Level : in Natural) is
begin
if New_Level = Engine.Section_Level and then New_Level /= 0 then
Engine.Output.End_Element ("li");
Engine.Output.Start_Element ("li");
Engine.Output.Write_Attribute ("class", "wiki-toc-entry");
end if;
-- Close the ul/li lists up to the expected level.
while New_Level < Engine.Section_Level loop
Engine.Output.End_Element ("li");
Engine.Output.End_Element ("ul");
Engine.Section_Level := Engine.Section_Level - 1;
end loop;
while New_Level > Engine.Section_Level loop
Engine.Output.Start_Element ("ul");
Engine.Output.Write_Attribute ("class", "wiki-toc-entry");
Engine.Output.Start_Element ("li");
Engine.Output.Write_Attribute ("class", "wiki-toc-entry");
Engine.Section_Level := Engine.Section_Level + 1;
Engine.Current_Section (Engine.Section_Level) := 0;
end loop;
end Set_Current_Level;
procedure Render_Entry (Node : in Wiki.Nodes.Node_Type) is
begin
if Node.Kind /= Wiki.Nodes.N_TOC_ENTRY or else Node.Level > Level then
return;
end if;
Set_Current_Level (Node.Level);
Engine.Current_Section (Engine.Section_Level)
:= Engine.Current_Section (Engine.Section_Level) + 1;
Engine.Output.Start_Element ("a");
Engine.Output.Write_Attribute ("class", "wiki-toc-ref");
Engine.Output.Write_Wide_Attribute ("href", Engine.Get_Section_Number ("#section_", '_'));
Engine.Output.Start_Element ("span");
Engine.Output.Write_Attribute ("class", "wiki-toc-level");
Engine.Output.Write_Wide_Text (Engine.Get_Section_Number ("", '.'));
Engine.Output.End_Element ("span");
Engine.Output.Start_Element ("span");
Engine.Output.Write_Attribute ("class", "wiki-toc-title");
Engine.Output.Write_Wide_Text (Node.Header);
Engine.Output.End_Element ("span");
Engine.Output.End_Element ("a");
end Render_Entry;
Toc : constant Wiki.Nodes.Lists.Node_List_Ref := Doc.Get_TOC;
begin
if Wiki.Nodes.Lists.Length (Toc) <= 3 then
Engine.Enable_Render_TOC := False;
elsif not Engine.TOC_Rendered then
Engine.Section_Level := 0;
Engine.Current_Section := (others => 0);
Engine.Output.Start_Element ("div");
Engine.Output.Write_Attribute ("class", "wiki-toc");
Wiki.Nodes.Lists.Iterate (Toc, Render_Entry'Access);
Set_Current_Level (0);
Engine.Output.End_Element ("div");
Engine.TOC_Rendered := True;
Engine.Current_Section := (others => 0);
end if;
end Render_TOC;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural) is
begin
if Engine.Quote_Level /= Level then
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
end if;
while Engine.Quote_Level < Level loop
Engine.Output.Start_Element ("blockquote");
Engine.Quote_Level := Engine.Quote_Level + 1;
end loop;
while Engine.Quote_Level > Level loop
Engine.Output.End_Element ("blockquote");
Engine.Quote_Level := Engine.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Render_List_Item (Engine : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Engine.Has_Paragraph then
Engine.Output.End_Element ("p");
Engine.Has_Paragraph := False;
end if;
if Engine.Has_Item then
Engine.Output.End_Element ("li");
Engine.Has_Item := False;
end if;
Engine.Need_Paragraph := False;
Engine.Open_Paragraph;
while Engine.Current_Level < Level loop
if Ordered then
Engine.Output.Start_Element ("ol");
else
Engine.Output.Start_Element ("ul");
end if;
Engine.Current_Level := Engine.Current_Level + 1;
Engine.List_Styles (Engine.Current_Level) := Ordered;
end loop;
end Render_List_Item;
procedure Close_Paragraph (Engine : in out Html_Renderer) is
begin
-- Don't close a paragraph if we are within a HTML text-level element.
if Engine.Has_Html_Paragraph then
return;
end if;
if Engine.Has_Paragraph then
Engine.Output.End_Element ("p");
end if;
if Engine.Has_Item then
Engine.Output.End_Element ("li");
end if;
while Engine.Current_Level > 0 loop
if Engine.List_Styles (Engine.Current_Level) then
Engine.Output.End_Element ("ol");
else
Engine.Output.End_Element ("ul");
end if;
Engine.Current_Level := Engine.Current_Level - 1;
end loop;
Engine.Has_Paragraph := False;
Engine.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Engine : in out Html_Renderer) is
begin
if Engine.Need_Paragraph then
Engine.Output.Start_Element ("p");
Engine.Has_Paragraph := True;
Engine.Need_Paragraph := False;
end if;
if Engine.Current_Level > 0 and not Engine.Has_Item then
Engine.Output.Start_Element ("li");
Engine.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Render a link.
-- ------------------------------
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List) is
pragma Unreferenced (Doc);
procedure Render_Attribute (Name : in String;
Value : in Wiki.Strings.WString);
procedure Render_Attribute (Name : in String;
Value : in Wiki.Strings.WString) is
begin
if Name = "href" then
declare
URI : Wiki.Strings.UString;
Exists : Boolean;
begin
Engine.Links.Make_Page_Link (Value, URI, Exists);
Engine.Output.Write_Wide_Attribute ("href", URI);
end;
elsif Value'Length = 0 then
return;
elsif Name = "lang" or Name = "title" or Name = "rel" or Name = "target"
or Name = "style" or Name = "class"
then
Engine.Output.Write_Wide_Attribute (Name, Value);
end if;
end Render_Attribute;
begin
Engine.Open_Paragraph;
Engine.Output.Start_Element ("a");
Wiki.Attributes.Iterate (Attr, Render_Attribute'Access);
Engine.Output.Write_Wide_Text (Title);
Engine.Output.End_Element ("a");
end Render_Link;
-- ------------------------------
-- Render an image.
-- ------------------------------
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List) is
pragma Unreferenced (Doc);
Src : constant Strings.WString := Attributes.Get_Attribute (Attr, "src");
Alt : constant Strings.WString := Attributes.Get_Attribute (Attr, "alt");
Desc : constant Strings.WString := Attributes.Get_Attribute (Attr, "longdesc");
Class : constant Strings.WString := Attributes.Get_Attribute (Attr, "class");
Style : constant Strings.WString := Attributes.Get_Attribute (Attr, "style");
Size : constant Strings.WString := Attributes.Get_Attribute (Attr, "size");
Frame : constant Strings.WString := Attributes.Get_Attribute (Attr, "frame");
Align : constant Strings.WString := Attributes.Get_Attribute (Attr, "align");
Valign : constant Strings.WString := Attributes.Get_Attribute (Attr, "valign");
URI : Wiki.Strings.UString;
Frame_Attr : Wiki.Strings.UString;
Width : Natural := 0;
Height : Natural := 0;
begin
if Frame'Length > 0 then
Strings.Append (Frame_Attr, "wiki-img-");
Strings.Append (Frame_Attr, Frame);
end if;
if Align'Length > 0 then
if Strings.Length (Frame_Attr) > 0 then
Strings.Append (Frame_Attr, " ");
end if;
Strings.Append (Frame_Attr, "wiki-img-");
Strings.Append (Frame_Attr, Align);
end if;
if Valign'Length > 0 then
if Strings.Length (Frame_Attr) > 0 then
Strings.Append (Frame_Attr, " ");
end if;
Strings.Append (Frame_Attr, "wiki-img-");
Strings.Append (Frame_Attr, Valign);
end if;
Engine.Open_Paragraph;
if Strings.Length (Frame_Attr) > 0 then
Engine.Output.Start_Element ("div");
Engine.Output.Write_Wide_Attribute ("class", Frame_Attr);
Engine.Output.Start_Element ("div");
Engine.Output.Write_Wide_Attribute ("class", "wiki-img-inner");
end if;
if Size'Length > 0 then
Wiki.Helpers.Get_Sizes (Size, Width, Height);
end if;
Engine.Output.Start_Element ("img");
Engine.Links.Make_Image_Link (Src, URI, Width, Height);
Engine.Output.Write_Wide_Attribute ("src", URI);
if Width > 0 then
Engine.Output.Write_Attribute ("width", Util.Strings.Image (Width));
end if;
if Height > 0 then
Engine.Output.Write_Attribute ("height", Util.Strings.Image (Height));
end if;
if Desc'Length > 0 then
Engine.Output.Write_Wide_Attribute ("longdesc", Desc);
end if;
if Class'Length > 0 then
Engine.Output.Write_Wide_Attribute ("class", Class);
end if;
if Style'Length > 0 then
Engine.Output.Write_Wide_Attribute ("style", Style);
end if;
if Title'Length > 0 and Alt'Length = 0 then
Engine.Output.Write_Wide_Attribute ("alt", Title);
elsif Alt'Length > 0 then
Engine.Output.Write_Wide_Attribute ("alt", Alt);
end if;
Engine.Output.End_Element ("img");
if Strings.Length (Frame_Attr) > 0 then
Engine.Output.End_Element ("div");
if Title'Length > 0 and Frame /= "border" and Frame /= "frameless" and Frame /= "" then
Engine.Output.Start_Element ("div");
Engine.Output.Write_Wide_Attribute ("class", "wiki-img-caption");
Engine.Output.Write_Wide_Text (Title);
Engine.Output.End_Element ("div");
end if;
Engine.Output.End_Element ("div");
end if;
end Render_Image;
-- ------------------------------
-- Render a quote.
-- ------------------------------
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List) is
pragma Unreferenced (Doc);
procedure Render_Attribute (Name : in String;
Value : in Wiki.Strings.WString);
procedure Render_Attribute (Name : in String;
Value : in Wiki.Strings.WString) is
begin
if Value'Length = 0 then
return;
elsif Name = "cite" or Name = "title" or Name = "lang"
or Name = "style" or Name = "class"
then
Engine.Output.Write_Wide_Attribute (Name, Value);
end if;
end Render_Attribute;
begin
Engine.Open_Paragraph;
Engine.Output.Start_Element ("q");
Wiki.Attributes.Iterate (Attr, Render_Attribute'Access);
Engine.Output.Write_Wide_Text (Title);
Engine.Output.End_Element ("q");
end Render_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Format_Type) of Wiki.String_Access;
HTML_ELEMENT : constant String_Array_Access :=
(BOLD => HTML_BOLD'Access,
ITALIC => HTML_ITALIC'Access,
CODE => HTML_CODE'Access,
SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
SUBSCRIPT => HTML_SUBSCRIPT'Access,
STRIKEOUT => HTML_STRIKEOUT'Access,
PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if not Engine.Has_Html_Paragraph or Engine.Html_Tag = Wiki.P_TAG then
Engine.Open_Paragraph;
elsif Engine.Need_Paragraph then
Engine.Output.Write (' ');
Engine.Need_Paragraph := False;
end if;
for I in Format'Range loop
if Format (I) then
Engine.Output.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Engine.Output.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Engine.Output.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Render a text block that is pre-formatted.
-- ------------------------------
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString) is
begin
Engine.Close_Paragraph;
if Format = "html" then
Engine.Output.Write (Text);
else
Engine.Output.Start_Element ("pre");
if Format'Length > 0 then
Engine.Output.Start_Element ("code");
Engine.Output.Write_Attribute ("class", "lang-" & Strings.To_String (Format));
Engine.Output.Write_Wide_Text (Text);
Engine.Output.End_Element ("code");
else
Engine.Output.Write_Wide_Text (Text);
end if;
Engine.Output.End_Element ("pre");
end if;
end Render_Preformatted;
-- ------------------------------
-- Render a table component such as N_TABLE, N_ROW or N_COLUMN.
-- ------------------------------
procedure Render_Table (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type;
Tag : in String) is
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes);
begin
Engine.Close_Paragraph;
Engine.Need_Paragraph := False;
Engine.Has_Paragraph := False;
Engine.Open_Paragraph;
Engine.Output.Start_Element (Tag);
while Wiki.Attributes.Has_Element (Iter) loop
Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
Engine.Render (Doc, Node.Children);
Engine.Close_Paragraph;
Engine.Has_Paragraph := False;
Engine.Need_Paragraph := True;
Engine.Output.End_Element (Tag);
end Render_Table;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document) is
begin
if Engine.Enable_Render_TOC and Doc.Is_Visible_TOC then
Engine.Render_TOC (Doc, 4);
end if;
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
end Finish;
end Wiki.Render.Html;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.Time_Statistics.Coarse_Timers;
with Natools.Time_Statistics.Fine_Timers;
with Natools.Time_Statistics.Generic_Timers;
package body Natools.Time_Statistics.Tests is
generic
with package Timers is new Generic_Timers (<>);
Total_Length : in Duration;
procedure Test_Timer (Test : in out NT.Test);
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Check is new NT.Generic_Check
(Natural, "=", Natural'Image, False);
procedure Check is new NT.Generic_Check
(Duration, "=", Duration'Image, False);
procedure Test_Timer (Test : in out NT.Test) is
Stats : aliased Summary;
begin
declare
Actual_Auto : Timers.Auto_Timer (Stats'Access);
Aborted_Auto : Timers.Auto_Timer (Stats'Access);
Manual : Timers.Manual_Timer (Stats'Access);
pragma Unreferenced (Actual_Auto);
begin
Manual.Start;
Check (Test, 0, Stats.Sample_Count);
delay Total_Length / 2;
Aborted_Auto.Cancel;
Manual.Stop;
Check (Test, 1, Stats.Sample_Count, "Sample count");
Manual.Start;
delay Total_Length / 2;
Manual.Cancel;
Check (Test, 1, Stats.Sample_Count, "Sample count");
end;
Check (Test, 2, Stats.Sample_Count, "Sample count");
end Test_Timer;
procedure Coarse_Timer is new Test_Timer (Coarse_Timers, 0.2);
procedure Fine_Timer is new Test_Timer (Fine_Timers, 0.2);
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Summary_Accumulator (Report);
Coarse_Timer (Report);
Fine_Timer (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Coarse_Timer (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Coarse timer standard use");
begin
Coarse_Timer (Test);
exception
when Error : others => Test.Report_Exception (Error);
end Coarse_Timer;
procedure Fine_Timer (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Fine timer standard use");
begin
Fine_Timer (Test);
exception
when Error : others => Test.Report_Exception (Error);
end Fine_Timer;
procedure Summary_Accumulator (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Summary accumulator");
begin
declare
Stats : Summary;
begin
Stats.Add (10.1);
Stats.Add (9.9);
Check (Test, 2, Stats.Sample_Count, "Sample count");
Check (Test, 10.1, Stats.Maximum, "Maximum");
Check (Test, 9.9, Stats.Minimum, "Minimum");
Check (Test, 10.0, Stats.Mean, "Mean");
Stats.Add (10.3);
Check (Test, 3, Stats.Sample_Count, "Sample count");
Check (Test, 10.3, Stats.Maximum, "Maximum");
Check (Test, 9.9, Stats.Minimum, "Minimum");
Check (Test, 10.1, Stats.Mean, "Mean");
end;
exception
when Error : others => Test.Report_Exception (Error);
end Summary_Accumulator;
end Natools.Time_Statistics.Tests;
|
package body Parent.Child is
function create return Domain_Member is
begin
return 0;
end create;
end Parent.Child;
|
generic
type Tipus_Element is private;
package pilas is
Memoria_Agotada : exception;
type Pila is limited private;
procedure Pila_Buida
(P : out Pila);
function Es_Buida
(P : Pila) return Boolean;
procedure Cim
(P : in Pila;
Element : out Tipus_Element);
procedure Empilar
(P : in out Pila;
Element : in Tipus_Element);
procedure Desempilar
(P : in out Pila);
procedure Destruir
(P : in out Pila);
private
type Component;
type Pila is access Component;
end pilas;
|
-- PACKAGE Extended_Real
--
-- package Extended_Real provides:
-- An arbitrary precision floating-point data type: e_Real.
--
-- Lower limit on precision is 28 decimals. No upper limit is
-- enforced. All internal arithmetic is done on 64-bit Integers,
-- so it's most efficient on 64-bit CPU's. The package is Pure.
-- Floating point attributes (Ada 95) are implemented as function
-- calls. The package exports standard floating point operators:
-- "*", "+", "/", "**", "Abs", "<", ">", "<=" , ">=", etc.
-- The standard operators make it easy to modify existing code to
-- use extended precision arithmetic. Procedure calls Mult(X,Y) and
-- Square(X) are also provided. They do multiplication "in-place",
-- (overwrite X with the result) and are somewhat faster than the
-- equivalent X := X*Y, and X := X*X.
--
-- To set the precision search below for:
--
-- Desired_Decimal_Digit_Precision
--
-- package Extended_Real.Elementary_Functions provides:
-- Sin, Cos, Sqrt, Arcsin, Arccos, Arctan, Log, Exp, Reciprocal (1/x),
-- Reciprocal_Nth_Root (x to the power of -1/N), Divide, and "**" for
-- e_Real arguments and e_Real exponents. Routines are Ada 95'ish.
--
-- package e_Derivs provides:
-- Extended precision routines for taking high order derivatives of
-- functions. Functions made from "*", "+", "/", "**", Sin, Cos,
-- Sqrt, Arcsin, Arccos, Arctan, Log, Exp, Compose = f(g(x)),
-- and Reciprocal can be differentiated to order specified by user.
--
-- package Extended_Real.IO provides:
-- Text to extended-precision e_Real translation routines, and
-- e_Real to Text translation routines.
--
-- package Extended_Real.Rand provides:
-- a (very) basic Random Number Generator. Really just for making
-- test vectors.
--
-- procedure e_real_demo_1.adb is:
-- an introductory routine that demonstrates use of Extended_Real.
--
-- procedure e_function_demo_1.adb is:
-- an introductory routine that demonstrates use of
-- Extended_Real.Elementary_Functions.
--
-- procedure e_jacobi_eigen_demo_1.adb demonstrates:
-- extended-precision eigen-decomposition on Hilbert's matrix using
-- package e_Jacobi_Eigen.
--
-- package e_Jacobi_Eigen is:
-- a Jabobi iterative eigen-decomposition routine
-- that shows how easy it is to upgrade a floating point routine
-- to extended precision. e_Jacobi_Eigen uses package Extended_Real.
--
-- good optimization on gcc/GNAT:
-- -gnatNp -O3 -march="your machine architecture" -funroll-loops -ffast-math
-- (sometimes:-ftree-vectorize -funroll-all-loops -falign-loops=4,
-- -falign-loops=3, or -frename-registers are worth trying.)
--
-- latest GNAT (gcc 4.3) try
-- gnatmake -gnatNp -O3 -march=native -mtune=native -funroll-loops -ffast-math
--
-- Always do a preliminary run which exercizes Assertions, and other Checks:
-- -gnato -gnatV -gnata
--
--
-- Because precision is arbitrary, Extended_Real is not specially
-- optimized for any particular precision. The chosen design works best
-- in the limit of 100's of decimal digits. If the package had been
-- designed for 32 decimal digits of precision, then almost every feature
-- of the design would have been different. On the other hand, performance
-- seems to be respectable on 64-bit CPU's even at the lower limit (eg
-- 28 or 38 decimal digits). (Comparison is with Intel's machine-optimized
-- 32 decimal-digit floating point: i.e. Intel Fortran Real*16 on an Intel
-- 64-bit CPU.) 32 digit floating point is probably the most often used
-- (and most often needed) extended precision floating point.
-- Most Fortrans (including the gcc Fortran) don't offer anything higher
-- than 18 digit floating point.
--
-- Common applications:
-- 0. Estimation of error in lower precision floating-point calculations.
-- 1. Evaluation of constants for math routines and Table-driven algorithms.
-- 2. Evaluation of series solutions of special function, especially when
-- the terms are constructed of large factorials and exponentials.
-- 3. Evaluation of recurrance relations for special functions.
--
-- Generics greatly reduce the work you have to do in modifying programs
-- to use extended floating point:
--
-- 1. place generic formal declarations
-- of the required extended arithmetic functions at the the top of the
-- package or subprogram to be modified.
--
-- 2. use the unary "-" and "+" routines that convert Real to Extended:
--
-- so that declarations
-- Number : Generic_Formal_Type := +1.234;
-- and statements like
-- Z := (+4.567834E+012) * X;
-- will be acceptible to both Real and Extended types.
--
-- Underflows to Zero. Overflows to Positive or Negative infinity. I am
-- still trying to decide if the Infinities are worth the trouble, but the
-- trouble isn't great and there seem to be benefits. Sometimes you can
-- put off worrying about overflow in intermediate calculation and test
-- for it at the end by testing for Positive_Infinity. There are no NaNs.
--
-- At the expense of purity, error messages using text_io can be
-- re-enabled in the body - see top of body of Extended_Real.
--
--***************************************************************************
--
-- SECTION I.
--
-- Constants and overflow/underflow/constraint_error conventions.
--
-- To test an arbitrary X : e_Real to see if X is Zero or infinity use the
-- function Are_Equal (X, Zero) etc. It's written to make the test efficient.
--
-- Underflows are to (unsigned) Zero; overflows to (signed) infinity:
--
-- Infinity here means a finite number that is too large to represent
-- in the floating point, and whose inverse is too small to represent in
-- floating point. The following conventions seemed sensible. Treat inf's
-- as Constraint Errors if uneasy with them. Assuming X is a positive e_Real:
-- 0*inf = 0, inf * inf = inf, X / inf = 0, |X| * -inf = -inf,
-- inf + inf = inf, X + inf = inf, -inf * inf = -inf, X - inf = -inf,
-- inf > X = True, -inf < X = True, inf > -inf = True,
-- (inf = -inf) = False
--
-- Constraint_Error:
--
-- The following ops have no sensible meaning, so Constraint_Error (ce) is
-- raised.
-- inf - inf => ce, inf / inf => ce, X / 0 => ce, inf / 0 => ce,
-- inf < inf => ce.
--
--***************************************************************************
-- SECTION II.
--
-- Standard arithmetic operators.
--
-- The arithmetic performed by these routines is supposed to be correct out
-- to the number of decimals specified by Desired_Decimal_Digit_Precision,
-- which you type in at the beginning of the spec. But the arithmetic is
-- actually performed on digits well beyond this limit in order to guarantee
-- this level of accuracy. The values
-- held by these extra digits (guard digits) are usually almost correct.
-- None of the following operators rounds away these guard digits.
-- Rounding is done explicitly by calling Round_Away_Smallest_Guard_Digit().
-- In particular, none of the following comparison operators ("<", ">=", etc.)
-- rounds away guard digits of operands before performing the comparison.
-- All of them perform their comparisons out to the final guard digit.
-- To reduce much confusion, I decided to leave rounding entirely up to the
-- user, with Round_Away_.... Whether it's best to round or not
-- depends on the algorithm. In a lot of algorithms it's better to
-- round before you use the "Are_Equal" operator, and better not to round
-- when you use the "<" and ">" operators.
--
-- "=" or Are_Equal(X, Zero) is the most efficient way to find out if X
-- is Zero. Same for Infinity. X < Zero is the efficient way find Sign of X.
-- X > Zero is efficient way to test positivity of X. Zero < X and
-- Zero > X are also handled efficiently.
--
--***************************************************************************
-- SECTION III.
--
-- Routines for conversion from Real to e_Real and back again.
--
-- Makes it easy to write generics that can be instantiated with either
-- conventional floating point of this extended floating point.
-- The unary + and - are here to make it easier to convert programs from
-- ordinary floating point to extended, by making it easy to replace
--
-- X : Generic_Float_Type := 1.2345; --here instantiate w/ Float.
-- X := 4.5678 * Y; --here instantiate w/ Float.
--
-- with
--
-- X : Generic_Float_Type := +1.2345; --here instantiate w/ e_Real or Float.
-- X := (+4.5678) * Y; --same here.
--
-- Now you can instantiate the generic with either e_Real or Float,
-- (but you have to add the unary "+" to the list of generic formals.)
--
--***************************************************************************
-- SECTION V.
--
-- Real * Extended operations.
--
-- More efficient operations. The "Real" is not your ordinary real, but
-- something in the range 0.0 .. Radix-1, and integer valued, though it
-- can have an negative or positive exponent. So it's not very appropriate
-- for general use;
--
-- The Real * Extended operations can be particularly efficient if
-- the Real number is in the same range as a Digit, ie, 0..Radix-1.
-- So we define a type e_Digit, a single real number with an
-- exponent. These mixed multiplication "*" and "/" ops are used by the
-- ascii to real_extended and real_extended to ascii translators,
-- and by Newton's method calculations of elementary functions.
-- This efficiency only comes if the real number can be represented by
-- a single digit: integer values in the range 0..Radix-1, (times
-- an exponent in a power-of-2 Radix. e.g. 0.5 is OK, 1.0/3.0 is not.)
-- Make_e_Digit will raise a constraint error if the range of the
-- intended real number is wrong.
--
--**********************************************************************
-- INTERNAL FORMAT OF e_Real
--
-- Internally the extended numbers are stored in such a way that the
-- value of e_Real number X is
--
-- Max
-- X = Radix**Exp * SUM {Radix**(-I) * Digit(I)}.
-- I=0
--
-- Externally, the user sees e_Real (via the Exponent, and Fraction
-- attribute functions) as tho' it were normalized. In other words, the
-- value of X is
--
-- Max
-- X = Radix**Exp * SUM {Radix**(-I-1) * Digit(I)}
-- I=0
--
-- Exp is called the "normalized" exponent. If Exp is the normalized exponent
-- then, say, a binary number would be written:
--
-- 0.111011010001 * 2**(Exp).
--
-- In other words the first binary digit in the mantissa is of power 2**(-1).
-- It is important to know this because the function Real'Exponent(x) returns
-- the *normalized* exponent, and the function Real'Fraction(x) returns
-- x * 2**(-Exp) where Exp is the normalized exponent. So in the above case,
-- 'Fraction would return 0.111011010001.
-- Also, in normalized form, the first binary digit of the mantissa is always
-- non-zero.
--***************************************************************************
generic
type Real is digits <>;
-- Make it 15 digits or greater. This is checked.
-- This is usually the type you are going to replace with e_Real.
package Extended_Real is
pragma Pure (Extended_Real);
pragma Assert (Real'Digits >= 15);
type e_Real is private; -- The extended precision floating pt type.
-- Instructions:
-- The only things that need to be adjusted by the user are
--
-- Desired_Decimal_Digit_Precision
-- and
-- Desired_No_Of_Bits_In_Radix
--
-- The 2 parameters follow next, along with instructions.
Desired_Decimal_Digit_Precision : constant := 28;
-- If you request 28 Decimal Digits, you usually get 29 or more.
-- If you request 29 to 37 Decimal Digits, you usually get 38 or more.
-- If you request 38 to 46 Decimal Digits, you usually get 47 or more.
-- If you request 47 to 55 Decimal Digits, you usually get 56 or more.
-- (And so on, in jumps of 9. Assumes Desired_No_Of_Bits_In_Radix = 30.)
--
-- The simple operators "*", "+", "/" usually give the best precision.
-- They should get the 1st guard digit right, and by themselves:
-- If you request 28 Decimal Digits, they're good to about 37 Decimal Digits.
-- If you request 37 Decimal Digits, they're good to about 46 Decimal Digits.
--
-- Large complicated floating point computations will usually get both
-- guard digits wrong and additional error will accumulate, so:
-- If you request 28 Decimal Digits, ultimately expect <28 Decimal Digits.
--
-- Lower limit on Desired_Decimal_Digit_Precision is 28.
pragma Assert (Desired_Decimal_Digit_Precision >= 28);
Desired_No_Of_Bits_In_Radix : constant := 30;
-- Anything under 31 works, but should be adjusted for best performance:
-- 30 is good if Desired_Decimal_Digit_Precision is 28 to 55.
-- 29 is good standard setting (use it when Desired_Decimal_Digit_Precision > 55).
-- 28 is good if Desired_Decimal_Digit_Precision >> 200. (But experiment.)
--
-- 30 is necessary if you want the minimum decimal digits setting: 28.
-- (If you choose 29 bits in Radix, you will get more decimals than you expect.)
pragma Assert (Desired_No_Of_Bits_In_Radix <= 30);
type e_Int is range -2**31+1 .. 2**31-1;
subtype e_Integer is e_Int'Base;
-- Type of Exponent. Also takes the place of Universal_Integer in the
-- "attribute" functions defined below for e_Real.
-- Keep it 32-bit. Smallest usually fastest.
pragma Assert (e_Integer'Size <= 32);
-- try fit e_Reals into small space; not essential, but Larger is slower.
Zero : constant e_Real;
One : constant e_Real;
Positive_Infinity : constant e_Real;
Negative_Infinity : constant e_Real;
-- To test an arbitrary X : e_Real to see if X is Zero or infinity use the
-- function: Are_Equal (X, Zero), or X = Zero etc. Testing for Zero is fast.
-- Infinity here means a finite number that is too large to represent in the
-- floating point, and whose inverse is too small to represent in floating
-- point Zero is positive.
-- SECTION II. Standard operators.
--
-- To reduce much confusion, rounding is entirely up to the
-- user, with Round_Away_Guard_Digits(). Whether it's best to round or not
-- depends on the algorithm. For example, in some cases it is better to
-- round before you use the "Are_Equal" operator, and better not to round
-- when you use the "<" and ">" operators. (see intro.)
function "*" (X, Y : e_Real) return e_Real; -- inline can slow it down.
function "+" (X, Y : e_Real) return e_Real; -- inline can slow it down.
function "-" (X, Y : e_Real) return e_Real;
function "+" (X : e_Real) return e_Real;
function "-" (X : e_Real) return e_Real;
function "/" (X, Y : e_Real) return e_Real;
function "**"(X : e_Real;
N : Integer) return e_Real;
procedure Square (X : in out e_Real);
-- Same as X := X * X; (but usually faster if < 120 decimal digits.)
procedure Mult
(X : in out e_Real;
Y : in e_Real);
-- Same as X := X * Y; (but usually faster if < 120 decimal digits.)
function "Abs" (X : e_Real) return e_Real;
function Are_Equal (X, Y : e_Real) return Boolean;
-- Return true only if
-- equality is exact in the cases of Zero and the 2 infinities.
-- Are_Equal(X, Zero) is the most efficient way to find out if X is Zero.
-- Same for Infinity. X < Zero is the efficient way find Sign of X.
-- X > Zero is efficient way to test positivity of X. Zero < X etc. OK too.
function "<" (X, Y : e_Real) return Boolean;
function "<=" (X, Y : e_Real) return Boolean;
function ">" (X, Y : e_Real) return Boolean;
function ">=" (X, Y : e_Real) return Boolean;
function "=" (X, Y : e_Real) return Boolean renames Are_Equal;
function Are_Not_Equal (X, Y : e_Real) return Boolean; -- not Are_Equal
-- SECTION III. Conversions between Real to e_Real. (see intro.)
function Make_Real (X : e_Real) return Real;
function Make_Extended (X : Real) return e_Real;
function "+" (X : Real) return e_Real renames Make_Extended;
function "-" (X : Real) return e_Real;
-- The above 3 functions are identical, except "-" changes sign of X.
-- Makes it easy to write generics that can be instantiated with either
-- conventional floating point of this extended floating point, via:
-- X : Generic_Float_Type := +1.2345;
function "+" (X : Integer) return e_Real;
-- Only works in range of Real (15 digits usually).
--
-- raises Constraint_Error
--
-- if X is greater than about 10**Real'Digits.
-- So X = 2**62 raises Constraint_Error if Real'Digits = 15.
-- It's really just for making e_Reals out of small ints: +7.
-- SECTION IV. Ada9X oriented attributes.
--
-- Below: Machine attributes and the function calls (like Truncation).
-- More information on the machine model is given in the introduction.
-- The machine model is static, so none of the Machine oriented attributes,
-- and none of the functions reflect varying precision. (see intro.)
--
-- Written in the spirit of the Ada attributes, but the fit is never
-- perfect.
function Remainder (X, Y : e_Real) return e_Real;
function Copy_Sign (Value, Sign : e_Real) return e_Real;
function e_Real_Machine_Rounds return Boolean;
function e_Real_Machine_Overflows return Boolean;
function e_Real_Signed_Zeros return Boolean;
function e_Real_Denorm return Boolean;
-- These functions always return False.
function e_Real_Machine_Emax return e_Integer;
function e_Real_Machine_Emin return e_Integer;
function e_Real_Machine_Mantissa return e_Integer;
-- Always returns Mantissa'Length: all the digits including guards.
--
-- NOT binary digits, NOT decimal digits.
function e_Real_Machine_Radix return Real;
-- Usually 2.0**29 or 2.0**30 for Integer digits; 2.0**24 for Flt pt digits.
-- Returns: No_of_Bits_in_Radix (as a Real type).
function Leading_Part (X : e_Real;
Radix_Digits : e_Integer) return e_Real;
-- Example: to set to zero all but the first digit of X use
-- First_Digit := Leading_Part (X, 1);
function Exponent (X : e_Real) return e_Integer;
-- By convention return 0 for Zero. Else return nomalized Expon.
-- Returns Max_Exponent+2 for the 2 infinities.
-- NOT decimal, and NOT binary Exponent.
function Fraction (X : e_Real) return e_Real;
function Compose (Fraction : e_Real;
Exponent : e_Integer) return e_Real;
function Scaling ( X : e_Real;
Adjustment : e_Integer) return e_Real;
-- Chop off fractional parts.
--
-- Rounding, Unbiased_Rounding, Ceiling, Floor return e_Real
-- with Zero fractions.
function Rounding (X : e_Real) return e_Real;
function Unbiased_Rounding (X : e_Real) return e_Real;
function Truncation (X : e_Real) return e_Real;
function Ceiling (X : e_Real) return e_Real;
function Floor (X : e_Real) return e_Real;
-- Round away guard digits.
--
-- function Machine rounds away the smallest Guard digit.
-- There's no one right way to round away Guard Digits or choose
-- Model_Epsilon's. Doesn't follow the Ada95 model for rounding
-- 64-bit floats. That model doesn't seem to fit very well.
function e_Real_Model_Epsilon return e_Real;
-- At present this calls: e_Real_Model_Epsilon_2 which is
-- 1 unit in the 3rd smallest digit. (The 3rd smallest digit
-- is the 1st digit that is larger than the 2 guard digits.)
function e_Real_Machine_Epsilon return e_Real;
-- At present this calls: e_Real_Model_Epsilon_1 which is
-- 1 unit in the 2nd smallest digit. (The 2nd smallest digit
-- is the larger of the 2 guard digits.)
function Machine (X : e_Real) return e_Real;
-- This calls:
-- Round_Away_Smallest_Guard_Digit
--
function Round_Away_Smallest_Guard_Digit (X : e_Real) return e_Real;
function e_Real_Model_Epsilon_1 return e_Real;
-- One unit in the 2nd smallest digit.
function e_Real_Model_Epsilon_2 return e_Real;
-- One unit in the 3rd smallest digit. (The smallest digit that
-- is *not* a Guard_Digit.
--
-- Guard_Digits = 2 always; assume neither of them is correct:
-- if there's 3 digits of Radix 2^30 then eps_2 is 2^(-30).
-- if there's 4 digits of Radix 2^30 then eps_2 is 2^(-60).
-- if there's 5 digits of Radix 2^30 then eps_2 is 2^(-90) or about 10**-27.
--
-- So Eps_2 is the smallest number s/t eps_2+.999999999999 /= .999999999999
-- when you remove both guard digits.
-- SECTION V. Digit * Extended operations.
--
-- More efficient operations. "Digit" is not your ordinary real, but
-- something in the range 0.0 .. Radix-1.0, and integral valued, though it
-- can have a negative exponent. So the following is not very appropriate
-- for general use; in the '83 version we export it so that it can be used by
-- elementary function packages.
type e_Digit is private;
function "*" (X : e_Digit; Y : e_Real) return e_Real;
function "/" (X : e_Real; Y : e_Digit) return e_Real;
function Sum_Of (X : e_Digit; Y : e_Real) return e_Real;
function "+" (X : e_Digit; Y : e_Real) return e_Real renames Sum_Of;
function Scaling (X : e_Digit; Adjustment : e_Integer) return e_Digit;
-- Multiply X by Radix**N where N = Adjustment.
function Make_Extended (X : e_Digit) return e_Real;
function Make_e_Digit (X : Real) return e_Digit;
-- X must be a whole number: 0.0, 1.0, 2.0 etc. in the range 0..Radix-1,
-- times some integer power of the Radix. So 0.5 is OK, but not 1/3.
function Number_Of_Guard_Digits return e_Integer;
-- Constant. To get number of digits that are being correctly calculated
-- (by conservative estimates) use
-- No_Correct_Digits = Present_Precision - Number_Of_Guard_Digits.
function Minimum_No_Of_Digits_Allowed return e_Integer;
-- Constant. Includes guard digits.
private
--
-- SECTION VII. Make the Data structure for e_Real.
--
-- Using 32-bit ints for the Digits: (don't do it)
--No_Of_Usable_Bits_In_Digit : constant := 31; -- bad idea; lots of trouble.
--No_Of_Bits_In_Radix : constant := 13; -- can't use 14 or >
-- Using 64-bit floats for the Digits: (don't bother)
--No_Of_Usable_Bits_In_Digit : constant := 53; -- if using flt pt Mantissa (slow)
--No_Of_Bits_In_Radix : constant := 24;
-- Using 64-bit ints for the Digits:
No_Of_Usable_Bits_In_Digit : constant := 63; -- Integer; must allow neg. vals
No_Of_Bits_In_Radix : constant := Desired_No_Of_Bits_In_Radix;
-- 30 is good if Desired_Decimal_Digit_Precision is 28 to 55.
-- 29 is good standard setting (especially: Desired_Decimal_Digit_Precision > 55).
-- 28 is good if Desired_Decimal_Digit_Precision is in the 100's. (But experiment.)
Sums_Per_Carry : constant := 2**(No_Of_Usable_Bits_In_Digit-2*No_Of_Bits_In_Radix)-1;
-- Sums_Per_Carry : This is number of sums you can accumulate during
-- multiplication before the carrys need to be performed.
--
-- You can do a large number of X*Y < Radix*Radix products, and then sum
-- (Sums_Per_Carry+1) of them before a Carry is necessary in multiplication.
-- a implies b is same as not (a) or b:
pragma Assert (not (No_Of_Bits_In_Radix = 30) or Sums_Per_Carry <= 8-1);
pragma Assert (not (No_Of_Bits_In_Radix = 29) or Sums_Per_Carry <= 32-1);
pragma Assert (not (No_Of_Bits_In_Radix = 28) or Sums_Per_Carry <= 128-1);
pragma Assert (not (No_Of_Bits_In_Radix = 27) or Sums_Per_Carry <= 512-1);
pragma Assert (not (No_Of_Bits_In_Radix = 26) or Sums_Per_Carry <= 2048-1);
--
-- Now that we know: No_Of_Bits_In_Radix,
--
-- get number of binary digits and extended digits needed to make e_Real.
-- Use the following formula for the number of Binary digits needed
-- to meet Desired Decimal Digit precision D:
--
-- Binary_Digits >= Ceiling (D * Log_Base_2_Of_10) + 1
--
-- where D = Desired_Decimal_Digit_Precision, and
-- where Log_Base_2_Of_10 = 3.321928094887362.
-- Ceiling of Real numbers with static declarations?
--
-- Ceiling (3.321928094887 * D) <= Ceiling (3.322 * D)
-- = Ceiling((3322.0 * D) / 1000.0)
-- = (3322 * D - 1) / 1000 + 1
-- D is integer valued, so use integer Ceiling (A / B) = (A - 1) / B + 1.
-- (for positive A). The above
-- steps give us the number of binary digits required: No_Of_B_Digits.
-- Next: min number of Radix 2.0**No_Of_Bits_In_Radix digits: No_Of_e_Digits.
-- To get No_Of_e_Digits divide by No_Of_Bits_In_Radix and take the Ceiling.
--
-- B is for binary, E for extended:
ILog_Base_2_Of_10_x_1000 : constant := 3322; -- Round UP.
D : constant := Desired_Decimal_Digit_Precision - 2;
No_Of_B_Digits : constant := (ILog_Base_2_Of_10_x_1000 * D - 1) / 1000 + 2;
No_Of_e_Digits : constant := (No_Of_B_Digits - 1) / No_Of_Bits_In_Radix + 1;
--
-- The following parameter settings give us 2 more words in the Mantissa
-- than required. These two are essential in getting the full desired
-- precision in extensive floating pt calculation, and also in IO, and in
-- functions that are evaluated by Newton's method.
-- (At least one such guard digit is essential anyway, to compensate for
-- leftward shift of the mantissa during normalization.)
-- The index of the digits is a subtype of the Exponent type because
-- there are frequent conversions between the two.
--
-- An assertion verifies that there are 2 guard digits.
--
-- e_Integer is used as the type of the index of the extended digits
-- because e_Integer is the type of the exponent (defined below).
-- There's a close relationship between the exponent of the number and the
-- index of the digits of the number. (They are often scaled
-- simultaneously, there is a relationship between their ultimate ranges,
-- so they are given the same type here.)
-- Log_Base_2_Of_10 : constant := 3.321928094887362;
--
No_Of_Guard_Digits : constant := 2;
-- Guard_Digits are extra digits of precision at the end of the mantissa.
--
-- The 2nd Guard_Digit makes
-- the Elementary Math Functions full precision (or almost full).
-- Also the IO routines need 2 Guard_Digits.
pragma Assert (No_Of_Guard_Digits = 2);
-- The following are not decimal digits.
Ultimate_Correct_Digit : constant e_Integer := No_Of_e_Digits - 1;
Ultimate_Digit : constant e_Integer := No_Of_Guard_Digits + Ultimate_Correct_Digit;
subtype Digits_Base is e_Integer range 0..Ultimate_Digit+1;
subtype Digit_Index is Digits_Base range 0..Ultimate_Digit;
pragma Assert (Digit_Index'First = 0);
-- some of the arithmetic in "+" assumes this.
-- The following are not decimal digits.
Min_No_Of_Correct_Digits : constant := 3;
-- Things stop working if this is less than 3.
Min_No_Of_Digits : constant := Min_No_Of_Correct_Digits + 2;
-- The 2 is the min number of guard digits.
pragma Assert (Ultimate_Digit >= Min_No_Of_Digits - 1);
pragma Assert (Ultimate_Digit >= Min_No_Of_Correct_Digits+No_Of_Guard_Digits-1);
-- Digits go from 0..Ultimate_Digit
Max_Exponent : constant e_Integer := 2 ** (e_Integer'Size - 5);
Min_Exponent : constant e_Integer := -Max_Exponent;
-- The exponent is usually 16 or 32 bit int. Limits on its range are set
-- below what the base type allows: no more than 1/4 the dynamic range
-- of the base type. If we use 1/8 of that limit, it allows us to delay
-- overflow check to end of most routines (except "**"). If we use 1/32
-- of that limit, it allows us to do IO more simply. So to make
-- IO work, at present the requirement is 2 ** (e_Integer'Size - 5).
pragma Assert (Max_Exponent <= 2 ** (e_Integer'Size - 5));
-- function e_Real_Machine_Emin returns Min_Exponent
-- function e_Real_Machine_Emax returns Max_Exponent
--subtype Digit_Type is Real;
-- Can use Floats with 53 bit mantissas as Digit_Type. Make 2 changes
-- above (search for No_Of_Usable_Bits_In_Digit and follow instructions)
-- and 2 changes in body (compiler will tell you where). Also comment
-- out next 3 statements. Amazingly, it worked nicely last time I did it.
-- It's slow, and it only makes sense when 64 bit ints are bad or missing.
type D_Type is range -2**63+1 .. 2**63-1;
subtype Digit_Type is D_Type'Base;
-- Must allow negative digits. Use 64 bit Integer.
pragma Assert (Digit_Type'Last = 2**(Digit_Type'Size-1)-1);
pragma Assert (Digit_Type'Size-1 >= No_Of_Usable_Bits_In_Digit);
Digit_Zero : constant Digit_Type := Digit_Type (0);
Digit_One : constant Digit_Type := Digit_Type (1);
Digit_Two : constant Digit_Type := Digit_Type (2);
Digit_Radix : constant Digit_Type := Digit_Two**No_Of_Bits_In_Radix;
Half_Radix : constant Digit_Type := Digit_Two**(No_Of_Bits_In_Radix-1);
Digit_Radix_Squared : constant Digit_Type := Digit_Radix * Digit_Radix;
Digit_Radix_Minus_1 : constant Digit_Type := Digit_Radix - Digit_One;
type Mantissa is array (Digit_Index) of Digit_Type;
type e_Real is record
Digit : Mantissa := (others => Digit_Zero);
Exp : e_Integer := 0;
Is_Zero : Boolean := True;
Is_Positive : Boolean := True;
Is_Infinite : Boolean := False;
end record;
--for e_Real'Size use (Digit_Type'Size*Mantissa'Length + e_Integer'Size*2);
-- Make e_Real'Size Integer number of 64-bit words. Usually doesn't matter.
-- Only for integer Digit_Type. Comment out for Float. pt. Digit types.
Zero : constant e_Real
:= e_Real' ((others => Digit_Zero), 0, True, True, False);
One : constant e_Real
:= e_Real' ((0 => Digit_One, others => Digit_Zero), 0, False, True, False);
Positive_Infinity : constant e_Real
:= e_Real' ((others => Digit_Zero), Max_Exponent+4, False, True, True);
Negative_Infinity : constant e_Real
:= e_Real' ((others => Digit_Zero), Max_Exponent+4, False, False, True);
-- For efficiency, we need an optimized (Real * Extended)
-- operation. So define type e_Digit, a single real number with
-- an exponent. It's a real number that's restricted to integral values
-- in the range to 0..Radix-1.
type e_Digit is record
Digit : Digit_Type := Digit_Zero;
Exp : e_Integer := 0;
Is_Zero : Boolean := True;
Is_Positive : Boolean := True;
end record;
-- Constants used in body. Real is used for easy communication with e_Real.
Real_Zero : constant Real := Real (0.0);
Real_One : constant Real := Real (1.0);
Real_Radix : constant Real := 2.0**No_Of_Bits_In_Radix;
Radix_Minus_1 : constant Real := 2.0**No_Of_Bits_In_Radix - 1.0;
Radix_Squared : constant Real := 2.0**(2*No_Of_Bits_In_Radix);
Inverse_Radix : constant Real := 2.0**(-No_Of_Bits_In_Radix);
Inverse_Radix_Squared : constant Real := Inverse_Radix * Inverse_Radix;
end Extended_Real;
|
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, not taking more than you give.
--
with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Ada.Command_Line;
with Ada.Exceptions;
with Types;
with Setup;
with Options;
with Command_Line;
with Sessions;
with Rules;
with Symbols;
with Symbols.IO;
with Parsers;
with Exceptions;
with Reports;
with States;
with Builds;
with Debugs;
procedure Cherry_Program is
procedure Put_Blessing;
procedure Put_Help;
procedure Put_Version;
procedure Put_Statistics (Session : in Sessions.Session_Type);
procedure Put_Blessing is
use Ada.Text_IO;
begin
Put_Line ("The author disclaims copyright to this source code. In place of");
Put_Line ("a legal notice, here is a blessing:");
New_Line;
Put_Line (" May you do good and not evil.");
Put_Line (" May you find forgiveness for yourself and forgive others.");
Put_Line (" May you share freely, not taking more than you give.");
New_Line;
end Put_Blessing;
procedure Put_Help is
begin
null; -- Handled by GNAT.Command_Line
end Put_Help;
procedure Put_Version
is
use Ada.Text_IO, Setup;
Version : constant String := Get_Program_Name & " (" & Get_Program_Version & ")";
Build : constant String := "Build (" & Get_Build_ISO8601_UTC & ")";
begin
Put_Line (Version);
Put_Line (Build);
New_Line;
end Put_Version;
procedure Put_Statistics (Session : in Sessions.Session_Type)
is
procedure Stats_Line (Text : in String;
Value : in Integer);
procedure Stats_Line (Text : in String;
Value : in Integer)
is
use Ada.Text_IO;
package Value_IO is
new Ada.Text_IO.Integer_IO (Integer);
Line : String (1 .. 35) := (others => '.');
begin
Value_IO.Default_Width := 5;
Line (Line'First .. Text'Last) := Text;
Put (" ");
Put (Line);
Put (" ");
Value_IO.Put (Value);
New_Line;
end Stats_Line;
subtype Symbol_Index is Types.Symbol_Index;
use type Symbol_Index;
Num_Non_Terminal : constant Symbol_Index :=
Session.Num_Symbol - Session.Num_Terminal;
begin
Ada.Text_IO.Put_Line ("Parser statistics:");
Stats_Line ("terminal symbols", Integer (Session.Num_Terminal));
Stats_Line ("non-terminal symbols", Integer (Num_Non_Terminal));
Stats_Line ("total symbols", Integer (Session.Num_Symbol));
Stats_Line ("rules", Integer (Session.Rule.Length));
Stats_Line ("states", Integer (Session.Num_X_State));
Stats_Line ("conflicts", Session.Num_Conflict);
Stats_Line ("action table entries", Session.Num_Action_Tab);
Stats_Line ("lookahead table entries", Session.Num_Lookahead_Tab);
Stats_Line ("total table size (bytes)", Session.Table_Size);
end Put_Statistics;
use Ada.Command_Line;
Parse_Success : Boolean;
begin
Command_Line.Parse (Parse_Success);
if not Parse_Success then
Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
if Options.Show_Version then
Put_Version;
Put_Blessing;
return;
end if;
if Options.Show_Help then
Put_Help;
return;
end if;
Options.Set_Language;
declare
use Ada.Strings.Unbounded;
use Ada.Text_IO;
use Symbols;
use Rules;
Session : aliased Sessions.Session_Type;
Failure : Ada.Command_Line.Exit_Status renames Ada.Command_Line.Failure;
Dummy_Symbol_Count : Types.Symbol_Index;
begin
Session := Sessions.Clean_Session;
Session.Error_Cnt := 0;
-- Initialize the machine
Symbols.Symbol_Init;
States.Initialize;
Session.Argv0 := To_Unbounded_String (Options.Program_Name.all);
Session.File_Name := To_Unbounded_String (Options.Input_File.all);
Session.Basis_Flag := Options.Basis_Flag;
Session.No_Linenos_Flag := Options.No_Line_Nos;
-- Extras.Symbol_Append (Key => "$");
declare
Dummy : constant Symbol_Access := Create ("$");
begin
null;
end;
-- Parse the input file
Parsers.Parse (Session);
if Session.Error_Cnt /= 0 then
Ada.Command_Line.Set_Exit_Status (Failure);
return;
end if;
if Session.Rule.Is_Empty then
Put_Line (Standard_Error, "Empty grammar.");
Ada.Command_Line.Set_Exit_Status (Failure);
return;
end if;
Session.Error_Symbol := Find ("error");
-- Count and index the symbols of the grammar
declare
Dummy : constant Symbol_Access := Create ("{default}");
begin
null;
end;
if Options.Debug_Level > 0 then
Ada.Text_IO.Put_Line ("debug_dump_symbols before sort");
Symbols.IO.JQ_Dump_Symbols (Session, Mode => 0);
end if;
Symbols.Sort;
if Options.Debug_Level > 0 then
Ada.Text_IO.Put_Line ("debug_dump_symbols after sort");
Symbols.IO.JQ_Dump_Symbols (Session, 0);
end if;
declare
Symbol_Count : Natural;
Terminal_Count : Natural;
begin
Symbols.Count_Symbols_And_Terminals (Symbol_Count => Symbol_Count,
Terminal_Count => Terminal_Count);
Session.Num_Symbol := Types.Symbol_Index (Symbol_Count);
Session.Num_Terminal := Types.Symbol_Index (Terminal_Count);
if Options.Debug_Level > 0 then
Ada.Text_IO.Put ("nsymbol:" & Natural'Image (Symbol_Count));
Ada.Text_IO.Put (" nterminal:" & Natural'Image (Terminal_Count));
Ada.Text_IO.Put_Line (" ");
end if;
end;
if Options.Debug_Level > 0 then
Ada.Text_IO.Put_Line ("debug_dump_rules first");
Debugs.JQ_Dump_Rules (Session, 0);
end if;
-- Assign sequential rule numbers. Start with 0. Put rules that have no
-- reduce action C-code associated with them last, so that the switch()
-- statement that selects reduction actions will have a smaller jump table.
Rules.Assing_Sequential_Rule_Numbers (List => Session.Rule);
-- Session.Num_Rule_With_Action := i;
-- lem.nruleWithAction = i;
-- Insert from lemon.c 3.32.3
-- Not sure is should go into Assing_Sequential_Rule_Numbers
if Options.Debug_Level > 0 then
Ada.Text_IO.Put_Line ("debug_dump_rules second");
Debugs.JQ_Dump_Rules (Session, 0);
end if;
Session.Start_Rule := Session.Rule.First;
Rule_Sort (Session.Rule);
if Options.Debug_Level > 0 then
Ada.Text_IO.Put_Line ("debug_dump_rules third");
Debugs.JQ_Dump_Rules (Session, 0);
end if;
-- Generate a reprint of the grammar, if requested on the command line
if Options.RP_Flag then
Reports.Reprint (Ada.Text_IO.Standard_Output, Session);
else
Builds.Reprint_Of_Grammar
(Session,
Base_Name => "XXX",
Token_Prefix => "YYY",
Terminal_Last => 999);
end if;
if Options.Statistics then
Put_Statistics (Session);
end if;
if Session.Num_Conflict > 0 then
Put_Line
(Standard_Error,
Integer'Image (Session.Num_Conflict) & " parsing conflicts.");
end if;
if
Session.Error_Cnt > 0 or
Session.Num_Conflict > 0
then
Ada.Command_Line.Set_Exit_Status (Failure);
return;
end if;
end;
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
exception
when OCC : Command_Line.Parameter_Error =>
Exceptions.Put_Message (OCC);
when Occ : others =>
Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Name (Occ));
Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (Occ));
Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (Occ));
Exceptions.Put_Message (Occ);
end Cherry_Program;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Tools Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2015, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with GNAT.Regexp;
package body Configure.Tests.Operating_System is
Operating_System_Name : constant Ada.Strings.Unbounded.Unbounded_String
:= Ada.Strings.Unbounded.To_Unbounded_String ("OPERATING_SYSTEM");
--------------------------
-- Get_Operating_System --
--------------------------
function Get_Operating_System
(Self : Operating_System_Test) return Operating_Systems is
begin
if Self.Executed then
return Self.Operating_System;
else
raise Program_Error with "operating system test was not executed";
end if;
end Get_Operating_System;
-------------
-- Execute --
-------------
overriding procedure Execute
(Self : in out Operating_System_Test;
Arguments : in out Unbounded_String_Vector)
is
use GNAT.Regexp;
begin
-- Command line parameter has preference other automatic detection.
Self.Report_Check ("detecting target operating system");
if Match
(+Target_Triplet, Compile ("[a-zA-Z0-9_]*-[a-zA-Z0-9_]*-mingw.*"))
then
Self.Operating_System := Windows;
Substitutions.Insert (Operating_System_Name, +"Windows");
Is_Windows := True;
Self.Report_Status ("Windows");
elsif Match
(+Target_Triplet, Compile ("[a-zA-Z0-9_]*-[a-zA-Z0-9_]*-darwin.*"))
then
Self.Operating_System := MacOS;
Substitutions.Insert (Operating_System_Name, +"MacOS");
Is_Windows := True;
Self.Report_Status ("MacOS");
else
Self.Operating_System := POSIX;
Substitutions.Insert (Operating_System_Name, +"POSIX");
Self.Report_Status ("POSIX");
end if;
Self.Executed := True;
end Execute;
----------
-- Help --
----------
overriding function Help
(Self : Operating_System_Test) return Unbounded_String_Vector is
begin
return Result : Unbounded_String_Vector;
end Help;
----------
-- Name --
----------
overriding function Name (Self : Operating_System_Test) return String is
begin
return "os";
end Name;
end Configure.Tests.Operating_System;
|
pragma Eliminate (Subp_Elim_Errors, Proc);
package Subp_Elim_Errors is
procedure Proc;
end Subp_Elim_Errors;
|
with Ada.Text_Io; use Ada.Text_Io;
package body Shapes is
-----------
-- Print --
-----------
procedure Print (Item : in Point) is
begin
Put_line("Point");
end Print;
----------
-- Setx --
----------
function Setx (Item : in Point; Val : Integer) return Point is
begin
return (Val, Item.Y);
end Setx;
----------
-- Sety --
----------
function Sety (Item : in Point; Val : Integer) return Point is
begin
return (Item.X, Val);
end Sety;
----------
-- Getx --
----------
function Getx (Item : in Point) return Integer is
begin
return Item.X;
end Getx;
----------
-- Gety --
----------
function Gety (Item : in Point) return Integer is
begin
return Item.Y;
end Gety;
------------
-- Create --
------------
function Create return Point is
begin
return (0, 0);
end Create;
------------
-- Create --
------------
function Create (X : Integer) return Point is
begin
return (X, 0);
end Create;
------------
-- Create --
------------
function Create (X, Y : Integer) return Point is
begin
return (X, Y);
end Create;
end Shapes;
|
-- Lumen.Font.Txf -- Display textual information using texture-mapped fonts
--
-- Chip Richards, NiEstu, Phoenix AZ, Summer 2010
-- Credit for the design of the texfont mechanism belongs to Mark J. Kilgard,
-- who invented it while he was at SGI. His paper on the topic, and his
-- original source code, may be found here:
--
-- http://www.opengl.org/resources/code/samples/mjktips/TexFont/TexFont.html
--
-- Mark's contributions to the field of computer graphics, and to the
-- advancement of OpenGL in particular, cannot be overstated.
-- This code is covered by the ISC License:
--
-- Copyright © 2010, NiEstu
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- The software is provided "as is" and the author disclaims all warranties
-- with regard to this software including all implied warranties of
-- merchantability and fitness. In no event shall the author be liable for any
-- special, direct, indirect, or consequential damages or any damages
-- whatsoever resulting from loss of use, data or profits, whether in an
-- action of contract, negligence or other tortious action, arising out of or
-- in connection with the use or performance of this software.
-- Environment
with Ada.Finalization;
with Lumen.GL;
package Lumen.Font.Txf is
---------------------------------------------------------------------------
-- Exceptions added by this package
Unknown_Format : exception; -- can't recognize the file's data
Invalid_Format : exception; -- thought we did, but encountered bad values
No_Glyph : exception; -- character has no glyph in the font
---------------------------------------------------------------------------
-- Our font handle, used to refer to fonts within the library and app
type Font_Info_Pointer is private;
type Handle is new Ada.Finalization.Limited_Controlled with record
Info : Font_Info_Pointer;
end record;
overriding procedure Finalize (Font : in out Handle);
---------------------------------------------------------------------------
-- Load a texture font
procedure Load (Font : in out Handle;
Pathname : in String);
-- Unload a texture font
procedure Unload (Font : in out Handle);
-- Set up an OpenGL texture object. If Object is zero, create a new object
-- to use for the font's texture.
function Establish_Texture (Font : in Handle;
Object : in GL.UInt;
Setup_Mipmaps : in Boolean) return GL.UInt;
-- Bind the font's texture to an OpenGL texture object
procedure Bind_Font_Texture (Font : in Handle);
-- Return dimensions of given string, to permit calculations for placing it
-- in a scene
procedure Get_String_Metrics (Font : in Handle;
Str : in String;
Width : out Natural;
Max_Ascent : out Natural;
Max_Descent : out Natural);
-- Render a single character
procedure Render (Font : in Handle;
Char : in Character);
-- Render a string of characters
procedure Render (Font : in Handle;
Str : in String);
-- Will eventually have (Wide_)Wide_String and UTF-8 too
---------------------------------------------------------------------------
private
type Font_Info;
type Font_Info_Pointer is access Font_Info;
---------------------------------------------------------------------------
end Lumen.Font.Txf;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- T E M P D I R --
-- --
-- S p e c --
-- --
-- Copyright (C) 2003-2010, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package is used by gnatmake and by the Project Manager to create
-- temporary files. If environment variable TMPDIR is defined and
-- designates an absolute path, temporary files are create in this directory.
-- Otherwise, temporary files are created in the current working directory.
with Namet; use Namet;
with GNAT.OS_Lib; use GNAT.OS_Lib;
package Tempdir is
procedure Create_Temp_File
(FD : out File_Descriptor;
Name : out Path_Name_Type);
-- Create a temporary text file and return its file descriptor and
-- its path name as a Name_Id. If environment variable TMPDIR is defined
-- and its value is an absolute path, the temp file is created in the
-- directory designated by TMPDIR, otherwise, it is created in the current
-- directory. If temporary file cannot be created, FD gets the value
-- Invalid_FD and Name gets the value No_Name.
end Tempdir;
|
-- MIT License
-- Copyright (c) 2021 Stephen Merrony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package Debug_Logs is
Num_Lines : constant Integer :=
100_000; -- each circular buffer has this many lines
type Logs is
(Debug_Log, -- Debug_Log, is the general-purpose _log,
Mt_Log, -- Mt_Log, is for the type 6026 MT tape module
Dkp_Log, -- Dkp_Log, is for the type 4231a Moving-Head Disk
Dpf_Log, -- Dpf_Log, is for the type 6061 DPF disk module
Dskp_Log, -- Dskp_Log, is for the type 6239 DSKP disk module
Map_Log, -- Map_Log, is for BMC/DCH-related _log,ging
Sc_Log -- Sc_Log, is for System Call logging in the VS emulator
);
type Log_Filenames_T is array (Logs'Range) of Unbounded_String;
Log_Filenames : constant Log_Filenames_T :=
(Debug_Log => To_Unbounded_String ("debug.log"),
Mt_Log => To_Unbounded_String ("mt_debug.log"),
Dkp_Log => To_Unbounded_String ("dkp_debug.log"),
Dpf_Log => To_Unbounded_String ("dpf_debug.log"),
Dskp_Log => To_Unbounded_String ("dskp_debug.log"),
Map_Log => To_Unbounded_String ("bmcdch_debug.log"),
Sc_Log => To_Unbounded_String ("syscall_debug.log"));
type Log_Arr_T is array (Logs'Range, 1..Num_Lines) of Unbounded_String;
type Log_Ptr_T is array (Logs'Range) of Positive;
protected Loggers is
procedure Init;
procedure Debug_Logs_Dump (Directory : in String);
procedure Debug_Print (Log : in Logs; Msg : in String);
private
Log_Array : Log_Arr_T;
First_Line, Last_Line : Log_Ptr_T;
end Loggers;
end Debug_Logs;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with League.Text_Codecs;
with Slim.Message_Visiters;
package body Slim.Messages.vers is
----------
-- Read --
----------
overriding function Read
(Data : not null access
League.Stream_Element_Vectors.Stream_Element_Vector)
return Vers_Message
is
begin
return Result : Vers_Message do
Result.Version :=
League.Text_Codecs.Codec_For_Application_Locale.Decode (Data.all);
end return;
end Read;
-----------------
-- Set_Version --
-----------------
not overriding procedure Set_Version
(Self : in out Vers_Message;
Value : League.Strings.Universal_String) is
begin
Self.Version := Value;
end Set_Version;
-----------
-- Visit --
-----------
overriding procedure Visit
(Self : not null access Vers_Message;
Visiter : in out Slim.Message_Visiters.Visiter'Class) is
begin
Visiter.vers (Self);
end Visit;
-----------
-- Write --
-----------
overriding procedure Write
(Self : Vers_Message;
Tag : out Message_Tag;
Data : out League.Stream_Element_Vectors.Stream_Element_Vector) is
begin
Tag := "vers";
Data :=
League.Text_Codecs.Codec_For_Application_Locale.Encode (Self.Version);
end Write;
end Slim.Messages.vers;
|
--------------------------------------------------------------------------------------------------------------------
-- Copyright (c) 2013-2020, Luke A. Guest
--
-- This software is provided 'as-is', without any express or implied
-- warranty. In no event will the authors be held liable for any damages
-- arising from the use of this software.
--
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it
-- freely, subject to the following restrictions:
--
-- 1. The origin of this software must not be misrepresented; you must not
-- claim that you wrote the original software. If you use this software
-- in a product, an acknowledgment in the product documentation would be
-- appreciated but is not required.
--
-- 2. Altered source versions must be plainly marked as such, and must not be
-- misrepresented as being the original software.
--
-- 3. This notice may not be removed or altered from any source
-- distribution.
--------------------------------------------------------------------------------------------------------------------
-- SDL.Hints
--
-- Access to library configuration variables.
--------------------------------------------------------------------------------------------------------------------
package SDL.Hints is
pragma Preelaborate;
-- TODO: Make this more robust using more functions and platform specific
-- packages with error checking on returned values?
-- Would be nice to have the compiler only allow that which is allowed on
-- a particular platform.
-- It would be nice to have the binding test the return values as well,
-- raising an exception on values that are just wrong for a particular
-- platform, i.e. direct3d on Linux or Mac? Exception raised!
-- This is raised when something has gone horribly wrong somewhere,
-- i.e. setting the wrong hint on a platform that does not allow it.
Hint_Error : exception;
type Hint is
(Frame_Buffer_Acceleration,
Render_Driver,
Render_OpenGL_Shaders,
Render_Scale_Quality,
Render_VSync,
Video_X11_XVidMode,
Video_X11_Xinerama,
Video_X11_XRandR,
Grab_Keyboard,
Video_Minimise_On_Focus_Loss,
Idle_Timer_Disabled,
IOS_Orientations,
XInput_Enabled, -- win
Game_Controller_Config, -- win, mac, linux
Joystick_Allow_Background_Events,
Allow_Topmost,
Timer_Resolution) with -- win7 and earlier
Discard_Names => True;
type Priorities is (Default, Normal, Override) with
Convention => C;
procedure Clear with
Import => True,
Convention => C,
External_Name => "SDL_ClearHints";
function Get (Name : in Hint) return String;
procedure Set (Name : in Hint; Value : in String);
procedure Set (Name : in Hint; Value : in String; Priority : in Priorities);
end SDL.Hints;
|
package CUPS is
type Job_Id is new Natural;
Cups_Error : exception;
end CUPS;
|
pragma Ada_2012;
package body Protypo.Code_Trees.Interpreter.String_Interpolation_Handlers is
------------
-- Create --
------------
function Create (Interp : Interpreter_Access)
return Handlers.Function_Interface_Access
is
begin
return new String_Interpolator'(Status => Interp);
end Create;
-------------
-- Process --
-------------
function Process
(Fun : String_Interpolator; Parameter : Engine_Value_Vectors.Vector)
return Engine_Value_Vectors.Vector
is
use type ada.Containers.Count_Type;
begin
if Parameter.Length /= 1 then
-- This should never happen
raise Program_Error;
end if;
if Parameter.First_Element.Class /= Text then
raise Run_Time_Error with "String interpolation applied to non-string";
end if;
declare
Input : constant String := Get_String (Parameter.First_Element);
Interpolated : constant String := Do_Escape (Status => Fun.Status,
Input => Input);
Result : Engine_Value_Vectors.Vector;
begin
Result.Append (Create (Interpolated));
return Result;
end;
end Process;
---------------
-- Signature --
---------------
function Signature
(Fun : String_Interpolator) return Parameter_Lists.Parameter_Signature
is (1 => Parameter_Lists.Mandatory);
end Protypo.Code_Trees.Interpreter.String_Interpolation_Handlers;
|
-- ////////////////////////////////////////////////////////////
-- //
-- // SFML - Simple and Fast Multimedia Library
-- // Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-- //
-- // This software is provided 'as-is', without any express or implied warranty.
-- // In no event will the authors be held liable for any damages arising from the use of this software.
-- //
-- // Permission is granted to anyone to use this software for any purpose,
-- // including commercial applications, and to alter it and redistribute it freely,
-- // subject to the following restrictions:
-- //
-- // 1. The origin of this software must not be misrepresented;
-- // you must not claim that you wrote the original software.
-- // If you use this software in a product, an acknowledgment
-- // in the product documentation would be appreciated but is not required.
-- //
-- // 2. Altered source versions must be plainly marked as such,
-- // and must not be misrepresented as being the original software.
-- //
-- // 3. This notice may not be removed or altered from any source distribution.
-- //
-- ////////////////////////////////////////////////////////////
-- ////////////////////////////////////////////////////////////
-- // Headers
-- ////////////////////////////////////////////////////////////
with Sf.Config;
package Sf.Window.Event is
use Sf.Config;
-- ////////////////////////////////////////////////////////////
-- /// Definition of key codes for keyboard events
-- ////////////////////////////////////////////////////////////
subtype sfKeyCode is sfUint32;
sfKeyA : constant sfKeyCode := 97;
sfKeyB : constant sfKeyCode := 98;
sfKeyC : constant sfKeyCode := 99;
sfKeyD : constant sfKeyCode := 100;
sfKeyE : constant sfKeyCode := 101;
sfKeyF : constant sfKeyCode := 102;
sfKeyG : constant sfKeyCode := 103;
sfKeyH : constant sfKeyCode := 104;
sfKeyI : constant sfKeyCode := 105;
sfKeyJ : constant sfKeyCode := 106;
sfKeyK : constant sfKeyCode := 107;
sfKeyL : constant sfKeyCode := 108;
sfKeyM : constant sfKeyCode := 109;
sfKeyN : constant sfKeyCode := 110;
sfKeyO : constant sfKeyCode := 111;
sfKeyP : constant sfKeyCode := 112;
sfKeyQ : constant sfKeyCode := 113;
sfKeyR : constant sfKeyCode := 114;
sfKeyS : constant sfKeyCode := 115;
sfKeyT : constant sfKeyCode := 116;
sfKeyU : constant sfKeyCode := 117;
sfKeyV : constant sfKeyCode := 118;
sfKeyW : constant sfKeyCode := 119;
sfKeyX : constant sfKeyCode := 120;
sfKeyY : constant sfKeyCode := 121;
sfKeyZ : constant sfKeyCode := 122;
sfKeyNum0 : constant sfKeyCode := 48;
sfKeyNum1 : constant sfKeyCode := 49;
sfKeyNum2 : constant sfKeyCode := 50;
sfKeyNum3 : constant sfKeyCode := 51;
sfKeyNum4 : constant sfKeyCode := 52;
sfKeyNum5 : constant sfKeyCode := 53;
sfKeyNum6 : constant sfKeyCode := 54;
sfKeyNum7 : constant sfKeyCode := 55;
sfKeyNum8 : constant sfKeyCode := 56;
sfKeyNum9 : constant sfKeyCode := 57;
sfKeyEscape : constant sfKeyCode := 256;
sfKeyLControl : constant sfKeyCode := 257;
sfKeyLShift : constant sfKeyCode := 258;
sfKeyLAlt : constant sfKeyCode := 259;
sfKeyLSystem : constant sfKeyCode := 260;
sfKeyRControl : constant sfKeyCode := 261;
sfKeyRShift : constant sfKeyCode := 262;
sfKeyRAlt : constant sfKeyCode := 263;
sfKeyRSystem : constant sfKeyCode := 264;
sfKeyMenu : constant sfKeyCode := 265;
sfKeyLBracket : constant sfKeyCode := 266;
sfKeyRBracket : constant sfKeyCode := 267;
sfKeySemiColon : constant sfKeyCode := 268;
sfKeyComma : constant sfKeyCode := 269;
sfKeyPeriod : constant sfKeyCode := 270;
sfKeyQuote : constant sfKeyCode := 271;
sfKeySlash : constant sfKeyCode := 272;
sfKeyBackSlash : constant sfKeyCode := 273;
sfKeyTilde : constant sfKeyCode := 274;
sfKeyEqual : constant sfKeyCode := 275;
sfKeyDash : constant sfKeyCode := 276;
sfKeySpace : constant sfKeyCode := 277;
sfKeyReturn : constant sfKeyCode := 278;
sfKeyBack : constant sfKeyCode := 279;
sfKeyTab : constant sfKeyCode := 280;
sfKeyPageUp : constant sfKeyCode := 281;
sfKeyPageDown : constant sfKeyCode := 282;
sfKeyEnd : constant sfKeyCode := 283;
sfKeyHome : constant sfKeyCode := 284;
sfKeyInsert : constant sfKeyCode := 285;
sfKeyDelete : constant sfKeyCode := 286;
sfKeyAdd : constant sfKeyCode := 287;
sfKeySubtract : constant sfKeyCode := 288;
sfKeyMultiply : constant sfKeyCode := 289;
sfKeyDivide : constant sfKeyCode := 290;
sfKeyLeft : constant sfKeyCode := 291;
sfKeyRight : constant sfKeyCode := 292;
sfKeyUp : constant sfKeyCode := 293;
sfKeyDown : constant sfKeyCode := 294;
sfKeyNumpad0 : constant sfKeyCode := 295;
sfKeyNumpad1 : constant sfKeyCode := 296;
sfKeyNumpad2 : constant sfKeyCode := 297;
sfKeyNumpad3 : constant sfKeyCode := 298;
sfKeyNumpad4 : constant sfKeyCode := 299;
sfKeyNumpad5 : constant sfKeyCode := 300;
sfKeyNumpad6 : constant sfKeyCode := 301;
sfKeyNumpad7 : constant sfKeyCode := 302;
sfKeyNumpad8 : constant sfKeyCode := 303;
sfKeyNumpad9 : constant sfKeyCode := 304;
sfKeyF1 : constant sfKeyCode := 305;
sfKeyF2 : constant sfKeyCode := 306;
sfKeyF3 : constant sfKeyCode := 307;
sfKeyF4 : constant sfKeyCode := 308;
sfKeyF5 : constant sfKeyCode := 309;
sfKeyF6 : constant sfKeyCode := 310;
sfKeyF7 : constant sfKeyCode := 311;
sfKeyF8 : constant sfKeyCode := 312;
sfKeyF9 : constant sfKeyCode := 313;
sfKeyF10 : constant sfKeyCode := 314;
sfKeyF11 : constant sfKeyCode := 315;
sfKeyF12 : constant sfKeyCode := 316;
sfKeyF13 : constant sfKeyCode := 317;
sfKeyF14 : constant sfKeyCode := 318;
sfKeyF15 : constant sfKeyCode := 319;
sfKeyPause : constant sfKeyCode := 320;
sfKeyCount : constant sfKeyCode := 321;
-- ////////////////////////////////////////////////////////////
-- /// Definition of button codes for mouse events
-- ////////////////////////////////////////////////////////////
type sfMouseButton is (sfButtonLeft, sfButtonRight, sfButtonMiddle, sfButtonX1, sfButtonX2);
-- ////////////////////////////////////////////////////////////
-- /// Definition of joystick axis for joystick events
-- ////////////////////////////////////////////////////////////
type sfJoyAxis is (
sfJoyAxisX,
sfJoyAxisY,
sfJoyAxisZ,
sfJoyAxisR,
sfJoyAxisU,
sfJoyAxisV,
sfJoyAxisPOV);
-- ////////////////////////////////////////////////////////////
-- /// Definition of all the event types
-- ////////////////////////////////////////////////////////////
type sfEventType is (
sfEvtClosed,
sfEvtResized,
sfEvtLostFocus,
sfEvtGainedFocus,
sfEvtTextEntered,
sfEvtKeyPressed,
sfEvtKeyReleased,
sfEvtMouseWheelMoved,
sfEvtMouseButtonPressed,
sfEvtMouseButtonReleased,
sfEvtMouseMoved,
sfEvtMouseEntered,
sfEvtMouseLeft,
sfEvtJoyButtonPressed,
sfEvtJoyButtonReleased,
sfEvtJoyMoved);
-- ////////////////////////////////////////////////////////////
-- /// Keyboard event parameters
-- ////////////////////////////////////////////////////////////
type sfKeyEvent is record
Event_Type : aliased sfEventType;
Code : aliased sfKeyCode;
Alt : aliased sfBool;
Control : aliased sfBool;
Shift : aliased sfBool;
end record;
-- ////////////////////////////////////////////////////////////
-- /// Text event parameters
-- ////////////////////////////////////////////////////////////
type sfTextEvent is record
Event_Type : aliased sfEventType;
Unicode : aliased sfUint32;
end record;
-- ////////////////////////////////////////////////////////////
-- /// Mouse move event parameters
-- ////////////////////////////////////////////////////////////
type sfMouseMoveEvent is record
Event_Type : aliased sfEventType;
X : aliased Integer;
Y : aliased Integer;
end record;
-- ////////////////////////////////////////////////////////////
-- /// Mouse buttons events parameters
-- ////////////////////////////////////////////////////////////
type sfMouseButtonEvent is record
Event_Type : aliased sfEventType;
Button : aliased sfMouseButton;
X : aliased Integer;
Y : aliased Integer;
end record;
-- ////////////////////////////////////////////////////////////
-- /// Mouse wheel events parameters
-- ////////////////////////////////////////////////////////////
type sfMouseWheelEvent is record
Event_Type : aliased sfEventType;
Delta_Value : aliased Integer;
end record;
-- ////////////////////////////////////////////////////////////
-- /// Joystick axis move event parameters
-- ////////////////////////////////////////////////////////////
type sfJoyMoveEvent is record
Event_Type : aliased sfEventType;
JoystickId : aliased sfUint32;
Axis : aliased sfJoyAxis;
Position : aliased Float;
end record;
-- ////////////////////////////////////////////////////////////
-- /// Joystick buttons events parameters
-- ////////////////////////////////////////////////////////////
type sfJoyButtonEvent is record
Event_Type : aliased sfEventType;
JoystickId : aliased sfUint32;
Button : aliased sfUint32;
end record;
-- ////////////////////////////////////////////////////////////
-- /// Size events parameters
-- ////////////////////////////////////////////////////////////
type sfSizeEvent is record
Event_Type : aliased sfEventType;
Width : aliased sfUint32;
Height : aliased sfUint32;
end record;
-- ////////////////////////////////////////////////////////////
-- /// sfEvent defines a system event and its parameters
-- ////////////////////////////////////////////////////////////
type sfEvent (Discr : sfUint32 := 0) is record
case Discr is
when 0 =>
Event_Type : aliased sfEventType;
when 1 =>
Key : aliased sfKeyEvent;
when 2 =>
Text : aliased sfTextEvent;
when 3 =>
MouseMove : aliased sfMouseMoveEvent;
when 4 =>
MouseButton : aliased sfMouseButtonEvent;
when 5 =>
MouseWheel : aliased sfMouseWheelEvent;
when 6 =>
JoyMove : aliased sfJoyMoveEvent;
when 7 =>
JoyButton : aliased sfJoyButtonEvent;
when others =>
Size : aliased sfSizeEvent;
end case;
end record;
private
pragma Convention (C, sfMouseButton);
pragma Convention (C, sfJoyAxis);
pragma Convention (C, sfEventType);
pragma Convention (C_Pass_By_Copy, sfKeyEvent);
pragma Convention (C_Pass_By_Copy, sfTextEvent);
pragma Convention (C_Pass_By_Copy, sfMouseMoveEvent);
pragma Convention (C_Pass_By_Copy, sfMouseButtonEvent);
pragma Convention (C_Pass_By_Copy, sfMouseWheelEvent);
pragma Convention (C_Pass_By_Copy, sfJoyMoveEvent);
pragma Convention (C_Pass_By_Copy, sfJoyButtonEvent);
pragma Convention (C_Pass_By_Copy, sfSizeEvent);
pragma Convention (C_Pass_By_Copy, sfEvent);
pragma Unchecked_Union (sfEvent);
end Sf.Window.Event;
|
pragma License (Unrestricted);
generic
type Index is (<>);
type Element is private;
type Element_Array is array (Index range <>) of aliased Element;
Default_Terminator : Element;
package Interfaces.C.Pointers is
-- pragma Preelaborate;
pragma Pure;
type Pointer is access all Element;
-- modified
for Pointer'Storage_Size use 0;
pragma No_Strict_Aliasing (Pointer);
-- extended
type Constant_Pointer is access constant Element;
for Constant_Pointer'Storage_Size use 0;
pragma No_Strict_Aliasing (Constant_Pointer);
-- function Value (Ref : Pointer; Terminator : Element := Default_Terminator)
-- return Element_Array;
function Value (
Ref : access constant Element; -- CXB3014 requires null
Terminator : Element := Default_Terminator)
return Element_Array;
-- function Value (Ref : Pointer; Length : ptrdiff_t)
-- return Element_Array;
function Value (
Ref : access constant Element; -- CXB3014 requires null
Length : ptrdiff_t)
return Element_Array;
Pointer_Error : exception
renames C.Pointer_Error;
-- C-style Pointer arithmetic
function "+" (
Left : Pointer; -- CXB3015 requires null
Right : ptrdiff_t)
return not null Pointer
with Convention => Intrinsic;
-- modified from here
function "+" (
Left : ptrdiff_t;
Right : not null Pointer) -- null exclusion
return not null Pointer
with Convention => Intrinsic;
-- to here
function "-" (
Left : Pointer; -- CXB3015 requires null
Right : ptrdiff_t)
return not null Pointer
with Convention => Intrinsic;
-- modified from here
-- function "-" (Left : Pointer; Right : Pointer) return ptrdiff_t;
function "-" (
Left : not null Pointer; -- null exclusion
Right : not null access constant Element)
return ptrdiff_t
with Convention => Intrinsic;
-- to here
pragma Pure_Function ("+");
pragma Pure_Function ("-");
pragma Inline_Always ("+");
pragma Inline_Always ("-");
-- modified from here
procedure Increment (
Ref : in out not null Pointer) -- null exclusion
with Convention => Intrinsic;
-- to here
procedure Decrement (
Ref : in out Pointer) -- CXB3015 requires null
with Convention => Intrinsic;
pragma Inline_Always (Increment);
pragma Inline_Always (Decrement);
-- extended from here
function "+" (Left : not null Constant_Pointer; Right : ptrdiff_t)
return not null Constant_Pointer
with Convention => Intrinsic;
function "+" (Left : ptrdiff_t; Right : not null Constant_Pointer)
return not null Constant_Pointer
with Convention => Intrinsic;
function "-" (Left : not null Constant_Pointer; Right : ptrdiff_t)
return not null Constant_Pointer
with Convention => Intrinsic;
function "-" (
Left : not null Constant_Pointer;
Right : not null access constant Element)
return ptrdiff_t
with Convention => Intrinsic;
pragma Pure_Function ("+");
pragma Pure_Function ("-");
pragma Inline_Always ("+");
pragma Inline_Always ("-");
procedure Increment (Ref : in out not null Constant_Pointer)
with Convention => Intrinsic;
procedure Decrement (Ref : in out not null Constant_Pointer)
with Convention => Intrinsic;
pragma Inline_Always (Increment);
pragma Inline_Always (Decrement);
-- to here
-- function Virtual_Length (
-- Ref : Pointer;
-- Terminator : Element := Default_Terminator)
-- return ptrdiff_t;
function Virtual_Length (
Ref : access constant Element; -- CXB3016 requires null
Terminator : Element := Default_Terminator)
return ptrdiff_t;
-- extended
-- This overloaded version Virtual_Length gets the length of Ref
-- less than or equal to Limit.
function Virtual_Length (
Ref : not null access constant Element;
Limit : ptrdiff_t;
Terminator : Element := Default_Terminator)
return ptrdiff_t;
-- procedure Copy_Terminated_Array (
-- Source : Pointer;
-- Target : Pointer;
-- Limit : ptrdiff_t := ptrdiff_t'Last;
-- Terminator : Element := Default_Terminator);
procedure Copy_Terminated_Array (
Source : access constant Element; -- CXB3016 requires null
Target : access Element; -- same as above
Limit : ptrdiff_t := ptrdiff_t'Last;
Terminator : Element := Default_Terminator);
-- Note: Copy_Terminated_Array (..., Limit) produces an unterminated Target
-- if there is no Terminator in the first Limit elements of Source.
-- This behavior is danger similar to strncpy.
-- Use Virtual_Length and Copy_Array, or imported strlcpy, instead of it.
-- procedure Copy_Array (
-- Source : Pointer;
-- Target : Pointer;
-- Length : ptrdiff_t);
procedure Copy_Array (
Source : access constant Element; -- CXB3016 requires null
Target : access Element; -- same as above
Length : ptrdiff_t);
end Interfaces.C.Pointers;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2013, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This package provides string handler optimized for SSE2 instructions set
-- on x86 and x86_64 processors.
------------------------------------------------------------------------------
with Interfaces;
generic
type Base_String_Handler is
abstract new Abstract_String_Handler with private;
with procedure Update_Index_Forward
(Mask : Interfaces.Unsigned_32;
Index : in out Positive);
-- Update character index based on value of the exclusion mask. It
-- increments Index by 8 excluding 1 for each pair of 1 bits in exclusion
-- mask.
with procedure Update_Index_Backward
(Mask : Interfaces.Unsigned_32;
Index : in out Positive);
-- Update character index based on value of the exclusion mask. It
-- decrements Index by 8 excluding 1 for each pair of 1 bits in exclusion
-- mask.
package Matreshka.Internals.Strings.Handlers.Generic_X86_SSE2 is
pragma Preelaborate;
type X86_SSE2_String_Handler is new Base_String_Handler with null record;
overriding procedure Fill_Null_Terminator
(Self : X86_SSE2_String_Handler;
Item : not null Shared_String_Access);
overriding function Is_Equal
(Self : X86_SSE2_String_Handler;
Left : not null Shared_String_Access;
Right : not null Shared_String_Access) return Boolean;
overriding function Is_Less
(Self : X86_SSE2_String_Handler;
Left : not null Shared_String_Access;
Right : not null Shared_String_Access) return Boolean;
overriding function Is_Greater
(Self : X86_SSE2_String_Handler;
Left : not null Shared_String_Access;
Right : not null Shared_String_Access) return Boolean;
overriding function Is_Less_Or_Equal
(Self : X86_SSE2_String_Handler;
Left : not null Shared_String_Access;
Right : not null Shared_String_Access) return Boolean;
overriding function Is_Greater_Or_Equal
(Self : X86_SSE2_String_Handler;
Left : not null Shared_String_Access;
Right : not null Shared_String_Access) return Boolean;
overriding function Index
(Self : X86_SSE2_String_Handler;
Item : Matreshka.Internals.Strings.Shared_String_Access;
From_Index : Positive;
From_Position : Matreshka.Internals.Utf16.Utf16_String_Index;
To_Position : Matreshka.Internals.Utf16.Utf16_String_Index;
Code : Matreshka.Internals.Unicode.Code_Point)
return Natural;
overriding function Last_Index
(Self : X86_SSE2_String_Handler;
Item : Matreshka.Internals.Strings.Shared_String_Access;
From_Position : Matreshka.Internals.Utf16.Utf16_String_Index;
To_Index : Positive;
To_Position : Matreshka.Internals.Utf16.Utf16_String_Index;
Code : Matreshka.Internals.Unicode.Code_Point) return Natural;
Handler : aliased X86_SSE2_String_Handler;
end Matreshka.Internals.Strings.Handlers.Generic_X86_SSE2;
|
pragma Warnings (Off);
pragma Style_Checks (Off);
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Strings.Fixed; use Ada.Strings, Ada.Strings.Fixed;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
-- with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Unchecked_Conversion;
with UnZip.Streams;
with Float_portable_binary_transfer;
pragma Elaborate_All (Float_portable_binary_transfer);
with GLOBE_3D.Textures;
with GL.IO;
package body GLOBE_3D.IO is
------------------------------------------------
-- Common, internal definitions, routines, .. . --
------------------------------------------------
stop_type : constant Character :=
Character'Val (26); -- Ctrl - Z to stop typing a binary file
signature_obj : constant String :=
"GLOBE_3D 3D Binary Object File (" & object_extension & "). " &
"Format version : 2 - Apr - 2008." & stop_type;
signature_bsp : constant String :=
"GLOBE_3D Binary Space Partition File (" & BSP_extension & "). " &
"Format version : 2 - Apr - 2008." & stop_type;
subtype U8 is GL.Ubyte;
type U16 is mod 2 ** 16; for U16'Size use 16;
type U32 is mod 2 ** 32; for U32'Size use 32;
type I16 is range -2 ** 15 .. 2 ** 15 - 1; for I16'Size use 16;
type I32 is range -2 ** 31 .. 2 ** 31 - 1; for I32'Size use 32;
f_scaling : constant := 2.0**24;
package FFBT is
new Float_portable_binary_transfer (GL.C_Float, I32, I16, True, f_scaling);
use FFBT;
d_scaling : constant := 2.0**27; -- 53/2=26.5
package DFBT is
new Float_portable_binary_transfer (GL.Double, I32, I16, True, d_scaling);
use DFBT;
function Cvt is new Ada.Unchecked_Conversion (I16, U16);
function Cvt is new Ada.Unchecked_Conversion (I32, U32);
function Cvt is new Ada.Unchecked_Conversion (U16, I16);
function Cvt is new Ada.Unchecked_Conversion (U32, I32);
generic
type Number is mod <>;
procedure Read_Intel_x86_number (sb : in out GL.IO.Input_buffer; n : out Number);
procedure Read_Intel_x86_number (sb : in out GL.IO.Input_buffer; n : out Number) is
b : U8;
m : Number := 1;
bytes : constant Integer := Number'Size / 8;
begin
n := 0;
for i in 1 .. bytes loop
GL.IO.Get_Byte (sb, b);
n := n + m * Number (b);
m := m * 256;
end loop;
end Read_Intel_x86_number;
procedure Read_Double (
sb : in out GL.IO.Input_buffer;
n : out GL.Double
) is
procedure Read_Intel is new Read_Intel_x86_number (U16);
procedure Read_Intel is new Read_Intel_x86_number (U32);
m1, m2 : U32; e : U16;
begin
Read_Intel (sb, m1);
Read_Intel (sb, m2);
Read_Intel (sb, e);
Merge (Cvt (m1), Cvt (m2), Cvt (e), n);
-- Double is stored in two parts due to the absence of
-- 64 - bit integers on certain compilers (e.g. OA 8.2)
end Read_Double;
generic
s : Ada.Streams.Stream_IO.Stream_Access;
type Number is mod <>;
procedure Write_Intel_x86_number (n : in Number);
procedure Write_Intel_x86_number (n : in Number) is
m : Number := n;
bytes : constant Integer := Number'Size/8;
begin
for i in 1 .. bytes loop
U8'Write (s, U8 (m mod 256));
m := m / 256;
end loop;
end Write_Intel_x86_number;
procedure Write_Double (
s : Ada.Streams.Stream_IO.Stream_Access;
n : in GL.Double)
is
procedure Write_Intel is new Write_Intel_x86_number (s, U16);
procedure Write_Intel is new Write_Intel_x86_number (s, U32);
m1, m2 : I32; e : I16;
begin
Split (n, m1, m2, e);
-- Double is stored in two parts due to the absence of
-- 64 - bit integers on certain compilers (e.g. OA 8.2)
Write_Intel (Cvt (m1));
Write_Intel (Cvt (m2));
Write_Intel (Cvt (e));
end Write_Double;
procedure Write_String (
s : in Ada.Streams.Stream_IO.Stream_Access;
str : in String
)
is
tstr : constant String := Trim (str, Right);
begin
U8'Write (s, tstr'Length);
String'Write (s, tstr);
end Write_String;
procedure Read_String (
sb : in out GL.IO.Input_buffer;
str : out String
)
is
l8 : U8;
l : Natural;
begin
GL.IO.Get_Byte (sb, l8);
l := Natural (l8);
if l > str'Length then
raise Constraint_Error;
end if;
for i in str'First .. str'First + l - 1 loop
GL.IO.Get_Byte (sb, l8);
str (i) := Character'Val (l8);
end loop;
str (str'First + l .. str'Last) := (others => ' ');
end Read_String;
-------------------
-- Object_3D I/O --
-------------------
procedure Read (
s : in Ada.Streams.Stream_IO.Stream_Access;
o : out p_Object_3D
)
is
buf : GL.IO.Input_buffer;
procedure Read_Intel is new Read_Intel_x86_number (U16);
procedure Read_Intel is new Read_Intel_x86_number (U32);
procedure Read_Float (n : out GL.C_Float) is
m : U32; e : U16;
begin
Read_Intel (buf, m);
Read_Intel (buf, e);
Merge (Cvt (m), Cvt (e), n);
end Read_Float;
procedure Read_Material_Float_vector (mfv : out GL.Material_Float_vector) is
begin
for i in mfv'Range loop
Read_Float (mfv (i));
end loop;
end Read_Material_Float_vector;
procedure Read_Point_3D (p : out Point_3D) is
begin
for i in p'Range loop
Read_Double (buf, p (i));
end loop;
end Read_Point_3D;
procedure Read_Map_idx_pair_array (m : out Map_idx_pair_array) is
begin
for i in m'Range loop
Read_Double (buf, m (i).U);
Read_Double (buf, m (i).V);
end loop;
end Read_Map_idx_pair_array;
v8 : U8;
v32, mp32, mf32 : U32;
procedure Read_face (face : out Face_type; face_invar : in out Face_invariant_type) is
begin
-- 1/ Points
for i in face.p'Range loop
Read_Intel (buf, v32);
face.p (i) := Integer (v32);
end loop;
-- 2/ Portal connection : object name is stored;
-- access must be found later
Read_String (buf, face_invar.connect_name);
-- 3/ Skin
GL.IO.Get_Byte (buf, v8);
face.skin := Skin_Type'Val (v8);
-- 4/ Mirror
GL.IO.Get_Byte (buf, v8);
face.mirror := Boolean'Val (v8);
-- 5/ Alpha
Read_Double (buf, face.alpha);
-- 6/ Colour
case face.skin is
when colour_only | coloured_texture =>
Read_Double (buf, face.colour.red);
Read_Double (buf, face.colour.green);
Read_Double (buf, face.colour.blue);
when others =>
null;
end case;
-- 7/ Material
case face.skin is
when material_only | material_texture =>
Read_Material_Float_vector (face.material.ambient);
Read_Material_Float_vector (face.material.diffuse);
Read_Material_Float_vector (face.material.specular);
Read_Material_Float_vector (face.material.emission);
Read_Float (face.material.shininess);
when others =>
null;
end case;
-- 8/ Texture : texture name is stored;
-- id must be found later
Read_String (buf, face_invar.texture_name);
GL.IO.Get_Byte (buf, v8);
face.whole_texture := Boolean'Val (v8);
GL.IO.Get_Byte (buf, v8);
face.repeat_U := Positive'Val (v8);
GL.IO.Get_Byte (buf, v8);
face.repeat_V := Positive'Val (v8);
if not face.whole_texture then
Read_Map_idx_pair_array (face.texture_edge_map);
end if;
end Read_face;
test_signature : String (signature_obj'Range);
ID : Ident;
begin
String'Read (s, test_signature);
if test_signature /= signature_obj then
raise Bad_data_format;
end if;
GL.IO.Attach_Stream (b => buf, stm => s);
Read_String (buf, ID);
-- Read the object's dimensions, create object, read its contents
Read_Intel (buf, mp32);
Read_Intel (buf, mf32);
o := new Object_3D (Integer (mp32), Integer (mf32));
o.ID := ID;
for p in o.Point'Range loop
Read_Point_3D (o.Point (p));
end loop;
for f in o.face'Range loop
Read_face (o.face (f), o.face_invariant (f));
end loop;
Read_Point_3D (o.Centre);
for i in Matrix_33'Range (1) loop
for j in Matrix_33'Range (2) loop
Read_Double (buf, o.rotation (i, j));
end loop;
end loop;
-- !! sub - objects : skipped !!
-- Main operation done!
end Read;
procedure Write (
s : in Ada.Streams.Stream_IO.Stream_Access;
o : in Object_3D
)
is
procedure Write_Intel is new Write_Intel_x86_number (s, U16);
procedure Write_Intel is new Write_Intel_x86_number (s, U32);
procedure Write_Float (n : in GL.C_Float) is
m : I32; e : I16;
begin
Split (n, m, e);
Write_Intel (Cvt (m));
Write_Intel (Cvt (e));
end Write_Float;
procedure Write_Material_Float_vector (mfv : in GL.Material_Float_vector) is
begin
for i in mfv'Range loop
Write_Float (mfv (i));
end loop;
end Write_Material_Float_vector;
procedure Write_Point_3D (p : in Point_3D) is
begin
for i in p'Range loop
Write_Double (s, p (i));
end loop;
end Write_Point_3D;
procedure Write_Map_idx_pair_array (m : in Map_idx_pair_array) is
begin
for i in m'Range loop
Write_Double (s, m (i).U);
Write_Double (s, m (i).V);
end loop;
end Write_Map_idx_pair_array;
procedure Write_face (face : Face_type; face_invar : Face_invariant_type) is
begin
-- 1/ Points
for i in face.p'Range loop
Write_Intel (U32 (face.p (i)));
end loop;
-- 2/ Portal connection : object name is stored
if face.connecting = null then
Write_String (s, empty);
else
Write_String (s, face.connecting.ID);
end if;
-- 3/ Skin
U8'Write (s, Skin_Type'Pos (face.skin));
-- 4/ Mirror
U8'Write (s, Boolean'Pos (face.mirror));
-- 5/ Alpha
Write_Double (s, face.alpha);
-- 6/ Colour
case face.skin is
when colour_only | coloured_texture =>
Write_Double (s, face.colour.red);
Write_Double (s, face.colour.green);
Write_Double (s, face.colour.blue);
when others =>
null;
end case;
-- 7/ Material
case face.skin is
when material_only | material_texture =>
Write_Material_Float_vector (face.material.ambient);
Write_Material_Float_vector (face.material.diffuse);
Write_Material_Float_vector (face.material.specular);
Write_Material_Float_vector (face.material.emission);
Write_Float (face.material.shininess);
when others =>
null;
end case;
-- 8/ Texture : texture name is stored
if face.texture = null_image then
-- Maybe a texture name has been given with Texture_name_hint,
-- but was not yet attached to a GL ID number through Rebuild_Links
Write_String (s, face_invar.texture_name);
else
-- Usual way : We can get the texture name associated to the
-- GL ID number; name is stored by GLOBE_3D.Textures.
Write_String (s, Textures.Texture_name (face.texture, False));
end if;
U8'Write (s, Boolean'Pos (face.whole_texture));
U8'Write (s, Positive'Pos (face.repeat_U));
U8'Write (s, Positive'Pos (face.repeat_V));
if not face.whole_texture then
Write_Map_idx_pair_array (face.texture_edge_map);
end if;
end Write_face;
begin
String'Write (s, signature_obj);
Write_String (s, o.ID);
Write_Intel (U32 (o.Max_points));
Write_Intel (U32 (o.Max_faces));
for p in o.Point'Range loop
Write_Point_3D (o.Point (p));
end loop;
for f in o.face'Range loop
Write_face (o.face (f), o.face_invariant (f));
end loop;
Write_Point_3D (o.Centre);
for i in Matrix_33'Range (1) loop
for j in Matrix_33'Range (2) loop
Write_Double (s, o.rotation (i, j));
end loop;
end loop;
-- !! sub - objects : skipped !!
-- Main operation done!
end Write;
generic
type Anything is private;
extension : String;
animal : String;
with procedure Read (
s : in Ada.Streams.Stream_IO.Stream_Access;
a : out Anything
);
procedure Load_generic (name_in_resource : String; a : out Anything);
procedure Load_generic (name_in_resource : String; a : out Anything) is
name_ext : constant String := name_in_resource & extension;
procedure Try (zif : in out Zip.Zip_info; name : String) is
use UnZip.Streams;
fobj : Zipped_File_Type;
begin -- Try
Load_if_needed (zif, name);
Open (fobj, zif, name_ext);
Read (Stream (fobj), a);
Close (fobj);
exception
when Zip.File_name_not_found =>
raise;
when e:others =>
Raise_Exception (
Exception_Identity (e),
Exception_Message (e) & " on " & animal & " : " & name_ext
);
end Try;
begin
begin
Try (zif_level, To_String (level_data_name));
exception
when Zip.File_name_not_found |
Zip.Zip_file_open_Error =>
-- Not found in level - specific pack
Try (zif_global, To_String (global_data_name));
end;
exception
when Zip.File_name_not_found |
Zip.Zip_file_open_Error =>
-- Never found - neither in level, nor in global pack
Raise_Exception (
Missing_object'Identity,
animal & " not found in any data resource pack : " & name_in_resource
);
end Load_generic;
procedure Load_Internal is
new Load_generic (
Anything => p_Object_3D,
extension => object_extension,
animal => "object",
Read => Read
);
procedure Load (name_in_resource : String; o : out p_Object_3D)
renames Load_Internal;
procedure Load_file (file_name : String; o : out p_Object_3D) is
use Ada.Streams.Stream_IO;
f : File_Type;
begin
Open (f, in_file, file_name);
Read (Stream (f), o);
Close (f);
end Load_file;
procedure Save_file (file_name : String; o : in Object_3D'Class) is
use Ada.Streams.Stream_IO;
f : File_Type;
begin
Create (f, out_file, file_name);
Write (Stream (f), Object_3D (o));
-- ^ endian - proof and floating - point hardware neutral;
-- using stream attribute would be machine - specific.
Close (f);
end Save_file;
procedure Save_file (o : in Object_3D'Class) is
begin
Save_file (Trim (o.ID, Right) & object_extension, o);
end Save_file;
-------------
-- BSP I/O --
-------------
-- Write a BSP tree to a stream
procedure Write (
s : in Ada.Streams.Stream_IO.Stream_Access;
tree : in BSP.p_BSP_node
)
is
procedure Write_Intel is new Write_Intel_x86_number (s, U32);
use BSP;
n : Natural := 0;
procedure Numbering (node : p_BSP_node) is
begin
if node /= null then
n := n + 1;
node.node_id := n;
Numbering (node.front_child);
Numbering (node.back_child);
end if;
end Numbering;
procedure Save_node (node : p_BSP_node) is
begin
if node /= null then
Write_Intel (U32 (node.node_id));
if node.front_child = null then
Write_Intel (U32' (0));
if node.front_leaf = null then
Write_String (s, empty);
else
Write_String (s, node.front_leaf.ID);
end if;
else
Write_Intel (U32 (node.front_child.node_id));
end if;
if node.back_child = null then
Write_Intel (U32' (0));
if node.back_leaf = null then
Write_String (s, empty);
else
Write_String (s, node.back_leaf.ID);
end if;
else
Write_Intel (U32 (node.back_child.node_id));
end if;
for i in node.normal'Range loop
Write_Double (s, node.normal (i));
end loop;
Write_Double (s, node.distance);
--
Save_node (node.front_child);
Save_node (node.back_child);
end if;
end Save_node;
begin
Numbering (tree); -- fill the node_id's
String'Write (s, signature_bsp); -- header
Write_Intel (U32 (n)); -- give the number of nodes first
Save_node (tree);
end Write;
-- Write a BSP tree to a file
procedure Save_file (file_name : String; tree : in BSP.p_BSP_node) is
use Ada.Streams.Stream_IO;
f : File_Type;
begin
if Index (file_name, ".")=0 then
Create (f, out_file, file_name & BSP_extension);
else
Create (f, out_file, file_name);
end if;
Write (Stream (f), tree);
Close (f);
end Save_file;
procedure Load (
name_in_resource : in String;
referred : in Map_of_Visuals;
tree : out BSP.p_BSP_node
)
is
function Find_object (ID : Ident; tolerant : Boolean) return p_Object_3D is
begin
if ID = empty then
return null;
else
return p_Object_3D (
Visuals_Mapping.Element (
Container => Visuals_Mapping.Map (referred),
Key => Ada.Strings.Unbounded.To_Unbounded_String (ID)
)
);
end if;
exception
when Constraint_Error =>
-- GNAT gives also the message:
-- no element available because key not in map
if tolerant then
return null;
else
Raise_Exception (
Missing_object_in_BSP'Identity,
"Object not found : [" & Trim (ID, Right) & ']'
);
end if;
end Find_object;
procedure Read (
s : in Ada.Streams.Stream_IO.Stream_Access;
tree : out BSP.p_BSP_node
)
is
use BSP;
buf : GL.IO.Input_buffer;
procedure Read_Intel is new Read_Intel_x86_number (U32);
test_signature : String (signature_bsp'Range);
n, j, k : U32;
ID : Ident;
tol : constant Boolean := False;
begin
String'Read (s, test_signature);
if test_signature /= signature_bsp then
raise Bad_data_format;
end if;
GL.IO.Attach_Stream (b => buf, stm => s);
Read_Intel (buf, n);
if n < 1 then
tree := null;
return;
end if;
declare
-- We put all the new - born nodes into a farm with numbered boxes,
-- because only the numbers are stored in the BSP file.
-- Once the nodes are linked together through accesses (pointers),
-- we can forget the farm and let the tree float .. .
farm : array (0 .. n) of p_BSP_Node;
begin
farm (0) := null;
for i in 1 .. n loop
farm (i) := new BSP_Node;
end loop;
for i in 1 .. n loop
Read_Intel (buf, j); -- node_id
farm (j).node_id := Integer (j);
Read_Intel (buf, k);
farm (j).front_child := farm (k);
if k = 0 then -- it is a front leaf - > associate object
Read_String (buf, ID);
farm (j).front_leaf := Find_object (ID, tol);
end if;
Read_Intel (buf, k);
farm (j).back_child := farm (k);
if k = 0 then -- it is a back leaf - > associate object
Read_String (buf, ID);
farm (j).back_leaf := Find_object (ID, tol);
end if;
-- The node's geometric information (a plane):
for ii in farm (j).normal'Range loop
Read_Double (buf, farm (j).normal (ii));
end loop;
Read_Double (buf, farm (j).distance);
end loop;
tree := farm (1);
end;
end Read;
procedure Load_Internal is
new Load_generic (
Anything => BSP.p_BSP_node,
extension => BSP_extension,
animal => "BSP tree",
Read => Read
);
begin
Load_Internal (name_in_resource, tree);
end Load;
end GLOBE_3D.IO;
|
package List is
pragma Elaborate_Body;
-- Create subprogram specs for adding to and removing from a list,
-- as well as return length of list and print the list
end List;
|
-- Copyright 2017-2019 Simon Symeonidis (psyomn)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.with Interfaces; use Interfaces;
with Interfaces; use Interfaces;
package Headers is
type Byte is range 0 .. 16#ff#;
type String_Access is access String;
type File_Signature is
record
Magic_Number : Unsigned_64;
Extension : String_Access;
Offset : Unsigned_64;
Bits : Natural;
Description : String_Access;
end record;
Unknown_Header : exception;
type Signatures is array (Positive range <>) of File_Signature;
type Magic_Bytes is array (Positive range <>) of Byte;
Zlib_No_Compression
: constant Unsigned_64 := 16#78_01#;
Zlib_Default_Compression
: constant Unsigned_64 := 16#78_9C#;
Zlib_Best_Compression
: constant Unsigned_64 := 16#78_DA#;
Dos_Executable
: constant Unsigned_64 := 16#4D_5A#;
-- Compressed with Lempel-Ziv-Welch algorithm
Tar_Z_Lzw
: constant Unsigned_64 := 16#1f_9d#;
-- Compressed with LZH
Tar_Z_Lzh
: constant Unsigned_64 := 16#1f_0a#;
Bz2
: constant Unsigned_64 := 16#42_5A_68#;
Webm
: constant Unsigned_64 := 16#1A_45_Df_A3#;
Psd
: constant Unsigned_64 := 16#38_42_50_53#;
Flif
: constant Unsigned_64 := 16#46_4c_49_46#;
Ogg
: constant Unsigned_64 := 16#4F_67_67_53#;
Rpm
: constant Unsigned_64 := 16#ed_ab_ee_db#;
Kindle_Updater
: constant Unsigned_64 := 16#53_50_30_31#;
Palm_Calendar_Archive
: constant Unsigned_64 := 16#be_ba_fe_ca#;
-- cafe babe! nice :)
Palm_To_Do_Archive
: constant Unsigned_64 := 16#00_01_42_44#;
Palm_Calendar_Archive_2
: constant Unsigned_64 := 16#00_01_44_54#;
Palm_Data_File
: constant Unsigned_64 := 16#00_01_00_00#;
Ico
: constant Unsigned_64 := 16#00_00_01_00#;
Tiff_Little_Endian
: constant Unsigned_64 := 16#49_49_2A_00#;
Tiff_Little_Big_Endian
: constant Unsigned_64 := 16#4D_4D_00_2A#;
Gif_87a
: constant Unsigned_64 := 16#47_49_46_38_37_61#;
Gif_89a
: constant Unsigned_64 := 16#47_49_46_38_39_61#;
Rar_1_50
: constant Unsigned_64 := 16#52_61_72_21_1a_07_00#;
Ms_Office
: constant Unsigned_64 := 16#d0_cf_11_e0_a1_b1_1a_e1#;
Rar_5
: constant Unsigned_64 := 16#52_61_72_21_1a_07_01_00#;
Tar_Ustar_00
: constant Unsigned_64 := 16#75_73_74_61_72_00_30_30#;
Tar_Ustar
: constant Unsigned_64 := 16#75_73_74_61_72_20_20_00#;
Png
: constant Unsigned_64 := 16#89_50_4e_47_0d_0a_1a_0a#;
-- TODO
-- Cr2 49_49_2A_00_10_00_00_00_43_52
-- Backmike_Disk 42_41_43_4b_4d_49_4b_45_44_49_53_4b
All_File_Signatures : constant Signatures
:= (
(Magic_Number => Dos_Executable,
Extension => new String'("exe"),
Bits => 16,
Offset => 0,
Description => new String'("MS Dos Executable")),
(Magic_Number => Tar_Z_Lzw,
Extension => new String'("tar"),
Bits => 0,
Offset => 0,
Description => new String'("Tar LZW archive")),
(Magic_Number => Tar_Z_Lzh,
Extension => new String'("tar"),
Bits => 0,
Offset => 0,
Description => new String'("Tar LZH archive")),
(Magic_Number => Bz2,
Extension => new String'("bz"),
Bits => 24,
Offset => 0,
Description => new String'("bunzip archive")),
(Magic_Number => Webm,
Extension => new String'("webm"),
Bits => 32,
Offset => 0,
Description => new String'("webm video file")),
(Magic_Number => Psd,
Extension => new String'("psd"),
Bits => 32,
Offset => 0,
Description => new String'("adobe photoshop document")),
(Magic_Number => Flif,
Extension => new String'("flif"),
Bits => 32,
Offset => 0,
Description => new String'("free lossless image format")),
(Magic_Number => Ogg,
Extension => new String'("ogg"),
Bits => 32,
Offset => 0,
Description => new String'("Ogg audio")),
(Magic_Number => Rpm,
Extension => new String'("rpm"),
Bits => 32,
Offset => 0,
Description => new String'("redhat package")),
(Magic_Number => Kindle_Updater,
Extension => new String'("bin"),
Bits => 32,
Offset => 0,
Description => new String'("kindle updater")),
(Magic_Number => Palm_Calendar_Archive,
Extension => new String'("dba"),
Bits => 32,
Offset => 0,
Description => new String'("palm calendar archive")),
(Magic_Number => Palm_To_Do_Archive,
Extension => new String'("dba"),
Bits => 32,
Offset => 0,
Description => new String'("palm todo archive")),
(Magic_Number => Palm_Calendar_Archive_2,
Extension => new String'("tda"),
Bits => 32,
Offset => 0,
Description => new String'("palm calendar archive")),
(Magic_Number => Palm_Data_File,
Extension => new String'(""),
Bits => 32,
Offset => 0,
Description =>
new String'("palm desktop data file (ms access format)")),
(Magic_Number => Gif_87a,
Extension => new String'("gif"),
Bits => 48,
Offset => 0,
Description => new String'("gif picture (87a)")),
(Magic_Number => Gif_89a,
Extension => new String'("gif"),
Bits => 48,
Offset => 0,
Description => new String'("gif picture (89a)")),
(Magic_Number => Png,
Extension => new String'("png"),
Bits => 0,
Offset => 0,
Description => new String'("PNG picture")),
(Magic_Number => Zlib_No_Compression,
Extension => new String'("zlib"),
Bits => 16,
Offset => 0,
Description => new String'("zlib no compression")),
(Magic_Number => Zlib_Default_Compression,
Extension => new String'("zlib"),
Bits => 16,
Offset => 0,
Description => new String'("zlib default compression")),
(Magic_Number => Zlib_Best_Compression,
Extension => new String'("zlib"),
Bits => 16,
Offset => 0,
Description => new String'("zlib best compression"))
);
procedure Print_File_Info (F : File_Signature);
end Headers;
|
with Ada.Text_Io;
use Ada.Text_Io;
package body Qsort is
task body SortTask is
List : vector_ptr;
Kids : array(1..2) of Sort_access;
HalfIndex : Integer;
HalfIndex2 : Integer;
LLeft : vector_ptr;
LRight : vector_ptr;
begin
accept PortIn(ValIn : in vector_ptr) do
List := ValIn;
Put_Line(Integer'Image(List'Length));
if List'Length > 2 then
Put_Line("Split");
HalfIndex := List'Length/2;
HalfIndex2 := HalfIndex + 1;
Put_Line(Integer'Image(HalfIndex));
LLeft := new vector(List'first..HalfIndex);
LRight := new vector(HalfIndex2..List'last);
--Kids(1).PortIn(LLeft);
--Kids(2).PortIn(LRight);
else
Put_Line("Sort");
end if;
end PortIn;
end SortTask;
procedure Sort (List : in out vector_ptr) is
sort_task_1 : SortTask;
begin
sort_task_1.PortIn(List);
end Sort;
end Qsort; |
-----------------------------------------------------------------------
-- gen-artifacts-distribs-bundles -- Merge bundles for distribution artifact
-- Copyright (C) 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with Ada.Text_IO;
with Util.Log.Loggers;
with Util.Properties;
package body Gen.Artifacts.Distribs.Bundles is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Bundles");
-- ------------------------------
-- Create a distribution rule to copy a set of files or directories.
-- ------------------------------
function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is
pragma Unreferenced (Node);
Result : constant Bundle_Rule_Access := new Bundle_Rule;
begin
return Result.all'Access;
end Create_Rule;
-- ------------------------------
-- Get a name to qualify the installation rule (used for logs).
-- ------------------------------
overriding
function Get_Install_Name (Rule : in Bundle_Rule) return String is
pragma Unreferenced (Rule);
begin
return "bundle";
end Get_Install_Name;
-- ------------------------------
-- Install the file <b>File</b> according to the distribution rule.
-- Merge all the files listed in <b>Files</b> in the target path specified by <b>Path</b>.
-- ------------------------------
overriding
procedure Install (Rule : in Bundle_Rule;
Path : in String;
Files : in File_Vector;
Context : in out Generator'Class) is
procedure Load_File (File : in File_Record);
procedure Merge_Property (Name : in String;
Item : in Util.Properties.Value);
procedure Save_Property (Name : in String;
Item : in Util.Properties.Value);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
Output : Ada.Text_IO.File_Type;
Merge : Util.Properties.Manager;
-- ------------------------------
-- Merge the property into the target property list.
-- ------------------------------
procedure Merge_Property (Name : in String;
Item : in Util.Properties.Value) is
begin
Merge.Set_Value (Name, Item);
end Merge_Property;
procedure Save_Property (Name : in String;
Item : in Util.Properties.Value) is
begin
Ada.Text_IO.Put (Output, Name);
Ada.Text_IO.Put (Output, "=");
Ada.Text_IO.Put_Line (Output, Util.Properties.To_String (Item));
end Save_Property;
-- ------------------------------
-- Append the file to the output
-- ------------------------------
procedure Load_File (File : in File_Record) is
File_Path : constant String := Rule.Get_Source_Path (File);
Props : Util.Properties.Manager;
begin
Log.Info ("loading {0}", File_Path);
Props.Load_Properties (Path => File_Path);
Props.Iterate (Process => Merge_Property'Access);
exception
when Ex : Ada.IO_Exceptions.Name_Error =>
Context.Error ("Cannot read {0}: ", File_Path, Ada.Exceptions.Exception_Message (Ex));
end Load_File;
Iter : File_Cursor := Files.First;
begin
Ada.Directories.Create_Path (Dir);
while File_Record_Vectors.Has_Element (Iter) loop
File_Record_Vectors.Query_Element (Iter, Load_File'Access);
File_Record_Vectors.Next (Iter);
end loop;
Ada.Text_IO.Create (File => Output, Mode => Ada.Text_IO.Out_File, Name => Path);
Merge.Iterate (Process => Save_Property'Access);
Ada.Text_IO.Close (File => Output);
end Install;
end Gen.Artifacts.Distribs.Bundles;
|
-- { dg-do compile }
package Small_Alignment is
type Int is range -512 .. 511;
for Int'Alignment use 1;
type R is record
I: Int;
end record;
Pragma Pack (R);
end Small_Alignment;
|
--
-- RTEMS / Specification
--
-- DESCRIPTION:
--
-- This package provides the interface to the RTEMS API.
--
-- DEPENDENCIES:
--
--
--
-- COPYRIGHT (c) 1997.
-- On-Line Applications Research Corporation (OAR).
--
-- The license and distribution terms for this file may in
-- the file LICENSE in this distribution or at
-- http://www.rtems.com/license/LICENSE.
--
-- $Id$
--
with System;
with System.Storage_Elements; use System.Storage_Elements;
with Interfaces;
with Interfaces.C;
package RTEMS is
pragma Elaborate_Body (RTEMS);
Structure_Alignment : constant := 8;
--
-- RTEMS Base Types
--
subtype Unsigned8 is Interfaces.Unsigned_8;
subtype Unsigned16 is Interfaces.Unsigned_16;
subtype Unsigned32 is Interfaces.Unsigned_32;
subtype Signed32 is Interfaces.Integer_32;
type Unsigned32_Pointer is access all RTEMS.Unsigned32;
type Unsigned16_Pointer is access all RTEMS.Unsigned16;
type Unsigned8_Pointer is access all RTEMS.Unsigned8;
type Signed32_Pointer is access all RTEMS.Signed32;
subtype Boolean is RTEMS.Unsigned32;
subtype Address is System.Address;
subtype Single is Interfaces.C.C_float;
subtype Double is Interfaces.C.Double;
--
-- The following define the size of each of the base types in
-- both bits and system units.
--
Unsigned8_Bits : constant := 7;
Unsigned16_Bits : constant := 15;
Unsigned32_Bits : constant := 31;
Boolean_Bits : constant := 31;
Address_Bits : constant := 31;
Single_Bits : constant := 31;
Double_Bits : constant := 63;
Unsigned8_Units : constant := 1;
Unsigned16_Units : constant := 2;
Unsigned32_Units : constant := 4;
Boolean_Units : constant := 4;
Address_Units : constant := 4;
Single_Units : constant := 4;
Double_Units : constant := 8;
Null_Address : constant RTEMS.Address :=
System.Storage_Elements.To_Address(0);
True : constant RTEMS.Boolean := 1;
False : constant RTEMS.Boolean := 0;
-- More Types
--
subtype Name is RTEMS.Unsigned32;
subtype ID is RTEMS.Unsigned32;
subtype Interval is RTEMS.Unsigned32;
subtype Attribute is RTEMS.Unsigned32;
subtype Mode is RTEMS.Unsigned32;
subtype Option is RTEMS.Unsigned32;
subtype Task_Priority is RTEMS.Unsigned32;
subtype Notepad_Index is RTEMS.Unsigned32 range 0 .. 15;
subtype Event_Set is RTEMS.Unsigned32;
subtype Signal_Set is RTEMS.Unsigned32;
subtype Debug_Set is RTEMS.Unsigned32;
subtype Device_Major_Number is RTEMS.Unsigned32;
subtype Device_Minor_Number is RTEMS.Unsigned32;
subtype Vector_Number is RTEMS.Unsigned32;
subtype ISR_Level is RTEMS.Unsigned32;
subtype Node is RTEMS.Unsigned32;
--
-- Task Related Types
-- XXXX fix this
subtype Task_Argument is RTEMS.Unsigned32;
type Task_Argument_PTR is access all Task_Argument;
-- XXXX fix this
subtype TCB is RTEMS.Unsigned32;
type TCB_Pointer is access all RTEMS.TCB;
subtype Task_States is RTEMS.Unsigned32;
type Task_Entry is access procedure (
Argument : RTEMS.Unsigned32
);
--
-- Clock and Time of Day Types
--
type Time_Of_Day is
record
Year : RTEMS.Unsigned32; -- year, A.D.
Month : RTEMS.Unsigned32; -- month, 1 .. 12
Day : RTEMS.Unsigned32; -- day, 1 .. 31
Hour : RTEMS.Unsigned32; -- hour, 0 .. 23
Minute : RTEMS.Unsigned32; -- minute, 0 .. 59
Second : RTEMS.Unsigned32; -- second, 0 .. 59
Ticks : RTEMS.Unsigned32; -- elapsed ticks between seconds
end record;
type Clock_Time_Value is
record
Seconds : RTEMS.Unsigned32;
Microseconds : RTEMS.Unsigned32;
end record;
type Clock_Get_Options is (
Clock_Get_TOD,
Clock_Get_Seconds_Since_Epoch,
Clock_Get_Ticks_Since_Boot,
Clock_Get_Ticks_Per_Seconds,
Clock_Get_Time_Value
);
--
-- Device Driver Entry Prototype
--
type Device_Driver_Entry is access function (
Major : in RTEMS.Device_Major_Number;
Minor : in RTEMS.Device_Major_Number;
Argument : in RTEMS.Unsigned32;
ID : in RTEMS.Unsigned32
) return RTEMS.Unsigned32;
type Driver_Address_Table_Entry is
record
Initialization : RTEMS.Device_Driver_Entry;
Open : RTEMS.Device_Driver_Entry;
Close : RTEMS.Device_Driver_Entry;
Read : RTEMS.Device_Driver_Entry;
Write : RTEMS.Device_Driver_Entry;
Control : RTEMS.Device_Driver_Entry;
end record;
type Driver_Address_Table is array ( RTEMS.Unsigned32
range 1 .. RTEMS.Unsigned32'Last ) of RTEMS.Driver_Address_Table_Entry;
type Driver_Address_Table_Pointer is access all Driver_Address_Table;
type Driver_Name_t is
record
Device_Name : RTEMS.Address;
Device_Name_Length : RTEMS.Unsigned32;
Major : RTEMS.Device_Major_Number;
Minor : RTEMS.Device_Minor_Number;
end record;
type Driver_Name_t_Pointer is access all Driver_Name_t;
--
-- Ident Options
--
Search_All_Nodes : constant RTEMS.Node := 0;
--
-- Options
--
Default_Options : constant RTEMS.Option := 16#0000#;
Wait : constant RTEMS.Option := 16#0000#;
No_Wait : constant RTEMS.Option := 16#0001#;
Event_All : constant RTEMS.Option := 16#0000#;
Event_Any : constant RTEMS.Option := 16#0002#;
--
-- Mode constants
--
Default_Modes : constant RTEMS.Mode := 16#0000#;
All_Mode_Masks : constant RTEMS.Mode := 16#0000_ffff#;
Current_Mode : constant RTEMS.Mode := 16#0000_0000#;
Preempt_Mask : constant RTEMS.Mode := 16#0000_0100#;
Timeslice_Mask : constant RTEMS.Mode := 16#0000_0200#;
ASR_Mask : constant RTEMS.Mode := 16#0000_0400#;
Interrupt_Mask : RTEMS.Mode;
Preempt : constant RTEMS.Mode := 16#0000_0000#;
No_Preempt : constant RTEMS.Mode := 16#0000_0100#;
No_Timeslice : constant RTEMS.Mode := 16#0000_0000#;
Timeslice : constant RTEMS.Mode := 16#0000_0200#;
ASR : constant RTEMS.Mode := 16#0000_0000#;
No_ASR : constant RTEMS.Mode := 16#0000_0400#;
pragma Import (C, Interrupt_Mask, "rtems_interrupt_mask");
--
-- Attribute constants
--
Default_Attributes : constant RTEMS.Attribute := 16#00000000#;
No_Floating_Point : constant RTEMS.Attribute := 16#00000000#;
Floating_Point : constant RTEMS.Attribute := 16#00000001#;
Local : constant RTEMS.Attribute := 16#00000000#;
Global : constant RTEMS.Attribute := 16#00000002#;
FIFO : constant RTEMS.Attribute := 16#00000000#;
Priority : constant RTEMS.Attribute := 16#00000004#;
Counting_Semaphore : constant RTEMS.Attribute := 16#00000000#;
Binary_Semaphore : constant RTEMS.Attribute := 16#00000010#;
No_Inherit_Priority : constant RTEMS.Attribute := 16#00000000#;
Inherit_Priority : constant RTEMS.Attribute := 16#00000020#;
No_Priority_Ceiling : constant RTEMS.Attribute := 16#00000000#;
Priority_Ceiling : constant RTEMS.Attribute := 16#00000040#;
function Interrupt_Level (
Level : in RTEMS.Unsigned32
) return RTEMS.Attribute;
pragma Import (C, Interrupt_Level, "rtems_interrupt_level_attribute");
Minimum_Stack_Size : RTEMS.Unsigned32;
pragma Import (C, Minimum_Stack_Size, "rtems_minimum_stack_size");
--
-- Notepad index constants
--
Notepad_0 : constant RTEMS.Unsigned32 := 0;
Notepad_1 : constant RTEMS.Unsigned32 := 1;
Notepad_2 : constant RTEMS.Unsigned32 := 2;
Notepad_3 : constant RTEMS.Unsigned32 := 3;
Notepad_4 : constant RTEMS.Unsigned32 := 4;
Notepad_5 : constant RTEMS.Unsigned32 := 5;
Notepad_6 : constant RTEMS.Unsigned32 := 6;
Notepad_7 : constant RTEMS.Unsigned32 := 7;
Notepad_8 : constant RTEMS.Unsigned32 := 8;
Notepad_9 : constant RTEMS.Unsigned32 := 9;
Notepad_10 : constant RTEMS.Unsigned32 := 10;
Notepad_11 : constant RTEMS.Unsigned32 := 11;
Notepad_12 : constant RTEMS.Unsigned32 := 12;
Notepad_13 : constant RTEMS.Unsigned32 := 13;
Notepad_14 : constant RTEMS.Unsigned32 := 14;
Notepad_15 : constant RTEMS.Unsigned32 := 15;
--
-- Miscellaneous
--
No_Timeout : constant RTEMS.Interval := 0;
Self : constant RTEMS.ID := 0;
Period_Status : constant RTEMS.Interval := 0;
Yield_Processor : constant RTEMS.Interval := 0;
Current_Priority : constant RTEMS.Task_Priority := 0;
No_Priority : constant RTEMS.Task_Priority := 0;
--
-- Extension Callouts and Table
--
type Thread_Create_Extension is access procedure (
Current_Task : in RTEMS.TCB_Pointer;
New_Task : in RTEMS.TCB_Pointer
);
type Thread_Start_Extension is access procedure (
Current_Task : in RTEMS.TCB_Pointer;
Started_Task : in RTEMS.TCB_Pointer
);
type Thread_Restart_Extension is access procedure (
Current_Task : in RTEMS.TCB_Pointer;
Restarted_Task : in RTEMS.TCB_Pointer
);
type Thread_Delete_Extension is access procedure (
Current_Task : in RTEMS.TCB_Pointer;
Deleted_Task : in RTEMS.TCB_Pointer
);
type Thread_Switch_Extension is access procedure (
Current_Task : in RTEMS.TCB_Pointer;
Heir_Task : in RTEMS.TCB_Pointer
);
type Thread_Post_Switch_Extension is access procedure (
Current_Task : in RTEMS.TCB_Pointer
);
type Thread_Begin_Extension is access procedure (
Current_Task : in RTEMS.TCB_Pointer
);
type Thread_Exitted_Extension is access procedure (
Current_Task : in RTEMS.TCB_Pointer
);
type Fatal_Error_Extension is access procedure (
Error : in RTEMS.Unsigned32
);
type Extensions_Table is
record
Thread_Create : RTEMS.Thread_Create_Extension;
Thread_Start : RTEMS.Thread_Start_Extension;
Thread_Restart : RTEMS.Thread_Restart_Extension;
Thread_Delete : RTEMS.Thread_Delete_Extension;
Thread_Switch : RTEMS.Thread_Switch_Extension;
Thread_Post_Switch : RTEMS.Thread_Post_Switch_Extension;
Thread_Begin : RTEMS.Thread_Begin_Extension;
Thread_Exitted : RTEMS.Thread_Exitted_Extension;
Fatal : RTEMS.Fatal_Error_Extension;
end record;
type Extensions_Table_Pointer is access all Extensions_Table;
--
-- The following type define a pointer to a watchdog/timer service routine.
--
type Timer_Service_Routine is access procedure (
ID : in RTEMS.ID;
User_Data : in RTEMS.Address
);
--
-- The following type define a pointer to a signal service routine.
--
type ASR_Handler is access procedure (
Signals : in RTEMS.Signal_Set
);
--
-- The following type defines the status information returned
-- about a period.
--
type Rate_Monotonic_Period_States is (
Inactive, -- off chain, never initialized
Owner_Is_Blocking, -- on chain, owner is blocking on it
Active, -- on chain, running continuously
Expired_While_Blocking, -- on chain, expired while owner was was blocking
Expired -- off chain, will be reset by next
-- rtems_rate_monotonic_period
);
for Rate_Monotonic_Period_States'Size use 32;
for Rate_Monotonic_Period_States use (
Inactive => 0,
Owner_Is_Blocking => 1,
Active => 2,
Expired_While_Blocking => 3,
Expired => 4
);
type Rate_Monotonic_Period_Status is
record
State : RTEMS.Rate_Monotonic_Period_States;
Ticks_Since_Last_Period : RTEMS.Unsigned32;
Ticks_Executed_Since_Last_Period : RTEMS.Unsigned32;
end record;
--
-- Method Completions Status Codes
--
type Status_Codes is (
Successful, -- successful completion
Task_Exitted, -- returned from a task
MP_Not_Configured, -- multiprocessing not configured
Invalid_Name, -- invalid object name
Invalid_ID, -- invalid object id
Too_Many, -- too many
Timeout, -- timed out waiting
Object_Was_Deleted, -- object deleted while waiting
Invalid_Size, -- specified size was invalid
Invalid_Address, -- address specified is invalid
Invalid_Number, -- number was invalid
Not_Defined, -- item has not been initialized
Resource_In_Use, -- resources still outstanding
Unsatisfied, -- request not satisfied
Incorrect_State, -- task is in wrong state
Already_Suspended, -- task already in state
Illegal_On_Self, -- illegal on calling task
Illegal_On_Remote_Object, -- illegal for remote object
Called_From_ISR, -- called from wrong environment
Invalid_Priority, -- invalid task priority
Invalid_Clock, -- invalid date/time
Invalid_Node, -- invalid node id
Not_Configured, -- directive not configured
Not_Owner_Of_Resource, -- not owner of resource
Not_Implemented, -- directive not implemented
Internal_Error, -- RTEMS inconsistency detected
No_Memory, -- no memory left in heap
IO_Error, -- driver IO error
Proxy_Blocking -- internal multiprocessing only
);
for Status_Codes'Size use 32;
for Status_Codes use (
Successful => 0,
Task_Exitted => 1,
MP_Not_Configured => 2,
Invalid_Name => 3,
Invalid_ID => 4,
Too_Many => 5,
Timeout => 6,
Object_Was_Deleted => 7,
Invalid_Size => 8,
Invalid_Address => 9,
Invalid_NumbeR => 10,
Not_Defined => 11,
Resource_In_Use => 12,
Unsatisfied => 13,
Incorrect_State => 14,
Already_Suspended => 15,
Illegal_On_Self => 16,
Illegal_On_Remote_Object => 17,
Called_From_ISR => 18,
Invalid_Priority => 19,
Invalid_Clock => 20,
Invalid_Node => 21,
Not_Configured => 22,
Not_Owner_Of_Resource => 23,
Not_ImplementeD => 24,
Internal_Error => 25,
No_Memory => 26,
IO_Error => 27,
Proxy_Blocking => 28
);
--
-- RTEMS Events
--
Pending_Events : constant RTEMS.Event_Set := 16#0000_0000#;
All_Events : constant RTEMS.Event_Set := 16#FFFF_FFFF#;
Event_0 : constant RTEMS.Event_Set := 16#0000_0001#;
Event_1 : constant RTEMS.Event_Set := 16#0000_0002#;
Event_2 : constant RTEMS.Event_Set := 16#0000_0004#;
Event_3 : constant RTEMS.Event_Set := 16#0000_0008#;
Event_4 : constant RTEMS.Event_Set := 16#0000_0010#;
Event_5 : constant RTEMS.Event_Set := 16#0000_0020#;
Event_6 : constant RTEMS.Event_Set := 16#0000_0040#;
Event_7 : constant RTEMS.Event_Set := 16#0000_0080#;
Event_8 : constant RTEMS.Event_Set := 16#0000_0100#;
Event_9 : constant RTEMS.Event_Set := 16#0000_0200#;
Event_10 : constant RTEMS.Event_Set := 16#0000_0400#;
Event_11 : constant RTEMS.Event_Set := 16#0000_0800#;
Event_12 : constant RTEMS.Event_Set := 16#0000_1000#;
Event_13 : constant RTEMS.Event_Set := 16#0000_2000#;
Event_14 : constant RTEMS.Event_Set := 16#0000_4000#;
Event_15 : constant RTEMS.Event_Set := 16#0000_8000#;
Event_16 : constant RTEMS.Event_Set := 16#0001_0000#;
Event_17 : constant RTEMS.Event_Set := 16#0002_0000#;
Event_18 : constant RTEMS.Event_Set := 16#0004_0000#;
Event_19 : constant RTEMS.Event_Set := 16#0008_0000#;
Event_20 : constant RTEMS.Event_Set := 16#0010_0000#;
Event_21 : constant RTEMS.Event_Set := 16#0020_0000#;
Event_22 : constant RTEMS.Event_Set := 16#0040_0000#;
Event_23 : constant RTEMS.Event_Set := 16#0080_0000#;
Event_24 : constant RTEMS.Event_Set := 16#0100_0000#;
Event_25 : constant RTEMS.Event_Set := 16#0200_0000#;
Event_26 : constant RTEMS.Event_Set := 16#0400_0000#;
Event_27 : constant RTEMS.Event_Set := 16#0800_0000#;
Event_28 : constant RTEMS.Event_Set := 16#1000_0000#;
Event_29 : constant RTEMS.Event_Set := 16#2000_0000#;
Event_30 : constant RTEMS.Event_Set := 16#4000_0000#;
Event_31 : constant RTEMS.Event_Set := 16#8000_0000#;
--
-- RTEMS Signals
--
All_Signals : constant RTEMS.Signal_Set := 16#7FFFFFFF#;
Signal_0 : constant RTEMS.Signal_Set := 16#00000001#;
Signal_1 : constant RTEMS.Signal_Set := 16#00000002#;
Signal_2 : constant RTEMS.Signal_Set := 16#00000004#;
Signal_3 : constant RTEMS.Signal_Set := 16#00000008#;
Signal_4 : constant RTEMS.Signal_Set := 16#00000010#;
Signal_5 : constant RTEMS.Signal_Set := 16#00000020#;
Signal_6 : constant RTEMS.Signal_Set := 16#00000040#;
Signal_7 : constant RTEMS.Signal_Set := 16#00000080#;
Signal_8 : constant RTEMS.Signal_Set := 16#00000100#;
Signal_9 : constant RTEMS.Signal_Set := 16#00000200#;
Signal_10 : constant RTEMS.Signal_Set := 16#00000400#;
Signal_11 : constant RTEMS.Signal_Set := 16#00000800#;
Signal_12 : constant RTEMS.Signal_Set := 16#00001000#;
Signal_13 : constant RTEMS.Signal_Set := 16#00002000#;
Signal_14 : constant RTEMS.Signal_Set := 16#00004000#;
Signal_15 : constant RTEMS.Signal_Set := 16#00008000#;
Signal_16 : constant RTEMS.Signal_Set := 16#00010000#;
Signal_17 : constant RTEMS.Signal_Set := 16#00020000#;
Signal_18 : constant RTEMS.Signal_Set := 16#00040000#;
Signal_19 : constant RTEMS.Signal_Set := 16#00080000#;
Signal_20 : constant RTEMS.Signal_Set := 16#00100000#;
Signal_21 : constant RTEMS.Signal_Set := 16#00200000#;
Signal_22 : constant RTEMS.Signal_Set := 16#00400000#;
Signal_23 : constant RTEMS.Signal_Set := 16#00800000#;
Signal_24 : constant RTEMS.Signal_Set := 16#01000000#;
Signal_25 : constant RTEMS.Signal_Set := 16#02000000#;
Signal_26 : constant RTEMS.Signal_Set := 16#04000000#;
Signal_27 : constant RTEMS.Signal_Set := 16#08000000#;
Signal_28 : constant RTEMS.Signal_Set := 16#10000000#;
Signal_29 : constant RTEMS.Signal_Set := 16#20000000#;
Signal_30 : constant RTEMS.Signal_Set := 16#40000000#;
Signal_31 : constant RTEMS.Signal_Set := 16#80000000#;
--
-- RTEMS API Configuration Information
--
type Initialization_Tasks_Table_Entry is
record
Name : RTEMS.Name; -- task name
Stack_Size : RTEMS.Unsigned32; -- task stack size
Initial_Priority : RTEMS.Task_priority; -- task priority
Attribute_Set : RTEMS.Attribute; -- task attributes
Entry_Point : RTEMS.Task_Entry; -- task entry point
Mode_Set : RTEMS.Mode; -- task initial mode
Argument : RTEMS.Unsigned32; -- task argument
end record;
type Initialization_Tasks_Table is array ( RTEMS.Unsigned32 range <> ) of
RTEMS.Initialization_Tasks_Table_Entry;
type Initialization_Tasks_Table_Pointer is access all
Initialization_Tasks_Table;
type API_Configuration_Table is
record
Maximum_Tasks : RTEMS.Unsigned32;
Maximum_Timers : RTEMS.Unsigned32;
Maximum_Semaphores : RTEMS.Unsigned32;
Maximum_Message_queues : RTEMS.Unsigned32;
Maximum_Partitions : RTEMS.Unsigned32;
Maximum_Regions : RTEMS.Unsigned32;
Maximum_Ports : RTEMS.Unsigned32;
Maximum_Periods : RTEMS.Unsigned32;
Number_Of_Initialization_Tasks : RTEMS.Unsigned32;
User_Initialization_Tasks_Table :
RTEMS.Initialization_Tasks_Table_Pointer;
end record;
type API_Configuration_Table_Pointer is access all API_Configuration_Table;
--
-- RTEMS POSIX API Configuration Information
--
type POSIX_Thread_Entry is access procedure (
Argument : in RTEMS.Address
);
type POSIX_Initialization_Threads_Table_Entry is
record
Thread_Entry : RTEMS.POSIX_Thread_Entry;
end record;
type POSIX_Initialization_Threads_Table is array
( RTEMS.Unsigned32 range <> ) of
RTEMS.POSIX_Initialization_Threads_Table_Entry;
type POSIX_Initialization_Threads_Table_Pointer is access all
POSIX_Initialization_Threads_Table;
type POSIX_API_Configuration_Table_Entry is
record
Maximum_Threads : Interfaces.C.Int;
Maximum_Mutexes : Interfaces.C.Int;
Maximum_Condition_Variables : Interfaces.C.Int;
Maximum_Keys : Interfaces.C.Int;
Maximum_Queued_Signals : Interfaces.C.Int;
Number_Of_Initialization_Tasks : Interfaces.C.Int;
User_Initialization_Tasks_Table :
RTEMS.POSIX_Initialization_Threads_Table_Pointer;
end record;
type POSIX_API_Configuration_Table is array ( RTEMS.Unsigned32 range <> ) of
RTEMS.POSIX_API_Configuration_Table_Entry;
type POSIX_API_Configuration_Table_Pointer is access all
RTEMS.POSIX_API_Configuration_Table;
--
-- MPCI Information include MPCI Configuration
--
type Configuration_Table_Pointer;
type MP_Packet_Classes is (
MP_PACKET_MPCI_INTERNAL,
MP_PACKET_TASKS,
MP_PACKET_MESSAGE_QUEUE,
MP_PACKET_SEMAPHORE,
MP_PACKET_PARTITION,
MP_PACKET_REGION,
MP_PACKET_EVENT,
MP_PACKET_SIGNAL
);
for MP_Packet_Classes use (
MP_PACKET_MPCI_INTERNAL => 0,
MP_PACKET_TASKS => 1,
MP_PACKET_MESSAGE_QUEUE => 2,
MP_PACKET_SEMAPHORE => 3,
MP_PACKET_PARTITION => 4,
MP_PACKET_REGION => 5,
MP_PACKET_EVENT => 6,
MP_PACKET_SIGNAL => 7
);
type Packet_Prefix is
record
The_Class : RTEMS.MP_Packet_Classes;
ID : RTEMS.ID;
Source_TID : RTEMS.ID;
Source_Priority : RTEMS.Task_Priority;
Return_Code : RTEMS.Unsigned32;
Length : RTEMS.Unsigned32;
To_Convert : RTEMS.Unsigned32;
Timeout : RTEMS.Interval;
end record;
type Packet_Prefix_Pointer is access all Packet_Prefix;
type MPCI_Initialization_Entry is access procedure (
Configuration : in RTEMS.Configuration_Table_Pointer
);
type MPCI_Get_Packet_Entry is access procedure (
Packet : access RTEMS.Packet_Prefix_Pointer
);
type MPCI_Return_Packet_Entry is access procedure (
Packet : in RTEMS.Packet_Prefix_Pointer
);
type MPCI_Send_Entry is access procedure (
Packet : in RTEMS.Packet_Prefix_Pointer
);
type MPCI_Receive_Entry is access procedure (
Packet : access RTEMS.Packet_Prefix_Pointer
);
type MPCI_Table is
record
Default_Timeout : RTEMS.Unsigned32; -- in ticks
Maximum_Packet_Size : RTEMS.Unsigned32;
Initialization : RTEMS.MPCI_Initialization_Entry;
Get_Packet : RTEMS.MPCI_Get_Packet_Entry;
Return_Packet : RTEMS.MPCI_Return_Packet_Entry;
Send : RTEMS.MPCI_Send_Entry;
Receive : RTEMS.MPCI_Receive_Entry;
end record;
type MPCI_Table_Pointer is access all MPCI_Table;
--
-- Configuration Information
--
type Multiprocessing_Table is
record
Node : RTEMS.Unsigned32;
Maximum_Nodes : RTEMS.Unsigned32;
Maximum_Global_Objects : RTEMS.Unsigned32;
Maximum_Proxies : RTEMS.Unsigned32;
User_MPCI_Table : RTEMS.MPCI_Table_Pointer;
end record;
type Multiprocessing_Table_Pointer is access all Multiprocessing_Table;
type Configuration_Table is
record
Work_Space_Start : RTEMS.Address;
Work_Space_Size : RTEMS.Unsigned32;
Maximum_Extensions : RTEMS.Unsigned32;
Microseconds_Per_Tick : RTEMS.Unsigned32;
Ticks_Per_Timeslice : RTEMS.Unsigned32;
Maximum_Devices : RTEMS.Unsigned32;
Maximum_Drivers : RTEMS.Unsigned32;
Number_Of_Device_Drivers : RTEMS.Unsigned32;
Device_Driver_Table : RTEMS.Driver_Address_Table_Pointer;
Number_Of_Initial_Extensions : RTEMS.Unsigned32;
User_Extension_Table : RTEMS.Extensions_Table_Pointer;
User_Multiprocessing_Table : RTEMS.Multiprocessing_Table_Pointer;
RTEMS_API_Configuration : RTEMS.API_Configuration_Table_Pointer;
POSIX_API_Configuration : RTEMS.POSIX_API_Configuration_Table_Pointer;
ITRON_API_Configuration : RTEMS.Address; -- XXX FIX ME
end record;
type Configuration_Table_Pointer is access all Configuration_Table;
--
-- For now, do not provide access to the CPU Table from Ada.
-- When this type is provided, a CPU dependent file must
-- define it.
--
subtype CPU_Table is RTEMS.Address;
type CPU_Table_Pointer is access all CPU_Table;
--
-- Utility Functions
--
function From_Ada_Boolean (
Ada_Boolean : Standard.Boolean
) return RTEMS.Boolean;
function To_Ada_Boolean (
RTEMS_Boolean : RTEMS.Boolean
) return Standard.Boolean;
function Milliseconds_To_Microseconds (
Milliseconds : RTEMS.Unsigned32
) return RTEMS.Unsigned32;
function Microseconds_To_Ticks (
Microseconds : RTEMS.Unsigned32
) return RTEMS.Interval;
function Milliseconds_To_Ticks (
Milliseconds : RTEMS.Unsigned32
) return RTEMS.Interval;
function Build_Name (
C1 : in Character;
C2 : in Character;
C3 : in Character;
C4 : in Character
) return RTEMS.Name;
procedure Name_To_Characters (
Name : in RTEMS.Name;
C1 : out Character;
C2 : out Character;
C3 : out Character;
C4 : out Character
);
function Get_Node (
ID : in RTEMS.ID
) return RTEMS.Unsigned32;
function Get_Index (
ID : in RTEMS.ID
) return RTEMS.Unsigned32;
function Are_Statuses_Equal (
Status : in RTEMS.Status_Codes;
Desired : in RTEMS.Status_Codes
) return Standard.Boolean;
function Is_Status_Successful (
Status : in RTEMS.Status_Codes
) return Standard.Boolean;
function Subtract (
Left : in RTEMS.Address;
Right : in RTEMS.Address
) return RTEMS.Unsigned32;
function Are_Equal (
Left : in RTEMS.Address;
Right : in RTEMS.Address
) return Standard.Boolean;
--
-- RTEMS API
--
--
-- Initialization Manager
--
procedure Initialize_Executive (
Configuration_Table : in RTEMS.Configuration_Table_Pointer;
CPU_Table : in RTEMS.CPU_Table_Pointer
);
procedure Initialize_Executive_Early (
Configuration_Table : in RTEMS.Configuration_Table_Pointer;
CPU_Table : in RTEMS.CPU_Table_Pointer;
Level : out RTEMS.ISR_Level
);
procedure Initialize_Executive_Late (
BSP_Level : in RTEMS.ISR_Level
);
procedure Shutdown_Executive (
Result : in RTEMS.Unsigned32
);
--
-- Task Manager
--
procedure Task_Create (
Name : in RTEMS.Name;
Initial_Priority : in RTEMS.Task_Priority;
Stack_Size : in Unsigned32;
Initial_Modes : in RTEMS.Mode;
Attribute_Set : in RTEMS.Attribute;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Task_Ident (
Name : in RTEMS.Name;
Node : in RTEMS.Node;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Task_Start (
ID : in RTEMS.ID;
Entry_Point : in RTEMS.Task_Entry;
Argument : in RTEMS.Task_Argument;
Result : out RTEMS.Status_Codes
);
procedure Task_Restart (
ID : in RTEMS.ID;
Argument : in RTEMS.Task_Argument;
Result : out RTEMS.Status_Codes
);
procedure Task_Delete (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Task_Suspend (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Task_Resume (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Task_Set_Priority (
ID : in RTEMS.ID;
New_Priority : in RTEMS.Task_Priority;
Old_Priority : out RTEMS.Task_Priority;
Result : out RTEMS.Status_Codes
);
procedure Task_Mode (
Mode_Set : in RTEMS.Mode;
Mask : in RTEMS.Mode;
Previous_Mode_Set : out RTEMS.Mode;
Result : out RTEMS.Status_Codes
);
procedure Task_Get_Note (
ID : in RTEMS.ID;
Notepad : in RTEMS.Notepad_Index;
Note : out RTEMS.Unsigned32;
Result : out RTEMS.Status_Codes
);
procedure Task_Set_Note (
ID : in RTEMS.ID;
Notepad : in RTEMS.Notepad_Index;
Note : in RTEMS.Unsigned32;
Result : out RTEMS.Status_Codes
);
type Task_Variable_Dtor is access procedure (
Argument : in RTEMS.Address;
);
procedure Task_Variable_Add (
ID : in RTEMS.ID;
Task_Variable : in RTEMS.Address;
Dtor : in RTEMS.Task_Variable_Dtor;
Result : out RTEMS.Status_Codes
);
procedure Task_Variable_Get (
ID : in RTEMS.ID;
Task_Variable : out RTEMS.Address;
Task_Variable_Value : out RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure Task_Variable_Delete (
ID : in RTEMS.ID;
Task_Variable : out RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure Task_Wake_When (
Time_Buffer : in RTEMS.Time_Of_Day;
Result : out RTEMS.Status_Codes
);
procedure Task_Wake_After (
Ticks : in RTEMS.Interval;
Result : out RTEMS.Status_Codes
);
--
-- Interrupt Manager
--
procedure Interrupt_Catch (
New_ISR_Handler : in RTEMS.Address;
Vector : in RTEMS.Vector_Number;
Old_ISR_Handler : out RTEMS.Address;
Result : out RTEMS.Status_Codes
);
function Interrupt_Disable return RTEMS.ISR_Level;
pragma Interface (C, Interrupt_Disable);
pragma Interface_Name (Interrupt_Disable, "rtems_interrupt_disable");
procedure Interrupt_Enable (
Level : in RTEMS.ISR_Level
);
pragma Interface (C, Interrupt_Enable);
pragma Interface_Name (Interrupt_Enable, "rtems_interrupt_enable");
procedure Interrupt_Flash (
Level : in RTEMS.ISR_Level
);
pragma Interface (C, Interrupt_Flash);
pragma Interface_Name (Interrupt_Flash, "rtems_interrupt_flash");
function Interrupt_Is_In_Progress return RTEMS.Boolean;
pragma Interface (C, Interrupt_Is_In_Progress);
pragma Interface_Name
(Interrupt_Is_In_Progress, "rtems_interrupt_is_in_progress");
--
-- Clock Manager
--
procedure Clock_Get (
Option : in RTEMS.Clock_Get_Options;
Time_Buffer : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure Clock_Set (
Time_Buffer : in RTEMS.Time_Of_Day;
Result : out RTEMS.Status_Codes
);
procedure Clock_Tick (
Result : out RTEMS.Status_Codes
);
--
-- Extension Manager
--
procedure Extension_Create (
Name : in RTEMS.Name;
Table : in RTEMS.Extensions_Table_Pointer;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Extension_Ident (
Name : in RTEMS.Name;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Extension_Delete (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
--
-- Timer Manager
--
procedure Timer_Create (
Name : in RTEMS.Name;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Timer_Ident (
Name : in RTEMS.Name;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Timer_Delete (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Timer_Fire_After (
ID : in RTEMS.ID;
Ticks : in RTEMS.Interval;
Routine : in RTEMS.Timer_Service_Routine;
User_Data : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure Timer_Server_Fire_After (
ID : in RTEMS.ID;
Ticks : in RTEMS.Interval;
Routine : in RTEMS.Timer_Service_Routine;
User_Data : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure Timer_Fire_When (
ID : in RTEMS.ID;
Wall_Time : in RTEMS.Time_Of_Day;
Routine : in RTEMS.Timer_Service_Routine;
User_Data : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure Timer_Server_Fire_When (
ID : in RTEMS.ID;
Wall_Time : in RTEMS.Time_Of_Day;
Routine : in RTEMS.Timer_Service_Routine;
User_Data : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure Timer_Reset (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Timer_Cancel (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Timer_Initiate_Server (
Server_Priority : in RTEMS.Task_Priority;
Stack_Size : in Unsigned32;
Attribute_Set : in RTEMS.Attribute;
Result : out RTEMS.Status_Codes
);
--
-- Semaphore Manager
--
procedure Semaphore_Create (
Name : in RTEMS.Name;
Count : in RTEMS.Unsigned32;
Attribute_Set : in RTEMS.Attribute;
Priority_Ceiling : in RTEMS.Task_Priority;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Semaphore_Delete (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Semaphore_Ident (
Name : in RTEMS.Name;
Node : in RTEMS.Unsigned32;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Semaphore_Obtain (
ID : in RTEMS.ID;
Option_Set : in RTEMS.Option;
Timeout : in RTEMS.Interval;
Result : out RTEMS.Status_Codes
);
procedure Semaphore_Release (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
--
-- Message Queue Manager
--
procedure Message_Queue_Create (
Name : in RTEMS.Name;
Count : in RTEMS.Unsigned32;
Max_Message_Size : in RTEMS.Unsigned32;
Attribute_Set : in RTEMS.Attribute;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Message_Queue_Ident (
Name : in RTEMS.Name;
Node : in RTEMS.Unsigned32;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Message_Queue_Delete (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Message_Queue_Send (
ID : in RTEMS.ID;
Buffer : in RTEMS.Address;
Size : in RTEMS.Unsigned32;
Result : out RTEMS.Status_Codes
);
procedure Message_Queue_Urgent (
ID : in RTEMS.ID;
Buffer : in RTEMS.Address;
Size : in RTEMS.Unsigned32;
Result : out RTEMS.Status_Codes
);
procedure Message_Queue_Broadcast (
ID : in RTEMS.ID;
Buffer : in RTEMS.Address;
Size : in RTEMS.Unsigned32;
Count : out RTEMS.Unsigned32;
Result : out RTEMS.Status_Codes
);
procedure Message_Queue_Receive (
ID : in RTEMS.ID;
Buffer : in RTEMS.Address;
Option_Set : in RTEMS.Option;
Timeout : in RTEMS.Interval;
Size : out RTEMS.Unsigned32;
Result : out RTEMS.Status_Codes
);
procedure Message_Queue_Flush (
ID : in RTEMS.ID;
Count : out RTEMS.Unsigned32;
Result : out RTEMS.Status_Codes
);
--
-- Event Manager
--
procedure Event_Send (
ID : in RTEMS.ID;
Event_In : in RTEMS.Event_Set;
Result : out RTEMS.Status_Codes
);
procedure Event_Receive (
Event_In : in RTEMS.Event_Set;
Option_Set : in RTEMS.Option;
Ticks : in RTEMS.Interval;
Event_Out : out RTEMS.Event_Set;
Result : out RTEMS.Status_Codes
);
--
-- Signal Manager
--
procedure Signal_Catch (
ASR_Handler : in RTEMS.ASR_Handler;
Mode_Set : in RTEMS.Mode;
Result : out RTEMS.Status_Codes
);
procedure Signal_Send (
ID : in RTEMS.ID;
Signal_Set : in RTEMS.Signal_Set;
Result : out RTEMS.Status_Codes
);
--
-- Partition Manager
--
procedure Partition_Create (
Name : in RTEMS.Name;
Starting_Address : in RTEMS.Address;
Length : in RTEMS.Unsigned32;
Buffer_Size : in RTEMS.Unsigned32;
Attribute_Set : in RTEMS.Attribute;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Partition_Ident (
Name : in RTEMS.Name;
Node : in RTEMS.Unsigned32;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Partition_Delete (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Partition_Get_Buffer (
ID : in RTEMS.ID;
Buffer : out RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure Partition_Return_Buffer (
ID : in RTEMS.ID;
Buffer : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
--
-- Region Manager
--
procedure Region_Create (
Name : in RTEMS.Name;
Starting_Address : in RTEMS.Address;
Length : in RTEMS.Unsigned32;
Page_Size : in RTEMS.Unsigned32;
Attribute_Set : in RTEMS.Attribute;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Region_Ident (
Name : in RTEMS.Name;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Region_Delete (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Region_Extend (
ID : in RTEMS.ID;
Starting_Address : in RTEMS.Address;
Length : in RTEMS.Unsigned32;
Result : out RTEMS.Status_Codes
);
procedure Region_Get_Segment (
ID : in RTEMS.ID;
Size : in RTEMS.Unsigned32;
Option_Set : in RTEMS.Option;
Timeout : in RTEMS.Interval;
Segment : out RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure Region_Get_Segment_Size (
ID : in RTEMS.ID;
Segment : in RTEMS.Address;
Size : out RTEMS.Unsigned32;
Result : out RTEMS.Status_Codes
);
procedure Region_Return_Segment (
ID : in RTEMS.ID;
Segment : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
--
-- Dual Ported Memory Manager
--
procedure Port_Create (
Name : in RTEMS.Name;
Internal_Start : in RTEMS.Address;
External_Start : in RTEMS.Address;
Length : in RTEMS.Unsigned32;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Port_Ident (
Name : in RTEMS.Name;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Port_Delete (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Port_External_To_Internal (
ID : in RTEMS.ID;
External : in RTEMS.Address;
Internal : out RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure Port_Internal_To_External (
ID : in RTEMS.ID;
Internal : in RTEMS.Address;
External : out RTEMS.Address;
Result : out RTEMS.Status_Codes
);
--
-- Input/Output Manager
--
procedure IO_Initialize (
Major : in RTEMS.Device_Major_Number;
Minor : in RTEMS.Device_Minor_Number;
Argument : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure IO_Register_Name (
Name : in String;
Major : in RTEMS.Device_Major_Number;
Minor : in RTEMS.Device_Minor_Number;
Result : out RTEMS.Status_Codes
);
procedure IO_Lookup_Name (
Name : in String;
Device_Info : In RTEMS.Driver_Name_t_Pointer;
Result : out RTEMS.Status_Codes
);
procedure IO_Open (
Major : in RTEMS.Device_Major_Number;
Minor : in RTEMS.Device_Minor_Number;
Argument : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure IO_Close (
Major : in RTEMS.Device_Major_Number;
Minor : in RTEMS.Device_Minor_Number;
Argument : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure IO_Read (
Major : in RTEMS.Device_Major_Number;
Minor : in RTEMS.Device_Minor_Number;
Argument : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure IO_Write (
Major : in RTEMS.Device_Major_Number;
Minor : in RTEMS.Device_Minor_Number;
Argument : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
procedure IO_Control (
Major : in RTEMS.Device_Major_Number;
Minor : in RTEMS.Device_Minor_Number;
Argument : in RTEMS.Address;
Result : out RTEMS.Status_Codes
);
--
-- Fatal Error Manager
--
procedure Fatal_Error_Occurred (
The_Error : in RTEMS.Unsigned32
);
--
-- Rate Monotonic Manager
--
procedure Rate_Monotonic_Create (
Name : in RTEMS.Name;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Rate_Monotonic_Ident (
Name : in RTEMS.Name;
ID : out RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Rate_Monotonic_Delete (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Rate_Monotonic_Cancel (
ID : in RTEMS.ID;
Result : out RTEMS.Status_Codes
);
procedure Rate_Monotonic_Period (
ID : in RTEMS.ID;
Length : in RTEMS.Interval;
Result : out RTEMS.Status_Codes
);
procedure Rate_Monotonic_Get_Status (
ID : in RTEMS.ID;
Status : out RTEMS.Rate_Monotonic_Period_Status;
Result : out RTEMS.Status_Codes
);
--
-- Debug Manager
--
Debug_All_Mask : constant RTEMS.Debug_Set := 16#ffffffff#;
Debug_Region : constant RTEMS.Debug_Set := 16#00000001#;
procedure Debug_Enable (
To_Be_Enabled : in RTEMS.Debug_Set
);
procedure Debug_Disable (
To_Be_Disabled : in RTEMS.Debug_Set
);
function Debug_Is_Enabled (
Level : in RTEMS.Debug_Set
) return RTEMS.Boolean;
--
-- Some Useful Data Items
--
Configuration : RTEMS.Configuration_Table_Pointer;
pragma Import (C, Configuration, "_Configuration_Table");
end RTEMS;
|
-- Práctica 4: César Borao Moratinos (Hash_Maps_G_Open.adb)
with Ada.Text_IO;
with Ada.Strings.Unbounded;
package body Hash_Maps_G is
package ASU renames Ada.Strings.Unbounded;
procedure Put (M: in out Map;
Key: Key_Type;
Value: Value_Type) is
Position: Hash_Range := Hash(Key);
Success : Boolean;
Found : Boolean := False;
First_Deleted : Hash_Range;
Deleted_Element: Boolean := False;
Free_Cell: Hash_Range;
begin
Success := False;
if M.P_Array = null then
M.P_Array := new Cell_Array;
M.P_Array(Position) := (Key,Value,True,False);
M.Length := 1;
else
if not M.P_Array(Position).Full then
if M.Length = Max then
raise Full_Map;
end if;
M.P_Array(Position) := (Key,Value,True,False);
M.Length := M.Length + 1;
elsif M.P_Array(Position).Key = Key and not M.P_Array(Position).Deleted then
M.P_Array(Position).Value := Value;
else
Position := Position + 1;
while not Success and Position < Hash_Range'Last loop
if M.P_Array(Position).Key = Key and not M.P_Array(Position).Deleted then
Success := True;
M.P_Array(Position).Value := Value;
end if;
if M.P_Array(Position).Deleted and not Deleted_Element then
First_Deleted := Position;
Deleted_Element := True;
Found := True;
end if;
if not M.P_Array(Position).Full and not Found then
Free_Cell := Position;
Found := True;
end if;
Position := Position + 1;
end loop;
if not Success and Deleted_Element then
if M.Length = Max then
raise Full_Map;
end if;
M.P_Array(First_Deleted) := (Key,Value,True,False);
M.Length := M.Length + 1;
Success := True;
end if;
if not Success then
if M.Length = Max then
raise Full_Map;
end if;
M.P_Array(Free_Cell) := (Key,Value,True,False);
M.Length := M.Length + 1;
end if;
end if;
end if;
end Put;
procedure Get (M: Map;
Key: in Key_Type;
Value: out Value_Type;
Success: out Boolean) is
Position: Hash_Range := Hash(Key);
First_Deleted : Hash_Range;
Deleted_Element: Boolean := False;
begin
Success := False;
if M.P_Array /= null then
if M.P_Array(Position).Full or M.P_Array(Position).Deleted then
if M.P_Array(Position).Key = Key and not M.P_Array(Position).Deleted then
Value := M.P_Array(Position).Value;
Success := True;
end if;
if M.P_Array(Position).Deleted and not Deleted_Element then
First_Deleted := Position;
Deleted_Element := True;
end if;
Position := Position + 1;
while not Success and Position < Hash_Range'Last loop
if not M.P_Array(Position).Deleted and M.P_Array(Position).Key = Key then
Value := M.P_Array(Position).Value;
Success := True;
end if;
if M.P_Array(Position).Deleted and not Deleted_Element then
First_Deleted := Position;
Deleted_Element := True;
end if;
Position := Position + 1;
end loop;
end if;
if Success and Deleted_Element then
M.P_Array(Position).Deleted := True;
M.P_Array(Position).Full := False;
M.P_Array(First_Deleted) := (Key,Value,True,False);
end if;
end if;
end Get;
procedure Delete (M: in out Map;
Key: in Key_Type;
Success: out Boolean) is
Position: Hash_Range := Hash(Key);
begin
Success := False;
if M.P_Array /= null then
if M.P_Array(Position).Full or M.P_Array(Position).Deleted then
if M.P_Array(Position).Key = Key and not M.P_Array(Position).Deleted then
M.P_Array(Position).Full := False;
M.P_Array(Position).Deleted := True;
M.Length := M.Length - 1;
Success := True;
end if;
Position := Position + 1;
while not Success and Position < Hash_Range'Last loop
if not M.P_Array(Position).Deleted and M.P_Array(Position).Key = Key then
M.P_Array(Position).Full := False;
M.P_Array(Position).Deleted := True;
M.Length := M.Length - 1;
Success := True;
end if;
Position := Position + 1;
end loop;
end if;
end if;
end Delete;
function Map_Length (M : Map) return Natural is
begin
return M.Length;
end Map_Length;
function First (M: Map) return Cursor is
C: Cursor;
begin
C.M := M;
C.Position := 0;
while not C.M.P_Array(C.Position).Full and C.Position < Hash_Range'Last loop
C.Position := C.Position + 1;
end loop;
return C;
end First;
procedure Next (C: in out Cursor) is
begin
C.Position := C.Position + 1;
if C.Position = Hash_Range'First then
C.End_Found := True;
end if;
while not C.M.P_Array(C.Position).Full and C.Position < Hash_Range'Last loop
C.Position := C.Position + 1;
end loop;
end Next;
function Has_Element (C: Cursor) return Boolean is
begin
if C.End_Found then
return False;
elsif C.M.P_Array(C.Position).Full then
return True;
else
return False;
end if;
end Has_Element;
function Element (C: Cursor) return Element_Type is
Element: Element_Type;
begin
if Has_Element (C) then
Element.Key := C.M.P_Array(C.Position).Key;
Element.Value := C.M.P_Array(C.Position).Value;
else
raise No_Element;
end if;
return Element;
end Element;
end Hash_Maps_G;
|
------------------------------------------------------------------------------
-- --
-- GNAT EXAMPLE --
-- --
-- Copyright (C) 2013-2014, 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. --
-- --
------------------------------------------------------------------------------
pragma Warnings (Off);
with System.SAM4S; use System.SAM4S;
pragma Warnings (On);
package body Leds is
Led_Pin_C : constant := 2 ** 23; -- PC23
Led1_Pin_C : constant := 2 ** 20; -- PC20
Led2_Pin_A : constant := 2 ** 16; -- PA16
Led3_Pin_C : constant := 2 ** 22; -- PC22;
But_Pin_A : constant := 2 ** 2; -- PA2
But1_Pin_A : constant := 2 ** 0; -- PA0
But2_Pin_C : constant := 2 ** 29; -- PC29
But3_Pin_C : constant := 2 ** 30; -- PC30
function Button1_Pressed return Boolean is
begin
return (PIOA.PDSR and But1_Pin_A) = 0;
end Button1_Pressed;
function Button2_Pressed return Boolean is
begin
return (PIOC.PDSR and But2_Pin_C) = 0;
end Button2_Pressed;
function Button3_Pressed return Boolean is
begin
return (PIOC.PDSR and But3_Pin_C) = 0;
end Button3_Pressed;
function Button_Pressed return Boolean is
begin
return (PIOA.PDSR and But_Pin_A) = 0;
end Button_Pressed;
procedure Set_Led (On : Boolean) is
begin
if On then
PIOC.CODR := Led_Pin_C;
else
PIOC.SODR := Led_Pin_C;
end if;
end Set_Led;
procedure Set_Led1 (On : Boolean) is
begin
if On then
PIOC.CODR := Led1_Pin_C;
else
PIOC.SODR := Led1_Pin_C;
end if;
end Set_Led1;
procedure Set_Led2 (On : Boolean) is
begin
if On then
PIOA.CODR := Led2_Pin_A;
else
PIOA.SODR := Led2_Pin_A;
end if;
end Set_Led2;
procedure Set_Led3 (On : Boolean) is
begin
if On then
PIOC.CODR := Led3_Pin_C;
else
PIOC.SODR := Led3_Pin_C;
end if;
end Set_Led3;
procedure Init is
begin
-- Enable clock for GPIO-A and GPIO-C
PMC.PMC_PCER0 := 2 ** PIOA_ID + 2 ** PIOC_ID;
-- Configure Led
PIOC.PER := Led_Pin_C + Led1_Pin_C + Led3_Pin_C
+ But2_Pin_C + But3_Pin_C;
PIOC.OER := Led_Pin_C + Led1_Pin_C + Led3_Pin_C;
PIOC.CODR := Led_Pin_C + Led1_Pin_C + Led3_Pin_C;
PIOC.MDDR := Led_Pin_C + Led1_Pin_C + Led3_Pin_C;
PIOC.PUER := But2_Pin_C + But3_Pin_C;
PIOA.PER := Led2_Pin_A + But_Pin_A + But1_Pin_A;
PIOA.OER := Led2_Pin_A;
PIOA.CODR := Led2_Pin_A;
PIOA.MDDR := Led2_Pin_A;
PIOA.PUER := But_Pin_A + But1_Pin_A;
end Init;
end Leds;
|
with Ada.Text_IO;
procedure Test_Function is
function Palindrome (Text : String) return Boolean is
begin
for Offset in 0 .. Text'Length / 2 - 1 loop
if Text (Text'First + Offset) /= Text (Text'Last - Offset) then
return False;
end if;
end loop;
return True;
end Palindrome;
str1 : String := "racecar";
str2 : String := "wombat";
begin
begin
pragma Assert(False); -- raises an exception if assertions are switched on
Ada.Text_IO.Put_Line("Skipping the test! Please compile with assertions switched on!");
exception
when others => -- assertions are switched on -- perform the tests
pragma Assert (Palindrome (str1) = True, "Assertion on str1 failed");
pragma Assert (Palindrome (str2) = False, "Assertion on str2 failed");
Ada.Text_IO.Put_Line("Test Passed!");
end;
end Test_Function;
|
with p1; use p1;
package body p2 with SPARK_Mode is
procedure write_to_uart (msg : Byte_Array) with
Global => (Output => some_register)
is
begin
some_register := msg(1);
end;
procedure foo is
begin
write_to_uart(p1.toBytes (some_constant));
end foo;
end p2;
|
-- Copyright 2019 by Martin Moene
--
-- https://github.com/martinmoene/kalman-estimator-ada
--
-- Distributed under the Boost Software License, Version 1.0.
-- (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
with system.machine_code; use system.machine_code;
with interfaces; use interfaces;
with system;
procedure avr_blink_led_e is
led_ddr : unsigned_8;
led_port : unsigned_8;
led_pin : constant := 5;
-- led_msk : constant := 2#0010_0000#;
led_ms : constant := 200;
for led_port'address use system'to_address ( 16#25# );
for led_ddr'address use system'to_address ( 16#24# );
function bitmask( pin : in natural ) return unsigned_8 is
begin
return shift_left( 1, pin );
end bitmask;
procedure delay_ms( ms : in natural ) is
f_cpu_hz : constant := 12_000_000;
ms_count : constant := f_cpu_hz / ( 7 * 1000 );
begin
for i in 1 .. ms loop
for k in 1 .. ms_count loop
asm ("nop", volatile => true );
end loop;
end loop;
end delay_ms;
procedure blink_ms( n : in natural; ms : in natural ) is
begin
for i in 1 .. n loop
led_port := led_port xor bitmask ( led_pin );
delay_ms( ms );
end loop;
end blink_ms;
begin
led_port := 2#1111_1111#;
led_ddr := led_ddr or bitmask( led_pin );
--blink_ms( 7, led_ms );
loop
delay_ms( led_ms );
led_port := led_port xor bitmask( led_pin );
end loop;
end avr_blink_led_e;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test is begin Put('a'); end; put('a');
|
with Memory.Container; use Memory.Container;
package Memory.Trace is
type Trace_Type is new Container_Type with private;
type Trace_Pointer is access all Trace_Type'Class;
function Create_Trace(mem : Memory_Pointer) return Trace_Pointer;
overriding
function Clone(mem : Trace_Type) return Memory_Pointer;
overriding
procedure Read(mem : in out Trace_Type;
address : in Address_Type;
size : in Positive);
overriding
procedure Write(mem : in out Trace_Type;
address : in Address_Type;
size : in Positive);
overriding
procedure Idle(mem : in out Trace_Type;
cycles : in Time_Type);
private
type Trace_Type is new Container_Type with null record;
end Memory.Trace;
|
-----------------------------------------------------------------------
-- keystore -- Ada keystore
-- Copyright (C) 2019 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
package body Keystore is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Keystore");
function To_String (UUID : in UUID_Type) return String is
Encode : constant Util.Encoders.Encoder := Util.Encoders.Create ("hex");
U1 : constant String := Encode.Encode_Unsigned_32 (UUID (1));
U2 : constant String := Encode.Encode_Unsigned_32 (UUID (2));
U3 : constant String := Encode.Encode_Unsigned_32 (UUID (3));
U4 : constant String := Encode.Encode_Unsigned_32 (UUID (4));
begin
return U1 & "-"
& U2 (U2'First .. U2'First + 3) & "-"
& U2 (U2'First + 4 .. U2'Last) & "-"
& U3 (U3'First .. U3'First + 3) & "-"
& U3 (U3'First + 4 .. U3'Last) & U4;
end To_String;
-- ------------------------------
-- Add in the wallet the named entry and associate it the content.
-- The content is encrypted in AES-CBC with a secret key and an IV vector
-- that is created randomly for the new named entry.
-- ------------------------------
procedure Add (Container : in out Wallet;
Name : in String;
Content : in String) is
use Ada.Streams;
Data : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
for Data'Address use Content'Address;
begin
Wallet'Class (Container).Add (Name, T_STRING, Data);
end Add;
-- ------------------------------
-- Add or update in the wallet the named entry and associate it the content.
-- The content is encrypted in AES-CBC with a secret key and an IV vector
-- that is created randomly for the new or updated named entry.
-- ------------------------------
procedure Set (Container : in out Wallet;
Name : in String;
Content : in String) is
use Ada.Streams;
Data : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
for Data'Address use Content'Address;
begin
Wallet'Class (Container).Set (Name, T_STRING, Data);
end Set;
-- ------------------------------
-- Update in the wallet the named entry and associate it the new content.
-- The secret key and IV vectors are not changed.
-- ------------------------------
procedure Update (Container : in out Wallet;
Name : in String;
Content : in String) is
use Ada.Streams;
Data : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
for Data'Address use Content'Address;
begin
Wallet'Class (Container).Update (Name, T_STRING, Data);
end Update;
-- ------------------------------
-- Get from the wallet the named entry.
-- ------------------------------
function Get (Container : in out Wallet;
Name : in String) return String is
use Ada.Streams;
Info : Entry_Info := Wallet'Class (Container).Find (Name);
Result : String (1 .. Natural (Info.Size));
Buffer : Stream_Element_Array (1 .. Stream_Element_Offset (Info.Size));
for Buffer'Address use Result'Address;
begin
Wallet'Class (Container).Get (Name, Info, Buffer);
return Result;
end Get;
-- ------------------------------
-- Start the tasks of the task manager.
-- ------------------------------
procedure Start (Manager : in Task_Manager_Access) is
begin
Manager.Start;
end Start;
-- ------------------------------
-- Stop the tasks.
-- ------------------------------
procedure Stop (Manager : in Task_Manager_Access) is
begin
Manager.Stop;
end Stop;
procedure Execute (Manager : in out Task_Manager;
Work : in Work_Type_Access) is
begin
Executors.Execute (Executors.Executor_Manager (Manager), Work);
end Execute;
procedure Execute (Work : in out Work_Type_Access) is
begin
Work.Execute;
end Execute;
procedure Error (Work : in out Work_Type_Access;
Ex : in Ada.Exceptions.Exception_Occurrence) is
pragma Unreferenced (Work);
begin
Log.Error ("Work error", Ex);
end Error;
end Keystore;
|
--
-- Raytracer implementation in Ada
-- by John Perry (github: johnperry-math)
-- 2021
--
-- implementation for Objects that may appear in the scene
--
pragma Ada_2020;
-- Ada packages
with Ada.Numerics.Generic_Elementary_Functions;
-- local packages
with RayTracing_Constants; use RayTracing_Constants;
with RayTracer;
package body Objects is
-------------------------------------------------------------------------
-- the next package, and the following two subprograms,
-- make the square root and floating-point exponentiation functions available
package Float_Numerics is new Ada.Numerics.Generic_Elementary_Functions
(
Float_Type => Float15
);
function Sqrt(X: Float15) return Float15 renames Float_Numerics.Sqrt;
function "**" (Left, Right : Float15) return Float15
renames Float_Numerics."**";
-------------------------------------------------------------------------
function Surface_Of(Thing: Thing_Type) return Surface_Type
is ( Thing.Surface );
procedure Get_Surface_Properties(
Surface: Surface_Type;
Position: Vector;
Properties: out Surface_Properties
)
is
begin
case Surface is
when Shiny =>
Properties.Diffuse := White;
Properties.Specular := Grey;
Properties.Reflect := 0.7;
Properties.Roughness := 250.0;
when Checkerboard =>
declare Val: constant Integer
:= Integer( Float15'Floor(Position.Z)
+ Float15'Floor(Position.X) );
begin
if Val mod 2 /= 0 then
Properties.Reflect := 0.1;
Properties.Diffuse := White;
else
Properties.Reflect := 0.7;
Properties.Diffuse := Black;
end if;
Properties.Specular := White;
Properties.Roughness := 150.0;
end;
end case;
end Get_Surface_Properties;
function Object_Distance( Obj: Thing_Type; Ray: Ray_Type ) return Float15 is
begin
case Obj.Kind is
when Sphere =>
declare
Eo: constant Vector := Obj.Center - Ray.Start;
V: constant Float15 := Eo * Ray.Dir;
begin
if V > 0.0 then
declare
Disc: constant Float15 := Obj.Radius2 - ( Eo * Eo - V * V );
begin
if Disc > 0.0 then
return V - Sqrt(Disc);
end if;
end;
end if;
end;
when Plane =>
declare
Denom: constant Float15 := Obj.Normal * Ray.Dir;
begin
if Denom <= 0.0 then
return ( Obj.Normal * Ray.Start + Obj.Offset ) / ( -Denom );
end if;
end;
end case;
return Far_Away;
end Object_Distance;
pragma Inline_Always(Object_Distance);
function Intersections(Ray: Ray_Type; Things: Thing_Array)
return Intersection_Type
is
Closest: Float15 := Far_Away; -- distance of closest object
Which: Natural := 0; -- closest object in Things
Dist: array(Things'Range) of Float15; -- distance to each object
begin
-- determine distance for each object
for I in Things'Range loop
Dist(I) := Object_Distance(Things(I), Ray);
if Dist(I) < Closest then
Which := I;
end if;
end loop;
return (
if Which = 0 then No_Intersection
else (
Thing => Things(Which),
Ray => Ray,
Dist => Dist(Which)
)
);
end Intersections;
function Object_Normal(Obj: Thing_Type; Position: Vector) return Vector is
(
(
case Obj.Kind is
when Sphere => ( Normal(Position - Obj.Center ) ),
when Plane => ( Obj.Normal )
)
);
function Create_Intersection(
Thing: Thing_Type;
Ray: Ray_Type;
Dist: Float15
)
return Intersection_Type
is ( ( Thing => Thing, Ray => Ray, Dist => Dist ) );
pragma Inline_Always(Create_Intersection);
procedure Create_Sphere(
Thing: out Thing_Type;
Center: Vector;
Radius: Float15;
Surface: Surface_Type
)
is
begin
Thing := (
Kind => Sphere,
Surface => Surface,
Radius2 => Radius * Radius,
Center => Center
);
end Create_Sphere;
procedure Create_Plane(
Thing: out Thing_Type;
Position: Vector;
Offset: Float15;
Surface: Surface_Type
)
is
begin
Thing := (
Kind => Plane,
Surface => Surface,
Offset => Offset,
Normal => Position
);
end Create_Plane;
end Objects;
|
-- DECLS.ads
-- Paquet de declaracions
package decls is
pragma pure;
end decls;
|
with Agar.Core.Thin;
with Agar.Core.Data_Source;
with Interfaces;
package Agar.Core.Object is
subtype Object_Access_t is Thin.Object.Object_Access_t;
subtype Object_Not_Null_Access_t is Thin.Object.Object_Not_Null_Access_t;
subtype Object_Header_Access_t is Thin.Object.Object_Header_Access_t;
subtype Object_Header_Not_Null_Access_t is Thin.Object.Object_Header_Not_Null_Access_t;
subtype Class_Access_t is Thin.Object.Class_Access_t;
subtype Class_Not_Null_Access_t is Thin.Object.Class_Not_Null_Access_t;
subtype Dependency_Access_t is Thin.Object.Dependency_Access_t;
subtype Dependency_Not_Null_Access_t is Thin.Object.Dependency_Not_Null_Access_t;
--
--
--
function New_Object
(Parent : in Object_Access_t;
Name : in String;
Object_Class : in Class_Not_Null_Access_t) return Object_Access_t;
procedure Init
(Object : in Object_Not_Null_Access_t;
Object_Class : in Class_Not_Null_Access_t)
renames Thin.Object.Init;
procedure Init_Static
(Object : in Object_Not_Null_Access_t;
Object_Class : in Class_Not_Null_Access_t)
renames Thin.Object.Init_Static;
procedure Attach
(New_Parent : in Object_Access_t;
Object : in Object_Not_Null_Access_t)
renames Thin.Object.Attach;
procedure Attach_To_Named
(VFS_Root : in Object_Not_Null_Access_t;
Path : in String;
Child : in Object_Access_t);
procedure Detach
(Object : in Object_Not_Null_Access_t)
renames Thin.Object.Detach;
procedure Move_To_Head
(Object : in Object_Not_Null_Access_t)
renames Thin.Object.Move_To_Head;
procedure Move_To_Tail
(Object : in Object_Not_Null_Access_t)
renames Thin.Object.Move_To_Tail;
procedure Move_Up
(Object : in Object_Not_Null_Access_t)
renames Thin.Object.Move_Up;
procedure Move_Down
(Object : in Object_Not_Null_Access_t)
renames Thin.Object.Move_Down;
procedure Delete
(Object : in Object_Not_Null_Access_t)
renames Thin.Object.Delete;
function Root (Object : in Object_Not_Null_Access_t)
return Object_Not_Null_Access_t
renames Thin.Object.Root;
function Parent (Object : in Object_Not_Null_Access_t)
return Object_Access_t renames Thin.Object.Parent;
function Find
(VFS_Root : in Object_Not_Null_Access_t;
Pattern : in String) return Object_Access_t;
function Find_Parent
(VFS_Root : in Object_Not_Null_Access_t;
Name : in String;
Object_Type : in String) return Object_Access_t;
function Find_Child
(VFS_Root : in Object_Not_Null_Access_t;
Name : in String) return Object_Access_t;
-- XXX: Semantics?
procedure Copy_Name
(Object : in Object_Not_Null_Access_t;
Path : out String;
Used : out Natural);
procedure Lock (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Lock;
procedure Unlock (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Unlock;
procedure Lock_VFS (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Lock_VFS;
procedure Unlock_VFS (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Unlock_VFS;
procedure Set_Name
(Object : in Object_Not_Null_Access_t;
Name : in String);
-- XXX: Semantics?
-- procedure Generate_Name
-- (Object : in Object_Not_Null_Access_t;
-- Object_Class : in Class_Not_Null_Access_t;
-- Buffer : in String);
-- procedure Generate_Name_Prefixed
-- (Object : in Object_Not_Null_Access_t;
-- Prefix : in String;
-- Buffer : out String;
-- Size : out Natural);
-- FIXME : AG_ObjectSetDebugFn
procedure Register_Class
(Object_Class : Class_Not_Null_Access_t)
renames Thin.Object.Register_Class;
procedure Unregister_Class
(Object_Class : Class_Not_Null_Access_t)
renames Thin.Object.Unregister_Class;
procedure Register_Namespace
(Name : in String;
Prefix : in String;
URL : in String);
procedure Unregister_Namespace
(Name : in String);
function Lookup_Class
(Spec : in String) return Class_Access_t;
function Load_Class
(Spec : in String) return Class_Access_t;
procedure Register_Module_Directory
(Path : in String);
procedure Unregister_Module_Directory
(Path : in String);
function Is_Of_Class
(Object : in Object_Not_Null_Access_t;
Pattern : in String) return Boolean;
function Superclass
(Object : in Object_Not_Null_Access_t) return Object_Access_t
renames Thin.Object.Superclass;
function In_Use
(Object : in Object_Not_Null_Access_t) return Boolean;
function Add_Dependency
(Object : in Object_Not_Null_Access_t;
Dependency : in Object_Not_Null_Access_t;
Persistent : in Boolean) return Dependency_Access_t;
procedure Delete_Dependency
(Object : in Object_Not_Null_Access_t;
Dependency : in Object_Not_Null_Access_t)
renames Thin.Object.Delete_Dependency;
function Encode_Name
(Object : in Object_Not_Null_Access_t;
Dependency : in Object_Not_Null_Access_t) return Interfaces.Unsigned_32
renames Thin.Object.Encode_Name;
function Find_Dependency
(Object : in Object_Not_Null_Access_t;
Index : in Interfaces.Unsigned_32;
Pointer : access Object_Not_Null_Access_t) return Boolean;
procedure Destroy (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Destroy;
procedure Free_Dataset (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Free_Dataset;
procedure Free_Events (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Free_Events;
procedure Free_Variables (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Free_Variables;
procedure Free_Dependencies (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Free_Dependencies;
procedure Free_Dummy_Dependencies (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Free_Dummy_Dependencies;
procedure Free_Children (Object : in Object_Not_Null_Access_t)
renames Thin.Object.Free_Children;
function Load (Object : in Object_Not_Null_Access_t) return Boolean;
function Load_From_File
(Object : in Object_Not_Null_Access_t;
File : in String) return Boolean;
function Load_Data (Object : in Object_Not_Null_Access_t) return Boolean;
function Load_Data_From_File
(Object : in Object_Not_Null_Access_t;
File : in String) return Boolean;
function Load_Generic (Object : in Object_Not_Null_Access_t) return Boolean;
function Load_Generic_From_File
(Object : in Object_Not_Null_Access_t;
File : in String) return Boolean;
function Save (Object : in Object_Not_Null_Access_t) return Boolean;
function Save_All (Object : in Object_Not_Null_Access_t) return Boolean;
function Save_To_File
(Object : in Object_Not_Null_Access_t;
File : in String) return Boolean;
function Serialize
(Object : in Object_Not_Null_Access_t;
Source : in Data_Source.Data_Source_Not_Null_Access_t) return Boolean;
function Unserialize
(Object : in Object_Not_Null_Access_t;
Source : in Data_Source.Data_Source_Not_Null_Access_t) return Boolean;
function Read_Header
(Object : in Object_Not_Null_Access_t;
Header : in Object_Header_Access_t) return Boolean;
function Page_In (Object : in Object_Not_Null_Access_t) return Boolean;
function Page_Out (Object : in Object_Not_Null_Access_t) return Boolean;
end Agar.Core.Object;
|
with Giza.Colors; use Giza.Colors;
with Giza.Bitmap_Fonts.FreeMono12pt7b;
with Giza.Bitmap_Fonts.FreeMono18pt7b;
with Giza.Bitmap_Fonts.FreeMono24pt7b;
with Giza.Bitmap_Fonts.FreeMono32pt7b;
with Giza.Bitmap_Fonts.FreeMono8pt7b;
with Giza.Bitmap_Fonts.FreeMonoBold12pt7b;
with Giza.Bitmap_Fonts.FreeMonoBold18pt7b;
with Giza.Bitmap_Fonts.FreeMonoBold24pt7b;
with Giza.Bitmap_Fonts.FreeMonoBold32pt7b;
with Giza.Bitmap_Fonts.FreeMonoBold8pt7b;
with Giza.Bitmap_Fonts.FreeMonoBoldOblique12pt7b;
with Giza.Bitmap_Fonts.FreeMonoBoldOblique18pt7b;
with Giza.Bitmap_Fonts.FreeMonoBoldOblique24pt7b;
with Giza.Bitmap_Fonts.FreeMonoBoldOblique32pt7b;
with Giza.Bitmap_Fonts.FreeMonoBoldOblique8pt7b;
with Giza.Bitmap_Fonts.FreeMonoOblique12pt7b;
with Giza.Bitmap_Fonts.FreeMonoOblique18pt7b;
with Giza.Bitmap_Fonts.FreeMonoOblique24pt7b;
with Giza.Bitmap_Fonts.FreeMonoOblique32pt7b;
with Giza.Bitmap_Fonts.FreeMonoOblique8pt7b;
with Giza.Bitmap_Fonts.FreeSans12pt7b;
with Giza.Bitmap_Fonts.FreeSans18pt7b;
with Giza.Bitmap_Fonts.FreeSans24pt7b;
with Giza.Bitmap_Fonts.FreeSans32pt7b;
with Giza.Bitmap_Fonts.FreeSans8pt7b;
with Giza.Bitmap_Fonts.FreeSansBold12pt7b;
with Giza.Bitmap_Fonts.FreeSansBold18pt7b;
with Giza.Bitmap_Fonts.FreeSansBold24pt7b;
with Giza.Bitmap_Fonts.FreeSansBold32pt7b;
with Giza.Bitmap_Fonts.FreeSansBold8pt7b;
with Giza.Bitmap_Fonts.FreeSansBoldOblique12pt7b;
with Giza.Bitmap_Fonts.FreeSansBoldOblique18pt7b;
with Giza.Bitmap_Fonts.FreeSansBoldOblique24pt7b;
with Giza.Bitmap_Fonts.FreeSansBoldOblique32pt7b;
with Giza.Bitmap_Fonts.FreeSansBoldOblique8pt7b;
with Giza.Bitmap_Fonts.FreeSansOblique12pt7b;
with Giza.Bitmap_Fonts.FreeSansOblique18pt7b;
with Giza.Bitmap_Fonts.FreeSansOblique24pt7b;
with Giza.Bitmap_Fonts.FreeSansOblique32pt7b;
with Giza.Bitmap_Fonts.FreeSansOblique8pt7b;
with Giza.Bitmap_Fonts.FreeSerif12pt7b;
with Giza.Bitmap_Fonts.FreeSerif18pt7b;
with Giza.Bitmap_Fonts.FreeSerif24pt7b;
with Giza.Bitmap_Fonts.FreeSerif32pt7b;
with Giza.Bitmap_Fonts.FreeSerif8pt7b;
with Giza.Bitmap_Fonts.FreeSerifBold12pt7b;
with Giza.Bitmap_Fonts.FreeSerifBold18pt7b;
with Giza.Bitmap_Fonts.FreeSerifBold24pt7b;
with Giza.Bitmap_Fonts.FreeSerifBold32pt7b;
with Giza.Bitmap_Fonts.FreeSerifBold8pt7b;
with Giza.Bitmap_Fonts.FreeSerifBoldItalic12pt7b;
with Giza.Bitmap_Fonts.FreeSerifBoldItalic18pt7b;
with Giza.Bitmap_Fonts.FreeSerifBoldItalic24pt7b;
with Giza.Bitmap_Fonts.FreeSerifBoldItalic32pt7b;
with Giza.Bitmap_Fonts.FreeSerifBoldItalic8pt7b;
with Giza.Bitmap_Fonts.FreeSerifItalic12pt7b;
with Giza.Bitmap_Fonts.FreeSerifItalic18pt7b;
with Giza.Bitmap_Fonts.FreeSerifItalic24pt7b;
with Giza.Bitmap_Fonts.FreeSerifItalic32pt7b;
with Giza.Bitmap_Fonts.FreeSerifItalic8pt7b;
with Giza.Hershey_Fonts.Astrology;
with Giza.Hershey_Fonts.Cursive;
with Giza.Hershey_Fonts.Cyrilc_1;
with Giza.Hershey_Fonts.Cyrillic;
with Giza.Hershey_Fonts.Futural;
with Giza.Hershey_Fonts.Futuram;
with Giza.Hershey_Fonts.Gothgbt;
with Giza.Hershey_Fonts.Gothgrt;
with Giza.Hershey_Fonts.Gothiceng;
with Giza.Hershey_Fonts.Gothicger;
with Giza.Hershey_Fonts.Gothicita;
with Giza.Hershey_Fonts.Gothitt;
with Giza.Hershey_Fonts.Greek;
with Giza.Hershey_Fonts.Greekc;
with Giza.Hershey_Fonts.Greeks;
with Giza.Hershey_Fonts.Japanese;
with Giza.Hershey_Fonts.Markers;
with Giza.Hershey_Fonts.Mathlow;
with Giza.Hershey_Fonts.Mathupp;
with Giza.Hershey_Fonts.Meteorology;
with Giza.Hershey_Fonts.Music;
with Giza.Hershey_Fonts.Rowmand;
with Giza.Hershey_Fonts.Rowmans;
with Giza.Hershey_Fonts.Rowmant;
with Giza.Hershey_Fonts.Scriptc;
with Giza.Hershey_Fonts.Scripts;
with Giza.Hershey_Fonts.Symbolic;
with Giza.Hershey_Fonts.Timesg;
with Giza.Hershey_Fonts.Timesi;
with Giza.Hershey_Fonts.Timesib;
with Giza.Hershey_Fonts.Timesr;
with Giza.Font; use Giza.Font;
package body Test_Fonts is
type Font_Ref_Array is array (Integer range <>) of Giza.Font.Ref_Const;
The_Fonts : constant Font_Ref_Array :=
(Giza.Bitmap_Fonts.FreeMono12pt7b.Font,
Giza.Bitmap_Fonts.FreeMono18pt7b.Font,
Giza.Bitmap_Fonts.FreeMono24pt7b.Font,
Giza.Bitmap_Fonts.FreeMono32pt7b.Font,
Giza.Bitmap_Fonts.FreeMono8pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoBold12pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoBold18pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoBold24pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoBold32pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoBold8pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoBoldOblique12pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoBoldOblique18pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoBoldOblique24pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoBoldOblique32pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoBoldOblique8pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoOblique12pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoOblique18pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoOblique24pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoOblique32pt7b.Font,
Giza.Bitmap_Fonts.FreeMonoOblique8pt7b.Font,
Giza.Bitmap_Fonts.FreeSans12pt7b.Font,
Giza.Bitmap_Fonts.FreeSans18pt7b.Font,
Giza.Bitmap_Fonts.FreeSans24pt7b.Font,
Giza.Bitmap_Fonts.FreeSans32pt7b.Font,
Giza.Bitmap_Fonts.FreeSans8pt7b.Font,
Giza.Bitmap_Fonts.FreeSansBold12pt7b.Font,
Giza.Bitmap_Fonts.FreeSansBold18pt7b.Font,
Giza.Bitmap_Fonts.FreeSansBold24pt7b.Font,
Giza.Bitmap_Fonts.FreeSansBold32pt7b.Font,
Giza.Bitmap_Fonts.FreeSansBold8pt7b.Font,
Giza.Bitmap_Fonts.FreeSansBoldOblique12pt7b.Font,
Giza.Bitmap_Fonts.FreeSansBoldOblique18pt7b.Font,
Giza.Bitmap_Fonts.FreeSansBoldOblique24pt7b.Font,
Giza.Bitmap_Fonts.FreeSansBoldOblique32pt7b.Font,
Giza.Bitmap_Fonts.FreeSansBoldOblique8pt7b.Font,
Giza.Bitmap_Fonts.FreeSansOblique12pt7b.Font,
Giza.Bitmap_Fonts.FreeSansOblique18pt7b.Font,
Giza.Bitmap_Fonts.FreeSansOblique24pt7b.Font,
Giza.Bitmap_Fonts.FreeSansOblique32pt7b.Font,
Giza.Bitmap_Fonts.FreeSansOblique8pt7b.Font,
Giza.Bitmap_Fonts.FreeSerif12pt7b.Font,
Giza.Bitmap_Fonts.FreeSerif18pt7b.Font,
Giza.Bitmap_Fonts.FreeSerif24pt7b.Font,
Giza.Bitmap_Fonts.FreeSerif32pt7b.Font,
Giza.Bitmap_Fonts.FreeSerif8pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifBold12pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifBold18pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifBold24pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifBold32pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifBold8pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifBoldItalic12pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifBoldItalic18pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifBoldItalic24pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifBoldItalic32pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifBoldItalic8pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifItalic12pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifItalic18pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifItalic24pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifItalic32pt7b.Font,
Giza.Bitmap_Fonts.FreeSerifItalic8pt7b.Font,
Giza.Hershey_Fonts.Astrology.Font,
Giza.Hershey_Fonts.Cursive.Font,
Giza.Hershey_Fonts.Cyrilc_1.Font,
Giza.Hershey_Fonts.Cyrillic.Font,
Giza.Hershey_Fonts.Futural.Font,
Giza.Hershey_Fonts.Futuram.Font,
Giza.Hershey_Fonts.Gothgbt.Font,
Giza.Hershey_Fonts.Gothgrt.Font,
Giza.Hershey_Fonts.Gothiceng.Font,
Giza.Hershey_Fonts.Gothicger.Font,
Giza.Hershey_Fonts.Gothicita.Font,
Giza.Hershey_Fonts.Gothitt.Font,
Giza.Hershey_Fonts.Greek.Font,
Giza.Hershey_Fonts.Greekc.Font,
Giza.Hershey_Fonts.Greeks.Font,
Giza.Hershey_Fonts.Japanese.Font,
Giza.Hershey_Fonts.Markers.Font,
Giza.Hershey_Fonts.Mathlow.Font,
Giza.Hershey_Fonts.Mathupp.Font,
Giza.Hershey_Fonts.Meteorology.Font,
Giza.Hershey_Fonts.Music.Font,
Giza.Hershey_Fonts.Rowmand.Font,
Giza.Hershey_Fonts.Rowmans.Font,
Giza.Hershey_Fonts.Rowmant.Font,
Giza.Hershey_Fonts.Scriptc.Font,
Giza.Hershey_Fonts.Scripts.Font,
Giza.Hershey_Fonts.Symbolic.Font,
Giza.Hershey_Fonts.Timesg.Font,
Giza.Hershey_Fonts.Timesi.Font,
Giza.Hershey_Fonts.Timesib.Font,
Giza.Hershey_Fonts.Timesr.Font);
function Font_Name (Index : Integer) return String;
---------------
-- Font_Name --
---------------
function Font_Name (Index : Integer) return String is
Offset : constant Integer := Index - The_Fonts'First;
begin
case Offset is
when 0 => return "Bitmap FreeMono12pt7b";
when 1 => return "Bitmap FreeMono18pt7b";
when 2 => return "Bitmap FreeMono24pt7b";
when 3 => return "Bitmap FreeMono32pt7b";
when 4 => return "Bitmap FreeMono8pt7b";
when 5 => return "Bitmap FreeMonoBold12pt7b";
when 6 => return "Bitmap FreeMonoBold18pt7b";
when 7 => return "Bitmap FreeMonoBold24pt7b";
when 8 => return "Bitmap FreeMonoBold32pt7b";
when 9 => return "Bitmap FreeMonoBold8pt7b";
when 10 => return "Bitmap FreeMonoBoldOblique12pt7b";
when 11 => return "Bitmap FreeMonoBoldOblique18pt7b";
when 12 => return "Bitmap FreeMonoBoldOblique24pt7b";
when 13 => return "Bitmap FreeMonoBoldOblique32pt7b";
when 14 => return "Bitmap FreeMonoBoldOblique8pt7b";
when 15 => return "Bitmap FreeMonoOblique12pt7b";
when 16 => return "Bitmap FreeMonoOblique18pt7b";
when 17 => return "Bitmap FreeMonoOblique24pt7b";
when 18 => return "Bitmap FreeMonoOblique32pt7b";
when 19 => return "Bitmap FreeMonoOblique8pt7b";
when 20 => return "Bitmap FreeSans12pt7b";
when 21 => return "Bitmap FreeSans18pt7b";
when 22 => return "Bitmap FreeSans24pt7b";
when 23 => return "Bitmap FreeSans32pt7b";
when 24 => return "Bitmap FreeSans8pt7b";
when 25 => return "Bitmap FreeSansBold12pt7b";
when 26 => return "Bitmap FreeSansBold18pt7b";
when 27 => return "Bitmap FreeSansBold24pt7b";
when 28 => return "Bitmap FreeSansBold32pt7b";
when 29 => return "Bitmap FreeSansBold8pt7b";
when 30 => return "Bitmap FreeSansBoldOblique12pt7b";
when 31 => return "Bitmap FreeSansBoldOblique18pt7b";
when 32 => return "Bitmap FreeSansBoldOblique24pt7b";
when 33 => return "Bitmap FreeSansBoldOblique32pt7b";
when 34 => return "Bitmap FreeSansBoldOblique8pt7b";
when 35 => return "Bitmap FreeSansOblique12pt7b";
when 36 => return "Bitmap FreeSansOblique18pt7b";
when 37 => return "Bitmap FreeSansOblique24pt7b";
when 38 => return "Bitmap FreeSansOblique32pt7b";
when 39 => return "Bitmap FreeSansOblique8pt7b";
when 40 => return "Bitmap FreeSerif12pt7b";
when 41 => return "Bitmap FreeSerif18pt7b";
when 42 => return "Bitmap FreeSerif24pt7b";
when 43 => return "Bitmap FreeSerif32pt7b";
when 44 => return "Bitmap FreeSerif8pt7b";
when 45 => return "Bitmap FreeSerifBold12pt7b";
when 46 => return "Bitmap FreeSerifBold18pt7b";
when 47 => return "Bitmap FreeSerifBold24pt7b";
when 48 => return "Bitmap FreeSerifBold32pt7b";
when 49 => return "Bitmap FreeSerifBold8pt7b";
when 50 => return "Bitmap FreeSerifBoldItalic12pt7b";
when 51 => return "Bitmap FreeSerifBoldItalic18pt7b";
when 52 => return "Bitmap FreeSerifBoldItalic24pt7b";
when 53 => return "Bitmap FreeSerifBoldItalic32pt7b";
when 54 => return "Bitmap FreeSerifBoldItalic8pt7b";
when 55 => return "Bitmap FreeSerifItalic12pt7b";
when 56 => return "Bitmap FreeSerifItalic18pt7b";
when 57 => return "Bitmap FreeSerifItalic24pt7b";
when 58 => return "Bitmap FreeSerifItalic32pt7b";
when 59 => return "Bitmap FreeSerifItalic8pt7b";
when 60 => return "Hershey Astrology";
when 61 => return "Hershey Cursive";
when 62 => return "Hershey Cyrilc_1";
when 63 => return "Hershey Cyrillic";
when 64 => return "Hershey Futural";
when 65 => return "Hershey Futuram";
when 66 => return "Hershey Gothgbt";
when 67 => return "Hershey Gothgrt";
when 68 => return "Hershey Gothiceng";
when 69 => return "Hershey Gothicger";
when 70 => return "Hershey Gothicita";
when 71 => return "Hershey Gothitt";
when 72 => return "Hershey Greek";
when 73 => return "Hershey Greekc";
when 74 => return "Hershey Greeks";
when 75 => return "Hershey Japanese";
when 76 => return "Hershey Markers";
when 77 => return "Hershey Mathlow";
when 78 => return "Hershey Mathupp";
when 79 => return "Hershey Meteorology";
when 80 => return "Hershey Music";
when 81 => return "Hershey Rowmand";
when 82 => return "Hershey Rowmans";
when 83 => return "Hershey Rowmant";
when 84 => return "Hershey Scriptc";
when 85 => return "Hershey Scripts";
when 86 => return "Hershey Symbolic";
when 87 => return "Hershey Timesg";
when 88 => return "Hershey Timesi";
when 89 => return "Hershey Timesib";
when 90 => return "Hershey Timesr";
when others => return "Unknown font...";
end case;
end Font_Name;
-------------
-- On_Init --
-------------
overriding procedure On_Init
(This : in out Test_Fonts_Window)
is
begin
On_Init (Test_Window (This));
This.Boxes.Set_Toggle;
This.Boxes.Set_Text ("Boxes");
This.Next.Set_Text ("Next");
This.Prev.Set_Text ("Prev");
This.Tile.Set_Size ((This.Get_Size.W, This.Get_Size.H / 10));
This.Tile.Set_Child (1, This.Prev'Unchecked_Access);
This.Tile.Set_Child (2, This.Boxes'Unchecked_Access);
This.Tile.Set_Child (3, This.Next'Unchecked_Access);
This.Add_Child (This.Tile'Unchecked_Access, (0, 0));
This.Font_Index := The_Fonts'First;
end On_Init;
----------
-- Draw --
----------
overriding procedure Draw
(This : in out Test_Fonts_Window;
Ctx : in out Giza.Context.Class;
Force : Boolean := True)
is
pragma Unreferenced (Force);
procedure Draw_Glyph_And_Values (Str : String;
Font : Giza.Font.Ref_Const;
Pt : Point_T);
-----------------------
-- Draw_Glyph_Values --
-----------------------
procedure Draw_Glyph_And_Values (Str : String;
Font : Giza.Font.Ref_Const;
Pt : Point_T)
is
Width, Height, X_Advance : Natural;
X_Offset, Y_Offset : Integer;
Org, Next : Point_T;
begin
Next := Pt;
for C of Str loop
Org := Next;
Ctx.Move_To (Org);
Font.Glyph_Box (C, Width, Height, X_Advance, X_Offset, Y_Offset);
Ctx.Set_Color (Black);
Font.Print_Glyph (Ctx, C);
Next := Ctx.Position;
if This.Boxes.Active then
Ctx.Set_Color (Blue);
Ctx.Rectangle
((Org + Point_T'(X_Offset, Y_Offset), (Width, Height)));
Ctx.Set_Color (Green);
Ctx.Move_To (Org);
Ctx.Line_To (Org + Point_T'(X_Advance, 0));
Ctx.Set_Color (Red);
Ctx.Move_To (Org);
Ctx.Line_To (Org + Point_T'(X_Offset, 0));
Ctx.Set_Color (Yellow);
Ctx.Move_To (Org);
Ctx.Line_To (Org + Point_T'(0, Y_Offset));
end if;
end loop;
end Draw_Glyph_And_Values;
Bounds : constant Rect_T := ((0, This.Get_Size.H / 10),
This.Get_Size - (0, This.Get_Size.H / 10));
Pt1 : constant Point_T := Bounds.Org + Point_T'(5, 20);
Pt2 : constant Point_T := Pt1 + Point_T'(0, 40);
Pt3 : constant Point_T := Pt2 + Point_T'(0, 40);
Str : constant String := "C'est un Test!";
Str2 : constant String := "Box Test";
Str3 : constant String := "Long string with a lot of split points and" &
ASCII.LF & "this one was forced (ASCII.LF)..." &
" A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" &
"abcdefghijklmnopqrstuvwxyz" & ASCII.LF &
"1234567890`~!@#$%^&*()-_=+[]{};:'""<>,.";
Rect : Rect_T;
begin
Draw (Test_Window (This), Ctx, Force => True);
Ctx.Set_Color (White);
Ctx.Fill_Rectangle (Bounds);
-- Print Font's name
Ctx.Move_To (Pt2);
Ctx.Set_Font (Giza.Bitmap_Fonts.FreeMono8pt7b.Font);
Ctx.Set_Color (Black);
Ctx.Print (Font_Name (This.Font_Index));
-- Set selected font
Ctx.Set_Font (The_Fonts (This.Font_Index));
-- Test box
Ctx.Move_To (Pt3);
Ctx.Set_Font (Giza.Bitmap_Fonts.FreeMono8pt7b.Font);
Ctx.Box (Str => Str2,
Rect => Rect,
Max_Width => This.Get_Size.W);
Ctx.Set_Color (Red);
Ctx.Rectangle (Pt3 + Rect);
Ctx.Set_Color (Black);
Ctx.Move_To (Pt3);
Ctx.Print (Str2);
Draw_Glyph_And_Values (Str, The_Fonts (This.Font_Index), Pt1);
Ctx.Set_Color (Black);
Ctx.Set_Font (The_Fonts (This.Font_Index));
Ctx.Print_In_Rect (Str3, Bounds);
end Draw;
-----------------------
-- On_Position_Event --
-----------------------
overriding function On_Position_Event
(This : in out Test_Fonts_Window;
Evt : Position_Event_Ref;
Pos : Point_T) return Boolean
is
begin
if On_Position_Event (Parent (This), Evt, Pos) then
if This.Next.Active then
if This.Font_Index = The_Fonts'Last then
This.Font_Index := The_Fonts'First;
else
This.Font_Index := This.Font_Index + 1;
end if;
elsif This.Prev.Active then
if This.Font_Index = The_Fonts'First then
This.Font_Index := The_Fonts'Last;
else
This.Font_Index := This.Font_Index - 1;
end if;
end if;
return True;
else
return False;
end if;
end On_Position_Event;
end Test_Fonts;
|
-- { dg-do compile }
package tag2 is
type I is synchronized interface;
type T1 is tagged;
type T2 is tagged;
type T3 is tagged;
type T4 is tagged;
type T5 is tagged;
type T6 is tagged;
protected type T1 is end T1; -- { dg-error "must be a tagged type" }
task type T2; -- { dg-error "must be a tagged type" }
type T3 is null record; -- { dg-error "must be a tagged type" }
task type T4 is new I with end;
protected type T5 is new I with end;
type T6 is tagged null record;
end tag2;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- SYSTEM.TASKING.PROTECTED_OBJECTS.OPERATIONS --
-- --
-- B o d y --
-- --
-- Copyright (C) 1998-2016, Free Software Foundation, Inc. --
-- --
-- GNARL is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNARL was developed by the GNARL team at Florida State University. --
-- Extensive contributions were provided by Ada Core Technologies, Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains all extended primitives related to Protected_Objects
-- with entries.
-- The handling of protected objects with no entries is done in
-- System.Tasking.Protected_Objects, the simple routines for protected
-- objects with entries in System.Tasking.Protected_Objects.Entries.
-- The split between Entries and Operations is needed to break circular
-- dependencies inside the run time.
-- This package contains all primitives related to Protected_Objects.
-- Note: the compiler generates direct calls to this interface, via Rtsfind.
with System.Task_Primitives.Operations;
with System.Tasking.Entry_Calls;
with System.Tasking.Queuing;
with System.Tasking.Rendezvous;
with System.Tasking.Utilities;
with System.Tasking.Debug;
with System.Parameters;
with System.Traces.Tasking;
with System.Restrictions;
with System.Tasking.Initialization;
pragma Elaborate_All (System.Tasking.Initialization);
-- Insures that tasking is initialized if any protected objects are created
package body System.Tasking.Protected_Objects.Operations is
package STPO renames System.Task_Primitives.Operations;
use Parameters;
use Task_Primitives;
use Ada.Exceptions;
use Entries;
use System.Restrictions;
use System.Restrictions.Rident;
use System.Traces;
use System.Traces.Tasking;
-----------------------
-- Local Subprograms --
-----------------------
procedure Update_For_Queue_To_PO
(Entry_Call : Entry_Call_Link;
With_Abort : Boolean);
pragma Inline (Update_For_Queue_To_PO);
-- Update the state of an existing entry call to reflect the fact that it
-- is being enqueued, based on whether the current queuing action is with
-- or without abort. Call this only while holding the PO's lock. It returns
-- with the PO's lock still held.
procedure Requeue_Call
(Self_Id : Task_Id;
Object : Protection_Entries_Access;
Entry_Call : Entry_Call_Link);
-- Handle requeue of Entry_Call.
-- In particular, queue the call if needed, or service it immediately
-- if possible.
---------------------------------
-- Cancel_Protected_Entry_Call --
---------------------------------
-- Compiler interface only (do not call from within the RTS)
-- This should have analogous effect to Cancel_Task_Entry_Call, setting
-- the value of Block.Cancelled instead of returning the parameter value
-- Cancelled.
-- The effect should be idempotent, since the call may already have been
-- dequeued.
-- Source code:
-- select r.e;
-- ...A...
-- then abort
-- ...B...
-- end select;
-- Expanded code:
-- declare
-- X : protected_entry_index := 1;
-- B80b : communication_block;
-- communication_blockIP (B80b);
-- begin
-- begin
-- A79b : label
-- A79b : declare
-- procedure _clean is
-- begin
-- if enqueued (B80b) then
-- cancel_protected_entry_call (B80b);
-- end if;
-- return;
-- end _clean;
-- begin
-- protected_entry_call (rTV!(r)._object'unchecked_access, X,
-- null_address, asynchronous_call, B80b, objectF => 0);
-- if enqueued (B80b) then
-- ...B...
-- end if;
-- at end
-- _clean;
-- end A79b;
-- exception
-- when _abort_signal =>
-- abort_undefer.all;
-- null;
-- end;
-- if not cancelled (B80b) then
-- x := ...A...
-- end if;
-- end;
-- If the entry call completes after we get into the abortable part,
-- Abort_Signal should be raised and ATC will take us to the at-end
-- handler, which will call _clean.
-- If the entry call returns with the call already completed, we can skip
-- this, and use the "if enqueued()" to go past the at-end handler, but we
-- will still call _clean.
-- If the abortable part completes before the entry call is Done, it will
-- call _clean.
-- If the entry call or the abortable part raises an exception,
-- we will still call _clean, but the value of Cancelled should not matter.
-- Whoever calls _clean first gets to decide whether the call
-- has been "cancelled".
-- Enqueued should be true if there is any chance that the call is still on
-- a queue. It seems to be safe to make it True if the call was Onqueue at
-- some point before return from Protected_Entry_Call.
-- Cancelled should be true iff the abortable part completed
-- and succeeded in cancelling the entry call before it completed.
-- ?????
-- The need for Enqueued is less obvious. The "if enqueued ()" tests are
-- not necessary, since Cancel_Protected_Entry_Call/Protected_Entry_Call
-- must do the same test internally, with locking. The one that makes
-- cancellation conditional may be a useful heuristic since at least 1/2
-- the time the call should be off-queue by that point. The other one seems
-- totally useless, since Protected_Entry_Call must do the same check and
-- then possibly wait for the call to be abortable, internally.
-- We can check Call.State here without locking the caller's mutex,
-- since the call must be over after returning from Wait_For_Completion.
-- No other task can access the call record at this point.
procedure Cancel_Protected_Entry_Call
(Block : in out Communication_Block) is
begin
Entry_Calls.Try_To_Cancel_Entry_Call (Block.Cancelled);
end Cancel_Protected_Entry_Call;
---------------
-- Cancelled --
---------------
function Cancelled (Block : Communication_Block) return Boolean is
begin
return Block.Cancelled;
end Cancelled;
-------------------------
-- Complete_Entry_Body --
-------------------------
procedure Complete_Entry_Body (Object : Protection_Entries_Access) is
begin
Exceptional_Complete_Entry_Body (Object, Ada.Exceptions.Null_Id);
end Complete_Entry_Body;
--------------
-- Enqueued --
--------------
function Enqueued (Block : Communication_Block) return Boolean is
begin
return Block.Enqueued;
end Enqueued;
-------------------------------------
-- Exceptional_Complete_Entry_Body --
-------------------------------------
procedure Exceptional_Complete_Entry_Body
(Object : Protection_Entries_Access;
Ex : Ada.Exceptions.Exception_Id)
is
procedure Transfer_Occurrence
(Target : Ada.Exceptions.Exception_Occurrence_Access;
Source : Ada.Exceptions.Exception_Occurrence);
pragma Import (C, Transfer_Occurrence, "__gnat_transfer_occurrence");
Entry_Call : constant Entry_Call_Link := Object.Call_In_Progress;
Self_Id : Task_Id;
begin
pragma Debug
(Debug.Trace (STPO.Self, "Exceptional_Complete_Entry_Body", 'P'));
-- We must have abort deferred, since we are inside a protected
-- operation.
if Entry_Call /= null then
-- The call was not requeued
Entry_Call.Exception_To_Raise := Ex;
if Ex /= Ada.Exceptions.Null_Id then
-- An exception was raised and abort was deferred, so adjust
-- before propagating, otherwise the task will stay with deferral
-- enabled for its remaining life.
Self_Id := STPO.Self;
if not ZCX_By_Default then
Initialization.Undefer_Abort_Nestable (Self_Id);
end if;
Transfer_Occurrence
(Entry_Call.Self.Common.Compiler_Data.Current_Excep'Access,
Self_Id.Common.Compiler_Data.Current_Excep);
end if;
-- Wakeup_Entry_Caller will be called from PO_Do_Or_Queue or
-- PO_Service_Entries on return.
end if;
if Runtime_Traces then
-- ??? Entry_Call can be null
Send_Trace_Info (PO_Done, Entry_Call.Self);
end if;
end Exceptional_Complete_Entry_Body;
--------------------
-- PO_Do_Or_Queue --
--------------------
procedure PO_Do_Or_Queue
(Self_ID : Task_Id;
Object : Protection_Entries_Access;
Entry_Call : Entry_Call_Link)
is
E : constant Protected_Entry_Index :=
Protected_Entry_Index (Entry_Call.E);
Index : constant Protected_Entry_Index :=
Object.Find_Body_Index (Object.Compiler_Info, E);
Barrier_Value : Boolean;
Queue_Length : Natural;
begin
-- When the Action procedure for an entry body returns, it is either
-- completed (having called [Exceptional_]Complete_Entry_Body) or it
-- is queued, having executed a requeue statement.
Barrier_Value :=
Object.Entry_Bodies (Index).Barrier (Object.Compiler_Info, E);
if Barrier_Value then
-- Not abortable while service is in progress
if Entry_Call.State = Now_Abortable then
Entry_Call.State := Was_Abortable;
end if;
Object.Call_In_Progress := Entry_Call;
pragma Debug
(Debug.Trace (Self_ID, "PODOQ: start entry body", 'P'));
Object.Entry_Bodies (Index).Action (
Object.Compiler_Info, Entry_Call.Uninterpreted_Data, E);
if Object.Call_In_Progress /= null then
-- Body of current entry served call to completion
Object.Call_In_Progress := null;
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Entry_Call.Self);
Initialization.Wakeup_Entry_Caller (Self_ID, Entry_Call, Done);
STPO.Unlock (Entry_Call.Self);
if Single_Lock then
STPO.Unlock_RTS;
end if;
else
Requeue_Call (Self_ID, Object, Entry_Call);
end if;
elsif Entry_Call.Mode /= Conditional_Call
or else not Entry_Call.With_Abort
then
if Run_Time_Restrictions.Set (Max_Entry_Queue_Length)
or else Object.Entry_Queue_Maxes /= null
then
-- Need to check the queue length. Computing the length is an
-- unusual case and is slow (need to walk the queue).
Queue_Length := Queuing.Count_Waiting (Object.Entry_Queues (E));
if (Run_Time_Restrictions.Set (Max_Entry_Queue_Length)
and then Queue_Length >=
Run_Time_Restrictions.Value (Max_Entry_Queue_Length))
or else
(Object.Entry_Queue_Maxes /= null
and then Object.Entry_Queue_Maxes (Index) /= 0
and then Queue_Length >= Object.Entry_Queue_Maxes (Index))
then
-- This violates the Max_Entry_Queue_Length restriction or the
-- Max_Queue_Length bound, raise Program_Error.
Entry_Call.Exception_To_Raise := Program_Error'Identity;
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Entry_Call.Self);
Initialization.Wakeup_Entry_Caller (Self_ID, Entry_Call, Done);
STPO.Unlock (Entry_Call.Self);
if Single_Lock then
STPO.Unlock_RTS;
end if;
return;
end if;
end if;
-- Do the work: queue the call
Queuing.Enqueue (Object.Entry_Queues (E), Entry_Call);
Update_For_Queue_To_PO (Entry_Call, Entry_Call.With_Abort);
return;
else
-- Conditional_Call and With_Abort
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Entry_Call.Self);
pragma Assert (Entry_Call.State /= Not_Yet_Abortable);
Initialization.Wakeup_Entry_Caller (Self_ID, Entry_Call, Cancelled);
STPO.Unlock (Entry_Call.Self);
if Single_Lock then
STPO.Unlock_RTS;
end if;
end if;
exception
when others =>
Queuing.Broadcast_Program_Error (Self_ID, Object, Entry_Call);
end PO_Do_Or_Queue;
------------------------
-- PO_Service_Entries --
------------------------
procedure PO_Service_Entries
(Self_ID : Task_Id;
Object : Entries.Protection_Entries_Access;
Unlock_Object : Boolean := True)
is
E : Protected_Entry_Index;
Caller : Task_Id;
Entry_Call : Entry_Call_Link;
begin
loop
Queuing.Select_Protected_Entry_Call (Self_ID, Object, Entry_Call);
exit when Entry_Call = null;
E := Protected_Entry_Index (Entry_Call.E);
-- Not abortable while service is in progress
if Entry_Call.State = Now_Abortable then
Entry_Call.State := Was_Abortable;
end if;
Object.Call_In_Progress := Entry_Call;
begin
if Runtime_Traces then
Send_Trace_Info (PO_Run, Self_ID,
Entry_Call.Self, Entry_Index (E));
end if;
pragma Debug
(Debug.Trace (Self_ID, "POSE: start entry body", 'P'));
Object.Entry_Bodies
(Object.Find_Body_Index (Object.Compiler_Info, E)).Action
(Object.Compiler_Info, Entry_Call.Uninterpreted_Data, E);
exception
when others =>
Queuing.Broadcast_Program_Error
(Self_ID, Object, Entry_Call);
end;
if Object.Call_In_Progress = null then
Requeue_Call (Self_ID, Object, Entry_Call);
exit when Entry_Call.State = Cancelled;
else
Object.Call_In_Progress := null;
Caller := Entry_Call.Self;
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Caller);
Initialization.Wakeup_Entry_Caller (Self_ID, Entry_Call, Done);
STPO.Unlock (Caller);
if Single_Lock then
STPO.Unlock_RTS;
end if;
end if;
end loop;
if Unlock_Object then
Unlock_Entries (Object);
end if;
end PO_Service_Entries;
---------------------
-- Protected_Count --
---------------------
function Protected_Count
(Object : Protection_Entries'Class;
E : Protected_Entry_Index) return Natural
is
begin
return Queuing.Count_Waiting (Object.Entry_Queues (E));
end Protected_Count;
--------------------------
-- Protected_Entry_Call --
--------------------------
-- Compiler interface only (do not call from within the RTS)
-- select r.e;
-- ...A...
-- else
-- ...B...
-- end select;
-- declare
-- X : protected_entry_index := 1;
-- B85b : communication_block;
-- communication_blockIP (B85b);
-- begin
-- protected_entry_call (rTV!(r)._object'unchecked_access, X,
-- null_address, conditional_call, B85b, objectF => 0);
-- if cancelled (B85b) then
-- ...B...
-- else
-- ...A...
-- end if;
-- end;
-- See also Cancel_Protected_Entry_Call for code expansion of asynchronous
-- entry call.
-- The initial part of this procedure does not need to lock the calling
-- task's ATCB, up to the point where the call record first may be queued
-- (PO_Do_Or_Queue), since before that no other task will have access to
-- the record.
-- If this is a call made inside of an abort deferred region, the call
-- should be never abortable.
-- If the call was not queued abortably, we need to wait until it is before
-- proceeding with the abortable part.
-- There are some heuristics here, just to save time for frequently
-- occurring cases. For example, we check Initially_Abortable to try to
-- avoid calling the procedure Wait_Until_Abortable, since the normal case
-- for async. entry calls is to be queued abortably.
-- Another heuristic uses the Block.Enqueued to try to avoid calling
-- Cancel_Protected_Entry_Call if the call can be served immediately.
procedure Protected_Entry_Call
(Object : Protection_Entries_Access;
E : Protected_Entry_Index;
Uninterpreted_Data : System.Address;
Mode : Call_Modes;
Block : out Communication_Block)
is
Self_ID : constant Task_Id := STPO.Self;
Entry_Call : Entry_Call_Link;
Initially_Abortable : Boolean;
Ceiling_Violation : Boolean;
begin
pragma Debug
(Debug.Trace (Self_ID, "Protected_Entry_Call", 'P'));
if Runtime_Traces then
Send_Trace_Info (PO_Call, Entry_Index (E));
end if;
if Self_ID.ATC_Nesting_Level = ATC_Level'Last then
raise Storage_Error with "not enough ATC nesting levels";
end if;
-- If pragma Detect_Blocking is active then Program_Error must be
-- raised if this potentially blocking operation is called from a
-- protected action.
if Detect_Blocking
and then Self_ID.Common.Protected_Action_Nesting > 0
then
raise Program_Error with "potentially blocking operation";
end if;
-- Self_ID.Deferral_Level should be 0, except when called from Finalize,
-- where abort is already deferred.
Initialization.Defer_Abort_Nestable (Self_ID);
Lock_Entries_With_Status (Object, Ceiling_Violation);
if Ceiling_Violation then
-- Failed ceiling check
Initialization.Undefer_Abort_Nestable (Self_ID);
raise Program_Error;
end if;
Block.Self := Self_ID;
Self_ID.ATC_Nesting_Level := Self_ID.ATC_Nesting_Level + 1;
pragma Debug
(Debug.Trace (Self_ID, "PEC: entered ATC level: " &
ATC_Level'Image (Self_ID.ATC_Nesting_Level), 'A'));
Entry_Call :=
Self_ID.Entry_Calls (Self_ID.ATC_Nesting_Level)'Access;
Entry_Call.Next := null;
Entry_Call.Mode := Mode;
Entry_Call.Cancellation_Attempted := False;
Entry_Call.State :=
(if Self_ID.Deferral_Level > 1
then Never_Abortable else Now_Abortable);
Entry_Call.E := Entry_Index (E);
Entry_Call.Prio := STPO.Get_Priority (Self_ID);
Entry_Call.Uninterpreted_Data := Uninterpreted_Data;
Entry_Call.Called_PO := To_Address (Object);
Entry_Call.Called_Task := null;
Entry_Call.Exception_To_Raise := Ada.Exceptions.Null_Id;
Entry_Call.With_Abort := True;
PO_Do_Or_Queue (Self_ID, Object, Entry_Call);
Initially_Abortable := Entry_Call.State = Now_Abortable;
PO_Service_Entries (Self_ID, Object);
-- Try to prevent waiting later (in Try_To_Cancel_Protected_Entry_Call)
-- for completed or cancelled calls. (This is a heuristic, only.)
if Entry_Call.State >= Done then
-- Once State >= Done it will not change any more
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Self_ID);
Utilities.Exit_One_ATC_Level (Self_ID);
STPO.Unlock (Self_ID);
if Single_Lock then
STPO.Unlock_RTS;
end if;
Block.Enqueued := False;
Block.Cancelled := Entry_Call.State = Cancelled;
Initialization.Undefer_Abort_Nestable (Self_ID);
Entry_Calls.Check_Exception (Self_ID, Entry_Call);
return;
else
-- In this case we cannot conclude anything, since State can change
-- concurrently.
null;
end if;
-- Now for the general case
if Mode = Asynchronous_Call then
-- Try to avoid an expensive call
if not Initially_Abortable then
if Single_Lock then
STPO.Lock_RTS;
Entry_Calls.Wait_Until_Abortable (Self_ID, Entry_Call);
STPO.Unlock_RTS;
else
Entry_Calls.Wait_Until_Abortable (Self_ID, Entry_Call);
end if;
end if;
else
case Mode is
when Conditional_Call
| Simple_Call
=>
if Single_Lock then
STPO.Lock_RTS;
Entry_Calls.Wait_For_Completion (Entry_Call);
STPO.Unlock_RTS;
else
STPO.Write_Lock (Self_ID);
Entry_Calls.Wait_For_Completion (Entry_Call);
STPO.Unlock (Self_ID);
end if;
Block.Cancelled := Entry_Call.State = Cancelled;
when Asynchronous_Call
| Timed_Call
=>
pragma Assert (False);
null;
end case;
end if;
Initialization.Undefer_Abort_Nestable (Self_ID);
Entry_Calls.Check_Exception (Self_ID, Entry_Call);
end Protected_Entry_Call;
------------------
-- Requeue_Call --
------------------
procedure Requeue_Call
(Self_Id : Task_Id;
Object : Protection_Entries_Access;
Entry_Call : Entry_Call_Link)
is
New_Object : Protection_Entries_Access;
Ceiling_Violation : Boolean;
Result : Boolean;
E : Protected_Entry_Index;
begin
New_Object := To_Protection (Entry_Call.Called_PO);
if New_Object = null then
-- Call is to be requeued to a task entry
if Single_Lock then
STPO.Lock_RTS;
end if;
Result := Rendezvous.Task_Do_Or_Queue (Self_Id, Entry_Call);
if not Result then
Queuing.Broadcast_Program_Error
(Self_Id, Object, Entry_Call, RTS_Locked => True);
end if;
if Single_Lock then
STPO.Unlock_RTS;
end if;
else
-- Call should be requeued to a PO
if Object /= New_Object then
-- Requeue is to different PO
Lock_Entries_With_Status (New_Object, Ceiling_Violation);
if Ceiling_Violation then
Object.Call_In_Progress := null;
Queuing.Broadcast_Program_Error (Self_Id, Object, Entry_Call);
else
PO_Do_Or_Queue (Self_Id, New_Object, Entry_Call);
PO_Service_Entries (Self_Id, New_Object);
end if;
else
-- Requeue is to same protected object
-- ??? Try to compensate apparent failure of the scheduler on some
-- OS (e.g VxWorks) to give higher priority tasks a chance to run
-- (see CXD6002).
STPO.Yield (Do_Yield => False);
if Entry_Call.With_Abort
and then Entry_Call.Cancellation_Attempted
then
-- If this is a requeue with abort and someone tried to cancel
-- this call, cancel it at this point.
Entry_Call.State := Cancelled;
return;
end if;
if not Entry_Call.With_Abort
or else Entry_Call.Mode /= Conditional_Call
then
E := Protected_Entry_Index (Entry_Call.E);
if Run_Time_Restrictions.Set (Max_Entry_Queue_Length)
and then
Run_Time_Restrictions.Value (Max_Entry_Queue_Length) <=
Queuing.Count_Waiting (Object.Entry_Queues (E))
then
-- This violates the Max_Entry_Queue_Length restriction,
-- raise Program_Error.
Entry_Call.Exception_To_Raise := Program_Error'Identity;
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Entry_Call.Self);
Initialization.Wakeup_Entry_Caller
(Self_Id, Entry_Call, Done);
STPO.Unlock (Entry_Call.Self);
if Single_Lock then
STPO.Unlock_RTS;
end if;
else
Queuing.Enqueue
(New_Object.Entry_Queues (E), Entry_Call);
Update_For_Queue_To_PO (Entry_Call, Entry_Call.With_Abort);
end if;
else
PO_Do_Or_Queue (Self_Id, New_Object, Entry_Call);
end if;
end if;
end if;
end Requeue_Call;
----------------------------
-- Protected_Entry_Caller --
----------------------------
function Protected_Entry_Caller
(Object : Protection_Entries'Class) return Task_Id is
begin
return Object.Call_In_Progress.Self;
end Protected_Entry_Caller;
-----------------------------
-- Requeue_Protected_Entry --
-----------------------------
-- Compiler interface only (do not call from within the RTS)
-- entry e when b is
-- begin
-- b := false;
-- ...A...
-- requeue e2;
-- end e;
-- procedure rPT__E10b (O : address; P : address; E :
-- protected_entry_index) is
-- type rTVP is access rTV;
-- freeze rTVP []
-- _object : rTVP := rTVP!(O);
-- begin
-- declare
-- rR : protection renames _object._object;
-- vP : integer renames _object.v;
-- bP : boolean renames _object.b;
-- begin
-- b := false;
-- ...A...
-- requeue_protected_entry (rR'unchecked_access, rR'
-- unchecked_access, 2, false, objectF => 0, new_objectF =>
-- 0);
-- return;
-- end;
-- complete_entry_body (_object._object'unchecked_access, objectF =>
-- 0);
-- return;
-- exception
-- when others =>
-- abort_undefer.all;
-- exceptional_complete_entry_body (_object._object'
-- unchecked_access, current_exception, objectF => 0);
-- return;
-- end rPT__E10b;
procedure Requeue_Protected_Entry
(Object : Protection_Entries_Access;
New_Object : Protection_Entries_Access;
E : Protected_Entry_Index;
With_Abort : Boolean)
is
Entry_Call : constant Entry_Call_Link := Object.Call_In_Progress;
begin
pragma Debug
(Debug.Trace (STPO.Self, "Requeue_Protected_Entry", 'P'));
pragma Assert (STPO.Self.Deferral_Level > 0);
Entry_Call.E := Entry_Index (E);
Entry_Call.Called_PO := To_Address (New_Object);
Entry_Call.Called_Task := null;
Entry_Call.With_Abort := With_Abort;
Object.Call_In_Progress := null;
end Requeue_Protected_Entry;
-------------------------------------
-- Requeue_Task_To_Protected_Entry --
-------------------------------------
-- Compiler interface only (do not call from within the RTS)
-- accept e1 do
-- ...A...
-- requeue r.e2;
-- end e1;
-- A79b : address;
-- L78b : label
-- begin
-- accept_call (1, A79b);
-- ...A...
-- requeue_task_to_protected_entry (rTV!(r)._object'
-- unchecked_access, 2, false, new_objectF => 0);
-- goto L78b;
-- <<L78b>>
-- complete_rendezvous;
-- exception
-- when all others =>
-- exceptional_complete_rendezvous (get_gnat_exception);
-- end;
procedure Requeue_Task_To_Protected_Entry
(New_Object : Protection_Entries_Access;
E : Protected_Entry_Index;
With_Abort : Boolean)
is
Self_ID : constant Task_Id := STPO.Self;
Entry_Call : constant Entry_Call_Link := Self_ID.Common.Call;
begin
Initialization.Defer_Abort (Self_ID);
-- We do not need to lock Self_ID here since the call is not abortable
-- at this point, and therefore, the caller cannot cancel the call.
Entry_Call.Needs_Requeue := True;
Entry_Call.With_Abort := With_Abort;
Entry_Call.Called_PO := To_Address (New_Object);
Entry_Call.Called_Task := null;
Entry_Call.E := Entry_Index (E);
Initialization.Undefer_Abort (Self_ID);
end Requeue_Task_To_Protected_Entry;
---------------------
-- Service_Entries --
---------------------
procedure Service_Entries (Object : Protection_Entries_Access) is
Self_ID : constant Task_Id := STPO.Self;
begin
PO_Service_Entries (Self_ID, Object);
end Service_Entries;
--------------------------------
-- Timed_Protected_Entry_Call --
--------------------------------
-- Compiler interface only (do not call from within the RTS)
procedure Timed_Protected_Entry_Call
(Object : Protection_Entries_Access;
E : Protected_Entry_Index;
Uninterpreted_Data : System.Address;
Timeout : Duration;
Mode : Delay_Modes;
Entry_Call_Successful : out Boolean)
is
Self_Id : constant Task_Id := STPO.Self;
Entry_Call : Entry_Call_Link;
Ceiling_Violation : Boolean;
Yielded : Boolean;
pragma Unreferenced (Yielded);
begin
if Self_Id.ATC_Nesting_Level = ATC_Level'Last then
raise Storage_Error with "not enough ATC nesting levels";
end if;
-- If pragma Detect_Blocking is active then Program_Error must be
-- raised if this potentially blocking operation is called from a
-- protected action.
if Detect_Blocking
and then Self_Id.Common.Protected_Action_Nesting > 0
then
raise Program_Error with "potentially blocking operation";
end if;
if Runtime_Traces then
Send_Trace_Info (POT_Call, Entry_Index (E), Timeout);
end if;
Initialization.Defer_Abort_Nestable (Self_Id);
Lock_Entries_With_Status (Object, Ceiling_Violation);
if Ceiling_Violation then
Initialization.Undefer_Abort (Self_Id);
raise Program_Error;
end if;
Self_Id.ATC_Nesting_Level := Self_Id.ATC_Nesting_Level + 1;
pragma Debug
(Debug.Trace (Self_Id, "TPEC: exited to ATC level: " &
ATC_Level'Image (Self_Id.ATC_Nesting_Level), 'A'));
Entry_Call := Self_Id.Entry_Calls (Self_Id.ATC_Nesting_Level)'Access;
Entry_Call.Next := null;
Entry_Call.Mode := Timed_Call;
Entry_Call.Cancellation_Attempted := False;
Entry_Call.State :=
(if Self_Id.Deferral_Level > 1
then Never_Abortable
else Now_Abortable);
Entry_Call.E := Entry_Index (E);
Entry_Call.Prio := STPO.Get_Priority (Self_Id);
Entry_Call.Uninterpreted_Data := Uninterpreted_Data;
Entry_Call.Called_PO := To_Address (Object);
Entry_Call.Called_Task := null;
Entry_Call.Exception_To_Raise := Ada.Exceptions.Null_Id;
Entry_Call.With_Abort := True;
PO_Do_Or_Queue (Self_Id, Object, Entry_Call);
PO_Service_Entries (Self_Id, Object);
if Single_Lock then
STPO.Lock_RTS;
else
STPO.Write_Lock (Self_Id);
end if;
-- Try to avoid waiting for completed or cancelled calls
if Entry_Call.State >= Done then
Utilities.Exit_One_ATC_Level (Self_Id);
if Single_Lock then
STPO.Unlock_RTS;
else
STPO.Unlock (Self_Id);
end if;
Entry_Call_Successful := Entry_Call.State = Done;
Initialization.Undefer_Abort_Nestable (Self_Id);
Entry_Calls.Check_Exception (Self_Id, Entry_Call);
return;
end if;
Entry_Calls.Wait_For_Completion_With_Timeout
(Entry_Call, Timeout, Mode, Yielded);
if Single_Lock then
STPO.Unlock_RTS;
else
STPO.Unlock (Self_Id);
end if;
-- ??? Do we need to yield in case Yielded is False
Initialization.Undefer_Abort_Nestable (Self_Id);
Entry_Call_Successful := Entry_Call.State = Done;
Entry_Calls.Check_Exception (Self_Id, Entry_Call);
end Timed_Protected_Entry_Call;
----------------------------
-- Update_For_Queue_To_PO --
----------------------------
-- Update the state of an existing entry call, based on
-- whether the current queuing action is with or without abort.
-- Call this only while holding the server's lock.
-- It returns with the server's lock released.
New_State : constant array (Boolean, Entry_Call_State)
of Entry_Call_State :=
(True =>
(Never_Abortable => Never_Abortable,
Not_Yet_Abortable => Now_Abortable,
Was_Abortable => Now_Abortable,
Now_Abortable => Now_Abortable,
Done => Done,
Cancelled => Cancelled),
False =>
(Never_Abortable => Never_Abortable,
Not_Yet_Abortable => Not_Yet_Abortable,
Was_Abortable => Was_Abortable,
Now_Abortable => Now_Abortable,
Done => Done,
Cancelled => Cancelled)
);
procedure Update_For_Queue_To_PO
(Entry_Call : Entry_Call_Link;
With_Abort : Boolean)
is
Old : constant Entry_Call_State := Entry_Call.State;
begin
pragma Assert (Old < Done);
Entry_Call.State := New_State (With_Abort, Entry_Call.State);
if Entry_Call.Mode = Asynchronous_Call then
if Old < Was_Abortable and then
Entry_Call.State = Now_Abortable
then
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Entry_Call.Self);
if Entry_Call.Self.Common.State = Async_Select_Sleep then
STPO.Wakeup (Entry_Call.Self, Async_Select_Sleep);
end if;
STPO.Unlock (Entry_Call.Self);
if Single_Lock then
STPO.Unlock_RTS;
end if;
end if;
elsif Entry_Call.Mode = Conditional_Call then
pragma Assert (Entry_Call.State < Was_Abortable);
null;
end if;
end Update_For_Queue_To_PO;
end System.Tasking.Protected_Objects.Operations;
|
-----------------------------------------------------------------------
-- awa-events-queues -- AWA Event Queues
-- Copyright (C) 2012, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Listeners;
private with Util.Refs;
with EL.Beans;
with EL.Contexts;
with AWA.Events.Models;
package AWA.Events.Queues is
FIFO_QUEUE_TYPE : constant String := "fifo";
PERSISTENT_QUEUE_TYPE : constant String := "persist";
type Queue_Ref is tagged private;
-- Queue the event.
procedure Enqueue (Into : in Queue_Ref;
Event : in AWA.Events.Module_Event'Class);
-- Dequeue an event and process it with the <b>Process</b> procedure.
procedure Dequeue (From : in Queue_Ref;
Process : access procedure (Event : in Module_Event'Class));
-- Add a listener that will be called each time an event is queued.
procedure Add_Listener (Into : in Queue_Ref;
Listener : in Util.Listeners.Listener_Access);
-- Returns true if the queue is available.
function Has_Queue (Queue : in Queue_Ref'Class) return Boolean;
-- Returns the queue name.
function Get_Name (Queue : in Queue_Ref'Class) return String;
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
function Get_Queue (Queue : in Queue_Ref'Class) return Events.Models.Queue_Ref;
-- Create the event queue identified by the name `Name`. The queue factory
-- identified by `Kind` is called to create the event queue instance.
-- Returns a reference to the queue.
function Create_Queue (Name : in String;
Kind : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class)
return Queue_Ref;
function Null_Queue return Queue_Ref;
private
type Queue is limited interface;
type Queue_Access is access all Queue'Class;
-- Get the queue name.
function Get_Name (From : in Queue) return String is abstract;
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
function Get_Queue (From : in Queue) return Events.Models.Queue_Ref is abstract;
-- Queue the event.
procedure Enqueue (Into : in out Queue;
Event : in AWA.Events.Module_Event'Class) is abstract;
-- Dequeue an event and process it with the `Process` procedure.
procedure Dequeue (From : in out Queue;
Process : access procedure (Event : in Module_Event'Class)) is abstract;
-- Release the queue storage.
procedure Finalize (From : in out Queue) is null;
type Queue_Info (Length : Natural) is new Util.Refs.Ref_Entity with record
Queue : Queue_Access := null;
Listeners : Util.Listeners.List;
Name : String (1 .. Length);
end record;
type Queue_Info_Access is access all Queue_Info;
-- Finalize the referenced object. This is called before the object is freed.
overriding
procedure Finalize (Object : in out Queue_Info);
package Queue_Refs is
new Util.Refs.Indefinite_References (Queue_Info, Queue_Info_Access);
subtype Queue_Info_Accessor is Queue_Refs.Element_Accessor;
type Queue_Ref is new Queue_Refs.Ref with null record;
end AWA.Events.Queues;
|
with ada.text_io, ada.Integer_text_IO, Ada.Text_IO.Text_Streams, Ada.Strings.Fixed, Interfaces.C;
use ada.text_io, ada.Integer_text_IO, Ada.Strings, Ada.Strings.Fixed, Interfaces.C;
procedure tictactoe is
type stringptr is access all char_array;
procedure PString(s : stringptr) is
begin
String'Write (Text_Streams.Stream (Current_Output), To_Ada(s.all));
end;
procedure PInt(i : in Integer) is
begin
String'Write (Text_Streams.Stream (Current_Output), Trim(Integer'Image(i), Left));
end;
procedure SkipSpaces is
C : Character;
Eol : Boolean;
begin
loop
Look_Ahead(C, Eol);
exit when Eol or C /= ' ';
Get(C);
end loop;
end;
--
--Tictactoe : un tictactoe avec une IA
--
-- La structure de donnée
type gamestate;
type gamestate_PTR is access gamestate;
type e is Array (Integer range <>) of Integer;
type e_PTR is access e;
type f is Array (Integer range <>) of e_PTR;
type f_PTR is access f;
type gamestate is record
cases : f_PTR;
firstToPlay : Boolean;
note : Integer;
ended : Boolean;
end record;
-- Un Mouvement
type move;
type move_PTR is access move;
type move is record
x : Integer;
y : Integer;
end record;
-- On affiche l'état
procedure print_state(g : in gamestate_PTR) is
begin
PString(new char_array'( To_C("" & Character'Val(10) & "|")));
for y in integer range 0..2 loop
for x in integer range 0..2 loop
if g.cases(x)(y) = 0
then
PString(new char_array'( To_C(" ")));
else
if g.cases(x)(y) = 1
then
PString(new char_array'( To_C("O")));
else
PString(new char_array'( To_C("X")));
end if;
end if;
PString(new char_array'( To_C("|")));
end loop;
if y /= 2
then
PString(new char_array'( To_C("" & Character'Val(10) & "|-|-|-|" & Character'Val(10) & "|")));
end if;
end loop;
PString(new char_array'( To_C("" & Character'Val(10))));
end;
-- On dit qui gagne (info stoquées dans g.ended et g.note )
procedure eval0(g : in gamestate_PTR) is
win : Integer;
linv : Integer;
lin : Integer;
freecase : Integer;
colv : Integer;
col : Integer;
begin
win := 0;
freecase := 0;
for y in integer range 0..2 loop
col := (-1);
lin := (-1);
for x in integer range 0..2 loop
if g.cases(x)(y) = 0
then
freecase := freecase + 1;
end if;
colv := g.cases(x)(y);
linv := g.cases(y)(x);
if col = (-1) and then colv /= 0
then
col := colv;
else
if colv /= col
then
col := (-2);
end if;
end if;
if lin = (-1) and then linv /= 0
then
lin := linv;
else
if linv /= lin
then
lin := (-2);
end if;
end if;
end loop;
if col >= 0
then
win := col;
else
if lin >= 0
then
win := lin;
end if;
end if;
end loop;
for x in integer range 1..2 loop
if (g.cases(0)(0) = x and then g.cases(1)(1) = x) and then g.cases(2)(2) = x
then
win := x;
end if;
if (g.cases(0)(2) = x and then g.cases(1)(1) = x) and then g.cases(2)(0) = x
then
win := x;
end if;
end loop;
g.ended := win /= 0 or else freecase = 0;
if win = 1
then
g.note := 1000;
else
if win = 2
then
g.note := (-1000);
else
g.note := 0;
end if;
end if;
end;
-- On applique un mouvement
procedure apply_move_xy(x : in Integer; y : in Integer; g : in gamestate_PTR) is
player : Integer;
begin
player := 2;
if g.firstToPlay
then
player := 1;
end if;
g.cases(x)(y) := player;
g.firstToPlay := not g.firstToPlay;
end;
procedure apply_move(m : in move_PTR; g : in gamestate_PTR) is
begin
apply_move_xy(m.x, m.y, g);
end;
procedure cancel_move_xy(x : in Integer; y : in Integer; g : in gamestate_PTR) is
begin
g.cases(x)(y) := 0;
g.firstToPlay := not g.firstToPlay;
g.ended := FALSE;
end;
procedure cancel_move(m : in move_PTR; g : in gamestate_PTR) is
begin
cancel_move_xy(m.x, m.y, g);
end;
function can_move_xy(x : in Integer; y : in Integer; g : in gamestate_PTR) return Boolean is
begin
return g.cases(x)(y) = 0;
end;
function can_move(m : in move_PTR; g : in gamestate_PTR) return Boolean is
begin
return can_move_xy(m.x, m.y, g);
end;
--
--Un minimax classique, renvoie la note du plateau
--
function minmax(g : in gamestate_PTR) return Integer is
maxNote : Integer;
currentNote : Integer;
begin
eval0(g);
if g.ended
then
return g.note;
end if;
maxNote := (-10000);
if not g.firstToPlay
then
maxNote := 10000;
end if;
for x in integer range 0..2 loop
for y in integer range 0..2 loop
if can_move_xy(x, y, g)
then
apply_move_xy(x, y, g);
currentNote := minmax(g);
cancel_move_xy(x, y, g);
-- Minimum ou Maximum selon le coté ou l'on joue
if (currentNote > maxNote) = g.firstToPlay
then
maxNote := currentNote;
end if;
end if;
end loop;
end loop;
return maxNote;
end;
--
--Renvoie le coup de l'IA
--
function play(g : in gamestate_PTR) return move_PTR is
minNote : Integer;
minMove : move_PTR;
currentNote : Integer;
begin
minMove := new move;
minMove.x := 0;
minMove.y := 0;
minNote := 10000;
for x in integer range 0..2 loop
for y in integer range 0..2 loop
if can_move_xy(x, y, g)
then
apply_move_xy(x, y, g);
currentNote := minmax(g);
PInt(x);
PString(new char_array'( To_C(", ")));
PInt(y);
PString(new char_array'( To_C(", ")));
PInt(currentNote);
PString(new char_array'( To_C("" & Character'Val(10))));
cancel_move_xy(x, y, g);
if currentNote < minNote
then
minNote := currentNote;
minMove.x := x;
minMove.y := y;
end if;
end if;
end loop;
end loop;
PInt(minMove.x);
PInt(minMove.y);
PString(new char_array'( To_C("" & Character'Val(10))));
return minMove;
end;
function init0 return gamestate_PTR is
tab : e_PTR;
cases : f_PTR;
a : gamestate_PTR;
begin
cases := new f (0..2);
for i in integer range 0..2 loop
tab := new e (0..2);
for j in integer range 0..2 loop
tab(j) := 0;
end loop;
cases(i) := tab;
end loop;
a := new gamestate;
a.cases := cases;
a.firstToPlay := TRUE;
a.note := 0;
a.ended := FALSE;
return a;
end;
function read_move return move_PTR is
y : Integer;
x : Integer;
b : move_PTR;
begin
Get(x);
SkipSpaces;
Get(y);
SkipSpaces;
b := new move;
b.x := x;
b.y := y;
return b;
end;
state : gamestate_PTR;
d : move_PTR;
c : move_PTR;
begin
for i in integer range 0..1 loop
state := init0;
c := new move;
c.x := 1;
c.y := 1;
apply_move(c, state);
d := new move;
d.x := 0;
d.y := 0;
apply_move(d, state);
while not state.ended loop
print_state(state);
apply_move(play(state), state);
eval0(state);
print_state(state);
if not state.ended
then
apply_move(play(state), state);
eval0(state);
end if;
end loop;
print_state(state);
PInt(state.note);
PString(new char_array'( To_C("" & Character'Val(10))));
end loop;
end;
|
pragma Ada_2005;
pragma Style_Checks (Off);
pragma Warnings (Off);
with Interfaces.C; use Interfaces.C;
package GStreamer.GST_Low_Level.gstreamer_0_10_gst_sdp_gstsdp_h is
-- GStreamer
-- * Copyright (C) <2005,2006> Wim Taymans <wim@fluendo.com>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Library General Public
-- * License as published by the Free Software Foundation; either
-- * version 2 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- * Library General Public License for more details.
-- *
-- * You should have received a copy of the GNU Library General Public
-- * License along with this library; if not, write to the
-- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-- * Boston, MA 02111-1307, USA.
--
-- * Unless otherwise indicated, Source Code is licensed under MIT license.
-- * See further explanation attached in License Statement (distributed in the file
-- * LICENSE).
-- *
-- * 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.
--
--*
-- * GstSDPResult:
-- * @GST_SDP_OK: A successful return value
-- * @GST_SDP_EINVAL: a function was given invalid parameters
-- *
-- * Return values for the SDP functions.
--
subtype GstSDPResult is int;
GST_SDP_OK : constant GstSDPResult := 0;
GST_SDP_EINVAL : constant GstSDPResult := -1; -- gst/sdp/gstsdp.h:56
end GStreamer.GST_Low_Level.gstreamer_0_10_gst_sdp_gstsdp_h;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012-2015, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
pragma Restrictions (No_Elaboration_Code);
-- GNAT: enforce generation of preinitialized data section instead of
-- generation of elaboration code.
package Matreshka.Internals.Unicode.Ucd.Core_001A is
pragma Preelaborate;
Group_001A : aliased constant Core_Second_Stage
:= (16#00# .. 16#16# => -- 1A00 .. 1A16
(Other_Letter, Neutral,
Other, A_Letter, O_Letter, Alphabetic,
(Alphabetic
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start => True,
others => False)),
16#17# .. 16#18# => -- 1A17 .. 1A18
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Combining_Mark,
(Other_Alphabetic
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#19# .. 16#1A# => -- 1A19 .. 1A1A
(Spacing_Mark, Neutral,
Spacing_Mark, Extend, Extend, Combining_Mark,
(Other_Alphabetic
| Alphabetic
| Grapheme_Base
| ID_Continue
| XID_Continue => True,
others => False)),
16#1B# => -- 1A1B
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Combining_Mark,
(Other_Alphabetic
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#1E# .. 16#1F# => -- 1A1E .. 1A1F
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Grapheme_Base => True,
others => False)),
16#20# .. 16#54# => -- 1A20 .. 1A54
(Other_Letter, Neutral,
Other, Other, O_Letter, Complex_Context,
(Alphabetic
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start => True,
others => False)),
16#55# => -- 1A55
(Spacing_Mark, Neutral,
Spacing_Mark, Extend, Extend, Complex_Context,
(Other_Alphabetic
| Alphabetic
| Grapheme_Base
| ID_Continue
| XID_Continue => True,
others => False)),
16#56# => -- 1A56
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Complex_Context,
(Other_Alphabetic
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#57# => -- 1A57
(Spacing_Mark, Neutral,
Spacing_Mark, Extend, Extend, Complex_Context,
(Other_Alphabetic
| Alphabetic
| Grapheme_Base
| ID_Continue
| XID_Continue => True,
others => False)),
16#58# .. 16#5E# => -- 1A58 .. 1A5E
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Complex_Context,
(Other_Alphabetic
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#60# => -- 1A60
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Complex_Context,
(Case_Ignorable
| Grapheme_Extend
| Grapheme_Link
| ID_Continue
| XID_Continue => True,
others => False)),
16#61# => -- 1A61
(Spacing_Mark, Neutral,
Other, Extend, Extend, Complex_Context,
(Other_Alphabetic
| Alphabetic
| Grapheme_Base
| ID_Continue
| XID_Continue => True,
others => False)),
16#62# => -- 1A62
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Complex_Context,
(Other_Alphabetic
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#63# .. 16#64# => -- 1A63 .. 1A64
(Spacing_Mark, Neutral,
Other, Extend, Extend, Complex_Context,
(Other_Alphabetic
| Alphabetic
| Grapheme_Base
| ID_Continue
| XID_Continue => True,
others => False)),
16#65# .. 16#6C# => -- 1A65 .. 1A6C
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Complex_Context,
(Other_Alphabetic
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#6D# .. 16#72# => -- 1A6D .. 1A72
(Spacing_Mark, Neutral,
Spacing_Mark, Extend, Extend, Complex_Context,
(Other_Alphabetic
| Alphabetic
| Grapheme_Base
| ID_Continue
| XID_Continue => True,
others => False)),
16#73# .. 16#74# => -- 1A73 .. 1A74
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Complex_Context,
(Other_Alphabetic
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#75# .. 16#7C# => -- 1A75 .. 1A7C
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Complex_Context,
(Diacritic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#7F# => -- 1A7F
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Combining_Mark,
(Diacritic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#80# .. 16#89# => -- 1A80 .. 1A89
(Decimal_Number, Neutral,
Other, Numeric, Numeric, Numeric,
(Grapheme_Base
| ID_Continue
| XID_Continue => True,
others => False)),
16#90# .. 16#99# => -- 1A90 .. 1A99
(Decimal_Number, Neutral,
Other, Numeric, Numeric, Numeric,
(Grapheme_Base
| ID_Continue
| XID_Continue => True,
others => False)),
16#A0# .. 16#A6# => -- 1AA0 .. 1AA6
(Other_Punctuation, Neutral,
Other, Other, Other, Complex_Context,
(Grapheme_Base => True,
others => False)),
16#A7# => -- 1AA7
(Modifier_Letter, Neutral,
Other, Other, O_Letter, Complex_Context,
(Extender
| Alphabetic
| Case_Ignorable
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start => True,
others => False)),
16#A8# .. 16#AB# => -- 1AA8 .. 1AAB
(Other_Punctuation, Neutral,
Other, Other, S_Term, Complex_Context,
(STerm
| Terminal_Punctuation
| Grapheme_Base => True,
others => False)),
16#AC# .. 16#AD# => -- 1AAC .. 1AAD
(Other_Punctuation, Neutral,
Other, Other, Other, Complex_Context,
(Grapheme_Base => True,
others => False)),
16#B0# .. 16#BD# => -- 1AB0 .. 1ABD
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Combining_Mark,
(Diacritic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#BE# => -- 1ABE
(Enclosing_Mark, Neutral,
Extend, Extend, Extend, Combining_Mark,
(Case_Ignorable
| Grapheme_Extend => True,
others => False)),
others =>
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)));
end Matreshka.Internals.Unicode.Ucd.Core_001A;
|
--***************************************************************
-- Procedure benchmarks FFT. 50000 calls to FFT and 50000 calls to
-- to the inverse FFT.
-- The FFT does 4N*ln(N) flops per call, where N=array length.
-- So 100000 FFT's do:
-- 1840*10**6 flops where N=512.
-- 4100*10**6 flops where N=1024.
--***************************************************************
with Fourier8;
with Text_IO; use Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
procedure fourier8_tst_1 is
type Real is digits 15;
package math is new Ada.Numerics.Generic_Elementary_Functions (Real);
use math;
package rio is new Float_IO(Real);
use rio;
package iio is new Integer_IO(Integer);
use iio;
--No_of_Repetitions : constant := 25_000; -- std, as described above.
No_of_Repetitions : constant := 1;
Log_Of_Max_Data_Length : constant := 22;
-- Means max data array size is 2**Log_Of_Max_Data_Length.
-- The larger you make this array, the slower program might run.
subtype Array_Index is Integer range 0..2**Log_Of_Max_Data_Length + 0;
-- Sometimes its faster to add a bit to the end.
--subtype Array_Index is Integer range 0..2**Log_Of_Max_Data_Length+1;
--subtype Array_Index is Integer range 0..2**(Log_Of_Max_Data_Length+1)-2;
type Data_Array is array(Array_Index) of Real;
package fft8 is new Fourier8
(Real, Array_Index, Data_Array, Log_Of_Max_Data_Length);
use fft8;
--Do_the_Bit_Reversal : constant Boolean := False;
Do_the_Bit_Reversal : constant Boolean := True;
D_Re : Data_Array;
D_Im : Data_Array;
Transformed_Data_Last, Data_Set_Last : Data_Index;
Theta : Real;
Inverse_No_Points, Inverse_No_Points2 : Real;
Num : Integer;
Error, D_Old, Max_Error : Real;
Transformed_Data_Length : Real;
Exp_Table : Exp_Storage;
-- and add the following to the FFT parameter list:
--
-- Exp_Table => Exp_Table,
--
------------------
-- Integer_Log2 --
------------------
function Integer_Log2 (I : Array_Index)
return Integer
is
Logarithm : Integer := 0;
Argument : constant Integer := Integer(I);
-- Rounds down, so on range (eg) 0..2**15-1 it
-- returns 0 .. 14, It returns 0 for I in 0..1
-- returns 1 for I in 2..3, etc.
begin
for Exponent in 0..63 loop
exit when 2**Exponent > Argument;
Logarithm := Exponent;
end loop;
return Logarithm;
end Integer_Log2;
begin
new_line;
put ("Enter number of data points in the FFT.");
new_line;
put ("Using a power of 2 like 1024 is good idea if you are doing benchmarks.");
new_line;
put ("Enter the desired number: ");
get (Num);
new_line;
Data_Set_Last := Array_Index (Num-1);
--Inverse_No_Points := 1.0 / (Real (Data_Set_Last) + 1.0);
-- But if Data_Set_Last+1 is not a power of 2, then FFT will pad data set
-- out to the nearest power of two. That is what we must divide by:
Transformed_Data_Length := 2.0**(Integer_Log2(Data_Set_Last) + 1);
Inverse_No_Points := 1.0 / Transformed_Data_Length;
Inverse_No_Points2 := Inverse_No_Points**2;
for I in Array_Index loop
D_Re(I) := 0.0;
D_Im(I) := 0.0;
end loop;
for I in Array_Index range 0..Data_Set_Last loop
Theta := Real (I);
D_Re(I) := 1.0 / (Theta + 1.0);
D_Im(I) := 1.0E-3 * Theta;
end loop;
for I in 1 .. No_of_Repetitions loop
FFT (Data_Re => D_Re,
Data_Im => D_Im,
Transformed_Data_Last => Transformed_Data_Last,
Input_Data_Last => Data_Set_Last,
Exp_Table => Exp_Table,
Inverse_FFT_Desired => False,
Normalized_Data_Desired => False,
Bit_Reversal_Desired => Do_the_Bit_Reversal);
FFT (Data_Re => D_Re,
Data_Im => D_Im,
Transformed_Data_Last => Transformed_Data_Last,
Input_Data_Last => Transformed_Data_Last,
Exp_Table => Exp_Table,
Inverse_FFT_Desired => True,
Normalized_Data_Desired => False,
Bit_Reversal_Desired => Do_the_Bit_Reversal);
FFT (Data_Re => D_Re,
Data_Im => D_Im,
Transformed_Data_Last => Transformed_Data_Last,
Input_Data_Last => Data_Set_Last,
Exp_Table => Exp_Table,
Inverse_FFT_Desired => False,
Normalized_Data_Desired => False,
Bit_Reversal_Desired => Do_the_Bit_Reversal);
FFT (Data_Re => D_Re,
Data_Im => D_Im,
Transformed_Data_Last => Transformed_Data_Last,
Input_Data_Last => Transformed_Data_Last,
Exp_Table => Exp_Table,
Inverse_FFT_Desired => True,
Normalized_Data_Desired => False,
Bit_Reversal_Desired => Do_the_Bit_Reversal);
for J in 0..Transformed_Data_Last loop
D_Re(J) := Inverse_No_Points2 * D_Re(J);
end loop;
for J in 0..Transformed_Data_Last loop
D_Im(J) := Inverse_No_Points2 * D_Im(J);
end loop;
end loop;
Max_Error := 0.0;
for J in 0..Data_Set_Last loop
Theta := Real (J);
D_Old := 1.0 / (Theta + 1.0);
Error := Abs (D_Re(J) - D_Old);
if Max_Error < Error then Max_Error := Error; end if;
D_Old := 1.0E-3 * Theta;
Error := Abs (D_Im(J) - D_Old);
if Max_Error < Error then Max_Error := Error; end if;
end loop;
--Max_Error := 0.0;
if Data_Set_Last < Data_Index'Last then
for J in Data_Set_Last+1 .. Transformed_Data_Last loop
Error := Abs (D_Re(J) - 0.0);
if Max_Error < Error then Max_Error := Error; end if;
Error := Abs (D_Im(J) - 0.0);
if Max_Error < Error then Max_Error := Error; end if;
end loop;
end if;
if Do_the_Bit_Reversal then
put("Maximum error = "); put(Max_Error); put (" ");
new_line;
end if;
end;
|
--Types
package Types is
pragma Elaborate_Body;
type Miles_T is digits 6;
-- Create types for at least two distance measurements (feet, meters, etc)
type Hours_T is digits 6;
-- Create types for at least two time measurements (seconds, minutes, etc)
-- Create "/" operator functions to divide distance by time to return MPH_T
-- Create helper functions to convert distance to miles and time to hours
end Types;
|
-- SPDX-FileCopyrightText: 2019-2021 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
--
-- Common type for Standard and full resolver
with Program.Element_Visitors;
with Program.Elements.Defining_Names;
with Program.Elements.Definitions;
with Program.Elements.Enumeration_Types;
with Program.Elements.Exception_Declarations;
with Program.Elements.Floating_Point_Types;
with Program.Elements.Subtype_Declarations;
with Program.Elements.Type_Declarations;
with Program.Visibility;
with Program.Cross_Reference_Updaters;
package Program.Resolvers.Basic is
pragma Preelaborate;
type Visitor
(Env : not null Program.Visibility.Context_Access;
Setter : not null
Program.Cross_Reference_Updaters.Cross_Reference_Updater_Access)
is new Program.Element_Visitors.Element_Visitor with record
Discriminants : Program.Elements.Definitions.Definition_Access;
Type_Name : Program.Elements.Defining_Names.Defining_Name_Access;
Type_View : Program.Visibility.View;
end record;
procedure Visit_Each_Child
(Self : in out Visitor;
Element : access Program.Elements.Element'Class);
overriding procedure Enumeration_Type
(Self : in out Visitor;
Element : not null Program.Elements.Enumeration_Types
.Enumeration_Type_Access);
overriding procedure Exception_Declaration
(Self : in out Visitor;
Element : not null Program.Elements.Exception_Declarations
.Exception_Declaration_Access);
overriding procedure Floating_Point_Type
(Self : in out Visitor;
Element : not null Program.Elements.Floating_Point_Types
.Floating_Point_Type_Access);
overriding procedure Subtype_Declaration
(Self : in out Visitor;
Element : not null Program.Elements.Subtype_Declarations
.Subtype_Declaration_Access);
overriding procedure Type_Declaration
(Self : in out Visitor;
Element : not null Program.Elements.Type_Declarations
.Type_Declaration_Access);
end Program.Resolvers.Basic;
|
with GESTE;
with GESTE.Tile_Bank;
with GESTE.Sprite.Rotated;
with GESTE_Config; use GESTE_Config;
with GESTE.Maths; use GESTE.Maths;
with GESTE.Physics;
with GESTE.Text;
with GESTE_Fonts.FreeMono6pt7b;
with Game_Assets.track_1;
with Game_Assets.Tileset;
with Interfaces; use Interfaces;
package body Player is
type Player_Type (Bank : not null GESTE.Tile_Bank.Const_Ref;
Init_Frame : GESTE_Config.Tile_Index)
is limited new GESTE.Physics.Object with record
Sprite : aliased GESTE.Sprite.Rotated.Instance (Bank, Init_Frame);
end record;
Tile_Bank : aliased GESTE.Tile_Bank.Instance
(Game_Assets.Tileset.Tiles'Access,
GESTE.No_Collisions,
Game_Assets.Palette'Access);
subtype Stat_Text is GESTE.Text.Instance
(Da_Font => GESTE_Fonts.FreeMono6pt7b.Font,
Number_Of_Columns => 15,
Number_Of_Lines => 1,
Foreground => 1,
Background => GESTE_Config.Transparent);
Next_Gate_Text : aliased Stat_Text;
Lap_Text : aliased Stat_Text;
Best_Text : aliased Stat_Text;
Current_Text : aliased Stat_Text;
Frame_Count : Unsigned_32 := 0;
Start : Game_Assets.Object renames
Game_Assets.track_1.Start.Objects (Game_Assets.track_1.Start.Objects'First);
P : aliased Player_Type (Tile_Bank'Access, 105);
Next_Gate : Natural := Game_Assets.track_1.gates.Objects'First;
Laps_Cnt : Natural := 0;
Best_Lap : Value := 0.0;
Current_Lap : Value := 0.0;
Do_Throttle : Boolean := False;
Do_Brake : Boolean := False;
Going_Left : Boolean := False;
Going_Right : Boolean := False;
function Inside_Gate (Obj : Game_Assets.Object) return Boolean;
-----------------
-- Inside_Gate --
-----------------
function Inside_Gate (Obj : Game_Assets.Object) return Boolean
is (P.Position.X in Obj.X .. Obj.X + Obj.Width
and then
P.Position.Y in Obj.Y .. Obj.Y + Obj.Height);
----------
-- Move --
----------
procedure Move (Pt : GESTE.Pix_Point) is
begin
P.Set_Position ((Value (Pt.X), Value (Pt.Y)));
end Move;
--------------
-- Position --
--------------
function Position return GESTE.Pix_Point
is ((Integer (P.Position.X), Integer (P.Position.Y)));
------------
-- Update --
------------
procedure Update (Elapsed : Value) is
Old : constant Point := P.Position;
Brake_Coef : Value;
Dir : constant Vect := P.Direction;
Traction : constant Vect := Dir * 10_000.0;
C_Drag : constant Value := 0.5 * 0.3 * 2.2 * 1.29;
VX : constant Value := P.Speed.X;
VY : constant Value := P.Speed.Y;
function Drag return Vect;
function Friction return Vect;
----------
-- Drag --
----------
function Drag return Vect is
Speed : constant Value := Magnitude (P.Speed);
begin
return (-(Value (C_Drag * VX) * Speed),
-(Value (C_Drag * VY) * Speed));
end Drag;
--------------
-- Friction --
--------------
function Friction return Vect is
C_TT : Value := 30.0 * C_Drag;
begin
if not GESTE.Collides ((Integer (Old.X), Integer (Old.Y))) then
-- Off track
C_TT := C_TT * 100;
end if;
return (-C_TT * VX, -C_TT * VY);
end Friction;
begin
Frame_Count := Frame_Count + 1;
if Going_Right then
P.Set_Angle (P.Angle - 0.060);
end if;
if Going_Left then
P.Set_Angle (P.Angle + 0.060);
end if;
if Do_Throttle then
P.Apply_Force (Traction);
end if;
if Do_Brake then
Brake_Coef := -120.0;
else
Brake_Coef := -90.0;
end if;
P.Apply_Force ((P.Speed.X * Brake_Coef, P.Speed.Y * Brake_Coef));
P.Apply_Force (Drag);
P.Apply_Force (Friction);
P.Step (Elapsed);
P.Set_Angle (P.Angle);
P.Sprite.Move ((Integer (P.Position.X) - 8,
Integer (P.Position.Y) - 8));
P.Sprite.Angle (P.Angle);
if Frame_Count mod 10 = 0 then
-- Update the current time every 10 frames
Current_Text.Clear;
Current_Text.Cursor (1, 1);
Current_Text.Put (Current_Lap'Img);
end if;
Current_Lap := Current_Lap + Elapsed;
if Inside_Gate (Game_Assets.track_1.gates.Objects (Next_Gate)) then
if Next_Gate = Game_Assets.track_1.gates.Objects'Last then
Next_Gate := Game_Assets.track_1.gates.Objects'First;
Laps_Cnt := Laps_Cnt + 1;
Lap_Text.Clear;
Lap_Text.Cursor (1, 1);
Lap_Text.Put ("Lap:" & Laps_Cnt'Img);
if Best_Lap = 0.0 or else Current_Lap < Best_Lap then
Best_Lap := Current_Lap;
Best_Text.Clear;
Best_Text.Cursor (1, 1);
Best_Text.Put ("Best:" & Best_Lap'Img);
end if;
Current_Lap := 0.0;
else
Next_Gate := Next_Gate + 1;
end if;
Next_Gate_Text.Clear;
Next_Gate_Text.Cursor (1, 1);
Next_Gate_Text.Put ("Next Gate:" & Next_Gate'Img);
end if;
Do_Throttle := False;
Do_Brake := False;
Going_Left := False;
Going_Right := False;
end Update;
--------------
-- Throttle --
--------------
procedure Throttle is
begin
Do_Throttle := True;
end Throttle;
-----------
-- Brake --
-----------
procedure Brake is
begin
Do_Brake := True;
end Brake;
---------------
-- Move_Left --
---------------
procedure Move_Left is
begin
Going_Left := True;
end Move_Left;
----------------
-- Move_Right --
----------------
procedure Move_Right is
begin
Going_Right := True;
end Move_Right;
begin
P.Set_Position ((Value (Start.X), Value (Start.Y)));
P.Set_Angle (Pi);
P.Set_Mass (90.0);
GESTE.Add (P.Sprite'Access, 3);
Next_Gate_Text.Move ((220, 0));
Next_Gate_Text.Put ("Next Gate: 0");
GESTE.Add (Next_Gate_Text'Access, 4);
Lap_Text.Move ((220, 10));
Lap_Text.Put ("Lap: 0");
GESTE.Add (Lap_Text'Access, 5);
Best_Text.Move ((220, 20));
Best_Text.Put ("Best: 0.0");
GESTE.Add (Best_Text'Access, 6);
Current_Text.Move ((260, 30));
GESTE.Add (Current_Text'Access, 7);
end Player;
|
with VisitablePackage, ObjectPack;
use VisitablePackage, ObjectPack;
package body VisitableBuiltinPackage is
function makeVisitableBuiltinPackage(o: ObjectPtr) return VisitableBuiltin is
ret : VisitableBuiltin;
begin
ret.builtin := o;
return ret;
end;
function getBuiltin(v: VisitableBuiltin) return ObjectPtr is
begin
return v.builtin;
end;
function setChildren(v: access VisitableBuiltin ; children : ObjectPtrArrayPtr) return VisitablePtr is
IndexOutOfBoundsException : exception;
begin
if children /= null then
raise IndexOutOfBoundsException;
end if;
return VisitablePtr(v);
end;
function getChildren(v: access VisitableBuiltin) return ObjectPtrArrayPtr is
ret : ObjectPtrArrayPtr := new ObjectPtrArray(0..0);
begin
ret(0) := new VisitableBuiltin;
return ret;
end;
function getChildAt(v: access VisitableBuiltin; i : Integer) return VisitablePtr is
error : exception;
begin
raise Error;
return null;
end;
function setChildAt(v: access VisitableBuiltin; i: in Integer; child: in VisitablePtr) return VisitablePtr is
error : exception;
begin
raise Error;
return VisitablePtr(v);
end;
function getChildCount(v: access VisitableBuiltin) return Integer is
begin
return 0;
end;
function toString(vb: VisitableBuiltin) return String is
begin
return toString(vb.builtin.all);
end;
end VisitableBuiltinPackage;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- ADA.STRINGS.TEXT_OUTPUT.UTILS --
-- --
-- B o d y --
-- --
-- Copyright (C) 2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
package body Ada.Strings.Text_Output.Utils is
procedure Put_Octet (S : in out Sink'Class; Item : Character) with Inline;
-- Send a single octet to the current Chunk
procedure Adjust_Column (S : in out Sink'Class) with Inline;
-- Adjust the column for a non-NL character.
procedure Put_UTF_8_Outline (S : in out Sink'Class; Item : UTF_8);
-- Out-of-line portion of Put_UTF_8. This exists solely to make Put_UTF_8
-- small enough to reasonably inline it.
procedure Full (S : in out Sink'Class) is
begin
pragma Assert (S.Last = S.Chunk_Length);
Full_Method (S);
pragma Assert (S.Last = 0);
end Full;
procedure Flush (S : in out Sink'Class) is
begin
Flush_Method (S);
end Flush;
procedure Put_Octet (S : in out Sink'Class; Item : Character) is
begin
S.Last := @ + 1;
S.Cur_Chunk.Chars (S.Last) := Item;
pragma Assert (S.Chunk_Length = S.Cur_Chunk.Chars'Length);
if S.Last = S.Chunk_Length then
Full (S);
end if;
end Put_Octet;
procedure Adjust_Column (S : in out Sink'Class) is
begin
-- If we're in the first column, indent. This is handled here, rather
-- than when we see NL, because we don't want spaces in a blank line.
-- The character we're about to put is not NL; NL is handled in
-- New_Line. So after indenting, we simply increment the Column.
if S.Column = 1 then
Tab_To_Column (S, S.Indentation + 1);
end if;
S.Column := @ + 1;
end Adjust_Column;
procedure Put_7bit (S : in out Sink'Class; Item : Character_7) is
begin
Adjust_Column (S);
Put_Octet (S, Item);
end Put_7bit;
procedure Put_7bit_NL (S : in out Sink'Class; Item : Character_7) is
begin
if Item = NL then
New_Line (S);
else
Put_7bit (S, Item);
end if;
end Put_7bit_NL;
procedure Put_Character (S : in out Sink'Class; Item : Character) is
begin
if Character'Pos (Item) < 2**7 then
Put_7bit_NL (S, Item);
else
Put_Wide_Wide_Character (S, To_Wide_Wide (Item));
end if;
end Put_Character;
procedure Put_Wide_Character
(S : in out Sink'Class; Item : Wide_Character) is
begin
if Wide_Character'Pos (Item) < 2**7 then
Put_7bit_NL (S, From_Wide (Item));
else
Put_Wide_Wide_Character (S, To_Wide_Wide (Item));
end if;
end Put_Wide_Character;
procedure Put_Wide_Wide_Character
(S : in out Sink'Class; Item : Wide_Wide_Character) is
begin
if Wide_Wide_Character'Pos (Item) < 2**7 then
Put_7bit_NL (S, From_Wide_Wide (Item));
else
S.All_7_Bits := False;
if Wide_Wide_Character'Pos (Item) >= 2**8 then
S.All_8_Bits := False;
end if;
declare
Temp : constant UTF_8_Lines :=
UTF_Encoding.Wide_Wide_Strings.Encode ((1 => Item));
begin
for X of Temp loop
pragma Assert (X /= NL);
Adjust_Column (S);
Put_Octet (S, X);
end loop;
end;
end if;
end Put_Wide_Wide_Character;
procedure Put_UTF_8_Outline (S : in out Sink'Class; Item : UTF_8) is
begin
if S.Last + Item'Length = S.Chunk_Length then
-- Item fits exactly in current chunk
S.Cur_Chunk.Chars (S.Last + 1 .. S.Last + Item'Length) := Item;
S.Last := S.Last + Item'Length;
S.Column := S.Column + Item'Length;
Full (S);
-- ???Seems like maybe we shouldn't call Full until we have MORE
-- characters. But then we can't pass Chunk_Length => 1 to
-- Create_File to get unbuffered output.
else
-- We get here only if Item doesn't fit in the current chunk, which
-- should be fairly rare. We split Item into Left and Right, where
-- Left exactly fills the current chunk, and recurse on Left and
-- Right. Right will fit into the next chunk unless it's very long,
-- so another level of recursion will be extremely rare.
declare
Left_Length : constant Natural := S.Chunk_Length - S.Last;
Right_First : constant Natural := Item'First + Left_Length;
Left : UTF_8 renames Item (Item'First .. Right_First - 1);
Right : UTF_8 renames Item (Right_First .. Item'Last);
pragma Assert (Left & Right = Item);
begin
Put_UTF_8 (S, Left); -- This will call Full.
Put_UTF_8 (S, Right); -- This might call Full, but probably not.
end;
end if;
end Put_UTF_8_Outline;
procedure Put_UTF_8 (S : in out Sink'Class; Item : UTF_8) is
begin
Adjust_Column (S);
if S.Last + Item'Length < S.Chunk_Length then
-- Item fits in current chunk
S.Cur_Chunk.Chars (S.Last + 1 .. S.Last + Item'Length) := Item;
S.Last := S.Last + Item'Length;
S.Column := S.Column + Item'Length;
else
Put_UTF_8_Outline (S, Item);
end if;
end Put_UTF_8;
procedure Put_UTF_8_Lines (S : in out Sink'Class; Item : UTF_8_Lines) is
Line_Start, Index : Integer := Item'First;
-- Needs to be Integer, because Item'First might be negative for empty
-- Items.
begin
while Index <= Item'Last loop
if Item (Index) = NL then
if Index > Line_Start then
Put_UTF_8 (S, Item (Line_Start .. Index - 1));
end if;
New_Line (S);
Line_Start := Index + 1;
end if;
Index := @ + 1;
end loop;
if Index > Line_Start then
Put_UTF_8 (S, Item (Line_Start .. Index - 1));
end if;
end Put_UTF_8_Lines;
procedure Put_String (S : in out Sink'Class; Item : String) is
begin
for X of Item loop
Put_Character (S, X);
end loop;
end Put_String;
procedure Put_Wide_String (S : in out Sink'Class; Item : Wide_String) is
begin
for X of Item loop
Put_Wide_Character (S, X);
end loop;
end Put_Wide_String;
procedure Put_Wide_Wide_String
(S : in out Sink'Class; Item : Wide_Wide_String) is
begin
for X of Item loop
Put_Wide_Wide_Character (S, X);
end loop;
end Put_Wide_Wide_String;
procedure New_Line (S : in out Sink'Class) is
begin
S.Column := 1;
Put_Octet (S, NL);
end New_Line;
function Column (S : Sink'Class) return Positive is (S.Column);
procedure Tab_To_Column (S : in out Sink'Class; Column : Positive) is
begin
if S.Column < Column then
for X in 1 .. Column - S.Column loop
Put_Octet (S, ' ');
end loop;
S.Column := Column;
end if;
end Tab_To_Column;
procedure Set_Indentation (S : in out Sink'Class; Amount : Natural) is
begin
S.Indentation := Amount;
end Set_Indentation;
function Indentation (S : Sink'Class) return Natural is (S.Indentation);
procedure Indent
(S : in out Sink'Class; Amount : Optional_Indentation := Default)
is
By : constant Natural :=
(if Amount = Default then S.Indent_Amount else Amount);
begin
Set_Indentation (S, Indentation (S) + By);
end Indent;
procedure Outdent
(S : in out Sink'Class; Amount : Optional_Indentation := Default)
is
By : constant Natural :=
(if Amount = Default then S.Indent_Amount else Amount);
begin
Set_Indentation (S, Indentation (S) - By);
end Outdent;
end Ada.Strings.Text_Output.Utils;
|
package body AdaM.program_Unit
is
procedure dummy is begin null; end dummy;
end AdaM.program_Unit;
|
with Ada.Interrupts;
with STM32.CAN;
with System;
package ACO.Drivers.Stm32f40x is
use STM32.CAN;
type CAN_Driver
(Device : not null access CAN_Controller)
is new Driver with private;
overriding
procedure Receive_Message_Blocking
(This : in out CAN_Driver;
Msg : out ACO.Messages.Message);
overriding
procedure Send_Message
(This : in out CAN_Driver;
Msg : in ACO.Messages.Message);
overriding
procedure Initialize
(This : in out CAN_Driver);
overriding
procedure Finalize
(This : in out CAN_Driver) is null;
overriding
function Is_Message_Pending
(This : CAN_Driver)
return Boolean;
overriding
function Current_Time
(This : CAN_Driver)
return Ada.Real_Time.Time;
package CAN_ISR is
function Tx_Interrupt_Id (Device : not null access CAN_Controller)
return Ada.Interrupts.Interrupt_ID;
function Rx0_Interrupt_Id (Device : not null access CAN_Controller)
return Ada.Interrupts.Interrupt_ID;
function Rx1_Interrupt_Id (Device : not null access CAN_Controller)
return Ada.Interrupts.Interrupt_ID;
function SCE_Interrupt_Id (Device : not null access CAN_Controller)
return Ada.Interrupts.Interrupt_ID;
subtype Index is Natural range 0 .. 7;
type Msg_Array is array (Index'Range) of CAN_Message;
type Message_Buffer is record
Buffer : Msg_Array;
Idx_New : Index := 0;
Idx_Old : Index := 0;
end record;
protected type Controller (Device : not null access CAN_Controller) is
pragma Interrupt_Priority (System.Interrupt_Priority'Last);
procedure Transmit_Message
(Message : in CAN_Message;
Success : out Boolean);
entry Receive_Message
(Message : out CAN_Message);
procedure Enable_Receiver
(Fifo : in Fifo_Nr);
function Is_Message_Pending
return Boolean;
private
Tx_Buffer : Message_Buffer;
Rx_Buffer : Message_Buffer;
Is_Rx_Pending : Boolean := False;
procedure Send;
procedure IRQ_Handler;
pragma Attach_Handler (IRQ_Handler, Tx_Interrupt_Id (Device));
pragma Attach_Handler (IRQ_Handler, Rx0_Interrupt_Id (Device));
pragma Attach_Handler (IRQ_Handler, Rx1_Interrupt_Id (Device));
pragma Attach_Handler (IRQ_Handler, SCE_Interrupt_Id (Device));
end Controller;
private
Max_Nof_Messages : constant Natural := Index'Last;
function Nof_Messages (This : Message_Buffer) return Natural;
procedure Get_Next_Message
(This : in out Message_Buffer;
Message : out CAN_Message)
with Pre => Nof_Messages (This) > 0;
procedure Put_Message
(This : in out Message_Buffer;
Message : in CAN_Message)
with Pre => Nof_Messages (This) < Max_Nof_Messages;
end CAN_ISR;
private
type CAN_Driver
(Device : not null access CAN_Controller)
is new Driver with record
Controller : CAN_ISR.Controller (Device);
end record;
function Convert (D : STM32.CAN.Message_Data)
return ACO.Messages.Data_Array
with Inline;
function Convert (D : ACO.Messages.Data_Array)
return STM32.CAN.Message_Data
with Inline;
end ACO.Drivers.Stm32f40x;
|
with Basic_Test_Window; use Basic_Test_Window;
with Giza.Widget.Keyboards;
package Test_Keyboard_Window is
type Keyboard_Window is new Test_Window with private;
type Keyboard_Window_Ref is access all Keyboard_Window;
overriding
procedure On_Init (This : in out Keyboard_Window);
overriding
procedure On_Displayed (This : in out Keyboard_Window) is null;
overriding
procedure On_Hidden (This : in out Keyboard_Window) is null;
private
type Keyboard_Window is new Test_Window with record
Keyboard : aliased Giza.Widget.Keyboards.Instance;
end record;
end Test_Keyboard_Window;
|
with Irc.Bot;
with Irc.Commands;
with Irc.Message;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Terminal_Interface.Curses; use Terminal_Interface.Curses;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Texaco;
with GNAT.Sockets;
package Pong_Bot is
Bot : Irc.Bot.Connection;
procedure Irc_Client;
end Pong_Bot;
|
-------------------------------------------------------------------------------
-- Copyright 2021, The Septum Developers (see AUTHORS file)
-- 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 Trendy_Terminal.Platform;
with Trendy_Terminal.Maps;
package body SP.Terminal is
function Colorize (S : String; Color : ANSI.Colors) return String is
begin
return ANSI.Foreground (Color)
& S
& ANSI.Foreground (ANSI.Default);
end Colorize;
function Colorize (US : Ada.Strings.Unbounded.Unbounded_String; Color : ANSI.Colors)
return Ada.Strings.Unbounded.Unbounded_String
is
use all type Ada.Strings.Unbounded.Unbounded_String;
begin
return ANSI.Foreground (Color)
& US
& ANSI.Foreground (ANSI.Default);
end Colorize;
protected body Cancellation_Gate is
entry Closed when Finished is
begin
null;
end Closed;
procedure Cancel is
begin
Cancelled := True;
end Cancel;
function Is_Cancelled return Boolean is
begin
return Cancelled;
end Is_Cancelled;
procedure Finish is
begin
Finished := True;
end Finish;
function Is_Finished return Boolean is
begin
return Finished;
end Is_Finished;
end Cancellation_Gate;
task body Terminal_Cancellation_Monitor is
task Input_Thread is end;
task body Input_Thread is
use all type Trendy_Terminal.Maps.Key;
begin
loop
declare
Input : constant String := Trendy_Terminal.Platform.Get_Input;
begin
if Trendy_Terminal.Maps.Key_For (Input) = Trendy_Terminal.Maps.Key_Ctrl_C then
select
Cancel;
exit;
else
null;
end select;
elsif Trendy_Terminal.Maps.Key_For (Input) = Trendy_Terminal.Maps.Key_Ctrl_D then
exit;
else
null;
end if;
end;
end loop;
end Input_Thread;
Done : Boolean := False;
begin
loop
select
accept Cancel do
Done := True;
Gate.Cancel;
end;
or
accept Stop do
Done := True;
end;
or
terminate;
end select;
exit when Done;
end loop;
abort Input_Thread;
end Terminal_Cancellation_Monitor;
end SP.Terminal; |
with Entities; use Entities;
with Worlds; use Worlds;
with Vectors2D; use Vectors2D;
with HAL.Bitmap; use HAL.Bitmap;
with Materials; use Materials;
with DemoLogic; use DemoLogic;
with Links; use Links;
package Renderer is
-- Displays the entities passed
procedure Render(W : in out World; Cue : VisualCue);
procedure RenderList(L : EntsListAcc; Selected : EntityClassAcc := null);
procedure RenderCue(Cue : VisualCue);
procedure RenderLinksList(L : LinksListAcc);
-- Failsafe translation to int Coords
function GetIntCoords(flCoords : Vec2D) return Point
with Post => GetIntCoords'Result.X <= 240 and GetIntCoords'Result.Y <= 320;
function GetBezierPoint(Link : LinkAcc; i : Natural; n : Positive; UseMul : Float := 0.0) return Point;
-- Gets the color appropriate for the material
function GetColor(Mat : in Material) return Bitmap_Color;
-- Gets the color for the link
function GetLinkColor(L : LinkAcc) return Bitmap_Color;
function GetCenteredPos(E : EntityClassAcc) return Point;
-- Tells if an entity is invalid
function InvalidEnt(E : EntityClassAcc) return Boolean;
procedure DrawRope(Link : LinkAcc);
procedure DrawSpring(Link : LinkAcc);
end Renderer;
|
with External; use External;
with Node; use Node;
with Logger;
with RandInt;
with Sender; use Sender;
with Receiver; use Receiver;
with EdgeRegistry; use EdgeRegistry;
with Plunderer; use Plunderer;
procedure Main is
package EDG renames EdgeRegistry;
n: Natural;
d: Natural;
b: Natural;
k: Natural;
h: Natural;
maxSleep: Natural;
plundererIntervals: Natural := 0;
begin
if CMD.Argument_Count < 6 then
PrintBounded("six arguments necessary");
return;
end if;
n := Natural'Value(CMD.Argument(1));
d := Natural'Value(CMD.Argument(2));
b := Natural'Value(CMD.Argument(3));
k := Natural'Value(CMD.Argument(4));
h := Natural'Value(CMD.Argument(5));
maxSleep := Natural'Value(CMD.Argument(6));
if CMD.Argument_Count > 6 then
plundererIntervals := Natural'Value(CMD.Argument(7));
end if;
-- first step of getting to the first node is free
h := Natural'Succ(h);
declare
subtype RangeN is Natural range 1..n;
subtype RangeD is Natural range 1..d;
subtype RangeB is Natural range 1..b;
subtype RangeK is Natural range 1..k;
nodes: pArray_pNodeObj;
package RAD renames RandInt;
type AdditionalEdges is array (Natural range <>, Natural range <>) of Natural;
type pAdditionalEdges is access AdditionalEdges;
shortcuts: pAdditionalEdges;
shortcutsEdgeRegistry: EDG.HashMap;
detours: pAdditionalEdges;
detoursEdgeRegistry: EDG.HashMap;
type AdditionalEdgesArrayLengths is array (RangeN) of Natural;
type pAdditionalEdgesArrayLengths is access AdditionalEdgesArrayLengths;
neighboursLengths: pAdditionalEdgesArrayLengths;
package LOG renames Logger;
logger: LOG.pLoggerReceiver;
tmp: Natural := 0;
tmp2: Natural := 0;
tmp3: Natural := 0;
iter: Natural := 0;
tmpExit: Boolean := False;
tmpNodeObj: pNodeObj;
tmpNodeObj2: pNodeObj;
sender: pSenderTask;
receiver: pReceiverTask;
plunderer: pPlundererTask;
reapers: pArray_pNodeTaskGrimReaper;
begin
-- instantiate the logger task
logger := new LOG.LoggerReceiver(n, d, k);
-- create all nodes
nodes := new Array_pNodeObj(RangeN);
for I in RangeN'Range loop
nodes.all(I) := new NodeObj;
nodes.all(I).all.id := Natural'Pred(I);
end loop;
-- generate shortcuts
logger.Log("shortcuts:");
shortcuts := new AdditionalEdges(RangeD, 1..2);
iter := 1;
while iter <= d loop
tmp := RAD.Next(n);
tmp2 := RAD.Next(n);
if tmp > tmp2 then
tmp3 := tmp;
tmp := tmp2;
tmp2 := tmp3;
end if;
if tmp /= tmp2 and not EDG.Exists(shortcutsEdgeRegistry, tmp, tmp2) then
-- indexes are not equal, and the potential edge is
-- not a duplicate of a one already existing
shortcuts(iter, 1) := tmp;
shortcuts(iter, 2) := tmp2;
logger.Log(Natural'Image(tmp-1) & " →" & Natural'Image(tmp2-1));
-- save the edge in the registry to avoid duplicates
EDG.Register(shortcutsEdgeRegistry, tmp, tmp2);
iter := Natural'Succ(iter); -- succulent
end if;
end loop;
logger.Log("");
-- generate detours
logger.Log("detours:");
detours := new AdditionalEdges(RangeB, 1..2);
iter := 1;
while iter <= b loop
tmp := RAD.Next(n);
tmp2 := RAD.Next(n);
if tmp < tmp2 then
tmp3 := tmp;
tmp := tmp2;
tmp2 := tmp3;
end if;
if tmp /= tmp2 and not EDG.Exists(detoursEdgeRegistry, tmp, tmp2) then
-- indexes are not equal, and the potential edge is
-- not a duplicate of a one already existing
detours(iter, 1) := tmp;
detours(iter, 2) := tmp2;
logger.Log(Natural'Image(tmp-1) & " →" & Natural'Image(tmp2-1));
-- save the edge in the registry to avoid duplicates
EDG.Register(detoursEdgeRegistry, tmp, tmp2);
iter := Natural'Succ(iter); -- succulent
end if;
end loop;
logger.Log("");
-- we need to precalculate the neighbours’ array size
neighboursLengths := new AdditionalEdgesArrayLengths;
-- initialize with `1`, because each node has at least one neighbour
for I in RangeN'Range loop
neighboursLengths.all(I) := 1;
end loop;
neighboursLengths.all(RangeN'Last) := 0;
-- count all the additional edges
for I in RangeD'Range loop
-- get the beginning node
tmp := shortcuts(I, 1);
if tmp > 0 and tmp <= n then
neighboursLengths.all(tmp) := neighboursLengths.all(tmp) + 1;
end if;
end loop;
for I in RangeB'Range loop
-- get the beginning node
tmp := detours(I, 1);
if tmp > 0 and tmp <= n then
neighboursLengths.all(tmp) := neighboursLengths.all(tmp) + 1;
end if;
end loop;
-- setup the receiver
receiver := new ReceiverTask(k);
-- now we can initialize our nodes
for I in RangeN'Range loop
tmpNodeObj := nodes.all(I);
tmpNodeObj.all.neighbours := new Array_pNodeObj(1..neighboursLengths.all(I));
if I < n then
tmpNodeObj.all.nodeTask := new NodeTask(tmpNodeObj, maxSleep, logger, False, receiver);
else
tmpNodeObj.all.nodeTask := new NodeTask(tmpNodeObj, maxSleep, logger, True, receiver);
end if;
tmpNodeObj.all.nodeStash := new NodeStash(tmpNodeObj);
end loop;
-- and add pointers to neighbours (shortcuts)
for I in RangeD'Range loop
-- get the beginning node of the edge
tmp := shortcuts.all(I, 1);
if tmp /= 0 then
tmpNodeObj := nodes.all(tmp);
-- get the ending node of the edge
tmp2 := shortcuts.all(I, 2);
tmpNodeObj2 := nodes.all(tmp2);
-- add the neighbour (we’re using the lengths array as our pointer)
tmpNodeObj.all.neighbours(neighboursLengths.all(tmp)) := tmpNodeObj2;
-- decrease the array pointer
neighboursLengths.all(tmp) := neighboursLengths.all(tmp) - 1;
end if;
end loop;
-- and add pointers to neighbours (detours)
for I in RangeB'Range loop
-- get the beginning node of the edge
tmp := detours.all(I, 1);
if tmp /= 0 then
tmpNodeObj := nodes.all(tmp);
-- get the ending node of the edge
tmp2 := detours.all(I, 2);
tmpNodeObj2 := nodes.all(tmp2);
-- add the neighbour (we’re using the lengths array as our pointer)
tmpNodeObj.all.neighbours(neighboursLengths.all(tmp)) := tmpNodeObj2;
-- decrease the array pointer
neighboursLengths.all(tmp) := neighboursLengths.all(tmp) - 1;
end if;
end loop;
-- also add the edges for adjacent nodes
for I in RangeN'Range loop
-- current node
tmpNodeObj := nodes(I);
if I < n then
-- next node
tmpNodeObj2 := nodes(I+1);
-- add as neighbour
tmpNodeObj.all.neighbours(1) := tmpNodeObj2;
else
-- special case for the last node
null;
end if;
end loop;
if plundererIntervals /= 0 then
-- setup the plunderer
logger.Log("plunderer active");
logger.Log("");
plunderer := new PlundererTask(nodes, maxSleep, plundererIntervals);
end if;
-- send the messages
tmpNodeObj2 := nodes(RangeN'First);
sender := new SenderTask(tmpNodeObj2, k, h);
-- wait for the receiver
receiver.all.Ended;
-- employ a squadron of grim reapers that kill all node tasks
reapers := new Array_pNodeTaskGrimReaper(RangeN);
for I in RangeN'Range loop
reapers(I) := new NodeTaskGrimReaper(nodes(I));
end loop;
logger.Stop;
end;
end Main;
|
-- Copyright (c) 1990 Regents of the University of California.
-- All rights reserved.
--
-- This software was developed by John Self of the Arcadia project
-- at the University of California, Irvine.
--
-- Redistribution and use in source and binary forms are permitted
-- provided that the above copyright notice and this paragraph are
-- duplicated in all such forms and that any documentation,
-- advertising materials, and other materials related to such
-- distribution and use acknowledge that the software was developed
-- by the University of California, Irvine. The name of the
-- University may not be used to endorse or promote products derived
-- from this software without specific prior written permission.
-- THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
-- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
-- WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
-- TITLE skeleton manager
-- AUTHOR: John Self (UCI)
-- DESCRIPTION outputs skeleton sections when called by gen.
-- NOTES allows use of internal or external skeleton
-- $Header: /dc/uc/self/arcadia/aflex/ada/src/alsys_dos/RCS/skelb.ada,v 1.3 1993/06/01 19:16:36 self Exp $
with MISC_DEFS, TEXT_IO, FILE_STRING;
package body SKELETON_MANAGER is
use FILE_STRING; -- to save having to type FILE_STRING 177 times
USE_EXTERNAL_SKELETON : BOOLEAN := FALSE;
-- are we using an external skelfile?
CURRENT_LINE : INTEGER := 1;
type FILE_ARRAY is array(POSITIVE range <>) of FILE_STRING.VSTRING;
SKEL_TEMPLATE : constant FILE_ARRAY := (
-- START OF SKELETON
-- START OF S1
VSTR("-- A lexical scanner generated by aflex"),
VSTR("with text_io; use text_io;"),
VSTR("%% user's code up to the double pound goes right here"),
-- BEGIN S2
VSTR("function YYLex return Token is"),
VSTR("subtype short is integer range -32768..32767;"),
VSTR(" yy_act : integer;"),
VSTR(" yy_c : short;"),
VSTR(""),
VSTR("-- returned upon end-of-file"),
VSTR("YY_END_TOK : constant integer := 0;"),
VSTR("%% tables get generated here."),
-- BEGIN S3
VSTR(""),
VSTR("-- copy whatever the last rule matched to the standard output"),
VSTR(""),
VSTR("procedure ECHO is"),
VSTR(" --% The following body changed by Sriram for porting to DOS/ALSYS."),
VSTR(" --% Occurrences of ASCII.LF is to be treated as new_line. See ASCAN.L"),
VSTR(" --% for old code."),
VSTR("begin"),
VSTR(" if (text_io.is_open(user_output_file)) then"),
VSTR(" for yyindex in yytext'range loop"),
VSTR(" if yytext(yyindex) = ascii.lf then"),
VSTR(" text_io.new_line(user_output_file);"),
VSTR(" else"),
VSTR(" text_io.put(user_output_file, yytext(yyindex));"),
VSTR(" end if;"),
VSTR(" end loop;"),
VSTR(" else"),
VSTR(" for yyindex in yytext'range loop"),
VSTR(" if yytext(yyindex) = ascii.lf then"),
VSTR(" text_io.new_line;"),
VSTR(" else"),
VSTR(" text_io.put(yytext(yyindex));"),
VSTR(" end if;"),
VSTR(" end loop;"),
VSTR(" end if;"),
VSTR("end ECHO;"),
VSTR(""),
VSTR("-- enter a start condition."),
VSTR("-- Using procedure requires a () after the ENTER, but makes everything"),
VSTR("-- much neater."),
VSTR(""),
VSTR("procedure ENTER( state : integer ) is"),
VSTR("begin"),
VSTR(" yy_start := 1 + 2 * state;"),
VSTR("end ENTER;"),
VSTR(""),
VSTR("-- action number for EOF rule of a given start state"),
VSTR("function YY_STATE_EOF(state : integer) return integer is"),
VSTR("begin"),
VSTR(" return YY_END_OF_BUFFER + state + 1;"),
VSTR("end YY_STATE_EOF;"),
VSTR(""),
VSTR("-- return all but the first 'n' matched characters back to the input stream"),
VSTR("procedure yyless(n : integer) is"),
VSTR("begin"),
VSTR(" yy_ch_buf(yy_cp) := yy_hold_char; -- undo effects of setting up yytext"),
VSTR(" yy_cp := yy_bp + n;"),
VSTR(" yy_c_buf_p := yy_cp;"),
VSTR(" YY_DO_BEFORE_ACTION; -- set up yytext again"),
VSTR("end yyless;"),
VSTR(""),
VSTR("-- redefine this if you have something you want each time."),
VSTR("procedure YY_USER_ACTION is"),
VSTR("begin"),
VSTR(" null;"),
VSTR("end;"),
VSTR(""),
VSTR("-- yy_get_previous_state - get the state just before the EOB char was reached"),
VSTR(""),
VSTR("function yy_get_previous_state return yy_state_type is"),
VSTR(" yy_current_state : yy_state_type;"),
VSTR(" yy_c : short;"),
VSTR("%% a local declaration of yy_bp goes here if bol_needed"),
VSTR("begin"),
VSTR("%% code to get the start state into yy_current_state goes here"),
-- BEGIN S3A
VSTR(""),
VSTR(" for yy_cp in yytext_ptr..yy_c_buf_p - 1 loop"),
VSTR("%% code to find the next state goes here"),
-- BEGIN S4
VSTR(" end loop;"),
VSTR(""),
VSTR(" return yy_current_state;"),
VSTR("end yy_get_previous_state;"),
VSTR(""),
VSTR("procedure yyrestart( input_file : file_type ) is"),
VSTR("begin"),
VSTR(" open_input(text_io.name(input_file));"),
VSTR("end yyrestart;"),
VSTR(""),
VSTR("begin -- of YYLex"),
VSTR("<<new_file>>"),
VSTR(" -- this is where we enter upon encountering an end-of-file and"),
VSTR(" -- yywrap() indicating that we should continue processing"),
VSTR(""),
VSTR(" if ( yy_init ) then"),
VSTR(" if ( yy_start = 0 ) then"),
VSTR(" yy_start := 1; -- first start state"),
VSTR(" end if;"),
VSTR(""),
VSTR(" -- we put in the '\n' and start reading from [1] so that an"),
VSTR(" -- initial match-at-newline will be true."),
VSTR(""),
VSTR(" yy_ch_buf(0) := ASCII.LF;"),
VSTR(" yy_n_chars := 1;"),
VSTR(""),
VSTR(" -- we always need two end-of-buffer characters. The first causes"),
VSTR(" -- a transition to the end-of-buffer state. The second causes"),
VSTR(" -- a jam in that state."),
VSTR(""),
VSTR(" yy_ch_buf(yy_n_chars) := YY_END_OF_BUFFER_CHAR;"),
VSTR(" yy_ch_buf(yy_n_chars + 1) := YY_END_OF_BUFFER_CHAR;"),
VSTR(""),
VSTR(" yy_eof_has_been_seen := false;"),
VSTR(""),
VSTR(" yytext_ptr := 1;"),
VSTR(" yy_c_buf_p := yytext_ptr;"),
VSTR(" yy_hold_char := yy_ch_buf(yy_c_buf_p);"),
VSTR(" yy_init := false;"),
VSTR("-- UMASS CODES :"),
VSTR("-- Initialization"),
VSTR(" tok_begin_line := 1;"),
VSTR(" tok_end_line := 1;"),
VSTR(" tok_begin_col := 0;"),
VSTR(" tok_end_col := 0;"),
VSTR(" token_at_end_of_line := false;"),
VSTR(" line_number_of_saved_tok_line1 := 0;"),
VSTR(" line_number_of_saved_tok_line2 := 0;"),
VSTR("-- END OF UMASS CODES."),
VSTR(" end if; -- yy_init"),
VSTR(""),
VSTR(" loop -- loops until end-of-file is reached"),
VSTR(""),
VSTR("-- UMASS CODES :"),
VSTR("-- if last matched token is end_of_line, we must"),
VSTR("-- update the token_end_line and reset tok_end_col."),
VSTR(" if Token_At_End_Of_Line then"),
VSTR(" Tok_End_Line := Tok_End_Line + 1;"),
VSTR(" Tok_End_Col := 0;"),
VSTR(" Token_At_End_Of_Line := False;"),
VSTR(" end if;"),
VSTR("-- END OF UMASS CODES."),
VSTR(""),
VSTR(" yy_cp := yy_c_buf_p;"),
VSTR(""),
VSTR(" -- support of yytext"),
VSTR(" yy_ch_buf(yy_cp) := yy_hold_char;"),
VSTR(""),
VSTR(" -- yy_bp points to the position in yy_ch_buf of the start of the"),
VSTR(" -- current run."),
VSTR("%%"),
-- BEGIN S5
VSTR(""),
VSTR("<<next_action>>"),
VSTR("%% call to gen_find_action goes here"),
-- BEGIN S6
VSTR(" YY_DO_BEFORE_ACTION;"),
VSTR(" YY_USER_ACTION;"),
VSTR(""),
VSTR(" if aflex_debug then -- output acceptance info. for (-d) debug mode"),
VSTR(" text_io.put( Standard_Output, ""--accepting rule #"" );"),
VSTR(" text_io.put( Standard_Output, INTEGER'IMAGE(yy_act) );"),
VSTR(" text_io.put_line( Standard_Output, ""("""""" & yytext & """""")"");"),
VSTR(" end if;"),
VSTR(""),
VSTR("-- UMASS CODES :"),
VSTR("-- Update tok_begin_line, tok_end_line, tok_begin_col and tok_end_col"),
VSTR("-- after matching the token."),
VSTR(" if yy_act /= YY_END_OF_BUFFER and then yy_act /= 0 then"),
VSTR("-- Token are matched only when yy_act is not yy_end_of_buffer or 0."),
VSTR(" Tok_Begin_Line := Tok_End_Line;"),
VSTR(" Tok_Begin_Col := Tok_End_Col + 1;"),
VSTR(" Tok_End_Col := Tok_Begin_Col + yy_cp - yy_bp - 1;"),
VSTR(" if yy_ch_buf ( yy_bp ) = ASCII.LF then"),
VSTR(" Token_At_End_Of_Line := True;"),
VSTR(" end if;"),
VSTR(" end if;"),
VSTR("-- END OF UMASS CODES."),
VSTR(""),
VSTR("<<do_action>> -- this label is used only to access EOF actions"),
VSTR(" case yy_act is"), VSTR("%% actions go here"),
-- BEGIN S7
VSTR(" when YY_END_OF_BUFFER =>"),
VSTR(" -- undo the effects of YY_DO_BEFORE_ACTION"),
VSTR(" yy_ch_buf(yy_cp) := yy_hold_char;"),
VSTR(""),
VSTR(" yytext_ptr := yy_bp;"), VSTR(""),
VSTR(" case yy_get_next_buffer is"),
VSTR(" when EOB_ACT_END_OF_FILE =>"),
VSTR(" begin"),
VSTR(" if ( yywrap ) then"),
VSTR(" -- note: because we've taken care in"),
VSTR(" -- yy_get_next_buffer() to have set up yytext,"),
VSTR(" -- we can now set up yy_c_buf_p so that if some"),
VSTR(" -- total hoser (like aflex itself) wants"),
VSTR(" -- to call the scanner after we return the"),
VSTR(" -- End_Of_Input, it'll still work - another"),
VSTR(" -- End_Of_Input will get returned."),
VSTR(""),
VSTR(" yy_c_buf_p := yytext_ptr;"),
VSTR(""),
VSTR(" yy_act := YY_STATE_EOF((yy_start - 1) / 2);"),
VSTR(""),
VSTR(" goto do_action;"),
VSTR(" else"),
VSTR(" -- start processing a new file"),
VSTR(" yy_init := true;"),
VSTR(" goto new_file;"),
VSTR(" end if;"),
VSTR(" end;"),
VSTR(" when EOB_ACT_RESTART_SCAN =>"),
VSTR(" yy_c_buf_p := yytext_ptr;"),
VSTR(" yy_hold_char := yy_ch_buf(yy_c_buf_p);"),
VSTR(" when EOB_ACT_LAST_MATCH =>"),
VSTR(" yy_c_buf_p := yy_n_chars;"),
VSTR(" yy_current_state := yy_get_previous_state;"),
VSTR(""),
VSTR(" yy_cp := yy_c_buf_p;"),
VSTR(" yy_bp := yytext_ptr;"),
VSTR(" goto next_action;"),
VSTR(" when others => null;"),
VSTR(" end case; -- case yy_get_next_buffer()"),
VSTR(" when others =>"),
VSTR(" text_io.put( ""action # "" );"),
VSTR(" text_io.put( INTEGER'IMAGE(yy_act) );"),
VSTR(" text_io.new_line;"),
VSTR(" raise AFLEX_INTERNAL_ERROR;"),
VSTR(" end case; -- case (yy_act)"),
VSTR(" end loop; -- end of loop waiting for end of file"),
VSTR("end YYLex;"),
VSTR("%%"),
VSTR("ERROR tried to output beyond end of skeleton file")
-- END OF SKELETON
);
-- set_external_skeleton
--
-- DESCRIPTION
-- sets flag so we know to use an external skelfile
procedure SET_EXTERNAL_SKELETON is
begin
USE_EXTERNAL_SKELETON := TRUE;
end SET_EXTERNAL_SKELETON;
procedure GET_INTERNAL(BUFFER : in out FILE_STRING.VSTRING) is
begin
BUFFER := SKEL_TEMPLATE(CURRENT_LINE);
CURRENT_LINE := CURRENT_LINE + 1;
end GET_INTERNAL;
procedure GET_EXTERNAL(BUFFER : in out FILE_STRING.VSTRING) is
begin
FILE_STRING.GET_LINE(MISC_DEFS.SKELFILE, BUFFER);
end GET_EXTERNAL;
-- end_of_skeleton
--
-- DESCRIPTION
-- returns true if there are no more lines left to output in the skeleton
function END_OF_SKELETON return BOOLEAN is
begin
if (USE_EXTERNAL_SKELETON) then
-- we're using an external skelfile
return TEXT_IO.END_OF_FILE(MISC_DEFS.SKELFILE);
else
-- internal skeleton
return CURRENT_LINE > SKEL_TEMPLATE'LAST;
end if;
end END_OF_SKELETON;
procedure GET_FILE_LINE(BUFFER : in out FILE_STRING.VSTRING) is
begin
if (USE_EXTERNAL_SKELETON) then
GET_EXTERNAL(BUFFER);
else
GET_INTERNAL(BUFFER);
end if;
end GET_FILE_LINE;
-- skelout - write out one section of the skeleton file
--
-- DESCRIPTION
-- Either outputs internal skeleton, or from a file with "%%" dividers
-- if a skeleton file is specified by the user.
-- Copies from skelfile to stdout until a line beginning with "%%" or
-- EOF is found.
procedure SKELOUT is
BUF : FILE_STRING.VSTRING;
LINE_LEN : INTEGER;
-- UMASS CODES :
Umass_Codes : Boolean := False;
-- Indicates whether or not current line of the template
-- is the Umass codes.
-- END OF UMASS CODES.
begin
while (not END_OF_SKELETON) loop
GET_FILE_LINE(BUF);
if ((FILE_STRING.LEN(BUF) >= 2)
and then ((FILE_STRING.CHAR(BUF, 1) = '%')
and (FILE_STRING.CHAR(BUF, 2) = '%'))) then
exit;
else
-- UMASS CODES :
-- In the template, the codes between "-- UMASS CODES : " and
-- "-- END OF UMASS CODES." are specific to be used by Ayacc-extension.
-- Ayacc-extension has more power in error recovery. So we
-- generate those codes only when Ayacc_Extension_Flag is True.
if FILE_STRING.STR(BUF) = "-- UMASS CODES :" then
Umass_Codes := True;
end if;
if not Umass_Codes or else
MISC_DEFS.Ayacc_Extension_Flag then
FILE_STRING.PUT_LINE(BUF);
end if;
if FILE_STRING.STR(BUF) = "-- END OF UMASS CODES." then
Umass_Codes := False;
end if;
-- END OF UMASS CODES.
-- UCI CODES commented out :
-- The following line is commented out because it is done in Umass codes.
-- FILE_STRING.PUT_LINE(BUF);
end if;
end loop;
end SKELOUT;
end SKELETON_MANAGER;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.